In Windows, a program can get a user access token by calling LogonUser
, OpenProcessToken
, SSPI functions, and a couple others. Once you have the token, there are quite a few functions that you can pass this token into in order to do things as this user. Do these sort of actions typically have side effects for the "parent" process?
For example, you can load the user's profile (registry settings, etc) via LoadUserProfile
. Amongst other things, LoadUserProfile
will load the user's registry hive into HKEY_USERS
and map HKEY_CURRENT_USER
to it. From the parent process' perspective, does this alter HKEY_CURRENT_USER
? Or is it only "visible" after starting a new process as that user via CreateProcessAsUser
, impersonating in the current process via ImpersonateLoggedOnUser
, etc?
Per its documentation, LoadUserProfile()
returns a handle to the HKEY_CURRENT_USER
key that was loaded. You can then pass that handle to Registry functions, and they will access that user's data. LoadUserProfile()
does not affect the HKEY_CURRENT_USER
key associated with the user that is running the calling process.
Impersonation CAN affect the calling process's HKEY_CURRENT_USER
key, but typically WILL NOT:
Predefined Keys
HKEY_CURRENT_USER
...
The mapping between HKEY_CURRENT_USER and HKEY_USERS is per process and is established the first time the process references HKEY_CURRENT_USER. The mapping is based on the security context of the first thread to reference HKEY_CURRENT_USER. If this security context does not have a registry hive loaded in HKEY_USERS, the mapping is established with HKEY_USERS.Default. After this mapping is established it persists, even if the security context of the thread changes.
So, if you are impersonating a user when you use HKEY_CURRENT_USER
for the first time, then it will map to that user's key for the duration of the process. Raymond Chen even said as much on his blog:
Is it wrong to call SHFileOperation from a service? Revised
The registry key HKEY_CURRENT_USER is bound to the current user at the time the key is first accessed by a process:
...
This means that if you impersonate a user, and then access HKEY_CURRENT_USER, then that binds HKEY_CURRENT_USER to the impersonated user. Even if you stop impersonating, future references to HKEY_CURRENT_USER will still refer to that user.
However, for the majority of cases, you will likely access the Registry before you impersonate anyone, or you will not access the Registry while impersonating, so HKEY_CURRENT_USER
will typically map to the user that the app is running as. If a thread is impersonating a user and needs to access that user's HKEY_CURRENT_USER
key, use OpenThreadToken()
(if you don't already have the token) and LoadUserProfile()
to get that user's HKEY_CURRENT_USER
handle.