Code Injection on WindowsRaashidBhatKashmirStudent Computer Security2nd year BE http://Twitter.com/raashidbhatt!
AgendaWhy Inject Code?Ways to Inject CodeQuestions?
Why inject Code?Trivially bypass anti-virus softwareTo be stealthy Malware makes the heavy use of injectionStealing credentials (Post Form grabbers, HTML injection etc. .etc.)Etc. etc.
Portable Executable(PE) FormatFile format for Windows executableConsists of Section having characteristics examples (.text, .bss,.data,.reloc , .debug)Imports and Exports by EXE file are stored in idata and rdata sectionsTexe 1.2 by Raashid Bhatt(PE Dumper) http://texe.codeplex.comBriefly Documented in <winnt.h>
Code injection Technique #1  # PE File Infection
PE File InfectionOverwrite the .code section ( or any section convenient for infection )Change the Entry Point of the ExecutableSave the registers , ESP, EBP etcReturn to original EP by Either Push EP ; RetOr JMP EP
The bad News?Calling functions egLoadlibrary() , GetprocAddress() in kernel32.dll when ASLR(address space layout randomization) is enabled. (/Fixed:NO MSVC)Sections .data,.bss are usually marked as writable and readable
RemedyUse PEB(Process Environment Block) to find kernel32.dll address PEB is located at FS[0x30]Consists heaps, binary information and loaded module information.Further Reading > The Last Stage of DeleriumWin32 Assembly Components. http://www.lsd-pl.net/documents/winasm-1.0.1.pdf;
Non-Executable SectionsSections .data,.bss.idata.edataetc are not executable as they are marked 0xC0000040          	INITIALIZED_DATA|READ|WRITEChange >>PIMAGE_SECTION_HEADER-> Characteristics = IMAGE_SCN_CNT_CODE (documented in Winnt.h)
Code injection Technique #2 # IAT Hooking
IATIAT(import address table)  holds information regarding the DLL to be loaded by a PE fileFunctions are Linked either by a ordinal or by name.Stored in .idatasection of PE file.Define in struct _IMAGE_IMPORT_DESCRIPTOR <winnt.h>
IAT hooking Used by botnets for Credential stealing (POST Form Grabbers, 0n-fly  html Injection)Can be achieved by changing the name of the Dll inside the import address table(IAT) table to proxy DllActivated when any function is called in org DLL
Proxy Dll(user32.dll)dllmain(...)int WINAPI MessageBoxA(...){	user32.ldd_MessageBoxA(...);	/* user code */}.Example for user32.dll proxy dll
Code injection Technique #3# Runtime Code Injection
CreateRemoteThreadWindows has CreateRemoteThread() APIAccording to MSDN “The CreateRemoteThread function creates a thread that runs in the virtual address space of another process”memory allocation in another process (possible) using VirtualAllocEx() APIForeign process memory read and write using WriteProcessMemory() & ReadProcessMemory()
1: DLL Loading  DLL’s can be loaded in another process using CreateRemoteThread. Steps:1: Allocate memory for the DLL name in the remote target process2:Write the DLL name, including full path, to the allocated memory.3:Mapping our DLL to the remote process via CreateRemoteThread & LoadLibrary
pLibRemote= VirtualAllocEx(hProc, NULL, sizeof(szDllPath), MEM_COMMIT, PAGE_READWRITE );bWriteCheck= WriteProcessMemory(hProc, pLibRemote, (void*)szDllPath, sizeof(szDllPath), NULL );	hThread = CreateRemoteThread(	hProc,NULL,NULL,(LPTHREAD_START_ROUTINE)GetProcAddress(hKernel32,"LoadLibraryA"),pLibRemote,NULL, NULL);	Equivalent to LoadlibraryA(“Dll name”);
2:In memory Execution First Documented as  “Reflective DLL Injection By Stephen Fewer” Harmony Security Implemented in MetasploitPlayloadInvolves Writing a Exe or dll file in the memory and executing from within Stealthy Execution
2:In memory Execution Implementing a minimal Portable Executable (PE) file loader. 1: Allocate Memory and Copy the file to memory2:Parse the Import Address table of PE File and Perform Fixups3:calculate the new base and Perform relocation (IMPORTANT)4:JUMP to Entry point of The PE File
Image RelocationsCertain hardcoded addresses need to be fixedInt x; int *p = &x;(hardcoded into p)PE file Stores Relocation Entries in .reloc section .reloc section stores offsets to the addresses to be fixed
Example of .reloc section0x0001 --- DD (pointer) 0x0013 >>0x0010 --- 0xdeadbeef0x0011 --- 0xdeadbeef0x0013 --- 0xdeadbeef..reloc sectionRELOC TYPE (4BITS) OFFSET(12bits) RVA
			         Thanks Questions?

