Skip to main content
Be Bitwise

Windows Security APIs

Windows API - GUI & System Programming · Windows Programming track

10 min read

In this module

Access Tokens, Privileges, and Security Descriptors

The Windows security model is denser than most. Three concepts hold most of it together. Access tokens say who you are. Security descriptors say who's allowed to touch a given object. Privileges say which system-wide trump cards your token gets to play. Get fluent in those three, and the rest of the picture — UAC, integrity levels, impersonation, ACL evaluation — falls into place. This is the surface that privilege-escalation research and incident-response work both spend most of their time on.

Access Tokens

Every process carries a primary token that pins down its security identity. Threads can layer an impersonation token on top, swapping identity for the duration of a request — handy for servers that need to act as the calling client:

c
// Get the current process token
HANDLE hToken;
OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES, &hToken);
// Query token information
TOKEN_USER *pUser = NULL;
DWORD size = 0;
GetTokenInformation(hToken, TokenUser, NULL, 0, &size);
pUser = (TOKEN_USER *)malloc(size);
GetTokenInformation(hToken, TokenUser, pUser, size, &size);
// Convert SID to string for display
LPSTR sidString;
ConvertSidToStringSidA(pUser->User.Sid, &sidString);
printf("User SID: %s\n", sidString); // e.g., S-1-5-21-...-1001
LocalFree(sidString);
free(pUser);

Token Contents

text
Access Token:
┌────────────────────────────────────────┐
│ User SID: S-1-5-21-...-1001 (alice) │
│ Group SIDs: │
│ S-1-5-32-544 (Administrators) │
│ S-1-5-32-545 (Users) │
│ S-1-5-21-...-513 (Domain Users) │
│ Privileges: │
│ SeDebugPrivilege (disabled) │
│ SeChangeNotifyPrivilege (enabled) │
│ SeShutdownPrivilege (disabled) │
│ Integrity Level: Medium (S-1-16-8192) │
│ Session ID: 1 │
│ Logon ID: 0x3e7 │
│ Token Type: Primary │
└────────────────────────────────────────┘
Security Identifiers (SIDs)

A SID is a unique binary value that identifies a security principal (user, group, or computer). SIDs have the format S-R-I-S1-S2-...-Sn, where R is the revision, I is the identifier authority, and S1-Sn are sub-authority values. Well-known SIDs include S-1-5-18 (SYSTEM), S-1-5-32-544 (Administrators), and S-1-5-32-545 (Users). SIDs are persistent - deleting and recreating an account with the same name creates a different SID.

Privilege Management

Privileges are the sledgehammers in the Windows security toolkit. Each one unlocks some system-wide operation that ordinary ACL checks can't gate. A privilege has to be both present in your token and explicitly enabled before it does anything:

c
// Enable SeDebugPrivilege (allows opening any process)
BOOL EnablePrivilege(HANDLE hToken, LPCSTR privilege) {
TOKEN_PRIVILEGES tp;
LUID luid;
// Look up the privilege LUID
if (!LookupPrivilegeValueA(NULL, privilege, &luid))
return FALSE;
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
return AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(tp),
NULL, NULL);
}
// Usage:
HANDLE hToken;
OpenProcessToken(GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken);
EnablePrivilege(hToken, SE_DEBUG_NAME); // "SeDebugPrivilege"
// Now we can open any process with OpenProcess()
CloseHandle(hToken);

Important Privileges

text
SeDebugPrivilege - Debug any process (open ANY process handle)
SeBackupPrivilege - Read any file regardless of ACLs
SeRestorePrivilege - Write any file regardless of ACLs
SeTakeOwnershipPrivilege - Take ownership of any object
SeLoadDriverPrivilege - Load kernel drivers
SeImpersonatePrivilege - Impersonate other users
SeAssignPrimaryTokenPrivilege - Assign tokens to processes
SeTcbPrivilege - Act as part of the operating system

Security Descriptors and ACLs

Anything Windows considers a securable object — files, registry keys, processes, services, named pipes, mutexes — carries a security descriptor holding its access control lists:

