Extracting Config from Agent Tesla RAT
Overview
Agent Tesla is a .NET-based Remote Access Trojan (RAT) and keylogger that ranked among the top 10 malware variants in 2024, impacting 6.3% of corporate networks globally. It exfiltrates stolen credentials via SMTP email, FTP upload, Telegram bot API, or Discord webhooks. The malware configuration is embedded in the .NET assembly, typically obfuscated using string encryption, resource encryption, or custom loaders that decrypt and execute Agent Tesla in memory via .NET Reflection (fileless). Configuration extraction involves decompiling the .NET assembly with dnSpy or ILSpy, identifying the decryption routine for configuration strings, and extracting SMTP server addresses, credentials, FTP endpoints, Telegram bot tokens, and targeted applications.
When to Use
- When performing authorized security testing that involves extracting config from agent tesla rat
- When analyzing malware samples or attack artifacts in a controlled environment
- When conducting red team exercises or penetration testing engagements
- When building detection capabilities based on offensive technique understanding
Prerequisites
- dnSpy or ILSpy for .NET decompilation
- Python 3.9+ with
dnlib or pythonnet for automated extraction
- de4dot for .NET deobfuscation
- Understanding of .NET IL code and Reflection
- Sandbox for dynamic analysis (ANY.RUN, CAPE)
Workflow
Step 1: Deobfuscate and Extract Configuration
#!/usr/bin/env python3
"""Extract Agent Tesla RAT configuration from .NET assemblies."""
import re
import sys
import json
import base64
import hashlib
from pathlib import Path
def extract_strings_from_dotnet(filepath):
"""Extract readable strings from .NET binary for config analysis."""
with open(filepath, 'rb') as f:
data = f.read()
# Extract US (User Strings) heap from .NET metadata
strings = []
# Look for common Agent Tesla config patterns
patterns = {
"smtp_server": re.compile(rb'smtp[\.\-][\w\.\-]+\.\w{2,}', re.I),
"email": re.compile(rb'[\w\.\-]+@[\w\.\-]+\.\w{2,}'),
"ftp_url": re.compile(rb'ftp://[\w\.\-:/]+', re.I),
"telegram_token": re.compile(rb'\d{8,10}:[A-Za-z0-9_-]{35}'),
"telegram_chat": re.compile(rb'(?:chat_id=|chatid[=:])[\-]?\d{5,15}', re.I),
"discord_webhook": re.compile(rb'https://discord\.com/api/webhooks/\d+/[\w-]+'),
"password": re.compile(rb'(?:pass(?:word)?|pwd)[=:]\s*[\w!@#$%^&*]{4,}', re.I),
"port": re.compile(rb'(?:port|smtp_port)[=:]\s*\d{2,5}', re.I),
}
results = {}
for name, pattern in patterns.items():
matches = pattern.findall(data)
if matches:
results[name] = [m.decode('utf-8', errors='replace') for m in matches]
# Extract Base64-encoded strings (common obfuscation)
b64_pattern = re.compile(rb'[A-Za-z0-9+/]{20,}={0,2}')
b64_decoded = []
for match in b64_pattern.finditer(data):
try:
decoded = base64.b64decode(match.group())
text = decoded.decode('utf-8', errors='strict')
if text.isprintable() and len(text) > 5:
b64_decoded.append(text)
except Exception:
pass
if b64_decoded:
results["base64_decoded_strings"] = b64_decoded[:30]
return results
def decrypt_agenttesla_strings(data, key_hex):
"""Decrypt Agent Tesla encrypted configuration strings."""
key = bytes.fromhex(key_hex)
# Agent Tesla V1: Simple XOR with key
decrypted_strings = []
# Find encrypted blobs (high-entropy byte sequences)
blob_pattern = re.compile(rb'[\x80-\xff]{16,256}')
for match in blob_pattern.finditer(data):
blob = match.group()
# Try XOR decryption
decrypted = bytes(b ^ key[i % len(key)] for i, b in enumerate(blob))
try:
text = decrypted.decode('utf-8', errors='strict')
if text.isprintable() and len(text.strip()) > 3:
decrypted_strings.append(text.strip())
except UnicodeDecodeError:
pass
# V2: SHA256-based key derivation then AES
sha256_key = hashlib.sha256(key).digest()
return decrypted_strings
def analyze_exfiltration_config(config):
"""Analyze extracted configuration for exfiltration methods."""
methods = []
if config.get("smtp_server"):
methods.append({
"type": "SMTP",
"servers": config["smtp_server"],
"emails": config.get("email", []),
})
if config.get("ftp_url"):
methods.append({
"type": "FTP",
"urls": config["ftp_url"],
})
if config.get("telegram_token"):
methods.append({
"type": "Telegram",
"tokens": config["telegram_token"],
"chat_ids": config.get("telegram_chat", []),
})
if config.get("discord_webhook"):
methods.append({
"type": "Discord",
"webhooks": config["discord_webhook"],
})
return methods
if __name__ == "__main__":
if len(sys.argv) < 2:
print(f"Usage: {sys.argv[0]} <agent_tesla_sample>")
sys.exit(1)
config = extract_strings_from_dotnet(sys.argv[1])
methods = analyze_exfiltration_config(config)
report = {"raw_config": config, "exfiltration_methods": methods}
print(json.dumps(report, indent=2))
Validation Criteria
- Exfiltration method identified (SMTP/FTP/Telegram/Discord)
- Server addresses and credentials extracted from config
- Targeted applications list recovered
- Keylogger and screenshot capture settings documented
- Persistence mechanism identified
- IOCs suitable for network blocking extracted
References
1---
2name: extracting-config-from-agent-tesla-rat
3description: Extract embedded configuration from Agent Tesla RAT samples including SMTP/FTP/Telegram exfiltration credentials,
4 keylogger settings, and C2 endpoints using .NET decompilation and memory analysis.
5domain: cybersecurity
6subdomain: malware-analysis
7tags:
8- agent-tesla
9- rat
10- config-extraction
11- dotnet
12- malware-analysis
13- keylogger
14- credential-theft
15version: '1.0'
16author: mahipal
17license: Apache-2.0
18atlas_techniques:
19- AML.T0024
20- AML.T0056
21- AML.T0086
22nist_ai_rmf:
23- GOVERN-1.1
24- MEASURE-2.7
25- MANAGE-3.1
26nist_csf:
27- DE.AE-02
28- RS.AN-03
29- ID.RA-01
30- DE.CM-01
31---
32
33# Extracting Config from Agent Tesla RAT
34
35## Overview
36
37Agent Tesla is a .NET-based Remote Access Trojan (RAT) and keylogger that ranked among the top 10 malware variants in 2024, impacting 6.3% of corporate networks globally. It exfiltrates stolen credentials via SMTP email, FTP upload, Telegram bot API, or Discord webhooks. The malware configuration is embedded in the .NET assembly, typically obfuscated using string encryption, resource encryption, or custom loaders that decrypt and execute Agent Tesla in memory via .NET Reflection (fileless). Configuration extraction involves decompiling the .NET assembly with dnSpy or ILSpy, identifying the decryption routine for configuration strings, and extracting SMTP server addresses, credentials, FTP endpoints, Telegram bot tokens, and targeted applications.
38
39
40## When to Use
41
42- When performing authorized security testing that involves extracting config from agent tesla rat
43- When analyzing malware samples or attack artifacts in a controlled environment
44- When conducting red team exercises or penetration testing engagements
45- When building detection capabilities based on offensive technique understanding
46
47## Prerequisites
48
49- dnSpy or ILSpy for .NET decompilation
50- Python 3.9+ with `dnlib` or `pythonnet` for automated extraction
51- de4dot for .NET deobfuscation
52- Understanding of .NET IL code and Reflection
53- Sandbox for dynamic analysis (ANY.RUN, CAPE)
54
55## Workflow
56
57### Step 1: Deobfuscate and Extract Configuration
58
59```python
60#!/usr/bin/env python3
61"""Extract Agent Tesla RAT configuration from .NET assemblies."""
62import re
63import sys
64import json
65import base64
66import hashlib
67from pathlib import Path
68
69
70def extract_strings_from_dotnet(filepath):
71 """Extract readable strings from .NET binary for config analysis."""
72 with open(filepath, 'rb') as f:
73 data = f.read()
74
75 # Extract US (User Strings) heap from .NET metadata
76 strings = []
77
78 # Look for common Agent Tesla config patterns
79 patterns = {
80 "smtp_server": re.compile(rb'smtp[\.\-][\w\.\-]+\.\w{2,}', re.I),
81 "email": re.compile(rb'[\w\.\-]+@[\w\.\-]+\.\w{2,}'),
82 "ftp_url": re.compile(rb'ftp://[\w\.\-:/]+', re.I),
83 "telegram_token": re.compile(rb'\d{8,10}:[A-Za-z0-9_-]{35}'),
84 "telegram_chat": re.compile(rb'(?:chat_id=|chatid[=:])[\-]?\d{5,15}', re.I),
85 "discord_webhook": re.compile(rb'https://discord\.com/api/webhooks/\d+/[\w-]+'),
86 "password": re.compile(rb'(?:pass(?:word)?|pwd)[=:]\s*[\w!@#$%^&*]{4,}', re.I),
87 "port": re.compile(rb'(?:port|smtp_port)[=:]\s*\d{2,5}', re.I),
88 }
89
90 results = {}
91 for name, pattern in patterns.items():
92 matches = pattern.findall(data)
93 if matches:
94 results[name] = [m.decode('utf-8', errors='replace') for m in matches]
95
96 # Extract Base64-encoded strings (common obfuscation)
97 b64_pattern = re.compile(rb'[A-Za-z0-9+/]{20,}={0,2}')
98 b64_decoded = []
99 for match in b64_pattern.finditer(data):
100 try:
101 decoded = base64.b64decode(match.group())
102 text = decoded.decode('utf-8', errors='strict')
103 if text.isprintable() and len(text) > 5:
104 b64_decoded.append(text)
105 except Exception:
106 pass
107
108 if b64_decoded:
109 results["base64_decoded_strings"] = b64_decoded[:30]
110
111 return results
112
113
114def decrypt_agenttesla_strings(data, key_hex):
115 """Decrypt Agent Tesla encrypted configuration strings."""
116 key = bytes.fromhex(key_hex)
117 # Agent Tesla V1: Simple XOR with key
118 decrypted_strings = []
119
120 # Find encrypted blobs (high-entropy byte sequences)
121 blob_pattern = re.compile(rb'[\x80-\xff]{16,256}')
122 for match in blob_pattern.finditer(data):
123 blob = match.group()
124 # Try XOR decryption
125 decrypted = bytes(b ^ key[i % len(key)] for i, b in enumerate(blob))
126 try:
127 text = decrypted.decode('utf-8', errors='strict')
128 if text.isprintable() and len(text.strip()) > 3:
129 decrypted_strings.append(text.strip())
130 except UnicodeDecodeError:
131 pass
132
133 # V2: SHA256-based key derivation then AES
134 sha256_key = hashlib.sha256(key).digest()
135
136 return decrypted_strings
137
138
139def analyze_exfiltration_config(config):
140 """Analyze extracted configuration for exfiltration methods."""
141 methods = []
142
143 if config.get("smtp_server"):
144 methods.append({
145 "type": "SMTP",
146 "servers": config["smtp_server"],
147 "emails": config.get("email", []),
148 })
149
150 if config.get("ftp_url"):
151 methods.append({
152 "type": "FTP",
153 "urls": config["ftp_url"],
154 })
155
156 if config.get("telegram_token"):
157 methods.append({
158 "type": "Telegram",
159 "tokens": config["telegram_token"],
160 "chat_ids": config.get("telegram_chat", []),
161 })
162
163 if config.get("discord_webhook"):
164 methods.append({
165 "type": "Discord",
166 "webhooks": config["discord_webhook"],
167 })
168
169 return methods
170
171
172if __name__ == "__main__":
173 if len(sys.argv) < 2:
174 print(f"Usage: {sys.argv[0]} <agent_tesla_sample>")
175 sys.exit(1)
176
177 config = extract_strings_from_dotnet(sys.argv[1])
178 methods = analyze_exfiltration_config(config)
179
180 report = {"raw_config": config, "exfiltration_methods": methods}
181 print(json.dumps(report, indent=2))
182```
183
184## Validation Criteria
185
186- Exfiltration method identified (SMTP/FTP/Telegram/Discord)
187- Server addresses and credentials extracted from config
188- Targeted applications list recovered
189- Keylogger and screenshot capture settings documented
190- Persistence mechanism identified
191- IOCs suitable for network blocking extracted
192
193## References
194
195- [Splunk - Agent Tesla Detection and Analysis](https://www.splunk.com/en_us/blog/security/inside-the-mind-of-a-rat-agent-tesla-detection-and-analysis.html)
196- [Qualys - Catching the RAT Agent Tesla](https://blog.qualys.com/vulnerabilities-threat-research/2022/02/02/catching-the-rat-called-agent-tesla)
197- [ANY.RUN Agent Tesla Analysis](https://any.run/malware-trends/agenttesla/)
198- [Trustwave - Agent Tesla Novel Loader](https://www.trustwave.com/en-us/resources/blogs/spiderlabs-blog/agent-teslas-new-ride-the-rise-of-a-novel-loader/)
199- [Malpedia - Agent Tesla](https://malpedia.caad.fkie.fraunhofer.de/details/win.agent_tesla)