Introduction

Maintaining access, also known as persistence, is the phase of a penetration test where the tester establishes mechanisms to retain access to compromised systems even after reboots, password changes, or network interruptions. In real-world attacks, persistence is what transforms a brief intrusion into a long-term compromise. In authorized testing, demonstrating persistence capabilities reveals gaps in an organization's ability to detect and remove unauthorized access.

This phase is particularly important from a defensive perspective. Understanding how persistence mechanisms work enables blue team members to identify indicators of compromise, develop detection rules, and validate that their incident response procedures can effectively eradicate attacker footholds. Many advanced persistent threat (APT) campaigns maintain access to victim networks for months or years through sophisticated persistence techniques.

During authorized penetration tests, persistence mechanisms are installed and documented with great care. Every persistence mechanism must be tracked for later removal, and testers must ensure that their persistence tools do not introduce new vulnerabilities that could be exploited by actual attackers during the engagement.

"Persistence is the key difference between a casual intruder and an advanced persistent threat. The ability to maintain access through reboots, credential rotations, and remediation attempts is what makes APT campaigns so devastating." -- Richard Bejtlich, The Practice of Network Security Monitoring

Persistence Mechanisms Overview

Persistence mechanisms can be categorized by their location in the system stack, their resilience to remediation, and their visibility to defenders:

CategoryLocationResilienceDetection Difficulty
User-LevelUser profile, startup folders, shell configsSurvives reboots, not OS reinstallLow -- visible in standard enumeration
Service/DaemonSystem services, cron, scheduled tasksSurvives reboots and user changesModerate -- requires service auditing
Registry/ConfigWindows registry, system configuration filesSurvives reboots, persists across updatesModerate -- requires baseline comparison
Kernel/DriverKernel modules, device driversSurvives reboots, difficult to removeHigh -- requires kernel-level analysis
Firmware/BIOSUEFI, BIOS, BMC, network device firmwareSurvives OS reinstallationVery High -- requires firmware analysis
Account-BasedNew user accounts, SSH keys, golden ticketsPersists until accounts are auditedLow-Moderate -- visible in user enumeration

Linux Persistence Techniques

Linux systems offer numerous persistence vectors due to the flexible nature of Unix-like operating systems. Understanding these vectors is essential for both red team operators and blue team defenders.

Cron and Systemd Persistence

Cron jobs and systemd services are among the most common persistence mechanisms on Linux. They execute automatically and are often overlooked during security reviews:

# Cron-based persistence (attacker perspective -- for defensive understanding)# User crontab -- runs as the compromised user(crontab -l 2>/dev/null; echo "*/5 * * * * /tmp/.hidden/callback.sh") | crontab -# System cron -- requires rootecho "*/10 * * * * root /opt/.maintenance/update.sh" >> /etc/crontab# Systemd service persistence (requires root)# A malicious service unit file:cat > /etc/systemd/system/system-update.service << 'UNIT'[Unit]Description=System Update ServiceAfter=network.target[Service]Type=simpleExecStart=/opt/.system/updaterRestart=alwaysRestartSec=60[Install]WantedBy=multi-user.targetUNITsystemctl enable system-update.service# DETECTION: Compare installed services against known-good baseline# Monitor: /etc/crontab, /etc/cron.d/, user crontabs, systemd unit files

SSH Key Persistence

Adding an authorized SSH key to a user's ~/.ssh/authorized_keys file provides password-independent access that persists through password changes:

# Attacker adds their public key (for defensive understanding)echo "ssh-rsa AAAA...attacker_key... comment" >> ~/.ssh/authorized_keys# DETECTION approaches:# 1. Monitor authorized_keys files for changes (file integrity monitoring)# 2. Audit all SSH keys against an approved key inventory# 3. Check for keys in unexpected user accounts# 4. Monitor SSH authentication logs for key-based logins from unusual sourcesfind / -name "authorized_keys" -exec ls -la {} \; 2>/dev/null

