Recovering custom hashes for the Petya/Notpetya malware

During our malware analysis, we often come across samples that contain (custom) hashes in stead of cleartext. Hashing is done in an effort to bypass detection and hinder malware analysts. There are tools to recover cleartext from known hashing methods (like John the Ripper and hashcat). But for custom hashing methods, you’ll have to write some code. In this blog post, we illustrate a method to recover the custom hashes of a non-croptygraphic hashing method used by malware to obfuscate its behavior.

The Petya/Notpetya malware contains code to check which processes are running on a victim machine, and change its behavior accordingly. Microsoft has explained this in detail, with the custom hashing function and hash values to identify processes, however without reporting the process names the malware looks for.

At NVISO, we like to share knowledge and this blog post is no different. We will explain you how we recovered the process names, so that you can use this method in your own malware analysis endeavors.

The names of the processes are not hardcoded in the malware code, but a custom hash function is used to identify the processes of interest:

The custom hash function clears bits in variable v10 if process names that match custom hash values 0x2E214B44, 0x6403527E and 0x651B3005 are found.

A (cryptographic) hash function is not reversible, so we will need to figure out another way to match these hashes with actual process names. Cracking hashes is done with dictionary and brute force attacks: a trial and error method where the hash function is used with input values from the dictionary/brute-force generator until a matching hash is found. Remark that this custom hash function is not a cryptographic hash function and that the hash value is 4 bytes long, so many collisions will be found when brute forcing.

We suspected that the process names of interest are security related: antivirus software, firewalls, … Meterpreter has a killav function that contains a list of process names of security software.  We used this list in our dictionary attack.

Next step is to write a program to perform the attack. Because execution speed could be crucial, we wrote it in C. We took the decompiled custom hash function source code and modified it a bit to be compiled with Visual Studio:

void ConfigCheckProcesses(_TCHAR* processname)
{
unsigned int v0; // ebx@3
unsigned int v1; // kr00_4@3
unsigned int v2; // edx@4
unsigned int v3; // esi@5
char *v4; // ecx@6
char v5; // al@6
int v9; // [esp+230h] [ebp-8h]@3
int v10; // [esp+234h] [ebp-4h]@1

v10 = -1;
v9 = 0x12345678;
v0 = 0;
v1 = _tcslen(processname);
do
{
v2 = 0;
if (v1)
{
v3 = v0;
do
{
v4 = (char *)&v9 + (v3 & 3);
v5 = (*v4 ^ LOBYTE(processname[v2++])) - 1;
++v3;
*v4 = v5;
} while (v2 < v1);
}
++v0;
} while (v0 < 3);
if (v9 == 0x2E214B44)
{
_tprintf_s(TEXT("0x2E214B44: %s\n"), processname);
}
else if (v9 == 0x6403527E)
{
_tprintf_s(TEXT("0x6403527E: %s\n"), processname);
}
else if (v9 == 0x651B3005)
{
_tprintf_s(TEXT("0x651B3005: %s\n"), processname);
}
}

While performing a dictionary attack with our customized hash function and Meterpreter’s list as dictionary, we recovered one hash: 0x2E214B44 is avp.exe (Kaspersky). When we searched Twitter for avp.exe, we found one interesting tweet. We looked at this person other tweets to see if they had recovered the other hashes, unfortunately they did not.

So the next step was to perform a brute-force attack. We generated process names with characters a-z, A-Z (the custom hash function is case sensitive), 0-9 and . – _ and assumed the extension would be .exe.
Here is the result:

Hash 0x651B3005 is NS.exe (Norton Security). That left us with hash 0x6403527E to recover. Since these two hashes are used to clear the same bit, we assumed that the processes might somehow be related. Googling for process names related to NS.exe, we came upon different process names for Norton and Symantec software. A short dictionary attack with these names revealed that 0x6403527E is ccSvcHst.exe (Symantec).

Conclusion

When you have a decompiler available to recover the source code of custom hash functions, one can quickly transform that source code in a working program to perform dictionary attacks and (small) brute force attacks. Larger brute force attacks will require more complex code to speed up the recovery process: multi-threaded code or code that uses GPUs.

To Petya or not to Petya

On June 27, 2017, we were informed via several channels that attackers launched a new type of ransomware. This cyber-attack affects companies across Europe and the US. The attack has some similarities with a previous attack known as “Wannacry”, but it has some distinct features.

The advisory below has been sent out to all our clients on the night of the attack.

The goal of the attack remains the same: Hijacking the system by encrypting files (and the Master Boot Record, rendering the system unusable) and asking for a ransom.

Update: Although the attack is qualified as a ransomware attack, the infected systems are hijacked by encrypting files and the Master Boot Record in exchange for a ransom, the goal of the attack does not seem to be making money, but to destroy as many systems as possible. This due to the fact that the attack itself was sophisticated, but the way the ransom needs to be paid ( 1 bitcoin address for all infections and 1 e-mail address to send a proof of transaction to) is more amateuristic.

Short Description

During our first analysis, we noticed that this attack is using several techniques to spread. When executed, it starts to encrypt files on the local system and attempts to spread across the internal network. The initial attack vectors that are used are under investigation, however; external resources identified and confirmed that the ransomware includes the following exploits:

  • A modified EternalBlue exploit (SMB), also used by WannaCry;
  • The EternalRomance exploit (SMB) – a remote code execution exploit targeting Windows XP to Windows 2008 systems over TCP port 445 (Note: patched with MS17-010);
  • An attack against the update mechanism of a third-party Ukrainian software product called MeDoc.

In comparison with “Wannacry” this could have a greater impact on corporate networks because once an internal host is infected, the ransomware will attempt to further infect internal systems via common Windows administration services (thus possibly also affecting patched systems as a second stage in the attack). As usual with ransomware, the attack is not targeted and is attempting to affect as many systems as possible.

How does the ransomware spread once the initial infection has taken place?
We can confirm that the ransomware is using WMI (Windows Management Instrumentation) and PSEXEC to infect other internal systems once the initial infection has taken place. The sample we analyzed has PSEXEC version 1.98 embedded and uses the Windows API function and ARP scanning to get a list of remote IP addresses of all TCP connections on the infected machine. All addresses it identifies it will then also attempt to infect (using the aforementioned PSEXEC & WMI).

Using WMI & PSEXEC, the ransomware can “ride” on the available user context (e.g. if the ransomware is executed with domain administrator credentials it will be able to affect the entire domain, regardless of patch levels). Provided the malware has the necessary rights, it will drop and execute a password extractor tool based on Mimikatz (stored in resources 1 (32-bit) and 2 (64-bit)) and leverage the extracted credentials for lateral movement with PSEXEC and WMI.

Encryption techniques

Multiple encryption techniques are being used based on the user privilege it has during execution:

  • When executed with administrative rights, the ransomware will encrypt the entire disk and will overwrite the (MBR) Master Boot Record.
  • If the ransomware has normal user privileges it will locate specific file types and will start to encrypt these files on the local system.

After a period of time (1 hour), a scheduled task will force the infected client to restart, thereby presenting the victim with a ransom screen including a bitcoin address together with a string of text as well as the email address to contact the authors when the payment was executed.

Is there a killswitch?

There are currently a few pointers that the ransomware could be halted by by creating a DLL file with a specific name in the C:\Windows. We are currently further investigating this.

Update: Yes! Our analysts found out that the presence of the file c:\windows\perfc will stop the malware from executing. This has been confirmed by Kaspersky and Microsoft.

Detection mechanisms

As opposed to WannaCry, this ransomware is not using command and control channels to communicate to the attacker environment (and thus no random domain names that could be used as kill switches). The detection of infected hosts cannot be done via monitoring outgoing connections because the ransomware does not appear to perform any outbound connectivity.

Detection should be mainly focused on internal monitoring (e.g internal firewall) and looking into the abnormal management traffic that is started via PSEXEC or WMI sessions (e.g. the use of PSEXEC creates a PSEXEC service as an artefact on target systems).

