import enum
import json
from typing import List, Dict, Callable, Any
# ==========================================
# 1. Data Structures & Enums
# ==========================================
class IncidentType(enum.Enum):
MALWARE = "MALWARE"
PHISHING = "PHISHING"
UNAUTHORIZED_ACCESS = "UNAUTHORIZED_ACCESS"
DLP = "DATA_LEAK"
class AssetCriticality(enum.Enum):
LOW = 1
MEDIUM = 2
HIGH = 3
CROWN_JEWEL = 4
class ActionSeverity(enum.Enum):
INVESTIGATIVE = "INVESTIGATIVE" # Safe actions (Enrichment)
REMEDIATIVE = "REMEDIATIVE" # Mild actions (Quarantine, Reset Password)
DISRUPTIVE = "DISRUPTIVE" # Severe actions (Shutdown Server, Firewall Block)
# ==========================================
# 2. Context Objects
# ==========================================
class Evidence:
def __init__(self, source: str, confidence: float, details: str):
self.source = source
self.confidence = confidence
self.details = details
class Incident:
def __init__(self, inc_id: str, inc_type: IncidentType, asset_crit: AssetCriticality, evidence_list: List[Evidence]):
self.inc_id = inc_id
self.type = inc_type
self.asset_criticality = asset_crit
self.evidence_list = evidence_list
def calculate_aggregate_confidence(self) -> float:
"""Weighted average or max confidence logic"""
if not self.evidence_list:
return 0.0
# Simple average for demonstration
return sum(e.confidence for e in self.evidence_list) / len(self.evidence_list)
# ==========================================
# 3. The Dynamic Playbook Engine
# ==========================================
class PlaybookEngine:
def __init__(self):
self.action_registry = {
"enrich_ip": self._action_enrich_ip,
"isolate_host": self._action_isolate_host,
"reset_password": self._action_reset_password,
"notify_tier1": self._action_notify_t1,
"escalate_tier2": self._action_escalate_t2,
"block_hash": self._action_block_hash
}
# --- Mock Action Executors ---
def _action_enrich_ip(self, incident: Incident):
return {"status": "success", "message": f"IP Enrichment complete for {incident.inc_id}"}
def _action_isolate_host(self, incident: Incident):
return {"status": "critical", "message": f"Host isolated for {incident.inc_id}"}
def _action_reset_password(self, incident: Incident):
return {"status": "success", "message": "Password reset triggered"}
def _action_notify_t1(self, incident: Incident):
return {"status": "success", "message": "Slack notification sent to SOC Tier 1"}
def _action_escalate_tier2(self, incident: Incident):
return {"status": "success", "message": "Jira ticket created for Tier 2 / On-Call"}
def _action_block_hash(self, incident: Incident):
return {"status": "success", "message": "Hash blocked globally"}
# --- The Core Logic Generator ---
def generate_flow(self, incident: Incident) -> List[Dict]:
"""
Dynamically generates a list of actions based on classification,
evidence quality, and criticality.
"""
flow = []
confidence = incident.calculate_aggregate_confidence()
print(f"--- Generating Playbook for {incident.inc_id} ---")
print(f"Type: {incident.type.value} | Confidence: {confidence:.2f} | Criticality: {incident.asset_criticality.name}")
# RULE SET 1: General Hygiene (Always Enrich)
flow.append({"action": "enrich_ip", "severity": ActionSeverity.INVESTIGATIVE})
# RULE SET 2: Malware Logic
if incident.type == IncidentType.MALWARE:
if confidence > 0.8:
# High confidence malware -> Block Hash immediately
flow.append({"action": "block_hash", "severity": ActionSeverity.REMEDIATIVE})
# Isolation logic based on Asset Criticality vs Risk
if incident.asset_criticality in [AssetCriticality.LOW, AssetCriticality.MEDIUM]:
flow.append({"action": "isolate_host", "severity": ActionSeverity.REMEDIATIVE})
elif incident.asset_criticality == AssetCriticality.HIGH:
# High value asset: Isolate only if confidence is very high, otherwise alert
if confidence > 0.9:
flow.append({"action": "isolate_host", "severity": ActionSeverity.REMEDIATIVE})
else:
flow.append({"action": "escalate_tier2", "severity": ActionSeverity.INVESTIGATIVE})
elif incident.asset_criticality == AssetCriticality.CROWN_JEWEL:
# Never auto-isolate Crown Jewels; always escalate for human decision
flow.append({"action": "escalate_tier2", "severity": ActionSeverity.INVESTIGATIVE})
# RULE SET 3: Unauthorized Access Logic
elif incident.type == IncidentType.UNAUTHORIZED_ACCESS:
if confidence > 0.7:
flow.append({"action": "reset_password", "severity": ActionSeverity.REMEDIATIVE})
flow.append({"action": "notify_tier1", "severity": ActionSeverity.INVESTIGATIVE})
else:
# Low confidence access -> Just notify
flow.append({"action": "notify_tier1", "severity": ActionSeverity.INVESTIGATIVE})
return flow
# --- Executor ---
def execute_flow(self, incident: Incident, flow: List[Dict]):
results = []
print(f"\n>>> Executing Dynamic Playbook for {incident.inc_id}")
requires_human_approval = any(
step['severity'] == ActionSeverity.DISRUPTIVE or
(step['severity'] == ActionSeverity.REMEDIATIVE and incident.asset_criticality == AssetCriticality.CROWN_JEWEL)
for step in flow
)
if requires_human_approval:
print("!! ALERT: Execution requires Human Approval due to Asset Criticality or Action Severity !!")
# In a real platform, this would pause the playbook and ping the SOC analyst
# return results
for step in flow:
action_name = step["action"]
if action_name in self.action_registry:
print(f"Running: {action_name}...")
result = self.action_registry[action_name](incident)
results.append(result)
else:
results.append({"status": "error", "message": f"Action {action_name} not found"})
return results
# ==========================================
# 4. Simulation / Main Execution
# ==========================================
if __name__ == "__main__":
engine = PlaybookEngine()
# Scenario A: High Confidence Malware on Low Criticality Asset
# Expected: Enrich, Block Hash, Auto-Isolate
evid_a = [Evidence("EDR", 0.95, "Trojan.Generic"), Evidence("SIEM", 0.85, "C2 Beaconing")]
incident_a = Incident("INC-101", IncidentType.MALWARE, AssetCriticality.LOW, evid_a)
flow_a = engine.generate_flow(incident_a)
engine.execute_flow(incident_a, flow_a)
print("-" * 50)
# Scenario B: Medium Confidence Malware on Crown Jewel
# Expected: Enrich, Escalate (Do NOT Isolate)
evid_b = [Evidence("Firewall", 0.65, "Suspicious outbound traffic")]
incident_b = Incident("INC-102", IncidentType.MALWARE, AssetCriticality.CROWN_JEWEL, evid_b)
flow_b = engine.generate_flow(incident_b)
engine.execute_flow(incident_b, flow_b)
print("-" * 50)
# Scenario C: Low Confidence Unauthorized Access
# Expected: Enrich, Notify T1 (Do NOT Reset Password)
evid_c = [Evidence("IAM", 0.30, "Login from unusual country")]
incident_c = Incident("INC-103", IncidentType.UNAUTHORIZED_ACCESS, AssetCriticality.MEDIUM, evid_c)
flow_c = engine.generate_flow(incident_c)
engine.execute_flow(incident_c, flow_c)