- Impersonation Levels (Authorization)
- Client Impersonation (Authorization)
- Windows Identity. Impersonate Метод
- Определение
- Перегрузки
- Impersonate()
- Возвращаемое значение
- Исключения
- Примеры
- Комментарии
- Примечания для тех, кто вызывает этот метод
- Применяется к
- Impersonate(IntPtr)
- Параметры
- Возвращаемое значение
- Исключения
- Примеры
- Комментарии
- Примечания для тех, кто вызывает этот метод
- Impersonation
- Access Tokens for Impersonation
- Delegation and Impersonation
Impersonation Levels (Authorization)
The SECURITY_IMPERSONATION_LEVEL enumeration defines four impersonation levels that determine the operations a server can perform in the client’s context.
Impersonation level | Description |
---|---|
SecurityAnonymous | The server cannot impersonate or identify the client. |
SecurityIdentification | The server can get the identity and privileges of the client, but cannot impersonate the client. |
SecurityImpersonation | The server can impersonate the client’s security context on the local system. |
SecurityDelegation | The server can impersonate the client’s security context on remote systems. |
The client of a named pipe, RPC, or DDE connection can control the impersonation level. For example, a named pipe client can call the CreateFile function to open a handle to a named pipe and specify the server’s impersonation level.
When the named pipe, RPC, or DDE connection is remote, the flags passed to CreateFile to set the impersonation level are ignored. In this case, the impersonation level of the client is determined by the impersonation levels enabled by the server, which is set by a flag on the server’s account in the directory service. For example, if the server is enabled for delegation, the client’s impersonation level will also be set to delegation even if the flags passed to CreateFile specify the identification impersonation level.
DDE clients use the DdeSetQualityOfService function with the SECURITY_QUALITY_OF_SERVICE structure to specify the impersonation level. The SecurityImpersonation level is the default for named pipe, RPC, and DDE servers. The ImpersonateSelf, DuplicateToken, and DuplicateTokenEx functions allow the caller to specify an impersonation level. Use the GetTokenInformation function to retrieve the impersonation level of an access token.
At the SecurityImpersonation level, most of the thread’s actions occur in the security context of the thread’s impersonation token rather than in the primary token of the process that owns the thread. For example, if an impersonating thread opens a securable object, the system uses the impersonation token to check the thread’s access. Similarly, if an impersonating thread creates a new object, for example by calling the CreateFile function, the owner of the new object is the default owner from the client’s access token.
However, the system uses the primary token of the process rather than the impersonation token of the calling thread in the following situations:
- If an impersonating thread calls the CreateProcess function, the new process always inherits the primary token of the process.
- For functions that require the SE_TCB_NAME privilege, such as the LogonUser function, the system always checks for the privilege in the primary token of the process.
- For functions that require the SE_AUDIT_NAME privilege, such as the ObjectOpenAuditAlarm function, the system always checks for the privilege in the primary token of the process.
- In a call to the OpenThreadToken function, a thread can specify whether the function uses the impersonation token or the primary token to determine whether to grant the requested access.
Client Impersonation (Authorization)
Impersonation is the ability of a thread to execute using different security information than the process that owns the thread. Typically, a thread in a server application impersonates a client. This allows the server thread to act on behalf of that client to access objects on the server or validate access to the client’s own objects.
The Microsoft Windows API provides the following functions to begin an impersonation:
- A DDE server application can call the DdeImpersonateClient function to impersonate a client.
- A named-pipe server can call the ImpersonateNamedPipeClient function.
- You can call the ImpersonateLoggedOnUser function to impersonate the security context of a logged-on user’s access token.
- The ImpersonateSelf function enables a thread to generate a copy of its own access token. This is useful when an application needs to change the security context of a single thread. For example, sometimes only one thread of a process needs to enable a privilege.
- You can call the SetThreadToken function to cause the target thread to run in the security context of a specified impersonation token.
- A Microsoft Remote Procedure Call (RPC) server application can call the RpcImpersonateClient function to impersonate a client.
- A security package or application server can call the ImpersonateSecurityContext function to impersonate a client.
For most of these impersonations, the impersonating thread can revert to its own security context by calling the RevertToSelf function. The exception is the RPC impersonation, in which the RPC server application calls RpcRevertToSelf or RpcRevertToSelfEx to revert to its own security context.
Windows Identity. Impersonate Метод
Определение
Позволяет олицетворять различных пользователей Windows с помощью кода. Allows code to impersonate a different Windows user.
Перегрузки
Олицетворяет пользователя, представленного объектом WindowsIdentity. Impersonates the user represented by the WindowsIdentity object.
Олицетворяет пользователя, представленного заданным токеном. Impersonates the user represented by the specified user token.
Impersonate()
Олицетворяет пользователя, представленного объектом WindowsIdentity. Impersonates the user represented by the WindowsIdentity object.
Возвращаемое значение
Объект, представляющий пользователя Windows до олицетворения; может использоваться для возврата к исходному контексту пользователя. An object that represents the Windows user prior to impersonation; this can be used to revert to the original user’s context.
Исключения
Попытка выполнить олицетворение с использованием анонимного удостоверения. An anonymous identity attempted to perform an impersonation.
Произошла ошибка Win32. A Win32 error occurred.
Примеры
В следующем примере показано, как получить маркер учетной записи Windows путем вызова неуправляемой LogonUser функции Win32 и как использовать этот маркер для олицетворения другого пользователя, а затем вернуться к исходному удостоверению. The following example demonstrates how to obtain a Windows account token by calling the unmanaged Win32 LogonUser function, and how to use that token to impersonate another user and then revert to the original identity.
Комментарии
На платформах Windows NT текущий пользователь должен иметь достаточные права для разрешения олицетворения. On Windows NT platforms, the current user must have sufficient rights to allow impersonation.
Избегайте использования этого метода с шаблоном async/await. Avoid using this method with the async/await pattern. В некоторых случаях это может привести к проблемам с надежностью из-за того, что олицетворение не будет отменено, даже если полученный результат WindowsImpersonationContext удален. In some cases it may lead to reliability issues due to impersonation not being reverted even if the resulting WindowsImpersonationContext is disposed. Взамен рекомендуется использовать RunImpersonated . Use RunImpersonated instead.
Примечания для тех, кто вызывает этот метод
После использования Impersonate() метода важно вызвать Undo() метод для завершения олицетворения. After using Impersonate(), it is important to call the Undo() method to end the impersonation.
Применяется к
Impersonate(IntPtr)
Олицетворяет пользователя, представленного заданным токеном. Impersonates the user represented by the specified user token.
Параметры
Дескриптор токена учетной записи Windows. The handle of a Windows account token. Этот токен обычно извлекается путем вызова неуправляемого кода, например вызова функции LogonUser API Windows. This token is usually retrieved through a call to unmanaged code, such as a call to the Windows API LogonUser function.
Возвращаемое значение
Объект, представляющий пользователя Windows до олицетворения; может использоваться для возврата к исходному контексту пользователя. An object that represents the Windows user prior to impersonation; this object can be used to revert to the original user’s context.
Исключения
Система Windows вернула код состояния STATUS_ACCESS_DENIED Windows NT. Windows returned the Windows NT status code STATUS_ACCESS_DENIED.
Не хватает памяти. There is insufficient memory available.
У вызывающего объекта нет нужных разрешений. The caller does not have the correct permissions.
Примеры
В следующем примере показано, как получить маркер учетной записи Windows путем вызова неуправляемой LogonUser функции Win32 и как использовать этот маркер для олицетворения другого пользователя, а затем вернуться к исходному удостоверению. The following example demonstrates how to obtain a Windows account token by calling the unmanaged Win32 LogonUser function, and how to use that token to impersonate another user and then revert to the original identity.
Комментарии
На платформах Windows NT текущий пользователь должен иметь достаточные права для разрешения олицетворения. On Windows NT platforms, the current user must have sufficient rights to allow impersonation.
Вызов Impersonate(IntPtr) метода со userToken значением Zero эквивалентен вызову RevertToSelf функции Win32. Calling the Impersonate(IntPtr) method with a userToken value of Zero is equivalent to calling the Win32 RevertToSelf function. Если в настоящее время выполняется олицетворение другого пользователя, управление возвращается к исходному пользователю. If another user is currently being impersonated, control reverts to the original user.
Дополнительные сведения о вызовах неуправляемого кода см. в разделе Использование неуправляемых функций DLL. For more information about calls to unmanaged code, see Consuming Unmanaged DLL Functions.
Избегайте использования этого метода с шаблоном async/await. Avoid using this method with the async/await pattern. В некоторых случаях это может привести к проблемам с надежностью из-за того, что олицетворение не будет отменено, даже если полученный результат WindowsImpersonationContext удален. In some cases it may lead to reliability issues due to impersonation not being reverted even if the resulting WindowsImpersonationContext is disposed. Взамен рекомендуется использовать RunImpersonated . Use RunImpersonated instead.
Примечания для тех, кто вызывает этот метод
После использования Impersonate(IntPtr) метода важно вызвать Undo() метод для завершения олицетворения. After using Impersonate(IntPtr), it is important to call the Undo() method to end the impersonation.
Impersonation
Impersonation is the ability of a thread to execute in a security context that is different from the context of the process that owns the thread. When running in the client’s security context, the server «is» the client, to some degree. The server thread uses an access token representing the client’s credentials to obtain access to the objects to which the client has access.
The primary reason for impersonation is to cause access checks to be performed against the client’s identity. Using the client’s identity for access checks can cause access to be either restricted or expanded, depending on what the client has permission to do. For example, suppose a file server has files containing confidential information and that each of these files is protected by an ACL. To help prevent a client from obtaining unauthorized access to information in these files, the server can impersonate the client before accessing the files.
Access Tokens for Impersonation
Access tokens are objects that describe the security context of a process or thread. They provide information that includes the identity of a user account and a subset of the privileges available to the user account. Every process has a primary access token that describes the security context of the user account associated with the process. By default, the system uses the primary token when a thread of the process interacts with a securable object. However, when a thread impersonates a client, the impersonating thread has both a primary access token and an impersonation token. The impersonation token represents the client’s security context, and this access token is the one that is used for access checks during impersonation. When impersonation is over, the thread reverts to using only the primary access token.
You can use the OpenProcessToken function to get a handle to the primary token of a process. Use the OpenThreadToken function to get a handle to the impersonation token of a thread.
Delegation and Impersonation
In client/server scenarios, it is common for one server to call another server to accomplish some task on a client’s behalf. The situation where a server is given the authority to act on a client’s behalf is called delegation.
From a security standpoint, two issues arise regarding delegation:
- What should the server be allowed to do when acting on the client’s behalf?
- What identity is presented by the server when it calls other servers on behalf of a client?
To deal with these issues, COM provides the following functionality. The client can set an impersonation level that determines to what extent the server will be able to act as the client. If the client grants enough authority to the server, the server can impersonate (pretend to be) the client. When impersonating the client, the server is given access to only those objects or resources that the client has permission to use. The server, acting as a client, can also enable cloaking to mask its own identity and project the client’s identity in calls to other COM components.
Consider the scenario illustrated by the preceding figure, where A and B are processes on a different machine from C. Process A calls B, and B calls C. Client A sets the impersonation level. B sets the cloaking capability. If A sets an impersonation level that permits impersonation, B can impersonate A when calling C on A’s behalf. The identity that is presented to process C will be either A’s identity or B’s identity, depending on whether cloaking was enabled by B. If cloaking is enabled, the identity presented to process C will be that of A. If cloaking is not enabled, B’s identity will be presented to C.
For more information, see the following topics: