top of page

Comprehensive Malware Analysis: Dissecting Agent Tesla’s Evasion Tactics, Persistence, and Network Behavior

  • Hacking By Doing
  • Sep 12, 2024
  • 14 min read

Updated: Feb 18


Introduction

In this analysis, I focus on a sample of Agent Tesla, a well-known Remote Access Trojan (RAT) and spyware. My goal was to unravel its techniques, particularly how it evades detection, establishes persistence, manipulates memory, and exfiltrates data.

Agent Tesla has evolved over time, employing sophisticated evasion tactics such as anti-debugging, dynamic API resolution, and persistence mechanisms via the Windows registry. This report will showcase my detailed static and dynamic analysis approach, explaining how I explored its core functionalities by using tools like PEStudio, Wireshark, ProcMon, IDA Pro, and x64dbg.


Static Analysis

The first step was to perform static analysis to gather information on the structure and components of the binary.

  • SHA-256 Hash: 9ed287cdbe94a52fa44d8ba055c5d067a437c823e1f75ddfe7262117d9df22ed


Strings Analysis

When I examined the strings, I expected to find API calls, C2 (Command and Control) URLs, or maybe even obfuscation techniques. Interestingly, much of the string content was obfuscated, except for a few telling strings that referenced certificate information. Strings like sectigo.com and USERTrust RSA Certification Authority stood out.

At this point, I suspected the malware might be trying to appear legitimate by using valid digital certificates, perhaps for code signing. This was reinforced by the presence of CRL URLs (Certificate Revocation Lists), like:

  • http://crt[.]sectigo[.]com/SectigoRSATimeStampingCA[.]crt

These URLs suggest the malware might use trusted Sectigo certificates for signing or to conceal its communications under secure SSL channels.


PEStudio Findings

PEStudio is an invaluable tool for static analysis, providing key insights into entropy, imports, and potential evasion techniques. Running the sample through PEStudio gave me a few critical data points:

  • Entropy: The binary showed an entropy score of 4.525. Typically, I interpret entropy scores above 7 as an indicator of heavy packing or encryption. Since this value was moderately high but not extreme, it told me that Agent Tesla might be partially obfuscated but still largely accessible for further static and dynamic analysis.


  • Imports: Analyzing the imports is always crucial for understanding the behavior of malware. I observed several important imports:


ree

    • VirtualProtect: This function often signifies memory manipulation. When malware uses VirtualProtect, it's likely preparing memory for injection, changing permissions to allow code execution in regions of memory that would otherwise be non-executable.

    • MemoryStream: This indicates that the malware may operate in-memory, storing sensitive data in memory to avoid writing it to disk, which is a tactic to evade forensics.

    • AesManaged and CryptoStream: These are part of the System.Security.Cryptography namespace, pointing to data encryption, which is likely used for obfuscating exfiltrated data. Given Agent Tesla's reputation for data exfiltration, this was a strong clue that encryption was used to secure its stolen data before sending it to its C2 servers.


Dynamic Analysis

Following the static analysis, I moved on to dynamic analysis to observe the malware's behavior during execution. I first ran the sample in a controlled environment, capturing its network activity with Wireshark and monitoring file and registry activity using ProcMon and Autoruns.


Wireshark Findings: C2 Communication and DNS Queries

Running Wireshark during the malware's execution revealed interesting DNS queries, leading to two main findings:


  1. DNS Query to mail[.]pakdisco[.]com:

ree

    • This domain seemed suspicious at first since it was associated with an Iranian juice company—a connection I uncovered through some OSINT (Open-Source Intelligence).


ree

    • The presence of this domain in malware network traffic raised a red flag. It's likely that the domain was compromised and is now being used as part of Agent Tesla’s C2 infrastructure. Attackers commonly use obscure, legitimate domains to mask their communications, making it more difficult for network monitoring tools to detect malicious traffic.


  1. DNS Query to api[.]apify[.]org:

ree

    • Apify is a well-known web scraping and automation service. The DNS query to this domain suggested that Agent Tesla might be leveraging legitimate APIs for malicious purposes—potentially for data scraping or as an additional communication channel to the C2 server.

    • By utilizing a legitimate service like Apify, Agent Tesla is able to further evade detection, hiding its traffic amidst normal web traffic.


This led me to conclude that Agent Tesla was using a mix of compromised domains and legitimate services to manage exfiltration and C2 communication, a strategy that makes its network traffic harder to detect.


Persistence Mechanisms: Autoruns Findings

Next, I turned to Autoruns to examine how Agent Tesla achieves persistence. The malware created a registry entry under the following path:

