I'm trying to run the application is hidden, but the application form is still visible.
ShellExecute(Handle, nil, 'app.exe', nil, nil, SW_HIDE);
How to run a hidden application in Delphi?
I would suggest using CreateProcess instead, because it returns the process ID of the newly launched application and you can use it to get the window's handle. Here's a function I have been using, maybe you can take away unnecessary fragments and adapt it to your needs?
// record to store window information
TWndInfo = record
pid: DWord;
WndHandle: HWND;
width, height: Integer;
end;
PWndInfo = ^TWndInfo;
{$HINTS OFF}
{ .: ExecNewProcess :. }
function ExecNewProcess(const ProgramName: String;
const StartHidden, WaitForInput: Boolean; out WndInfo: TWndInfo): Boolean;
var
StartInfo: TStartupInfo;
ProcInfo: TProcessInformation;
R: TRect;
SL: TStringList;
{$REGION 'EnumProcess'}
function EnumProcess(hHwnd: HWND; lParam: Integer): Boolean; stdcall;
var
WndInfo: PWndInfo;
pid: DWORD;
begin
Result := True;
WndInfo := PWndInfo(lParam);
if (WndInfo = nil) or (hHwnd = 0) then
exit;
GetWindowThreadProcessId(hHwnd, pid);
if (pid = WndInfo.PID) then
begin
if (WndInfo.WndHandle = 0) and (IsWindowVisible(hHwnd)) then
WndInfo.WndHandle := hHwnd;
//Result := False;
end;
end;
{$ENDREGION}
begin
Result := False;
ZeroMemory(#StartInfo, SizeOf(TStartupInfo));
ZeroMemory(#ProcInfo, SizeOf(TProcessInformation));
StartInfo.cb := SizeOf(TStartupInfo);
StartInfo.dwFlags := STARTF_USESTDHANDLES;
if StartHidden then
begin
StartInfo.dwFlags := STARTF_USESHOWWINDOW or StartInfo.dwFlags;
StartInfo.wShowWindow := SW_SHOWMINNOACTIVE;
end;
Result := CreateProcess(PChar(ProgramName), nil, nil, nil, False, 0, nil,
nil, StartInfo, ProcInfo);
try
if Result then
begin
WndInfo.WndHandle := 0;
WndInfo.PID := ProcInfo.dwProcessId;
if WaitForInput then
WaitForInputIdle(ProcInfo.hProcess, INFINITE);
EnumWindows(#EnumProcess, Integer(#WndInfo));
if (WndInfo.WndHandle <> 0) then
begin
if (StartHidden) then
ShowWindow(WndInfo.WndHandle, SW_HIDE);
Windows.GetWindowRect(WndInfo.WndHandle, R);
WndInfo.Width := R.Right - R.Left;
WndInfo.Height := R.Bottom - R.Top;
end;
end;
finally
CloseHandle(ProcInfo.hProcess);
CloseHandle(ProcInfo.hThread);
end;
end;
{$HINTS ON}
As you can read here
http://msdn.microsoft.com/en-us/library/windows/desktop/bb762153%28v=vs.85%29.aspx
it is up to the application to decide how to handle the SW_HIDE. Thus the application has to fetch the message and hide itself, as far as i see...
Related
I need to run a process under the current user from another process that runs under SYSTEM (system process runs another process as current user).
I can run it with this code, but there is an issue with environment variables.. e.g. in the new 'user-mode' process, I see that the APPDATA value is C:\Windows\System32\config\systemprofile\AppData\Roaming instead of C:\Users\username\AppData\Roaming
function RunProcessAsCurrentUser(FileName: string): Boolean;
var
ProcessId: Integer;
hWindow, hProcess, TokenHandle: THandle;
si: Tstartupinfo;
p: Tprocessinformation;
begin
Result := False;
hWindow := FindWindow('Progman', 'Program Manager');
GetWindowThreadProcessID(hWindow, #ProcessID);
hProcess := OpenProcess (PROCESS_ALL_ACCESS, FALSE, ProcessID);
if OpenProcessToken(hProcess, TOKEN_ALL_ACCESS, TokenHandle) then
begin
FillChar(si,SizeOf(si),0);
with Si do begin
cb := SizeOf( Si);
dwFlags := startf_UseShowWindow;
wShowWindow := SW_NORMAL;
lpDesktop := PChar('winsta0\default');
end;
Result := CreateProcessAsUser(TokenHandle, nil,
PChar('"'+FileName+'"'),
nil, nil, false, Create_default_error_mode, nil, nil, si, p);
end;
end;
the issue is actual in win7,8,10
I supposed that all process settings are copied from explorer.exe (and new process runs as user in the TaskManager) but looks like something stays from the SYSTEM... Please help to resolve
When using CreateProcessAsUser(), you should retrieve the user's environment using CreateEnvironmentBlock():
Retrieves the environment variables for the specified user. This block can then be passed to the CreateProcessAsUser function.
Pass that value to the lpEnvironment parameter of CreateProcessAsUser(). Otherwise, the new process inherits the environment of the calling process instead.
For example:
function RunProcessAsCurrentUser(FileName: string): Boolean;
var
ProcessId: Integer;
hWindow, hProcess, TokenHandle: THandle;
si: Tstartupinfo;
p: Tprocessinformation;
lpEnvironment: Pointer;
begin
Result := False;
hWindow := FindWindow('Progman', 'Program Manager');
if hWindow = 0 then Exit;
GetWindowThreadProcessID(hWindow, #ProcessID);
hProcess := OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, ProcessID);
if hProcess = 0 then Exit;
try
if not OpenProcessToken(hProcess, TOKEN_ALL_ACCESS, TokenHandle) then Exit;
FillChar(si,SizeOf(si),0);
with Si do begin
cb := SizeOf( Si);
dwFlags := startf_UseShowWindow;
wShowWindow := SW_NORMAL;
lpDesktop := PChar('winsta0\default');
end;
lpEnvironment := nil;
CreateEnvironmentBlock(#lpEnvironment, TokenHandle, FALSE);
try
Result := CreateProcessAsUser(TokenHandle, nil,
PChar('"'+FileName+'"'),
nil, nil, FALSE, CREATE_DEFAULT_ERROR_MODE,
lpEnvironment, nil, si, p);
finally
DestroyEnvironmentBlock(lpEnvironment);
end;
finally
CloseHandle(hProcess);
end;
end;
I'm trying to get PIDs of processes which belongs to the current user but I don't know how to check the process owner.
This is my code (the user's checking condition is missing):
uses
TlHelp32, ...;
type
TCardinalArray = array of Cardinal;
function GetCurrentUserPIDs(const AProcessName : string) : TCardinalArray;
var
ContinueLoop: boolean;
FSnapshotHandle: THandle;
FProcessEntry32: TProcessEntry32;
begin
SetLength(Result, 0);
FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
FProcessEntry32.dwSize := SizeOf(FProcessEntry32);
ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32);
while(ContinueLoop) do
begin
if(SameText(FProcessEntry32.szExeFile, AProcessName)) then
begin
if((* is this my process? *)) then
begin
SetLength(Result, Length(Result) + 1);
Result[Length(Result) - 1] := FProcessEntry32.th32ProcessID;
end;
end;
ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
end;
CloseHandle(FSnapshotHandle);
end;
I found a GetUserAndDomainFromPID function which allows to easily accomplish the task.
As Sertac Akyuz suggested, the function uses OpenProcessToken and GetTokenInformation. It also uses LookupAccountSid:
uses
TlHelp32;
type
PTOKEN_USER = ^TOKEN_USER;
_TOKEN_USER = record
User: TSidAndAttributes;
end;
TOKEN_USER = _TOKEN_USER;
function GetUserAndDomainFromPID(ProcessId: DWORD;
var User, Domain: string): Boolean;
var
hToken: THandle;
cbBuf: Cardinal;
ptiUser: PTOKEN_USER;
snu: SID_NAME_USE;
ProcessHandle: THandle;
UserSize, DomainSize: DWORD;
bSuccess: Boolean;
begin
Result := False;
ProcessHandle := OpenProcess(PROCESS_QUERY_INFORMATION, False, ProcessId);
if ProcessHandle <> 0 then
begin
// EnableProcessPrivilege(ProcessHandle, 'SeSecurityPrivilege', True);
if OpenProcessToken(ProcessHandle, TOKEN_QUERY, hToken) then
begin
bSuccess := GetTokenInformation(hToken, TokenUser, nil, 0, cbBuf);
ptiUser := nil;
while (not bSuccess) and (GetLastError = ERROR_INSUFFICIENT_BUFFER) do
begin
ReallocMem(ptiUser, cbBuf);
bSuccess := GetTokenInformation(hToken, TokenUser, ptiUser, cbBuf, cbBuf);
end;
CloseHandle(hToken);
if not bSuccess then
begin
Exit;
end;
UserSize := 0;
DomainSize := 0;
LookupAccountSid(nil, ptiUser.User.Sid, nil, UserSize, nil, DomainSize, snu);
if (UserSize <> 0) and (DomainSize <> 0) then
begin
SetLength(User, UserSize);
SetLength(Domain, DomainSize);
if LookupAccountSid(nil, ptiUser.User.Sid, PChar(User), UserSize,
PChar(Domain), DomainSize, snu) then
begin
Result := True;
User := StrPas(PChar(User));
Domain := StrPas(PChar(Domain));
end;
end;
if bSuccess then
begin
FreeMem(ptiUser);
end;
end;
CloseHandle(ProcessHandle);
end;
end;
Then I've written a function for getting the current windows username (It uses GetUserName):
const
UNLEN = 256; // Maximum user name length
function GetWindowsUsername: string;
var
UserName : string;
UserNameLen : Dword;
begin
UserNameLen := UNLEN;
SetLength(UserName, UserNameLen) ;
if GetUserName(PChar(UserName), UserNameLen)
then Result := Copy(UserName, 1, UserNameLen - 1)
else Result := '';
end;
The following function returns an array composed by all ids of processes who belongs to the current user (Note that processes are filtered by process name):
uses
TlHelp32;
type
TCardinalArray = array of Cardinal;
function GetCurrentUserPIDs(const AProcessName : string) : TCardinalArray;
var
ContinueLoop: boolean;
FSnapshotHandle: THandle;
FProcessEntry32: TProcessEntry32;
UserName : string;
DomainName : string;
CurrentUser : string;
begin
CurrentUser := GetWindowsUsername();
SetLength(Result, 0);
FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
FProcessEntry32.dwSize := SizeOf(FProcessEntry32);
ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32);
while(ContinueLoop) do
begin
if(SameText(FProcessEntry32.szExeFile, AProcessName)) then
begin
if(GetUserAndDomainFromPID(FProcessEntry32.th32ProcessID, UserName, DomainName)) then
begin
if(UserName = CurrentUser) then
begin
SetLength(Result, Length(Result) + 1);
Result[Length(Result) - 1] := FProcessEntry32.th32ProcessID;
end;
end;
end;
ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
end;
CloseHandle(FSnapshotHandle);
end;
After I found this useful question, I am able to create an application as Windows Service with sucess.
Then, I have created a separate executable to execute my application as a service, but my application isn't executed.
Flsh_Service.exe is the separate executable that executes Start_Dll.exe
This is my application that should work, but fails.
So i ask:
Why is my application not correctly executed as a service?
with relation to question refered above, cmd.exe here is target to injection and application to run as service is: Start_Dll.exe ( that in question refered above is cmd.exe ).
program Start_Dll;
{$APPTYPE CONSOLE}
uses
SysUtils,
Winapi.windows,
CreateProcessIntr,
vcl.forms,
Winapi.messages,
shellapi,
tlhelp32;
Const SE_DEBUG_NAME = 'SeDebugPrivilege';
procedure GetDebugPrivs;
var
hToken: THandle;
tkp: TTokenPrivileges;
retval: dword;
begin
if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken)) then
begin
LookupPrivilegeValue(nil, SE_DEBUG_NAME, tkp.Privileges[0].Luid);
tkp.PrivilegeCount := 1;
tkp.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges(hToken, false, tkp, 0, nil, retval);
end;
end;
procedure InjectDLL(const ADLLName: AnsiString; targetproc: Cardinal);
var
dllname: AnsiString;
pDLLname, pStartAddr: Pointer;
bw: NativeUInt;
hProcess, hRemoteThread: THandle;
TID: Cardinal;
begin
hProcess := OpenProcess(PROCESS_ALL_ACCESS, false, targetproc);
pDLLname := VirtualAllocEx(hProcess, 0, length(dllname) + 1,
MEM_COMMIT or MEM_RESERVE, PAGE_EXECUTE_READWRITE);
WriteProcessMemory(hProcess, pDLLname, Pointer(dllname),
length(dllname) + 1, bw);
pStartAddr := GetProcAddress(GetModuleHandle('kernel32.dll'), 'LoadLibraryW');
hRemoteThread := CreateRemoteThread(hProcess, nil, 0, pStartAddr,
pDLLname, 0, TID);
WaitForSingleObject(hRemoteThread, INFINITE);
CloseHandle(hProcess);
end;
function search(name:string): Cardinal;
var ExeFile : String;
PE : TProcessEntry32;
FSnap: THandle;
begin
result:= 0;
FSnap:= Tlhelp32.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
PE.dwSize:= SizeOf(PE);
if (Tlhelp32.Process32First(FSnap,PE)) Then
Repeat
ExeFile:= PE.szExeFile;
if pos(pchar(lowercase(name)), lowercase(ExeFile))>0 then
Begin
result:= PE.th32ProcessID;
break
End;
Until Not Process32Next(FSnap,PE)
end;
var
PID: Dword;
dll_to_inject: AnsiString;
Process: String;
////////////////////////////////////////////////////////////////////////////////
begin
{Sleep(120000);}
//GetDebugPrivs;
dll_to_inject:=ExtractFilePath(application.ExeName) + 'myDLL.dll;
Process:= 'cmd.exe';
ExecuteProcessAsLoggedOnUser(Process);
PID:=search(PROCESS);
if PID=0 then begin
exit;
end;
InjectDll(dll_to_inject, PID);
end.
CreateProcessIntr.pas
unit CreateProcessIntr;
interface
uses
Windows, SysUtils, Registry, TlHelp32;
procedure ExecuteProcessAsLoggedOnUser(FileName: string);
implementation
function GetShellProcessName: string;
var
Reg: TRegistry;
begin
Reg := TRegistry.Create(KEY_READ);
try
Reg.RootKey := HKEY_LOCAL_MACHINE;
Reg.OpenKeyReadOnly('Software\Microsoft\Windows NT\CurrentVersion\WinLogon');
Result := Reg.ReadString('Shell');
finally
Reg.Free;
end;
end;
function GetShellProcessPid(const Name: string): Longword;
var
Snapshot: THandle;
Process: TProcessEntry32;
B: Boolean;
begin
Result := 0;
Snapshot := CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if Snapshot <> INVALID_HANDLE_VALUE then
try
FillChar(Process, SizeOf(Process), 0);
Process.dwSize := SizeOf(Process);
B := Process32First(Snapshot, Process);
while B do
begin
if CompareText(Process.szExeFile, Name) = 0 then
begin
Result := Process.th32ProcessID;
Break;
end;
B := Process32Next(Snapshot, Process);
end;
finally
CloseHandle(Snapshot);
end;
end;
function GetShellHandle: THandle;
var
Pid: Longword;
begin
Pid := GetShellProcessPid(GetShellProcessName);
Result := OpenProcess(PROCESS_ALL_ACCESS, False, Pid);
end;
procedure ExecuteProcessAsLoggedOnUser(FileName: string);
var
ph: THandle;
hToken, nToken: THandle;
ProcInfo: TProcessInformation;
StartInfo: TStartupInfo;
begin
ph := GetShellHandle;
if ph > 0 then
begin
if OpenProcessToken(ph, TOKEN_DUPLICATE or TOKEN_QUERY, hToken) then
begin
if DuplicateTokenEx(hToken, TOKEN_ASSIGN_PRIMARY or TOKEN_DUPLICATE or TOKEN_QUERY,
nil, SecurityImpersonation, TokenPrimary, nToken) then
begin
if ImpersonateLoggedOnUser(nToken) then
begin
// Initialize then STARTUPINFO structure
FillChar(StartInfo, SizeOf(TStartupInfo), 0);
StartInfo.cb := SizeOf(TStartupInfo);
StartInfo.dwFlags := STARTF_USESHOWWINDOW;
StartInfo.wShowWindow := 0;
// Specify that the process runs in the interactive desktop
StartInfo.lpDesktop := PChar('WinSta0\Default');
// Launch the process in the client's logon session
CreateProcessAsUser(nToken, nil, PChar(FileName), nil, nil, False,
CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS, nil, nil, StartInfo, ProcInfo);
// End impersonation of client
RevertToSelf();
end;
CloseHandle(nToken);
end;
CloseHandle(hToken);
end;
end;
end;
end.
How can I get all the exported functions from a DLL, programmatically? I am trying to compare two DLL's for exported functions.
This is the code that I use:
uses
System.Classes, Winapi.Windows;
type
PIMAGE_NT_HEADERS = ^IMAGE_NT_HEADERS;
PIMAGE_EXPORT_DIRECTORY = ^IMAGE_EXPORT_DIRECTORY;
function ImageNtHeader(Base: Pointer): PIMAGE_NT_HEADERS; stdcall; external 'dbghelp.dll';
function ImageRvaToVa(NtHeaders: Pointer; Base: Pointer; Rva: ULONG; LastRvaSection: Pointer): Pointer; stdcall; external 'dbghelp.dll';
procedure EnumerateImageExportedFunctionNames(const ImageName: string; NamesList: TStrings);
var
i: Integer;
FileHandle: THandle;
ImageHandle: THandle;
ImagePointer: Pointer;
Header: PIMAGE_NT_HEADERS;
ExportTable: PIMAGE_EXPORT_DIRECTORY;
NamesPointer: Pointer;
NamesPtr: PCardinal;
NamePtr: PAnsiChar;
begin
//NOTE: our policy in this procedure is to exit upon any failure and return and empty list
NamesList.Clear;
FileHandle := CreateFile(
PChar(ImageName),
GENERIC_READ,
FILE_SHARE_READ,
nil,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0
);
if FileHandle=INVALID_HANDLE_VALUE then begin
exit;
end;
Try
ImageHandle := CreateFileMapping(FileHandle, nil, PAGE_READONLY, 0, 0, nil);
if ImageHandle=0 then begin
exit;
end;
Try
ImagePointer := MapViewOfFile(ImageHandle, FILE_MAP_READ, 0, 0, 0);
if not Assigned(ImagePointer) then begin
exit;
end;
Try
Header := ImageNtHeader(ImagePointer);
if not Assigned(Header) then begin
exit;
end;
if Header.Signature<>$00004550 then begin // "PE\0\0" as a DWORD.
exit;
end;
ExportTable := ImageRvaToVa(Header, ImagePointer, Header.OptionalHeader.DataDirectory[0].VirtualAddress, nil);
if not Assigned(ExportTable) then begin
exit;
end;
NamesPtr := ImageRvaToVa(Header, ImagePointer, Cardinal(ExportTable.AddressOfNames), nil);
if not Assigned(NamesPtr) then begin
exit;
end;
for i := 0 to ExportTable.NumberOfNames-1 do begin
NamePtr := ImageRvaToVa(Header, ImagePointer, NamesPtr^, nil);
if not Assigned(NamePtr) then begin
exit;
end;
NamesList.Add(NamePtr);
inc(NamesPtr);
end;
Finally
UnmapViewOfFile(ImagePointer); // Ignore error as there is not much we could do.
End;
Finally
CloseHandle(ImageHandle);
End;
Finally
CloseHandle(FileHandle);
End;
end;
I came here to find a way to list all functions contained within an ocx (which is basically a dll). All infos here didn't give me what I was looking for. But then I found the free dllexp.exe from nirsoft (https://www.nirsoft.net/utils/dll_export_viewer.html).
Direct download link: https://www.nirsoft.net/packages/progtools.zip which perfectly shows all exported functions of a dll/ocx and is very user-friendly.
I create a service in Delphi. I need this service to run my program. In Windows 7, I use this code to execute a program :
procedure ExecuteProcessAsLoggedOnUser(FileName: string);
implementation
function GetShellProcessName: string;
var
Reg: TRegistry;
begin
Reg := TRegistry.Create(KEY_READ);
try
Reg.RootKey := HKEY_LOCAL_MACHINE;
Reg.OpenKeyReadOnly
('Software\Microsoft\Windows NT\CurrentVersion\WinLogon');
Result := Reg.ReadString('Shell');
finally
Reg.Free;
end;
end;
function GetShellProcessPid(const Name: string): Longword;
var
Snapshot: THandle;
Process: TProcessEntry32;
B: Boolean;
begin
Result := 0;
Snapshot := CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if Snapshot <> INVALID_HANDLE_VALUE then
try
FillChar(Process, SizeOf(Process), 0);
Process.dwSize := SizeOf(Process);
B := Process32First(Snapshot, Process);
while B do
begin
if CompareText(Process.szExeFile, Name) = 0 then
begin
Result := Process.th32ProcessID;
Break;
end;
B := Process32Next(Snapshot, Process);
end;
finally
CloseHandle(Snapshot);
end;
end;
function GetShellHandle: THandle;
var
Pid: Longword;
begin
Pid := GetShellProcessPid(GetShellProcessName);
Result := OpenProcess(PROCESS_ALL_ACCESS, False, Pid);
end;
procedure ExecuteProcessAsLoggedOnUser(FileName: string);
var
ph: THandle;
hToken, nToken: THandle;
ProcInfo: TProcessInformation;
StartInfo: TStartupInfo;
begin
ph := GetShellHandle;
if ph > 0 then
begin
if OpenProcessToken(ph, TOKEN_DUPLICATE or TOKEN_QUERY, hToken) then
begin
if DuplicateTokenEx(hToken, TOKEN_ASSIGN_PRIMARY or TOKEN_DUPLICATE or
TOKEN_QUERY, nil, SecurityImpersonation, TokenPrimary, nToken) then
begin
if ImpersonateLoggedOnUser(nToken) then
begin
// Initialize then STARTUPINFO structure
FillChar(StartInfo, SizeOf(TStartupInfo), 0);
StartInfo.cb := SizeOf(TStartupInfo);
// Specify that the process runs in the interactive desktop
StartInfo.lpDesktop := PChar('WinSta0\Default');
// Launch the process in the client's logon session
CreateProcessAsUser(nToken, nil, PChar(FileName), nil, nil, False,
CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS, nil, nil, StartInfo,
ProcInfo);
// End impersonation of client
RevertToSelf();
end;
CloseHandle(nToken);
end;
CloseHandle(hToken);
end;
end;
end;
The code works fine for an "empty" program. So I drop TVirtualExpolorerTreeview onto the form of my program. if I start my service then there will be an error when the program is being called. I guess the program can't enumerate PIDL or blabla (I don't know much about Windows Shell). How do I force the program so it can run normally?
Your WinSta0 might be the cause:
Starting with Windows Vista, the way that services (and processes started by services) can interact with the desktop changed, as services no longer run in the same session as the user at the console.
By default, they cannot interact with the desktop any more.
See this thread for some nice links on this matter.