Lesson 10 of 10
Practice & Quiz - Advanced Threats & Threat Hunting
Test your advanced threat knowledge: APT TTPs, ransomware kill chain, supply chain attacks, threat hunting queries, and MITRE ATT&CK mapping with a practical Sigma rule exercise and 5 quiz questions.
Practical Exercise - Threat Hunting with Sigma Rules & Log Analysis
#!/usr/bin/env python3
"""
Threat Hunting: Sigma rule writing and log correlation.
Sigma rules are SIEM-agnostic detection signatures (like Snort for logs).
"""
import json, re, datetime
from dataclasses import dataclass, field
# ─── Sigma Rule Structure ─────────────────────────────────────
# Sigma is YAML-based, but we'll represent as Python dicts for analysis
SIGMA_RULES = {
'ransomware_shadow_delete': {
'title': 'Shadow Copy Deletion - Ransomware Pre-Stage',
'id': 'e7b5b3e2-1234-5678-abcd-ef1234567890',
'status': 'stable',
'description': 'Detects vssadmin or wmic commands used to delete shadow copies - common ransomware behavior before encryption',
'references': ['https://attack.mitre.org/techniques/T1490/'],
'author': 'Security Team',
'tags': ['attack.impact', 'attack.t1490'],
'logsource': {'category': 'process_creation', 'product': 'windows'},
'detection': {
'selection_vss': {
'CommandLine|contains|all': ['vssadmin', 'delete', 'shadows'],
},
'selection_wmic': {
'CommandLine|contains|all': ['wmic', 'shadowcopy', 'delete'],
},
'selection_bcdedit': {
'CommandLine|contains|all': ['bcdedit', 'recoveryenabled', 'no'],
},
'condition': 'selection_vss or selection_wmic or selection_bcdedit',
},
'falsepositives': ['Legitimate backup administration', 'IT maintenance scripts'],
'level': 'critical',
'mitre_attack': 'T1490 - Inhibit System Recovery',
},
'lateral_movement_psexec': {
'title': 'PsExec Remote Execution - Lateral Movement',
'status': 'stable',
'description': 'Detects PsExec usage for lateral movement - creates PSEXESVC service on remote host',
'tags': ['attack.lateral_movement', 'attack.t1021.002'],
'logsource': {'category': 'process_creation', 'product': 'windows'},
'detection': {
'selection': {
'Image|endswith': ['\\psexec.exe', '\\psexec64.exe', '\\PsExec.exe'],
},
'condition': 'selection',
},
'level': 'high',
'mitre_attack': 'T1021.002 - SMB/Windows Admin Shares',
},
'persistence_registry_run': {
'title': 'Registry Run Key Persistence',
'status': 'stable',
'description': 'Detects modifications to common persistence registry keys',
'tags': ['attack.persistence', 'attack.t1547.001'],
'logsource': {'category': 'registry_event', 'product': 'windows'},
'detection': {
'selection': {
'TargetObject|contains': [
'HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run',
'HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Run',
'HKEY_USERS\\Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce',
],
},
'filter_legit': {
'Details|contains': [
'OneDrive', 'Dropbox', 'Spotify', # common legitimate entries
],
},
'condition': 'selection and not filter_legit',
},
'level': 'medium',
'mitre_attack': 'T1547.001 - Registry Run Keys / Startup Folder',
},
}
# ─── Log Event Matcher ─────────────────────────────────────────
class SigmaDetector:
def __init__(self, rules: dict):
self.rules = rules
def match_event(self, event: dict) -> list[dict]:
"""Match a Windows event against all sigma rules."""
matches = []
for rule_name, rule in self.rules.items():
if self._evaluate_detection(rule.get('detection', {}), event):
matches.append({
'rule': rule['title'],
'level': rule.get('level', 'unknown'),
'mitre': rule.get('mitre_attack', ''),
'event': event,
})
return matches
def _evaluate_detection(self, detection: dict, event: dict) -> bool:
"""Simplified Sigma detection evaluation."""
condition = detection.get('condition', '')
selections = {}
for key, criteria in detection.items():
if key in ('condition',) or key.startswith('filter_'):
continue
selections[key] = self._match_selection(criteria, event)
# Evaluate simple conditions
for sel_name, matched in selections.items():
if sel_name in condition and matched:
return True
return False
def _match_selection(self, criteria: dict, event: dict) -> bool:
for field_mod, values in criteria.items():
parts = field_mod.split('|')
field = parts[0]
modifiers = parts[1:] if len(parts) > 1 else []
field_value = event.get(field, '')
if 'contains|all' in '|'.join(modifiers):
if isinstance(values, list):
return all(v.lower() in field_value.lower() for v in values)
elif 'endswith' in modifiers:
return any(field_value.endswith(v) for v in (values if isinstance(values, list) else [values]))
elif 'contains' in modifiers:
return any(v in field_value for v in (values if isinstance(values, list) else [values]))
return False
# ─── Simulate Ransomware Attack Events ────────────────────────
detector = SigmaDetector(SIGMA_RULES)
attack_events = [
{'CommandLine': 'vssadmin delete shadows /all /quiet', 'Image': 'vssadmin.exe'},
{'CommandLine': 'wmic shadowcopy delete', 'Image': 'wmic.exe'},
{'CommandLine': 'bcdedit /set recoveryenabled no', 'Image': 'bcdedit.exe'},
{'Image': 'C:\\Tools\\PsExec.exe', 'CommandLine': 'psexec \\\\192.168.1.50 cmd'},
{'TargetObject': 'HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\\MalwareXYZ'},
]
print('=== Threat Hunting: Sigma Rule Matches ===')
for event in attack_events:
matches = detector.match_event(event)
for match in matches:
print(f'🚨 [{match["level"].upper()}] {match["rule"]}')
print(f' MITRE: {match["mitre"]}')
print(f' Event: {json.dumps(event)[:100]}')Module Quiz
What is an APT (Advanced Persistent Threat) and what distinguishes it from opportunistic cybercrime?
Tip
Tip
Practice Practice Quiz Advanced Threats Threat Hunting in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
The foundational security model: Confidentiality (privacy), Integrity (trust), and Availability (uptime).
Practice Task
Note
Practice Task - (1) Write a working example of Practice Quiz Advanced Threats Threat Hunting from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Practice Quiz Advanced Threats Threat Hunting is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cybersecurity code.
Finished this lesson?