Searching for a SID in an Access Token Program Example 2
The following program example is another working sample which is a smaller than the previous one. Notice the functions used in this program and compared to the previous program example.
Create a new empty Win32 console application project. Give a suitable project name and change the project location if needed.
Then, add the source file and give it a suitable name.
Next, add the following source code.
#include <windows.h>
#include <stdio.h>
/*
This routine returns TRUE if the caller's process is a member of the
Administrators local group. Caller is NOT expected
to be impersonating anyone and is expected to be able
to open its own process and process token.
Arguments: None.
Return Value:
TRUE - Caller has Administrators local group.
FALSE - Caller does not have Administrators local group.
*/
BOOL IsUserAdminGrp(void)
{
BOOL check = FALSE;
SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
PSID AdministratorsGroup;
check = AllocateAndInitializeSid(
&NtAuthority,
2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0,
&AdministratorsGroup);
// if TRUE
if(check)
{
wprintf(LSID was allocated and initialized...\n);
// Determines whether a specified security identifier (SID) is enabled in an access token.
if(!CheckTokenMembership(
NULL, // uses the impersonation token of the calling thread.
// If the thread is not impersonating, the function duplicates
// the thread's primary token to create an impersonation token
AdministratorsGroup, // Pointer to a SID structure
&check // Result of the SID
))
{
wprintf(LCheckTokenMembership() failed, error %u\n, GetLastError());
}
else
{
wprintf(LCheckTokenMembership() is OK!\n);
// If the SID (the 2nd parameter) is present and has the SE_GROUP_ENABLED attribute,
// check (3rd parameter) returns TRUE; otherwise, it returns FALSE.
if(check == TRUE)
wprintf(LYes, you are an Administrators group!\n);
else
wprintf(LNo, you are not an Administrators group!\n);
}
FreeSid(AdministratorsGroup);
}
else
wprintf(LAllocateAndInitializeSid() failed, error %u\n, GetLastError());
return(check);
}
int wmain(int argc, WCHAR **argv)
{
BOOL bRetVal = IsUserAdminGrp();
if(!bRetVal)
wprintf(LIsUserAdminGrp() failed, error %u\n, GetLastError());
else
wprintf(LIsUserAdminGrp() is OK!\n);
return 0;
}
Build and run the project. The following screenshot is a sample output.