WCry/WanaCry Ransomware Technical Analysis

As we discussed Friday when this outbreak began, the WCry or WanaCrypt0r ransomware spread quickly across Europe and Asia, impacting almost 100 countries and disrupting or closing 45 hospitals in the UK. As the ransomware continued to propagate, I got my hands on a sample and quickly began analyzing the malware. This post will walk through my findings and provide a technical overview of the strain of WCry ransomware which caused the massive impact on Friday.  Many have done great work analyzing this malware in action and helping contain its spread, and I hope my comprehensive static analysis will provide a good overall picture of this particular ransomware variant on top of that.

 

The Note

With estimates over 100,000 computers impacted globally thus far, many people received unwelcome notes Friday similar to those below demanding a fee to decrypt their files. Notes like these are unfortunately all too common and typical of today’s ransomware.  While the notes promise to return the data, it’s not guaranteed that paying the ransom will return data safe and sound, but if it gets this far and adequate backups are not in place, it may be the only recourse the victim has.  No one ever wants to see one of these.

 

Ransom Note

 

Ransom Note Desktop Background

 

 

Where to Begin?

There has been a lot of discussion about the method of propagation and the overall impact of this ransomware, but what does this ransomware actually do from start to finish?  That is the question I’ll answer in this post.

To begin, we accessed the malware by grabbing it (SHA256 24d004a104d4d54034dbcffc2a4b19a11f39008a575aa614ea04703480b1022c/MD5 Db349b97c37d22f5ea1d1841e3c89eb4 ) from VirusTotal. See the appendix  for a  summary of the files dropped with the malware.

 

Dropper Malware Details

MD5: Db349b97c37d22f5ea1d1841e3c89eb4 

 

Dropped EXE Details

MD5: 84c82835a5d21bbcf75a61706d8ab549

 

The WCry Execution Flow

The WCry ransomware follows a flow similar to that of other ransomware as it damages a machine.  The high level flow is as follows:  It begins with an initial beacon, other researchers have already reported is basically a killswitch function.  If it makes it past that step, then it looks to exploit the ETERNALBLUE/MS17-010 vulnerability and propagate to other hosts.  WCry then goes to work doing damage to the system, first laying the foundations for doing the damage and getting paid for recovery, and once that’s done, WCry starts encrypting files on the system.  See the diagram below for an overview of how this malware works.  I’ll walk through each of these steps in more detail below.  

 

As the graphic illustrates, the malware inflicts damage by executing a series of tasks. I’ll walk through each of these tasks, which are numbered below. Each first level of the outline corresponds to that step in the execution flow graphic.

 

Initial infection and propagation

1. Beacon to hxxp://www[.]iuqerfsodp9ifjaposdfjhgosurijfaewrwergwea[.]com. Successful connection will cause the malware to quit.  Note that other researchers have reported seeing strains since Friday which have an alternate killswitch URL.  

2. Run the resource Exe as a new service

    a. If Command line args as “-m security”

        1. OpenSCmanager

        2. Create a new service called "Microsoft Security Center (2.0) Service”; “mssecsvc2.0"  as mssecsvc.exe

        3. StartService

        4. Load Resource “tasksche.exe”

        5. Save as C:\\WINDOWS\\tasksche.exe

        6. Move C:\\WINDOWS\\tasksche.exe to C:\\WINDOWS\\qeriuwjhrf

    b. Else Propagate via SMB ETERNAL BLUE / DOUBLE PULSAR Exploit

        1. OpenSCManager

        2. Access service “mssecsvc2.0"

        3. Change Service Config

        4. Start Service Crtl Dispatcher (Run SMB Exploit)

            a. Run thread containing the Payload transfer

 

Setting up the payload

            b. GetAdaptersInfo to get IPs

            c. New thread to propagate the payload

 

Payload Delivery

                1. Get TCP Socket for Port 445 (Server Message Block/SMB)
                2. Connect to SMB Socket and get SMB tree_id

                    a. SMB_COM_NEGOTIATE
                    b. Get Tree: ipc_share = "\\\\#{ip}\\IPC$” and SMB_COM_TREE_CONNECT_ANDX
                    c. SMB_COM_TRANSACTION

Example Pseudocode: The screenshot above is from the Metasploit Framework's implementation created after the Shadow Broker's leaks and recent weaponized exploit from RiskSense-Ops.

                3. Run smb ms17-010 Exploit function
                    a. do_smb_ms17_010_probe(tree_id)

                        1. Setup SMB_TRANS_PKT

                    b. If vulnerable, do_smb_doublepulsar_probe(tree_id)
                        1. Prepare Base64 Payload in Memory
                        2. Setup SMBv1 Echo Packet
                        3. make_smb_trans2_doublepulsar

                            a. Setup SMB_TRANS2_PKT (See Appendix)
                        4. if code == 0x51: Successful payload
                    c. Execute Payload Shellcode (See Appendix)


