npx skills add mukul975/Anthropic-Cybersecurity-SkillsMITRE ATT&CK
When to Use
- Building detection rules for pre-ransomware network activity (the average time from Cobalt Strike deployment to encryption is 17 minutes)
- Monitoring for initial access broker (IAB) indicators that precede ransomware deployment
- Creating SIEM correlation rules that chain multiple precursor events into high-confidence alerts
- Tuning network detection systems to distinguish ransomware staging from normal administrative activity
- Investigating suspicious network patterns that may indicate ransomware operators have established a foothold
Do not use for post-encryption response (see recovering-from-ransomware-attack). This skill focuses on the pre-encryption detection window where containment can prevent data loss.
Prerequisites
- Network detection platform (Zeek/Bro, Suricata, or Arkime/Moloch) deployed on network TAP or SPAN ports
- SIEM platform (Splunk, Elastic Security, Microsoft Sentinel, or QRadar) ingesting network logs
- Threat intelligence feeds covering ransomware IOCs (CISA, abuse.ch, OTX, MISP)
- Network flow data (NetFlow/IPFIX) from core routers and firewalls
- DNS query logging from internal resolvers
- Full packet capture capability for incident investigation
Workflow
Step 1: Identify Ransomware Kill Chain Phases in Network Traffic
Map network-observable indicators to each pre-encryption phase:
| Kill Chain Phase | Network Indicators | Detection Source |
|---|---|---|
| Initial Access | RDP brute force, VPN credential stuffing, phishing callback | Firewall logs, IDS, proxy logs |
| C2 Establishment | Cobalt Strike beacons (HTTPS/DNS), Sliver/Brute Ratel callbacks | Zeek SSL/HTTP logs, DNS logs |
| Credential Harvesting | NTLM relay, Kerberoasting, DCSync traffic | Zeek Kerberos/NTLM logs, DC logs |
| Reconnaissance | Internal port scanning, AD enumeration (LDAP/SMB) | Zeek conn.log, flow data |
| Lateral Movement | PsExec/WMI/WinRM traffic, RDP pivoting, SMB file copies | Zeek SMB/DCE-RPC logs |
| Staging | Data aggregation, archive creation, cloud upload prep | Proxy logs, DNS logs, DLP |
Step 2: Deploy Network Detection Rules
Suricata rules for common ransomware precursors:
# Cobalt Strike default HTTPS beacon profile detection
alert tls $HOME_NET any -> $EXTERNAL_NET any (msg:"RANSOMWARE PRECURSOR - Cobalt Strike Default TLS Certificate"; tls.cert_subject; content:"Major Cobalt Strike"; sid:3000001; rev:1;)
# Cobalt Strike DNS beacon
alert dns $HOME_NET any -> any 53 (msg:"RANSOMWARE PRECURSOR - Cobalt Strike DNS Beacon Pattern"; dns.query; pcre:"/^[a-z0-9]{3}\.[a-z]{4,8}\./"; threshold:type both, track by_src, count 50, seconds 60; sid:3000002; rev:1;)
# Mimikatz network signature (DCSync - DRS GetNCChanges)
alert tcp $HOME_NET any -> $HOME_NET 135 (msg:"RANSOMWARE PRECURSOR - Possible DCSync/Mimikatz"; content:"|05 00 0b|"; offset:0; depth:3; content:"|e3 51 4d 2b 4b 47 15 d2|"; sid:3000003; rev:1;)
# Internal network scanning (many connections, few bytes)
alert tcp $HOME_NET any -> $HOME_NET any (msg:"RANSOMWARE PRECURSOR - Internal Port Scan"; flags:S; threshold:type both, track by_src, count 100, seconds 10; sid:3000004; rev:1;)
# PsExec service installation over SMB
alert tcp $HOME_NET any -> $HOME_NET 445 (msg:"RANSOMWARE PRECURSOR - PsExec Service Install"; content:"|ff|SMB"; content:"PSEXESVC"; nocase; sid:3000005; rev:1;)
# RDP brute force from internal host (lateral movement)
alert tcp $HOME_NET any -> $HOME_NET 3389 (msg:"RANSOMWARE PRECURSOR - Internal RDP Brute Force"; flow:to_server,established; threshold:type both, track by_src, count 20, seconds 60; sid:3000006; rev:1;)
# Large SMB file transfer (data staging)
alert tcp $HOME_NET any -> $HOME_NET 445 (msg:"RANSOMWARE PRECURSOR - Large SMB Transfer Possible Staging"; flow:to_server,established; dsize:>60000; threshold:type both, track by_src, count 100, seconds 300; sid:3000007; rev:1;)Zeek scripts for behavioral detection:
# detect_ransomware_precursors.zeek
# Detect high volume of failed SMB connections (credential testing)
@load base/protocols/smb
module RansomwarePrecursor;
export {
redef enum Notice::Type += {
SMB_Brute_Force,
Suspicious_Internal_Scan,
Excessive_DNS_Queries,
SMB_Admin_Share_Access,
};
const smb_fail_threshold = 10 &redef;
const scan_threshold = 50 &redef;
const dns_query_threshold = 200 &redef;
}
global smb_fail_count: table[addr] of count &default=0 &create_expire=5min;
global conn_count: table[addr] of set[addr] &create_expire=1min;
event smb2_message(c: connection, hdr: SMB2::Header, is_orig: bool) {
if (hdr$status != 0) {
++smb_fail_count[c$id$orig_h];
if (smb_fail_count[c$id$orig_h] >= smb_fail_threshold) {
NOTICE([$note=SMB_Brute_Force,
$msg=fmt("Host %s has %d failed SMB attempts", c$id$orig_h, smb_fail_count[c$id$orig_h]),
$src=c$id$orig_h,
$identifier=cat(c$id$orig_h)]);
}
}
}
event new_connection(c: connection) {
if (c$id$orig_h in Site::local_nets && c$id$resp_h in Site::local_nets) {
if (c$id$orig_h !in conn_count)
conn_count[c$id$orig_h] = set();
add conn_count[c$id$orig_h][c$id$resp_h];
if (|conn_count[c$id$orig_h]| >= scan_threshold) {
NOTICE([$note=Suspicious_Internal_Scan,
$msg=fmt("Host %s connected to %d internal hosts in 1 min", c$id$orig_h, |conn_count[c$id$orig_h]|),
$src=c$id$orig_h,
$identifier=cat(c$id$orig_h)]);
}
}
}Step 3: Create SIEM Correlation Rules
Splunk correlation for ransomware precursor chain:
| tstats count FROM datamodel=Network_Traffic
WHERE earliest=-24h All_Traffic.dest_port IN (445, 135, 139, 3389, 5985, 5986)
AND All_Traffic.src_ip IN 10.0.0.0/8
AND All_Traffic.dest_ip IN 10.0.0.0/8
BY All_Traffic.src_ip, All_Traffic.dest_port, _time span=1h
| stats dc(All_Traffic.dest_port) as port_count,
values(All_Traffic.dest_port) as ports,
count as total_conns
BY All_Traffic.src_ip
| where port_count >= 3 AND total_conns > 50
| rename All_Traffic.src_ip as src_ip
| lookup threat_intel_ioc ip as src_ip OUTPUT threat_type
| eval risk_score = case(
port_count >= 5 AND total_conns > 200, "CRITICAL",
port_count >= 3 AND total_conns > 50, "HIGH",
1=1, "MEDIUM")
| table src_ip, ports, port_count, total_conns, risk_score, threat_typeMicrosoft Sentinel KQL - Ransomware precursor correlation:
let timeframe = 24h;
let RDPBruteForce = SecurityEvent
| where TimeGenerated > ago(timeframe)
| where EventID == 4625
| where LogonType == 10
| summarize FailedRDP = count() by TargetAccount, IpAddress, bin(TimeGenerated, 1h)
| where FailedRDP > 10;
let SuspiciousSMB = SecurityEvent
| where TimeGenerated > ago(timeframe)
| where EventID == 5145
| where ShareName has "ADMIN$" or ShareName has "C$" or ShareName has "IPC$"
| summarize AdminShareAccess = count() by SubjectUserName, IpAddress, bin(TimeGenerated, 1h)
| where AdminShareAccess > 5;
let ServiceInstalls = SecurityEvent
| where TimeGenerated > ago(timeframe)
| where EventID == 7045
| where ServiceName has_any ("PSEXESVC", "meterpreter", "beacon");
RDPBruteForce
| join kind=inner SuspiciousSMB on IpAddress
| project TimeGenerated, IpAddress, TargetAccount, FailedRDP, SubjectUserName, AdminShareAccess
| extend AlertTitle = "Ransomware Precursor: RDP Brute Force + Admin Share Access"Step 4: Integrate Threat Intelligence
Configure automated IOC feeds for known ransomware infrastructure:
# Download and update ransomware C2 blocklists
# abuse.ch Feodo Tracker (Cobalt Strike, TrickBot, BazarLoader C2s)
curl -s https://feodotracker.abuse.ch/downloads/ipblocklist.csv | \
grep -v "^#" | cut -d, -f2 > /opt/threat-intel/feodo_ips.txt
# abuse.ch URLhaus (malware distribution URLs)
curl -s https://urlhaus.abuse.ch/downloads/csv_recent/ | \
grep -v "^#" | cut -d, -f3 > /opt/threat-intel/urlhaus_urls.txt
# abuse.ch ThreatFox (ransomware IOCs)
curl -s https://threatfox.abuse.ch/export/csv/recent/ | \
grep -i "ransomware" | cut -d, -f3 > /opt/threat-intel/ransomware_iocs.txt
# CISA Known Exploited Vulnerabilities (initial access vectors)
curl -s https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json | \
python3 -c "import json,sys; data=json.load(sys.stdin); [print(v['cveID'],v['vendorProject'],v['product']) for v in data['vulnerabilities'] if 'ransomware' in v.get('knownRansomwareCampaignUse','').lower()]"Step 5: Establish Alert Triage and Escalation
Define triage procedures based on precursor confidence level:
| Alert Type | Confidence | Response Time | Action |
|---|---|---|---|
| Confirmed Cobalt Strike beacon | High | 15 minutes | Isolate host immediately, trigger IR |
| DCSync/Kerberoasting from non-DC | High | 15 minutes | Disable account, isolate host, trigger IR |
| Internal port scan + admin share access | Medium-High | 30 minutes | Investigate source host, check EDR telemetry |
| RDP brute force from internal host | Medium | 1 hour | Verify if legitimate admin activity, check host |
| Unusual DNS query volume | Low-Medium | 4 hours | Check for DNS tunneling, correlate with other alerts |
Key Concepts
| Term | Definition |
|---|---|
| Ransomware Precursor | Network activity that precedes ransomware encryption, including C2 communication, lateral movement, and data staging |
| Dwell Time | Time between initial compromise and ransomware deployment, averaging 21 days but sometimes as short as 17 minutes |
| Initial Access Broker (IAB) | Threat actors who sell compromised network access to ransomware operators on dark web markets |
| Beaconing | Periodic C2 callbacks from implants (Cobalt Strike, Sliver) that can be detected by analyzing connection timing patterns |
| Kerberoasting | Credential harvesting technique requesting Kerberos service tickets for offline cracking, detectable via unusual TGS-REQ patterns |
| DCSync | Technique using Directory Replication Service to extract password hashes from domain controllers, critical ransomware precursor |
Tools & Systems
- Zeek (formerly Bro): Network analysis framework generating structured logs for SMB, Kerberos, DNS, HTTP, and TLS connections
- Suricata: High-performance IDS/IPS with protocol analysis and multi-threading support for ransomware signature detection
- Arkime (formerly Moloch): Full packet capture and search platform for deep forensic investigation of network events
- RITA (Real Intelligence Threat Analytics): Open-source tool for detecting beaconing, DNS tunneling, and long connections in Zeek logs
- AC-Hunter: Network threat hunting platform from Active Countermeasures for beacon detection and C2 identification
Common Scenarios
Scenario: Detecting LockBit Precursors in a Manufacturing Network
Context: A manufacturing company's SOC receives an alert for unusual SMB traffic from a workstation (10.1.5.42) in the engineering department. The workstation connected to 47 internal hosts on port 445 within 5 minutes at 2:00 AM.
Approach:
- Zeek conn.log analysis shows 10.1.5.42 initiated connections to 47 unique internal IPs on port 445, 135, and 3389 between 01:55-02:05
- Zeek ssl.log reveals an outbound HTTPS connection to 185.x.x.x every 60 seconds with consistent 48-byte payloads (Cobalt Strike beacon pattern)
- RITA beacon analysis confirms high beacon score (0.96) for the external IP with 60-second jitter
- Zeek kerberos.log shows TGS-REQ for multiple SPN accounts from 10.1.5.42 (Kerberoasting)
- SMB tree_connect events show access to ADMIN$ shares on 12 hosts (lateral movement staging)
- Containment: Host isolated, credentials for engineering user reset, blocking rule for C2 IP deployed
- Full IR initiated before ransomware deployment could begin
Pitfalls:
- Dismissing internal port scans as vulnerability scanner activity without verifying the source is an authorized scanner
- Not correlating individual low-severity alerts (DNS anomaly + SMB access + failed logins) into a high-severity chain
- Setting detection thresholds too high to avoid false positives, missing low-and-slow reconnaissance
- Ignoring encrypted traffic analysis (JA3/JA4 fingerprinting) that can identify Cobalt Strike even in TLS tunnels
Output Format
## Ransomware Precursor Detection Alert
**Alert ID**: [SIEM-generated ID]
**Detection Time**: [Timestamp]
**Source Host**: [IP / Hostname]
**Confidence**: [High / Medium / Low]
**Kill Chain Phase**: [Initial Access / C2 / Credential Harvest / Recon / Lateral Movement / Staging]
### Indicators Detected
| Indicator | Source | Detail | MITRE ATT&CK |
|-----------|--------|--------|--------------|
| [Type] | [Zeek/Suricata/SIEM] | [Description] | [T-ID] |
### Correlation Chain
1. [Timestamp] - [Event 1]
2. [Timestamp] - [Event 2]
3. [Timestamp] - [Event 3]
### Recommended Actions
- [ ] Isolate source host from network
- [ ] Check EDR telemetry for host-based indicators
- [ ] Reset credentials for affected user accounts
- [ ] Block identified C2 infrastructure
- [ ] Escalate to incident response teamReferences and resources
Everything below is rendered for inspection. Script files are read-only and never run.
References 3
api-reference.md5.2 KB
API Reference — Detecting Ransomware Precursors in Network Traffic
Zeek (Bro) Log Fields
conn.log
| Field | Type | Description |
|---|---|---|
ts |
time | Connection start timestamp (Unix epoch) |
id.orig_h |
addr | Source IP address |
id.orig_p |
port | Source port |
id.resp_h |
addr | Destination IP address |
id.resp_p |
port | Destination port |
proto |
enum | Transport protocol (tcp/udp/icmp) |
orig_bytes |
count | Bytes sent by originator |
resp_bytes |
count | Bytes sent by responder |
conn_state |
string | Connection state (SF=normal, S0=no reply, REJ=rejected) |
duration |
interval | Duration of connection |
smb_files.log
| Field | Type | Description |
|---|---|---|
action |
enum | SMB action (SMB_FILE_OPEN, SMB_FILE_WRITE, SMB_FILE_DELETE) |
path |
string | Full UNC path accessed |
name |
string | Filename |
size |
count | File size in bytes |
id.orig_h |
addr | Source host (accessor) |
id.resp_h |
addr | Target host |
kerberos.log
| Field | Type | Description |
|---|---|---|
request_type |
string | KRB_AS_REQ, KRB_TGS_REQ |
client |
string | Client principal |
service |
string | Service principal (SPN) |
success |
bool | Whether request succeeded |
error_msg |
string | Error type (e.g., KDC_ERR_PREAUTH_REQUIRED) |
Suricata CLI
Start in IDS mode
suricata -c /etc/suricata/suricata.yaml -i eth0Start in IPS mode (NFQUEUE)
suricata -c /etc/suricata/suricata.yaml -q 0
# Configure iptables to send traffic to NFQUEUE:
iptables -I FORWARD -j NFQUEUE --queue-num 0Run on pcap file
suricata -c /etc/suricata/suricata.yaml -r capture.pcap -l /var/log/suricata/Update rules with suricata-update
suricata-update # Update all enabled sources
suricata-update list-sources # List available rule sources
suricata-update enable-source et/open # Enable Emerging Threats Open
suricata-update enable-source ptresearch/attackdetection # PT Research rules
suricata-update update-sources # Refresh source index
suricata-update --no-reload # Update without live reloadReload rules without restart
kill -USR2 $(pidof suricata)
# Or via Unix socket:
suricatasc -c reload-rulesQuery eve.json for alerts
# Ransomware-related alerts in last hour
jq 'select(.event_type=="alert") | select(.alert.signature | test("ransomware|cobalt|mimikatz|psexec";"i"))' \
/var/log/suricata/eve.json | jq -r '[.timestamp,.src_ip,.dest_ip,.alert.signature] | @tsv'
# Top 10 alert signatures
jq -r 'select(.event_type=="alert") | .alert.signature' /var/log/suricata/eve.json | \
sort | uniq -c | sort -rn | head -10RITA (Real Intelligence Threat Analytics)
Import Zeek logs and analyze
rita import --input /var/log/zeek/current/ --database my_network
rita analyze my_networkBeacon detection output
rita show-beacons my_network --human-readable
# Columns: Score | Source | Dest | Connections | Avg Bytes | TS Delta
# Score 0.9+ = high confidence beaconDNS tunneling detection
rita show-exploded-dns my_network | head -20
rita show-long-connections my_network --human-readableSplunk SPL — Ransomware Precursor Queries
Internal lateral movement via SMB/RDP/WinRM
index=zeek sourcetype=zeek_conn
id.resp_p IN (445, 135, 3389, 5985, 5986)
id.orig_h IN 10.0.0.0/8
id.resp_h IN 10.0.0.0/8
| stats dc(id.resp_h) as targets count as conns by id.orig_h
| where targets >= 10
| sort -targetsDetect beaconing (regular connection intervals)
index=zeek sourcetype=zeek_conn
| bucket _time span=1m
| stats count as conns by id.orig_h, id.resp_h, id.resp_p, _time
| stats stdev(conns) as jitter avg(conns) as avg_conns count as minutes
by id.orig_h, id.resp_h, id.resp_p
| where minutes > 10 AND jitter < 2 AND avg_conns > 0
| eval beacon_score = round(1 - (jitter / (avg_conns + 0.001)), 2)
| where beacon_score > 0.8
| sort -beacon_scoreabuse.ch Threat Intelligence Feeds
Feodo Tracker (C2 IPs — Cobalt Strike, BazarLoader)
# CSV format: first_seen,dst_ip,dst_port,c2_status,malware
curl -s https://feodotracker.abuse.ch/downloads/ipblocklist.csv | \
grep -v "^#" | awk -F, '{print $2}' > /tmp/c2_ips.txtThreatFox IOC API
# Query recent ransomware IOCs
curl -s -X POST https://threatfox-api.abuse.ch/api/v1/ \
-H "Content-Type: application/json" \
-d '{"query":"get_iocs","days":7,"tag":"ransomware"}' | \
jq '.data[] | [.ioc_value,.ioc_type,.malware,.confidence_level] | @tsv' -rMITRE ATT&CK Ransomware Precursor Techniques
| Technique | ID | Network Indicator |
|---|---|---|
| Remote Services: SMB/WMI | T1021.002 | SMB port 445 traffic to many hosts |
| OS Credential Dumping: DCSync | T1003.006 | DRS GetNCChanges from non-DC |
| Kerberoasting | T1558.003 | TGS-REQ for many SPNs |
| Command & Control | T1071.001 | Regular HTTPS beaconing |
| Lateral Tool Transfer | T1570 | Large SMB file writes across hosts |
| Network Service Scanning | T1046 | Port sweeps on 445/3389/135 |
standards.md1.7 KB
Standards & References - Detecting Ransomware Precursors
MITRE ATT&CK Mapping
Initial Access (TA0001)
- T1078: Valid Accounts (compromised credentials from IABs)
- T1133: External Remote Services (VPN/RDP exploitation)
- T1566: Phishing (email-based initial access)
Command and Control (TA0011)
- T1071.001: Application Layer Protocol: Web (HTTPS beacons)
- T1071.004: Application Layer Protocol: DNS (DNS tunneling)
- T1573: Encrypted Channel (C2 over TLS)
- T1090: Proxy (redirectors and relay infrastructure)
Credential Access (TA0006)
- T1558.003: Kerberoasting
- T1003.006: DCSync
- T1557: Adversary-in-the-Middle (NTLM relay)
Discovery (TA0007)
- T1046: Network Service Discovery (port scanning)
- T1018: Remote System Discovery (AD enumeration)
- T1087: Account Discovery
Lateral Movement (TA0008)
- T1021.002: Remote Services: SMB/Windows Admin Shares
- T1021.001: Remote Services: RDP
- T1047: Windows Management Instrumentation (WMI)
- T1569.002: System Services: Service Execution (PsExec)
Industry References
CISA Advisories
- AA23-136A: #StopRansomware - BianLian Ransomware Group
- AA23-158A: #StopRansomware - CL0P Ransomware Gang
- AA24-131A: #StopRansomware - Black Basta
- AA23-165A: Understanding Ransomware Threat Actors: LockBit
NIST
- SP 800-94 Rev 1: Guide to Intrusion Detection and Prevention Systems
- SP 800-86: Guide to Integrating Forensic Techniques into Incident Response
- IR 8374: Ransomware Risk Management
Threat Intelligence Sources
- abuse.ch Feodo Tracker: https://feodotracker.abuse.ch/
- abuse.ch ThreatFox: https://threatfox.abuse.ch/
- CISA Known Exploited Vulnerabilities: https://www.cisa.gov/known-exploited-vulnerabilities-catalog
- Emerging Threats Ruleset: https://rules.emergingthreats.net/
workflows.md2.6 KB
Workflows - Detecting Ransomware Precursors in Network
Workflow 1: Network Sensor Deployment
Start
|
v
[Identify network chokepoints] --> Core switches, internet edge, DC segments
|
v
[Deploy network TAPs or configure SPAN ports]
|
v
[Install Zeek sensor] --> Configure local.zeek with site-specific networks
|
v
[Install Suricata IDS] --> Load ET Open + custom ransomware rules
|
v
[Configure log forwarding to SIEM]
|-- Zeek: conn.log, ssl.log, dns.log, smb.log, kerberos.log, notice.log
|-- Suricata: eve.json (alerts, flow, dns, tls)
|
v
[Deploy RITA for beacon analysis] --> Schedule hourly Zeek log imports
|
v
[Load threat intelligence feeds] --> Feodo, ThreatFox, CISA KEV
|
v
[Validate detection with controlled Cobalt Strike beacon test]
|
v
EndWorkflow 2: Alert Triage for Ransomware Precursors
Alert Received
|
v
[Classify alert type]
|-- C2 Beaconing --> Priority: CRITICAL, SLA: 15 min
|-- Credential Harvesting --> Priority: CRITICAL, SLA: 15 min
|-- Internal Scanning --> Priority: HIGH, SLA: 30 min
|-- Admin Share Access --> Priority: HIGH, SLA: 30 min
|-- RDP Brute Force --> Priority: MEDIUM, SLA: 1 hour
|-- DNS Anomaly --> Priority: LOW, SLA: 4 hours
|
v
[Check for correlated alerts on same source IP]
|-- Multiple categories? --> Elevate to CRITICAL regardless
|-- Single category? --> Proceed with category SLA
|
v
[Verify source host context]
|-- Known admin workstation? --> Check if scheduled activity
|-- Server? --> Check for authorized maintenance window
|-- Standard workstation? --> Likely compromise indicator
|
v
[Decision: True Positive or False Positive?]
|
TP --> [Contain host: network isolation via NAC/EDR]
| |
| v
| [Trigger incident response playbook]
|
FP --> [Document FP reason]
|
v
[Update detection rule to reduce FP rate]
|
v
EndWorkflow 3: Beacon Detection with RITA
Hourly Cron Job
|
v
[Import latest Zeek logs into RITA database]
$ rita import /opt/zeek/logs/current rita-db
|
v
[Analyze beacons]
$ rita show-beacons rita-db --human-readable
|
v
[Filter results by beacon score > 0.7]
|
v
[For each high-score beacon:]
|-- Look up destination IP in threat intel
|-- Check JA3/JA4 hash against known C2 fingerprints
|-- Verify beacon interval and jitter pattern
|
v
[Score > 0.9 AND matches threat intel?]
|
Yes --> [Generate CRITICAL alert]
|
No --> [Score > 0.7?]
|
Yes --> [Generate MEDIUM alert for analyst review]
|
No --> [Log and continue monitoring]
|
v
EndScripts 2
agent.py7.2 KB
#!/usr/bin/env python3
"""Agent for detecting ransomware precursor activity in network traffic and logs."""
import argparse
import json
import os
import subprocess
import sys
from datetime import datetime, timezone
RANSOMWARE_PORTS = {445, 3389, 4444, 5985, 5986, 135, 139, 8443}
SUSPICIOUS_PROCESSES = [
"vssadmin.exe", "wmic.exe", "bcdedit.exe", "wbadmin.exe",
"powershell.exe", "cmd.exe", "certutil.exe", "bitsadmin.exe",
"mshta.exe", "rundll32.exe", "regsvr32.exe", "cscript.exe",
]
SHADOW_COPY_PATTERNS = [
r"vssadmin\s+delete\s+shadows",
r"wmic\s+shadowcopy\s+delete",
r"bcdedit.*recoveryenabled.*no",
r"wbadmin\s+delete\s+(catalog|systemstatebackup)",
]
SMB_LATERAL_PATTERNS = [
r"\\\\[\d\.]+\\(C\$|ADMIN\$|IPC\$)",
r"psexec",
r"wmiexec",
]
def parse_zeek_conn_log(log_path):
"""Parse Zeek conn.log for suspicious network connections."""
alerts = []
try:
with open(log_path, "r") as f:
for line in f:
if line.startswith("#"):
continue
fields = line.strip().split("\t")
if len(fields) < 7:
continue
src_ip, src_port, dst_ip, dst_port = fields[2], fields[3], fields[4], fields[5]
try:
dp = int(dst_port)
except ValueError:
continue
if dp in RANSOMWARE_PORTS:
alerts.append({
"type": "suspicious_port",
"src": src_ip,
"dst": dst_ip,
"port": dp,
"detail": f"Connection to ransomware-associated port {dp}",
})
except FileNotFoundError:
print(f"[!] Log file not found: {log_path}")
return alerts
def analyze_event_logs_windows():
"""Check Windows event logs for ransomware precursors."""
alerts = []
queries = [
("Shadow copy deletion", "Get-WinEvent -FilterHashtable @{LogName='System';Id=7036} "
"| Where-Object {$_.Message -match 'Volume Shadow Copy'} | Select-Object -First 10 "
"| ConvertTo-Json"),
("RDP brute force", "Get-WinEvent -FilterHashtable @{LogName='Security';Id=4625} "
"| Select-Object -First 20 | Group-Object {$_.Properties[5].Value} "
"| Where-Object {$_.Count -gt 5} | ConvertTo-Json"),
("Service installs", "Get-WinEvent -FilterHashtable @{LogName='System';Id=7045} "
"| Select-Object -First 10 | ConvertTo-Json"),
]
for name, ps_cmd in queries:
try:
result = subprocess.check_output(
["powershell", "-NoProfile", "-Command", ps_cmd],
text=True, errors="replace", timeout=30
)
if result.strip():
data = json.loads(result) if result.strip().startswith(("[", "{")) else result
alerts.append({"check": name, "findings": data})
except (subprocess.SubprocessError, json.JSONDecodeError):
pass
return alerts
def scan_process_list():
"""Check running processes for ransomware tooling."""
suspicious = []
if sys.platform == "win32":
try:
out = subprocess.check_output(
["tasklist", "/FO", "CSV", "/NH"], text=True, errors="replace",
timeout=120,
)
for line in out.splitlines():
parts = line.strip('"').split('","')
if parts:
pname = parts[0].lower()
for sp in SUSPICIOUS_PROCESSES:
if pname == sp.lower():
suspicious.append({"process": pname, "pid": parts[1] if len(parts) > 1 else "?"})
except subprocess.SubprocessError:
pass
else:
try:
out = subprocess.check_output(["ps", "-eo", "pid,comm", "--no-headers"], text=True, timeout=120)
for line in out.splitlines():
parts = line.split(None, 1)
if len(parts) == 2:
for sp in SUSPICIOUS_PROCESSES:
if parts[1].strip().lower() == sp.replace(".exe", ""):
suspicious.append({"process": parts[1].strip(), "pid": parts[0]})
except subprocess.SubprocessError:
pass
return suspicious
def check_file_encryption_activity(directory, threshold=50):
"""Detect mass file renaming or new encrypted extensions."""
suspicious_exts = {".encrypted", ".locked", ".crypto", ".crypt", ".enc",
".locky", ".cerber", ".zepto", ".thor", ".aaa"}
findings = []
count = 0
try:
for root, _, files in os.walk(directory):
for f in files:
ext = os.path.splitext(f)[1].lower()
if ext in suspicious_exts:
count += 1
if count <= 10:
findings.append(os.path.join(root, f))
if count >= threshold:
break
except PermissionError:
pass
return {"encrypted_file_count": count, "samples": findings, "threshold_exceeded": count >= threshold}
def main():
parser = argparse.ArgumentParser(
description="Detect ransomware precursor activity in network and host"
)
parser.add_argument("--conn-log", help="Path to Zeek conn.log")
parser.add_argument("--scan-dir", help="Directory to scan for encrypted files")
parser.add_argument("--check-processes", action="store_true", help="Scan running processes")
parser.add_argument("--windows-logs", action="store_true", help="Check Windows event logs")
parser.add_argument("--output", "-o", help="Output JSON report path")
args = parser.parse_args()
print("[*] Ransomware Precursor Detection Agent")
report = {"timestamp": datetime.now(timezone.utc).isoformat(), "findings": {}}
if args.conn_log:
alerts = parse_zeek_conn_log(args.conn_log)
report["findings"]["network"] = alerts
print(f"[*] Network alerts: {len(alerts)}")
if args.check_processes:
procs = scan_process_list()
report["findings"]["suspicious_processes"] = procs
print(f"[*] Suspicious processes: {len(procs)}")
if args.windows_logs and sys.platform == "win32":
events = analyze_event_logs_windows()
report["findings"]["windows_events"] = events
print(f"[*] Windows event findings: {len(events)}")
if args.scan_dir:
enc = check_file_encryption_activity(args.scan_dir)
report["findings"]["encryption_activity"] = enc
print(f"[*] Encrypted files found: {enc['encrypted_file_count']}")
total = sum(
len(v) if isinstance(v, list) else (1 if isinstance(v, dict) and v.get("threshold_exceeded") else 0)
for v in report["findings"].values()
)
report["risk_level"] = "CRITICAL" if total >= 10 else "HIGH" if total >= 5 else "MEDIUM" if total > 0 else "LOW"
print(f"[*] Overall risk: {report['risk_level']}")
if args.output:
with open(args.output, "w") as f:
json.dump(report, f, indent=2)
print(f"[*] Report saved to {args.output}")
else:
print(json.dumps(report, indent=2))
if __name__ == "__main__":
main()
process.py19.0 KB
#!/usr/bin/env python3
"""
Ransomware Precursor Detection Engine
Analyzes network logs (Zeek format) to detect ransomware precursor patterns:
- C2 beaconing detection via statistical interval analysis
- Internal reconnaissance scanning
- Kerberoasting and credential harvesting indicators
- Admin share enumeration
- Data staging via large SMB transfers
Reads Zeek TSV logs and generates structured alerts.
"""
import csv
import json
import math
import os
import sys
import statistics
from collections import defaultdict
from dataclasses import dataclass, field, asdict
from datetime import datetime, timedelta
from pathlib import Path
from typing import Optional
@dataclass
class PrecursorAlert:
alert_id: str
timestamp: str
source_ip: str
dest_ip: str
category: str
confidence: str
kill_chain_phase: str
description: str
mitre_technique: str
evidence: list = field(default_factory=list)
class BeaconDetector:
"""Detects C2 beaconing by analyzing connection interval patterns."""
def __init__(self, min_connections: int = 20, beacon_score_threshold: float = 0.7):
self.min_connections = min_connections
self.beacon_score_threshold = beacon_score_threshold
self.connections = defaultdict(list)
def add_connection(self, src_ip: str, dst_ip: str, timestamp: float, orig_bytes: int, resp_bytes: int):
key = (src_ip, dst_ip)
self.connections[key].append({
"ts": timestamp,
"orig_bytes": orig_bytes,
"resp_bytes": resp_bytes,
})
def calculate_beacon_score(self, timestamps: list) -> dict:
"""Calculate beacon score based on connection interval regularity."""
if len(timestamps) < self.min_connections:
return {"score": 0.0, "interval": 0, "jitter": 0}
sorted_ts = sorted(timestamps)
intervals = [sorted_ts[i + 1] - sorted_ts[i] for i in range(len(sorted_ts) - 1)]
if not intervals:
return {"score": 0.0, "interval": 0, "jitter": 0}
median_interval = statistics.median(intervals)
if median_interval == 0:
return {"score": 0.0, "interval": 0, "jitter": 0}
# Calculate coefficient of variation (lower = more regular = more likely beacon)
try:
stdev = statistics.stdev(intervals)
cv = stdev / median_interval
except statistics.StatisticsError:
cv = 0
# Beacon score: inverse of coefficient of variation, capped at 1.0
# Perfect beacon (cv=0) scores 1.0, high variation scores low
if cv == 0:
score = 1.0
else:
score = max(0, min(1.0, 1.0 - cv))
# Penalize very short intervals (likely legitimate keep-alives under 5s)
if median_interval < 5:
score *= 0.5
# Penalize very long intervals (over 1 hour - less likely active C2)
if median_interval > 3600:
score *= 0.7
return {
"score": round(score, 3),
"interval": round(median_interval, 1),
"jitter": round(stdev, 1) if stdev else 0,
"connection_count": len(timestamps),
}
def detect(self) -> list:
"""Detect beaconing patterns in collected connections."""
alerts = []
for (src_ip, dst_ip), conns in self.connections.items():
timestamps = [c["ts"] for c in conns]
result = self.calculate_beacon_score(timestamps)
if result["score"] >= self.beacon_score_threshold:
# Check for consistent payload sizes (another beacon indicator)
orig_sizes = [c["orig_bytes"] for c in conns if c["orig_bytes"] > 0]
size_consistency = 0.0
if len(orig_sizes) >= 5:
try:
size_cv = statistics.stdev(orig_sizes) / statistics.mean(orig_sizes)
size_consistency = max(0, 1.0 - size_cv)
except (statistics.StatisticsError, ZeroDivisionError):
pass
combined_score = (result["score"] * 0.7) + (size_consistency * 0.3)
if combined_score >= self.beacon_score_threshold:
confidence = "High" if combined_score >= 0.9 else "Medium"
alert = PrecursorAlert(
alert_id=f"BEACON-{src_ip}-{dst_ip}",
timestamp=datetime.fromtimestamp(max(timestamps)).isoformat(),
source_ip=src_ip,
dest_ip=dst_ip,
category="C2 Beaconing",
confidence=confidence,
kill_chain_phase="Command and Control",
description=(
f"Beaconing pattern detected: {result['connection_count']} connections "
f"at {result['interval']}s intervals (jitter: {result['jitter']}s, "
f"beacon score: {combined_score:.3f})"
),
mitre_technique="T1071 - Application Layer Protocol",
evidence=[
f"Beacon score: {combined_score:.3f}",
f"Interval: {result['interval']}s",
f"Jitter: {result['jitter']}s",
f"Payload size consistency: {size_consistency:.3f}",
f"Connections: {result['connection_count']}",
],
)
alerts.append(alert)
return alerts
class ScanDetector:
"""Detects internal reconnaissance scanning."""
def __init__(self, unique_dest_threshold: int = 30, time_window_seconds: int = 300):
self.threshold = unique_dest_threshold
self.window = time_window_seconds
self.connections = defaultdict(list)
def add_connection(self, src_ip: str, dst_ip: str, dst_port: int, timestamp: float):
self.connections[src_ip].append({
"dst_ip": dst_ip,
"dst_port": dst_port,
"ts": timestamp,
})
def detect(self) -> list:
alerts = []
for src_ip, conns in self.connections.items():
sorted_conns = sorted(conns, key=lambda c: c["ts"])
# Sliding window analysis
window_start = 0
for window_end in range(len(sorted_conns)):
while (sorted_conns[window_end]["ts"] - sorted_conns[window_start]["ts"]) > self.window:
window_start += 1
window_conns = sorted_conns[window_start:window_end + 1]
unique_dests = set(c["dst_ip"] for c in window_conns)
unique_ports = set(c["dst_port"] for c in window_conns)
if len(unique_dests) >= self.threshold:
alert = PrecursorAlert(
alert_id=f"SCAN-{src_ip}-{int(sorted_conns[window_start]['ts'])}",
timestamp=datetime.fromtimestamp(sorted_conns[window_end]["ts"]).isoformat(),
source_ip=src_ip,
dest_ip="Multiple",
category="Internal Reconnaissance",
confidence="High" if len(unique_dests) >= self.threshold * 2 else "Medium",
kill_chain_phase="Discovery",
description=(
f"Internal scan: {len(unique_dests)} unique destinations on "
f"{len(unique_ports)} ports within {self.window}s window"
),
mitre_technique="T1046 - Network Service Discovery",
evidence=[
f"Unique destinations: {len(unique_dests)}",
f"Unique ports: {sorted(unique_ports)}",
f"Total connections: {len(window_conns)}",
f"Time window: {self.window}s",
],
)
alerts.append(alert)
break # One alert per source IP per window
return alerts
class CredentialHarvestDetector:
"""Detects Kerberoasting and credential harvesting patterns."""
def __init__(self, kerberoast_threshold: int = 5):
self.threshold = kerberoast_threshold
self.tgs_requests = defaultdict(list)
self.smb_failures = defaultdict(int)
def add_kerberos_event(self, src_ip: str, service_name: str, encryption_type: str, timestamp: float):
self.tgs_requests[src_ip].append({
"service": service_name,
"enc_type": encryption_type,
"ts": timestamp,
})
def add_smb_failure(self, src_ip: str, dst_ip: str):
self.smb_failures[src_ip] += 1
def detect(self) -> list:
alerts = []
# Kerberoasting: multiple TGS requests for unique services with RC4 encryption
for src_ip, requests in self.tgs_requests.items():
rc4_requests = [r for r in requests if "rc4" in r.get("enc_type", "").lower()
or "23" in str(r.get("enc_type", ""))]
unique_services = set(r["service"] for r in rc4_requests)
if len(unique_services) >= self.threshold:
alert = PrecursorAlert(
alert_id=f"KERB-{src_ip}",
timestamp=datetime.fromtimestamp(max(r["ts"] for r in rc4_requests)).isoformat(),
source_ip=src_ip,
dest_ip="Domain Controller",
category="Kerberoasting",
confidence="High",
kill_chain_phase="Credential Access",
description=(
f"Possible Kerberoasting: {len(unique_services)} unique service ticket "
f"requests with RC4 encryption from single host"
),
mitre_technique="T1558.003 - Kerberoasting",
evidence=[
f"Unique services targeted: {len(unique_services)}",
f"RC4 encryption requests: {len(rc4_requests)}",
f"Services: {list(unique_services)[:10]}",
],
)
alerts.append(alert)
# SMB brute force
for src_ip, count in self.smb_failures.items():
if count >= 10:
alert = PrecursorAlert(
alert_id=f"SMB-BRUTE-{src_ip}",
timestamp=datetime.now().isoformat(),
source_ip=src_ip,
dest_ip="Multiple",
category="SMB Brute Force",
confidence="Medium",
kill_chain_phase="Credential Access",
description=f"SMB authentication failures: {count} failed attempts",
mitre_technique="T1110 - Brute Force",
evidence=[f"Failed SMB auth count: {count}"],
)
alerts.append(alert)
return alerts
class AdminShareDetector:
"""Detects suspicious access to administrative shares (C$, ADMIN$, IPC$)."""
def __init__(self, threshold: int = 5):
self.threshold = threshold
self.share_access = defaultdict(lambda: defaultdict(set))
def add_share_access(self, src_ip: str, dst_ip: str, share_name: str, timestamp: float):
admin_shares = {"ADMIN$", "C$", "IPC$", "D$", "E$"}
normalized_share = share_name.split("\\")[-1].upper()
if normalized_share in admin_shares:
self.share_access[src_ip][normalized_share].add(dst_ip)
def detect(self) -> list:
alerts = []
for src_ip, shares in self.share_access.items():
total_targets = set()
for share, targets in shares.items():
total_targets.update(targets)
if len(total_targets) >= self.threshold:
alert = PrecursorAlert(
alert_id=f"ADMINSHARE-{src_ip}",
timestamp=datetime.now().isoformat(),
source_ip=src_ip,
dest_ip="Multiple",
category="Admin Share Enumeration",
confidence="High" if len(total_targets) >= self.threshold * 2 else "Medium",
kill_chain_phase="Lateral Movement",
description=(
f"Admin share access to {len(total_targets)} hosts: "
f"shares accessed: {list(shares.keys())}"
),
mitre_technique="T1021.002 - SMB/Windows Admin Shares",
evidence=[
f"Unique targets: {len(total_targets)}",
f"Shares accessed: {dict((s, len(t)) for s, t in shares.items())}",
],
)
alerts.append(alert)
return alerts
class RansomwarePrecursorEngine:
"""Orchestrates all detection modules."""
def __init__(self):
self.beacon_detector = BeaconDetector()
self.scan_detector = ScanDetector()
self.cred_detector = CredentialHarvestDetector()
self.share_detector = AdminShareDetector()
self.alerts = []
def load_zeek_conn_log(self, filepath: str):
"""Parse Zeek conn.log for beacon and scan detection."""
with open(filepath, "r") as f:
for line in f:
if line.startswith("#"):
continue
fields = line.strip().split("\t")
if len(fields) < 20:
continue
try:
ts = float(fields[0])
src_ip = fields[2]
src_port = int(fields[3]) if fields[3] != "-" else 0
dst_ip = fields[4]
dst_port = int(fields[5]) if fields[5] != "-" else 0
proto = fields[6]
orig_bytes = int(fields[9]) if fields[9] != "-" else 0
resp_bytes = int(fields[10]) if fields[10] != "-" else 0
# Feed to beacon detector (external destinations)
if not self._is_internal(dst_ip):
self.beacon_detector.add_connection(src_ip, dst_ip, ts, orig_bytes, resp_bytes)
# Feed to scan detector (internal destinations)
if self._is_internal(src_ip) and self._is_internal(dst_ip):
self.scan_detector.add_connection(src_ip, dst_ip, dst_port, ts)
except (ValueError, IndexError):
continue
def _is_internal(self, ip: str) -> bool:
"""Check if IP is in RFC1918 private range."""
parts = ip.split(".")
if len(parts) != 4:
return False
try:
first = int(parts[0])
second = int(parts[1])
if first == 10:
return True
if first == 172 and 16 <= second <= 31:
return True
if first == 192 and second == 168:
return True
except ValueError:
pass
return False
def run_detection(self) -> list:
"""Run all detectors and return combined alerts."""
self.alerts = []
self.alerts.extend(self.beacon_detector.detect())
self.alerts.extend(self.scan_detector.detect())
self.alerts.extend(self.cred_detector.detect())
self.alerts.extend(self.share_detector.detect())
# Sort by confidence (High first)
confidence_order = {"High": 0, "Medium": 1, "Low": 2}
self.alerts.sort(key=lambda a: confidence_order.get(a.confidence, 3))
return self.alerts
def generate_report(self) -> str:
"""Generate formatted detection report."""
if not self.alerts:
self.run_detection()
lines = []
lines.append("=" * 70)
lines.append("RANSOMWARE PRECURSOR DETECTION REPORT")
lines.append("=" * 70)
lines.append(f"Generated: {datetime.now().isoformat()}")
lines.append(f"Total Alerts: {len(self.alerts)}")
by_category = defaultdict(list)
for alert in self.alerts:
by_category[alert.category].append(alert)
lines.append(f"\nAlert Categories:")
for cat, cat_alerts in sorted(by_category.items()):
lines.append(f" - {cat}: {len(cat_alerts)}")
lines.append("")
for i, alert in enumerate(self.alerts, 1):
lines.append("-" * 50)
lines.append(f"Alert #{i}: {alert.alert_id}")
lines.append(f" Category: {alert.category}")
lines.append(f" Confidence: {alert.confidence}")
lines.append(f" Kill Chain: {alert.kill_chain_phase}")
lines.append(f" Source: {alert.source_ip}")
lines.append(f" Destination: {alert.dest_ip}")
lines.append(f" MITRE: {alert.mitre_technique}")
lines.append(f" Description: {alert.description}")
lines.append(f" Evidence:")
for e in alert.evidence:
lines.append(f" - {e}")
lines.append("")
lines.append("=" * 70)
return "\n".join(lines)
def main():
"""Run detection engine with sample data or Zeek log file."""
engine = RansomwarePrecursorEngine()
# Check for Zeek conn.log argument
if len(sys.argv) > 1:
log_file = sys.argv[1]
if os.path.exists(log_file):
print(f"Loading Zeek conn.log: {log_file}")
engine.load_zeek_conn_log(log_file)
else:
print(f"File not found: {log_file}")
sys.exit(1)
else:
# Demo with simulated data
print("No Zeek log provided. Running with simulated beacon data...")
import time
base_time = time.time() - 3600 # 1 hour ago
# Simulate Cobalt Strike beacon (60-second interval)
for i in range(40):
jitter = (i % 3) * 2 # Small jitter
engine.beacon_detector.add_connection(
"10.1.5.42", "185.220.101.42",
base_time + (i * 60) + jitter,
orig_bytes=48, resp_bytes=128,
)
# Simulate internal port scan
for i in range(50):
engine.scan_detector.add_connection(
"10.1.5.42", f"10.1.5.{100 + i}", 445,
base_time + 1800 + (i * 2),
)
# Simulate Kerberoasting
for i in range(8):
engine.cred_detector.add_kerberos_event(
"10.1.5.42", f"MSSQLSvc/sql{i}.corp.local:1433",
"rc4-hmac", base_time + 2000 + (i * 5),
)
# Simulate admin share access
for i in range(12):
engine.share_detector.add_share_access(
"10.1.5.42", f"10.1.5.{200 + i}", "ADMIN$",
base_time + 2500 + (i * 10),
)
report = engine.generate_report()
print(report)
# Export alerts as JSON
alerts_json = [asdict(a) for a in engine.alerts]
output_path = Path(__file__).parent / "precursor_alerts.json"
with open(output_path, "w") as f:
json.dump(alerts_json, f, indent=2)
print(f"\nAlerts exported to: {output_path}")
if __name__ == "__main__":
main()