ree
  • Registry Key: HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\

    • Executable Path: c:\users\user\appdata\local\temp\IPYIgv\IPYIgv.exe

ree

This registry entry ensures that Agent Tesla is executed every time the user logs in, without requiring administrative privileges. This method of persistence was notable for several reasons:

  • Stealth: By operating under user-level privileges, it avoids the attention that might come from requiring admin access.

  • Disguise: The malware's executable was disguised as a Microsoft .NET Framework CAS Policy Manager, making it less likely to draw suspicion.

I concluded that Agent Tesla relies on user-level registry modifications to maintain a foothold in the system and uses a common persistence tactic that blends in with legitimate system processes.


Registry and Process Activity: ProcDot and ProcMon

To gain deeper insights into Agent Tesla's behavior after detonation, I used ProcDot and ProcMon to visualize its interaction with system processes and the registry.

ree

Registry Modifications

A major part of Agent Tesla's stealth strategy involves registry tampering. Using ProcDot, I traced the malware's interactions with critical registry keys:

  1. Security Notifications Disabled:

    • Key Modified: HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Notifications\Settings\Windows.System.Toast.SecurityAndMaintenance\Enabled

    • Purpose: By disabling security and maintenance notifications, the malware ensures that no alerts will be shown to the user, allowing it to operate undetected for longer.

  2. Disabling UAC:

    • Key Modified: HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA

    • Purpose: This key controls User Account Control (UAC). By modifying this value, Agent Tesla can suppress UAC prompts, allowing the malware to perform elevated actions without triggering security warnings.

  3. Modifying Proxy and Network Settings:

    • Keys Modified: Several entries under HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings were changed, suggesting that the malware was attempting to manipulate how network traffic is routed, possibly setting up a proxy or altering other settings to facilitate C2 communication.


Process Creation and Manipulation

ree

Using ProcMon, I was able to trace process creation activities:

  1. PowerShell Command to Modify Defender:

    • Command: powershell.exe -Force -AddMpPreference -ExclusionPath "C:\Users\[redacted]\Desktop\agent_tesla.exe"

    • Purpose: This command modifies Windows Defender to add an exclusion path, effectively instructing Defender to ignore the malware's executable. I identified this as a clear evasion tactic—by excluding its own path, Agent Tesla avoids detection by Windows' built-in antivirus.

  2. WerFault.exe Manipulation:

    • WerFault.exe is the Windows Error Reporting service, commonly invoked when an application crashes. I found Agent Tesla calling this process, which could either be a technique to mask its activities by simulating errors or an attempt to suppress legitimate crash reports from being sent to Microsoft.


Interaction with GDI32.dll and USER32.dll by Agent Tesla

ree

During ProcMon analysis, I observed that Agent Tesla interacted heavily with GDI32.dll and USER32.dll, which are critical Windows system libraries:


  • GDI32.dll: This library is responsible for graphical device interface functions, such as rendering and manipulating graphical objects. The interaction suggests that Agent Tesla might be using GDI functions to perform screen capturing activities, stealing sensitive visual data such as screenshots or window contents.


  • USER32.dll: This library handles user interface components and input methods, like keyboard and mouse input. Its use points toward keylogging or clipboard monitoring. The malware likely monitors user input to capture keystrokes and steal sensitive information such as passwords, personal data, or communication content.


These observations are consistent with Agent Tesla’s spyware capabilities, where it captures both keystrokes and screen contents to exfiltrate confidential data from compromised machines.


Keylogging Hooks: SetWindowsHookEx and CallNextHookEx

ree

Through dynamic analysis using ProcMon and x64dbg, I identified key functions SetWindowsHookEx and CallNextHookEx being utilized, which are strong indicators of keylogging activity.


  • SetWindowsHookEx: This API is used to install a keyboard or mouse hook that intercepts user input. In this case, Agent Tesla likely employs this function to monitor keystrokes and possibly mouse clicks. The hook captures keystrokes and forwards the intercepted input to the malware.

  • CallNextHookEx: After capturing the user input, this function ensures the input is passed to the next hook procedure in the chain, preserving normal user interaction while secretly logging the data.


Together, these functions indicate Agent Tesla’s keylogging functionality, allowing it to silently capture user inputs like credentials, private messages, and other sensitive data without disrupting the user’s experience.


Other Functions and Libraries

  • USER32.dll: This DLL contains essential functions for handling the Windows user interface and input methods. Its involvement in Agent Tesla’s activity further supports the hypothesis that the malware is manipulating user input for data exfiltration through keylogging.

  • LdrpInitializeProcessin (NTDLL.dll): This function is commonly seen in malware for initializing processes and working with thread control. It was used alongside NtQueryInformationThread, which indicates that Agent Tesla is possibly monitoring threads to ensure its keylogging hooks are functioning as intended or avoiding detection from security tools.