If code == 0x51 - successful payload!!!

 

    c. After Service execution

        1. Gets the computer name
        2. Randomizes string
        3. Get command line args and Checks for switch “/i”

 

Preparation for Ransomware Activity

3. Extract ZIp and Prep Tor and Bitcoin Info:

    a. Extract resource zip file XIA with hardcoded password “WNcry@2ol7”
    b. Get c.wnry, which includes the Tor configuration used by the malware used by the malware
    c. Extract the configuration from c.wnry to get the Tor browser and onion sites to be used for communication and onion sites to be used for communication:

gx7ekbenv2riucmf.onion;

57g7spgrzlojinas.onion;

xxlvbrloxvriy2c5.onion;

76jdd2ir2embyv47.onion;

cwwnhwhlz52maqm7.onion;

hxxps://dist[.]torproject[.]org/torbrowser/6.5.1/tor-win32-0.2.9.10.zip

    d. Load Bitcoin wallets which have been previously set up by the attackers for payment for file restoration and update c.wnry

“13AM4VW2dhxYgXeQepoHkHSQuy6NgaEb94”

“12t9YDPgwueZ9NyMgw519p7AA8isjr6SMw"

“115p7UMMngoj1pMvkpHijcRdfJNXj6LrLn"

4. Hide Extract Zip Directory and Modify Security Descriptors

    a. Create process: Runs command to hide current directory: "attrib +h . “
    b. Runs command: icacls . /grant Everyone:F /T /C /Q.  This grants all users full access to files in the current directory and all directories below.

5. Prep Encryption Public Key, AES Key, Decrypt the DLL

    a. Load exports with getprocaddress: CreateFileW, WriteFile, ReadFile, MoveFileW, MoveFileExW, DeleteFileW, CloseHandle
    b. Set up Encryption Keys

        1. SetUp Cypto function exports: CryptGenKey, CryptDecrypt, CryptEncrypt, CryptDestroyKey, CryptImportKey, CryptAcquireContextA
        2. Get RSA_AES Cryptographic Provider
        3. CryptImportKey import the hard coded public key


BOOL WINAPI CryptImportKey(

 _In_  HCRYPTPROV hProv,

 _In_  BYTE *pbData,

 _In_  DWORD dwDataLen, 1172B 2048 bit RSA key (See Appendix)

 _In_  HCRYPTKEY  hPubKey,

 _In_  DWORD dwFlags,

 _Out_ HCRYPTKEY  *phKey

);

        3. Parse t.wnry to get AES key used to decrypt the DLL key used to decrypt the DLL
            a. WANACRY! Length 8
            b. Read Length 100h = Encrypted AES Key
            c. Read 4h = 04 00 00 00
            d. Read 8h DLL Length = 00 00 01 00 00 00 00 00
            e. Decrypt Encrypted AES Key with Public Key
            f. Read encrypted DLL length 1000h
            g. Decrypt DLL with custom AES-128-CBC algorithm with 16B AES Key (See Appendix)
        4. Get Native System Info and GetProcessHeap

        5. Put EncryptedData In Heap Location
        6. Change the protection of that memory location.

 

Encrypted DLL Details

96de5f0587f7201b9f5f16ba2e374f80

Spoofed information the decrypted DLL’s VERSIONINFO resource

 

6. Run DLL Export at function TaskStart

7. Creates Encryption Keys to be used by the user file encryption routine

a. Create Encryption Key by Encrypting the user’’s private key with the ransomware public key and stored in  “%08X.eky” (See Appendix)
b. Also tries to access “%08X.dky” for the received Decryption key

8. Creates Mutex for all threads: Global\\MsWinZonesCacheCounterMutexW

a. Other researchers have noted that if this mutex is present, the malware will not start, offering another way to defend against this malware.

9. Creates a new thread pointing to the setup that starts encrypting files

a. Generates AES Keys to encrypt files using CryptGenKey

 

Encryption routine

10. Creates a new thread to overwrite files on disk

a. Generate a key
b. Generate Data Buffers for each file
c. Call thread for function StartAddress to begin writing encrypting file contents
d. Tack on extension ".WNCRYT”

11. Run new process taskdl.exe in a new thread

12. Set Up the Decrypter Persistence:

