# LockBit Ransomware Analysis Notes **[amgedwageh.medium.com/lockbit-ransomware-analysis-notes-93a542fc8511](https://amgedwageh.medium.com/lockbit-ransomware-analysis-notes-93a542fc8511)** Amged Wageh August 17, 2021 [Amged Wageh](https://amgedwageh.medium.com/?source=post_page-----93a542fc8511--------------------------------) Aug 17, 2021 14 min read LockBit is a relatively new family of ransomware that has been discovered for the first time in 2019, and since then, it keeps evolving in both the social and the technical aspects to keep up with the modern ransomware, for example, in the newest versions, the ransom-note contains a threat to the victims to leak their private data if the victim just restored his data from a backup and didn’t pay the ransom, they explicitly reminds them with the GDPR as a direct way of extortion, as for the technical aspect, they started using multi-threading to enhance the performance of the malware and some other technical details that will be described in this story . So, let’s take a closer look at a sample that have been recently published. ## Sample Info. ``` 5761ee98b1c2fea31b5408516a8929ea 4d043df23e55088bfc04c14dfb9ddb329a703cc1 0a937d4fe8aa6cb947b95841c490d73e452a3cafcd92645afc353006786aba76 0x5E4A2B92 (Sun Feb 16 21:58:42 2020) ``` NOTE: This is the final payload so, we’ll directly dive into the real nefarious stuff of the malware. ## A Quick Look By having a very quick look at the sample to get an idea of what kind of binary we’ll be dealing with, it appears that the the section names are very normal, the entropy are a little high for the `.text and the` `.rdata sections but not that high, which indicates that most` probably this binary is not packed however, it applies some obfuscation techniques. ----- The Sections Entropy ## A Quick Behavioral Analysis NOTE: I usually give the binary any arbitrary name because I don’t know yet what kind of anti-analysis techniques are being applied so, “lockbit.exe” and “anghami.exe” are the same binary. — just so you don’t be confused if you’ve noticed that in that screenshots below. By having a quick look at the process tree of the malware, we can see a bunch of ``` dllhost.exe executions with CLSIDs of COM objects that are known to be vulnerable to ``` UAC bypassing, one of them spawns the `lockbit.exe process.` ----- UAC Bypassing Also, we can easily notice that it tries to inhibit the system recovery by deleting the shadow copy, deleting the windows backup catalog, and modifying the boot configuration to disable windows automatic recovery features. The Process Tree Neglecting the fact that we already know that we’re dealing with a ransomware, that behavior is a quick give away that most probably this is the case. We can also see that, for some reason, it tries to scan the network by sending a tons of ARP requests to the entire network. Network Scanning And it will try to connect via port 445 (SMB) ----- SMB Connection Regarding the Registry, we’ll notice a huge amount of activities that are related to registry access and modification, but the ones that we’re most interested in are the following keys, ``` SOFTWARE\LockBit SOFTWARE\LockBit\full SOFTWARE\LockBit\Public HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\XO1XADpO01 ``` Registry Modification Finally, the background will be changed and all the files will be encrypted and has the ``` .lockbit extension. ``` ----- Changing The Background And of course, the ransom-note will be dropped. Dropping The Ransom-Note ## Analysis Notes ----- After performing a full static analysis to the sample and adding meaningful names to the variables and functions, adding few comments to the important sections of code, deobfuscating the strings, and validating the results with a full behavioral analysis, here is some interesting snippets from the malware that could help us understanding the behavior of it and build detection for it. ## Anti Debugging The malware checks the `NtGlobalFlag which exists in the` `PEB (Process Environment` Block) at offset `0x68 to know whether or no the process is being debugged. It performs a` ``` TEST to check the value of the flag, if it equals 0x70 (which means the process is being ``` debugged), the execution will be transferred to a block of code that exists the process. Anti Debugging Also, The malware has multiple calls to `Sleep with high number of seconds, this usually` being done to avoid being automatically analyzed inside a free sandbox, as most of the free sandboxes limit the amount of execution time to a limited number of minutes. ## Token Impersonation The malware will try to impersonate the token of the logged on user via the physical console by firstly getting session identifier of the console session by calling ``` WTSGetActiveConsoleSessionId then it will pass that sessionId to WTSQueryUserToken to obtain the primary access token of the logged user, if it fails to get ``` the token, it will create the process with the current security context by calling ``` CreateProcessW however, if it manages to get the user’s access token, it will duplicate the ``` token by calling `DuplicateTokenEx then it will use the duplicate token to create the new` process using `CreateProcessAsUserW .` ----- Token Impersonation Usually malware use this technique for two reasons: 1. if the impersonated user has a higher privilege. 2. to bypass access controls. ## String Obfuscation This sample has all of its strings encrypted via a simple `XOR encryption with a unique key` for each string, each encrypted sequence of bytes will have the fist byte as the key. The malware first loads the encrypted strings onto the stack then, it runs the decryption loop. This loop is being noticed in almost all the functions. ----- XOR Decryption Here is a very simple python function I wrote to help me decrypting the strings. This function takes the hex values as a string then it will decrypt it. ``` import binasciidef xor_decrypt(data): data = binascii.unhexlify(data) key = data[0] result = '' for byte in data: result += chr(byte ^ key)return result ## Debugging Messages ``` This malware does something very cool which is printing what seems to be debugging messages to a hidden console window. For the malware to be stealthier as much as it could be, all the strings are obfuscated using the same `XOR encryption algorithm we discussed,` after de-obfuscating all the strings and tracking them, analyzing the sample has became much easier. ----- Printing Debugging Messages ## Generating And Storing the Decryption Keys The malware uses two algorithms for the encryption which are RSA and AES. ----- Firstly, The malware will generate an RSA session key pair then, it will encrypt the private key using a hard-coded public key then, it stores the encrypted key in the ``` SOFTWARE\LockBit\full registry key and the public key will be stored in SOFTWARE\LockBit\Public ``` Creating The SOFTWARE\LockBit Reg. Key The malware will randomly generate a new AES key for each file. Once it’s being used for encrypting the file, the AES key will be encrypted using the RSA public session key and appended to the end of the encrypted file. The debugging messages that we mentioned earlier have made it easy to detect the function that will generate the session keys as the deobfuscated string says “ Generating session keys”! ----- Session Keys Generation The following snippets show the keys storing and querying. ----- Querying The Keys For generating the random numbers, LockBit will use `LoadLibraryA and` ``` GetProcAddress to dynamically load bcrypt.dll for importing the BCryptGenRandom ``` API for generating 32 bytes of random numbers, and if it couldn’t load the necessary libraries, it’ll call `CryptAcquireContextW and` `CryptGenRandom to get the job done.` Generating Random Numbers ## Utilizing IOCP (Completion I/O ports) As we mentioned earlier, LockBit has been technically evolved, one of the technical aspects is using the [Windows I/O Completion ports mechanism for providing an efficient threading](https://docs.microsoft.com/en-us/windows/win32/fileio/i-o-completion-ports#:~:text=I%2FO%20completion%20ports%20provide,is%20to%20service%20these%20requests.) model for processing multiple asynchronous I/O requests on a multiprocessor system. ----- Creating Completion I/O Ports The malware has each function of its behavior separated in a subroutine, it creates an I/O completion port by calling `CreateIoCompletionPort then, it will enter a loop to create a` bunch of threads by calling either one of the undocumented and more stealthier following APIs `NtCreateThreadEx or` `RtlCreateUserThread and it will set the entry point of each` thread to one of the subroutines. After that, `NtSetInformationThread will be called for` setting the thread priority for each created thread. ----- Threads Creation ## Privilege Escalation Firstly, LockBit checks its privileges by getting the process token by calling ``` NtOpenProcessToken then, it queries that token via NtQueryInformationToken after ``` that, it creates a user security identifier (SID) that matches the administrator group by passing `WinBuiltinAdministratorsSid to` `CreateWellKnownSid . Finally, it calls` ``` CheckTokenMembership to check whether the current process privileges include the ``` Administrator privileges or not. ----- Checking Privileges [If it doesn’t include the Administrator privileges, LockBit will perform a UAC bypassing by](https://docs.microsoft.com/en-us/windows/security/identity-protection/user-account-control/how-user-account-control-works) [calling a windows COM objects that can auto-elevate, and for masquerading, LockBit](https://docs.microsoft.com/en-us/windows/win32/com/the-component-object-model#:~:text=A%20COM%20object%20is%20one,an%20interface%20are%20called%20methods.) implements a publicly available function called `supMasqueradeProcess which allows the` malware to conceal its process information by injecting into a process that runs in a trusted directory, it choose `explorer.exe to be its target.` ----- ``` supMasqueradeProcess Implementation ``` ----- For the actual UAC bypassing, LockBit will call `CoGetObject with the following CLSIDs:` ``` {3E5FC7F9–9A51–4367–9063-A120244FBEC7} {D2E7041B-2927–42fb-8E9F-7CE93B6DC937} ``` Calling CoGetObject ----- Querying The CLSIDs and Creating The dllhost.exe procsses ## Killing Processes LockBit calls `CreateToolhelp32Snapshot for getting a snapshot of the running processes` then, it uses `Process32First and` `Process32Next to enumerate the snapshot. For each` process, it’ll compare its name against a list of a process, and if it matches, it well pass the process handle that it got by calling `OpenProcess to` `TerminateProcess to terminate the` process. The list of the processes was also encrypted using `XOR .` ----- Process Termination ----- Process Names After Being Decrypted In Memory **And here is a list of the process that will be terminated if exists:** ``` wxServerwxServerViewsqlmangrRAguisuperviseCultureDefwatchwinwordQBW32QBDBMgrqbupdateax CloudAdobe Desktop ServiceCoreSyncAdobe CEF HelpernodeAdobeIPCBrokersynctaskbarsyncworkerInputPersonalizationAdobeCollabSyncBrCtrlCntrBrCcUxSysSimplyConnectionManagerSim exp-engineserviceTeamViewer_ServiceTeamViewertv_w32tv_x64TitanVSsmsnotepadRdrCEForacleocssddbsnm ## Stopping Services ``` LockBit has a list of services that will try to stop by calling `OpenSCManagerA to establish a` connection to the service control manager on the local computer then, it loops over a list of predefined services passing each service to `OpenServiceA to` check the existent of that service, if the service exists, it’ll check its status by calling ``` QueryServiceStatusEx and it will call ControlService with the parameter 0x00000001: SERVICE_CONTROL_STOP to stop the service. In order to not cause any crashes to the ``` system, LockBit will stop all the dependent services by calling `EnumDependentServicesA` before stopping the target service. Those services are mostly backup services, anti-virus services, and other services that may lock some files due to having handles to them. ----- Stopping Some Services ----- Services Names After Being Decrypted In Memory **Here is a list of the services that LockBit tries to stop:** ``` wrapperDefWatchccEvtMgrccSetMgrSavRoamSqlservrsqlagentsqladhlpCulserverRTVscansqlbrows usbarbitator64vmwareconverterdbsrv12dbeng8MSSQL$MICROSOFT##WIDMSSQL$VEEAMSQL2012SQLAgent$VEEAMSQL2012SQLBr ExchangeMSSQL$MICROSOFT##SSEEMSSQL$SBSMONITORINGMSSQL$SHAREPOINTMSSQLFDLauncher$SBSMON ## Excluding Files And Directories ``` To avoid any system crashes and to make sure that the system has functional browsers for connection and negotiation, besides avoiding entering an infinite loop of encrypting the already encrypted files and not to encrypt the ransom-notes, LockBit has a list of files, folders, and extensions exclusions. ----- A List Of Exclusions **Here is the list of exclusions:** ``` windowsintelrecycle.bintor browserwindowsntmsbuildmicrosoftall userssystem volume informationperflogsgoogleappdatamozillamicrosoft .netmicrosoft sharedinternet explorercommon filesopera intelwindows journalntldrntuser.dat.logbootsec.bakautorun.infthumbs.dbiconcahce.dbrestore-myfiles.txt.386.cmd.ani.adv.theme.msi.msp.com.diagpkg.nls.diagcab.lock.mpa.cpl.mod.hta.i ## Mutex Creation ``` ----- For avoiding multiple infection on the same host, LockBit creates the following mutex ``` Global\{BEF590BE-11A6–442A-A85B-656C1081E04C} . Firstly, it will try to open that mutex ``` by calling `OpenMutexA, if it succeeds, which means that host is already infected, it will exit` the process, otherwise, it’ll call `CreateMutexA for creating the mutex then, it’ll proceed with` the rest of the malware functionality. Mutex Creation ## Persistence In order to maintain a persistence and to service reboots, LockBit creates the following registry key ``` HKCU\SOFTWARE\Microsoft\Windows\CurrentVaersion\Run\XO1XADpO01 with a value of ``` ----- it s path on disk. Maintaining Persistence After Decrypting The Key In Memory ----- ## Shutdown Prevention In order to ensure that the encryption operation didn’t get disrupted even by shutting the system down, LockBit will create a shutdown block reason by calling ``` ShutdownBlockReasonCreate . ``` Creating Shutdown Block Reason ## Netwrok Enumeration ----- In order to ensure infecting as many victims as possible, LockBit scans the attached drivers and network shares and when it finds files that meets its previously discussed requirements, it’ll also encrypt those files. LockBit starts this function by calling `GetLogicalDrives to git a bitmask representing the` currently available disk drivers then, it loops over them and passed them to ``` GetDriveTypeW to determine the type of the driver whether it is a removable, fixed, CD ``` ROM, RAM disk, or network drive, it specifically looking for `0x4: DRIVE_REMOTE . Once it` finds a networked drive, it calls `WNetGetConnectionW to retrieve the name of that network` resource, then it will do a recursive calls to `WNetOpenEnumW and` `WNetEnumResourceW` enumerate the folders and files of that network resource. Network Enumeration LockBit can also access the network shares that require user credentials by calling ``` WNetAddConnection2W with lpUserName=0 and lpPassword=0 which automatically ``` sends the username and password of the currently logged in user. ----- Connecting Over SMB Connecting To Shares With Creds. ## The Ransom Note While LockBit is performing the encryption, it will drop a text file called `Restore-My-` ``` Files.txt which is the ransom-note. All your important files are encrypted!Any attempts to restore your files with the thrid-party software will be fatal for your files!RESTORE YOU DATA POSIBLE ONLY BUYING private key from us.There is only one way to get your files back:| 1. Download Tor browser - and install it.| 2. Open link in TOR browser - ?A0C155001DD0CBxxxEDA0D This link only works in Tor Browser! | 3. Follow the instructions on this page ### Attention! ### # Do not rename encrypted files. # Do not try to decrypt using third party software, it may cause permanent data loss. # Decryption of your files with the help of third parties may cause increased price(they add their fee to our). # Tor Browser may be blocked in your country or corporate network. Use or use Tor Browser over VPN. # Tor Browser user manual !!! We also download huge amount of your private data, including finance information, clients personal info, network diagrams, passwords and so on.Don't forget about GDPR. ``` The content of this file is also encrypted and it has been decrypted in memory before writing the files. ----- The Ransom-Note In Memory ## Self Deleting After a successful execution, LockBit will delete its executable for reducing the artifacts it leaves on the infected system. In order to do that, it runs the following command `C ping` ``` 1.1.1.1 -n 22 > Nul & \ ``` ----- Self Deleting ## Inhibiting System Recovery As almost all ransomware does, LockBit will delete the volume shadow copies, the backup catalog, disable automatic windows recovery, and clear the windows logs as well by running the following commands. ``` /c vssadmin delete shadows /all /quiet & wmic shadowcopy delete & bcdedit /set {default} bootstatuspolicy ignoreallfailures & bcdedit /set {default} recoveryenabled No & wbadmin delete catalog -quiet/c vssadmin Delete Shadows /All /Quiet/c bcdedit /set {default} recoveryenabled No/c bcdedit /set {default} bootstatuspolicy ignoreallfailures/c wbadmin DELETE SYSTEMSTATEBACKUP/c wbadmin DELETE SYSTEMSTATEBACKUP -deleteOldest/c wmic SHADOWCOPY /nointeractive/c wevtutil cl security/c wevtutil cl system/c wevtutil cl application ``` After Decrypting The Commands In Memory ----- Behavioral Analysis Artifacts Of The Executed Commands ## Mitre TTPs The following is a list of the most important MITRE ATT&CK TTPs identified while analyzing the malware. Mitre TTPs Thanks for reading, your comments and feedback are most welcomed 🙂 -----