NotPetya Technical Analysis

In our Detecting Petya/NotPetya post earlier this week, we described the way in which NotPetya (or “Nyetna” as it has also been named) spreads to other systems on the network without use of the ETERNALBLUE/ETERNALROMANCE SMBv1 exploits. (Although the code contains the ability to spread by this exploit as well, so patching is still imperative).

The malware harvests SMB and user credentials from the infected host and uses those credentials to connect to other systems on the network, propagating the malware. Therefore, it potentially only takes one infected machine in an organization to take down all systems in the network. In this post, we will go more into depth on the functionality and destructive capabilities of NotPetya.

Disk Destruction Overview

Although initially labeled as ransomware due to the ransom message that is displayed after infection, it appears now that NotPetya functions more as a destructive wiper-like tool than actual ransomware.

Initially, analysis showed many similarities with Petya ransomware samples from 2016, but further research indicated the malware had been modified to cause data destruction. NotPetya overwrites sectors of the physical hard drive and C: volume, but does not contain the ability to restore the files, rendering recovery impossible even if the ransom is paid.

Using the Windows API DeviceIoControl, the malware is able to obtain direct read and write access to the physical hard drive, without interaction with the operating system (provided it has the proper administrative permissions).

This allows the code to determine the number of disks and partitions on the system, unmount a mounted volume (even if in use), and determine the drive geometry for the drives on the system (i.e., the number of sectors, bytes per sector, etc.). The malware uses this access to destroy data critical to the operating system. NotPetya also has the ability to replace the OS bootloader with custom code embedded in the binary.

Further details on this wiping capability are discussed in the Analysis section below.

NotPetya “Vaccine” or “Kill Switch”

NotPetya contains a check upon initial execution that attempts to determine whether the victim system has already been infected. It has been stated that creating a file named “perfc” or “perfc.dat” in the root of the hard drive will cause the malware to halt execution, touting this as a “vaccine” or “kill switch” to prevent the spread of the malware.

However, while the original name of the file was “perfc.dat” and so this check will work successfully to prevent execution of this variant, a simple file name change will render this protection useless. As seen in the example screenshots below, writing a “perfc” or “perfc.dat” to the file system will not prevent execution if the name of the DLL is changed (in this case, to “027cc.dll”):

Figure 1: Check for Files named 027cc or 027cc.dll

Figure 1. Check for Files Named “027cc” or “027cc.dll” (Click on images to view larger.)

As the malware checks for the filename matching the name of the running process, a simple redeployment of the tool using a filename other than “perfc.dat” will defeat this protection.

NotPetya Analysis and Techniques

Samples analyzed (SHA-256): 027cc450ef5f8c5f653329641ec1fed91f694e0d229928963b30f6b0d7d3a745 64b0b58a2c030c77fdb2b537b2fcc4af432bc55ffb36599a31d418c7c69e94b1

The analyzed samples of NotPetya are 32-bit Windows DLLs with an original file name of “perfc.dat.” Although the initial infection vector has not been confirmed, there is evidence that the updater process of the Ukrainian tax software MEDoc was responsible for execution of some of the initial infections.

As noted before, although the malware can utilize the SMBv1 exploit to spread to unpatched machines, it also contains other propagation techniques capable of infecting even patched machines. This is critical to note, as means that just one infected system on a network can spread across the enterprise. The methods of propagation discussed below are as follows:

  1. Exploitation of machines vulnerable to the ETERNALBLUE/ETERNALROMANCE SMBv1 exploit
  2. Using harvested credentials from the victim system to infect systems on the network by logging into SMB (any version) shares on the remote system

The malware employs two separate credential harvesting techniques which are discussed in more detail below.

Unlike Windows executables, DLLs such as the NotPetya sample contain “export functions” that are called by external programs to execute functionality. These export functions are contained in a table within the DLL that lists the functions by name and “ordinal” number. For example, below is the export table for perfc.dat:

Export Name Ordinal
perfc.1 1
DIIEntryPoint [main entry]

Table 1: Perfc.dat Export Table

DLLs have a default export function, but in the case of perfc.dat, a call to this function will not execute the malware. Instead, the perfc.1 function must be called by ordinal rather than name, as seen below. Malware often employs this technique to hinder analysis efforts.

C:\Windows\System32\rundll32.exe "C:\Windows\perfc.dat",#1

Upon initial execution, perfc.dat performs a check for the following privileges of the running process:

Privilege Name Description
SeShutdownPrivilege The process has the right to shut down the system.
SeDebugPrivilege The process has debug rights, which allows it to read and modify the memory of processes from other owners.
SeTcbPrivilege This indicates the process is part of the Trusted Computer/Computing Base. Allows for higher privileged access to operating subsystems.

Table 2: Privilege Descriptions ref: Microsoft

The malware sets a global flag that indicates which of these privileges are owned by the process. The privileges granted determine the path of code execution as it relates to the propagation, encryption, and wiping methodologies employed.

