Let's say I have a handle the following code
pid = 1234
pHandle = win32api.OpenProcess(win32con.MAXIMUM_ALLOWED,pywintypes.FALSE,pid)
tHandle = win32security.OpenProcessToken(pHandle,win32con.MAXIMUM_ALLOWED)
How would I determine if the process' token was a primary or impersonation token?
CodePudding user response:
process token is always primary token. so here nothing to determine. the thread token is always (if exist) impersonation token. so when you open process or thread token - you already know it type. all api which return token - return known from begin token type. only case, when you need determine token type (which is unknown ) - you enumerate process handles and try check token handles.
for this you need use GetTokenInformation
with TokenType
, but really this is rare case, when you can need this. only for some debug utility.
demo code on c/c
ULONG GetTokenType(_In_ HANDLE hToken, _Out_ PTOKEN_TYPE ptp)
{
ULONG cb;
return GetTokenInformation(hToken, ::TokenType, ptp,
sizeof(TOKEN_TYPE), &cb) ? NOERROR : GetLastError();
}
void DemT()
{
HANDLE hToken;
if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
{
TOKEN_TYPE tp;
// we already know that token is primary
if (GetTokenType(hToken, &tp) != NOERROR || tp != TokenPrimary)
{
__debugbreak();
}
CloseHandle(hToken);
if (0 <= NtImpersonateAnonymousToken(GetCurrentThread()))
{
if (OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &hToken))
{
// we already know that token is impersonating
if (GetTokenType(hToken, &tp) != NOERROR || tp != TokenImpersonation)
{
__debugbreak();
}
CloseHandle(hToken);
}
SetThreadToken(0, 0);
}
}
}