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.
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)
Practical Steps
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-rat3description: Extract embedded configuration from Agent Tesla RAT samples including SMTP/FTP/Telegram exfiltration credentials, keylogger settings, and C2 endpoints using .NET decompilation and memory analysis.4license: Apache-2.05---6# Extracting Config from Agent Tesla RAT78## Overview910Agent 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.1112## Prerequisites1314- dnSpy or ILSpy for .NET decompilation15- Python 3.9+ with `dnlib` or `pythonnet` for automated extraction16- de4dot for .NET deobfuscation17- Understanding of .NET IL code and Reflection18- Sandbox for dynamic analysis (ANY.RUN, CAPE)1920## Practical Steps2122### Step 1: Deobfuscate and Extract Configuration2324```python25#!/usr/bin/env python326"""Extract Agent Tesla RAT configuration from .NET assemblies."""27import re28import sys29import json30import base6431import hashlib32from pathlib import Path333435def extract_strings_from_dotnet(filepath):36 """Extract readable strings from .NET binary for config analysis."""37 with open(filepath, 'rb') as f:38 data = f.read()3940 # Extract US (User Strings) heap from .NET metadata41 strings = []4243 # Look for common Agent Tesla config patterns44 patterns = {45 "smtp_server": re.compile(rb'smtp[\.\-][\w\.\-]+\.\w{2,}', re.I),46 "email": re.compile(rb'[\w\.\-]+@[\w\.\-]+\.\w{2,}'),47 "ftp_url": re.compile(rb'ftp://[\w\.\-:/]+', re.I),48 "telegram_token": re.compile(rb'\d{8,10}:[A-Za-z0-9_-]{35}'),49 "telegram_chat": re.compile(rb'(?:chat_id=|chatid[=:])[\-]?\d{5,15}', re.I),50 "discord_webhook": re.compile(rb'https://discord\.com/api/webhooks/\d+/[\w-]+'),51 "password": re.compile(rb'(?:pass(?:word)?|pwd)[=:]\s*[\w!@#$%^&*]{4,}', re.I),52 "port": re.compile(rb'(?:port|smtp_port)[=:]\s*\d{2,5}', re.I),53 }5455 results = {}56 for name, pattern in patterns.items():57 matches = pattern.findall(data)58 if matches:59 results[name] = [m.decode('utf-8', errors='replace') for m in matches]6061 # Extract Base64-encoded strings (common obfuscation)62 b64_pattern = re.compile(rb'[A-Za-z0-9+/]{20,}={0,2}')63 b64_decoded = []64 for match in b64_pattern.finditer(data):65 try:66 decoded = base64.b64decode(match.group())67 text = decoded.decode('utf-8', errors='strict')68 if text.isprintable() and len(text) > 5:69 b64_decoded.append(text)70 except Exception:71 pass7273 if b64_decoded:74 results["base64_decoded_strings"] = b64_decoded[:30]7576 return results777879def decrypt_agenttesla_strings(data, key_hex):80 """Decrypt Agent Tesla encrypted configuration strings."""81 key = bytes.fromhex(key_hex)82 # Agent Tesla V1: Simple XOR with key83 decrypted_strings = []8485 # Find encrypted blobs (high-entropy byte sequences)86 blob_pattern = re.compile(rb'[\x80-\xff]{16,256}')87 for match in blob_pattern.finditer(data):88 blob = match.group()89 # Try XOR decryption90 decrypted = bytes(b ^ key[i % len(key)] for i, b in enumerate(blob))91 try:92 text = decrypted.decode('utf-8', errors='strict')93 if text.isprintable() and len(text.strip()) > 3:94 decrypted_strings.append(text.strip())95 except UnicodeDecodeError:96 pass9798 # V2: SHA256-based key derivation then AES99 sha256_key = hashlib.sha256(key).digest()100101 return decrypted_strings102103104def analyze_exfiltration_config(config):105 """Analyze extracted configuration for exfiltration methods."""106 methods = []107108 if config.get("smtp_server"):109 methods.append({110 "type": "SMTP",111 "servers": config["smtp_server"],112 "emails": config.get("email", []),113 })114115 if config.get("ftp_url"):116 methods.append({117 "type": "FTP",118 "urls": config["ftp_url"],119 })120121 if config.get("telegram_token"):122 methods.append({123 "type": "Telegram",124 "tokens": config["telegram_token"],125 "chat_ids": config.get("telegram_chat", []),126 })127128 if config.get("discord_webhook"):129 methods.append({130 "type": "Discord",131 "webhooks": config["discord_webhook"],132 })133134 return methods135136137if __name__ == "__main__":138 if len(sys.argv) < 2:139 print(f"Usage: {sys.argv[0]} <agent_tesla_sample>")140 sys.exit(1)141142 config = extract_strings_from_dotnet(sys.argv[1])143 methods = analyze_exfiltration_config(config)144145 report = {"raw_config": config, "exfiltration_methods": methods}146 print(json.dumps(report, indent=2))147```148149## Validation Criteria150151- Exfiltration method identified (SMTP/FTP/Telegram/Discord)152- Server addresses and credentials extracted from config153- Targeted applications list recovered154- Keylogger and screenshot capture settings documented155- Persistence mechanism identified156- IOCs suitable for network blocking extracted157158## References159160- [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)161- [Qualys - Catching the RAT Agent Tesla](https://blog.qualys.com/vulnerabilities-threat-research/2022/02/02/catching-the-rat-called-agent-tesla)162- [ANY.RUN Agent Tesla Analysis](https://any.run/malware-trends/agenttesla/)163- [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/)164- [Malpedia - Agent Tesla](https://malpedia.caad.fkie.fraunhofer.de/details/win.agent_tesla)