Search code examples
winapiportable-executablekernel32

Get lpbaseaddress of a suspended process


Hi i have a source that does the following.

int[] context = new int[179];
context[0] = 65538; //context integer
GetThreadContext(PI.hThread, context); //from kernel32

ReadProcessMemory(PI.hProcess, context[41]+ 8, ref BaseAddress, 4, ref ReadWrite)

After googling much, context[41] refers to EBX. Any idea why? PInvokes.net shows the following.

[StructLayout(LayoutKind.Sequential)]
public struct CONTEXT
{
     public uint ContextFlags; //set this to an appropriate value 
     // Retrieved by CONTEXT_DEBUG_REGISTERS 
     public uint Dr0;  
     public uint Dr1; 
     public uint Dr2; 
     public uint Dr3; 
     public uint Dr6; 
     public uint Dr7; 
     // Retrieved by CONTEXT_FLOATING_POINT 
     public FLOATING_SAVE_AREA FloatSave; 
     // Retrieved by CONTEXT_SEGMENTS 
     public uint SegGs; 
     public uint SegFs; 
     public uint SegEs; 
     public uint SegDs; 
     // Retrieved by CONTEXT_INTEGER 
     public uint Edi; 
     public uint Esi; 
     public uint Ebx; 
     public uint Edx; 
     public uint Ecx; 
     public uint Eax; 
     // Retrieved by CONTEXT_CONTROL 
     public uint Ebp; 
     public uint Eip; 
     public uint SegCs; 
     public uint EFlags; 
     public uint Esp; 
     public uint SegSs;
     // Retrieved by CONTEXT_EXTENDED_REGISTERS 
     [MarshalAs(UnmanagedType.ByValArray, SizeConst = 512)] 
     public byte[] ExtendedRegisters;
} 

Also why must we ebx+8 to get the lpbaseaddress?


Solution

  • The CONTEXT structure is defined in winnt.h. Beware that it has different definitions based on the processor architecture. Use this structure definition to access the ebx register instead of a specific offset to the start. The EBX register points to the process's PEB (Process Environment Block) where the Ldr pointer contains the base address. All of this is used for a technique called 'Dynamic Forking' to run a process in the context of another process. Used for example in malware applications.