Retrieve if my own process have SeDebugPrivilege enabled

Viewed 267

How can I determine if my own process have SeDebugPrivilege enabled?

1 Answers

Here is the solution if somebody more need it.

type
  TPrivilegesArray = array [0..1024] of TLuidAndAttributes;
  PPrivilegesArray = ^TPrivilegesArray;
var
  luid          : TLargeInteger;
  LuidSDP       : TLargeInteger;
  hToken        : THandle;

  Size          : Cardinal;
  Privileges    : PTokenPrivileges;
  I             : Integer;

  Name          : string;
  Attr          : Longword;

  function AttrToString: string;
  begin
    Result := 'Disabled';
    if (Attr and SE_PRIVILEGE_ENABLED) <> 0 then Result := 'Enabled';
    if (Attr and SE_PRIVILEGE_ENABLED_BY_DEFAULT) <> 0 then Result := 'Enabled By Default';

    Result := Result;
  end;
begin
  OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, hToken);

  GetTokenInformation(hToken, TokenPrivileges, nil, 0, Size);
  Privileges := AllocMem(Size);
  GetTokenInformation(hToken, TokenPrivileges, Privileges, Size, Size);
  LookupPrivilegeValue(nil, 'SeDebugPrivilege', LuidSDP);

  for I := 0 to Privileges.PrivilegeCount - 1 do
  begin
    if LuidSDP <> PPrivilegesArray(@Privileges^.Privileges)^[I].Luid then Continue;

    Luid := PPrivilegesArray(@Privileges^.Privileges)^[I].Luid;
    Attr := PPrivilegesArray(@Privileges^.Privileges)^[I].Attributes;
    Size := 0;

    LookupPrivilegeName(nil, Luid, nil, Size);
    SetLength(Name, Size);
    LookupPrivilegeName(nil, Luid, PChar(Name), Size);

    Form1.Memo2.Lines.Add(Format('[%d][%s][%s]', [Luid, PChar(Name), AttrToString]));
  end;

  FreeMem(Privileges);
  CloseHandle(hToken);

This code list all privileges and if are disabled, enabled by default or enabled. After some search and modifications this code are working perfectly.

if need list all privileges just comment the line

if LuidSDP <> PPrivilegesArray(@Privileges^.Privileges)^[I].Luid then Continue;
Related