Check specific process is elevated in delphi

385 Views Asked by At

I have the following code that can help to check whether the process is running under elevated.

img1

How can I modify the code in order to allow it to check whether a certain process is elevated?

function IsElevated: Boolean;
const
  TokenElevation = TTokenInformationClass(20);
type
  TOKEN_ELEVATION = record
    TokenIsElevated: DWORD;
  end;
var
  TokenHandle: THandle;
  ResultLength: Cardinal;
  ATokenElevation: TOKEN_ELEVATION;
  HaveToken: Boolean;
begin
  if CheckWin32Version(6, 0) then
  begin
    TokenHandle := 0;
    HaveToken := OpenThreadToken(GetCurrentThread, TOKEN_QUERY, True, TokenHandle);
    if (not HaveToken) and (GetLastError = ERROR_NO_TOKEN) then
      HaveToken := OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, TokenHandle);
    if HaveToken then
    begin
      try
        ResultLength := 0;
        if GetTokenInformation(TokenHandle, TokenElevation, @ATokenElevation, SizeOf(ATokenElevation), ResultLength) then
          Result := ATokenElevation.TokenIsElevated <> 0
        else
          Result := False;
      finally
        CloseHandle(TokenHandle);
      end;
    end
    else
      Result := False;
  end
  else
    Result := True;
end;
1

There are 1 best solutions below

3
fpiette On

Your answer is almost in your question...

The function IsElevated get the result from GetTokenInformation which takes a TokenHandle. That TokenHandle is given by OpenProcessToken which receives the current process handle.

Now you are interested not by current process but by another for which you have ProcessID. So you get process handle you need by calling OpenProcess with processID. It is likely you need elevated privilege to do that.