Post

Agent Tesla - Begone, Foul RAT!

A technical analysis of the Agent Tesla malware

Agent Tesla, a remote access trojan (RAT) coded in .NET, has been in circulation since 2014, primarily targeting users of Microsoft Windows operating systems. Its sophisticated design enables a wide array of functionalities, including data theft, keystroke logging, and screen capture. Notably, this malware undergoes periodic updates and is commercialized through a subscription-based model. Typically, its deployment initiates with phishing emails designed to mimic authentic correspondence, thus luring unsuspecting recipients into its trap.

Stage 1: The Dropper


A quick scan with Detect It Easy reveals that we are dealing with an obfuscated 32-bit .NET binary.

1
2
3
4
5
6
7
8
9
10
11
[*] Pattern validated: 000620????????5A20????????612B??000620????????5A20????????612B??
[*] Pattern validated: 20????????66
PE32
    Linker: Microsoft Linker
    Library: .NET(v4.0.30319)
    Sign tool: Windows Authenticode(2.0)[PKCS #7]
    Protection: Obfuscation(Heuristic)
    Protection: Anti analysis(Heuristic)
    Packer: Packer detected(Heuristic)
    Overlay: Binary
        Certificate: WinAuth(2.0)[PKCS #7]

We will direct our attention to the InitializeMethod() method inside of Form2 class. There is something suspicious happening in this method that you typically do not see in genuine .NET binaries.

An embedded resource named off is retrieved from resources and then decrypted through a simple XOR algorithm using J9EZ6H5428445C755C8RZH as decryption key. XOR Decryption Code View

After the buffer has been decrypted we can see that the buffer contains the second stage payload. We know this because of the first two bytes in the decrypted buffer. 0x5A4D (MZ) serves as a signature that marks the file as a MS-DOS-compatible executable. XOR Decrypted Code View

The second stage payload named SimpleLogin will be loaded into memory and method Justy(string, string, string) from class LoginForm will be invoked with the following arguments: 6643416A, 687077, and AndroidSignTool. Assembly Loading View Assembly Loading Debug View

Stage 2, 3: SimpleLogin.dll & Gamma.dll


An embedded resource named Key0 is retrieved from resource through method TI.Ⴜ() and then GZip decompressed. Justy Resource Retrieval And Decompression View When examining the buffer, we can see that the buffer contains the third stage payload. The assembly name of this payload is Gamma.dll. Justy Resource Retrieval And Decompression View

The class ReactionVessel which resides in Gamma.dll is instantiated.

The method CausalitySource(string) from instantiated class is called twice. Once with 6643416A as argument and the second time with 687077 as argument. The method converts the hexadecimal values to their respective ASCII value. This means that 6643416A becomes fCAj and 687077 becomes hpw.

The method LowestBreakIteration(string, string) is invoked with the following arguments: fCAj, AndroidSignTool and will retrieve the embedded resource fCAj from the executing assembly and instantiate it as a bitmap. The fourth stage payload is encoded into this image through a steganography technique and will be decoded in method SearchResult(byte[], string) using hpw as decryption key. Justy Resource Retrieval And Decompression View

Finally, the fourth stage payload named Tyrone.dll is loaded into memory and method Oex9YxVO6h() from class gfjFseo7ilTwA8Y0nJ is invoked. Justy Resource Retrieval And Decompression View

Stage 4: Tyrone.dll


I renamed a bunch of types, methods, etc… and prefixed them with mw_ since they were heavily obfuscated and to make this section easier to follow. My apologies if I missed a few here and there…

Config


In the constructor of class gfjFseo7ilTwA8Y0nJ we can find a hardcoded config. The config looks as follows:

1
2
0||1||0||1||0||||||1||1||1||0||||||||||||||0||0||0||0||0||0||0||0||4.0||2||12640||0||0||||||
0||0||1||3||3||auto||1||.exe||

The hardcoded config gets parsed and distributed amongst their respective member variables.

Justy Resource Retrieval And Decompression View This is only a partial view of the config.

Windows Defender Exclusion


The malware will attempt to add the full path of the malicious file to the exception list in Windows Defender. This is done by spawning another process executing PowerShell with the following argument:

Add-MpPreference -ExclusionPath "/path/to/malicious/file.exe"

Justy Resource Retrieval And Decompression View

Task Scheduler Persistence


The main executable is copied over to C:\Users\<name>\AppData\Roaming and renamed to XSYZHcH.exe. The copied file has been marked as a system file, is readonly, and not visible to the user. The user has lost permissions to delete the file, write to the file, change file permissions, take ownership, and change file attributes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
BaseName            : XSYZHcH
ResolvedTarget      : C:\Users\Bitscape\AppData\Roaming\XSYZHcH.exe
Target              :
LinkType            :
Name                : XSYZHcH.exe
Length              : 813056
DirectoryName       : C:\Users\Bitscape\AppData\Roaming
Directory           : C:\Users\Bitscape\AppData\Roaming
IsReadOnly          : True
Exists              : True
FullName            : C:\Users\Bitscape\AppData\Roaming\XSYZHcH.exe
Extension           : .exe
CreationTime        : 5/17/2024 9:53:38 PM
CreationTimeUtc     : 5/17/2024 7:53:38 PM
LastAccessTime      : 5/17/2024 9:53:38 PM
LastAccessTimeUtc   : 5/17/2024 7:53:38 PM
LastWriteTime       : 5/12/2024 7:58:22 PM
LastWriteTimeUtc    : 5/12/2024 5:58:22 PM
LinkTarget          :
UnixFileMode        : -1
Attributes          : ReadOnly, Hidden, System, Archive, NotContentIndexed

The malware will attempt to add the full path of XSYZHcH.exe to the exception list in Windows Defender. This is done by spawning another process executing PowerShell with the following argument:

Add-MpPreference -ExclusionPath "/path/to/malicious/file.exe"

Justy Resource Retrieval And Decompression View

The XML schema for the Task Scheduler is Base64 encoded and hardcoded in the assembly. The hardcoded schema will be decoded and slightly altered so its targeting the XSYZHcH.exe binary.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?xml version=\"1.0\" encoding=\"UTF-16\"?>\n
<Task version=\"1.2\"
	xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\n
	<RegistrationInfo>\n    
		<Date>2014-10-25T14:27:44.8929027</Date>\n    
		<Author>DESKTOP-OINTIL9\\Bitscape</Author>\n  
	</RegistrationInfo>\n  
	<Triggers>\n    
		<LogonTrigger>\n      
			<Enabled>true</Enabled>\n      
			<UserId>DESKTOP-OINTIL9\\Bitscape</UserId>\n    
		</LogonTrigger>\n    
		<RegistrationTrigger>\n      
			<Enabled>false</Enabled>\n    
		</RegistrationTrigger>\n  
	</Triggers>\n  
	<Principals>\n    
		<Principal id=\"Author\">\n      
			<UserId>DESKTOP-OINTIL9\\Bitscape</UserId>\n      
			<LogonType>InteractiveToken</LogonType>\n      
			<RunLevel>LeastPrivilege</RunLevel>\n    
		</Principal>\n  
	</Principals>\n  
	<Settings>\n    
		<MultipleInstancesPolicy>StopExisting</MultipleInstancesPolicy>\n    
		<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>\n    
		<StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>\n    
		<AllowHardTerminate>false</AllowHardTerminate>\n    
		<StartWhenAvailable>true</StartWhenAvailable>\n    
		<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>\n    
		<IdleSettings>\n      
			<StopOnIdleEnd>true</StopOnIdleEnd>\n      
			<RestartOnIdle>false</RestartOnIdle>\n    
		</IdleSettings>\n    
		<AllowStartOnDemand>true</AllowStartOnDemand>\n    
		<Enabled>true</Enabled>\n    
		<Hidden>false</Hidden>\n    
		<RunOnlyIfIdle>false</RunOnlyIfIdle>\n    
		<WakeToRun>false</WakeToRun>\n    
		<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>\n    
		<Priority>7</Priority>\n  
	</Settings>\n  
	<Actions Context=\"Author\">\n    
		<Exec>\n      
			<Command>C:\\Users\\Bitscape\\AppData\\Roaming\\XSYZHcH.exe</Command>\n    
		</Exec>\n  
	</Actions>\n
</Task>

The XML schema is then written to tmp5924.tmp and stored in the %TEMP% directory. Justy Resource Retrieval And Decompression View

A new process will be spawned executing schtasks.exe with the following arguments:

@"/Create /TN ""Updates\XSYZHcH"" /XML ""C:\Users\Bitscape\AppData\Local\Temp\tmp5924.tmp"""

Justy Resource Retrieval And Decompression View

Behold; the scheduled task has been created and will be triggered at login and after task creation and modification. Justy Resource Retrieval And Decompression View

Process Hollowing


An embedded resource named PVrTN is retrieved from resources and passed to method mw_decrypt_payload() along with oZjuznn as decryption key. Justy Resource Retrieval And Decompression View

The embedded resource is decrypted through a simple XOR algorithm and then returned. Justy Resource Retrieval And Decompression View

When examining the buffer we can see that the buffer contains the fifth and final payload. This payload will be used in the process hollowing process. Justy Resource Retrieval And Decompression View

With the payload decrypted the actual process hollowing process can begin. The malware creates a new process of itself in suspended state and unhollows/unmaps its memory. Memory is then allocated in the suspended process to accommodate the payload. The payload is then written to the allocated memory space of the suspended process. The entry point of the suspended process is set to the malicious code and then finally the thread will be resumed which executes the malicious code. Justy Resource Retrieval And Decompression View

Final Stage: Agent Tesla


I renamed a bunch of types, methods, etc… and prefixed them with mw_ since they were obfuscated and to make this section easier to follow. My apologies if I missed a few here and there…

Similar Process Termination


The malware will attempt to kill processes sharing the same name except for itself. Justy Resource Retrieval And Decompression View Code responsible for terminating processes sharing the same name

HWID Generation


The malware will grab hardware related information such as the processor id, motherboard serial number, and mac addresses from all enabled network interfaces. Justy Resource Retrieval And Decompression View Code responsible for generating Hardware ID of victim system

WMI ClassDetails
Win32_BaseBoardRetrieves value from SerialNumber property and returns it
Win32_ProcessorRetrieves value from ProcessorID property and returns it
Win32_NetworkAdapterConfigurationRetrieves value from MacAddress property and removes all
: characters from the string and finally returns it

All values are then concatenated and hashed through the MD5 hashing algorithm. The hash is then returned and stored in property for later use.

Public IP Gathering


The malware will send a GET request to http://api.ipify.org/ and parses the result. The result is then returned from method and stored in property for later use. If the status code does not equal 200 OK then a empty string is returned instead. Justy Resource Retrieval And Decompression View

Anti-Analysis Techniques


Agent Tesla employs a few techniques in an effort to strengthen its defensive capabilities against analysis. Let’s explore them.

CheckRemoteDebuggerPresent


The malware checks whether or not it is being debugged remotely. If this is true then the malware will terminate itself. Justy Resource Retrieval And Decompression View

Hosting Provider Check


The malware checks whether or not the victims machine belongs to a hosting provider. If this machine does belong to a hosting provider then true will be returned and the malware will terminate itself. If the machine does not belong to a hosting provider then the malware will resume execution as planned. Justy Resource Retrieval And Decompression View

Tick Count


The malware will store the amount of ticks and immediately sleeps for 10 seconds. After awakening it will measure the tick count once more. Then a check is performed to see if the difference between the initial and final tick is less than 10. The malware will resume execution as planned if this is not true. If it is true then the malware will terminate itself. Justy Resource Retrieval And Decompression View

Sandbox/Anti-Virus Detection


The malware will try to obtain the handle of any of the DLL files listed below. If any of the DLL files are present then true will be returned and the malware will terminate itself. If none of the DLL files are present then the malware will resume execution as planned. Justy Resource Retrieval And Decompression View

DLL FileProduct
cmdvrt32.dllComodo Antivirus
SbieDll.dllSandboxie
Sf2.dllAvast Antivirus
snxhk.dllAvast Antivirus
SxIn.dll360 Total Security

Virtual Machine Detection


The malware will attempt to detect if it is running in a virtual machine by utilizing two WMI queries and parsing a few properties. Justy Resource Retrieval And Decompression View

WMI QueryProperties Used
Select * From Win32_ComputerSystemManufacturer, Model
Select * From Win32_VideoControllerName

The malware will terminate itself when one of the following conditions are met:

  • If Manufacturer equals microsoft corporation && Model contains VIRTUAL
  • If Manufacturer contains vmware
  • If Model equals VirtualBox
  • If Name contains VMware && Name contains VBox

Calculator Downloader


The malware will download an application called calc.exe from some wordpress website and executes it. The Downloader property in GClass0 has been set to true meaning that this code will be run.

I spend quite some time trying to download the file but all attempts failed.

Justy Resource Retrieval And Decompression View Code responsible for downloading calculator if the functionality is enabled, which it is

Persistence


The malware achieves persistence a second time by copying the executing assembly to folder C:\Users\<Username>\AppData\Roaming\Adobe and name the file Adobe.exe. The file attributes will not be changed because the HideFileStartup property in GClass0 has been set to false. Justy Resource Retrieval And Decompression View

Two entries in the Windows Registry are then created to ensure the malware is launched each time the systems boots up. Justy Resource Retrieval And Decompression View

Justy Resource Retrieval And Decompression View Justy Resource Retrieval And Decompression View

Stealing Credentials


The malware goes through a list of hardcoded browsers, email clients, and instant messaging clients and attempts to steal the stored credentials. This data is not stored on disk but retained in memory and wiped after exfiltration. Justy Resource Retrieval And Decompression View Justy Resource Retrieval And Decompression View

Chromium BasedMozilla BasedOther BrowsersEmailIM
Opera BrowserFirefoxUC BrowserOutlookTrillian
Yandex BrowserSeaMonkeySafari for WindowsWindows Mail 
Iridium BrowserThunderbirdQQ BrowserThe Bat! 
ChromiumBlackHawkFalkon BrowserIncredi Mail 
7StarCyberFoxFlock BrowserEudora 
Torch BrowserK-Meleon Claws Mail 
Cool NovoIceCat Fox Mail 
KometaPaleMoon Poco Mail 
AmigoIceDragon eM Client 
BraveWaterFox Mailbird 
CentBrowserPostbox   
ChedotFlock   
Orbitum    
Sputnik    
Comodo Dragon    
Vivaldi    
Citrio    
360 Browser    
Uran    
Liebao Browser    
Elements Browser    
Epic Privacy    
Coccoc    
Sleipnir 6    
QIP Surf    
Coowon    
Chrome    
Edge Chromium    

I have Edge, Chrome, and Firefox installed on my system and entered some bogus credentials inside of their passwords managers. Below you can see the extracted credentials from the aforementioned browsers. Justy Resource Retrieval And Decompression View

Please see the Data Exfiltration section on how the malware exfiltrates the data back to their servers.

Keylogging


Agent Tesla records every keystroke and appends the data to property this.KeylogText. Every hour the recorded keystrokes are sent back to their servers. Justy Resource Retrieval And Decompression View

Some additional system information is appended to the property this.KeylogText before the exfiltration takes place. Justy Resource Retrieval And Decompression View

Please see the Data Exfiltration section on how the malware exfiltrates the data back to their servers.

Clipboard


Agent Tesla will read and parse the content of the victim’s clipboard whenever the clipboard’s content gets updated. If the current data in clipboard is the same as the previous data in the clipboard then the data is ignored. If the data in clipboard is not the same then certain characters in the data are replaced. The data is then appended to a property called this.KeylogText.

The property this.KeylogText is shared with the Keylogger.

Justy Resource Retrieval And Decompression View

Screen Capture


Agent Tesla will attempt to take a screenshot of the victim’s desktop once per hour. Justy Resource Retrieval And Decompression View

The bytes that make up the screenshot are Base64 encoded and then exfiltrated. Justy Resource Retrieval And Decompression View

Please see the Data Exfiltration section on how the malware exfiltrates the data back to their servers.

Stealing Thunderbird Identities


Agent Tesla is capable of retrieving all idenities stored in global-messages-db.sqlite from Thunderbird. Justy Resource Retrieval And Decompression View

The bytes that make up an identity are encoded to Base64 and then exfiltrated. Justy Resource Retrieval And Decompression View

Please see the Data Exfiltration section on how the malware exfiltrates the data back to their servers.

Data Exfiltration


The following method is responsible for exfiltrating the data back to their servers. Let’s explore and find out how exactly the data is exfiltrated. Justy Resource Retrieval And Decompression View

Please use the following table to get an understanding on how the data is structured prior to getting exfiltrated.

DataDescription
id3 - Keylogged Data
4 - Captured Screenshot
5 - Extracted Credentials
7 - Extracted contacts from Thunderbird
secret_keyThe secret key used during TripleDES encryption
PcHwidThe previously generated HWID of victim PC
secret_keyThe secret key used during TripleDES encryption
DateTime.NowThe current date and time
secret_keyThe secret key used during TripleDES encryption
ThisComputerNameThe computer name of the victim
secret_keyThe secret key used during TripleDES encryption
dataThe collected data based on id

Let’s take the harvested credentials as an example. Below you will find the harvested credentials structured according to the information in the table above.

1
2
3
4
5
6
7
8
9
503059def2c05b37c42947dfb206de40a1fa0d1b7aec64378FEB3-563B-F852-821F-9223-5617-F8F9-A9FD0305
9def2c05b37c42947dfb206de40a1fa0d1b7aec643782024-05-17 11:21:0403059def2c05b37c42947dfb206de
40a1fa0d1b7aec64378Bitscape/DESKTOP-OINTIL903059def2c05b37c42947dfb206de40a1fa0d1b7aec64378[
[\"Chrome\",\"https://yahoo.com/\",\"mybusinessemail%40yahoo.com\",\"super_secret_111\"],[\"
Chrome\",\"https://facebook.com/\",\"myemail%40gmail.com\",\"avadakedavra\"],[\"Edge Chromiu
m\",\"https://tiktok.com/\",\"tikkietok\",\"toktok123\"],[\"Edge Chromium\",\"https://youtub
e.com/\",\"%3Center_secret_email%3E\",\"%3Center_secret_password%3E\"],[\"Firefox\",\"https:
//twitter.com\",\"tweet_tweet\",\"twitwit123\"],[\"Firefox\",\"https://myspace.com\",\"myuni
queusername\",\"myspaceisdead\"]]

The structured data is then encrypted through TripleDES with 03059def2c05b37c42947dfb206de40a1fa0d1b7aec64378 hashed through MD5 as secret key. The transformed bytes are then encoded to a Base64 string. Justy Resource Retrieval And Decompression View

1
2
3
4
5
6
7
8
9
10
11
B+s30+8l4gYHbTBenHz7jQC7pG+FQHsdts8yfv0LeIalxOllVIkK+CXuw2SUupeEz0fGoe9lo998wGDD4AqeILK1qPCu
ueHvpIoiQbTB7V83t5Dn6HXJGd0IHxz0hSCgxDbSb5oqN5FMTQPaFDiUip95nwyp7m+W7lJYNTpW84i8aUfJu/QGj3YV
/p4uCj/PL14JL+z5uObeyTIv4F2BhOrPx666vRRyhRi2Ftqd9e3uNcpwg40MuAD0AW5BPWXCtPLPWSRe+14y7vqcizKU
cYSwsnw5utZpLxbxbRlZSK4cu5jOMvYN9+rPx666vRRyhRi2Ftqd9e3uNcpwg40MuAD0AW5BPWXCtPLPWSRe+17/ikIf
a6rTFrlTnerUChLpb5UUcpxTXcWcqRbNN8H0bqRn8MtW6z1v7yOibUOEv2x3fvaiX0LlhOR9Z1JzJg3XaaPm774AZraz
GB/cN/4bQSamK7BMt3XDkawgSvI/DlzvHqSE4UO2YbdGcjYR4CObhn9hWbmoXj8TZ5017NiI3uUapHir1RVNZIHZwhhj
jJ7ryuVO9VGWvUSCyuOO0Y4MLWiPqg2VfAZsf5+MhyjbvFHLEscSwt2xtlA23k3oqlKbVp2roQEuXf2WCOmYapBWXPei
u0UhgNXpGMtSkvPZ+C1oj6oNlXwGbH+fjIco27xvlRRynFNdxV3R+RDqti9UoB4sDZLfKisduMW2XpfOrOQYJYLQ2B1g
e0+oUFeFZJ0sx2pJtjnwsKrEYMPSHxDz1W6AXLyRtam3hJzJ/7VoGu8thvZSKuogL2xsmpVzfRaTjRyqXB36qoNVne0b
BzgSSnOM8Rbf7eG+n5NwN6w8J2bnj1BVdxGcD0aQEB9845aoTOswCMbt8e8epIThQ7Zhc3G/xe/66byvTeu/MnGCE99o
+YxrkM17YWVKsRjggMsXRLvEISDWmuHy7OedRNPnxognN3vRPRw=

Finally, the malware is ready to exfiltrate the data. The exfiltration is done through a POST request to https://dancingtutorial.com.ng/blackmarket/inc/ed02af730792a8.php using Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:99.0) Gecko/20100101 Firefox/99.0 as user agent. Justy Resource Retrieval And Decompression View

Indicators of Compromise


Indicator 
FilePO 22367812_PDF Radiant Chemicals Ltd iGST_eH2mYaM.exE
SHA256D7FDAAF1D1C26D555C92DE3611BDDADD30B75AA48BC997C012EDC92AF6B20635
Indicator 
FileSimpleLogin.dll
SHA256871828768AFCED1753273F32AB22718EEEEE9FB5AC3B1208265B734F7217580A
Indicator 
FileGamma.dll
SHA2564A53290143B4EAAED49B05CAB7D25711AD549232822C05651C565B7F39CDDD8B
Indicator 
FileTyrone.dll
SHA256D24339DD80A4B37DEFEA8A0AA744CD89CD854CA2B0EF4A9D3391F5F95E45C105
Indicator 
Filebfb5da9f-48ba-40d7-85d4-7ec204e8e6d3.exe
SHA256EF5E91F4B30BE10DAE9A0A62A9D6B10A1483505ACDE58CC1B0826CF607476D78
Indicator 
URLhttps://dancingtutorial.com.ng/blackmarket/inc/ed02af730792a8.php
Indicator 
URLhttps://mzcomedy.com.ng/wp/wp-content/uploads/calc.exe

MITRE ATT&CK® Techniques


TacticTechnique NameTechnique ID
Command and ControlWeb ProtocolsT1071.001
CollectionArchive Collected DataT1560
PersistenceRegistry Run Keys / Startup FolderT1547.001
CollectionClipboard DataT1115
Credential AccessCredentials from Web BrowserT1555
Defensive EvasionDeobfuscate/Decode Files or InformationT1140
ExfiltrationExfiltration Over Unencrypted Non-C2 ProtocolT1048.003
Defensive EvasionHidden Files and DirectoriesT1564
Defensive EvasionHidden WindowT1564.003
CollectionKeyloggingT1056.001
Defensive EvasionModify RegistryT1112
Defensive EvasionSteganographyT1027.003
Defensive EvasionEmbedded PayloadsT1027.009
Defensive EvasionEncrytped/Encoded FileT1027.013
DiscoveryProcess DiscoveryT1057
Defensive EvasionProcess HollowingT1055.012
PersistenceScheduled TaskT1053
CollectionScreen CaptureT1113
DiscoverySystem Information DiscoveryT1082
DiscoverySystem Network Configuration DiscoveryT1016
DiscoverySystem Owner/User DiscoveryT1033
DiscoverySystem Time DiscoveryT1124
Credential AccessCredentials In FilesT1552.001
Credential AccessCredentials in RegistryT1552
ExecutionMalicious FileT1204
Defensive EvasionVirtualization/Sandbox EvasionT1497
ExecutionWindows Management InstrumentationT1047
This post is licensed under CC BY 4.0 by the author.

Trending Tags