Friday, June 01, 2012

toolsmith: Security Investigations with PowerShell


Prerequisites
Windows, ideally Windows 7 or Windows Server 2008 R2 as PowerShell is native
There are 32-bit & 64bit versions of PowerShell for Windows XP, Windows Server 2003, Windows Vista and Windows Server 2008 as well.

Introduction
Windows power users have long sought strong fu at the command line. In the beginning, Bill said “Let there be shell.” And lo, there was command.com and cmd.exe. Then Jim said, there must be scripting support and automation, and thus the likes of Windows Script Host and WMIC were brought to light. But alas, there were challenges; no shell integration, no interoperability. Then unto thee was delivered the shell prophet Monad (see the Monad Manifesto), later renamed Window PowerShell in 2006.
In a nutshell, PowerShell is powerful. Alright, enough of the PowerShell parable.
Really though, any sysadmin running modern Windows platforms is likely using or has used PowerShell. Full disclosure: I work for Microsoft. But before you write me off as just being a fan boy, hear me out. Aside from all the administrative horsepower PowerShell provides it also lends significant punch to security-related investigations as part of incident response and/or forensic reviews.
As you know, I always prefer to “ask the expert” when it comes to toolsmith topics so I sought counsel from Ed Wilson (Microsoft Scripting Guy) regarding security investigations with PowerShell.

“Using Windows PowerShell to aid in security forensics is a no-brainer. First of all, Windows PowerShell is installed by default beginning with Windows 7, so the tool is likely to already be available. Second Windows PowerShell makes it extremely easy to collect the data you need to analyze. A very simple Windows PowerShell script (or a few Windows PowerShell commands) can dump the windows logs, take a snapshot of running services, processes, and gather system time. In addition, the script can collect any other logs you wish. The above can be done in just a few lines of easily readable code. When Windows PowerShell remoting is enabled (enabled by default on Windows Server 2012) there is no difference between running a command on one or a thousand different systems.
The real power begins, however, when you decide to parse the collected data. A number of Windows PowerShell cmdlets make trolling through massive amounts of XML, CSV, or even unstructured text a breeze. Whether you are parsing an offline Windows event log, a firewall log, or even a syslog gathered from a remote Unix machine the process remains the same. In short Windows PowerShell is the one tool you do not want to leave home (even virtually) without.”  

I pitch a straight fastball right in Ed’s wheelhouse and he drives it out of the park for me.
We’ll take on both of these scenarios as described by Ed:
·         Using PowerShell to dump Windows logs, assess running services, processes, and gather other useful system data.
·         Using PowerShell to parse collected data
In a case of shameless self-promotion I want to call out the benefits of tools that aid in culling evil from logs as described above. My recently posted SANS Reading Room paper for my GCIA Gold research effort, Evil Through The Lens of Web Logs discusses a number of tools to conduct such parsing activity but it fails to mention PowerShell. This is my chance to correct that shortcoming.

Using PowerShell

There are endless online PowerShell resources via the likes of TechNet, MSDN, CodePlex, and SANS-related content. Also check out Adam Bell’s great list on Lead, Follow, or Move. Rather than rehash such content, I’ll instead walk through an investigation using cmdlets and scripts that are directly relevant to the cause. Do remember that get-help from the PowerShell prompt is definitely your friend.
Caveat: I do not lay claim to any of the strings or commands included hereafter, they are mimicked and modified from the above mentioned resources or yanked right from Get-Help. This work is neither unique nor particularly creative. It is instead intended to help you recognize why PowerShell is so incredibly useful. To those true aficionados who swiftly recognize how much detail I’m leaving out, feel free to share your feedback and I’ll add it the related blogpost and/or accept comments.
Imagine a malicious person has created a backdoor on a Windows system using tini, has renamed tini to a trusted file name, created a service to ensure that it always runs, and has changed the listening port to 31337 (original, I know). I’m operating from the premise that we already know the basic gist of the attacker activity and will focus much more on how to discover it with PowerShell. So, what PowerShell juju can we utilize to rebuild the trail of malfeasance?
First, fire up a PowerShell prompt. Start | Programs | Accessories | Windows PowerShell followed by your preferred PowerShell (x86 or 64-bit) or Integrated Scripting Environment (ISE). Note: when you bring PowerShell scripts on your system that have been created by other users, you may need to check script execution policy. By default, unsigned PS1 files are prevented from execution for reasons of inherent risk to the system as untrusted. As long as you are cognitive of this risk you can do the following, in order, from the PowerShell prompt.
1)  Get-ExecutionPolicy
2)  Set-ExecutionPolicy where policy is one of four options:
a.       Restricted - default execution policy, doesn’t run scripts, interactive only
b.      AllSigned - runs scripts, scripts and configuration files must be signed by trusted publisher
c.       RemoteSigned – Like as AllSigned when script is downloaded apps such as IE and Outlook
d.      Unrestricted – goes without saying

Let’s start with running services. You have reason to believe that the attacker’s backdoor is running as a known service name. Begin with get-service. Results are a little busy so let’s narrow it down. Get-Service | Where-Object {$_.status -eq "running"} thins the crowd a bit by presenting only running services, but still nothing leaps right out. Sometimes the service description or lack thereof is revealing.  There is no parameter defined via get-service to pull a service description but it can be done via get-wmiobject win32_service | format-list Name, Description. The result is again busy but I found my culprit as seen in Figure 1.

Figure 1: Service description gone wild
Now that we know the name of our faux service in this imaginary scenario, let’s explore possibly related processes with Get-Process | Out-Gridview. This will spawn a second window with a conveniently interactive table view of the results. If we operate on the premise that a malicious process name TapiSrv might be in play, we can filter the grid view or we can drill in for it specifically with Get-Process TapiSrv as seen in Figure2.  

