Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not getting path of various system processes by GetModuleFileNameEx()

Tags:

delphi

I have created this function to get the path of various network processes, like svchost, Firefox, etc. Here is the code:

function GetProcessPath(var pId:Integer):String;
var
    Handle: THandle;

begin
    Result := '';
    try
        Handle := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, pID);
        if Handle <> 0 then
        begin
            try
               SetLength(Result, MAX_PATH);
               if GetModuleFileNameEx(Handle, 0, PChar(Result), MAX_PATH) > 0 then
                   SetLength(Result, StrLen(PChar(Result)))
               else
                  Result := '';
            finally
                CloseHandle(Handle);
        end;
    end;

    except
       on E:Exception do
           ShowMessage(E.ClassName + ':' + E.Message);
    end;
end;

My problem is that I do not get the path of all the processes. It works fine for getting the path of Firefox, and other similar user level processes. But for processes like alg, Svchost, I cannot get the path by this method. My guess is I must use some different API. How can I fix this problem?

I am using Windows XP, 32 bits.

like image 795
CyprUS Avatar asked Jul 21 '11 05:07

CyprUS


1 Answers

You need to set debug privileges. Here is how it is done:

function NTSetPrivilege(sPrivilege: string; bEnabled: Boolean): Boolean;
var
  hToken: THandle;
  TokenPriv: TOKEN_PRIVILEGES;
  PrevTokenPriv: TOKEN_PRIVILEGES;
  ReturnLength: Cardinal;
begin
  Result := True;

  // Only for Windows NT/2000/XP and later.
  if not (Win32Platform = VER_PLATFORM_WIN32_NT) then Exit;

  Result := False;

  // Obtain the processes token
  if OpenProcessToken(GetCurrentProcess(),
    TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken) then
  begin
    try
      // Get the locally unique identifier (LUID) .
      if LookupPrivilegeValue(nil, PChar(sPrivilege),
        TokenPriv.Privileges[0].Luid) then
      begin
        TokenPriv.PrivilegeCount := 1; // One privilege to set

        case bEnabled of
          True: TokenPriv.Privileges[0].Attributes  := SE_PRIVILEGE_ENABLED;
          False: TokenPriv.Privileges[0].Attributes := 0;
        end;

        ReturnLength := 0; // Replaces a var parameter
        PrevTokenPriv := TokenPriv;

        // Enable or disable the privilege

        AdjustTokenPrivileges(hToken, False, TokenPriv, SizeOf(PrevTokenPriv),
          PrevTokenPriv, ReturnLength);
      end;
    finally
      CloseHandle(hToken);
    end;
  end;
end;

NtSetPrivilege('SeDebugPrivilege', TRUE); // Call this on form create
like image 51
opc0de Avatar answered Nov 09 '22 03:11

opc0de