Shell Configuration Persistence

Shell configuration files (.bashrc, .bash_profile, .profile, .zshrc) execute every time a user opens a shell session. Malicious commands inserted into these files run automatically:

# Persistence via .bashrc (for defensive understanding)echo '/tmp/.hidden/callback &' >> ~/.bashrc# Persistence via .bash_profile (login shells)echo 'nohup /dev/shm/.updater &>/dev/null &' >> ~/.bash_profile# DETECTION:# 1. File integrity monitoring on shell configuration files# 2. Compare current configs against known-good baselines# 3. Look for commands executing binaries from /tmp, /dev/shm, or hidden directories# 4. Monitor for unusual .bashrc modifications in audit logs

Windows Persistence Techniques

Windows provides a rich set of persistence mechanisms through the registry, scheduled tasks, services, and various auto-start extensibility points (ASEPs). The Windows operating system has over 100 documented locations where programs can be configured to start automatically.

Registry Run Keys

The Windows registry contains several keys that specify programs to execute at user logon or system startup:

# Common registry persistence locations (for defensive understanding)# Per-user (HKCU) -- does not require admin privileges:reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v "UpdateService" /t REG_SZ /d "C:\Users\user\AppData\updater.exe"# System-wide (HKLM) -- requires admin privileges:reg add "HKLM\Software\Microsoft\Windows\CurrentVersion\Run" /v "SystemHelper" /t REG_SZ /d "C:\Windows\Temp\helper.exe"# Other registry persistence locations:# HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnce# HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce# HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon (Userinit, Shell)# HKLM\System\CurrentControlSet\Services# DETECTION: Monitor these registry keys for changes using Sysmon Event ID 13# or EDR solutions that track registry modifications

Scheduled Tasks

Windows scheduled tasks provide flexible persistence that supports various triggers (time-based, event-based, logon-based):

# Create a scheduled task for persistence (for defensive understanding)schtasks /create /tn "SystemMaintenance" /tr "C:\Windows\Temp\updater.exe" /sc onlogon /ru SYSTEM# PowerShell alternative with more options$action = New-ScheduledTaskAction -Execute "C:\Windows\Temp\updater.exe"$trigger = New-ScheduledTaskTrigger -AtLogonRegister-ScheduledTask -TaskName "SystemMaintenance" -Action $action -Trigger $trigger -RunLevel Highest# DETECTION:# 1. Monitor Task Scheduler logs (Event ID 106: task registered)# 2. Enumerate all scheduled tasks and compare to baseline# 3. Look for tasks executing from unusual directoriesschtasks /query /fo LIST /v# 4. Monitor Sysmon Event ID 1 for schtasks.exe process creation

WMI Event Subscriptions

Windows Management Instrumentation (WMI) event subscriptions provide a powerful and stealthy persistence mechanism. They consist of three components: an event filter (trigger condition), an event consumer (action to take), and a binding between the two. WMI persistence is entirely fileless -- the subscription is stored in the WMI repository, not on the file system.

ComponentPurposeExample Trigger
Event FilterDefines when the action triggersSystem startup, user logon, specific time interval
Event ConsumerDefines what action to takeExecute a command, run a script
Filter-to-Consumer BindingLinks the filter to the consumerAssociates trigger with action
# DETECTION of WMI persistence:# List all WMI event subscriptionsGet-WmiObject -Namespace root\subscription -Class __EventFilterGet-WmiObject -Namespace root\subscription -Class __EventConsumerGet-WmiObject -Namespace root\subscription -Class __FilterToConsumerBinding# Monitor Sysmon Event ID 19, 20, 21 for WMI events# Use Autoruns (Sysinternals) to enumerate WMI persistence

Backdoors and Web Shells

A backdoor is any mechanism that bypasses normal authentication to provide unauthorized access. Backdoors can range from simple additional user accounts to sophisticated implants with encrypted communication channels. Web shells are a specific type of backdoor -- server-side scripts deployed on web servers that provide command execution through HTTP requests.

