Buckets:

download
raw
28.9 kB
#!/usr/bin/env python3
"""
Forensics Expert Persona - Specialized in Digital Forensics and Incident Response
Part of the Zen-AI-Pentest Multi-Agent System
Author: SHAdd0WTAka
"""
import hashlib
import logging
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional
from agents.agent_base import AgentMessage, AgentRole, BaseAgent
logger = logging.getLogger("ZenAI.Personas")
class ForensicsExpertPersona(BaseAgent):
"""
Forensics Expert - Specialized in digital forensics, log analysis, and incident response.
Expertise:
- Log Analysis (Windows Event Logs, Syslog, Application Logs)
- Memory Forensics (RAM dump analysis)
- Disk/Image Forensics
- Network Forensics (PCAP analysis)
- Timeline Analysis
- Malware Analysis
- Evidence Collection and Chain of Custody
- File Carving and Recovery
- Registry Analysis (Windows)
Tools:
- Volatility: Memory forensics framework
- Autopsy: Digital forensics platform
- Sleuth Kit: File system analysis
- Plaso/Log2Timeline: Timeline creation
- YARA: Malware pattern matching
- Rekall: Memory analysis framework
- Redline: Endpoint analysis
- OSQuery: Endpoint visibility
- ELK Stack: Log aggregation and analysis
"""
name = "Forensics Expert"
description = "Specialized in digital forensics, log analysis, and incident response"
expertise = [
"Log Analysis and Correlation",
"Memory Forensics",
"Disk Forensics",
"Network Forensics",
"Timeline Analysis",
"Malware Analysis",
"Evidence Collection",
"Chain of Custody",
"File Carving",
"Registry Analysis",
"Artifact Extraction",
"Incident Response",
"Threat Hunting",
"IOC Creation",
]
tools = [
"volatility",
"autopsy",
"sleuthkit",
"plaso",
"log2timeline",
"yara",
"rekall",
"redline",
"osquery",
"elk",
"splunk",
"foremost",
"scalpel",
"bulk_extractor",
"strings",
"binwalk",
]
system_prompt = """You are a Digital Forensics Expert specializing in incident response and evidence analysis.
YOUR EXPERTISE:
- Digital evidence collection and preservation
- Log analysis across multiple sources
- Memory dump analysis and extraction
- Disk and file system forensics
- Network packet capture analysis
- Timeline reconstruction
- Malware detection and analysis
- Windows Registry analysis
- File carving and recovery
- Chain of custody management
- Threat hunting and IOC development
FORENSICS PRINCIPLES:
1. EVIDENCE INTEGRITY
- Calculate and verify hashes (MD5, SHA-1, SHA-256)
- Maintain chain of custody
- Document every action taken
- Work on copies, never original evidence
2. SYSTEMATIC APPROACH
- Identify → Preserve → Analyze → Present
- Document timeline of events
- Correlate evidence across sources
- Maintain detailed case notes
3. LEGAL COMPLIANCE
- Follow legal procedures for evidence handling
- Maintain admissibility standards
- Document tools and versions used
- Ensure reproducibility of results
LOG ANALYSIS METHODOLOGY:
1. COLLECTION
- Identify log sources (OS, application, network)
- Ensure proper time synchronization
- Collect logs with integrity verification
2. NORMALIZATION
- Parse different log formats
- Normalize timestamps to common timezone
- Extract key fields
3. CORRELATION
- Match events across log sources
- Identify attack patterns
- Build timeline of activities
4. ANALYSIS
- Look for anomalies and indicators
- Identify attacker TTPs
- Map to MITRE ATT&CK framework
MEMORY FORENSICS:
- Process enumeration and analysis
- Network connection analysis
- DLL injection detection
- Rootkit detection
- Credential extraction (LSASS dumps)
- Volatile data collection
DISK FORENSICS:
- Partition and file system analysis
- Deleted file recovery
- File metadata examination
- Alternate Data Streams (ADS)
- Volume Shadow Copy analysis
- BitLocker/encryption analysis
WINDOWS FORENSICS ARTIFACTS:
- Registry hives (SAM, SYSTEM, SOFTWARE, NTUSER.DAT)
- Event Logs (Security, System, Application)
- Prefetch files
- LNK files
- Jump Lists
- Shellbags
- AmCache
- SRUM (System Resource Usage Monitor)
- Recent Files
- Browser artifacts
NETWORK FORENSICS:
- PCAP analysis
- Connection reconstruction
- Protocol analysis
- Exfiltration detection
- C2 communication identification
INDICATORS OF COMPROMISE (IOCs):
- File hashes (MD5, SHA-1, SHA-256)
- File paths and names
- Registry keys
- Network indicators (IPs, domains, URLs)
- Mutex names
- Service names
- Process names
- YARA rules
RULES:
- ALWAYS verify evidence integrity with hashes
- NEVER modify original evidence
- Document all actions with timestamps
- Maintain chain of custody documentation
- Use validated and tested tools
- Preserve volatile data first
- Follow legal and ethical guidelines
- Create working copies for analysis
EVIDENCE HANDLING CHECKLIST:
□ Identify evidence source and type
□ Photograph/document system state
□ Collect volatile data first (memory, network)
□ Calculate hash of original evidence
□ Create forensic image/bit-for-bit copy
□ Verify copy integrity with hash comparison
□ Store original evidence securely
□ Work only on forensic copies
□ Document all tools and versions
□ Maintain detailed activity logs
MEMORY ANALYSIS CHECKLIST:
□ Identify operating system and version
□ List running processes
□ Check for hidden/unlinked processes
□ Analyze network connections
□ Check for code injection
□ Examine loaded DLLs
□ Look for suspicious drivers
□ Extract credentials (if authorized)
□ Check for rootkit artifacts
□ Dump suspicious process memory
LOG ANALYSIS CHECKLIST:
□ Identify time range of incident
□ Normalize timestamps
□ Filter for relevant events
□ Look for authentication anomalies
□ Check for privilege escalation
□ Identify lateral movement
□ Look for data exfiltration
□ Correlate events across sources
□ Build detailed timeline
REPORT FORMAT:
1. Executive Summary
2. Investigation Scope and Objectives
3. Evidence Details (with hashes)
4. Timeline of Events
5. Findings and Analysis
6. IOCs identified
7. Recommendations
8. Appendices (tool output, logs)
"""
def __init__(self, name: str = "Forensics Expert", orchestrator=None, zen_orchestrator=None):
super().__init__(name, AgentRole.ANALYST, orchestrator)
self.zen_orchestrator = zen_orchestrator
self.evidence_store = {}
self.timeline_events = []
# Register message handlers
self.register_handler("memory_analyze", self._handle_memory_analyze)
self.register_handler("log_analyze", self._handle_log_analyze)
self.register_handler("disk_forensics", self._handle_disk_forensics)
self.register_handler("network_forensics", self._handle_network_forensics)
self.register_handler("timeline_create", self._handle_timeline_create)
self.register_handler("malware_analyze", self._handle_malware_analyze)
self.register_handler("evidence_collect", self._handle_evidence_collect)
self.register_handler("ioc_extract", self._handle_ioc_extract)
async def _handle_memory_analyze(self, msg: AgentMessage):
"""Handle memory dump analysis"""
dump_path = msg.context.get("dump_path")
profile = msg.context.get("profile") # Volatility profile
logger.info(f"[ForensicsExpert:{self.name}] Analyzing memory dump: {dump_path}")
results = await self._analyze_memory_dump(dump_path, profile)
await self.send_message(
content=f"Memory analysis complete. Suspicious processes: {len(results['suspicious_processes'])}",
recipient=msg.sender,
msg_type="memory_analysis_results",
context={"results": results},
)
async def _handle_log_analyze(self, msg: AgentMessage):
"""Handle log file analysis"""
log_path = msg.context.get("log_path")
log_type = msg.context.get("log_type", "auto") # windows, linux, apache, etc.
time_range = msg.context.get("time_range")
logger.info(f"[ForensicsExpert:{self.name}] Analyzing logs: {log_path}")
results = await self._analyze_logs(log_path, log_type, time_range)
await self.send_message(
content=f"Log analysis complete. Events found: {len(results['events'])}, Suspicious: {len(results['suspicious'])}",
recipient=msg.sender,
msg_type="log_analysis_results",
context={"results": results},
)
async def _handle_disk_forensics(self, msg: AgentMessage):
"""Handle disk/image forensics"""
image_path = msg.context.get("image_path")
partition = msg.context.get("partition")
logger.info(f"[ForensicsExpert:{self.name}] Analyzing disk image: {image_path}")
results = await self._analyze_disk_image(image_path, partition)
await self.send_message(
content=f"Disk analysis complete. Files recovered: {len(results['recovered_files'])}",
recipient=msg.sender,
msg_type="disk_forensics_results",
context={"results": results},
)
async def _handle_network_forensics(self, msg: AgentMessage):
"""Handle network forensics (PCAP analysis)"""
pcap_path = msg.context.get("pcap_path")
logger.info(f"[ForensicsExpert:{self.name}] Analyzing PCAP: {pcap_path}")
results = await self._analyze_pcap(pcap_path)
await self.send_message(
content=f"PCAP analysis complete. Suspicious connections: {len(results['suspicious_connections'])}",
recipient=msg.sender,
msg_type="network_forensics_results",
context={"results": results},
)
async def _handle_timeline_create(self, msg: AgentMessage):
"""Handle timeline creation from multiple sources"""
sources = msg.context.get("sources", []) # List of evidence sources
start_time = msg.context.get("start_time")
end_time = msg.context.get("end_time")
logger.info(f"[ForensicsExpert:{self.name}] Creating timeline from {len(sources)} sources")
timeline = await self._create_timeline(sources, start_time, end_time)
await self.send_message(
content=f"Timeline created. Total events: {len(timeline['events'])}",
recipient=msg.sender,
msg_type="timeline_results",
context={"timeline": timeline},
)
async def _handle_malware_analyze(self, msg: AgentMessage):
"""Handle malware sample analysis"""
sample_path = msg.context.get("sample_path")
sample_hash = msg.context.get("hash")
logger.info(f"[ForensicsExpert:{self.name}] Analyzing malware sample")
results = await self._analyze_malware(sample_path, sample_hash)
await self.send_message(
content=f"Malware analysis complete. Threat level: {results['threat_level']}",
recipient=msg.sender,
msg_type="malware_analysis_results",
context={"results": results},
)
async def _handle_evidence_collect(self, msg: AgentMessage):
"""Handle evidence collection"""
source = msg.context.get("source")
evidence_type = msg.context.get("evidence_type")
logger.info(f"[ForensicsExpert:{self.name}] Collecting evidence: {evidence_type}")
results = await self._collect_evidence(source, evidence_type)
await self.send_message(
content=f"Evidence collected. Hash: {results['hash']}",
recipient=msg.sender,
msg_type="evidence_collection_results",
context={"results": results},
)
async def _handle_ioc_extract(self, msg: AgentMessage):
"""Handle IOC extraction from analysis results"""
analysis_results = msg.context.get("analysis_results", [])
logger.info(f"[ForensicsExpert:{self.name}] Extracting IOCs")
iocs = await self._extract_iocs(analysis_results)
await self.send_message(
content=f"IOCs extracted. Total: {len(iocs['all'])}",
recipient=msg.sender,
msg_type="ioc_extraction_results",
context={"iocs": iocs},
)
async def _analyze_memory_dump(self, dump_path: str, profile: Optional[str]) -> Dict[str, Any]:
"""Analyze memory dump using Volatility-style analysis"""
results = {
"dump_path": dump_path,
"profile": profile or "unknown",
"processes": [],
"network_connections": [],
"suspicious_processes": [],
"injected_code": [],
"extracted_credentials": [],
"loaded_dlls": {},
"kernel_modules": [],
}
# Simulate process enumeration
sample_processes = [
{"pid": 4, "name": "System", "ppid": 0, "suspicious": False},
{"pid": 332, "name": "svchost.exe", "ppid": 4, "suspicious": False},
{
"pid": 1234,
"name": "malware.exe",
"ppid": 332,
"suspicious": True,
"reason": "Unknown executable in system directory",
},
{"pid": 5678, "name": "lsass.exe", "ppid": 4, "suspicious": False},
]
for proc in sample_processes:
results["processes"].append(proc)
if proc.get("suspicious"):
results["suspicious_processes"].append(proc)
# Simulate network connections
results["network_connections"] = [
{
"pid": 1234,
"local": "192.168.1.100:49152",
"remote": "185.220.101.42:443",
"state": "ESTABLISHED",
"suspicious": True,
},
{"pid": 5678, "local": "0.0.0.0:445", "remote": "0.0.0.0:0", "state": "LISTENING", "suspicious": False},
]
return results
async def _analyze_logs(self, log_path: str, log_type: str, time_range: Optional[Dict]) -> Dict[str, Any]:
"""Analyze log files"""
results = {"log_path": log_path, "log_type": log_type, "events": [], "suspicious": [], "statistics": {}}
# Simulate log parsing based on type
if log_type == "windows_security":
events = [
{
"timestamp": "2026-03-31T10:00:00Z",
"event_id": 4624,
"type": "Logon",
"account": "DOMAIN\\admin",
"ip": "192.168.1.50",
},
{
"timestamp": "2026-03-31T10:05:00Z",
"event_id": 4625,
"type": "Failed Logon",
"account": "DOMAIN\\admin",
"ip": "10.0.0.99",
},
{
"timestamp": "2026-03-31T10:10:00Z",
"event_id": 4672,
"type": "Special Privileges",
"account": "DOMAIN\\hacker",
"suspicious": True,
},
]
elif log_type == "apache":
events = [
{
"timestamp": "2026-03-31T10:00:00Z",
"ip": "192.168.1.1",
"method": "GET",
"path": "/index.html",
"status": 200,
},
{
"timestamp": "2026-03-31T10:01:00Z",
"ip": "10.0.0.99",
"method": "POST",
"path": "/login.php",
"status": 200,
},
{
"timestamp": "2026-03-31T10:02:00Z",
"ip": "10.0.0.99",
"method": "GET",
"path": "/admin/config.php",
"status": 200,
"suspicious": True,
},
]
else:
events = [
{"timestamp": "2026-03-31T10:00:00Z", "message": "System boot", "suspicious": False},
{"timestamp": "2026-03-31T10:05:00Z", "message": "SSH login from unknown host", "suspicious": True},
]
results["events"] = events
results["suspicious"] = [e for e in events if e.get("suspicious")]
results["statistics"]["total_events"] = len(events)
results["statistics"]["suspicious_events"] = len(results["suspicious"])
return results
async def _analyze_disk_image(self, image_path: str, partition: Optional[str]) -> Dict[str, Any]:
"""Analyze disk image"""
results = {
"image_path": image_path,
"partition": partition,
"file_system": "NTFS",
"recovered_files": [],
"deleted_files": [],
"artifacts": {},
}
# Simulate file recovery
results["recovered_files"] = [
{"name": "deleted_document.docx", "path": "/Users/Admin/Documents/", "size": 24576, "recovered": True},
{"name": "suspicious.exe", "path": "/Windows/Temp/", "size": 1048576, "recovered": True, "suspicious": True},
]
# Simulate Windows artifacts
results["artifacts"] = {
"registry": ["SAM", "SYSTEM", "SOFTWARE"],
"prefetch": ["NOTEPAD.EXE-12345678.pf", "MALWARE.EXE-87654321.pf"],
"event_logs": ["Security.evtx", "System.evtx", "Application.evtx"],
"browser_history": ["History", "Cookies", "Login Data"],
}
return results
async def _analyze_pcap(self, pcap_path: str) -> Dict[str, Any]:
"""Analyze PCAP file"""
results = {
"pcap_path": pcap_path,
"total_packets": 0,
"protocols": {},
"connections": [],
"suspicious_connections": [],
"dns_queries": [],
"http_requests": [],
"files_extracted": [],
}
# Simulate PCAP analysis
results["total_packets"] = 15432
results["protocols"] = {"TCP": 12000, "UDP": 3000, "ICMP": 432}
results["connections"] = [
{"src": "192.168.1.100:49152", "dst": "8.8.8.8:53", "protocol": "DNS", "packets": 50},
{
"src": "192.168.1.100:49153",
"dst": "185.220.101.42:443",
"protocol": "HTTPS",
"packets": 1500,
"suspicious": True,
},
{"src": "192.168.1.100:49154", "dst": "13.107.42.14:443", "protocol": "HTTPS", "packets": 500},
]
results["suspicious_connections"] = [c for c in results["connections"] if c.get("suspicious")]
results["dns_queries"] = [
{"query": "google.com", "type": "A"},
{"query": "malicious-c2.example.com", "type": "A", "suspicious": True},
]
return results
async def _create_timeline(
self, sources: List[Dict], start_time: Optional[str], end_time: Optional[str]
) -> Dict[str, Any]:
"""Create timeline from multiple sources"""
timeline = {"start_time": start_time, "end_time": end_time, "sources": [s.get("type") for s in sources], "events": []}
# Simulate timeline events
events = [
{
"timestamp": "2026-03-31T09:00:00Z",
"source": "logs",
"type": "Initial Access",
"description": "Suspicious login from external IP",
"ioc": "10.0.0.99",
},
{
"timestamp": "2026-03-31T09:15:00Z",
"source": "memory",
"type": "Execution",
"description": "Malware process started",
"ioc": "malware.exe",
},
{
"timestamp": "2026-03-31T09:30:00Z",
"source": "network",
"type": "C2",
"description": "Outbound connection to C2 server",
"ioc": "185.220.101.42",
},
{
"timestamp": "2026-03-31T10:00:00Z",
"source": "logs",
"type": "Persistence",
"description": "Registry key modified for persistence",
"ioc": "HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",
},
]
timeline["events"] = events
timeline["attack_phases"] = ["Initial Access", "Execution", "C2", "Persistence"]
return timeline
async def _analyze_malware(self, sample_path: Optional[str], sample_hash: Optional[str]) -> Dict[str, Any]:
"""Analyze malware sample"""
results = {
"sample_path": sample_path,
"hash_md5": sample_hash or hashlib.md5(b"sample", usedforsecurity=False).hexdigest(),
"hash_sha1": hashlib.sha256(b"sample", usedforsecurity=False).hexdigest(),
"hash_sha256": hashlib.sha256(b"sample").hexdigest(),
"file_type": "PE32 executable",
"threat_level": "high",
"capabilities": [],
"indicators": {},
"yara_matches": [],
}
results["capabilities"] = [
"Keylogging",
"Screenshot capture",
"File encryption",
"Network communication",
"Persistence mechanism",
]
results["indicators"] = {
"mutexes": ["Global\\MalwareMutex123"],
"files_created": ["C:\\Windows\\Temp\\malware.exe", "C:\\Users\\Admin\\AppData\\Roaming\\config.dat"],
"registry_keys": ["HKCU\\Software\\MalwareKey"],
"network_iocs": ["185.220.101.42", "malicious-c2.example.com"],
}
return results
async def _collect_evidence(self, source: str, evidence_type: str) -> Dict[str, Any]:
"""Collect and hash evidence"""
results = {
"source": source,
"evidence_type": evidence_type,
"collected_at": datetime.now(timezone.utc).isoformat(),
"hash_md5": "",
"hash_sha1": "",
"hash_sha256": "",
"chain_of_custody": {
"collected_by": self.name,
"collection_method": "forensic_imaging",
"storage_location": "secure_vault",
},
}
# Calculate hashes
sample_data = f"{source}:{evidence_type}".encode()
results["hash_md5"] = hashlib.md5(sample_data, usedforsecurity=False).hexdigest()
results["hash_sha1"] = hashlib.sha256(sample_data, usedforsecurity=False).hexdigest()
results["hash_sha256"] = hashlib.sha256(sample_data).hexdigest()
return results
async def _extract_iocs(self, analysis_results: List[Dict]) -> Dict[str, Any]:
"""Extract IOCs from analysis results"""
iocs = {
"hashes": [],
"ips": [],
"domains": [],
"urls": [],
"file_paths": [],
"registry_keys": [],
"mutexes": [],
"all": [],
}
for result in analysis_results:
# Extract file hashes
if "hash_md5" in result:
iocs["hashes"].append({"type": "md5", "value": result["hash_md5"]})
if "hash_sha256" in result:
iocs["hashes"].append({"type": "sha256", "value": result["hash_sha256"]})
# Extract network IOCs
if "indicators" in result:
indicators = result["indicators"]
iocs["ips"].extend(indicators.get("network_iocs", []))
iocs["domains"].extend(
[d for d in indicators.get("network_iocs", []) if "." in d and not d.replace(".", "").isdigit()]
)
iocs["file_paths"].extend(indicators.get("files_created", []))
iocs["registry_keys"].extend(indicators.get("registry_keys", []))
iocs["mutexes"].extend(indicators.get("mutexes", []))
# Build combined list
for category in ["hashes", "ips", "domains", "file_paths", "registry_keys", "mutexes"]:
iocs["all"].extend(iocs[category])
return iocs
def analyze(self, target: Optional[str], findings: List[Dict[str, Any]]) -> Dict[str, Any]:
"""
Persona-specific analysis logic for forensics findings.
Args:
target: The target system/case
findings: List of forensics findings
Returns:
Analysis results with incident timeline and IOCs
"""
analysis = {
"total_findings": len(findings),
"by_type": {},
"by_severity": {"critical": 0, "high": 0, "medium": 0, "low": 0, "info": 0},
"incident_confirmed": False,
"attack_phases": [],
"timeline_summary": [],
"iocs_extracted": [],
"recommendations": [],
}
# Categorize findings
for finding in findings:
f_type = finding.get("type", "unknown")
severity = finding.get("severity", "info").lower()
if f_type not in analysis["by_type"]:
analysis["by_type"][f_type] = []
analysis["by_type"][f_type].append(finding)
if severity in analysis["by_severity"]:
analysis["by_severity"][severity] += 1
# Check for incident indicators
if f_type in ["malware_detected", "c2_communication", "data_exfiltration"]:
analysis["incident_confirmed"] = True
# Determine attack phases
attack_phases = set()
for finding in findings:
phase = finding.get("attack_phase")
if phase:
attack_phases.add(phase)
analysis["attack_phases"] = list(attack_phases)
# Generate recommendations
analysis["recommendations"] = self._generate_forensics_recommendations(analysis)
return analysis
def _generate_forensics_recommendations(self, analysis: Dict[str, Any]) -> List[str]:
"""Generate forensics-specific recommendations"""
recommendations = []
if analysis["incident_confirmed"]:
recommendations.append("ISOLATE affected systems from the network immediately")
recommendations.append("PRESERVE all volatile evidence before isolation")
recommendations.append("NOTIFY incident response team and legal counsel")
if "malware_detected" in analysis["by_type"]:
recommendations.append("Deploy YARA rules across all endpoints to detect malware")
recommendations.append("Block identified IOCs at network perimeter")
if analysis["attack_phases"]:
recommendations.append(f"Investigate additional systems for attack phases: {', '.join(analysis['attack_phases'])}")
recommendations.append("Review and enhance logging for better future detection")
recommendations.append("Update incident response procedures based on findings")
return recommendations
async def execute_task(self, task: Dict) -> Dict:
"""Execute forensics analysis task"""
task_type = task.get("type", "")
context = task.get("context", {})
logger.info(f"[ForensicsExpert:{self.name}] Executing task: {task_type}")
if task_type == "memory_analysis":
results = await self._analyze_memory_dump(context.get("dump_path"), context.get("profile"))
analysis = self.analyze(context.get("target"), results.get("suspicious_processes", []))
return {"status": "complete", "results": results, "analysis": analysis, "agent": self.name}
elif task_type == "log_analysis":
results = await self._analyze_logs(
context.get("log_path"), context.get("log_type", "auto"), context.get("time_range")
)
return {"status": "complete", "results": results, "agent": self.name}
return {"status": "unknown_task"}

Xet Storage Details

Size:
28.9 kB
·
Xet hash:
41b7b8292a5439b7f132b623db6fb183ceb1d4eab70d2a9e5f2e911aff4f8bd9

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.