I'm duplicating a window's process token and using it to impersonate the user:
DuplicateTokenEx(lsassProcessToken, 0x2000000, NULL, SecurityImpersonation, TokenPrimary, &duplicatedToken);
ImpersonateLoggedOnUser(duplicatedToken);
Now, I wonder if it is safe to close the handle with CloseHandle(duplicatedToken)
while still impersonating? Or, does the handle to the token need to be open until I call RevertToSelf()
?
Does ImpersonateLoggedOnUser
take ownership of the duplicated token and the token is correctly deleted after RevertToSelf()
?
Yes, after researching and a few tests, it is safe to close the duplicated token handle after you have called ImpersonateLoggedOnUser()
. In fact, it is recommended to do so, to prevent any possible resource leak.
The Reason being:
The ImpersonateLoggedOnUser()
function does not take ownership of the token handle, it simply uses the token internally to change the security context of the calling thread.
According to Microsoft's documentation on ImpersonateLoggedOnUser()
:
The calling thread continues to run in the security context of the impersonated user until the
RevertToSelf
function is called.The token handle passed to the function must have TOKEN_IMPERSONATE access.
Although, there's no mention that ImpersonateLoggedOnUser()
retains or manages the handle's lifecycle, but after a few tests it seems that closing the handle does not undo the impersonation and the thread continues impersonating the user until you explicitly call RevertToSelf()
.