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
Trigger phrases:
"extracting config from agent tesla rat"
"Extract embedded configuration from Agent Tesla RAT samples including SMTP/FTP/T"
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
- Scope the task — define objectives, boundaries, and success criteria
- Gather information — collect all necessary data and context before proceeding
- Execute the core workflow — follow the domain-specific steps methodically
- Validate results — verify outputs against expected outcomes or baselines
- Document findings — record results, anomalies, and recommendations
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
When NOT to Use
- You need to analyze extracted data (use analyzing-* skills)
- Task is about detecting extraction (use detecting-* skills)
- You need to implement extraction tools (use implementing-* skills)
- Task is about building extraction infrastructure (use building-* skills)
- You don't have access to forensic images
- Task requires chain of custody (follow forensic process)
Red Flags
- Performing actions without explicit written authorization from the asset owner
- Testing against production systems without a defined scope and rules of engagement
- Sharing sensitive findings or credentials in unencrypted communications
- Failing to properly scope and contain the assessment before starting
Verification
- All steps executed successfully against a test environment before production use
- Output documented with screenshots or logs demonstrating expected behavior
- Results validated against known-good baselines or reference implementations
- Documentation complete enough for another analyst to reproduce findings
References
Process
- Analyze the task requirements
- Apply domain expertise
- Verify output quality
Anti-Rationalization Table
| Rationalization |
Reality |
| "We are too small to be targeted" |
Automated attacks target everyone. Size does not matter. |
| "Security slows us down" |
A breach slows you down 100x more. Build security in from the start. |
| "We will fix it after launch" |
Vulnerabilities in production are exploited within hours. Fix before deploy. |
1---2name: extracting-config-from-agent-tesla-rat3description: Use when extract embedded configuration from Agent Tesla RAT samples4 including SMTP/FTP/Telegram exfiltration credentials, keylogger settings, and C25 endpoints using .NET decompilation and memory analysis. Use when working with extracting6 config from agent tesla rat.7domain: cybersecurity8subdomain: malware-analysis9tags:10- agent-tesla11- rat12- config-extraction13- dotnet14- malware-analysis15- keylogger16- credential-theft17version: '1.0'18author: oyi7719license: Apache-2.020atlas_techniques:21- AML.T002422- AML.T005623- AML.T008624nist_ai_rmf:25- GOVERN-1.126- MEASURE-2.727- MANAGE-3.128nist_csf:29- DE.AE-0230- RS.AN-0331- ID.RA-0132- DE.CM-0133category: cybersecurity34metadata:35 source: https://skillmd.com/skills/oyi77/extracting-config-from-agent-tesla-rat36---3738# Extracting Config from Agent Tesla RAT3940## Overview4142Agent 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.434445## When to Use46**Trigger phrases:**47- "extracting config from agent tesla rat"48- "Extract embedded configuration from Agent Tesla RAT samples including SMTP/FTP/T"495051- When performing authorized security testing that involves extracting config from agent tesla rat52- When analyzing malware samples or attack artifacts in a controlled environment53- When conducting red team exercises or penetration testing engagements54- When building detection capabilities based on offensive technique understanding5556## Prerequisites5758- dnSpy or ILSpy for .NET decompilation59- Python 3.9+ with `dnlib` or `pythonnet` for automated extraction60- de4dot for .NET deobfuscation61- Understanding of .NET IL code and Reflection62- Sandbox for dynamic analysis (ANY.RUN, CAPE)6364## Workflow65661. **Scope the task** — define objectives, boundaries, and success criteria672. **Gather information** — collect all necessary data and context before proceeding683. **Execute the core workflow** — follow the domain-specific steps methodically694. **Validate results** — verify outputs against expected outcomes or baselines705. **Document findings** — record results, anomalies, and recommendations71### Step 1: Deobfuscate and Extract Configuration7273```python74#!/usr/bin/env python375"""Extract Agent Tesla RAT configuration from .NET assemblies."""76import re77import sys78import json79import base6480import hashlib81from pathlib import Path828384def extract_strings_from_dotnet(filepath):85 """Extract readable strings from .NET binary for config analysis."""86 with open(filepath, 'rb') as f:87 data = f.read()8889 # Extract US (User Strings) heap from .NET metadata90 strings = []9192 # Look for common Agent Tesla config patterns93 patterns = {94 "smtp_server": re.compile(rb'smtp[\.\-][\w\.\-]+\.\w{2,}', re.I),95 "email": re.compile(rb'[\w\.\-]+@[\w\.\-]+\.\w{2,}'),96 "ftp_url": re.compile(rb'ftp://[\w\.\-:/]+', re.I),97 "telegram_token": re.compile(rb'\d{8,10}:[A-Za-z0-9_-]{35}'),98 "telegram_chat": re.compile(rb'(?:chat_id=|chatid[=:])[\-]?\d{5,15}', re.I),99 "discord_webhook": re.compile(rb'https://discord\.com/api/webhooks/\d+/[\w-]+'),100 "password": re.compile(rb'(?:pass(?:word)?|pwd)[=:]\s*[\w!@#$%^&*]{4,}', re.I),101 "port": re.compile(rb'(?:port|smtp_port)[=:]\s*\d{2,5}', re.I),102 }103104 results = {}105 for name, pattern in patterns.items():106 matches = pattern.findall(data)107 if matches:108 results[name] = [m.decode('utf-8', errors='replace') for m in matches]109110 # Extract Base64-encoded strings (common obfuscation)111 b64_pattern = re.compile(rb'[A-Za-z0-9+/]{20,}={0,2}')112 b64_decoded = []113 for match in b64_pattern.finditer(data):114 try:115 decoded = base64.b64decode(match.group())116 text = decoded.decode('utf-8', errors='strict')117 if text.isprintable() and len(text) > 5:118 b64_decoded.append(text)119 except Exception:120 pass121122 if b64_decoded:123 results["base64_decoded_strings"] = b64_decoded[:30]124125 return results126127128def decrypt_agenttesla_strings(data, key_hex):129 """Decrypt Agent Tesla encrypted configuration strings."""130 key = bytes.fromhex(key_hex)131 # Agent Tesla V1: Simple XOR with key132 decrypted_strings = []133134 # Find encrypted blobs (high-entropy byte sequences)135 blob_pattern = re.compile(rb'[\x80-\xff]{16,256}')136 for match in blob_pattern.finditer(data):137 blob = match.group()138 # Try XOR decryption139 decrypted = bytes(b ^ key[i % len(key)] for i, b in enumerate(blob))140 try:141 text = decrypted.decode('utf-8', errors='strict')142 if text.isprintable() and len(text.strip()) > 3:143 decrypted_strings.append(text.strip())144 except UnicodeDecodeError:145 pass146147 # V2: SHA256-based key derivation then AES148 sha256_key = hashlib.sha256(key).digest()149150 return decrypted_strings151152153def analyze_exfiltration_config(config):154 """Analyze extracted configuration for exfiltration methods."""155 methods = []156157 if config.get("smtp_server"):158 methods.append({159 "type": "SMTP",160 "servers": config["smtp_server"],161 "emails": config.get("email", []),162 })163164 if config.get("ftp_url"):165 methods.append({166 "type": "FTP",167 "urls": config["ftp_url"],168 })169170 if config.get("telegram_token"):171 methods.append({172 "type": "Telegram",173 "tokens": config["telegram_token"],174 "chat_ids": config.get("telegram_chat", []),175 })176177 if config.get("discord_webhook"):178 methods.append({179 "type": "Discord",180 "webhooks": config["discord_webhook"],181 })182183 return methods184185186if __name__ == "__main__":187 if len(sys.argv) < 2:188 print(f"Usage: {sys.argv[0]} <agent_tesla_sample>")189 sys.exit(1)190191 config = extract_strings_from_dotnet(sys.argv[1])192 methods = analyze_exfiltration_config(config)193194 report = {"raw_config": config, "exfiltration_methods": methods}195 print(json.dumps(report, indent=2))196```197198## Validation Criteria199200- Exfiltration method identified (SMTP/FTP/Telegram/Discord)201- Server addresses and credentials extracted from config202- Targeted applications list recovered203- Keylogger and screenshot capture settings documented204- Persistence mechanism identified205- IOCs suitable for network blocking extracted206207## When NOT to Use208209- You need to analyze extracted data (use analyzing-* skills)210- Task is about detecting extraction (use detecting-* skills)211- You need to implement extraction tools (use implementing-* skills)212- Task is about building extraction infrastructure (use building-* skills)213- You don't have access to forensic images214- Task requires chain of custody (follow forensic process)215216217## Red Flags218219- Performing actions without explicit written authorization from the asset owner220- Testing against production systems without a defined scope and rules of engagement221- Sharing sensitive findings or credentials in unencrypted communications222- Failing to properly scope and contain the assessment before starting223224## Verification225226- All steps executed successfully against a test environment before production use227- Output documented with screenshots or logs demonstrating expected behavior228- Results validated against known-good baselines or reference implementations229- Documentation complete enough for another analyst to reproduce findings230231## References232233- [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)234- [Qualys - Catching the RAT Agent Tesla](https://blog.qualys.com/vulnerabilities-threat-research/2022/02/02/catching-the-rat-called-agent-tesla)235- [ANY.RUN Agent Tesla Analysis](https://any.run/malware-trends/agenttesla/)236- [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/)237- [Malpedia - Agent Tesla](https://malpedia.caad.fkie.fraunhofer.de/details/win.agent_tesla)238239## Process2402411. Analyze the task requirements2422. Apply domain expertise2433. Verify output quality244245## Anti-Rationalization Table246247| Rationalization | Reality |248|---|---|249| "We are too small to be targeted" | Automated attacks target everyone. Size does not matter. |250| "Security slows us down" | A breach slows you down 100x more. Build security in from the start. |251| "We will fix it after launch" | Vulnerabilities in production are exploited within hours. Fix before deploy. |