Figure 2: Malicious process
Let’s determine the TapiSrv file information and process owner. Get-Process TapiSrv –fileversioninfo tells us the TapiSrv resides in C:\tmp\TapiSrv.exe. Helpful, but wait, there’s more. (get-wmiobject win32_process | where{$_.ProcessName -eq 'TapiSrv.exe'}).getowner() | Select -property domain, user will tell us that I am he who propagates the evil and write-host ([WMI]'').ConvertToDateTime((Get-WmiObject win32_process | where{$_.ProcessName -eq 'TapiSrv.exe'}).creationdate) will tell us the date and time I created it as seen in Figure 3 (no you do not get to see my domain name).

Figure 3: Process owner, creation date & time
The Get-Member cmdlets will help you determine which properties and methods are available to you where the likes of get-wmiobject win32_process | get-member told us that getownerConvertToDateTime, and creationdate were all available to us via get-wmiobject.

Figure 2 gave us something useful to explore further in the Id, also known as the PID.
We can take information such as 9512 and throw Microsoft MVP Shay Levy’s Get-NetworkStatistics at it. When you want to add PowerShell modules such as Shay’s that aren’t native you can use import-module as follows after saving the code from your preferred resource as a PSM1 file:
import-module -name D:\tools\powershell\Get-NetworkStatistics.psm1 –verbose
Thereafter, Get-NetworkStatistics will simply be available on demand. Issuing Get-NetworkStatistics | where{$_.PID -eq '9512'} | format-table reveals all our suspicions and closes the loop as seen in Figure 4.

Figure 4: Mapping PID to port and process
TapiSrv is PID 9512 and listening on port 31337. There’s the evil backdoor.

Ed also described using PowerShell for log analysis. In the above mentioned Evil Through The Lens of Web Logs research paper, I used Log Parser-related tools. Early stages of this research were also included in the April 2012 toolsmith column on Log Parser Lizard. Can one conduct similar activity without Log Parser via PowerShell? Of course. Tim Medin, of CommandLine Kung Fu (one of my absolute favorite blogs), wrote the sweet little PowerShell IIS LogObjectifier. Saved as a script or modularized, Tim’s code allows you to search by common IIS log field identifiers such as UriStem, UriQuery, UserAgent, and Win32Status. Utilizing the same log sample analyzed for the research paper, as well as similar principles, I set a PowerShell query using Tim’s script to identify log entries with 500 status codes from a specific SourceIp as an example. Imagine we have reason to suspect that SourceIp of a SQL injection attack. The query, .\objectify.ps1 $log | where{$_.Win32Status -eq '500' -and $_.SourceIp -eq '78.46.28.97'} resulted in Figure 5.

Figure 5: IIS log objectified via PowerShell
As you can see, 78.46.28.97 made an attempt to inject a HEX-obfuscated DECLARE statement into the victim application.

The possibilities are endless. I didn’t even touch the concepts of PowerShell remoting or running PowerShell cmdlets at scale. Did I mention the possibilities are endless? Hopefully, this brief synopsis whets your appetite.

In Conclusion

So much data, not enough time or word space. There is clearly so much that can be done with Windows PowerShell. The last resource I’ll share with you may become your PowerShell dashboard: A Task-Based Guide toWindows PowerShell Cmdlets. This resource will send you right down the rabbit hole as you further explore what we’ve started here. No reason not to head there now. Much thanks to Ed Wilson for supporting this exploration.
Ping me via email if you have questions (russ at holisticinfosec dot org).
Cheers…until next month.

Acknowledgements

Ed Wilson (The Scripting Guy) for content and endless insight on PowerShell.


Wednesday, May 23, 2012

Bredolab author jailed, rehash of Bredolab analysis

Just read that the Bredolab botnet author was sentenced to 4 years in prison in Armenia.
In July 2010, when Bredolab was in it's heyday I used Netwitness Investigator to do analysis of a Bredolab-infected host. In honor of Georgy Avanesov's arrest, following is a reprint of the resulting toolsmith article. Bredolab samples and PCAPs available upon request via email or @holisiticinfosec. Netwitness is now in version 9.7.5.4, so some of the guidance and how-to herein may have changed.




Prerequisites
Windows operating system (XP/2003 or later)


Introduction
As I write this month’s column I’m on a plane returning from the 22nd Annual FIRST Conference in Miami. As always, in addition to a collection of the world’s finest computer incident response teams, there were a select number of vendors. I will be honest when I admit that I typically avoid conference vendor booths unless the swag is really good, but some of my favorites were in attendance including Mandiant and Secunia. When I noticed the NetWitness booth I was reminded of the suggestions I’d heard suggesting NetWitness Investigator as a toolsmith topic. During Robert Rounsavall’s FIRST presentation, Forensics considerations in next generation cloud environments, he made mention of the fact that the Terremark teams make use of NetWitness offerings on their high throughput network capture platforms. Incident responders, network analysts, and security engineers typically can’t get enough of good network capture tools; the reminder triggered by the NetWitness booth presence clearly indicated that the time had come.
Specifically, NetWitness Investigator is part of a suite of products offered by NetWitness that are designed to capture network traffic and use the resulting data for business and security problem analysis. Others include Administrator, Decoder, Concentrator, Broker, Informer, and the NwConsole. Most NetWitness applications are commercial offerings, but Investigator is freely available and quite useful.