How to defend against this ransomware

In order to defend against this ransomware the following are key recommendations to keep into account:

  • Ensure Microsoft’s patch (MS17-010) is rolled out throughout your organisation (also in the internal network) to prevent the spread of the malware using the SMB exploit;
  • Ensure Windows SMB services (typically TCP port 445) are not directly exposed to the Internet;
  • Review and monitor the internal network on anomalies in management traffic that starts via PSEXEC and WMI;
  • Review internal hosts for the creation of scheduled tasks or the PSEXEC service;
  • Implement network segmentation and restrict access between systems on the internal network. In larger corporate networks, management traffic is only allowed via a dedicated out-of-band network.
  • Upon infection: isolate any infected hosts from the network;
  • Continue end-user awareness to prevent possible initial compromise through phishing (not confirmed);
  • Implement mail sandboxing solutions to block incoming malicious mail attachments.

More information?
More technical blog posts will be released here in the coming days!

Should you require additional support, please don’t hesitate to contact our 24/7 hotline on +32 (0)2 588 43 80 or cert@nviso.be

If you are interested in receiving our advisories via our mailing list, you can subscribe by sending us an e-mail to cert@nviso.be.

A word from our interns Aras, Gaetan and Wouter!

During the first half of 2017 we had the pleasure of working with three bright interns assisting us on various projects ranging from developing an interactive training platform to creating challenges for the Cyber Security Challenge to working on improving our own IT environment.

We asked them to let us know what they thought of their time spent here. Below is the feedback we received!

Interns_Q1_Q2_2017

Posing in front of our beloved blue bird with a great smile! 😊

Gaëtan:
During my internship at NVISO, I assisted the company into deploying and assessing new components in the IT environment. Due to NVISO’s sector of operation, a large emphasis was placed on the security of this environment both in the cloud and on the workstations used to access the services and resources. The aim of this migration was to provide a more unified set of services with increased productivity features while maintaining a strong, secure and controlled environment.

Overall it was a pleasure to work at NVISO during my internship. Working with such a dynamic team was a pleasure, and the overall ambiance and working with like-minded people was a delight.

Aras:
Personally I am proud on doing my internship at NVISO and also with his team that had respect, experience and fun.
During my internship I did two different projects:
1 – creation of the IoT village for the Cyber Security Challenge
2 – Working with open source information databases on connected devices, such as Shodan.

Thank you again guys to all great moment and your patience,

Wouter – Howest:
During my internship I worked on building the back end for an interactive training infrastructure. This infrastructure will help NVISO in improving its trainings, demonstrations and workshops. Building this infrastructure would not have been possible without the support of the NVISO team. I really enjoyed working at NVISO during my internship. The working atmosphere and colleagues are really top notch.

We would like to take this opportunity to thank you all for your commitment and enthusiasm you all brought into the workplace! Hope to see you again soon 🐀!

The entire NVISO team.

Malicious PowerPoint Documents Abusing Mouse Over Actions

A new type of malicious MS Office document has appeared: a PowerPoint document that executes a PowerShell command by hovering over a link with the mouse cursor (this attack does not involve VBA macros).

In this blogpost, we will show how to analyze such documents with free, open-source tools.

As usual in attacks involving malicious MS Office document, the document is delivered via email to the victims.
(MD5 DD8CA064682CCCCD133FFE486E0BC77C)

Using emldump.py (a tool to analyze MIME files), we can analyze the email received by the user:

pp-01

The output indicates that the mail attachment is located in part 5. We select part 5, and perform an HEX/ASCII dump of the first 100 bytes to get an idea which type of file we are dealing with:

pp-02

A file starting with PK is most likely a ZIP file. So let’s dump this file and pipe into zipdump.py (a tool to analyze ZIP files):

pp-03

It is indeed a ZIP file. Judging from the filenames in the ZIP file, we can assume it is a PowerPoint file: .pptx or .ppsx.