After checking for privileges, the malware then enumerates all running processes on the victim, looking for three specific antivirus products: Kaspersky, Symantec, and Norton Security. The executable names are encrypted using a custom XOR algorithm, as seen below and explained in this post from Carbon Black.

Figure 2: Executables Names Encrypted Using a Custom XOR Algorithm

Figure 2. Executables Names Encrypted Using a Custom XOR Algorithm

The result of this check determines the execution path of the malware during propagation to remote systems. The results from both the privilege check and the AV check are stored in bitmasked global variables for reference throughout the program. Below are the enumerated variables resulting from the privilege check:

Granted Privileges Global Flag Value
SeShutdownPrivilege 0x1
SeDebugPrivilege 0x2
SeShutdownPrivilege and SeDebugPrivilege 0x3
SeTcbPrivilege 0x4
SeTcbPrivilege and SeShutdownPrivilege 0x5
SeTcbPrivilege and SeDebugPrivilege 0x6
SeShutdownPrivilege and SeDebugPrivilege and SeTcbPrivilege 0x7

Table 3: Enumerated Variables from Privilege Check

The flags indicating whether Kaspersky, Symantec, or Norton are running are as follows (as can be seen in the screenshot above):

Antivirus Product Global Flag Value
None 0xFF
Kaspersky 0xF7
Symantec OR Norton 0xFB
Kaspersky AND Symantec OR Norton 0xF3

Table 4: Antivirus Indicated

After this flag value is set, the malware can determine which antivirus is installed by performing a bitwise AND operation on the flag with a constant. This method of “bitmasking” allows the malware to store multiple values in a single variable. For more information on this technique and how it is used by NotPetya, see the “Bitmasking” section at the end of this post.

The malware then checks privileges and performs the following if SeDebugPrivilege is granted:

  • Checks for the existence of “perfc.dat” on the system
    • If the file exists, the malware exists (see “NotPetya Vaccine or Kill Switch” section above)
    • If not, the malware copies itself onto the victim’s hard drive
  • Opens a handle to the raw logical volume \.\C:
    • Retrieves the drive geometry (bytes per sector, number of sectors, etc.)
    • Overwrites sectors at the beginning of the volume
    • Checks to see if Kaspersky flag is set and attempts to overwrite the MBR with a custom bootloader
      • If Kaspersky is not running and the MBR overwrite fails, the malware obtains a handle to the first physical drive (\.\PhysicalDrive0) and again retrieves the geometry
      • It then forcibly dismounts the volume and overwrites sectors on the drive

After the above actions have been attempted, NotPetya creates a task to perform a shutdown after a calculated amount of time as follows:

  • If the process has all three privileges described above and the OS version is Vista/2008/7 or greater, a scheduled task will be created and configured to run under the “SYSTEM” account, as seen in the highlighted parameter below. This parameter is omitted if the malware does not have the appropriate permissions. The scheduled time indicated by and is calculated from manipulation of the current system time.
  cmd.exe /c schtasks /RU "SYSTEM" /Create /SC once /TN "" /TR "shutdown.exe /r /f" /ST <HOUR>:<MINUTES>
  
  • If the system is running an older version of Windows (such as XP), the malware uses the built-in “AT” command to schedule the shutdown using the following command:
  cmd.exe /c at <HOUR>:<MINUTES> "shutdown.exe /r /f"
  

Next the malware creates a thread to gather network information about the victim and if DHCP is enabled, attempts to enumerate all subnets and subnet clients defined on the DHCP server. The malware attempts to connect to each host, testing SMB ports 445 and 139 for write access using select(). Network information for each host with these ports open is then enumerated and saved.

If the malware has SeDebugPrivilege, it proceeds to extract files from its resource section. The embedded resources are compressed using the zlib 1.2.8 library.

Resource Name Description
1 32-bit credential harvesting binary
2 64-bit credential harvesting binary
3 PsExec tool for remote process execution
4 XOR encrypted Shellcode (key 0x86, unknown functionality at time of analysis)

Table 5: Description of Embedded Resources

Depending on the system architecture, either the 32- or 64-bit version of the credential harvester is inflated and written to a pseudo-randomly named file in %TEMP%. NotPetya then creates a named pipe and executes the temp file, using the pipe to retrieve credentials from the harvester. These credential harvester binaries have been reported as modified versions of the tool “mimikatz,” although this has not been verified as of the time this report was written.

As discussed in our previous post (link), in addition to harvesting credentials using the embedded harvester program, NotPetya also enumerates credentials using the CredEnumerateW() Windows API, saving only those credentials of type 2 (SMB).

Resource 3 is a copy of the Windows Sysinternals tool PsExec, which is used to execute commands on a system remotely. This file is inflated and written to %WinDir%\dllhost.dat. When infecting remote systems, NotPetya uses this tool to execute the malware on the remote system with the following command:

psexec -accepteula -s -d c:\windows\system32\rundll32.exe "C:\Windows\<filename>\,#1"