c
// Create a security descriptor with a custom DACL
SECURITY_DESCRIPTOR sd;
InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);
// Create a DACL
EXPLICIT_ACCESS ea[2];
ZeroMemory(ea, sizeof(ea));
// ACE 1: Allow Administrators full control
ea[0].grfAccessPermissions = GENERIC_ALL;
ea[0].grfAccessMode = SET_ACCESS;
ea[0].grfInheritance = NO_INHERITANCE;
ea[0].Trustee.TrusteeForm = TRUSTEE_IS_SID;
// ... set Trustee to Administrators SID ...
// ACE 2: Allow Users read access
ea[1].grfAccessPermissions = GENERIC_READ;
ea[1].grfAccessMode = SET_ACCESS;
ea[1].grfInheritance = NO_INHERITANCE;
ea[1].Trustee.TrusteeForm = TRUSTEE_IS_NAME;
ea[1].Trustee.ptstrName = TEXT("BUILTIN\\Users");
PACL pDacl = NULL;
SetEntriesInAcl(2, ea, NULL, &pDacl);
SetSecurityDescriptorDacl(&sd, TRUE, pDacl, FALSE);
// Apply to a file
SECURITY_ATTRIBUTES sa = {
.nLength = sizeof(sa),
.lpSecurityDescriptor = &sd,
.bInheritHandle = FALSE
};
HANDLE hFile = CreateFile(TEXT("protected.dat"), GENERIC_ALL,
0, &sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

Impersonation

Impersonation lets a thread borrow somebody else's identity for a stretch:

c
// Server impersonating a client (e.g., named pipe server)
ImpersonateNamedPipeClient(hPipe);
// Thread now runs with client's token
// File accesses are checked against client's identity
// Check who we're impersonating
HANDLE hToken;
OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &hToken);
// ... query token information ...
// Revert to original identity
RevertToSelf();

IIS and RPC servers do this all day: receive a request, drop to the calling user's identity, perform the operation under that user's ACLs, and revert. The user gets exactly the access they're entitled to, without the server having to duplicate the access-check logic itself.

UAC and Integrity Levels

UAC adds a second axis of access control on top of the SID/ACL world: integrity levels. Even when you're logged in as Administrator, your processes get capped at Medium until you explicitly request a higher integrity token. Reads go through normal ACL evaluation. Writes get pre-checked against the integrity level, and a Low-IL process simply cannot stomp on a High-IL object regardless of what the DACL says:

text
Integrity Levels:
┌────────────────────────────────────────┐
│ System (S-1-16-16384) │ SYSTEM services
│ High (S-1-16-12288) │ Elevated admin processes
│ Medium (S-1-16-8192) │ Standard user processes
│ Low (S-1-16-4096) │ Browser sandboxes
│ Untrusted (S-1-16-0) │ Most restricted
└────────────────────────────────────────┘

The mechanism enforcing this is called Mandatory Integrity Control (MIC), and it's the bedrock that makes browser sandboxes possible on Windows.

c
// Check current integrity level
HANDLE hToken;
OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken);
TOKEN_MANDATORY_LABEL *pLabel = NULL;
DWORD size = 0;
GetTokenInformation(hToken, TokenIntegrityLevel, NULL, 0, &size);
pLabel = (TOKEN_MANDATORY_LABEL *)malloc(size);
GetTokenInformation(hToken, TokenIntegrityLevel, pLabel, size, &size);
DWORD integrityLevel = *GetSidSubAuthority(
pLabel->Label.Sid,
*GetSidSubAuthorityCount(pLabel->Label.Sid) - 1);
if (integrityLevel >= SECURITY_MANDATORY_HIGH_RID)
printf("Running elevated (High integrity)\n");
else if (integrityLevel >= SECURITY_MANDATORY_MEDIUM_RID)
printf("Running as standard user (Medium integrity)\n");
else
printf("Running in sandbox (Low integrity)\n");
Key Concept
UAC Elevation

When an administrator user logs in, Windows creates two tokens: a filtered token (medium integrity, admin group disabled) and a full admin token (high integrity). Standard processes use the filtered token. When elevation is needed (running as administrator), the consent UI appears, and if approved, the process gets the full admin token. This dual-token design means admin users run with reduced privileges by default.

CryptoAPI Basics

Windows ships its own crypto stack for hashing, encryption, and digital signatures. The original interface is CryptoAPI:

c
#include <wincrypt.h>
// Acquire a cryptographic provider
HCRYPTPROV hProv;
CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT);
// Create a hash object
HCRYPTHASH hHash;
CryptCreateHash(hProv, CALG_SHA_256, 0, 0, &hHash);
// Hash some data
BYTE data[] = "Hello, World!";
CryptHashData(hHash, data, sizeof(data) - 1, 0);
// Get the hash value
BYTE hashValue[32];
DWORD hashLen = sizeof(hashValue);
CryptGetHashParam(hHash, HP_HASHVAL, hashValue, &hashLen, 0);
// Print hash
for (DWORD i = 0; i < hashLen; i++)
printf("%02x", hashValue[i]);
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);

For new code, reach for Cryptography Next Generation (CNG) — the BCrypt* family of functions. CNG ships modern algorithms, plays better with FIPS validation, and is what Microsoft is actually maintaining.

The Windows security model is layered, and the layers only make sense together. Tokens carry identity. ACLs carry permissions. Integrity levels add a coarse veto on top, and privileges punch through ACL checks entirely for system-wide operations. Pull on any one of these without understanding the others and you'll misread what's actually allowed — which is exactly how privilege-escalation bugs hide in plain sight, and why incident responders spend so much time staring at token dumps.