npx skills add mukul975/Anthropic-Cybersecurity-SkillsMITRE ATT&CK
When to Use
- When reconstructing the timeline of a security incident from available log sources
- During post-breach investigation to identify initial access, lateral movement, and exfiltration
- When correlating events across multiple systems and log sources
- For establishing evidence of unauthorized access or policy violations
- When preparing forensic reports requiring detailed event chronology
Prerequisites
- Access to collected log files (Windows Event Logs, syslog, application logs)
- Log parsing tools (LogParser, jq, awk, or ELK stack)
- Understanding of log formats (EVTX, syslog, JSON, CSV)
- NTP-synchronized timestamps across all log sources for correlation
- Sufficient storage for log aggregation and indexing
- Timeline analysis tools (log2timeline, Plaso)
Workflow
Step 1: Collect and Preserve Log Sources
# Create case log directory structure
mkdir -p /cases/case-2024-001/logs/{windows,linux,network,application,web}
# Extract Windows Event Logs from forensic image
cp /mnt/evidence/Windows/System32/winevt/Logs/*.evtx /cases/case-2024-001/logs/windows/
# Key Windows Event Logs to collect
# Security.evtx - Authentication, access control, policy changes
# System.evtx - Service starts/stops, driver loads, system errors
# Application.evtx - Application errors and events
# Microsoft-Windows-PowerShell%4Operational.evtx - PowerShell execution
# Microsoft-Windows-Sysmon%4Operational.evtx - Sysmon detailed events
# Microsoft-Windows-TaskScheduler%4Operational.evtx - Scheduled tasks
# Microsoft-Windows-TerminalServices-LocalSessionManager%4Operational.evtx - RDP
# Collect Linux logs
cp /mnt/evidence/var/log/auth.log* /cases/case-2024-001/logs/linux/
cp /mnt/evidence/var/log/syslog* /cases/case-2024-001/logs/linux/
cp /mnt/evidence/var/log/kern.log* /cases/case-2024-001/logs/linux/
cp /mnt/evidence/var/log/secure* /cases/case-2024-001/logs/linux/
cp /mnt/evidence/var/log/audit/audit.log* /cases/case-2024-001/logs/linux/
# Collect web server logs
cp /mnt/evidence/var/log/apache2/access.log* /cases/case-2024-001/logs/web/
cp /mnt/evidence/var/log/nginx/access.log* /cases/case-2024-001/logs/web/
# Hash all collected logs for integrity
find /cases/case-2024-001/logs/ -type f -exec sha256sum {} \; > /cases/case-2024-001/logs/log_hashes.txtStep 2: Parse Windows Event Logs
# Install python-evtx for EVTX parsing
pip install python-evtx
# Convert EVTX to XML/JSON for analysis
python3 -c "
import Evtx.Evtx as evtx
import json, xml.etree.ElementTree as ET
with evtx.Evtx('/cases/case-2024-001/logs/windows/Security.evtx') as log:
for record in log.records():
print(record.xml())
" > /cases/case-2024-001/logs/windows/Security_parsed.xml
# Using evtxexport (libevtx-utils)
sudo apt-get install libevtx-utils
evtxexport /cases/case-2024-001/logs/windows/Security.evtx \
> /cases/case-2024-001/logs/windows/Security_exported.txt
# Key Security Event IDs to investigate
# 4624 - Successful logon
# 4625 - Failed logon
# 4648 - Logon using explicit credentials (runas, lateral movement)
# 4672 - Special privileges assigned (admin logon)
# 4688 - Process creation (with command line if auditing enabled)
# 4697 - Service installed
# 4698/4702 - Scheduled task created/updated
# 4720 - User account created
# 4732 - Member added to security-enabled local group
# 1102 - Audit log cleared
# Extract specific events with python-evtx
python3 << 'PYEOF'
import Evtx.Evtx as evtx
import xml.etree.ElementTree as ET
target_events = ['4624', '4625', '4648', '4672', '4688', '4697', '1102']
with evtx.Evtx('/cases/case-2024-001/logs/windows/Security.evtx') as log:
for record in log.records():
root = ET.fromstring(record.xml())
ns = {'ns': 'http://schemas.microsoft.com/win/2004/08/events/event'}
event_id = root.find('.//ns:EventID', ns).text
if event_id in target_events:
time = root.find('.//ns:TimeCreated', ns).get('SystemTime')
print(f"[{time}] EventID: {event_id}")
for data in root.findall('.//ns:Data', ns):
print(f" {data.get('Name')}: {data.text}")
print()
PYEOFStep 3: Parse and Analyze Linux/Syslog Entries
# Parse auth.log for SSH and sudo events
grep -E '(sshd|sudo|su\[|passwd|useradd|usermod)' \
/cases/case-2024-001/logs/linux/auth.log* | \
sort > /cases/case-2024-001/analysis/auth_events.txt
# Extract failed SSH login attempts
grep 'Failed password' /cases/case-2024-001/logs/linux/auth.log* | \
awk '{print $1,$2,$3,$9,$11}' | sort | uniq -c | sort -rn \
> /cases/case-2024-001/analysis/failed_ssh.txt
# Extract successful SSH logins
grep 'Accepted' /cases/case-2024-001/logs/linux/auth.log* | \
awk '{print $1,$2,$3,$9,$11}' > /cases/case-2024-001/analysis/successful_ssh.txt
# Parse audit logs for file access and command execution
ausearch -if /cases/case-2024-001/logs/linux/audit.log \
--start 2024-01-15 --end 2024-01-20 \
-m EXECVE > /cases/case-2024-001/analysis/audit_commands.txt
ausearch -if /cases/case-2024-001/logs/linux/audit.log \
-m USER_AUTH,USER_LOGIN,USER_CMD \
> /cases/case-2024-001/analysis/audit_auth.txt
# Parse web access logs for suspicious requests
cat /cases/case-2024-001/logs/web/access.log* | \
grep -iE '(union.*select|<script|\.\.\/|cmd\.exe|/etc/passwd)' \
> /cases/case-2024-001/analysis/web_attacks.txt
# Extract unique IP addresses from web logs
awk '{print $1}' /cases/case-2024-001/logs/web/access.log* | \
sort | uniq -c | sort -rn > /cases/case-2024-001/analysis/web_ips.txtStep 4: Correlate Events Across Sources
# Normalize timestamps and merge log sources
python3 << 'PYEOF'
import csv
import datetime
from collections import defaultdict
events = []
# Parse Windows Security events (pre-exported to CSV)
with open('/cases/case-2024-001/analysis/windows_events.csv') as f:
reader = csv.DictReader(f)
for row in reader:
events.append({
'timestamp': row['TimeCreated'],
'source': 'Windows-Security',
'event_id': row['EventID'],
'description': row['Description'],
'details': row.get('Details', '')
})
# Parse Linux auth events
with open('/cases/case-2024-001/analysis/auth_events.txt') as f:
for line in f:
parts = line.strip().split()
if len(parts) >= 6:
events.append({
'timestamp': ' '.join(parts[:3]),
'source': 'Linux-Auth',
'event_id': parts[4].rstrip(':'),
'description': ' '.join(parts[5:]),
'details': ''
})
# Sort by timestamp
events.sort(key=lambda x: x['timestamp'])
# Write correlated timeline
with open('/cases/case-2024-001/analysis/correlated_timeline.csv', 'w', newline='') as f:
writer = csv.DictWriter(f, fieldnames=['timestamp', 'source', 'event_id', 'description', 'details'])
writer.writeheader()
writer.writerows(events)
print(f"Total correlated events: {len(events)}")
PYEOF
# Quick correlation: find events within time windows
# Look for lateral movement patterns
grep "4648\|4624.*Type.*3\|4624.*Type.*10" /cases/case-2024-001/analysis/windows_events.csv | \
sort > /cases/case-2024-001/analysis/lateral_movement.txtStep 5: Generate Forensic Timeline Report
# Create structured investigation report
cat << 'REPORT' > /cases/case-2024-001/analysis/log_analysis_report.txt
LOG ANALYSIS FORENSIC REPORT
=============================
Case: 2024-001
Analyst: [Examiner Name]
Date: $(date -u)
LOG SOURCES ANALYZED:
- Windows Security Event Log (Security.evtx) - 245,678 events
- Windows System Event Log (System.evtx) - 45,234 events
- Windows PowerShell Operational - 12,456 events
- Linux auth.log - 34,567 entries
- Apache access.log - 567,890 entries
- Linux audit.log - 89,012 entries
KEY FINDINGS:
1. Initial Access: [timestamp] - Successful RDP login from external IP
2. Privilege Escalation: [timestamp] - New admin account created
3. Lateral Movement: [timestamp] - Pass-the-hash detected across 3 systems
4. Data Exfiltration: [timestamp] - Large data transfer to external IP
5. Log Tampering: [timestamp] - Security event log cleared (Event 1102)
TIMELINE OF EVENTS:
[See correlated_timeline.csv for complete chronology]
REPORT
# Package analysis artifacts
tar -czf /cases/case-2024-001/log_analysis_package.tar.gz \
/cases/case-2024-001/analysis/Key Concepts
| Concept | Description |
|---|---|
| Event correlation | Linking related events across multiple log sources by time, IP, user, or session |
| Log normalization | Converting diverse log formats into a common schema for unified analysis |
| Timeline analysis | Chronological ordering of events to reconstruct incident sequence |
| Log integrity | Verifying logs have not been tampered with using hashes and chain of custody |
| Logon types | Windows categorization of authentication methods (2=interactive, 3=network, 10=RDP) |
| Audit policy | System configuration determining which events are recorded in logs |
| Log rotation | Automatic archiving of log files that affects evidence availability |
| Anti-forensics | Attacker techniques for clearing or modifying logs to cover tracks |
Tools & Systems
| Tool | Purpose |
|---|---|
| python-evtx | Python library for parsing Windows EVTX event log files |
| evtxexport | Command-line EVTX export utility from libevtx |
| LogParser | Microsoft SQL-like query engine for Windows logs |
| ausearch | Linux audit log search utility |
| jq | JSON query tool for parsing structured log formats |
| ELK Stack | Elasticsearch, Logstash, Kibana for log aggregation and visualization |
| Chainsaw | Sigma-based Windows Event Log analysis tool |
| Hayabusa | Fast Windows Event Log forensic timeline generator |
Common Scenarios
Scenario 1: Brute Force Attack Detection Filter Security.evtx for Event ID 4625 (failed logons), group by source IP and target account, identify patterns of rapid successive failures, find the successful logon (4624) that followed, trace subsequent activity from the compromised account.
Scenario 2: Insider Threat Investigation Collect all log sources from the suspect's workstation and accessed servers, correlate file access events with authentication events, build timeline of data access during non-business hours, identify data transfers to external media or cloud storage.
Scenario 3: Web Application Compromise Parse web server access logs for SQLi, XSS, and path traversal patterns, identify the attack IP and timeline, correlate with application logs for successful exploitation, trace post-exploitation activity through system and auth logs.
Scenario 4: Ransomware Incident Timeline Identify the initial execution through process creation events (4688), trace privilege escalation through service installation (4697), map lateral movement via network logons (4624 Type 3), identify encryption start from file system activity, find the earliest IoC for remediation scoping.
Output Format
Log Analysis Summary:
Investigation Period: 2024-01-15 00:00 to 2024-01-20 23:59 UTC
Total Events Analyzed: 894,567
Log Sources: 6 (3 Windows, 3 Linux)
Critical Events:
Failed Logons: 1,234 (from 5 unique IPs)
Successful Logons: 456 (3 anomalous)
Account Changes: 12 (1 unauthorized admin creation)
Process Creations: 8,234 (15 suspicious)
Log Clearings: 2 (Security log cleared at 2024-01-18 03:00 UTC)
Service Installs: 3 (1 unknown service)
Attack Timeline:
2024-01-15 14:32 - Initial access via RDP brute force
2024-01-15 14:45 - Admin account "svcbackup" created
2024-01-16 02:15 - Lateral movement to 3 servers
2024-01-17 03:00 - Data staging in C:\ProgramData\temp\
2024-01-18 01:30 - 4.2 GB exfiltrated to 185.x.x.x
2024-01-18 03:00 - Security logs cleared
Report: /cases/case-2024-001/analysis/log_analysis_report.txtReferences and resources
Everything below is rendered for inspection. Script files are read-only and never run.
References 1
api-reference.md1.8 KB
API Reference: Log Analysis for Forensic Investigation
python-evtx Library
import Evtx.Evtx as evtx
with evtx.Evtx("Security.evtx") as log:
for record in log.records():
print(record.xml())Key Windows Security Event IDs
| Event ID | Description | Forensic Value |
|---|---|---|
| 4624 | Successful logon | Track authentication patterns |
| 4625 | Failed logon | Brute force detection |
| 4648 | Explicit credentials | Lateral movement indicator |
| 4688 | Process creation | Command execution timeline |
| 4697 | Service installed | Persistence mechanism |
| 4698 | Scheduled task created | Persistence mechanism |
| 1102 | Audit log cleared | Anti-forensics detection |
Syslog Parsing
| Log File | Content | Key Events |
|---|---|---|
/var/log/auth.log |
SSH, sudo, su | Failed/successful SSH, privilege escalation |
/var/log/syslog |
General system | Service events, kernel messages |
/var/log/audit/audit.log |
auditd | File access, command execution |
Python Libraries
| Library | Version | Purpose |
|---|---|---|
python-evtx |
>=0.7 | Windows EVTX event log parsing |
csv |
stdlib | Log data export and normalization |
re |
stdlib | Syslog and access log parsing |
CLI Tools
| Tool | Command | Description |
|---|---|---|
| evtxexport | evtxexport Security.evtx |
Export EVTX to text |
| Chainsaw | chainsaw hunt <evtx_dir> -s sigma/ |
Sigma-based EVTX analysis |
| Hayabusa | hayabusa csv-timeline -d <evtx_dir> |
Fast EVTX timeline generator |
References
- python-evtx: https://github.com/williballenthin/python-evtx
- Chainsaw: https://github.com/WithSecureLabs/chainsaw
- Hayabusa: https://github.com/Yamato-Security/hayabusa
- Sigma rules: https://github.com/SigmaHQ/sigma
Scripts 1
agent.py8.3 KB
#!/usr/bin/env python3
"""Agent for performing log analysis for forensic investigation.
Parses Windows EVTX, Linux syslog, and web access logs to build
correlated forensic timelines for incident investigations.
"""
import json
import sys
import csv
import re
from datetime import datetime
from collections import defaultdict
from pathlib import Path
class ForensicLogAnalyzer:
"""Analyzes and correlates logs for forensic investigations."""
def __init__(self, case_id, output_dir):
self.case_id = case_id
self.output_dir = Path(output_dir)
self.output_dir.mkdir(parents=True, exist_ok=True)
self.events = []
def parse_evtx(self, evtx_path):
"""Parse Windows EVTX event log files."""
try:
import Evtx.Evtx as evtx
import xml.etree.ElementTree as ET
except ImportError:
print("Install python-evtx: pip install python-evtx")
return []
records = []
target_ids = {"4624", "4625", "4648", "4672", "4688", "4697", "4698", "1102"}
with evtx.Evtx(evtx_path) as log:
for record in log.records():
try:
root = ET.fromstring(record.xml())
ns = {"ns": "http://schemas.microsoft.com/win/2004/08/events/event"}
event_id = root.find(".//ns:EventID", ns).text
if event_id not in target_ids:
continue
time_elem = root.find(".//ns:TimeCreated", ns)
timestamp = time_elem.get("SystemTime") if time_elem is not None else ""
data_fields = {}
for data in root.findall(".//ns:Data", ns):
name = data.get("Name", "")
data_fields[name] = data.text or ""
event = {
"timestamp": timestamp,
"source": "Windows-Security",
"event_id": event_id,
"computer": data_fields.get("Computer", ""),
"user": data_fields.get("TargetUserName", ""),
"details": data_fields,
}
records.append(event)
self.events.append(event)
except Exception:
continue
return records
def parse_syslog(self, log_path):
"""Parse Linux syslog/auth.log files."""
records = []
syslog_re = re.compile(
r"^(\w{3}\s+\d+\s+\d{2}:\d{2}:\d{2})\s+(\S+)\s+(\S+?)(?:\[\d+\])?:\s+(.*)"
)
with open(log_path, "r", errors="ignore") as f:
for line in f:
match = syslog_re.match(line.strip())
if match:
event = {
"timestamp": match.group(1),
"source": "Linux-Syslog",
"host": match.group(2),
"service": match.group(3),
"message": match.group(4),
}
records.append(event)
self.events.append(event)
return records
def parse_web_access_log(self, log_path):
"""Parse Apache/Nginx combined access log format."""
records = []
access_re = re.compile(
r'^(\S+)\s+\S+\s+\S+\s+\[([^\]]+)\]\s+"([^"]+)"\s+(\d{3})\s+(\d+)'
)
with open(log_path, "r", errors="ignore") as f:
for line in f:
match = access_re.match(line.strip())
if match:
event = {
"timestamp": match.group(2),
"source": "Web-Access",
"client_ip": match.group(1),
"request": match.group(3),
"status": match.group(4),
"size": match.group(5),
}
records.append(event)
self.events.append(event)
return records
def detect_attack_patterns(self, web_events):
"""Detect common web attack patterns in access logs."""
patterns = {
"sql_injection": re.compile(r"(union.*select|or\s+1\s*=\s*1|drop\s+table)", re.I),
"xss": re.compile(r"(<script|javascript:|onerror=|onload=)", re.I),
"path_traversal": re.compile(r"(\.\./|\.\.\\|/etc/passwd|/etc/shadow)", re.I),
"command_injection": re.compile(r"(;\s*(ls|cat|wget|curl|nc)\b|`|\$\()", re.I),
}
findings = defaultdict(list)
for event in web_events:
request = event.get("request", "")
for attack_type, pattern in patterns.items():
if pattern.search(request):
findings[attack_type].append({
"timestamp": event["timestamp"],
"client_ip": event.get("client_ip", ""),
"request": request[:200],
"status": event.get("status", ""),
})
return dict(findings)
def detect_brute_force(self):
"""Detect brute force patterns in authentication events."""
failed_by_source = defaultdict(lambda: {"count": 0, "users": set()})
for event in self.events:
if event.get("event_id") == "4625":
src = event.get("details", {}).get("IpAddress", "unknown")
user = event.get("user", "unknown")
failed_by_source[src]["count"] += 1
failed_by_source[src]["users"].add(user)
return [
{"source_ip": src, "failed_attempts": data["count"],
"targeted_users": sorted(data["users"])}
for src, data in failed_by_source.items()
if data["count"] > 5
]
def detect_log_clearing(self):
"""Detect audit log clearing events (anti-forensics)."""
return [
event for event in self.events
if event.get("event_id") == "1102"
]
def build_correlated_timeline(self):
"""Build a unified correlated timeline from all log sources."""
sorted_events = sorted(self.events, key=lambda e: e.get("timestamp", ""))
return sorted_events
def generate_forensic_report(self):
"""Generate a comprehensive forensic log analysis report."""
timeline = self.build_correlated_timeline()
brute_force = self.detect_brute_force()
log_clearing = self.detect_log_clearing()
web_events = [e for e in self.events if e.get("source") == "Web-Access"]
attack_patterns = self.detect_attack_patterns(web_events)
source_counts = defaultdict(int)
for event in self.events:
source_counts[event.get("source", "unknown")] += 1
report = {
"case_id": self.case_id,
"report_date": datetime.utcnow().isoformat(),
"total_events": len(self.events),
"source_breakdown": dict(source_counts),
"brute_force_detections": brute_force,
"log_clearing_events": log_clearing,
"web_attack_patterns": {k: len(v) for k, v in attack_patterns.items()},
"timeline_entries": len(timeline),
}
report_path = self.output_dir / f"{self.case_id}_log_analysis.json"
with open(report_path, "w") as f:
json.dump(report, f, indent=2, default=list)
timeline_path = self.output_dir / f"{self.case_id}_timeline.csv"
if timeline:
with open(timeline_path, "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=list(timeline[0].keys()))
writer.writeheader()
for event in timeline[:10000]:
writer.writerow({k: str(v)[:200] for k, v in event.items()})
print(json.dumps(report, indent=2, default=list))
return report
def main():
if len(sys.argv) < 3:
print("Usage: agent.py <case_id> <output_dir> [evtx_file] [syslog_file] [access_log]")
sys.exit(1)
case_id = sys.argv[1]
output_dir = sys.argv[2]
analyzer = ForensicLogAnalyzer(case_id, output_dir)
if len(sys.argv) > 3:
analyzer.parse_evtx(sys.argv[3])
if len(sys.argv) > 4:
analyzer.parse_syslog(sys.argv[4])
if len(sys.argv) > 5:
analyzer.parse_web_access_log(sys.argv[5])
analyzer.generate_forensic_report()
if __name__ == "__main__":
main()