Windows 用户模仿有什么副作用?

What side affects are there from Windows user impersonation?

在 Windows 中,程序可以通过调用 LogonUser, OpenProcessToken、SSPI 函数和其他几个函数来获取用户访问令牌。获得令牌后,您可以将此令牌传递给许多函数,以便以该用户的身份执行操作。这些操作通常会对 "parent" 过程产生副作用吗?

例如,您可以通过 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 等加载用户的配置文件(注册表设置等)?

根据其 documentationLoadUserProfile() returns 加载的 HKEY_CURRENT_USER 键的句柄。然后您可以将该句柄传递给注册表函数,它们将访问该用户的数据。 LoadUserProfile() 不影响与 运行 调用进程的用户关联的 HKEY_CURRENT_USER 键。

模拟可以影响调用进程的 HKEY_CURRENT_USER 键,但通常不会:

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.

因此,如果您在第一次使用 HKEY_CURRENT_USER 时模拟用户,那么在整个过程中它将映射到该用户的密钥。陈峰甚至在他的博客上说了很多:

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.

但是,在大多数情况下,您可能会在模拟任何人之前访问注册表,或者您在模拟时不会访问注册表,因此 HKEY_CURRENT_USER 通常会映射到该应用程序的用户运行 作为。如果线程正在模拟用户并需要访问该用户的 HKEY_CURRENT_USER 密钥,请使用 OpenThreadToken()(如果您还没有令牌)和 LoadUserProfile() 来获取该用户的 HKEY_CURRENT_USER句柄。