program Inject;
{$APPTYPE CONSOLE}
{$IF CompilerVersion >= 21.0}
{$WEAKLINKRTTI ON}
{$RTTI EXPLICIT METHODS([]) PROPERTIES([]) FIELDS([])}
{$IFEND}
uses
Winapi.Windows;
Type
NtCreateThreadExProc = Function(Var hThread:THandle; Access:DWORD; Attributes:Pointer; hProcess:THandle; pStart:Pointer; pParameter:Pointer; Suspended:BOOL; StackSize, u1, u2:DWORD; Unknown:Pointer):DWORD; stdcall;
Function CheckOs():Boolean;
Var
lpVersionInformation :TOSVersionInfoW;
begin
Result := False;
if GetVersionExW(lpVersionInformation) then
begin
if lpVersionInformation.dwPlatformId = VER_PLATFORM_WIN32_NT Then
begin
if (lpVersionInformation.dwMajorVersion < 6) then
begin
Result := True;
end;
end;
end;
end;
Function EnableDebugPrivilege():Boolean;
Var
hToKen :THandle;
TokenPri :TTokenPrivileges;
begin
Result := False;
if(OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES, hToKen)) Then
begin
TokenPri.PrivilegeCount := 1;
If LookupPrivilegeValueW(Nil, 'SeDebugPrivilege', TokenPri.Privileges[0].Luid) Then
begin
TokenPri.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
Result := AdjustTokenPrivileges(hToken, False, TokenPri, SizeOf(TTokenPrivileges), Nil, PDWORD(Nil)^);
end Else Writeln('LookupPrivilege Error');
CloseHandle(hToKen);
end;
end;
Function RemoteThread(hProcess:THandle; pThreadProc:Pointer; pRemote:Pointer):THandle;
Label NtCreate, Create;
Var
pFunc :Pointer;
hThread :THandle;
begin
hThread := 0;
if Not CheckOs() then //根据系统版本来选择使用的API
begin
NtCreate:
pFunc := GetProcAddress(LoadLibraryW('ntdll.dll'), 'NtCreateThreadEx');
if pFunc = Nil then Goto Create;
NtCreateThreadExProc(pFunc)(hThread, $1FFFFF, Nil, hProcess, pThreadProc, pRemote, False, 0, 0, 0, Nil);
if hThread = 0 then Goto Create;
end Else
begin
Create:
hThread := CreateRemoteThread(hProcess, Nil, 0, pThreadProc, pRemote, 0, PDWORD(Nil)^);
end;
Writeln('RemoteThread Ok!');
Result := hThread;
end;
Function InjectDll2Pid(szPath:PWideChar; uPID:DWORD):Boolean;
Var
hProcess :THandle;
hThread :THandle;
szRemote :PWideChar;
uSize :SIZE_T;
uWrite :SIZE_T;
pStartAddr:Pointer;
begin
Result := False;
if EnableDebugPrivilege then
begin //先提升下进程的权限
hProcess := OpenProcess(PROCESS_ALL_ACCESS, false, uPID);
if hProcess > 0 then
begin
uSize := lstrlenW(szPath) * 2 + 4;
szRemote := VirtualAllocEx(hProcess, Nil, uSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
if WriteProcessMemory(hProcess, szRemote, szPath, uSize, uWrite) And (uWrite = uSize) then
begin
pStartAddr := GetProcAddress(LoadLibrary('Kernel32.dll'), 'LoadLibraryW');
hThread := RemoteThread(hProcess, pStartAddr, szRemote);
Result := hThread <> 0;
CloseHandle(hThread);
end Else
begin
Writeln('WriteMemory Error');
end;
end;
end;
end;
Function StrToInt(S: String): Integer;
Var
E: Integer;
Begin
Val(S, Result, E);
End;
begin
InjectDll2Pid(PWideChar(ParamStr(2)), StrToInt(ParamStr(1)));
end.
来源:https://www.7xcode.com/archives/90.html