Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to find out if a service is running as the SYSTEM user

What is the correct way to find out if a process is running as the SYSTEM user. I'm looking for a win32 C API to check for the system user.

We used to check if the username was "SYSTEM", but since Windows Server 2008 R2 the SYSTEM user appears to be localised. I.e SYSTEEM on a Dutch system.

I cant find much information about the system user via search engines as you get millions of false hits.

Thanks in advance Neil

like image 245
Neil Wightman Avatar asked Oct 26 '10 12:10

Neil Wightman


1 Answers

There is code to do this independent of localization here.

BOOL IsLocalSystem()
{
  HANDLE hToken;
  UCHAR bTokenUser[sizeof(TOKEN_USER) + 8 + 4 * SID_MAX_SUB_AUTHORITIES];
  PTOKEN_USER pTokenUser = (PTOKEN_USER)bTokenUser;
  ULONG cbTokenUser;
  SID_IDENTIFIER_AUTHORITY siaNT = SECURITY_NT_AUTHORITY;
  PSID pSystemSid;
  BOOL bSystem;

  // open process token
  if (!OpenProcessToken(GetCurrentProcess(),
    TOKEN_QUERY,
    &hToken))
      return FALSE;

  // retrieve user SID
  if (!GetTokenInformation(hToken, TokenUser, pTokenUser,
    sizeof(bTokenUser), &cbTokenUser))
  {
    CloseHandle(hToken);
    return FALSE;
  }

  CloseHandle(hToken);

  // allocate LocalSystem well-known SID
  if (!AllocateAndInitializeSid(&siaNT, 1, SECURITY_LOCAL_SYSTEM_RID,
    0, 0, 0, 0, 0, 0, 0, &pSystemSid))
    return FALSE;

  // compare the user SID from the token with the LocalSystem SID
  bSystem = EqualSid(pTokenUser->User.Sid, pSystemSid);

  FreeSid(pSystemSid);

  return bSystem;
}

The same code would work (if modified) for any of the well-known SIDs defined here.

like image 162
Steve Townsend Avatar answered Oct 29 '22 14:10

Steve Townsend