If the malware is running with at least SeTcbPrivilege, NotPetya will create a thread that attempts to connect to the \\admin$ share of all known hosts on the network with the previously stolen credentials. If connection is successful, the malware checks to see if the host is already infected (identified by the malicious binary resident in %WinDir%), copying itself to the host if the file does not exist. The malware then infects the system either using PsExec as shown above, or using the built-in Windows Management Instrumentation Command-line tool (WMIC) as follows:

c:\windows\system32\wbem\wmic.exe /node:"<node>" /user:"<user>" /password:"<password>" process call create "C:\Windows\System32\rundll32.exe "C:\Windows\<file>\" #1

After infecting systems on the local network, the malware proceeds to perform encryption on all files with the following extensions:

 .3ds .7z .accdb .ai .asp .aspx .avhd .back .bak .c .cfg .conf .cpp .cs .ctl .dbf .disk .djvu .doc .docx .dwg .eml .fdb .gz .h .hdd .kdbx .mail .mdb .msg .nrg .ora .ost .ova .ovf .pdf .php .pmf .ppt .pptx .pst .pvi .py .pyc .rar .rtf .sln .sql .tar .vbox .vbs .vcb .vdi .vfd .vmc .vmdk .vmsd .vmx .vsdx .vsv .work .xls .xlsx .xvd .zip

Depending on the AV flag, NotPetya takes different execution paths at this point. If none of the three AV products are running, the malware executes the full encryption and MBR wiping functionality and performs anti-forensics techniques of clearing event logs and deleting the USN journal (which is used to track file changes on NTFS volumes). The command below clears all entries in the Setup, System, Security, Application logs, and then deletes the USN journal on the C:\ drive:

wevtutil cl Setup & wevtutil cl System & wevtutil cl Security & wevtutil cl Application & fsutil usn deletejournal /D %c:  

If Kaspersky is running, however, the malware takes an alternate path in which the anti-forensics techniques are not performed. Furthermore, the following function that overwrites the initial sectors of the physical drive is also not called if Kaspersky is running.

Figure 3: Function that Overwrites the Initial Sectors of the Physical Drive are Not Called if Kaspersky is Running

Figure 3. Function that Overwrites the Initial Sectors of the Physical Drive are Not Called if Kaspersky is Running

Interestingly, static analysis also suggests that the ETERNALBLUE/ETERNALROMANCE SMBv1 exploitation techniques are only performed if Kaspersky is running. Reference to the code that generates the SMBv1 payloads was not found outside of the Kaspersky-specific code during the course of analysis. Further review is necessary to determine the comprehensive differences in these two code paths.

At this point in execution, if the malware has not already rebooted the system, it makes two more attempts using Windows API calls. First, the API InitiateSystemShutdownExW() is called with parameters to “ForceAppsClosed” and “RebootAfterShutdown” enabled. If this fails, a call to ExitWindowsEx() is made with the same parameter options, and the process exits.

Bitmasking

“Bitmasking” allows the malware to store multiple values in a single variable. The malware can determine which AV is installed by performing a bitwise AND operation on the stored flag value with a constant. For example, the following highlighted code checks to see if Kaspersky is running before proceeding with the main wiping and encryption functionality:

Figure 4: Highlighted Code Checks to see if Kaspersky is Running

Figure 4. Highlighted Code Checks to See if Kaspersky is Running

The bitmasking works as follows: an AND operation is carried out on each bit of the flag (0xF7) and constant (0x4). The AND operation returns 1 if the bits match, and 0 if they do not, as seen in the following example:

Flag 0xF7 1 1 1 1 0 1 1 1
Constant 0x4 0 0 0 0 0 1 0 0
Operation 0xF7 & 0x4 = 0x4 0 0 0 0 0 1 0 0

The result of the operation highlighted above is therefore the value 0x4. This method provides an efficient way to keep track of data globally.

Recommendations

As with most malware mitigations, regular system backups and patch management are the most useful measures in preventing widespread damage from an incident. Maintaining good security measures such as password complexity enforcement, security product maintenance, and limiting user privileges also helps to mitigate attacks such as NotPetya, even if it doesn’t prevent them entirely. Below are additional measures that can be taken that are specific to NotPetya:

  • Due to the capability to spread internally over SMB, it is important that any users with administrative access on the domain keep up to date on software patches as they come available, and minimize their footprint on the network.
  • NotPetya still contains functionality to spread via the ETERNALBLUE SMBv1 exploit, so it is still imperative to patch the vulnerability fixed in security update MS17-10 as soon as possible.
  • Employing a tool that can monitor and verify the integrity of the MBR on the system can prevent its destruction.

Please reference the Detecting Petya/NotPetya post to access AI Engine rules to help you detect NotPetya.

Acknowledgements

Thanks to LogRhythm Labs team members Nathanial Quist, and Andrew Costis for their continued work analyzing and reporting on Petya / NotPetya threat research.

Detecting Petya/NotPetya Ransomware

A Technical Analysis of WannaCry Ransomware

WannaCry Ransomware