npx skills add mukul975/Anthropic-Cybersecurity-SkillsMITRE ATT&CK
NIST CSF 2.0
MITRE ATLAS
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
dnliborpythonnetfor 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
References and resources
Everything below is rendered for inspection. Script files are read-only and never run.
References 3
api-reference.md2.2 KB
API Reference: Agent Tesla RAT Configuration Extraction
Agent Tesla Overview
- Type: .NET RAT / Information Stealer
- Exfiltration: SMTP, FTP, Telegram, HTTP POST
- Capabilities: Keylogging, clipboard, screenshots, credential theft
String Extraction
Python Regex for ASCII Strings
re.finditer(rb'[\x20-\x7e]{6,}', binary_data)Wide Strings (UTF-16LE)
re.finditer(rb'(?:[\x20-\x7e]\x00){6,}', binary_data)Configuration Indicators
SMTP Exfiltration
| Field | Pattern |
|---|---|
| Server | smtp.gmail.com, smtp.yandex.com |
| Port | 587, 465, 25 |
[\w.+-]+@[\w-]+\.[\w.]+ |
|
| Password | Base64 or XOR encoded |
FTP Exfiltration
| Field | Pattern |
|---|---|
| Server | ftp.\w+\.\w+ |
| URI | ftp://user:pass@host/path |
Telegram Bot
| Field | Pattern |
|---|---|
| Bot Token | \d{8,12}:[A-Za-z0-9_-]{35} |
| Chat ID | \d{9,13} |
| API URL | api.telegram.org/bot{token}/sendDocument |
.NET Decompilation
dnSpy
# Open sample in dnSpy
# Navigate to namespace: AgentTesla / WebMonitor / etc.
# Look for hardcoded credentials in static fieldsILSpy / dotPeek
Alternative .NET decompilers for config extraction.
YARA Rule
rule AgentTesla {
meta:
description = "Agent Tesla keylogger/RAT"
strings:
$smtp = "SmtpPort" ascii wide
$hook = "KeyboardHook" ascii wide
$clip = "GetClipboardData" ascii wide
$ns1 = "AgentTesla" ascii
$ns2 = "WebMonitor" ascii
condition:
uint16(0) == 0x5A4D and 3 of them
}File Hashing
Python hashlib
import hashlib
sha256 = hashlib.sha256(open(path, 'rb').read()).hexdigest()VirusTotal API — Sample Lookup
GET https://www.virustotal.com/api/v3/files/{sha256}
x-apikey: {API_KEY}Response Fields
| Field | Description |
|---|---|
data.attributes.popular_threat_classification |
Malware family |
data.attributes.last_analysis_stats |
AV detection counts |
data.attributes.sandbox_verdicts |
Sandbox analysis results |
Sandbox Analysis
- ANY.RUN: Interactive analysis
- Hybrid Analysis: Automated report
- Joe Sandbox: Deep behavioral analysis
standards.md0.3 KB
Standards Reference - extracting-config-from-agent-tesla-rat
Applicable Standards
- MITRE ATT&CK Framework
- NIST SP 800-83 Guide to Malware Incident Prevention
- NIST SP 800-86 Guide to Integrating Forensic Techniques
Related MITRE ATT&CK Techniques
See SKILL.md for specific technique mappings.
workflows.md0.5 KB
Analysis Workflows - extracting-config-from-agent-tesla-rat
Primary Workflow
[Sample Collection] --> [Static Analysis] --> [Dynamic Analysis] --> [IOC Extraction]
|
v
[Report Generation]See SKILL.md for detailed step-by-step procedures.
Scripts 1
agent.py5.5 KB
#!/usr/bin/env python3
"""Agent for extracting configuration from Agent Tesla RAT samples (malware analysis)."""
import argparse
import base64
import hashlib
import json
import os
import re
from datetime import datetime, timezone
AGENT_TESLA_INDICATORS = {
"strings": [
"smtp.gmail.com", "smtp.yandex.com", "SmtpPort",
"KeyboardHook", "ClipboardLogger", "ScreenCapture",
"GetClipboardData", "GetForegroundWindow",
"Mozilla/5.0", "passwords.txt",
],
"namespaces": [
"AgentTesla", "WebMonitor", "HPDefender",
"GodMode", "AKStealer", "Origin Logger",
],
}
def compute_file_hashes(file_path):
"""Compute MD5, SHA1, SHA256 of a file."""
md5 = hashlib.md5()
sha1 = hashlib.sha1()
sha256 = hashlib.sha256()
with open(file_path, "rb") as f:
for chunk in iter(lambda: f.read(65536), b""):
md5.update(chunk)
sha1.update(chunk)
sha256.update(chunk)
return {
"md5": md5.hexdigest(),
"sha1": sha1.hexdigest(),
"sha256": sha256.hexdigest(),
}
def extract_strings(file_path, min_len=6):
"""Extract ASCII and wide strings from binary."""
strings = []
with open(file_path, "rb") as f:
data = f.read()
# ASCII strings
for match in re.finditer(rb'[\x20-\x7e]{%d,}' % min_len, data):
strings.append(match.group().decode("ascii", errors="replace"))
# Wide strings (UTF-16LE)
for match in re.finditer(rb'(?:[\x20-\x7e]\x00){%d,}' % min_len, data):
try:
strings.append(match.group().decode("utf-16-le", errors="replace"))
except UnicodeDecodeError:
pass
return strings
def find_smtp_config(strings_list):
"""Extract SMTP configuration from string artifacts."""
config = {"smtp_server": None, "smtp_port": None, "email": None, "password": None}
for s in strings_list:
if re.match(r'smtp\.\w+\.\w+', s, re.I):
config["smtp_server"] = s
if re.match(r'^\d{2,5}$', s) and int(s) in (25, 465, 587, 2525):
config["smtp_port"] = int(s)
if re.match(r'[\w.+-]+@[\w-]+\.[\w.]+', s):
config["email"] = s
return config
def find_ftp_config(strings_list):
"""Extract FTP exfiltration configuration."""
config = {"ftp_server": None, "ftp_user": None, "ftp_password": None}
for s in strings_list:
if re.match(r'ftp\.\w+\.\w+', s, re.I):
config["ftp_server"] = s
if "ftp://" in s.lower():
config["ftp_url"] = s
return config
def find_telegram_config(strings_list):
"""Extract Telegram bot exfiltration config."""
config = {"bot_token": None, "chat_id": None}
for s in strings_list:
if re.match(r'\d{8,12}:[A-Za-z0-9_-]{35}', s):
config["bot_token"] = s
if re.match(r'^-?\d{9,13}$', s):
config["chat_id"] = s
return config
def decode_base64_strings(strings_list):
"""Try to decode base64-encoded configuration strings."""
decoded = []
for s in strings_list:
if len(s) > 20 and re.match(r'^[A-Za-z0-9+/=]+$', s):
try:
d = base64.b64decode(s).decode("utf-8", errors="replace")
if any(c.isprintable() for c in d) and len(d) > 4:
decoded.append({"encoded": s[:40], "decoded": d[:100]})
except Exception:
pass
return decoded
def analyze_sample(file_path):
"""Full analysis of suspected Agent Tesla sample."""
hashes = compute_file_hashes(file_path)
strings = extract_strings(file_path)
indicators_found = []
for indicator in AGENT_TESLA_INDICATORS["strings"]:
if any(indicator.lower() in s.lower() for s in strings):
indicators_found.append(indicator)
smtp = find_smtp_config(strings)
ftp = find_ftp_config(strings)
telegram = find_telegram_config(strings)
b64_decoded = decode_base64_strings(strings)
return {
"file": file_path,
"file_size": os.path.getsize(file_path),
"hashes": hashes,
"agent_tesla_indicators": indicators_found,
"is_agent_tesla": len(indicators_found) >= 3,
"config": {
"smtp": smtp,
"ftp": ftp,
"telegram": telegram,
},
"base64_decoded": b64_decoded[:10],
"total_strings": len(strings),
}
def main():
parser = argparse.ArgumentParser(
description="Extract configuration from Agent Tesla RAT samples"
)
parser.add_argument("sample", help="Path to suspected Agent Tesla sample")
parser.add_argument("--output", "-o", help="Output JSON report")
parser.add_argument("--verbose", "-v", action="store_true")
args = parser.parse_args()
print("[*] Agent Tesla Configuration Extraction Agent")
result = analyze_sample(args.sample)
print(f"[*] SHA256: {result['hashes']['sha256']}")
print(f"[*] Agent Tesla indicators: {len(result['agent_tesla_indicators'])}")
print(f"[*] Likely Agent Tesla: {result['is_agent_tesla']}")
if result["config"]["smtp"]["smtp_server"]:
print(f"[*] SMTP C2: {result['config']['smtp']['smtp_server']}")
if result["config"]["telegram"]["bot_token"]:
print(f"[*] Telegram bot found")
report = {"timestamp": datetime.now(timezone.utc).isoformat(), "analysis": result}
if args.output:
with open(args.output, "w") as f:
json.dump(report, f, indent=2)
print(f"[*] Report saved to {args.output}")
else:
print(json.dumps(report, indent=2))
if __name__ == "__main__":
main()