Common backdoor types:

  • Rogue user accounts -- creating new administrative accounts or modifying existing account permissions
  • Modified binaries -- replacing legitimate system binaries (like sshd or login) with trojaned versions that accept a hardcoded password
  • Web shells -- PHP, ASP, JSP, or other server-side scripts that accept commands via HTTP parameters. Common web shells include China Chopper, WSO, b374k, and c99
  • Bind/reverse shells -- lightweight listeners or callbacks that provide command-line access
  • PAM backdoors -- modifying Linux's Pluggable Authentication Module configuration to accept a universal password
# DETECTION of web shells:# 1. File integrity monitoring on web directoriesfind /var/www -name "*.php" -newer /var/www/index.php -lsfind /var/www -name "*.php" -exec grep -l "eval\|base64_decode\|system\|passthru\|exec\|shell_exec" {} \;# 2. Monitor web server logs for unusual POST requests to static-looking URLs# 3. Check for files with unusual permissions or ownership in web directories# 4. Use YARA rules to scan for known web shell signatures# DETECTION of rogue accounts:# Linux: compare /etc/passwd against known-good baselineawk -F: '$3 == 0 {print $1}' /etc/passwd # Find all UID 0 accounts# Windows: enumerate local administratorsnet localgroup administrators

"A web shell on a server is like having a key to the front door that no one knows about. It is simple, effective, and unless you are actively looking for it, nearly invisible." -- MITRE ATT&CK documentation on Server Software Component: Web Shell (T1505.003)

Rootkits

A rootkit is a collection of tools designed to maintain access while actively concealing the attacker's presence. Unlike simple backdoors, rootkits modify the operating system itself to hide files, processes, network connections, and registry entries from administrators and security tools. For a detailed analysis of rootkit technology, see Rootkits Explained.

Rootkit TypeOperating LevelPersistenceDetection Method
User-modeApplication layer (API hooking)ModerateCross-view comparison, integrity checking
Kernel-modeKernel (syscall hooking, DKOM)HighKernel memory analysis, offline scanning
BootkitsBoot process (MBR/VBR/UEFI)Very HighSecure Boot validation, boot sector analysis
HypervisorBelow the OS (virtual machine based)Extremely HighTiming analysis, hardware-based detection
FirmwareHardware firmware (BIOS, NIC, HDD)Survives OS reinstallFirmware verification, supply chain security
# Rootkit detection tools:# Linux:chkrootkit # Checks for known rootkit signaturesrkhunter --check # Rootkit Hunter -- checks binaries, boot, and network# Cross-view detection:# Compare output of 'ps' (which rootkits may hook) with /proc enumerationls /proc | grep -E '^[0-9]+$' | wc -l # Direct /proc countps aux | wc -l # ps count (may be hooked)# Discrepancy suggests hidden processes# Memory forensics with Volatility:volatility -f memory.dump --profile=LinuxProfile linux_check_syscallvolatility -f memory.dump --profile=Win10x64 malfind

Command and Control (C2) Frameworks

Command and Control (C2) frameworks provide the infrastructure that allows a penetration tester (or attacker) to remotely manage compromised systems. C2 frameworks handle communication between the operator and deployed agents, providing features like encrypted channels, task management, file transfer, and pivoting through compromised networks.

Understanding C2 infrastructure is critical for defenders because C2 communication is often the most detectable phase of an attack. If an organization can identify and block C2 traffic, the attacker loses control of compromised systems regardless of their persistence mechanisms.

FrameworkLanguageLicenseNotable Features
Cobalt StrikeJavaCommercialMalleable C2 profiles, Beacon payload, extensive ecosystem
MetasploitRubyOpen Source / CommercialMeterpreter, extensive exploit library, community modules
SliverGoOpen SourceMulti-protocol (mTLS, HTTP, DNS, WireGuard), cross-platform
HavocC/C++Open SourceModern UI, BOF support, extensible agents
CovenantC#Open Source.NET-focused, Grunts payload, collaborative
MythicPython/GoOpen SourceModular agent architecture, extensive logging

