CreateProcessAsUserInjectA/W()

Example Code

function CreateProcessAsUserInjectA(hToken: THandle; lpApplicationName: PAnsiChar; lpCommandLine: PAnsiChar; lpProcessAttributes: PSecurityAttributes; lpThreadAttributes: PSecurityAttributes; bInheritHandles: BOOL; dwCreationFlags: DWORD; lpEnvironment: PVOID; lpCurrentDirectory: PAnsiChar; const lpStartupInfo: _STARTUPINFOA; lpProcessInformation: PPROCESS_INFORMATION; lpFullDLLName: PAnsiChar): BOOL; stdcall; function CreateProcessAsUserInjectW(hToken: THandle; lpApplicationName: PWChar; lpCommandLine: PWChar; lpProcessAttributes: PSecurityAttributes; lpThreadAttributes: PSecurityAttributes; bInheritHandles: BOOL; dwCreationFlags: DWORD; lpEnvironment: PVOID; lpCurrentDirectory: PWChar; const lpStartupInfo: _STARTUPINFOW; lpProcessInformation: PPROCESS_INFORMATION; lpFullDLLName: PWChar): BOOL; stdcall; // Creates a new process and injects a library (DLL) // Works in any session and is intended for services as a counterpart to CreateProcessInjectA/W() function WTSQueryUserToken(SessionId: ULONG; phToken: PHANDLE): BOOL; stdcall; external 'wtsapi32'; function WTSGetActiveConsoleSessionId: ULONG; stdcall; external 'kernel32'; function CreateEnvironmentBlock(lpEnvironment: PPointer; hToken: THandle; bInherit: BOOL): BOOL; stdcall; external 'userenv'; function DestroyEnvironmentBlock(lpEnvironment: Pointer): BOOL; stdcall; external 'userenv'; const CREATE_BREAKAWAY_FROM_JOB = $01000000; function CreateProcessFromService(): BOOL; const dwFlags: DWORD = (CREATE_UNICODE_ENVIRONMENT or CREATE_BREAKAWAY_FROM_JOB); var hToken: THandle; si: _STARTUPINFOW; pi: PROCESS_INFORMATION; pEnv: Pointer; SessionId: ULONG; lpFileName: Array [0..MAX_PATH-1] of WChar; lpDLL: Array [0..MAX_PATH-1] of WChar; begin result := False; ZeroMemory(@si, sizeof(si)); si.cb := sizeof(_STARTUPINFOW); SessionId := WTSGetActiveConsoleSessionId(); if SessionId <> ULONG(-1) then begin if WTSQueryUserToken(SessionId, @hToken) then begin if CreateEnvironmentBlock(@pEnv, hToken, False) then begin ZeroMemory(@lpFileName, sizeof(lpFileName)); lstrcpyW(@lpFileName, 'calc.exe'); ZeroMemory(@lpDLL, sizeof(lpDLL)); lstrcpyW(@lpDLL, 'C:\Inject.dll'); result := CreateProcessAsUserInjectW(hToken, nil, @lpFileName, nil, nil, False, dwFlags, pEnv, nil, si, pi, @lpDLL); if (result) then begin CloseHandle(pi.hProcess); CloseHandle(pi.hThread); end; DestroyEnvironmentBlock(pEnv); end; CloseHandle(hToken); end; end; end;