Installing and configuring NetWitness Investigator
Installation is point and click simple. Accept defaults or modify installation paths as you see fit. You will need to register the Computer ID generated for the host on which you’re installing that is generated as part of the license key. Provide a valid email address; you’ll be sent a link to activate your installation for first use.
Keep in mind that by default NetWitness Investigator does phone home for new updates and will reach out to the NetWitness web service to offer you the most recent FAQs, News and Community posts in the
Welcome page. If you prefer otherwise select Edit, then Options, and uncheck Automatically Check for Updates as well as Allow Investigator to Reach Internet.
If you don’t have WinPcap installed you will be prompted to do so; WinPcap 4.1.1 is bundled with the installation package.
Under View be sure to enable the Capture Bar as it will present a Capture icon and Collection selector at the bottom of the NetWitness Investigator UI.
You can also pre-define the interface from which you’d like to capture via the Options menu as described above.

Using NetWitness Investigator

The NetWitness Investigator (NI) Welcome Page provides useful FAQ; read it as you get underway.
NI allows you to either capture data directly from the host network interfaces, including wireless adapters, or import network captures from other sources and its use is built around Collections. The free version of NI doesn’t offer Remote Collections as they are specific to retrieving data gathered by other NetWitness commercial offerings. That said you can create Local Collections.
Ctrl + L will pull up the new Local Collection UI, you can also click Collection, then New Local Collection from the menu bar or click the create icon from the Collection toolbar.
I called my collection bredolab (you’ll learn why shortly) and will refer to it hereafter.
Once you create a collection right-click it then connect to it.
You know have two options, capture or import.
Capture
To capture, use the Capture Bar, select the already-created Collection or create a new by collecting the Capture icon first. Once you click the Capture icon NI will capture network data until you click the Capture icon again to halt the process.
Import
Right-click the already-created Collection to add data via the Import Packets options.

Configuring NetWitness Investigator

Select a PCAP file from your local file system, and click Open.