Using zipdump and option -E (the -E option provides extra information on the type of the contained files), we can get an idea what type of files are contained in this PowerPoint files by looking at the headers and counting how many files have the same header:

pp-04

So the ZIP files (.pptx or .ppsx) contains 1 JPEG file (JFIF), 11 empty files and 36 XML files.

As said at the beginning, malware authors can abuse the mouseover feature of PowerPoint to launch commands. This can be done with an URL using the ppaction:// protocol to launch a PowerShell command.

To identify if this document abuses this feature, we can use YARA. We defined 2 simple YARA rules to search for the strings “ppaction” and “powershell”:

rule ppaction {
strings:
$a = "ppaction" nocase
condition:
$a
}</p>
<p style="text-align: justify;">rule powershell {
strings:
$a = "powershell" nocase
condition:
$a
}

We use zipdump.py to apply the YARA rules on each file contained in the ZIP file:

pp-05

As shown in the screenshot above, file 19 (ppt/slides/slide1.xml, that’s the first slide of the presentation) contains the string ppaction string, file 21 (ppt/slides/_rels/slide1.xml.rels) contains the string powershell.

Let’s take a look at file 19:

pp-06

We can see that it contains a a:linkMouseOver element with an action to launch a program (ppaction://program). So this document will launch a program when the user hovers with his mouse over a link. Clicking is not required, as is explained here.

The program to be executed can be found with id rId2, but we already suspect that the program is Powershell and is defined in file 21. So let’s take a look:

pp-07

Indeed, as shown in the screenshot above, we have a Target=”powershell… command with Id=”rId2″. Let’s extract and decode this command. First we use re-search.py to extract Target values with a regular expression:

pp-08

This gives us the URL-encoded PowerShell command (and a second Target value, a name for an .xml file, which is not important for this analysis). With translate.py and a bit of Python code, we can use module urllib to decode the URL:

pp-09

Now we can clearly recognize the PowerShell command: it will download and execute a file. The URL is not completely clear yet. It is constructed by concatenating (+) strings and bytes cast to characters ([char] 0x2F) in PowerShell. Byte 0x2F is the ASCII value of the forward slash (/), so let’s use sed to replace this byte cast by the actual character:

pp-10

And we can now “perform the string concatenation” by removing ‘+’ using sed again:

pp-11

We can now clearly see from which URL the file is downloaded, that it is written in the temporary folder with .jse extension and then executed.

To extract the URL, we can use re-search.py again:

pp-12

A .jse file is an encoded JavaScript file. It’s the same encoding as for VBE (encoded VBScript), and can be decoded using this tool.

Conclusion

It’s rather easy to detect potentially malicious PowerPoint files that abuse this feature by looking for string ppaction (this string can be obfuscated). The string powershell is also a good candidate to search for, but note that other programs than PowerShell can be used to perform a malicious action.

Update

We produced a video demonstrating a proof-of-concept PowerPoint document that abuses mouse over actions (we will not release this PoC). This video shows the alerts produced by Microsoft PowerPoint, and also illustrates what happens with documents with a mark-of-web (documents downloaded from the Internet or saved from email attachments).

Sources:
“Zusy” PowerPoint Malware Spreads Without Needing Macros: https://sentinelone.com/blogs/zusy-powerpoint-malware-spreads-without-needing-macros/
Tools used: https://blog.didierstevens.com/didier-stevens-suite/
a:hlinkMouseOver: http://www.datypic.com/sc/ooxml/e-a_hlinkMouseOver-1.html
shp-hyperlink: http://python-pptx.readthedocs.io/en/latest/dev/analysis/shp-hyperlink.html
Sed: https://en.wikipedia.org/wiki/Sed

MoveBot: Battling inactivity one micro-exercise at a time

Many of our NVISO colleagues are very active during their free time. We have colleagues who go mountain-biking, rock climbing, swimming, running, … The problem is that during the day, they often sit at their desk for four hours straight, grab some lunch, and go back to their desk to sit and work at their computers. To make everyone just a little bit more active during the day, we created MoveBot.

MoveBot is a Slack bot that posts messages to our Slack channel twice a day. For example, just this morning, I got the following notification:

Screen Shot 2017-04-14 at 14.45.50

After having done the exercise, I clicked the “I did it” button, and MoveBot congratulated me:

Screen Shot 2017-04-14 at 14.47.20

Of course, a concept like this doesn’t work without some gamification, so every time someone completes an exercise, they get some points. At the end of the month, we give out a little prize to the most active members. You may think that this encourages cheating, but that’s why we had everyone sign a mock contract where they promise to try to live healthy and never ever ever lie to MoveBot ;).