Disk Writing Activity: WriteFile in x64dbg

ree

In x64dbg, I set a breakpoint on the WriteFile function and observed Agent Tesla writing to disk after certain threads were executed. This suggests that the malware was saving captured data (possibly keylogged information or screenshots) to disk before exfiltrating it to its Command-and-Control (C2) server.


Process Hacker Observations:

ree

After the WriteFile call, I noticed spikes in disk activity in Process Hacker. The disk I/O highlighted temporary file writes, which are likely related to storing data before transmitting it over the network to remote servers.



JScript Execution via jsc.exe

ree

During dynamic analysis, Agent Tesla launched a child process, jsc.exe, immediately after the disk-writing activity. JSC.exe is a legitimate system component used to compile and execute JScript code. However, its execution in this context suggests the malware might be using it to run malicious JScript payloads.

  • Malicious Behavior: Given its execution right after WriteFile, it's possible that Agent Tesla is using jsc.exe to dynamically generate and execute JScript code, allowing it to carry out additional malicious activities such as executing more advanced payloads or facilitating code injection into other processes.



Anti-Debugging Techniques: IsDebuggerPresent, GetTickCount, and More

ree

During my analysis in x64dbg, I encountered several anti-debugging mechanisms:

  • IsDebuggerPresent: A classic anti-debugging technique used by malware to detect if it’s being debugged. When the function returns TRUE, the malware might alter its behavior to avoid being fully analyzed.

  • QueryPerformanceCounter, GetTickCount, and Sleep: These functions were used to introduce delays and measure execution time, which can cause issues in virtualized or debugged environments. They are commonly used to detect debugging tools by measuring timing discrepancies that wouldn't appear in a normal execution environment.


Despite managing to bypass some of these checks manually, I found that Agent Tesla’s anti-debugging mechanisms were well-implemented and would require considerable effort to fully bypass without disrupting the malware’s natural execution flow.

Additionally, anti-debugging mechanisms made it difficult to reach the CreateRemoteThread call,

ree

which I was attempting to inspect to determine which process was being hijacked. Ultimately, the malware’s sophistication in this area delayed further analysis.



In-Depth Static Analysis in IDA Pro: Deobfuscation and Key Findings

ree

After struggling with the obfuscated code in IDA Pro, I realized that Agent Tesla had used sophisticated obfuscation techniques, including Unicode escape sequences. These sequences were used to disguise function names and control flow, making it extremely difficult to discern the malware’s true behavior through traditional static analysis.

At this point, I knew I needed to deobfuscate the binary to make sense of it, so I turned to de4dot, a tool that specializes in deobfuscating .NET assemblies.


Step 1: Deobfuscation with de4dot

Once I ran de4dot on the Agent Tesla sample, it successfully removed the obfuscation, revealing much more meaningful method names and class structures in IDA Pro. The deobfuscation exposed the following critical components:

ree
  • GClass0::ctor(): This constructor method initializes several core components of the malware. I suspected this function orchestrated the initial setup of key malicious capabilities, such as keylogging, data exfiltration, and memory manipulation. By reversing this function, I was able to observe how the malware prepared itself for execution.

  • Stealth Features (FreeConsole()): One of the immediate stealth tactics I observed was the malware's call to FreeConsole(). This API call effectively hides the console window, ensuring that the malware runs silently in the background without raising the user’s suspicion. This is a common trick used by Agent Tesla to avoid alerting the victim during its execution.


Step 2: Memory Manipulation Using VirtualProtect

ree

Another critical function I encountered was VirtualProtect, a well-known Windows API used for changing memory protection flags. Agent Tesla employs this function to alter memory regions, allowing it to execute shellcode or inject code into other processes. My goal was to trace how this function was being used within the malware and understand its role in memory manipulation.


Cross-referencing VirtualProtect

Through cross-references (xrefs) in IDA Pro, I was able to locate where VirtualProtect was being called and observed two key behaviors:

