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