WCry/WanaCry ransomware technical analysis

Editor’s Note: Elastic joined forces with Endgame in October 2019, and has migrated some of the Endgame blog content to elastic.co. See Elastic Security to learn more about our integrated security solutions.

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.

endgame-wcry-ransom-note-blog.png

Ransom Note

endgame-wcry-ransom-background-blog.png

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

endgame-wcry-dropper-malware-details-blog.png

Dropped EXE Details

MD5: 84c82835a5d21bbcf75a61706d8ab549

endgame-wcry-dropped-exe-details-blog.png

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.

endgame-wcry-wcry-execution-flow-blog.png

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
    1. 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
    2. 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)
        1. Run thread containing the Payload transfer
        2. endgame-wcry-thread-payload-blog.png
          Setting up the payload
        3. GetAdaptersInfo to get IPs
        4. New thread to propagate the payload
        5. endgame-wcry-propogate-payload-blog.png
          Payload Delivery
          1. Get TCP Socket for Port 445 (Server Message Block/SMB)
          2. Connect to SMB Socket and get SMB tree_id
            1. SMB_COM_NEGOTIATE
            2. Get Tree: ipc_share = "\\\\#{ip}\\IPC$” and SMB_COM_TREE_CONNECT_ANDX
            3. SMB_COM_TRANSACTION
            4. endgame-wcry-metasploit-blog.png
              Example Pseudocode: The screenshot above is from the Metasploit Framework's implementation created after the Shadow Broker's leaks and recent weaponized exploit fromRiskSense-Ops
          3. Run smb ms17-010 Exploit function
            1. do_smb_ms17_010_probe(tree_id)
              1. Setup SMB_TRANS_PKT
            2. If vulnerable, do_smb_doublepulsar_probe(tree_id)
              1. Prepare Base64 Payload in Memory
              2. Setup SMBv1 Echo Packet
              3. make_smb_trans2_doublepulsar
                1. Setup SMB_TRANS2_PKT (See Appendix)
              4. if code == 0x51: Successful payload
            3. Execute Payload Shellcode (See Appendix)
            4. endgame-wcry-code51-blog.png
              If code == 0x51 - successful payload!!!
    3. 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

  1. Extract Zip and Prep Tor and Bitcoin Info:
    1. Extract resource zip file XIA with hardcoded password “WNcry@2ol7”
    2. Get c.wnry, which includes the Tor configuration used by the malware used by the malware
    3. 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:
      1. gx7ekbenv2riucmf.onion;
      2. 57g7spgrzlojinas.onion;
      3. xxlvbrloxvriy2c5.onion;
      4. 76jdd2ir2embyv47.onion;
      5. cwwnhwhlz52maqm7.onion;
      6. hxxps://dist[.]torproject[.]org/torbrowser/6.5.1/tor-win32-0.2.9.10.zip
    4. Load Bitcoin wallets which have been previously set up by the attackers for payment for file restoration and update c.wnry
      1. "13AM4VW2dhxYgXeQepoHkHSQuy6NgaEb94"
      2. "12t9YDPgwueZ9NyMgw519p7AA8isjr6SMw"
      3. "115p7UMMngoj1pMvkpHijcRdfJNXj6LrLn"
  2. Hide Extract Zip Directory and Modify Security Descriptors
    1. Create process: Runs command to hide current directory: "attrib +h . "
    2. 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.
  3. Prep Encryption Public Key, AES Key, Decrypt the DLL
    1. Load exports with getprocaddress: CreateFileW, WriteFile, ReadFile, MoveFileW, MoveFileExW, DeleteFileW, CloseHandle
    2. 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
        1. BOOL WINAPI CryptImportKey(
        2. _In_ HCRYPTPROV hProv,
        3. _In_ BYTE *pbData,
        4. _In_ DWORD dwDataLen, 1172B 2048 bit RSA key (See Appendix)
        5. _In_ HCRYPTKEY hPubKey,
        6. _In_ DWORD dwFlags,
        7. _Out_ HCRYPTKEY *phKey
      4. Parse t.wnry to get AES key used to decrypt the DLL key used to decrypt the DLL
        1. WANACRY! Length 8
        2. Read Length 100h = Encrypted AES Key
        3. Read 4h = 04 00 00 00
        4. Read 8h DLL Length = 00 00 01 00 00 00 00 00
        5. Decrypt Encrypted AES Key with Public Key
        6. Read encrypted DLL length 1000h
        7. Decrypt DLL with custom AES-128-CBC algorithm with 16B AES Key (See Appendix)
      5. Get Native System Info and GetProcessHeap
      6. Put EncryptedData In Heap Location
      7. Change the protection of that memory location.
      8. Encrypted DLL Details
        96de5f0587f7201b9f5f16ba2e374f80
        endgame-wcry-encrypted-dll-details-blog.png
        Spoofed information the decrypted DLL’s VERSIONINFO resource
  4. Run DLL Export at function TaskStart
  5. Creates Encryption Keys to be used by the user file encryption routine
    1. Create Encryption Key by Encrypting the user’’s private key with the ransomware public key and stored in “%08X.eky” (See Appendix)
    2. Also tries to access “%08X.dky” for the received Decryption key
  6. Creates Mutex for all threads: Global\\MsWinZonesCacheCounterMutexW
    1. Other researchers have noted that if this mutex is present, the malware will not start, offering another way to defend against this malware.
  7. Creates a new thread pointing to the setup that starts encrypting files
    1. Generates AES Keys to encrypt files using CryptGenKey

ENCRYPTION ROUTINE

  1. Creates a new thread to overwrite files on disk
    1. Generate a key
    2. Generate Data Buffers for each file
    3. Call thread for function StartAddress to begin writing encrypting file contents
    4. Tack on extension ".WNCRYT”
  2. Run new process taskdl.exe in a new thread
  3. Set Up the Decrypter Persistence:
    1. Read Configuration File
    2. Finds the location of @WanaDecryptor@.exe
    3. Create process "taskse.exe @WanaDecryptor@.exe”
    4. Set persistence key to run itself on reboot HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
    5. CheckTokenMembership, GetComputerName Info
    6. Run: cmd.exe /c reg add "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run” /v "<rand>" /t REG_SZ /d “\"tasksche.exe\"" /f
    7. Looks for “f.wnry" (what this is for is not clear in my analysis)
    8. @WanaDecryptor@.exe Details
      MD5: 7bf2b57f2a205768755c07f238fb32cc
      endgame-wcry-wanadecryptor-blog.png
      SPOOFED INFORMATION THE DECRYPTED DLL’S VERSIONINFO RESOURCE
  4. RUNS: @WANADECRYPTOR@.EXE FI
    1. Reads config file for Tor Client
    2. 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.
  5. Creates @WanaDecryptor@.exe persistence and backup
    1. Creates lnk file @WanaDecryptor@.exe.lnk via batch script
    2.             @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
              
    3. Write to <randominteger>.bat
      1. Execute batch script
      2. Delete: del /a %%0
  6. Creates Ransom Notes @Please_Read_Me@.txt from “r.wnry"
  7. Encrypts files, kills /database and email server-related processes if they are running
    1. Capture UserName
    2. Get Drive Type
    3. Runs:
    4.             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
              
    5. Check Free Disk Space
    6. Loops through files and encrypts (see appendix for the targeted extensions) and encrypts (See Appendix for the targeted extensions)
  8. Runs: @WanaDecryptor@.exe co
    1. Writes to .res file compiled by the time decrypted
    2. Writes to .res file compiled by the time decrypted
    3. Run Tor service: taskhsvc.exe TaskData\Tor\taskhsvc.exe
  9. Runs: cmd.exe /c start /b @WanaDecryptor@.exe vs
    1. 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

endgame-wcry-summary-of-files-blog.png

ZIP FILE (B576ADA...31) CONTENTS

endgame-wcry-zip-file-blog.png

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/tMqnv4c4aUPQV51F77LAnVgVYtPaDybZ3W4BhGByrFNVq/TtwnRM/LiET8eev4/urbkNxJW0dUtYFXxMnniiJ9sqQkwpoxN6Cm6rCggKxGGABYxu8cY2+ZIhe1Q1swZzJATaJyYA3jx2JZ08MsTxhCToCXbhO9YgKn4wKht+R/s2fo6AT0y0wd9HwqNerluVIljcDaWSXBlwnUIyRdmeFOmxqslkSCmHyoe6oJMjksRFt1sz3j0xesFWEgW1gRYQP/N/5J6VSyVsGKKPedAPWx3Jm3L6kHv8glu1RhADMnDZk8oVNzzZg3ciw8ZHbeguD7s/vGdcS2q6G2fkOvgKvePNbSb4MmK+1X9aKTAVIZJxA4Rz5PMTkQggtsriK5gtt35PMNOhIMJNd340usz015GYwrYvnID3gydlsNkt5uWTNvF4kSNSIkBw9F05lDOz7GyvsXMMG1mw52Gx+I59Ar0BhtPux9oLNoSa4jcg4j5QDTvu77Bde3Ub35/vfJSGtNb2bHbUBP06wILcjNnmBKTze4nbX5h+f6i2lxGqqQDANzP5Y6Ykoy9fknHu5UBenMSE7tJHzhKa9ngPK6c3uTSsp+gIP5yyuML2FzC0TgxJT0/NBTvUj1s5fQc2BfDvwSYG47o01PLrsksfuzyRjAfNK9Nnai+LApKV/2o88UBnswjNaj+57WumDepb9lEtpUJrSNNEJYUWWfdgSXqiuesAmpW/W5WSTAxOjKW0DJPfCielGRnKrVNzYx3UPLRMx522IoT6hLb7/25TRvW3jwlXHyvsrYzEXl0KRkyHdUyUdZMmVZNm1ep+jyuIPGWbkBLVNb10zdhzpIHFLIuBVXpFWVJQ8Njv9/qFi0N/TbpWL4ZbOT3x4OCteXxuMk4BabSNvbfcZiPGMPVIb2Ku01KCIDaz7evrCNcSnqVBiSqyYmzDhWTdRDG0odKwR2XA4LDXTuNnxt0+hNDaLKWE5NQBw3nPl1Ry7XrhgtnBJhXllRnqUgdbMEgWEQ0Bt/HdVjkX4PbmHp4nSWSjOFppT3J2Ck62xPLmmLaqdQ+zifcoyL08tXy5YOHcuKxsK+v55WoDhjSNnQP/T05V6FL6TG/jvN8LuyL9ZPJxdJbZE/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

endgame-wcry-extracted-encrypt-twnry-blog.jpg

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

endgame-wcry-other-files-blog.png

STRUCT FOR SMB_TRANS2_PKT

endgame-wcry-smb-trans2-pkt-blog.jpg

SCREENSHOT OF SHELLCODE IN SMB1 TRANS2 PACKET BODY

endgame-wcry-packetbody-blog.png