ree
  1. First VirtualProtect Call with 0x40 Flag:

    • The malware first called VirtualProtect with the protection constant 0x40, which translates to PAGE_EXECUTE_READWRITE. This is a clear indicator that the malware was preparing a memory region to be both writable and executable.

    • Why it matters: Allowing memory to be both writable and executable is typical in shellcode injection. The malware sets up this memory region to store malicious code that will be dynamically generated or injected into the process.

  2. Memory Copy via Marshal.Copy:

    • After the VirtualProtect call, I traced the execution to a Marshal.Copy method. This method was copying data from a managed byte array (likely malicious code or shellcode) into the newly allocated memory space.

    • Why it matters: This confirms that Agent Tesla is not just allocating memory but is actively loading malicious code into that region. This behavior is consistent with process injection techniques where the malware injects shellcode into memory for later execution.

  3. Second VirtualProtect Call with 0x20 Flag:

ree

    • Once the byte array was copied into memory, the malware made a second VirtualProtect call, this time using PAGE_EXECUTE_READ (flag 0x20). This change in permissions locked the memory region, allowing it to be executed but preventing further modifications.

    • Why it matters: This sequence of events—unlocking memory, copying code, and re-securing the memory for execution—is a typical shellcode execution pattern used in advanced malware. It ensures that the malicious code can run while remaining protected from further tampering.


      Conclusion of IDA Pro and de4dot Analysis

      The combination of de4dot and IDA Pro allowed me to fully reverse-engineer Agent Tesla’s obfuscated behavior. By breaking down its dynamic API resolution, memory manipulation through VirtualProtect, and its use of JScript execution via jsc.exe, I uncovered critical parts of the malware’s functionality, including:

      • Shellcode injection via memory manipulation and bytecode copying.

      • Dynamic API resolution for evasive execution.

      • Keylogging capabilities and screen-capturing potential through hooks into USER32.dll and GDI32.dll.

      • Stealth techniques like console hiding via FreeConsole().

      These findings highlight Agent Tesla’s sophistication in evading detection, executing malicious payloads, and ensuring persistence on infected machines. By leveraging advanced techniques such as code injection, dynamic API calls, and anti-debugging mechanisms, Agent Tesla remains one of the more challenging malware strains to fully reverse-engineer.



Step 3: Understanding API Resolution via GetProcAddressForCaller

During my analysis, I encountered the GetProcAddressForCaller function, a more advanced and context-aware variant of the typical GetProcAddress. This function adds a layer of complexity by dynamically resolving function addresses based on who is making the request, adding caller context as an additional parameter. This context-sensitive behavior allowed Agent Tesla to resolve different functions depending on where and how the call originated.


Tracing GetProcAddressForCaller in x64dbg
ree

To observe how Agent Tesla resolves API calls dynamically, I set breakpoints on GetProcAddressForCaller in x64dbg. This allowed me to capture the resolved functions as the malware made the call. Unlike GetProcAddress, which consistently resolves the same function, GetProcAddressForCaller introduces variability depending on the calling function's context.

By examining the memory contents of RDX, I was able to track which functions the malware was resolving, and how they might vary based on different contexts.


Key APIs Dynamically Resolved
ree
  1. RegOpenKeyExW:

    • This API is used to open a handle to a registry key, and its resolution was likely part of Agent Tesla’s persistence mechanisms or for interacting with critical configuration data stored in the Windows registry.

    • Why It Matters: Registry interaction is central to many malware activities, including ensuring persistence and extracting system-specific information. In the context of GetProcAddressForCaller, this function could be conditionally resolved to evade detection in certain environments, like sandboxes or debuggers.

  2. URLOpenBlockingStreamW:

    • This API facilitates the opening of URLs and reading their contents in a blocking manner, which means the malware waits for a response before proceeding. It was likely used for exfiltrating data to its C2 server or retrieving additional payloads.

    • Why It Matters: In a standard analysis environment, the malware could use URLOpenBlockingStreamW to send sensitive data like keylogs or screenshots to a remote server. If it detects a debugger, it may resolve an alternate function to avoid exposing this behavior.

  3. VirtualProtect:

    • This API is used to modify memory protections, allowing regions of memory to be marked as executable. In Agent Tesla, this is a key component of memory manipulation and shellcode execution.

    • Why It Matters: By dynamically resolving VirtualProtect, Agent Tesla can adjust its behavior depending on the environment. In some cases, it might avoid resolving this API altogether if it detects debugging tools, further complicating analysis.

  4. PathCombineW and UrlIsW:

    • These APIs are responsible for file path manipulation and URL validation. They could be used by Agent Tesla to construct file paths for temporary storage or to validate URLs before making network requests.

    • Why It Matters: The dynamic resolution of file and network-related functions ensures that Agent Tesla can flexibly interact with the file system or network in various execution contexts. If the malware detects analysis tools, it might fail to resolve these functions, obscuring its true behavior.


Conclusion of API Resolution via GetProcAddressForCaller

