function InjectDllToTarget(dllName : string; TargetProcessID : DWORD ; code : pointer; CodeSize : integer ): boolean;
var
InitDataAddr , WriteAddr : pointer;
hProcess , ThreadHandle : Thandle;
BytesWritten , TheadID : DWORD;
InitData : TInjectDllData;
begin
result := false;
// it would probably be a good idea to set these
// from the IAT rather than assuming kernel32.dll
// is loaded in the same place in the remote process
InitData.pLoadLibrary := GetProcAddress(LoadLibrary('kernel32.dll'), 'LoadLibraryA');
InitData.pGetProcAddress := GetProcAddress(LoadLibrary('kernel32.dll'), 'GetProcAddress');
InitData.pGetModuleHandle := GetProcAddress(LoadLibrary('kernel32.dll'), 'GetModuleHandleA');
hProcess := OpenProcess( PROCESS_ALL_ACCESS, FALSE, TargetProcessID );
if (hProcess = 0) then exit;
// write the initdata strucutre to the remote prcess
InitDataAddr := VirtualAllocEx(hProcess , 0, sizeof(InitData) , MEM_COMMIT , PAGE_READWRITE) ;
if ( InitDataAddr <> nil) then
begin
WriteProcessMemory(hProcess , InitDataAddr , (@InitData) , sizeof(InitData) , BytesWritten );
end ;
// alocate and write the
dll name to the remote process
InitData.lib_name := VirtualAllocEx(hProcess , 0, length(dllName) + 5 , MEM_COMMIT , PAGE_READWRITE) ;
if ( InitData.lib_name <> nil) then
begin
WriteProcessMemory(hProcess , InitData.lib_name , pchar(dllName) , length(dllName) , BytesWritten );
end ;
// write our proc that loads the
dll into the remote process
// then execute it
WriteAddr := VirtualAllocEx(hProcess , 0, CodeSize , MEM_COMMIT , PAGE_READWRITE) ;
if (WriteAddr <> nil) then
begin
WriteProcessMemory(hProcess , WriteAddr , code , CodeSize , BytesWritten );
if BytesWritten = CodeSize then
begin
ThreadHandle := CreateRemoteThread( hProcess , nil , 0, WriteAddr , InitDataAddr ,0 , TheadID );
WaitForSingleObject( ThreadHandle , INFINITE); //wait for the thread to execute
VirtualFreeEx( hProcess , WriteAddr , 0 , MEM_RELEASE); // free the memory we allocated
result := true;
end;
end;
// free the memory we allocated for the
dll name
VirtualFreeEx( hProcess , InitDataAddr , 0 , MEM_RELEASE);
VirtualFreeEx( hProcess , InitData.lib_name , 0 , MEM_RELEASE);
CloseHandle(hProcess);
end;