""" Playbook: notify-alert Recibe incidentes desde una cola SQS dedicada y publica una notificacion estructurada en SNS. Tambien deja evidencia operativa en S3. Incidentes soportados: - BRUTE_FORCE (severity HIGH) → Componente C, Incidente 1 - PORT_SCAN (severity MEDIUM) → Componente C, Incidente 2 - PRIVILEGE_ESCALATION (severity CRITICAL) - CREDENTIAL_LEAK (severity CRITICAL) - EXFILTRATION (severity HIGH) """ import json import os import uuid from datetime import datetime from zoneinfo import ZoneInfo import boto3 sns = boto3.client("sns") s3 = boto3.client("s3") SNS_ARN = os.environ["SNS_ALERTS_ARN"] EVIDENCE_BUCKET = os.environ["EVIDENCE_BUCKET"] RESPONSE_PREFIX = os.environ.get("RESPONSE_PREFIX", "responses/notify-alert") EC_TZ = ZoneInfo("America/Guayaquil") # Tipos de incidente que este playbook debe procesar. # Cualquier otro tipo se omite (skip) para evitar procesamiento no intencionado. SUPPORTED_INCIDENT_TYPES = { "BRUTE_FORCE", "PORT_SCAN", "PRIVILEGE_ESCALATION", "CREDENTIAL_LEAK", "EXFILTRATION", } def now_ecuador() -> str: return datetime.now(EC_TZ).isoformat() def lambda_handler(event, context): results = [] for record in event.get("Records", []): try: body = json.loads(record.get("body", "{}")) except json.JSONDecodeError as exc: results.append({"status": "skipped", "reason": f"invalid_json: {exc}"}) continue incident_type = body.get("incident_type", "UNKNOWN") if incident_type not in SUPPORTED_INCIDENT_TYPES: results.append({"status": "skipped", "reason": f"unsupported_type:{incident_type}"}) continue # ── Construir alerta estructurada ────────────────────────────────── alert = { "alert_type": "SECURITY_INCIDENT", "incident_type": incident_type, "severity": body.get("severity", "MEDIUM"), "sourceIPAddress": body.get("sourceIPAddress", "unknown"), "affectedResource": body.get("affectedResource", "unknown"), "affected_service": body.get("affected_service", body.get("affectedService", "unknown")), "asset_name": body.get("asset_name", body.get("assetName", "unknown")), "severity_basis": body.get("severity_basis", f"Umbral de {incident_type} alcanzado."), "detectedAt": body.get("timestamp", now_ecuador()), "respondedAt": now_ecuador(), "timezone": "America/Guayaquil", "playbook": "notify-alert", "status": "NOTIFIED", "s3_log_key": body.get("s3_log_key", ""), "incident_id": body.get("incident_id", ""), } # Campos extra según el tipo de incidente if incident_type == "PORT_SCAN": alert["scanned_ports_count"] = body.get("scanned_ports_count", body.get("event_count", 0)) alert["rejected_connections"] = body.get("rejected_connections", 0) elif incident_type == "BRUTE_FORCE": alert["failed_attempts"] = body.get("failed_attempts", body.get("event_count", 0)) alert["detection_window"] = body.get("detection_window", "5 minutes") # ── Guardar evidencia en S3 ──────────────────────────────────────── key = f"{RESPONSE_PREFIX}/{body.get('incident_id') or uuid.uuid4().hex}.json" s3.put_object( Bucket=EVIDENCE_BUCKET, Key=key, Body=json.dumps(alert, indent=2, ensure_ascii=False).encode("utf-8"), ContentType="application/json", ) # ── Publicar en SNS ──────────────────────────────────────────────── subject = f"[{alert['severity']}] Playbook notify-alert: {incident_type}" sns.publish( TopicArn=SNS_ARN, Subject=subject[:100], Message=json.dumps(alert, indent=2, ensure_ascii=False), ) print(f"[notify-alert] {incident_type} notificado. evidence_key={key}") results.append({"status": "success", "action": "sns_published", "evidence_key": key}) return { "status": "success", "processed": len(results), "results": results, "timestamp": now_ecuador(), }