C2 communication channels commonly used:

  • HTTPS -- the most common channel, as it blends with normal web traffic and is encrypted
  • DNS -- encodes data in DNS queries and responses; extremely difficult to block since DNS is essential for network operation
  • Domain fronting -- routes C2 traffic through legitimate CDN domains, making it appear as traffic to trusted services
  • Named pipes / SMB -- for internal lateral movement without generating external traffic
  • Custom protocols -- protocols designed to mimic legitimate traffic patterns

Detection Methods

Detecting persistence mechanisms and C2 activity is a core function of defensive security operations. Effective detection combines multiple approaches:

  • Autoruns analysis -- Microsoft Sysinternals Autoruns enumerates all auto-start extensibility points on Windows, revealing persistence mechanisms in registry keys, services, scheduled tasks, WMI, and more
  • File integrity monitoring (FIM) -- tools like OSSEC, Tripwire, and AIDE detect unauthorized changes to critical files and directories
  • Network traffic analysis -- monitor for beaconing patterns (regular interval callbacks), unusual DNS query volumes, connections to known-bad infrastructure, and encrypted traffic to unexpected destinations
  • Endpoint Detection and Response (EDR) -- modern EDR solutions monitor process creation, file modifications, registry changes, and network connections in real-time
  • Memory forensics -- tools like Volatility analyze system memory for injected code, hidden processes, and rootkit indicators
  • Log correlation -- SIEM platforms correlate events across multiple sources to identify persistence and C2 patterns
  • Threat hunting -- proactive searches for indicators of compromise using MITRE ATT&CK persistence techniques as a framework

"Detection of persistence mechanisms is not optional -- it is a fundamental requirement for any mature security program. If you cannot detect an attacker's persistence, you cannot confirm that you have fully eradicated them from your environment." -- David Bianco, creator of the Pyramid of Pain

Incident Response Considerations

When persistence mechanisms are discovered during a real incident (as opposed to an authorized test), the response requires careful planning to ensure complete eradication:

  • Identify all persistence mechanisms -- attackers typically deploy multiple persistence methods. Removing only one while others remain active means the attacker retains access
  • Coordinate remediation -- remove all persistence mechanisms simultaneously to prevent the attacker from detecting partial remediation and establishing new footholds
  • Credential rotation -- assume all credentials on compromised systems are compromised. Rotate passwords, revoke and reissue SSH keys, and invalidate Kerberos tickets
  • Rebuild vs. clean -- for systems with kernel-level or firmware persistence, rebuilding from known-good media is often more reliable than attempting to clean the infection
  • Post-remediation monitoring -- increase monitoring intensity after remediation to detect any persistence mechanisms that were missed

For the next phase of penetration testing, see Covering Tracks. For background on the previous phase, see Privilege Escalation.

References

  • MITRE ATT&CK. (2024). "Persistence." Tactic TA0003. The MITRE Corporation.
  • Bejtlich, R. (2013). The Practice of Network Security Monitoring. No Starch Press.
  • Russinovich, M. (2024). Sysinternals Autoruns Documentation. Microsoft.
  • Mudge, R. (2023). Cobalt Strike Documentation. Fortra.
  • Case, A., & Levy, J. (2022). The Art of Memory Forensics. Wiley.
  • CISA. (2023). "Detecting and Preventing Web Shell Malware." Cybersecurity and Infrastructure Security Agency.
  • NSA & CISA. (2023). "Hunting and Detecting Persistence Mechanisms." Joint Cybersecurity Advisory.
  • Bianco, D. (2014). "The Pyramid of Pain." detect-respond.blogspot.com.
  • NIST SP 800-61 Rev. 2. (2012). Computer Security Incident Handling Guide. National Institute of Standards and Technology.
  • Mandiant. (2023). M-Trends 2023: Special Report. Google Cloud.