# CUBA Ransomware Malware Analysis **elastic.co/security-labs/cuba-ransomware-malware-analysis** By Salim Bitam 01 June 2022 ## Summary As a part of Elastic Security’s ongoing threat detection and monitoring efforts, we have recently observed a ransomware intrusion by the CUBA ransomware threat group, internally tracked as REF9019. This report will detail the inner workings of the ransomware deployed inside the network to encrypt the victim’s files. Cuba ransomware provides the attacker with the flexibility to encrypt both local and network shares files in the enterprise. CUBA uses the ChaCha20 cipher algorithm for symmetric encryption and RSA encryption to protect the ChaCha20 keys. CUBA is multithreaded for faster encryption with resource access synchronization to avoid file corruption. In this analysis we will describe the following: Operations mode Process and services termination Enumeration of volumes Threading implementation ----- File encryption and algorithms used MITRE Attack mapping YARA rule Indicators of compromise ### Static Analysis **SHA256 Packed** 0f385cc69a93abeaf84994e7887cb173e889d309a515b55b2205805bdfe468a3 **SHA256 Unpacked** 3654af86dc682e95c811e4fd87ea405b627bca81c656f3a520a4b24bf2de879f **File Size** 135168 bytes **FileType:** Executable **Imphash:** CA5F4AF10ABC885182F3FB9ED425DE65 **Compile Time** Wed Mar 09 22:00:31 2022 | UTC **Entropy** 6.582 ### Sections **Name** **VirtualAddress** **Virtual** **Size** **Raw** **Size** **Entropy** **MD5** .text 0x00401000 0x13B5F 0x13C00 6.608 931B22064E9E214BF59A4E07A6CA9109 .rdata 0x00415000 0xA71C 0xA800 5.855 F6F97411BCD64126A96B08BA9AE1E775 .data 0x00420000 0x16B0 0xC00 3.450 03B1B11B4531BB656E43A8B457D4A5F7 .rsrc 0x00422000 0x1E0 0x200 4.704 F754ADBD7F5D6195FD6D527001CAB98C .reloc 0x00423000 0x1200 0x1200 6.573 08B0994DAECAAAA4173B388A80CC52FE CUBA Campaign Analysis If you're interested in a technical deep-dive on the CUBA campaign, check out our campaign analysis research [here.](https://www.elastic.co/security-labs/cuba-ransomware-campaign-analysis) ### Imports ----- ``` GetProcessImageFileNameW EnumProcesses NetApiBufferFree NetShareEnum GetIpNetTable PathFindFileNameW FindFirstFileExW FindFirstFileW FindNextFileW WriteFile SetFileAttributesW MoveFileExW FindFirstVolumeW TerminateProcess GetEnvironmentStringsW OpenProcess GetCurrentProcessId CreateProcessW GetVolumePathNamesForVolumeNameW FindNextVolumeW GetCurrentThreadId RaiseException GetModuleHandleExW OpenProcessToken CryptAcquireContextA CryptGenRandom CryptReleaseContext AdjustTokenPrivileges LookupPrivilegeValueA ControlService ChangeServiceConfigW PathAddBackslashW GetCPInfo GetOEMCP IsValidCodePage lstrcpynW InterlockedDecrement FindClose CreateFileW Sleep lstrcatW CloseHandle CreateThread lstrcpyW lstrcmpW ReadFile GetFileSizeEx EnterCriticalSection GetCurrentProcess GetModuleFileNameW LeaveCriticalSection GetCommandLineA WaitForSingleObject GetLastError SetEvent GetDiskFreeSpaceExW ResetEvent GetWindowsDirectoryW SetFilePointerEx ExitProcess CreateEventA ``` ----- ``` lstrcmpiW GetTickCount DeleteCriticalSection QueryPerformanceCounter SetStdHandle FreeEnvironmentStringsW GetCommandLineW DecodePointer GetStringTypeW GetProcessHeap FlushFileBuffers GetConsoleCP HeapSize WriteConsoleW InitializeCriticalSection UnhandledExceptionFilter SetUnhandledExceptionFilter IsProcessorFeaturePresent InitializeCriticalSectionAndSpinCount WaitForSingleObjectEx CreateEventW GetModuleHandleW GetProcAddress IsDebuggerPresent GetStartupInfoW GetSystemTimeAsFileTime InitializeSListHead RtlUnwind SetLastError EncodePointer TlsAlloc TlsGetValue TlsSetValue TlsFree FreeLibrary LoadLibraryExW GetFileType GetStdHandle MultiByteToWideChar WideCharToMultiByte GetACP HeapFree HeapAlloc LCMapStringW HeapReAlloc GetConsoleMode CharLowerW GetKeyboardLayoutList wsprintfW CloseServiceHandle OpenSCManagerW OpenServiceW QueryServiceStatusExRead more ### Strings ``` ----- ``` Good day. All your files are encrypted. For decryption contact us. Write here waterstatus@cock.li reserve admin@encryption-support.com jabber cuba_support@exploit.im We also inform that your databases, ftp server and file server were downloaded by us to our servers. If we do not receive a message from you within three days, we regard this as a refusal to negotiate. Check our platform: http://cuba4ikm4jakjgmkezytyawtdgr2xymvy6nvzgw5cglswg3si76icnqd.onion/ * Do not rename encrypted files. * Do not try to decrypt your data using third party software, it may cause permanent data loss. * Do not stop process of encryption, because partial encryption cannot be decrypted. !! READ ME !!.txtRead more ## Code Analysis ### Entry Point ``` The malware starts by retrieving the active input locale identifier of the victim using the GetKeyboardLayout API. When the Russian language is in the list of supported languages of the machine, the process deletes and terminates itself with a simple command line: c:\system32\cmd.exe c/ del PATH_TO_BINARY without encrypting the file system. ### Command-line Options The threat actor included 4 different operations based on the following command-line arguments: The network keyword An IP keyword A path keyword The local keyword ----- **Network keyword parameter** When specifying the network keyword, the malware retrieves the Address Resolution Protocol (ARP) table of the machine using the GetIpNetTable Windows API and enumerates the shares of each IP in the ARP table, this information is added to a linked list that will be accessed by the encryption capability, which will be discussed further below in detail. **IP keyword parameter** By specifying an IP address as the first parameter in the command line the malware proceeds by enumerating and encrypting every share found for the specified IP. ----- **Path keyword parameter** The malware will encrypt the local directory contents, or the file provided, as the first parameter of the command-line. **Local keyword parameter** The local keyword is used to encrypt every local volume on the machine, and because the malware targets volumes by their ID, it can encrypt both mounted and unmounted volumes. ### Process Termination CUBA starts by acquiring SeDebugPrivilege and then terminates a hardcoded list of processes and [services using a common Windows API (see appendix for list [1], [2]). For some services, the malware](https://www.elastic.co/security-labs/cuba-ransomware-malware-analysis#list-of-terminated-processes) first tries to disable the service– indicated by the second parameter of TerminateProcesses::TerminateServiceByName function. This is mainly done to prevent interference with the encryption process by applications that may lock files from external changes, for example, databases. ### Local Volume Enumeration The malware enumerates all the local volumes and for each volume larger than 1GB it saves the volume’s GUID in a custom linked list. The ransomware utilizes the CriticalSection object to access this linked list for synchronization purposes due to multiple threads accessing the same resource. This ----- helps to avoid two threads encrypting the same file at the same time, a race condition that would corrupt the file. ### Multithreaded Encryption Synchronization After preparing a list to encrypt, CUBA ransomware spawns encryption threads with the structure defined below as a parameter. Depending on the command line arguments, the malware starts 4 threads for local encryption or 8 threads for network encryption. ----- When a thread finishes its task, it will decrement a counter until it reaches 0: lpParameter>NumberOfThreadRunning. When the last thread completes, it will alert the program that the task is done with a call to SetEvent API, which will self delete and terminate the malware. ### Encryption Implementation The malware leverages the symmetric encryption algorithm ChaCha20 to encrypt files and the asymmetric encryption algorithm RSA to protect the ChaCha20 Key and Initialization Vector (IV). The [author has utilized a customized version of WolfSSL, an open source SSL/TLS library, to implement](https://github.com/wolfSSL/wolfssl) this capability. Other samples (2957226fc315f71dc22f862065fe376efab9c21d61bbc374dde34d47cde85658) implemented a similar [function using the libtomcrypt library. Other implementations may exist that are not described here.](https://github.com/libtom/libtomcrypt) The ransomware allocates a large custom structure called block that contains all the required [encryption information. It then initializes an RsaKey structure with wc_InitRsaKey and decodes an](https://www.wolfssl.com/doxygen/group__RSA.html#ga02c9b34d405c5f1c24956ee84a843ef6) [embedded 4096 bit RSA public key in DER format using](https://wiki.openssl.org/index.php/DER) [wc_RsaPublicKeyDecode which it saves to](https://www.wolfssl.com/doxygen/group__RSA.html#ga2610326206b322f33f59e31a845e24b9) block.PubRsaKey. ### File Enumeration Each thread takes an entry from the linked list and starts recursively enumerating files starting from the root of the volume. In the case of a specific directory, the same function is called recursively except for [specific directories (see appendix for list). Otherwise, it will ignore the ransom note file !! READ ME](https://www.elastic.co/security-labs/cuba-ransomware-malware-analysis#excluded-directories) [!!.txt and files with specific extensions (see appendix for list).](https://www.elastic.co/security-labs/cuba-ransomware-malware-analysis#excluded-file-extensions) ----- [The malware uses wc_RNG_GenerateBlock a WolfSSL function, to randomly generate 44 bytes. The](https://www.wolfssl.com/doxygen/group__Random.html#ga9a289fb3f58f4a5f7e15c2b5a1b0d7c6) first 32 bytes of that are used as the ChaCha20 key and the other 12 bytes are used as the IV, it then calls a function to initiate the ChaCha20 structure block.chacha20_KeyIv that will be later used to encrypt the file content. At this point, the ransomware is ready to start encrypting and writing to the file. Before encrypting a file, Cuba ransomware prepends a 1024 byte header, the first 256 bytes are the string FIDEL.CA and some DWORD bytes values, the next 512 bytes are the encrypted ChaCha20 KEY/IV with the public RSA key and the rest is padded with 0. ----- Before starting the encryption, the malware double checks if the file was already encrypted by comparing the first 8 bytes of the file to the header string FIDEL.CA. If equal, the malware terminates the encryption process as described below. ----- Then CUBA writes the 1024 byte header and if the file is larger than 2 MB it reads 1 MB of data at a time from the file and encrypts it with the ChaCha20 cipher. Otherwise, it will read and encrypt the entire contents at once. The malware encrypts the file in 1 MB chunks and, depending on the file’s size, it will skip a preset number of bytes. This is done primarily to speed up the encryption process of large files, below is a table to illustrate. File Size Chunk Size Skipped Size Less than 2 MB All the file content 0 MB ----- Less than 10 MB 1MB 4 MB Less than 50 MB 1MB 8 MB Less than 200 MB 1MB 16 MB Less than 10 GB 1MB 200 MB More than 10 GB 1MB 500 MB Finally, it will rename the file by adding the extension .cuba. ## MITRE ATT&CK Techniques Using the MITRE ATT&CK® framework, techniques and sub techniques represent how an adversary achieves a tactical goal by performing an action. [Data Encrypted for Impact](https://attack.mitre.org/techniques/T1486/) [Network Share Discovery](https://attack.mitre.org/techniques/T1135/) [Process Discovery](https://attack.mitre.org/techniques/T1057/) [Service Stop](https://attack.mitre.org/techniques/T1489/) [System Information Discovery](https://attack.mitre.org/techniques/T1082/) [Indicator Removal on Host: File Deletion](https://attack.mitre.org/techniques/T1070/004/) [Obfuscated Files or Information: Software Packing](https://attack.mitre.org/techniques/T1027/002/) [System Network Configuration Discovery](https://attack.mitre.org/techniques/T1016/) [System Location Discovery: System Language Discovery](https://attack.mitre.org/techniques/T1614/001/) [Data Encrypted for Impact](https://attack.mitre.org/techniques/T1486/) [Access Token Manipulation](https://attack.mitre.org/techniques/T1134/) ----- ## Appendix ### List of Terminated Processes sqlagent.exe sqlservr.exe sqlwriter.exe sqlceip.exe msdtc.exe sqlbrowser.exe vmwp.exe vmsp.exe outlook.exe Microsoft.Exchange.Store.Worker.exe ### List of Terminated Services MySQL MySQL80 SQLSERVERAGENT MSSQLSERVER SQLWriter SQLTELEMETRY MSDTC SQLBrowser vmcompute vmms MSExchangeUMCR MSExchangeUM MSExchangeTransportLogSearch MSExchangeTransport MSExchangeThrottling MSExchangeSubmission MSExchangeServiceHost MSExchangeRPC MSExchangeRepl MSExchangePOP3BE MSExchangePop3 MSExchangeNotificationsBroker MSExchangeMailboxReplication MSExchangeMailboxAssistants MSExchangeIS MSExchangeIMAP4BE MSExchangeImap4 MSExchangeHMRecovery MSExchangeHM MSExchangeFrontEndTransport MSExchangeFastSearch ----- MSExchangeEdgeSync MSExchangeDiagnostics MSExchangeDelivery MSExchangeDagMgmt MSExchangeCompliance MSExchangeAntispamUpdate ### Excluded Directories \windows\ \program files\microsoft office\ \program files (x86)\microsoft office\ \program files\avs\ \program files (x86)\avs\ \$recycle.bin\ \boot\ \recovery\ \system volume information\ \msocache\ \users\all users\ \users\default user\ \users\default\ \temp\ \inetcache\ \google\ ### Excluded File Extensions .exe .dll .sys .ini .lnk .vbm .cuba ## YARA Rule Elastic Security has created YARA rules to identify CUBA ransomware activity. ----- ``` rule Windows_Ransomware_Cuba { meta: os = "Windows" arch = "x86" category_type = "Ransomware" family = "Cuba" threat_name = "Windows.Ransomware.Cuba" Reference_sample = "33352a38454cfc247bc7465bf177f5f97d7fd0bd220103d4422c8ec45b4d3d0e" strings: $a1 = { 45 EC 8B F9 8B 45 14 89 45 F0 8D 45 E4 50 8D 45 F8 66 0F 13 } $a2 = { 8B 06 81 38 46 49 44 45 75 ?? 81 78 04 4C 2E 43 41 74 } $b1 = "We also inform that your databases, ftp server and file server were downloaded by us to our servers." ascii fullword $b2 = "Good day. All your files are encrypted. For decryption contact us." ascii fullword $b3 = ".cuba" wide fullword condition: any of ($a*) or all of ($b*) }Read more ## Observations ``` Atomic indicators observed in our investigation. Indicator Type Note 32beefe2c5e28e87357813c0ef91f47b631a3dff4a6235256aa123fc77564346 SHA256 CUBA Ransomware 0f385cc69a93abeaf84994e7887cb173e889d309a515b55b2205805bdfe468a3 SHA256 CUBA Ransomware bcf0f202db47ca671ed6146040795e3c8315b7fb4f886161c675d4ddf5fdd0c4 SHA256 CUBA Ransomware ## Artifacts Artifacts are also available for download in both ECS and STIX format in a combined zip bundle. ## Related content See all top stories ----- ### CUBA Ransomware Campaign Analysis Elastic Security observed a ransomware and extortion campaign leveraging a combination of offensive security tools, LOLBAS, and exploits to deliver the CUBA ransomware malware. ### A peek behind the BPFDoor ----- In this research piece, we explore BPFDoor — a backdoor payload specifically crafted for Linux in order to gain re-entry into a previously or actively compromised target environment. ### Going Coast to Coast - Climbing the Pyramid with the Deimos Implant The Deimos implant was first reported in 2020 and has been in active development; employing advanced analysis countermeasures to frustrate analysis. This post details the campaign TTPs through the malware indicators. -----