(*
* Author : Michael Puff - [url]http://www.michael-puff.de[/url]
* License : PUBLIC DOMAIN
*)
program Project1;
{$APPTYPE CONSOLE}
uses
Windows;
function GetSecurityInfo(
handle: THandle; ObjectType: DWord; SecurityInfo: SECURITY_INFORMATION; ppsidOwner: PSID;
ppsidGroup: PSID; ppDacl: PACL; ppSacl: PACL; ppSecurityDescriptor: PSECURITY_DESCRIPTOR): DWORD;
stdcall;
external
'
advapi32.dll';
function ConvertSidToStringSid(Sid: PSID;
var StringSid: PChar): LongBool;
stdcall;
external '
advapi32.dll'
name
'
ConvertSidToStringSidA';
function ConvertStringSidToSid(StringSid: PChar;
var Sid: PSID): Boolean;
stdcall;
external '
advapi32.dll'
name
'
ConvertStringSidToSidA';
////////////////////////////////////////////////////////////////////////////////
// Procedure : SidToString
// Comment : Converts a SID to its string representation
function SidToString(ASID: PSID):
string;
var
sDummy : LPTSTR;
begin
ConvertSidToStringSid(ASID, sDummy);
Result :=
string(sDummy);
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : StrSIDToName
// Comment : Obtains the user friendly name of a string SID
function StrSIDToName(
const StrSID:
string;
var Name:
string;
var SIDType: DWORD): Boolean;
var
SID : PSID;
Buffer : PChar;
NameLen, TempLen : Cardinal;
err : Boolean;
begin
SID :=
nil;
err := ConvertStringSIDToSID(PChar(StrSID), SID);
if err
then
begin
NameLen := 0;
TempLen := 0;
LookupAccountSidW(
nil, SID,
nil, NameLen,
nil, TempLen, SIDType);
GetMem(Buffer, NameLen);
try
err := LookupAccountSidA(
nil, SID, Buffer, NameLen,
nil, TempLen, SIDType);
if err
then
SetString(
Name, Buffer, Namelen);
finally
FreeMem(Buffer);
end;
end;
if Assigned(SID)
then
LocalFree(Cardinal(SID));
result := err;
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : GetProcessOwner
// Comment : Obtains the owner of the given process
function GetProcessOwner(PID: DWord;
var SID: PSID): Boolean;
var
hProcess : THandle;
err : DWord;
const
SE_UNKNOWN_OBJECT_TYPE: DWord = 0;
SE_FILE_OBJECT : DWord = 1;
SE_SERVICE : DWord = 2;
SE_PRINTER : DWord = 3;
SE_REGISTRY_KEY : DWord = 4;
SE_LMSHARE : DWord = 5;
SE_KERNEL_OBJECT : DWord = 6;
SE_WINDOW_OBJECT : DWord = 7;
begin
hProcess := 0;
err := 0;
try
hProcess := OpenProcess(PROCESS_QUERY_INFORMATION
or GENERIC_READ, False, pid);
if (hProcess <> 0)
then
begin
err := GetSecurityInfo(hProcess, SE_KERNEL_OBJECT, OWNER_SECURITY_INFORMATION, @SID,
nil,
nil,
nil,
nil);
CloseHandle(hProcess);
end;
except
end;
// Successfull if err = 0 AND hProcess <> 0
Result := (err = 0)
and (hProcess <> 0);
end;
var
SID : PSID;
ProcOwner :
string;
SidType : DWORD;
s :
string;
begin
if GetProcessOwner(GetCurrentProcessId, SID)
then
begin
StrSidToName(SidToString(SID), ProcOwner, SidType);
Writeln(ParamStr(0) + '
: ' + ProcOwner);
end
else
begin
Str(GetLastError, s);
Writeln('
GetLastError: ' + s);
end;
Readln;
end.