We also use our MoveBot to do some team-building. For example, our set of “exercises” also includes “go get lunch for a colleague” or “during lunch, take a walk around the block with a colleague”.

Sharing is caring, so we’ve pushed the basic code behind our MoveBot to GitHub. Keep in mind that this was a quick project (and my first ever Flask/SQLAlchemy application) so the code isn’t that great, but it does what it’s supposed to do :).

 

Critical Samba vulnerability CVE-2017-7494 – Impact on Belgium

The Samba Team disclosed vulnerability CVE-2017-7494: Remote code execution from a writable share.

HD Moore reported that the vulnerability is simple to exploit: on an open, writable SMB share, a shared library has to be uploaded which can then be easily executed on that server. The Samba Team has released patches and new versions (the vulnerability was introduced in version 3.5.0).

As a Brussels-based company, we are interested to understand what traction this vulnerability can get in the Internet landscape in Belgium. We took our question to Shodan.

  • In Belgium, there are (at the time of writing) 628 Samba servers running with a public IP address scanned by Shodan.
  • 370 of those servers require no authentication.
  • 301 of those servers share disks.
  • 266 of those servers use a vulnerable Samba version (we found no reported versions that include the fix).
  • And finally, 77 of those servers share a disk with read-only property explicitly set to false.

Breaking these down by OS, Shodan reports:

  • 38 Unix servers,
  • 30 Windows 6.1 servers and
  • 9 QTS servers (QNAS OS).

Several of the servers reporting as Windows 6.1 OS look to be honey pots.

If we filter these remaining servers for NAS devices (by looking at the comment of the IPC$ share), we end up with 33 servers.

All in all, a small set of potentially vulnerable devices. This analysis is solely based on Shodan data, we did not execute any scans ourselves.

Post created by:
Didier Stevens
Senior malware analyst @ NVISO

Using binsnitch.py to detect files touched by malware

Yesterday, we released binsnitch.py – a tool you can use to detect unwanted changes to the file sytem. The tool and documentation is available here: https://github.com/NVISO-BE/binsnitch.

Binsnitch can be used to detect silent (unwanted) changes to files on your system. It will scan a given directory recursively for files and keep track of any changes it detects, based on the SHA256 hash of the file. You have the option to either track executable files (based on a static list available in the source code), or all files.

Binsnitch.py can be used for a variety of use cases, including:

  • Use binsnitch.py to create a baseline of trusted files for a workstation (golden image) and use it again later on to automatically generate a list of all modifications made to that system (for example caused by rogue executables installed by users, or dropped malware files). The baseline could also be used for other detection purposes later on (e.g., in a whitelist);
  • Use binsnitch.py to automatically generate hashes of executables (or all files if you are feeling adventurous) in a certain directory (and its subdirectories);
  • Use binsnitch.py during live malware analysis to carefully track which files are touched by malware (this is the topic of this blog post).