Code Injection in Windows

  • 1.
    Code Injection onWindowsRaashidBhatKashmirStudent Computer Security2nd year BE http://Twitter.com/raashidbhatt!
  • 2.
    AgendaWhy Inject Code?Waysto Inject CodeQuestions?
  • 3.
    Why inject Code?Triviallybypass anti-virus softwareTo be stealthy Malware makes the heavy use of injectionStealing credentials (Post Form grabbers, HTML injection etc. .etc.)Etc. etc.
  • 4.
    Portable Executable(PE) FormatFileformat for Windows executableConsists of Section having characteristics examples (.text, .bss,.data,.reloc , .debug)Imports and Exports by EXE file are stored in idata and rdata sectionsTexe 1.2 by Raashid Bhatt(PE Dumper) http://texe.codeplex.comBriefly Documented in <winnt.h>
  • 5.
    Code injection Technique#1 # PE File Infection
  • 6.
    PE File InfectionOverwritethe .code section ( or any section convenient for infection )Change the Entry Point of the ExecutableSave the registers , ESP, EBP etcReturn to original EP by Either Push EP ; RetOr JMP EP
  • 7.
    The bad News?Callingfunctions egLoadlibrary() , GetprocAddress() in kernel32.dll when ASLR(address space layout randomization) is enabled. (/Fixed:NO MSVC)Sections .data,.bss are usually marked as writable and readable
  • 8.
    RemedyUse PEB(Process EnvironmentBlock) to find kernel32.dll address PEB is located at FS[0x30]Consists heaps, binary information and loaded module information.Further Reading > The Last Stage of DeleriumWin32 Assembly Components. http://www.lsd-pl.net/documents/winasm-1.0.1.pdf;
  • 9.
    Non-Executable SectionsSections .data,.bss.idata.edataetcare not executable as they are marked 0xC0000040 INITIALIZED_DATA|READ|WRITEChange >>PIMAGE_SECTION_HEADER-> Characteristics = IMAGE_SCN_CNT_CODE (documented in Winnt.h)
  • 10.
    Code injection Technique#2 # IAT Hooking
  • 11.
    IATIAT(import address table) holds information regarding the DLL to be loaded by a PE fileFunctions are Linked either by a ordinal or by name.Stored in .idatasection of PE file.Define in struct _IMAGE_IMPORT_DESCRIPTOR <winnt.h>
  • 12.
    IAT hooking Usedby botnets for Credential stealing (POST Form Grabbers, 0n-fly html Injection)Can be achieved by changing the name of the Dll inside the import address table(IAT) table to proxy DllActivated when any function is called in org DLL
  • 13.
    Proxy Dll(user32.dll)dllmain(...)int WINAPIMessageBoxA(...){ user32.ldd_MessageBoxA(...); /* user code */}.Example for user32.dll proxy dll
  • 14.
    Code injection Technique#3# Runtime Code Injection
  • 15.
    CreateRemoteThreadWindows has CreateRemoteThread()APIAccording to MSDN “The CreateRemoteThread function creates a thread that runs in the virtual address space of another process”memory allocation in another process (possible) using VirtualAllocEx() APIForeign process memory read and write using WriteProcessMemory() & ReadProcessMemory()
  • 16.
    1: DLL Loading DLL’s can be loaded in another process using CreateRemoteThread. Steps:1: Allocate memory for the DLL name in the remote target process2:Write the DLL name, including full path, to the allocated memory.3:Mapping our DLL to the remote process via CreateRemoteThread & LoadLibrary
  • 17.
    pLibRemote= VirtualAllocEx(hProc, NULL,sizeof(szDllPath), MEM_COMMIT, PAGE_READWRITE );bWriteCheck= WriteProcessMemory(hProc, pLibRemote, (void*)szDllPath, sizeof(szDllPath), NULL ); hThread = CreateRemoteThread( hProc,NULL,NULL,(LPTHREAD_START_ROUTINE)GetProcAddress(hKernel32,"LoadLibraryA"),pLibRemote,NULL, NULL); Equivalent to LoadlibraryA(“Dll name”);
  • 18.
    2:In memory ExecutionFirst Documented as “Reflective DLL Injection By Stephen Fewer” Harmony Security Implemented in MetasploitPlayloadInvolves Writing a Exe or dll file in the memory and executing from within Stealthy Execution
  • 19.
    2:In memory ExecutionImplementing a minimal Portable Executable (PE) file loader. 1: Allocate Memory and Copy the file to memory2:Parse the Import Address table of PE File and Perform Fixups3:calculate the new base and Perform relocation (IMPORTANT)4:JUMP to Entry point of The PE File
  • 20.
    Image RelocationsCertain hardcodedaddresses need to be fixedInt x; int *p = &x;(hardcoded into p)PE file Stores Relocation Entries in .reloc section .reloc section stores offsets to the addresses to be fixed
  • 21.
    Example of .relocsection0x0001 --- DD (pointer) 0x0013 >>0x0010 --- 0xdeadbeef0x0011 --- 0xdeadbeef0x0013 --- 0xdeadbeef..reloc sectionRELOC TYPE (4BITS) OFFSET(12bits) RVA
  • 22.
    Thanks Questions?