The use of GetProcAddressForCaller in Agent Tesla highlights its sophisticated approach to dynamic API resolution and anti-analysis techniques. By resolving function addresses based on the caller context, Agent Tesla can adapt its behavior depending on the execution environment. This allows the malware to:

  • Elicit different behaviors depending on whether it's being executed in a sandbox or debugging environment, as opposed to a real-world victim machine.

  • Dynamically resolve APIs crucial for its core functionality—such as registry manipulation, network communication, and memory protection—only when certain conditions are met, making it harder to predict its behavior using static analysis alone.

This context-sensitive dynamic resolution represents a more advanced technique in malware development, aimed at thwarting traditional analysis tools and making dynamic reverse engineering significantly more challenging.


Final Conclusion: Dissecting Agent Tesla’s Sophisticated Tactics

The comprehensive analysis of Agent Tesla revealed a highly evasive and technically sophisticated malware, adept at evading detection and analysis. Through a combination of static and dynamic techniques, we uncovered its use of memory manipulation, dynamic API resolution, persistence mechanisms, and anti-debugging features.


Key Findings and Techniques

  1. Keylogging and Screen Capture:

    • Agent Tesla interacts with USER32.dll and GDI32.dll to enable keylogging and potential screen capturing functionalities. The use of APIs like SetWindowsHookEx and CallNextHookEx clearly indicates its ability to intercept keystrokes, capturing sensitive user data such as passwords and personal information in a stealthy manner.

    • These hooks allow the malware to collect user input without interfering with normal operations, further enhancing its ability to remain undetected on compromised systems.

  2. Dynamic Memory Manipulation via VirtualProtect:

    • The use of VirtualProtect demonstrated Agent Tesla’s capability to manipulate memory protections, enabling the malware to inject shellcode or execute dynamically generated code. By leveraging Marshal.Copy and subsequent memory protection modifications, the malware efficiently prepares regions of memory for malicious code execution.

    • This memory manipulation is a hallmark of code injection techniques, allowing the malware to hide in legitimate processes and operate under the radar.

  3. Context-Aware API Resolution with GetProcAddressForCaller:

    • One of the most advanced tactics employed by Agent Tesla is its use of GetProcAddressForCaller, a variant of the standard GetProcAddress. This API resolution method allows the malware to dynamically resolve function addresses based on caller context, adding a sophisticated layer of anti-analysis and evasion.

    • The ability to resolve different APIs depending on the calling function adds significant complexity to the reverse-engineering process. The malware can change its behavior based on the execution environment, making it harder for analysts to determine which APIs are in use without tracing the full control flow.

  4. Persistence via Registry Manipulation:

    • Agent Tesla ensures its persistence by writing to the HKCU\Run registry key, launching itself upon user login without needing administrative privileges. This persistence mechanism relies on subtle modifications to user-level registry keys, making it less likely to be detected by traditional antivirus solutions.

    • By embedding itself in commonly ignored locations like AppData and masking its presence through process names mimicking legitimate Microsoft services, Agent Tesla further enhances its persistence and evasion capabilities.

  5. Disk Writing and JScript Execution:

    • The malware was observed using WriteFile to store data, which was later accessed for exfiltration or further malicious activities. Following the disk-writing activity, Agent Tesla launched jsc.exe, indicating that it might use JScript to dynamically compile and execute additional payloads or scripts.

    • The use of JScript execution through jsc.exe shows the flexibility of the malware in leveraging legitimate system processes to run custom scripts without raising suspicion.

  6. Sophisticated Anti-Debugging Techniques:

    • Agent Tesla employs multiple anti-debugging mechanisms, including IsDebuggerPresent, GetTickCount, and QueryPerformanceCounter, which introduce delays or manipulate the execution flow when running under a debugger. These mechanisms make traditional debugging more difficult and prevent analysts from easily stepping through the malware’s code.

    • Combined with context-aware API resolution, these anti-debugging tactics significantly increase the effort required to analyze the malware’s behavior in detail, further protecting the malware from security researchers.


Final Thoughts

Through this analysis, I was able to uncover Agent Tesla’s complex evasion techniques, showing how it leverages dynamic memory manipulation, keylogging, and adaptive function resolution to remain hidden and operational on victim machines. The depth of this analysis demonstrates the sophistication of modern malware and the critical need for robust tools and strategies in combating such threats.

The insights gained from dissecting Agent Tesla provide valuable lessons in handling obfuscated malware and context-driven evasive behavior, highlighting the ongoing evolution of malware design and the increasing challenges faced by cybersecurity professionals.

 
 
bottom of page