I worked primarily with imported PCAPs, though testing NI’s capture capability proved successful. I did find that in resource-limited virtual environments capturing network traffic with NI causes fairly significant VM grind.
As I was testing NI in the toolsmith lab a golden opportunity to put it though its motions presented itself via the SANS ISC Diary. The Lenovo support site had been discovered to be compromised and propagating the Bredolab Trojan via an embedded IFRAME. As I had literally just been to the Lenovo site to update my laptop BIOS (I had not experienced the malicious behavior) I was pleased with the near real-time relevance and the opportunity to check NI against a new sample. The CyberInsecure article called out the exact malware URL that the IFRAME pointed to (hxxp://volgo-marun.cn/pek/exe.exe) so I grabbed it immediately via my malware sandbox VM. After firing up Wireshark on my VM server, I executed exe.exe (great name) and captured the resulting traffic.  I imported the resulting bredolab.pcap (email me if you’d like a copy) into NI and compared results against details provided in the Lenovo compromise article. While this is a really small PCAP it serves well in exemplifying NI features.

Claim: The malware “receives commands from C&C server with domain sicha-linna8.com”
Validation: Check. Right out of the gate we can see sicha-linna8.com as part of the Collection Navigation view, under Hostname Aliases.

Bredolab sample collection navigation

Left-click the hostname alias result to drill into it.
Right-click it to evoke bonus functionality such as SANS IP History, SamSpade, and CentralOps.
Drilling in the Hostname Alias entry reduces the Service Type findings to just HTTP and DNS traffic which is useful as they are the primary services of interest with this sample. As seen in Figure 2, we can drill further into the single referenced DNS session. The resulting Session view, using the Hybrid option, shows us both a thumbnail view and session details. Further Content options are presented in the lower pane with additional functionality such as, were it relevant, rebuilding instant messaging (IM) and audio, as well as mail and web content reconstruction. The Best Reconstruction option is tidy; it organizes into the three packets for the DNS session represented as the two request packets (as hex) and the response from server.

DNS session content
You can make use of Google Earth as well, if installed. But be sure to default your private IP addresses to your local latitude and longitude. As if we hadn’t already imagined or determined it so, sicha-linna8.com is attributed to the Russian Federation (RU).
Click the Google Earth icon in the Session view.
Satellite imagery does a fair job of bearing that out, although, but unless I’m mistaken Figure 4’s reference pointer looks to be more like China.

Google Earth view of DNS request domain location
Now, I’m just being silly here, but again NI justifies my being so with its capabilities.
As mentioned above, the malware “receives commands from C&C server”. Hmm, that sounds like a bot. Duh, ok Russ, prove it. Navigate back to the Collection summary via the URL window, scroll down to the Querystring reference and click [open]. See, I told you so.

Hello, I’m a bot
That would be the HTTP GET equivalent of calling home to the mothership and requesting mission orders. As if action=bot and action=report weren’t enough for you, the fact that the Filename reference in Figure 5 is also controller.php really help you reach a reasonable conclusion.
By the way, Trend Micro’s Bredolab summary (not specific to this sample) will give a good understanding of its behavioral attributes, but there should be no surprises.

There are endless additional features including the use of breadcrumbs to help you leave a trail as you navigate through large captures, excellent reporting capabilities, as well as the ability export sessions to a file (PCAP, CSV, XML, HTML, etc.) or a new or different collection.
If you click Help, you’ll be offered the 168 page NetWitness Investigator User Guide, which will do this tool far more justice than I have. Consider it required reading before going too far down the rabbit hole on your own.

In Conclusion

There’s much more that I could have covered for you regarding NetWitness Investigator, would time and space have allowed it, but hopefully this effort will get you cracking with this tool if you haven’t already partaken.
NetWitness Investigator is really slick and I’m pleased enough with it to declare it a candidate for the 2010 Toolsmith Tool of the Year to be decided no later than January 2011.
Check it out for yourself and let me know what you think.
Cheers…until next month.

Tuesday, May 01, 2012

toolsmith: Buster Sandbox Anayzer















Prerequisites
Windows
Sandboxie 3.64 or later


Introduction
On April 10th, 2012 a new version of Sandboxie was released, and on April 16th so too was a new version of the Buster Sandbox Analyzer  which uses Sandboxie at its core. Voila! Instant toolsmith fodder.
It’s been a few months since we’ve covered a malware analysis-specific tool so the timing was excellent.
Buster Sandbox Analyzer is intended for use in analysis of process behavior and system changes (file system, registry, ports) during runtime for evaluation as suspicious. You’ll find it listed among the Sandbox Tools for Malware Analysis on one of my favorite Internet resources, Grand Stream Dreams.
As always, I pinged the developer and Pedro Lopez (pseudonym) provided me with a number of insightful details.
He releases new versions of Buster Sandbox Analyzer on a fairly regular basis, version 1.59 is current as I write this. There’s an update mechanism built right into BSA; just click Updates then Check for Updates.  Pedro has recently improved static analysis and he’s always trying to improve dynamic analysis as he considers it the most important aspect of the tool.
For future releases the TO-DO list is short given over two years of constant development.
The following features are planned for:
A feature to analyze URLs in automatic mode.
Utilizing the information stored in the SQL database, a feature to generate statistics including used compressors, detected samples, and others.
Pedro continuously looks for new malware behaviors to include and improvements for the features already implemented. Your feedback is welcome here, readership.

Pedro was first motivated to create the tool thanks in large part to Sandboxie.
“Before I start coding Buster Sandbox Analyzer back in late 2010, I knew of Sandboxie already. I started using this great software around 2008 and had coded other utilities using Sandboxie as a file container so I knew already of the potential to write other types of programs for use with Sandboxie.
I created Buster Sandbox Analyzer because I didn't like that all publicly available malware analyzers were running under Linux. I like Linux based operating systems but I'm mainly a Windows user, so I wanted a malware analysis tool running under Windows. I knew Sandboxie was perfect for this task and with the help of Ronen Tzur (Sandboxie's author) it was possible to do it.”

Pedro cites several favorite use cases but two are stand outs for him:
1. Use the tool to know what files and registry modifications were created by a program. While this use case is not always directly related to malware analysis, it can be used by any user that wants such information regarding program behavior.
2. Use the tool to learn if a file (executable, PDF document, Word document, etc) exhibits malware-specific behavior.
Goes without saying, right?
Pedro reports that Buster Sandbox Analyzer suffers from a lack of user feedback (help change that!).
He’s not really sure how many people have used it to date or how many use it regularly but does recall one success story from a user on the Wilders Security Forums:
"I was shopping on Usenet for some tax software... I found it and ran it in the sandbox. As is my practice, I explored the installed files. Everything worked well. No obvious signs of infection, no writing to Windows, no start/run entries, and no files created in temp folders. But I still wasn't satisfied. I used Buster's program and reran the install...
The program logs were literally laced with created events, DNS queries to Russia, and many hidden processes. Needless to say, I kept it in the sandbox."

One message to convey to you, readers: a few versions ago Pedro introduced multi-language support; there are translations for next Spanish, Russian and Portuguese (Brazil) while a translation to German may be available soon. He would like to have translations for Italian, French, Japanese and Chinese and would be grateful if someone can contribute translations for these languages.
Given the likelihood that this article will be read by security professionals, Pedro welcomes anyone who tries out BSA and has suggestions, ideas, feedback, bugs, etc. to send them to his attention at malware dot collector at gmail dot com.


Configure BSA

Refer to installation and usage documentation on the BSA site as your primary source but you may find the BSA guidance at reboot.pro helpful but a bit dated. Consider it documentation reloaded. Actual installation of both Sandboxie and BSA is really straightforward but there are some configuration tricks worth paying attention to. After reading reboot.pro be sure to add the following to the Sandboxie default configuration file:
InjectDLL=C:\BSA\LOG_API.DLL
OpenWinClass=TFormBSA
NotifyDirectDiskAccess=y
Even more importantly, this assumes you’ve installed BSA in C:\bsa. If you choose differently, you must modify the Sandboxie configuration file accordingly. Avoid the Program Files directories on later versions of Windows given the need for administrative permissions to write there.
I’m a big fan of Windows shell integration with any tool that offers it. Under Options | Program Options | Windows Shell Integration select Add right-click action “Run BSA” and “Analyze in BSA”.
From Options set Common Analysis Options to include saving packet captures under Packet Sniffer via Save Capture To File. Be sure to select the correct adapter here as well. Note: BSA utilizes NetworkMinerConsole.exe for PCAP analysis. :-)
Also set your Report Options from the Options menu. I prefer HTML; you may also select PDF and XML.
You may also like the SQL options where you can write to a SQL database for analysis and report results.
Be sure to check out the additional features under the Utilities menu including submittal to online analyzers, file tools including disassembly, hashing, hex editing, renaming, signature check, scanning, and strings. There are also “explorers” for memory, PCAPs, PE files, processes, and registry hives as seen in Figure 1.

Figure 1: BSA Explorer features

Experiment and fine tune your settings. To then remember settings and load them automatically when the tool starts, select Options | Program Options | Save settings on exit. You can also save multiple configuration files via Options | Program Settings | Save Settings As so as to make use of different analysis patterns.
Lastly, and I imagine you knew I was going to say this, I run BSA in a Windows XP virtual machine and on a bare metal install of Windows 7 running SteadierState . Some malware not only knows when its running in a VM but it knows when it’s running in Sandboxie. If you suspect that’s the case, you can hide Sandboxie during a BSA run via Program Options | Hide Sandboxie.


Using BSA

I wanted to test BSA in two different capacities, one with a browser-borne exploit and one with a “normal” PE.
I am privileged to receive a daily report inclusive of a number of drive-by exploit vehicles so I am always rich in options for exploration, and
hxxp:// www.ugpag.cd/index.php?option=com_content&view=article&id=49&Itemid=75 was no exception.
To examine, I started BSA via bsa.exe in C:\BSA, tuned my BSA configuration to include some additional reporting options, clicked Start Analysis, right-clicked Internet Explorer and chose Run Sandboxed (given that Sandboxie is also integrated right into the Windows shell), and finally browsed to the ugpag.cd site. Once I willingly stepped through a few browser blocks (yes, I’m sure I want to do that),  the “infection” process completed and I chose Terminate All Programs by right-clicking on the system tray Sandboxie icon followed by Finish Analysis in BSA.
A few key elements jumped right out during BSA analysis and findings.
First, the site spawned an instance of Windows Media Player in order to “play” hcp_asx as seen in Figure 2.

Figure 2: Pwned site spawns Media Player for hcp_asx
Second, when reviewing Report.html, I quickly spotted to evil URLs (lukastroy.in & zdravyou.in) under Network services. Also note the Process/window information as seen in Figure 3.

Figure 3: BSA reporting reveals BlackHole URLs
A quick URLquery.net search for the URLs called gave me everything I needed to know.
Yep, BlackHole exploit kit. That was easy.

I used a Banload sample, (MD5: D03BF6AE5654550A8A0863F3A265A412) to validate BSA PE analysis capabilities. As expected, they were robust. The File Disassembler utility immediately discerned that the sample was UPX-packed. Figure 4 points out a number of revealing elements.

Figure 4: BSA API logging reveals Banload behavior
Of interest is the fact that a connection is made to hxxp://alessandrodertolazzi.hospedagemdesites.ws (187.45.240.69) in Brazil and attempts to download mac.rar. Banload/Banker commonly originates from Brazil so this comes as no surprise. This sample is a bit dated so the evilware hosted on Alessandro’s site is long gone, but you get idea. If you optimize your BSA reporting options to include Virustotal results, the Changes to file system section will include all the detections for created files as seen in Figure 5.

Figure 5: BSA reporting provides Virustotal results with created file
The opportunities for exploration are many with Buster Sandbox Analyzer and the fact that it’s free and regularly developed is of huge benefit to our community. Among the features you may find noteworthy and useful are BSA’s ability to BSA is able to automatically analyze a folder in a batch process as well as dump analyzed processes. BSA has moved to the top of my list for sandbox analysis, plain and simple.

In Conclusion

The combined strengths of Sandboxie and Buster Sandbox Analyzer make for a truly powerful combination and invaluable malware analysis platform. No reason for you to get started exploring right away. As always, do be careful playing with live samples and remember to provide feedback to the BSA project, your support is welcome.
Ping me via email if you have questions (russ at holisticinfosec dot org).
Cheers…until next month.

Acknowledgements

Pedro Lopez, lead developer, Buster Sandbox Analyzer






Tuesday, April 03, 2012

toolsmith: Log Parser Lizard









Prerequisites
Windows

Introduction
At RSA Conference 2012 I gave a presentation called Evil Through The Lens of Web Logs. This presentation is built on research I’m conducting for a SANS Gold paper for graduate school and pays particular attention to SQL injection and Remote File Include attacks. One of the tools discussed as very useful for analysis tactics is Log Parser Lizard. You’re probably familiar with Log Parser, but I’ll bet you didn’t there was a great GUI-based tool with which to leverage its raw power with ease. Log Parser Lizard (LPL) is the brainchild of Dimce Kuzmanov, a Macedonian software engineer, who started Lizard Labs in 1998. In 2006 while also working as a part time sysadmin on financial systems, Dimce recognized that he was using Logparser on a daily basis for creating reports, analyzing logs, automatic error reporting, transferring data with txt files, etc. Over time his collection of queries became unmanageable and difficult to maintain so he created LPL for his personal use and because, having benefited from free software himself, wanted to release a useful freeware product to give back to the community. While LPL very successfully harnesses Log Parser’s capabilities Dimce firmly believes that as a great UI it help users learn and organize their queries with less effort. When he added log4net and regex input support the Logparser community really began to embrace LPL. LPL releases are a bit sporadic, usually based on a few new features, bug or code fixes and future releases are planned but not with a known frequency. Today LPL has a user base of about 2000 installations each month based on trend analysis for the last three years and approximately 80000 users worldwide.
The current production release of LPL is 2.1 and features include:
·         Ability to organize queries along with an improved source code editor that includes enhanced source navigation and analysis capability, syntax-highlighting, automatic source code completion, method insight, undo/redo, bookmarks, and more
·         Support for Facebook Query Language (FQL). This feature was introduced to help Facebook developers organize their queries
·         Code snippets (code templates) and constants. Log Parser Lizard also supports “constants” binding to static/shared properties from Microsoft .Net
·         Numerous other user-interface features including advanced grid with filtering and grouping as well as support for charts without requiring a Microsoft Office installation as is a dependcy for  a standalone instance of Logparser
·         Support for printing and exporting results to Excel and PDF documents
o   For registered users ($26.51 USD)
·         Support for inline VB.Net code to create LogParser SQL queries
Inline VB.net support allows you to drop your code between <% and %> marks; it will then be executed and the resulting string will be replaced in the query. Lizard Labs believes this feature will be very useful for LPL users. Before parsing logs you can move-copy-rename files, download via FTP, shutdown IIS, etc. You can also use .Net data types like DateTime for arithmetic operations and/or System.Environment settings in query parameters.

As I write this I’m testing the beta for LPL 2.5 and the new feature set includes:
·         Conditional field formatting (color, font, size, image) to identify required information. As an example, you can set the conditions to change error colors to red, warnings to yellow, etc. or highlight a specific field if it contains a string value of interest
·         Store and organize queries in SQL Server database for ease of use among multiple users and computers in an organization as well as backups, auditing and all other benefits that database storage allows
·         Excel-style row filtering
·         Ability to add columns with Excel style formulas (with most Excel functions) and support for exporting in Excel 2007 format (more than 65365 rows)

What would a toolsmith article be without a tool roadmap so let’s not break a good habit, eh? LPL 3.0 will likely include out of the box queries for IIS web reports (as in other commercial log analysis products), support for query execution scheduling, reports sent via e-mail from LPL, command line support, a query builder tool, text file input format (where a single file is one record and fields can be extracted with RegEx or with Logparser functions), and improved log4net input format. As with most of the tools we discuss, Dimce is certainly open to good ideas for the product and welcomes feedback and ideas from the user community. In total fantasy land the future of LPL may even include queries “in the cloud”, an LPL ASP.net web app that can be installed right on the server, a web service supporting LPL, mobile apps that can use this service, and a global query dictionary that users can submit, comment and rate the queries. “The future’s so bright, I gotta wear shades.” Whoa, 80’s flashback, sorry. 


Using Log Parser Lizard

Installing Log Parser Lizard is so straightforward it doesn’t even warrant a section. Ensure you have Log Parser and .Net 3.5 installed, then execute the LPL installer. Finito.

As described above, I’ve been working on research for a paper which includes analysis of a mass SQL injection attack, well described in detail this past December by Mark Hofman on the SANS Internet Storm Center Diary. In addition to Mark’s analysis, this popular post included many comments and replies from readers who had suffered or noted the attack in their logs and even some helpful folks who submitted log samples. You likely remember the LizaMoon attack and the Lilupophilupop attack was quite similar. In both cases, injected sites offered a URL that then caused redirection to a fake antivirus offering. Specifically, was embedded in victim sites where sl.php bounced you to the likes of hxxp://ift72hbot.rr.nu, the on to rogue AV. I actually had to look up the .rr.nu TLD; it’s the Republic of Moldova, and has been implicated recently in massive SPAM campaigns as well as the current WordPress hacks (as of this writing). 
Figure 1 represents a victim site still exhibiting typical signs of compromise.

Figure 1: Lilupophilupop victim site
 Victim sites were most often running ASP.net apps on IIS with MS-SQL back-ends. It was quickly learned that a few identifying traits of the Lilupophilupop attack included the fact that a rather large hex blob that was evident in IIS logs. I’ve always found that checking logs for 500 errors when analyzing for SQL injection attacks can typically point you down the right path. Using a log file submitted by an ISC reader (anonymized for obvious reasons), I first built a query to seek ASP application errors from a default query included in LPL. I launched LPL, clicked IIS Logs, then ASP App Errors, replaced #IISW3C# in the FROM statement with the path to my anonymized log file, and finally clicked Run Query as seen in Figure 2. Email me if you’d like me send you the log file so you can experiment for yourself.

Figure 2: LPL parsing error messages
Using this query, including FROM D:\logs\lilupophilupop\ex111201anon.log WHERE (sc-status = 500) AND (cs-uri-stem LIKE '%.asp'), prior to being aware of lilupophilupop as a keyword or part of an injected URL, would have immediately narrowed the search vectors.
Also common to attacks of this nature might be a DECLARE statement (defines variable(s)) visible in logs. A query as seen in Figure 3 produced three results that included a DECLARE statement followed by a CAST (converts an expression of one data type to another) statement wherein an attempt to pass the hex blob to the backend was noted.

Figure 3: LPL parsing DECLARE statements
 I clicked one of the results from 78.46.28.97, chose Select All, then Copy, and dropped the content to a text editor. I then grabbed the hex from just after the CAST statement to just prior to the AS VARCHAR statement and copied into a Burp Suite decoder window and chose decode as ascii hex.
Figure 4 shows the converted attack string.

Figure 4: Burp decoder converts hex
Long and short of it, the attack loops through all columns in all tables and updates their value by adding JavaScript to point to hxxp://lilupophilupop.com/sl.php.
This took all of 5 to 10 minutes with LPL and a little experimentation. Yes, you can do all of this with Log Parser at the command line but if you’re looking for strong query management, tidy reporting exports including charts, and downright convenience, LPL is the way to go.

In Conclusion

Log Parser Lizard is one of those indispensable tools that treads lightly on your system but offers a huge bang for the buck. Free or $26? Puhleeze. Keep in mind that while I used an IIS log sample for the article you can throw LPL at generic XML, CSV, TSV and W3C based logs all day long. Download it and put it to good use right away. Dimce would love to hear from you, and I look forward to hearing your success stories.
Ping me via email if you have questions (russ at holisticinfosec dot org).
Cheers…until next month.

Acknowledgements

Dimce Kuzmanov, lead developer and founder, Lizard Labs

Saturday, March 31, 2012

MIR-ROR 2.0 released


MIR-ROR 2.0 has been released as the project has benefited from Jon Mark Allen's (ubahmapk) many contributions, giving MIR-ROR some much needed attention. 
MIR-ROR, or Motile Incident Response - Respond Objectively, Remediate, is a security incident response specialized, command-line script that calls specific Windows Sysinternals tools, as well as some other useful utilities, to provide live capture data for investigation.
You can easily enhance MIR-ROR to your liking with whatever command line tools you find useful. 
For incident response resource, we’ve found it indispensable.
Windows Systinternals licensing prevents us from bundling the tools in a distribution package; you’ll have to retrieve them for yourself. You can download the complete Sysinternals Suite, along with the other utilities needed, and unpack in a preferred directory on your system (C:\tools\MIR-ROR). Check fetch.txt for everything you need to download.
Please feel free to submit suggestions or fixes via Issue Tracker and we'll review potential updates for future releases. 
You can read the complete ISSA Journal article, MIR-ROR: Motile Incident Response - Respond Objectively, Remediate, here.

Sunday, March 11, 2012

More Mayhem with Pwn Plug

In my last post regarding Pwn Plug I discussed the features available to those of you who build your own with a Sheevaplug and Pwn Plug Community Edition.
Here I'll give you an overview of some of the additional pwntastic upside you'll benefit from should you choose to buy Pwn Plug Wireless, 3G, or Elite. Wireless will get you an external 1000mW USB ALFA, 3G offers am O2 E160, and an Elite includes 16GB SDHC card for extra storage (along with all the goodies you get with Wireless & 3G). All commercial versions  include support and the Plug UI which makes setup insanely simple. I configured the Pwn Plug I tested for 802.11 evil with the ALFA as seen in Figure 1.

Figure 1: Pwn Plug Wireless
In the Pwn Plug UI (HTTPS over port 8443 by default) I clicked Basic Setup, then Evil AP Config. Figure 2 shows the AMIEVIL SSID coming to life.

Figure 2: Am I evil?
This is a GUI configuration method for airbase-ng, specifically airbase-ng -P -C 30 -c 3 -e AMIEVIL -v mon0.
Then all you need to do is follow with Karmetasploit via ./msfconsole -r karma.rc and you're off. "Karmetasploit is a great function within Metasploit, allowing you to fake access points, capture passwords, harvest data, and conduct browser attacks against clients."
In addition to all the MSF3 functionality you'd expect you can also utilize David Kennedy's Fast Track. I ran  ./fast-track.py -i, selected 6. Exploits, then 7. mIRC 6.34 Remote Buffer Overflow Exploit. Figure 3 show my Windows XP SP 3 victim coming aboard for pwnzor.

Figure 3: mIRC pwn


With you Pwn Plug firmly established on your target network your recon options are also endless with an 802.11 interface enabled. Figure 4 shows Kismet happily enumerating from the Pwn Plug.

Figure 4: Kismet
So much fun, so little time. For those of you with penetration testing duties that include social engineering and red teaming tactics, I strongly suggest you explore the Pwnie Express site for yourself and the Pwn Plug options and features. You will not be disappointed.



Thursday, March 01, 2012

toolsmith: Pen Testing with Pwn Plug



Prerequisites
4GB SD card (needed for installation)






Dedicated to the memory of Tareq Saade 1983-2012:
This flesh and bone 
Is just the way that we are tied in 
But there's no one home
I grieve for you –Peter Gabriel 

Introduction
As you likely know by now given toolsmith’s position at the back of the ISSA Journal, March’s theme is Advanced Threat Concepts and Cyberwarfare. Well, dear reader, for your pwntastic reading pleasure I have just the topic for you. The Pwn Plug can be considered an advanced threat and useful in tactics that certainly resemble cyberwarfare methodology. Of course, those of us in the penetration testing discipline would only ever use such a device to the benefit of our legally engaged targets.
A half year ago I read about the Pwn Plug when it was offered in partnership with SANS for students taking vLive versions of SEC560: Network Penetration Testing and Ethical Hacking or SEC660: Advanced Penetration Testing, Exploits, and Ethical Hacking. It seemed very intriguing, but I’d already taken the 560 track, and was immersed in other course work. Then a couple of months ago I read that Pwnie Express had released the Pwn Plug Community Edition and was even more intrigued but I had a few things I planned to purchase for the lab before adding a Sheevaplug to the collection.  
But alas, the small world clause kicked in, and Dave Porcello (grep) and Mark Hughes from Pwnie Express, along with Peter LaPlante emailed to ask if I’d like to review a Pwn Plug.
The answer to that which you, dear readers, know to be a rhetorical question goes without saying.
Here’s the caveat. For toolsmith I’ll only discuss offering that are free and/or open source. Pwn Plug Community Edition meets that standard, but the Pwnie Express team provided me with a Pwn Plug Elite for testing. As such, for this article, I will discuss only the features freely available in the CE to anyone who owns a Sheevaplug: “Pwn Plug Community Edition does not include the web-based Plug UI, 3G/GSM support, NAC/802.1x bypass.”
For those of you interested in a review of the remaining features exclusive to commercial versions, I’ll post it to my blog on the heels of this column’s publishing.
Dave provided me with a few insights including the Pwn Plug's most common use cases:
·         Remote, low-cost pen testing: penetration test customers save on travel expenses, service providers save on travel time
·         Penetration tests with a focus on physical security and social engineering
·         Data leakage/exfiltration testing: using a variety of covert channels, the Pwn Plug is able to tunnel through many IDS/IPS solutions and application-aware firewalls undetected
·         Information security training: the Pwn Plug touches on many facets of information security (physical, social & employee awareness, data leakage, etc.), thus making it a comprehensive (and fun!) learning tool

One of Pwnie Express’ favorite success stories comes from Jayson Street (The Forbidden Network) who was hired by a large bank to conduct a physical/social penetration test on ten bank branch offices. Armed with a Pwn Plug and a bit of social engineering finesse, Jayson was able to deploy a Pwn Plug to four out of four branch offices attempted against before the client decided to cut their losses and end the test early. In one instance, a branch manager actually directed Jayson to connect the Pwn Plug underneath his desk. Pwnie Express hopes the Pwn Plug helps illustrate how critical physical security and employee awareness are and Jayson’s efforts delivered exactly that to his enterprise client.
Adrian Crenshaw (Irongeek) has Jayson’s Derbycon 2011 presentation video posted on his site. It’s well worth your time to watch it.

In addition to the Pwn Plug there is also the Pwn Phone which is also capable of full-scale wireless penetration testing. Penetration testers and service providers often utilize the Pwn Phone for proposal meetings and demonstrations as the "wow factor" is high. As with Pwn Plug, if you already own or can acquire a Nokia N900 you can download the community edition of Pwn Phone and get after it right away.

PwnPlug compatibility is currently limited to Sheevaplug devices. There has been little demand so far for the Guruplug/Dreamplug form factors and the Guruplug hardware has a history of overheating while the Dreamplug is quite bulky and flashy. Bulky and flashy do not equate to good resources for physical & social testing. The development team is working on a trimmed down of Pwn Plug for the $25 Pogoplug. Even though it only offers about half the performance and capacity of the Sheeva, with a larger board, it is only $25.

Figure 1 is a picture taken of the Pwn Plug I was sent for testing. You can see what we mean by the importance of form factor. It’s barely bigger that a common wall wart and you can use the included cord or plug it in straight to the wall. Pwnie Express included a couple of sticker options for the Sheeva. I chose what looks to be a very typical bar code and manufacturer sticker that even has a PX part number. I chuckle every time I look at it.

Figure 1: Who, me?
With Sheevaplugs typically sporting a 1.2Ghz ARM processor, 512M SDRAM, and 512M NAND Flash configuration it’s recommended that you don’t treat the device like a work horse (no Fastttack, Autopwn, or password cracking) but it’s crazy good for maintaining access in stealth mode, reconnaissance, sniffing, exploitation, and pivoting off to other victim hosts. Figure you’ll find the 512M storage at about 70% of capacity after installation but adding SD storage means you can add software within reason. Pwn Plug is Ubuntu underneath so apt-get is still your friend.
The tool list for a device this small is impressive. Expect to find MSF3, dsniff, fasttrack, kismet, nikto, ptunnel, scapy and many others at you command, most of which can be called right from the prompt without changing directories.

Installation

To install Pwn Plug CE to a stock Sheevaplug download the JFFS2 and follow the instructions. No need to reinvent the wheel here.

Pwning with PwnPlug

To ensure full understanding for those who may not think in evil mode or conduct penetration testing activity, here’s a quick executive summary followed by the longer play:
Sneak a Pwn Plug into a physical location, plug it in, and properly configured it phones home allowing you reverse shell access via a number of possible stealth modes. You can then set up a variety of exploit activities and/or run scanners or do specific social engineering activity I am about to demonstrate. The results are collected on the device and you can then collect them over the established shell access.

First, imagine the Pwn Plug hidden at the target site, lurking amongst all the other items usually plugged in to a power strip, hiding behind a desk in so innocuous a fashion so as to go easily undetected. Figure 2 will send you scurrying about your workplace to ensure there are none in hiding as we speak.

Figure 2: The Pwn Plug looking so innocent 
I’ll walk through an extremely fun example with Pwn Plug but first you’ll need to ensure access. Commercial Pwn Plug users benefit from the Plug UI but those rolling their own with Pwn Plug CE can still phone home. Have a favorite flavor of reverse shell pwnzorship? Plain old reverse SSH is available or shell over DNS, HTTP, ICMP, SSL, or via 3G if you have the likes of an O2 E160.
The supporting scripts for reverse shell on the Pwn Plug are found in /var/pwnplug/scripts.
On your SSH receiver (Backtrack 5 recommended) I suggest checking out the PwnieScripts for Pwnie Express from Security Generation. @securitygen even has a method for setting up reverse SSH over Tor. I configured the Pwn Plug for HTTP because who doesn’t allow HTTP traffic outbound? J

Figure 3: Have shell, will pwn
Access established, time to pwn. One of my all-time favorite collections of mayhem is the Social Engineer Toolkit (SET). You will find SET at /var/pwnplug/set. Change directories appropriately via your established shell and run ./set.  You will be presented with the SET menu. I chose 2. Website Attack Vectors, then 3. Credential Harvester Attack Method followed by 2. Site Cloner (SET supports both HTTP and HTTPS). In an entirely intentional twist of irony I submitted http://mail.ccnt.com/igenus/login.php to SET as the URL to clone. Mind you, this is not a hack of the actual site being cloned so much as it is harvesting credentials via an extremely accurate replica wherein usernames and passwords are posted back to the Pwn Plug.
The test Pwn Plug was set up in the HolisticInfoSec Lab with an IP address of 192.168.248.23.
Imagine I’ve sent the victim a URL with http://192.168.248.23 hyperlinked as opposed to http://mail.ccnt.com/igenus/login.php and enticed them into clicking. Now don’t blink or you’ll miss it; I froze it for you in Figure 4.
Figure 4: SET harvesting from Pwn Plug
 After passing credentials the victim is then redirected back to the legitimate site none the wiser.
All the while, because you have shell access, you can gather results at your discretion. SET has a nice report generator and writes out to XML or HTML.
This is the tip of the iceberg for SET, and a mere fraction of the chaos you can unleash in whisper quiet mode via Pwn Plug. There are simply too many options to do it much justice in such short word space so as mentioned earlier I’ll continue the conversation on the HolisticInfoSec blog.

In Conclusion

I had a blast testing Pwn Plug, this is me after spending days doing so.


 If you make your living as penetration tester or need a really capable demonstration tool for social engineering awareness and prevention training, Pwn Plug is for you. Grab yourself a Sheevaplug, download Pwn Plug CE and enjoy yourself (with permission)!
Ping me via email if you have questions (russ at holisticinfosec dot org).
Cheers…until next month.

Acknowledgements

Dave Porcello, CEO and Technical Lead, Pwnie Express

Moving blog to HolisticInfoSec.io

toolsmith and HolisticInfoSec have moved. I've decided to consolidate all content on one platform, namely an R markdown blogdown sit...