a. Read Configuration File
b. Finds the location of @WanaDecryptor@.exe
c. Create process "taskse.exe @WanaDecryptor@.exe”
d. Set persistence key to run itself on reboot HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
e. CheckTokenMembership, GetComputerName Info
f. Run: cmd.exe /c reg add "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run” /v "<rand>" /t REG_SZ /d “\"tasksche.exe\"" /f
g. Looks for “f.wnry" (what this is for is not clear in my analysis)

 

@WanaDecryptor@.exe Details

MD5: 7bf2b57f2a205768755c07f238fb32cc

 

 

Spoofed information the decrypted DLL’s VERSIONINFO resource 

13. Runs: @WanaDecryptor@.exe fi

a. Reads config file for Tor Client
b. Runs Tor Client.  Note that I did not drill into the communications deeply during this analysis.  It’s basically connecting to the .onion sites listed above to allow for user payment and tracking. 

14. Creates @WanaDecryptor@.exe persistence and backup

a. Creates lnk file @WanaDecryptor@.exe.lnk via batch script


@echo off
echo SET ow = WScript.CreateObject("WScript.Shell")> m.vbs
echo SET om = ow.CreateShortcut(“@WanaDecryptor@.exe.lnk")>> m.vbs
echo om.TargetPath = "@WanaDecryptor@.exe">> m.vbs
echo om.Save>> m.vbs
cscript.exe  //nologo m.vbs
del m.vbs

b. Write to <randominteger>.bat

1. Execute batch script
2. Delete: del /a %%0

15. Creates Ransom Notes @Please_Read_Me@.txt from “r.wnry"
16. Encrypts files, kills /database and email server-related processes if they are running

a. Capture UserName
b. Get Drive Type
c. Runs:

taskkill.exe /f /im Microsoft.Exchange.*

taskkill.exe /f /im MSExchange*

taskkill.exe /f /im sqlserver.exe

taskkill.exe /f /im sqlwriter.exe

taskkill.exe /f /im mysqld.exe

d. Check Free Disk Space
e. Loops through files and encrypts (see appendix for the targeted extensions) and encrypts (See Appendix for the targeted extensions)

17. Runs: @WanaDecryptor@.exe co

a. Writes to .res file compiled by the time decrypted

b. Writes to .res file compiled by the time decrypted

c. Run Tor service: taskhsvc.exe TaskData\Tor\taskhsvc.exe

18. Runs: cmd.exe /c start /b @WanaDecryptor@.exe vs

a. Deletes the volume shadow copies with the command: Cmd.exe /c vssadmin delete shadows /all /quiet & wmic shadowcopy delete &  bcdedit /set {default} bootstatuspolicy ignoreallfailures & bcdedit /set {default} recoveryenabled no & wbadmin delete catalog -quiet with the command: Cmd.exe /c vssadmin delete shadows /all /quiet & wmic shadowcopy delete &  bcdedit /set {default} bootstatuspolicy ignoreallfailures & bcdedit /set {default} recoveryenabled no & wbadmin delete catalog -quiet

 

Conclusion

Despite its ability to propagate so quickly, the ransomware activities taken by this malware are not particularly interesting or novel.  As I demonstrated in this malware, the killswitch in the execution flow provided a unique opportunity to slow down the ransomware. As security researcher MalwareTech discovered, and Talos described in detail, this malware was programmed to bail out upon a successful connection to that server, which stops the malware altogether.  We should all thank MalwareTech for setting up the sinkhole, which caused this outbreak to slow sooner than it otherwise would have.  

This malware is easy to modify.  As mentioned above, other researchers are already finding variants in the wild.  If you’re running Windows and haven’t patched yet, now’s the time to do it. And while you’re at it, go test your backups to build some confidence that you won’t be forced to choose between paying up or losing data should the worst happen to you or your organization.

 

Appendix

 

Summary of Files

Zip File (b576ada...31) Contents

 

Extensions to encrypt

.doc,.docx,.docb,.docm,.dot,.dotm,.dotx,.xls,.xlsx,.xlsm,.xlsb,.xlw,.xlt,.xlm,.xlc,.xltx,.xltm,.ppt,.pptx,.pptm,.pot,.pps,.ppsm,.ppsx,.ppam,.potx,.potm,.pst,.ost,.msg,.eml,.edb,.vsd,.vsdx,.txt,.csv,.rtf,.123,.wks,.wk1,.pdf,.dwg,.onetoc2,.snt,.hwp,.602,.sxi,.sti,.sldx,.sldm,.sldm,.vdi,.vmdk,.vmx,.gpg,.aes,.ARC,.PAQ,.bz2,.tbk,.bak,.tar,.tgz,.gz,.7z,.rar,.zip,.backup,.iso,.vcd,.jpeg,.jpg,.bmp,.png,.gif,.raw,.cgm,.tif,.tiff,.nef,.psd,.ai,.svg,.djvu,.m4u,.m3u,.mid,.wma,.flv,.3g2,.mkv,.3gp,.mp4,.mov,.avi,.asf,.mpeg,.vob,.mpg,.wmv,.fla,.swf,.wav,.mp3,.sh,.class,.jar,.java,.rb,.asp,.php,.jsp,.brd,.sch,.dch,.dip,.pl,.vb,.vbs,.ps1,.bat,.cmd,.js,.asm,.h,.pas,.cpp,.c,.cs,.suo,.sln,.ldf,.mdf,.ibd,.myi,.myd,.frm,.odb,.dbf,.db,.mdb,.accdb,.sql,.sqlitedb,.sqlite3,.asc,.lay6,.lay,.mml,.sxm,.otg,.odg,.uop,.std,.sxd,.otp,.odp,.wb2,.slk,.dif,.stc,.sxc,.ots,.ods,.3dm,.max,.3ds,.uot,.stw,.sxw,.ott,.odt,.pem,.p12,.csr,.crt,.key,.pfx,.der 

Public RSA2 Key to Decrypt AES Key (Converted to Base64 for Display)

BwIAAACkAABSU0EyAAgAAAEAAQBDK00rBJwK2Z8e2l/tMqnv4c4aUPQV51F77LAnVgVYtPaDybZ3W4B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N8LuyL9ZPJxdJbZE/2ub6bT9WYW68ToBBfE+Yg1/H+KBl2ZjkCC7lrTPRMd8fn0lLjE1iyoYq9JByTKqS8rvKB2/KpwcNgJrAg+n7RDAoNrPCXJZW8Y8+RV/qiIAcuClXHkGbmI1M4lWq1/x/ZNiToEePfwFaaQvURviyA6mhqK/naScs9yJs+Ow8Ndg1mzeaR7JsAKFltc1hjYWW+YF4fkL7SWA4AoExZZdNGxM8ODHt4qQPJiiepLqUekF7H08yc2qtmaz20jPfftt3QS5G5eevuFYZv3pcKz5/7YjF/3wNQxBOjiaLz8WKuipczB8OMnEfsZopHj+bQAoTjOH5bbJxT3sDpID6xWbOHO/D8F7WolR8Zdx9dXKRJ+H5901bcAfzVuTwQAO8aklyPboi8c=

  

AES Decrypted Key for Decrypting the DLL

BE E1 9B 98 D2 E5 B1 22 11 CE 21 1E EC B1 3D E6

 

Extracting Encrypted AES Key and Encrypted DLL from t.wrny

 

Hard Coded Public Key to Encrypt User Private Key (Converted to Base64 for Display)

BgIAAACkAABSU0ExAAgAAAEAAQB1l0w7hEbeLCr0lahdwM1t2tfUkh4TgjRqcI2PfPcEklV/8aInsp5BrJCAkRiTwrF7rSvz/6/bK1G+HaMn46dXCFq+wR32BPgcvluxZ/vkyNp1AHCxF3AkbAljdKxLCh1xrn+uZbjFhnnFfp+YYExSuSliyyMp7TGRdHt7CyYb8n1nv9p6QNryYU2UpX2tWWutnqM6OcZbbp/Suza19dJl9Sww2MEXva8oAJYgRqctYgMM19B1oAsH6tQfyujZTts48iZ1yxKmiHCb4eoy3PhxclBB5heBaCdCjt/l3qFy2Tv75Z0wEWmSzWAr4tVGPCjPnTBK9625+w+R/i6+GPHO

Dll Decrypt Private Key (Converted to Base64 for Display)

BgIAAACkAABSU0ExAAgAAAEAAQBDK00rBJwK2Z8e2l/tMqnv4c4aUPQV51F77LAnVgVYtPaDybZ3W4BhGByrFNVq/TtwnRM/LiET8eev4/urbkNxJW0dUtYFXxMnniiJ9sqQkwpoxN6Cm6rCggKxGGABYxu8cY2+ZIhe1Q1swZzJATaJyYA3jx2JZ08MsTxhCToCXbhO9YgKn4wKht+R/s2fo6AT0y0wd9HwqNerluVIljcDaWSXBlwnUIyRdmeFOmxqslkSCmHyoe6oJMjksRFt1sz3j0xesFWEgW1gRYQP/N/5J6VSyVsGKKPedAPWx3Jm3L6kHv8glu1RhADMnDZk8oVNzzZg3ciw8ZHbeguD7s/v

 

Other Files

 

Struct for SMB_TRANS2_PKT

 

Screenshot of Shellcode in SMB1 Trans2 Packet Body