Posted on Leave a comment

VBA Office Document: Which Version?, (Wed, May 1st)

In some cases, like malicious Word documents without VBA source code, you want to know which version of Office was used to create the VBA macros. Because compiled macros (VBA) don’t run on all versions.

This information can be found inside the _VBA_PROJECT stream:

The 3rd and 4th bytes in this stream are a little endian word, whose value indicates the version of Office that was used to create the VBA code. This is all documented by Microsoft, except for the field values themselves.

Here is a list I compiled for different Office versions (Windows):

Office Version 32-bit 64-bit
2003 0x0079 N/A
2007 0x0085 N/A
2010 0x0097 0x0097
2013 0x00A3 0x00A6
2016 0x00AF 0x00B2
2019 0x00AF 0x00B2

 

 

 

 

 

 

 

If you have other info for other versions, please post a comment or submit a sample.

Didier Stevens
Senior handler
Microsoft MVP
blog.DidierStevens.com DidierStevensLabs.com

(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

Posted on Leave a comment

Introduction to KAPE, (Tue, Apr 30th)

 

In this diary, I will talk about KAPE by SANS Instructor Eric Zimmerman. 

 

What is KAPE?

Kroll Artifact Parser and Extractor (KAPE) is primarily a triage program that will target a device or storage location, find the most forensically relevant artifacts (based on your needs), and parse them within a few minutes.

Because of its speed, KAPE allows investigators to find and prioritize the more critical systems to their case. Additionally, KAPE can be used to collect the most critical artifacts prior to the start of the imaging process.

While the imaging completes, the data generated by KAPE can be reviewed for leads, building timelines, etc.

Install

KAPE can be downloaded from the following link:

https://learn.duffandphelps.com/kape?utm_campaign=2019_cyberitbn-KAPE-launch&utm_source=kroll&utm_medium=referral&utm_term=kape-launch-blog-post

Once you download and unzip KAPE you can find two executables:

One is kape.exe which is the command line version and the other one is gkape.exe which is the GUI version.

Usage

For this diary, I am going to use the GUI version. Like most of forensics acquisition tools, KAPE needs an administrative privilege to do its job.

To collect data first click on the “Use Target Options” checkbox then choose what do you want to collect. In this example, I am going to select the C drive as a target source and I am going to choose the following “EvidenceOfExecution, RegistryHives, and FilSystem. 

This step will just collect the evidence file. To parse these files, you need to choose it from the modules, For this example, I will choose “JLECmd,MFTECmd_$MFT,RegRipper-sam and RegRipper-security “.

Unfortunately, some of the modules do not come by default with KAPE. One of these modules is reg.exe. but that’s not the end of the world, you can just go kapemodules and open the yaml of the specific module. In this example, I am going to open RegRipper-sam.mkape and check which additional module does it need. 

 

Now just follow the instructions in the file. You need to specify the output directory for both Target and Modules.Now back to the gkape and click “Execute”.   Or if you would like to run it from a command line you can just copy the command line version of the same selection from current command line section 

 

 

(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

Posted on Leave a comment

Update about Weblogic CVE-2019-2725 (Exploits Used in the Wild, Patch Status), (Sun, Apr 28th)

Late last week, news emerged about a potential new vulnerability in WebLogic [1]. The vulnerability was first reported to the Chinese National Vulnerability Database (CNVD). A proof of concept exploit labeled “CVE-2018-2628” was made available at the same time. The name of the exploit caused some confusion.  CVE-2018-2628 refers to a WebLogic vulnerability that was fixed last year in Oracle’s April critical patch update.

On Friday, Oracle released a statement clarifying the issue [2]. The vulnerability is new and was not patched by any critical patch update, including the last one released this month. Oracle assigned CVE-2019-2725 to identify this new vulnerability. On Friday, Oracle released a patch for WebLogic 10.3.6. A patch for WebLogic 12.1.3 should be released on Monday (today) April 29th.

We already see active exploits of the vulnerability to install crypto coin miners in our honeypot. The proof of concept exploit released last week allows the trivial install of a shell on a WebLogic server. However, remember that our honeypots are not “special” in the sense that they are only seeing random exploits. We have to assume that at the same time, targeted attacks are underway to wreak more havoc.

[pcap file of some test runs of one of the exploits against a vulnerable server]

If you find a vulnerable server in your environment, assume that it has been compromised. Do not just remove the coin miner. There may have been additional attacks.

CVE-2019-2725 is yet another deserializing vulnerability affecting WebLogic. WebLogic’s design makes it particularly prone to these types of vulnerabilities. Do not expose WebLogic to the Internet if you can help it. I doubt that this was the last such vulnerability.

A quick look at the patch shows that it includes the “validate” function that was added and later enhanced in response to similar flaws. But a quick look didn’t show any obvious additions. NSFocus had a great discussion of this function following prior vulnerabilities [3]. 

On our test server, we only saw logs indicating an attack if the script the attacker attempted to execute failed. For example, in the sample below, the attacker tried to execute “wget”, but “wget” was not installed on the system:

#### <> <[[email protected][app:bea_wls_internal module:bea_wls_internal.war path:/bea_wls_internal spec-version:null]] Servlet failed with IOException
java.io.IOException: Cannot run program "wget": java.io.IOException: error=2, No such file or directory

I will try to update this post on Monday as we learn more.

(thanks to our handler Renato Marino to significantly contribute to this post)

[1] https://isc.sans.edu/forums/diary/Unpatched+Vulnerability+Alert+WebLogic+Zero+Day/24880/
[2] https://www.oracle.com/technetwork/security-advisory/alert-cve-2019-2725-5466295.html
[3] https://blog.nsfocusglobal.com/threats/vulnerability-analysis/technical-analysis-and-solution-of-weblogic-server-wls-component-vulnerability/


Johannes B. Ullrich, Ph.D. , Dean of Research, SANS Technology Institute
Twitter|

(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

Posted on Leave a comment

Quick Tip for Dissecting CVE-2017-11882 Exploits, (Sat, Apr 27th)

In diary entry “Dissecting a CVE-2017-11882 Exploit” I analyze an equation editor exploit. These kind of exploits have become prevalent, I often see malware exploiting this vulnerability.

In my diary entry, I use my tool format-bytes.py to dissect the exploit using a long string of format specifiers. This is not practical if you have to do this often:

That’s why I have now added a library of format strings to my tool format-bytes.py, eqn1 is the format string to use for this exploit:

So in stead of typing “-f “<HIHIIIIIBBBBBBBBBB40s…" ", you can now just type: "-f name=eqn1".

 

Didier Stevens
Senior handler
Microsoft MVP
blog.DidierStevens.com DidierStevensLabs.com

(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

Posted on Leave a comment

Pillaging Passwords from Service Accounts, (Fri, Apr 26th)

In our “pretend pentest” that we’ve been running these last few days, we’ve now got all the domain admins listed, all the service accounts found and listed, and the intersection of those two things – the service accounts that are either local admin or domain admin.
So what’s the obvious next step?  Let’s recover the passwords for those target service accounts!  Because once we have the full credentials, we have admin rights that no SEIM or systems admin will be tracking the use of – these accounts are almost universally ignored, since they login every time those services start (say during a system restart).  So if this is for instance a service account with domain or local admin rights that’s on every server and workstation, you are now “better than domain admin”.  You have all the rights, but no system controls are watching you!

Let’s get on with the job at hand.

First of all, credentials for service accounts are stored in the local registry, as what’s called “LSA Secrets” in the registry key HKEY_LOCAL_MACHINE/Security/Policy/Secrets.  Because the service needs to read the actual password to login as the service account, that password is in the registry in clear-text.  Yup, you read that right – this is why service accounts are such a great target.  LSA Secrets are well protected however, you can’t just fire up regedt32 and read them – only the SYSTEM account has rights.  So you need … yes, some powershell!  Not only that, many of today’s tools are based on some powershell posted way back in the day on microsoft.com!
https://gallery.technet.microsoft.com/scriptcenter/Enable-TSDuplicateToken-6f485980
https://gallery.technet.microsoft.com/scriptcenter/Get-TSLSASecret-9bf94965
(Thanks TrueSec!!  In fact, thanks from all of us! )

Or if you’re not in the mood for PowerShell, you could use some Python tools, or Metasploit or Mimikatz works too – choose your own adventure!  Often you’ll need to try a few different methods, and then maybe wrap one in some “AV evasion” code to make it work for you, but the results are worth it in the end!!

Nishang

Those original scripts from microsoft don’t work on modern hosts with any patches applied at all, but of course there’s a toolkit that’s improved on these scripts over time.  I generally use Nishang for the PowerShell-centric “I’m on the box” approach to LSA Secret recovery
Nishang can run locally on the Windows host being targetted, or you can of course use PSRemoting.  The problem with this tool is that if there’s an AV product in play anywhere in the chain, it will very likely have a problem with you running Nishang.  In fact, even downloading this on a Windows host with a default install (ie – with W10 Windows Defender in play) can be a problem.

Anyway, once it’s installed, the execution if pretty straightforward:

> Import-Module .nishangGatherGet-LSASecret.ps1
> Import-Module ./nishang/Escalation/Enable-DuplicateToken.ps1
> Enable-DuplicateToken
> Get-LSASecret

Name                                Account        Secret                ComputerName
—-                                ——-        ——                ————


_SC_Service Name Being Targeted    .SVCAccount    Passw0rd123           ComputerName

Metasploit

Metasploit of course has a module for this. You can run it locally or (more likely) remotely.  The module is post/windows/gather/lsa_secrets.
Because endpoint protection programs tend to focus so much on Metasploit (which of course tells us just how good this tool is), you need to be careful where and how you run it if the goal is to get this job done with any degree of stealth.  You’ll want to put some up-front work into evading whatever your client has for AV – this work pays off in all kinds of ways if the pentest you’re running is longer than a few days.  This method does a great job though, even though (depending on the module you’re running) it’ll tend to scream at the AV solutions “Look! Look at me! I’m running Metasploit!”
The MetaSploit method is a simple as “run post/windows/gather/lsa_secrets

For me the most attractive thing about using Metasploit is that you can script the exploits.  So if you need to, you can run 4-5-6 exploits against hundreds of machines in one go.

Dumping LSASS

You can dump the LSASS process memory and recover service passwords (and a ton of other stuff too) from that, but that becomes less and less reliable over time as Microsoft puts more fences and protections around LSASS.  I’ve never had to go this way on a real engagement.  The easier method is to run the MimiKatz PowerShell Module and just watch the magic happen.  That is if you put the work into evasion against your endpoint protection solution to allow MimiKatz to run.

Impacket

Impacket makes a great little python based tool to accomplish the same thing.  This is my first, go-to, it almost always works method – mainly because all you run on the target host is standard windows commands, then the rest of the attack is on the attacker’s host.  This makes it the least likely of these methods to trigger any AV alerts or other security measures.

First, from the local host we dump the 3 registry hives that are in play:

reg save hklmsam sam.out

reg save hklmsecurity security.out

reg save hklmsystem system.out

Now take those files and get thee to your Kali VM!   If you don’t have impacket installed yet (it’s not in the default install), there’s no time like the present.  To install:

$ sudo apt-get install python-dev python-pip -y

$ pip install –upgrade pip

$ sudo pip install pycrypto pyasn1 pyOpenSSL ldapdomaindump

$ git clone https://github.com/CoreSecurity/impacket.git

$ cd impacket

$ sudo python setup.py install

(in most cases you don’t need all of those pre-reqs, I put them all in just in case).  Now you’re good to go:

impacket-secretsdump -sam ./sam.out -security ./security.out -system ./system.out LOCAL

(you’ll find a bunch of other interesting security stuff in this tool’s output – all the local account password hashes for one thing!)

At the bottom of the output, you’ll see what we’re looking for, the locally stored password for that service account!!  In this case I put a “fake” account on my SFTP server service (Solarwinds SFTP doesn’t have a service account by default).

That’s it – no fuss, no muss, and best of all, nothing to trigger AV or any similar “endpoint next-gen machine-learning AI user behavioural analysis security” product on the target host.

 

Other tools like CrackMapExec do a good job as well – I haven’t used that one specifically yet, really the impacket method has done the job for me so far.  While I tend to have a “try one or two new things” or “write one new tool” rule for each test, I haven’t gotten around to using any other tools for this particular thing.  

Do you use a different tool to dump service passwords?  Does your tool collect more useful information than just that particular thing?  Or maybe you’ve got a cool AV evasion that relates to this?   Please, use our comment form and share your experiences on this!

=============
Rob VandenBrink
Compugen

(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

Posted on Leave a comment

Service Accounts Redux – Collecting Service Accounts with PowerShell, (Thu, Apr 25th)

Back in 2015 I wrote up a “find the service accounts” story  – https://isc.sans.edu/forums/diary/Windows+Service+Accounts+Why+Theyre+Evil+and+Why+Pentesters+Love+them/20029/ (yes, it really has been that long).  The approach I wrote up then used WMIC.  Those scripts saw a lot of use back in the day, but don’t reflect the fastest or most efficient way to collect this information – I thought today was a good day to cover how to do this much quicker in PowerShell.

Why would you need to do this?  In a penetration test or an internal security assessment, you normally want to enumerate any services that don’t use the built-in Microsoft Service Accounts.  This is because actual service accounts almost never see a password change, and almost always are given local administrator or domain administrator rights.  Mainly because if you’re going to be a software vendor that’s dumb enough to still use Windows XP era service accounts, you might as well go all the way and make those accounts Domain Admin for any malware that wants to collect those passwords (stay tuned, we’ll be doing this tomorrow!).  Microsoft’s current recommended approach is to use the various built-in service accounts for services.  These don’t have passwords, and can’t be used for lateral movement to other workstations or servers.

That being said, let’s pretend to be malware and collect those service accounts across an AD domain!

$targets =get-adcomputer -filter * -Property DNSHostName
$vallist = @()
$i = 1
$count = $targets.count

foreach ($targethost in $targets) {
  write-host $i of $count –  $targethost.DNSHostName
  if (Test-Connection -ComputerName $targethost.DNSHostName -count 2 -Quiet) {
    $vallist += Get-WmiObject Win32_service -Computer $targethost.DNSHostName | select-object systemname, displayname, startname, state
    ++$i
    }
  }
$vallist | export-csv all-services.csv

A few things to discuss.
First of all, $i, $count, and the “write-host” line are there just so that if you have several thousand hosts to enumerate, you can ensure that your script isn’t hung, and how far along it might be at any given time.

The “Test-connection” check is there so that you don’t wait several seconds trying to connect up to remote hosts that might not be up.

Also, this can only enumerate hosts that are actually up and accept a connection – you likely want to run this script during the day.  If you start your script and see that it’s going to take longer than a business day to complete (for a larger domain for instance), you might want to pause it towards the end of the business day, and restart it the next morning after everyone is back at their desks.

OK – so now that the script has run, what have we found?  What we have is the list of all services that are installed on all hosts in the domain, along with the account that’s used to start the service.

This is great for system admins looking for one thing or another, but for most security purposes you don’t want the ones that are using the built-in service accounts.  To filter those out, you want to remove any service that is started by these accounts:

  • NT AUTHORITYLocalService
  • LocalSystem
  • NT AUTHORITYNetworkService
  • or an empty field

To do this, add these lines to the bottom of your script

$filtlist = @(“LocalService”, “LocalSystem”, “NetworkService”, “NT AUTHORITYLocalService”, “NT AUTHORITYNetworkService”, “NT AUTHORITYNETWORK SERVICE”, “NT AUTHORITYLOCAL SERVICE”)
$TargetServices = $vallist | Where-Object { $filtlist -notcontains $_.startname }

$TargetServices | export-csv bad-services.csv

Things to note in this bit of code?  the “contains” and “notcontains” operators are case-insensitive, so you upper / lower case doesn’t matter in your filter.

So, what can we do with this list if we’re attacking a domain?  We can use the domain admin and local admin lists that we sleuthed yesterday, and see which of these service passwords are domain admins!

Let’s take that list of $TargetServices, and list the offending accounts:

$TargetSVCAccounts = $TargetServices.startname | Sort-Object -Unique

ADbiztalkhost
adAppService
ADBizRuleEngine
ADSSOService
ADSQLService
[email protected]

In a different domain it’s common to also see service accounts that are local to the machine being enumerated, often those will have local admin rights, and often you’ll find that those same (local admin) service userid and password are used on all workstations and often on all servers – which gets you almost the same access as domain admin rights (oops).

Normally the lists that come out of these scripts are short enough that I can compare them by eye to the list of local and domain admins we collected in yesterday’s story.  But if you have one of those unfortunate domains where dozens or hundreds of people have domain or local admin rights, you might want to add a bit more code:

$SVCDomAdmins = @()
$Admins = $DomainAdmins.SAMAccountName.toupper()

Foreach ($Acct in $TargetSVCAccounts) {
    $a = $Acct.toUpper().Trim(“AD”).Trim(“@AD.INT”)
    if ($Admins.Contains($a)) {$SVCDomAdmins += $a}
    }

$SVCDomAdmins | Sort-Object -Unique | export-csv Service-DomainAdmins.csv

To find Service Accounts that are local admins, it’s the exact same code, but replace line 2 with “$Admins += $localadmins.AdminID.toupper()

If you have a minute today, try this on your domain – use our comment form to let us know if you find anything interesting!

What will we do with this list of accounts next?  Stay tuned for the next installment tomorrow 🙂

 

===============
Rob VandenBrink
Compugen

(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

Posted on Leave a comment

Unpatched Vulnerability Alert – WebLogic Zero Day, (Thu, Apr 25th)

The news today is full of a new deserialization vulnerability in Oracle WebLogic.  This affects all current versions of the product (the POC is against 10.3, but 12.x versions are also affected).  The vulnerability affects the wls9_async_response package (which is not included by default in all builds), so the workaround is to either ACL the Z/_async/* and /wls-wsat/* paths, or delete wls9_async_response.war.  A successful attack gets the attacker remote code exec on the vulnerable server.

The root cause here seems to be that the affected WAR components ingest and process all serialized data, and have a blacklist of “bad” content.  What this means to me is that we’re likely to see a number of similar vulnerabilities / attacks crop up over the next while, until Oracle changes this approach.

Indications are that this is in the “tens of thousands” of affected sites, not hundreds or thousands or millions (not yet at least).

The vulnerability is posted as CNVD-2018-07811 (China National Vulnerability Database) at http://www.cnvd.org.cn/flaw/show/CNVD-2018-07811.  We don’t have a CVE yet.

This bug was originally disclosed by the China Minsheng Banking Co.  There’s a good write-up by the KnownSec 404 Team with  a bit more detail here: https://medium.com/@knownseczoomeye/knownsec-404-team-oracle-weblogic-deserialization-rce-vulnerability-0day-alert-90dd9a79ae93

This comes just one week after Oracle’s “Patch Everything” Critical Patch Update (CPU) last week.  The next CPU isn’t due for 3 months, so it’ll be interesting to see what the out-of-band response patch or patches (if any) to this might be.

Stay tuned – we’ll udpate this story as we get more information – in particular if we see attacks in the wild we’ll post IoC’s as we get them.

(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

Posted on Leave a comment

Finding Local Administrators on a Domain Member Stations, (Wed, Apr 24th)

Now that we’ve got a list of domain admins ( https://isc.sans.edu/forums/diary/Where+have+all+the+Domain+Admins+gone+Rooting+out+Unwanted+Domain+Administrators/24874 ), lets find all the accounts that have local Administrator rights.
Local Admin used to be a common thing, back in the early XP days when Windows Security was new.  It was common back then to see everyone’s AD account have local admin on their own machine, so that they could do things like update the clock, install printer drivers, or install games when they took their laptop home.

Sound familiar?  Well, those days are gone (or they should be).  In 99% of cases, you absolutely, positively do NOT need local admin for anything on a domain member computer (especially if it’s not a server) that’s administered by IT staff.  You might need an extra right here or there, but even then, it’s very likely that you don’t.  Windows 10 and even Windows 7 both do a good job without giving folks admin rights.  (We won’t talk about that dark Windows 8 detour that nobody took, but W8 does just as good a job on this score)

What local admin does give you is rights that you shouldn’t have, to perhaps install malware that might then access system files that nobody wants changed.  And if you don’t use LAPS, local admin on one station will likely give you local admin on ALL the stations, which from a malware point of view is as good as domain admin in lots of organizations.

So let’s get on with it – to find local admins across the board, you’ll want something that looks like this:

import-module ActiveDirectory

function get-localadmin {
  param ($strcomputer)
  $admins = Gwmi win32_groupuser –computer $strcomputer  
  $admins = $admins |? {$_.groupcomponent –like ‘*”Administrators”‘}
  $admins |% {
    $_.partcomponent –match “.+Domain=(.+),Name=(.+)$” > $nul
    $matches[1].trim(‘”‘) + “” + $matches[2].trim(‘”‘)
  }
}

$i = 1
$localadmins = @()
$targets = Get-ADComputer -Filter * -Property DNSHostName
foreach ($targethost in $targets) {
  write-host “Testing” $targethost.DNSHostName “,” $i “hosts completed”
  if (Test-Connection -ComputerName $targethost.DNSHostName -count 2 -Quiet) {
    $admins = get-localadmin $targethost.DNSHostName
    foreach ($a in $admins) {
      $val = new-object psobject
      $val | add-member -membertype NoteProperty -name Hostname -value $targethost.name
      $val | add-member -membertype NoteProperty -name AdminID -value $a
      $localadmins += $val
      }
  ++$i
  }
}
$localadmins | export-csv -append localadminusers.csv

Note that this code will grab everything, so when it hits the domain controllers it’ll enumerate domain admins (which is the honest truth when you think about it).  Note also that if a station is not on the network when you run this script, of course you won’t be able to enumerate any user information from it.

Run this on your own domain, user our comment form let us know if you find anything unexpected!

===============
Rob VandenBrink
Compugen

(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

Posted on Leave a comment

Where have all the Domain Admins gone? Rooting out Unwanted Domain Administrators, (Wed, Apr 24th)

Ever been in an internal security assessment or penetration test, and need to list all domain admins?
First of all, why would you need to do that?  All to often, you’ll find that way too many people have domain admins – you know, “just in case”
People like:

  • developers – who needed local admin on that one server, that one time, but we gave them domain admin and then forgot
  • or developers, because don’t all devs need domain admin?
  • IT VP’s and dev managers, because they used to be admins
  • the CEO, because they insisted
  • Steve, because Steve needed to update the timezone or install a printer at home, and the helpdesk mistakenly gave Steve domain admin rights for that

You get the idea.

So, aside from the people that are actual members of “Domain Admins”, there are lots of groups that have elevated privileges in a domain, so we’ll need to enumerate all of those too.  And you can put groups into groups, so we’ll have to recurse through that mess to get the full list of users.  This can take quite a while in the GUI, but it’s only a few lines of code in PowerShell:

 

$DomainAdmins = @()
$a = $()
‘Domain Admins’, ‘Administrators’, ‘Enterprise Admins’, ‘Schema Admins’, ‘Server Operators’, ‘Backup Operators’ | ForEach-Object {
    $groupName = $_
    $a = Get-ADGroupMember -Identity $_ -Recursive | Get-ADUser | Select-Object Name, samaccountname, @{n=’GroupName’;e={ $groupName }}
    $DomainAdmins += $a
}
$DomainAdmins | export-csv alldomainadmins.csv

This will list all the Admin users, and the group membership that put them there.  So you might find the same person on this list a few times (but that’s a good thing in most cases).

If you just want the de-dup’d list of unique userids (without how they got there), add this snip to your code:

$uniqadmins = ($DomainAdmins | select SamAccountName,name )  | Sort-Object -Property samaccountname -Unique

$pctdomadmins = ($uniqadmins.count / (Get-ADUser -filter * ).count) *100
write-host $pctdomadmins “percent of domain users have domain admin rights”

$pctdomadmins$uniqadmins | export-csv uniqadmins.csv

When you run this against your domain, what is your percentage?  Did you find any surprises?  Please, use our comment form and let us know!

===============
Rob VandenBrink
Compugen

(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

Posted on Leave a comment

Malicious VBA Office Document Without Source Code, (Tue, Apr 23rd)

A couple of years ago, we posted diary entry “VBA and P-code“: we featured a VBA P-code disassembler developed by Dr. Bontchev. VBA source code is compiled into P-code, which is stored alongside the compressed source code into the ole file with VBA macros.

Dr. Bontchev also published a PoC Word document with VBA code: it contained just the P-code, and no VBA source code. Hence to analyze the document, you could not extract the source code, but you had to disassemble the P-code with pcodedmp.py.

Yesterday, I was pointed towards a malicious Word document found in-the-wild that was hard to analyze. It turned out the VBA source code had been wiped (recently, this method has also been referred to as VBA stomping).

Here’s how I analyzed this document. First, I get this output with oledump.py:

With this output and the context I was given, I can already conclude that this is a malicious document: the recipient received an unexpected .docm file from an unknown sender -> maldoc.

Remark also that stream A3 has no M indicator, while its name (Module1) indicates it should contain VBA code. That’s why I use option -i to get more info:

For every stream with VBA code, option -i will display 2 numbers: the size of the compiled code (P-code) and the size of the compressed VBA source code.

For stream A3, I see that the compressed VBA code is 1280 bytes in size. So why is there no M indicator?

Decompressing the VBA code throws an error:

I take a look at the raw, compressed VBA code (using suffix s for source code):

It has been wiped: the compressed VBA code has been overwritten with 0x00 bytes!

If you were still unsure if this document was malicious or not: now you can cast aside any doubt. Microsoft Office applications do not produce documents like this. This document has been tampered with to try to bypass AV detection.

And if your job is to determine if a document like this is malicious or not, you can report your findings now: this is a maldoc.

But if you need to figure out what this maldoc does, there’s a bit more to analyze.

Using suffix c (compiled), I select all bytes that make up the P-code:

Notices strings Winmgts and Win32_Process (reversed): it looks like this maldoc creates a new process via WMI.

Now I’m using pcodedmp.py to look at the disassembly:

Here is the disassembled P-code. P-code is executed by a stack machine: first arguments are put on the stack, and then functions are called that pop arguments from the stack and push results to the stack.

Here I see a string constant (consisting of digits) assigned to variable E_MO, and then passed as argument to function B_RA, who’s output is used as argument to CreateObject. The result is assigned to variable F_DC. Thus the string is an obfuscated object name, and function B_RA does the deobfuscation.

In the following screenshot, I see a variable (SP_LL) of the Word document (ActiveDocument) that is passed to function B_RA, to be deobfuscated, and then executed (F_DC.Exec).

And here is function B_RA:

It contains a For loop, function Mid is used to select substrings of 3 characters long, which are then converted to an integer and then have 0x1A (26) subtracted from them, to be finally converted to a character. With this information, I can make an educated guess on how to decode the obfuscated string.

But first, I need to find the value of variable SP_LL. Since this is a .docm file, I need to search into XML files contained in a ZIP file. zipdump.py with its YARA functionality is what I need here:

File settings.xml contains variable SP_LL:

With re-search.py and a regular expression to match strings of 10 digits or longer, I extract the value for SP_LL (a long string of digits):

Next I need to break this string up in substrings of 3 digits. I can do this too with re-search.py, and a regular expression for 3 digits:

Now I need to convert these numbers to characters. numbers-to-string.py was designed to do just this. I use option -n 1 to process one number per line (by default, numbers-to-string.py expects at least 3 numbers per line):

This is not yet the decoded string we want: I need to subtract 26 from each number, like this:

Here I recognize cmd.exe … Finally, I use option -j to join all lines into a single line:

And this is a command that launches PowerShell with a downloader script.

 

Didier Stevens
Senior handler
Microsoft MVP
blog.DidierStevens.com DidierStevensLabs.com

(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.