Investigating Token Impersonation and Mitigating Token Theft Risks
Executive Summary
In the world of cyber security, our role as cyber-security experts is crucial. Staying updated on the latest news of cyber-attacks is a constant necessity. Companies worldwide are always under the threat of malicious actors. Behind the scenes, cyber-security companies that develop security products, offer security consulting, or offer security services play a vital role in staying updated on the latest attacks, such as new vulnerabilities discovered and published by security researchers, emerging APT groups, and evolving tactics, techniques, and procedures (TTPs).
As a security researcher, I have observed the use of Token Impersonation by APT groups and malware, such as APT41, AppleSeed, BlackCat, Cuba, etc. This technique is employed to elevate the privileges of the malware on the targeted system, enabling it to execute its operations without limitations.
This research will delve into the intricate world of one of the known techniques, the Access Token Manipulation technique, the Token Impersonation/Theft sub-technique, and the challenging task of mitigating token theft.
Token Impersonation
Token Impersonation is a technique that allows threat actors to steal tokens of privileged processes or users. Threat actors can use those tokens and do the following operations:
1. Steal the token of a privileged user and impersonate themselves as the privileged user.
2. Steal the token of a privileged process and impersonate themselves as the privileged process and get SYSTEM privileges.
While threat actors or penetration testers get their foothold on the targeted machine and get local administrator’s privileges, sometimes, they cannot dump the content memory of the lsass.exe process and continue with their lateral movement techniques. It is a result of disabling the SeDebugPrivilege from the local administrator group; it can be done through the local group policy or the domain group policy.
Windows Privileges and Access Rights
Privileges in the Windows OS are the rights of users, groups, processes, or services to perform system operations according to their level of privileges. Privileges can come into play in accessing system resources and objects in the Windows OS, such as folders, SMB shares, NTFS, files, policies, configurations, etc. Also, in regular operations, privileges can come into play, such as system time changes, closing tasks, configuring scheduled tasks, system commands, etc.
In the different Windows environments, such as WORKGROUP and Domain environments, the ability to grant privileges to users is controlled by administrator users or users with administrative privileges. For example, in the WORKGROUP environment, local administrators have permission to grant privileges to users in the local system. In contrast, in the Domain environment, Domain administrators have control over user accounts, privileges, and security policies in all the systems that are connected to the same Active Directory.
On the contrary, access rights define the level of access that a user or process has to a particular resource. These access rights include permissions such as read, write, execute, modify, and delete. Those permissions are applied to objects in the Windows OS, such as files, directories, registry keys, etc.
Windows uses ACLs (Access Control Lists) to manage privileges and access rights. Each object in the system has the associated ACL that specifies which users, groups, processes, or services have the level of access to the particular objects.
Access Token
In Windows OS, an Access Token is a data structure that contains information about a user account and its associated security attributes. When a user logs in to his account in the Windows system, a unique access token is created for that user. This token includes details such as the user’s security identifier (SID), group membership, privileges, determine if the token is a primary or impersonation token and other details.
Windows uses the tokens to make secure interactions between users and the file system. When a user attempts to access a file, folder, or other secured object in the system, the OS examines the access token of the user’s session to determine whether the requested action should be allowed or not.
For example, a non-privileged domain user privileges:
Another example of a privileged domain user privileges:
Types of Tokens
There are two types of tokens:
0x01: Primary/Delegation Token
The primary token is associated with a user’s logon session when they initially authenticate to the system. It represents the security content of the user account and contains information about the particular user, including privileges.
The primary token is used by processes to perform operations on behalf of the logged-in user. For example, when a user launches an application, the application’s process takes the primary token of the user’s logon session, and it allows the process to access resources according to the user’s permissions. Furthermore, when a primary token is created, it cannot be changed. If the user’s privileges or group were changed, a new creation of the primary token is needed through a logon session.
0x02: Impersonation Token
Impersonation tokens are created when users log in non-interactively to a system, such as accessing a shared network drive. In some cases, when a domain user tries to access a network share, they may not enter their credentials, but their tokens can still be used to authenticate them.
Windows Authentication
When a user attempts to log in to their account in a WORKGROUP or DOMAIN environment, they must enter their login credentials. Behind the Windows logon screen, a process called winlogon.exe displays the user and password request. Once the user enters the credentials, the Winlogon process transfers the information to the LSA (Local Security Authority). The LSA is responsible for validating users for both local and remote sign-ins, and it enforces local security policies. The validation process takes place in the lsass.exe (Local Security Authority Subsystem Service) process, which is a part of the LSA. This process validates the credentials provided by the user by checking them against the Security Accounts Manager (SAM) database. The SAM is a database in the Windows OS that contains local usernames and passwords. If the credentials match the information in the SAM database, a unique primary token is generated by the LSA for the user based on their group permissions. However, if the credentials do not match, the system will return an error message, and the user will be asked to enter their credentials again.
Local Token Impersonation Vs. Remote Token Impersonation
There are two methods that attackers can use when they get their initial access to the system and elevate their privileges within a system: local token impersonation and remote token impersonation.
Local token impersonation is a technique that attackers can use to escalate privileges. This method involves stealing the primary token of a privileged user or process in order to impersonate them and obtain their level of access. When a potential attacker gets initial access to a system, the attacker can exploit the token mechanism to manipulate access tokens. On the other hand, remote token impersonation is a technique in which a potential attacker exploits the token impersonation in network boundaries to steal and impersonate the primary token of a privileged user or process on a remote system.
Even the local token impersonation and remote token impersonation are almost the same, there are several differences:
1. Local token impersonation is a technique that can be exploited in the same local system. In contrast, remote token impersonation is a technique that can be exploited across network boundaries remotely.
2. In local token impersonation, attackers exploit misconfigurations of privileges on processes and users in the local system to manipulate access tokens and escalate privileges. In contrast, in remote token impersonation, attackers exploit vulnerabilities in network protocols, services, or processes to get initial access to remote systems and manipulate access tokens across network boundaries.
3. The risk level or the impact of local impersonation can be limited because attackers manipulate access tokens in local systems. In contrast, remote token impersonation has a much higher risk because it can enable attackers to escalate privileges across systems and networks, and it can lead to lateral movement.
Local Token Impersonation
Eventually, when a threat actor gets initial access to a system, its first action is to maintain access to the particular system and then find a way to escalate privileges to do more actions on the system and perform lateral movement techniques. One of the privilege escalation techniques is token impersonation. Local token impersonation is a technique that allows threat actors to steal the primary token of a privileged process or user and perform actions on their behalf without limitations.
0x01 Reversing Section
This section will dive deeper into the local token impersonation technique using reverse engineering and understand how threat actors can perform the particular technique, from API functions usage to Proof-of-Concept (PoC).
First, the program executes the ‘sub_140001000’ subroutine to enable the SeDebugPrivilege privilege constant of the current process to debug and monitor other processes running on the local system. It gives the ability to ignore the DACL for the remote process.
BOOL LookupPrivilegeValueA(
[in, optional] LPCSTR lpSystemName,
[in] LPCSTR lpName,
[out] PLUID lpLuid
);
The lpName is a pointer that specifies the name of the privilege constant, which is the SeDebugPrivilege. The lpLuid is a pointer to a variable that receives the LUID.
If the program succeeds in retrieving the LUID of the privilege constant, it jumps to the 140001055 memory location in the code, which is responsible for opening the access token of the current process using the OpenProcessToken function.
In this situation, if the program succeeds in accessing the access token of the current process, it will then jump to the memory location 1400010A6. This location is responsible for enabling the privilege constant in the current process by using the AdjustTokenPrivileges. It does this by using the NewState parameter, which is a pointer to the TOKEN_PRIVILEGES structure. This structure specifies the privilege constant to be modified and its attributes. The program uses the SE_PRIVILEGE_ENABLED attribute to enable the privilege.
After the program enables the SeDebugPrivilege privilege constant, it obtains the access token of the targeted process. First, the program uses the OpenProcess API to open and get a handle on the targeted process. The targeted process id is specified in the dwProcessId parameter. Then, it uses the OpenProcessToken API to open the access token of the targeted process. To open the access token of the process, the handle of the process must have the PROCESS_QUERY_LIMITED_INFORMATION access permission. Then, it prints the appropriate messages that the process access token was obtained successfully.
After the program obtained the access token, it specified the cmd.exe process path to open a cmd window with the privileges of the targeted process. It executed the code inside the 140001900 subroutine.
In the 140001900 subroutine, the program uses the DuplicateTokenEx API to create a new access token that duplicates the existing token in the targeted process. The function creates a new primary token, which is specified in the TokenType parameter; the new token is saved under the phNewToken (hToken) parameter. Then, it creates a new process, which is the cmd.exe process, with the new access token and loads the targeted user profile with the CreateProcessWithTokenW API function. The program loads the targeted user profile in the dwLogonFlags parameter with the LOGON_WITH_PROFILE logon options, which means that the program loads the user’s profile from the HKEY_USERS registry key. And it opens the cmd.exe process in the lpApplicationName parameter.
0x02 Execution Section
This section will demonstrate the execution of the program that we reverse engineered in the previous section. The following screenshot demonstrates the program execution that successfully obtained the access token of the lsass.exe process and duplicated the token. As a result, it opens a CMD window with SYSTEM privileges.
Remote Token Impersonation
Remote token impersonation is a technique in which a potential attacker can exploit the token impersonation in network boundaries to steal and impersonate the primary token of a privileged user or process on a remote system in the same network. This kind of technique enables attackers to perform actions on behalf of that process or user privileges.
0x01 Named Pipes Explanation
Named pipes are a Windows mechanism that provides a way for processes to communicate with each other, even if they are running on different systems. Eventually, Named Pipes gives a possibility to make communication channels that allow one process to send data to another process, even locally or over a network. Named Pipes can be used for synchronous and asynchronous communication, which enables data exchange between processes while ensuring secure and reliable communication across system configurations.
For a better understanding of the purpose of Named Pipes and their role in the Windows OS, the following diagram demonstrates the Named Pipes’s purpose.
There are two separate Windows systems in the same network connection. Two processes need to exchange data with each other to run their functionalities properly. Guy’s Windows system executes a process that opens a Named Pipe server to open a block of shared memory for the data exchange and waits for the client’s connection. Lior’s Windows system executes a process that connects to the Named Pipe server and starts the data exchange as expected.
0x02 Reversing Section — Server Side
This section is going to be the same as local token impersonation. This section will dive deeper into the remote token impersonation technique using reverse engineering and understand how threat actors can perform the particular technique, from API functions usage to Proof-of-Concept (PoC).
When using the remote token impersonation technique, a server side is required to open and handle the named pipe server.
The initial operation of the process obtains the primary token of the current process using the GetCurrentProcess and the OpenProcessToken functions.
After the process obtains the primary token of the current process, it uses the LookupPrivilegeValue function to retrieve the locally unique identifier (LUID) of the SE_IMPERSONATE_NAME privilege, which is for impersonating a client after authentication.
Then, it configures the NewState structure to enable the SE_IMPERSONATE_NAME privilege. It can be seen when the program sets the PrivilegeCount to 1 and the Attributes to 2; it indicates the intent to enable the privilege. The AdjustTokenPrivileges function modifies the process’s token with the new privileges.
The server program uses the CreateNamedPipeW function to open the named pipe and define the required parameters, such as name, type, and the open mode. The lpName parameter is the unique pipe named that must be configured as the following string:
\\.\pipe\pipedexample
The dwOpenMode parameter must be specified from one of the mode lists that Microsoft documented:
The mode configuration can be any from Microsoft’s list, but in a regular named pipe, the mode configuration should be PIPE_ACCESS_DUPLEX to allow the client side and the server side read/write permissions to the named pipe.
Then, it specifies the pipe mode in the dwPipeMode parameter, which configures the data that is written to the pipe.
Finally, this subroutine uses the ConnectNamedPipe to wait for and handle the incoming connections from clients.
When the client establishes the communication with the named pipe, then, the data exchange moves using the WriteFile function.
The program uses the ImpersonateNamedPipeClient to enable the impersonation of the connected client and allows the possibility to perform actions on the client’s behalf.
Furthermore, the program uses the OpenThreadToken and DuplicateTokenEx functions to open and duplicate the elevated access token for subsequent process creation. Finally, it opens the cmd.exe process with the new duplicated token using the CreateProcessWithTokenW function.
0x03 Reversing Section — Client side
The client side is intended for communicating with the remote named pipe that the server-side opened.
First, the client specifies the path to the named pipe using CreateFileW, which opens the specified named pipe. It then enters a loop, where it repeatedly calls the ReadFile function to read data from the named pipe into the Buffer.
0x04 Execution Section
This section will demonstrate the execution of both the client and the server side that we reverse engineered. The following screenshot demonstrates the program execution that successfully obtained the access token of the client and duplicated the token. As a result, it opens a CMD window with SYSTEM privileges.
Using the ((Get-ChildItem \\.\pipe\).name)[-1..-5] command, we can see the available pipes in the current system.
Mitigation / Detection
For detecting the token impersonation techniques, it’s recommended to use security products such as EDR (Endpoint Detection and Response), XDR (Extended Detection and Response), or SIEM (Security Information and Event Management) system. When using EDR, XDR, or SIEM they can help you with monitoring for suspicious and malicious behaviors in the system, such as privilege escalation techniques or changes in the token privileges.
However, privilege escalation techniques and token manipulation can be detected manually. It can be done using the Windows audit events, configuring code integrity policies, enabling the protected processes mode, etc.
Windows Audit
Windows Audit is a feature in the Windows OS that allows users, administrators, or security products to monitor security events that occur on a computer or network. Windows Audit can be helpful for detecting various suspicious and malicious activities, such as user logon events, file and object access, account management changes, new processes opened, running services, etc. This kind of log can be seen in the Windows Security log, which is part of the Event Viewer program.
There are several Windows events in the Windows audit, for example:
When creating a user in the system, the following EIDs (Event IDs) should be triggered:
4728: A member was added to a security-enabled global group
4720: A user account was created
4722: A user account was enabled
4738: A user account was changed
4724: An attempt was made to reset an accounts password
4732: A member was added to a security-enabled local group
The 4720 EID is sufficient for analyzing logs and identifying which user was created in the system. In the event details, we can extract the hostname, username of the user who created the new user, new username, and other relevant information related to the new user account.
Detecting the Token Impersonation
The detection process is based on the system access control list (SACL) in the Windows OS. SACL allows users and administrators to log every successful or failed access attempt to processes, directories, and files to the Windows Audit Log.
For setting the audit policy for object access, it is possible to use the auditpol command to enable the auditing for the Object Access category, including both success and failure events.
auditpol /set /category:”Object Access” /success:enable /failure:enable
In contrast, it is possible to enable the auditing for the Object Access category manually through the Group Policy, and it can be found in the following path:
Computer Configuration > Windows Settings > Security Settings > Local Policies > Audit Policy > Audit object access
Then, we should configure an SACL to the lsass.exe process objects to log every successful or failed access attempt to the Windows Audit log. To do that, we need to install the NtObjectManager PowerShell module.
Install-Module -Name NtObjectManager
Import-Module NtObjectManager
After the module installation, we use the Get-NtProcess and GetSecurityDescriptor functions to obtain a handle the lsass.exe process with the appropriate privileges to request SACL access.
By default, the audit log doesn’t log every access to objects in the Windows OS. Because of that, we need to update the security descriptor of the lsass.exe process. To do that, we need to configure the discretionary access control list (DACL) for the object.
$requestSACLPrivileges = Get-NtProcess -Name lsass.exe -Access GenericAll,AccessSystemSecurity
Set-NtSecurityDescriptor $requestSACLPrivileges “S:(AU;SAFA;0x1400;;;WD)” Sacl
S: Setting the security descriptor.
(AU;SAFA;0x1400;;;WD): Specifies the DACL for the object:
AU: indicates the audit ACE type, meaning it will generate a security event when specified access rights are triggered.
SAFA: It specifies that the audit ACE applies to successful and failed access attempts.
0x1400: It is a hexadecimal value that represents the bitwise OR of two access right. For example, the 0x400 value represents the PROCESS_QUERY_INFORMATION security attribute, and the 0x1000 value represents the PROCESS_QUERY_LIMITED_INFORMATION security attribute.
WD: The audit ACE will be applied to the Everyone group.
Sacl: Specifies that we are updating the SACL of the object.
0x01 0x1000 Access Mask
After the successful execution of the Token Impersonation technique on the lsass.exe process, the EID 4656 has triggered in the Windows event viewer. The 4656 EID represents A handle to an object was requested. The TokenImpersonation.exe process requests a handle to the lsass.exe object. In the Access Request information column, there is the Access Mask parameter that indicates the hexadecimal value of the security attribute, which is 0x1000, which represents the PROCESS_QUERY_LIMITED_INFORMATION.
0x02 0x1400 Access Mask
Another successful execution of the Token Impersonation technique on the lsass.exe process, the EID 4656, has triggered again in the Windows event viewer. The Access Mask parameter value is 0x1400, which represents the PROCESS_QUERY_INFORMATION.
0x03 0x1FFFFF Access Mask
The third successful execution of the Token Impersonation technique on the lsass.exe process, the EID 4656, has triggered again in the Windows event viewer. The Access Mask parameter value is 0x1FFFFF, which represents the PROCESS_ALL_ACCESS. The 0x1FFFFF hexadecimal value is equal to 2097151 in decimal, which this value indicates the full access right to the object.
Mitigating the Token Impersonation
When it comes to token impersonation or token theft, threat actors cannot steal and duplicate tokens of all processes in the operating system. For example, it is possible to steal and duplicate the wlms.exe process’s token and get a CMD window with SYSTEM privileges.
In contrast, for some reason, it is impossible to steal and duplicate the spoolsv.exe process’s token and get a CMD window with the appropriate privileges.
To understand why, in some SYSTEM processes, the token impersonation technique works or not, we need to understand the given privileges that the particular processes have and find differences. The comparison will be between the wlms.exe process to the spoolsv.exe process.
0x01 Advanced Permission Properties
In the Sysinternals suite’s Process Explorer tool, users can view advanced permission properties for specific processes they want to investigate.
In the wlms.exe process’s advanced permission properties, we can determine that the Administrators group has only the Terminate, Read Memory, Query Information, Query Limited Information, and Read Permissions advanced permissions.
The spoolsv.exe process’s advanced permission properties only have the Query Information and Query Limited Information permissions. On the contrary of the wlms.exe process, the spoolsv.exe process does not have the Terminate, Read Memory, and Read Permissions advanced permissions.
0x02 Protected Process
In Process Explorer, users can check if system processes have special protection mechanisms. Processes like smss.exe, wininit.exe, services.exe, and csrss.exe (among others) are protected by the PsProtectedSignerWinTcb-Light. The PsProtectedSignerWinTcb-Light process protection indicates that the process has been signed with a special Microsoft Windows TCB (Trusted Computing Base) certificate. This certificate is used for system components that require a higher level of privilege. Using the Microsoft Windows TCB, the OS enforces strict integrity checks to ensure that the process has not been tampered with or modified by unauthorized components and processes. In addition, the OS ensures that only privileged users and system components with appropriate permissions can modify the protected process. This kind of protection can prevent and mitigate token manipulation techniques.
Conclusion
In this token manipulation research, we delved into token impersonation and manipulation in the Windows OS. In this research and analysis, we explored two different kinds of token impersonation techniques, different kinds of Windows privileges, and detection and mitigation of the Token Impersonation techniques.
This research began with an in-depth overview of access tokens, Windows privileges, access rights, and Windows authentication. We examined in detail the structure of access tokens and the components of access tokens, including user and group SIDs and privileges. In addition, we explored the meaning of tokens in the aspect of process impersonation and highlighted their role in determining access rights and permissions within the system.
Finally, we explored the detection and mitigation of the token impersonation techniques by the Windows Event Audit Log and security mechanisms in the system.