In this blog post, we will use binsnitch.py during the analysis of a malware sample (VirusTotal link:
https://virustotal.com/en/file/adb63fa734946d7a7bb7d61c88c133b58a6390a1e1cb045358bfea04f1639d3a/analysis/)

A summary of options available at the time of writing in binsnitchy.py:

usage: binsnitch.py [-h] [-v] [-s] [-a] [-n] [-b] [-w] dir

positional arguments:
  dir               the directory to monitor

optional arguments:
  -h, --help        show this help message and exit
  -v, --verbose     increase output verbosity
  -s, --singlepass  do a single pass over all files
  -a, --all         keep track of all files, not only executables
  -n, --new         alert on new files too, not only on modified files
  -b, --baseline    do not generate alerts (useful to create baseline)
  -w, --wipe        start with a clean db.json and alerts.log file

We are going to use binsnitch.py to detect which files are created or modified by the sample. We start our analysis by creating a “baseline” of all the executable files in the system. We will then execute the malware and run binsnitch.py again to detect changes to disk.

Creating the baseline

Capture.PNG

Command to create the baseline of our entire system.

We only need a single pass of the file system to generate the clean baseline of our system (using the “-s” option). In addition, we are not interested in generating any alerts yet (again: we are merely generating a baseline here!), hence the “-b” option (baseline). Finally, we run with the “-w” argument to start with a clean database file.

After launching the command, binsnitch.py will start hashing all the executable files it discovers, and write the results to a folder called binsnitch_data. This can take a while, especially if you scan an entire drive (“C:/” in this case).

Capture.PNG

Baseline creation in progress … time to fetch some cheese in the meantime! 🐀 🧀

After the command has completed, we check the alerts file in “binsnitch_data/alerts.log”. As we ran with the “-b” command to generate a baseline, we don’t expect to see alerts:

Capture 2.PNG

Baseline successfully created! No alerts in the file, as we expected.

Looks good! The baseline was created in 7 minutes.

We are now ready to launch our malware and let it do its thing (of-course, we do this step in a fully isolated sandbox environment).

Running the malware sample and analyzing changes

Next, we run the malware sample. After that, we canrun binsnitch.py again to check which executable files have been created (or modified):

Capture.PNG

Scanning our system again to detect changes to disk performed by the sample.

We again use the “-s” flag to do a single pass of all executable files on the “C:/” drive. In addition, we also provide the “-n” flag: this ensures we are not only alerted on modified executable files, but also on new files that might have been created since the creation of the baseline. Don’t run using the “-w” flag this time, as this would wipe the baseline results. Optionally, you could also add the “-a” flag, which would track ALL files (not only executable files). If you do so, make sure your baseline is also created using the “-a” flag (otherwise, you will be facing a ton of alerts in the next step!).

Running the command above will again take a few minutes (in our example, it took 2 minutes to rescan the entire “C:/” drive for changes). The resulting alerts file (“binsnitch_data/alerts.log”) looks as following:

Capture.PNG

Bingo! We can clearly spot suspicious behaviour now observing the alerts.log file. 🔥

A few observations based on the above:

  • The malware file itself was detected in “C:/malware”. This is normal of-course, since the malware file itself was not present in our baseline! However, we had to copy it in order to run it;
  • A bunch of new files are detected in the “C:/Program Files(x86)/” folder;
  • More suspicious though are the new executable files created in “C:/Users/admin/AppData/Local/Temp” and the startup folder.

The SHA256 hash of the newly created startup item is readily available in the alerts.log file: 8b030f151c855e24748a08c234cfd518d2bae6ac6075b544d775f93c4c0af2f3

Doing a quick VirusTotal search for this hash results in a clear “hit” confirming our suspicion that this sample is malicious (see below). The filename on VirusTotal also matches the filename of the executable created in the C:/Users/admin/AppData/Local/Temp folder (“A Bastard’s Tale.exe”).

Screen Shot 2017-05-17 at 00.28.05.png

VirusTotal confirms that the dropped file is malicious.

You can also dive deeper into the details of the scan by opening “binsnitch_data/data.json” (warning, this file can grow huge over time, especially when using the “-a” option!):

Capture.PNG

Details on the scanned files. In case a file is modified over time, the different hashes per file will be tracked here, too.

From here on, you would continue your investigation into the behaviour of the sample (network, services, memory, etc.) but this is outside the scope of this blog post.

We hope you find binsnitch.py useful during your own investigations and let us know on github if you have any suggestions for improvements, or if you want to contribute yourself!

Squeak out! 🐁

Daan