1

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;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Leong
  • 229
  • 2
  • 11

1 Answers1

1

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.

fpiette
  • 11,983
  • 1
  • 24
  • 46
  • `OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, TokenHandle); ` is it replace the 'GetCurrentProcess' to PID? – Leong Dec 04 '20 at 08:29
  • 1
    I added links to Windows API functions. ProcessID ==> OpenProcess ==> OpenProcessToken ==> GetTokenInformation ==> TokenElevation. – fpiette Dec 04 '20 at 10:02
  • If my answer fits your needs, please mark it as accepted (The check mark on the left of the answer). Thanks. – fpiette Dec 08 '20 at 13:02