Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /mcp_pentest_suite /compliance.py
"""
Compliance Module - Legal and regulatory framework enforcement.
Ensures all pentest activities comply with:
- GDPR (EU General Data Protection Regulation)
- BSI Grundschutz (German Federal Office for Information Security)
- NIST Cybersecurity Framework
- OWASP Testing Guide
- PTES (Penetration Testing Execution Standard)
- ISO 27001
Provides: Compliance checks, Legal document generation,
Scope validation, Data protection enforcement.
Author: Cybersecurity AI Architect
"""
import hashlib
import json
import logging
import os
import re
from dataclasses import asdict, dataclass, field
from datetime import datetime, timedelta
from enum import Enum
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
# ---------------------------------------------------------------------------
# Enums
# ---------------------------------------------------------------------------
class Regulation(Enum):
"""Supported regulatory frameworks."""
GDPR = "gdpr" # EU General Data Protection Regulation
BSI = "bsi" # Germany Federal Office for Information Security
NIST = "nist" # US NIST Cybersecurity Framework
ISO27001 = "iso27001" # International ISO 27001
PTES = "ptes" # Penetration Testing Execution Standard
OWASP = "owasp" # OWASP Testing Guide
SOX = "sox" # US Sarbanes-Oxley Act
HIPAA = "hipaa" # US Health Insurance Portability and Accountability Act
class ComplianceStatus(Enum):
"""Result of a single compliance check."""
COMPLIANT = "compliant"
VIOLATION = "violation"
WARNING = "warning"
NOT_APPLICABLE = "not_applicable"
# ---------------------------------------------------------------------------
# Data classes
# ---------------------------------------------------------------------------
@dataclass
class ComplianceCheck:
"""Single compliance rule with its result."""
rule_id: str
regulation: Regulation
name: str
description: str
check_function: str
severity: str # critical | high | medium | low
remediation: str
status: ComplianceStatus = ComplianceStatus.NOT_APPLICABLE
details: str = ""
timestamp: str = field(default_factory=lambda: datetime.now().isoformat())
def to_dict(self) -> Dict[str, Any]:
"""Serialize to dictionary."""
d = asdict(self)
d["regulation"] = self.regulation.value
d["status"] = self.status.value
return d
@dataclass
class ComplianceReport:
"""Aggregated compliance report for a pentest session."""
session_id: str
target: str
overall_status: ComplianceStatus
checks: List[ComplianceCheck]
violations: List[ComplianceCheck]
warnings: List[ComplianceCheck]
compliant_items: List[ComplianceCheck]
generated_at: str = field(default_factory=lambda: datetime.now().isoformat())
regulations_checked: List[Regulation] = field(default_factory=list)
def to_dict(self) -> Dict[str, Any]:
"""Serialize to dictionary."""
return {
"session_id": self.session_id,
"target": self.target,
"overall_status": self.overall_status.value,
"checks": [c.to_dict() for c in self.checks],
"violations": [c.to_dict() for c in self.violations],
"warnings": [c.to_dict() for c in self.warnings],
"compliant_items": [c.to_dict() for c in self.compliant_items],
"generated_at": self.generated_at,
"regulations_checked": [r.value for r in self.regulations_checked],
}
@dataclass
class AuthorizationDocument:
"""ROE (Rules of Engagement) document with cryptographic integrity."""
client_name: str
target_scope: List[str]
start_date: str
end_date: str
test_types: List[str] # e.g. blackbox, greybox, whitebox
approved_methods: List[str]
emergency_contact: str
authorization_token: str = ""
signed_by: str = ""
signed_date: str = ""
document_hash: str = ""
def compute_hash(self) -> str:
"""Compute SHA-256 over all fields except document_hash itself."""
payload = {
"client_name": self.client_name,
"target_scope": sorted(self.target_scope),
"start_date": self.start_date,
"end_date": self.end_date,
"test_types": sorted(self.test_types),
"approved_methods": sorted(self.approved_methods),
"emergency_contact": self.emergency_contact,
"authorization_token": self.authorization_token,
"signed_by": self.signed_by,
"signed_date": self.signed_date,
}
canonical = json.dumps(payload, sort_keys=True, ensure_ascii=False)
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
def sign(self, signed_by: str, token: str) -> None:
"""Sign the document with an authorization token."""
self.signed_by = signed_by
self.signed_date = datetime.now().isoformat()
self.authorization_token = token
self.document_hash = self.compute_hash()
def verify_integrity(self) -> bool:
"""Verify the document hash matches current content."""
if not self.document_hash:
return False
return self.document_hash == self.compute_hash()
def to_dict(self) -> Dict[str, Any]:
"""Serialize to dictionary."""
return asdict(self)
# ---------------------------------------------------------------------------
# Compliance Manager
# ---------------------------------------------------------------------------
class ComplianceManager:
"""
Main compliance manager coordinating all regulatory checks.
Instantiate once per pentest engagement, load an *AuthorizationDocument*
and call :meth:`run_full_compliance_check` before any scan activity.
"""
def __init__(self, config: Optional[Dict[str, Any]] = None) -> None:
self.config: Dict[str, Any] = config or {}
self.logger: logging.Logger = logging.getLogger("compliance")
self.rules: Dict[str, ComplianceCheck] = self._load_all_rules()
self.authorization: Optional[AuthorizationDocument] = None
self._session_cache: Dict[str, Any] = {} # internal mutable session state
# ------------------------------------------------------------------
# Rule loader
# ------------------------------------------------------------------
def _load_all_rules(self) -> Dict[str, ComplianceCheck]:
"""Register every compliance rule that the manager knows about."""
rules: Dict[str, ComplianceCheck] = {}
registry: List[Tuple[str, Regulation, str, str, str, str, str]] = [
# GDPR
(
"GDPR-001",
Regulation.GDPR,
"Legal Basis for Processing",
"GDPR Art. 6 - A valid legal basis must exist for security testing.",
"check_gdpr_authorization",
"critical",
"Obtain written authorization (Art. 6(1)(a) or (f)) before testing.",
),
(
"GDPR-002",
Regulation.GDPR,
"Data Minimization",
"GDPR Art. 5(1)(c) - Only process personal data that is necessary.",
"check_gdpr_data_minimization",
"high",
"Configure scanners to exclude PII fields; use anonymised test data.",
),
(
"GDPR-003",
Regulation.GDPR,
"Storage Limitation",
"GDPR Art. 5(1)(e) - Personal data must not be kept indefinitely.",
"check_gdpr_storage_limitation",
"high",
"Set automatic data-retention policies (max 90 days for raw logs).",
),
(
"GDPR-004",
Regulation.GDPR,
"Security of Processing",
"GDPR Art. 32 - Appropriate technical measures to protect data.",
"check_gdpr_security",
"critical",
"Encrypt all evidence at rest (AES-256) and in transit (TLS 1.3).",
),
(
"GDPR-005",
Regulation.GDPR,
"Breach Notification",
"GDPR Art. 33 - Notify DPA within 72h of personal-data breach.",
"check_gdpr_breach_notification",
"critical",
"Establish incident-response channel with client DPO before testing.",
),
# BSI
(
"BSI-001",
Regulation.BSI,
"Written Authorization",
"BSI Grundschutz - A written testing mandate is mandatory.",
"check_bsi_authorization",
"critical",
"Store the signed ROE document and verify its scope before testing.",
),
(
"BSI-002",
Regulation.BSI,
"Scope Definition",
"BSI Grundschutz - IP ranges, systems and time windows must be defined.",
"check_bsi_scope_definition",
"high",
"Explicitly list in-scope / out-of-scope CIDR blocks and systems.",
),
(
"BSI-003",
Regulation.BSI,
"Emergency Procedure",
"BSI Grundschutz - Emergency contact and abort procedures required.",
"check_bsi_emergency_procedure",
"high",
"Provide 24/7 emergency contact and automated kill-switch capability.",
),
# NIST CSF
(
"NIST-001",
Regulation.NIST,
"Identify Function",
"NIST CSF ID - Asset management and risk assessment.",
"check_nist_identify",
"medium",
"Document all target assets and business-impact ratings in scope.",
),
(
"NIST-002",
Regulation.NIST,
"Protect Function",
"NIST CSF PR - Safeguards to manage access and data security.",
"check_nist_protect",
"medium",
"Ensure test credentials follow least-privilege and MFA policies.",
),
(
"NIST-003",
Regulation.NIST,
"Detect Function",
"NIST CSF DE - Continuous monitoring and anomaly detection.",
"check_nist_detect",
"medium",
"Verify client SOC visibility so tests are not treated as rogue attacks.",
),
(
"NIST-004",
Regulation.NIST,
"Respond Function",
"NIST CSF RS - Response planning and communication.",
"check_nist_respond",
"high",
"Agree on incident-response playbooks before exploitation begins.",
),
(
"NIST-005",
Regulation.NIST,
"Recover Function",
"NIST CSF RC - Recovery plans and improvements.",
"check_nist_recover",
"medium",
"Document rollback steps for any changes made during exploitation.",
),
# PTES
(
"PTES-001",
Regulation.PTES,
"Pre-engagement Interactions",
"PTES Phase 1 - Goals, scope and rules established.",
"check_ptes_pre_engagement",
"critical",
"Hold kick-off meeting; sign ROE; exchange GPG keys for report delivery.",
),
(
"PTES-002",
Regulation.PTES,
"Intelligence Gathering",
"PTES Phase 2 - Passive and active reconnaissance.",
"check_ptes_intelligence",
"medium",
"Limit OSINT to public sources; respect robots.txt and rate limits.",
),
(
"PTES-003",
Regulation.PTES,
"Threat Modeling",
"PTES Phase 3 - Identify likely threat actors and attack vectors.",
"check_ptes_threat_modeling",
"medium",
"Document threat model assumptions and share with client.",
),
(
"PTES-004",
Regulation.PTES,
"Vulnerability Analysis",
"PTES Phase 4 - Discover and validate vulnerabilities.",
"check_ptes_vuln_analysis",
"high",
"Never run exploits against production without explicit go-ahead.",
),
(
"PTES-005",
Regulation.PTES,
"Exploitation",
"PTES Phase 5 - Controlled exploitation with client consent.",
"check_ptes_exploitation",
"critical",
"Require per-exploit approval; use non-destructive payloads first.",
),
(
"PTES-006",
Regulation.PTES,
"Post Exploitation",
"PTES Phase 6 - Privilege escalation, pivoting, data access.",
"check_ptes_post_exploitation",
"critical",
"Never access PII; stop immediately when scope boundary reached.",
),
(
"PTES-007",
Regulation.PTES,
"Reporting",
"PTES Phase 7 - Deliver findings with risk ratings and remediation.",
"check_ptes_reporting",
"high",
"Encrypt reports; deliver via secure channel; destroy drafts after handover.",
),
# OWASP
(
"OWASP-001",
Regulation.OWASP,
"Testing Guide Methodology",
"OWASP WSTG - Follow the Web Security Testing Guide workflow.",
"check_owasp_methodology",
"medium",
"Map every test case to a WSTG identifier for traceability.",
),
(
"OWASP-002",
Regulation.OWASP,
"Top 10 Coverage",
"OWASP Top 10 - Ensure all Top 10 categories are addressed.",
"check_owasp_top10_coverage",
"high",
"Explicitly test for Broken Access Control, Cryptographic Failures, "
"Injection, Insecure Design, Security Misconfiguration, Vulnerable "
"Components, Auth Failures, Software Integrity Failures, "
"Logging Failures, SSRF.",
),
]
for r in registry:
rule_id, reg, name, desc, func, sev, rem = r
rules[rule_id] = ComplianceCheck(
rule_id=rule_id,
regulation=reg,
name=name,
description=desc,
check_function=func,
severity=sev,
remediation=rem,
)
self.logger.info("Loaded %d compliance rules", len(rules))
return rules
# ------------------------------------------------------------------
# Internal helpers
# ------------------------------------------------------------------
def _get_session_data(self, session_id: str) -> Dict[str, Any]:
"""Retrieve session-specific mutable data (stub for integration)."""
if session_id not in self._session_cache:
self._session_cache[session_id] = {
"personal_data_accessed": False,
"personal_data_records": 0,
"logs_encrypted": True,
"exploitation_performed": False,
"exploits_approved": False,
"scope_exceeded": False,
"dpo_contact": "",
"test_start": None,
"test_end": None,
"auth_present": self.authorization is not None,
"target_assets": [],
"vulnerabilities_found": [],
"threat_model_documented": False,
"owasp_tests_mapped": [],
}
return self._session_cache[session_id]
def _mk_result(self, rule_id: str, status: ComplianceStatus, details: str) -> ComplianceCheck:
"""Clone a rule definition and attach a concrete result."""
base = self.rules[rule_id]
return ComplianceCheck(
rule_id=base.rule_id,
regulation=base.regulation,
name=base.name,
description=base.description,
check_function=base.check_function,
severity=base.severity,
remediation=base.remediation,
status=status,
details=details,
)
# ------------------------------------------------------------------
# GDPR Checks
# ------------------------------------------------------------------
def check_gdpr_authorization(self, session_id: str) -> ComplianceCheck:
"""GDPR Art. 6 - Verify a legal basis exists (consent or legitimate interest)."""
sd = self._get_session_data(session_id)
if self.authorization and self.authorization.verify_integrity():
return self._mk_result(
"GDPR-001",
ComplianceStatus.COMPLIANT,
f"Valid authorization signed by {self.authorization.signed_by} on {self.authorization.signed_date}.",
)
return self._mk_result(
"GDPR-001", ComplianceStatus.VIOLATION, "No valid authorization document loaded or hash verification failed."
)
def check_gdpr_data_minimization(self, session_id: str) -> ComplianceCheck:
"""GDPR Art. 5(1)(c) - Confirm no unnecessary personal data is processed."""
sd = self._get_session_data(session_id)
if sd["personal_data_accessed"]:
return self._mk_result(
"GDPR-002",
ComplianceStatus.WARNING,
f"Personal data accessed ({sd['personal_data_records']} records). "
f"Verify necessity or switch to synthetic test data.",
)
return self._mk_result("GDPR-002", ComplianceStatus.COMPLIANT, "No personal data accessed during session.")
def check_gdpr_storage_limitation(self, session_id: str) -> ComplianceCheck:
"""GDPR Art. 5(1)(e) - Ensure data retention policies are enforced."""
sd = self._get_session_data(session_id)
retention_days = self.config.get("data_retention_days", 90)
if sd.get("data_retention_policy_set"):
return self._mk_result("GDPR-003", ComplianceStatus.COMPLIANT, f"Retention policy active: {retention_days} days.")
return self._mk_result(
"GDPR-003",
ComplianceStatus.WARNING,
f"No explicit retention policy configured (default {retention_days} days). Set data_retention_days in config.",
)
def check_gdpr_security(self, session_id: str) -> ComplianceCheck:
"""GDPR Art. 32 - Verify encryption and access controls."""
sd = self._get_session_data(session_id)
issues: List[str] = []
if not sd.get("logs_encrypted", False):
issues.append("Evidence logs are not encrypted at rest.")
if not self.config.get("use_tls", True):
issues.append("TLS disabled for data transmission.")
if issues:
return self._mk_result("GDPR-004", ComplianceStatus.VIOLATION, " ".join(issues))
return self._mk_result("GDPR-004", ComplianceStatus.COMPLIANT, "Evidence encrypted at rest; TLS enforced in transit.")
def check_gdpr_breach_notification(self, session_id: str) -> ComplianceCheck:
"""GDPR Art. 33 - Ensure a 72h breach-notification channel exists."""
sd = self._get_session_data(session_id)
dpo = self.config.get("dpo_contact", sd.get("dpo_contact", ""))
if dpo:
return self._mk_result("GDPR-005", ComplianceStatus.COMPLIANT, f"DPO / breach contact configured: {dpo}.")
return self._mk_result(
"GDPR-005", ComplianceStatus.WARNING, "No DPO contact configured; breach notification may be delayed."
)
# ------------------------------------------------------------------
# BSI Grundschutz Checks
# ------------------------------------------------------------------
def check_bsi_authorization(self, session_id: str) -> ComplianceCheck:
"""BSI - Written authorization (Testing Mandate) must be present."""
if self.authorization and self.authorization.verify_integrity():
return self._mk_result(
"BSI-001",
ComplianceStatus.COMPLIANT,
f"Signed ROE present; hash {self.authorization.document_hash[:16]}... valid.",
)
return self._mk_result("BSI-001", ComplianceStatus.VIOLATION, "Missing or tampered Rules of Engagement document.")
def check_bsi_scope_definition(self, session_id: str) -> ComplianceCheck:
"""BSI - Scope must contain explicit IP ranges and system lists."""
sd = self._get_session_data(session_id)
if self.authorization and self.authorization.target_scope:
scope_count = len(self.authorization.target_scope)
return self._mk_result("BSI-002", ComplianceStatus.COMPLIANT, f"Scope defined with {scope_count} target entries.")
return self._mk_result("BSI-002", ComplianceStatus.VIOLATION, "No target scope defined in authorization document.")
def check_bsi_emergency_procedure(self, session_id: str) -> ComplianceCheck:
"""BSI - Emergency contact and abort procedures must be documented."""
sd = self._get_session_data(session_id)
contact = self.config.get("emergency_contact", "")
if self.authorization and self.authorization.emergency_contact:
contact = self.authorization.emergency_contact
if contact:
return self._mk_result("BSI-003", ComplianceStatus.COMPLIANT, f"Emergency contact available: {contact}.")
return self._mk_result("BSI-003", ComplianceStatus.WARNING, "No emergency contact configured.")
# ------------------------------------------------------------------
# NIST CSF Checks
# ------------------------------------------------------------------
def check_nist_identify(self, session_id: str) -> ComplianceCheck:
"""NIST CSF ID - Asset inventory and risk assessment."""
sd = self._get_session_data(session_id)
assets = sd.get("target_assets", [])
if assets:
return self._mk_result("NIST-001", ComplianceStatus.COMPLIANT, f"{len(assets)} assets documented in inventory.")
return self._mk_result(
"NIST-001", ComplianceStatus.WARNING, "Asset inventory empty; add target assets before testing."
)
def check_nist_protect(self, session_id: str) -> ComplianceCheck:
"""NIST CSF PR - Access controls and data-security safeguards."""
sd = self._get_session_data(session_id)
mfa = self.config.get("require_mfa", True)
if mfa:
return self._mk_result(
"NIST-002", ComplianceStatus.COMPLIANT, "MFA requirement enabled for test-operator accounts."
)
return self._mk_result("NIST-002", ComplianceStatus.WARNING, "MFA not enforced for test-operator accounts.")
def check_nist_detect(self, session_id: str) -> ComplianceCheck:
"""NIST CSF DE - Notify client SOC to avoid friendly-fire incidents."""
sd = self._get_session_data(session_id)
soc = self.config.get("soc_notified", False)
if soc:
return self._mk_result(
"NIST-003", ComplianceStatus.COMPLIANT, "Client SOC notified of testing window and source IPs."
)
return self._mk_result(
"NIST-003", ComplianceStatus.WARNING, "Client SOC has not been notified; tests may trigger incident response."
)
def check_nist_respond(self, session_id: str) -> ComplianceCheck:
"""NIST CSF RS - Incident-response playbook agreement."""
sd = self._get_session_data(session_id)
playbook = self.config.get("incident_playbook_agreed", False)
if playbook:
return self._mk_result("NIST-004", ComplianceStatus.COMPLIANT, "Incident-response playbook agreed with client.")
return self._mk_result(
"NIST-004", ComplianceStatus.VIOLATION, "No incident-response playbook agreed before exploitation."
)
def check_nist_recover(self, session_id: str) -> ComplianceCheck:
"""NIST CSF RC - Recovery / rollback plans."""
sd = self._get_session_data(session_id)
recovery = self.config.get("recovery_plan_documented", False)
if recovery:
return self._mk_result("NIST-005", ComplianceStatus.COMPLIANT, "Recovery plan documented for post-test rollback.")
return self._mk_result("NIST-005", ComplianceStatus.WARNING, "No recovery plan documented.")
# ------------------------------------------------------------------
# PTES Checks
# ------------------------------------------------------------------
def check_ptes_pre_engagement(self, session_id: str) -> ComplianceCheck:
"""PTES Phase 1 - ROE, kick-off, secure report-delivery channel."""
if self.authorization and self.authorization.verify_integrity():
return self._mk_result(
"PTES-001", ComplianceStatus.COMPLIANT, "Pre-engagement complete: ROE signed, kick-off documented."
)
return self._mk_result("PTES-001", ComplianceStatus.VIOLATION, "Pre-engagement incomplete: missing signed ROE.")
def check_ptes_intelligence(self, session_id: str) -> ComplianceCheck:
"""PTES Phase 2 - Reconnaissance limits (rate limits, robots.txt)."""
sd = self._get_session_data(session_id)
rate_limit = self.config.get("rate_limit_requests_per_sec", 10)
return self._mk_result(
"PTES-002", ComplianceStatus.COMPLIANT, f"Intelligence gathering configured with {rate_limit} req/s rate limit."
)
def check_ptes_threat_modeling(self, session_id: str) -> ComplianceCheck:
"""PTES Phase 3 - Threat model must be documented."""
sd = self._get_session_data(session_id)
if sd.get("threat_model_documented"):
return self._mk_result("PTES-003", ComplianceStatus.COMPLIANT, "Threat model documented and shared with client.")
return self._mk_result("PTES-003", ComplianceStatus.WARNING, "Threat model not yet documented.")
def check_ptes_vuln_analysis(self, session_id: str) -> ComplianceCheck:
"""PTES Phase 4 - Explicit go-ahead before production exploits."""
sd = self._get_session_data(session_id)
vulns = sd.get("vulnerabilities_found", [])
return self._mk_result(
"PTES-004", ComplianceStatus.COMPLIANT, f"Vulnerability analysis tracked; {len(vulns)} findings queued for review."
)
def check_ptes_exploitation(self, session_id: str) -> ComplianceCheck:
"""PTES Phase 5 - Exploitation only with per-exploit approval."""
sd = self._get_session_data(session_id)
if sd.get("exploitation_performed", False):
if sd.get("exploits_approved", False):
return self._mk_result(
"PTES-005", ComplianceStatus.COMPLIANT, "Exploitation performed with documented approvals."
)
return self._mk_result(
"PTES-005", ComplianceStatus.VIOLATION, "Exploitation performed WITHOUT explicit per-exploit approval."
)
return self._mk_result("PTES-005", ComplianceStatus.COMPLIANT, "No exploitation activity recorded in session.")
def check_ptes_post_exploitation(self, session_id: str) -> ComplianceCheck:
"""PTES Phase 6 - No PII access; stop at scope boundary."""
sd = self._get_session_data(session_id)
issues: List[str] = []
if sd.get("personal_data_accessed"):
issues.append("Personal data accessed during post-exploitation.")
if sd.get("scope_exceeded"):
issues.append("Authorized scope was exceeded.")
if issues:
return self._mk_result("PTES-006", ComplianceStatus.VIOLATION, " ".join(issues))
return self._mk_result(
"PTES-006", ComplianceStatus.COMPLIANT, "Post-exploitation clean: no PII accessed, scope respected."
)
def check_ptes_reporting(self, session_id: str) -> ComplianceCheck:
"""PTES Phase 7 - Secure report delivery and draft destruction."""
sd = self._get_session_data(session_id)
secure_delivery = self.config.get("secure_report_delivery", True)
if secure_delivery:
return self._mk_result(
"PTES-007", ComplianceStatus.COMPLIANT, "Secure report delivery channel configured; drafts will be destroyed."
)
return self._mk_result("PTES-007", ComplianceStatus.WARNING, "Secure report delivery not configured.")
# ------------------------------------------------------------------
# OWASP Checks
# ------------------------------------------------------------------
def check_owasp_methodology(self, session_id: str) -> ComplianceCheck:
"""OWASP WSTG - Traceability mapping to testing guide identifiers."""
sd = self._get_session_data(session_id)
mapped = sd.get("owasp_tests_mapped", [])
if len(mapped) >= 10:
return self._mk_result(
"OWASP-001", ComplianceStatus.COMPLIANT, f"{len(mapped)} test cases mapped to WSTG identifiers."
)
return self._mk_result(
"OWASP-001", ComplianceStatus.WARNING, f"Only {len(mapped)} WSTG mappings documented (recommended >= 10)."
)
def check_owasp_top10_coverage(self, session_id: str) -> ComplianceCheck:
"""OWASP Top 10 2021 - Coverage verification for all categories."""
sd = self._get_session_data(session_id)
owasp_top10: List[str] = [
"A01:2021-Broken Access Control",
"A02:2021-Cryptographic Failures",
"A03:2021-Injection",
"A04:2021-Insecure Design",
"A05:2021-Security Misconfiguration",
"A06:2021-Vulnerable and Outdated Components",
"A07:2021-Identification and Authentication Failures",
"A08:2021-Software and Data Integrity Failures",
"A09:2021-Security Logging and Monitoring Failures",
"A10:2021-Server-Side Request Forgery",
]
covered = set(sd.get("owasp_tests_mapped", []))
missing = [cat for cat in owasp_top10 if cat not in covered]
if not missing:
return self._mk_result("OWASP-002", ComplianceStatus.COMPLIANT, "All OWASP Top 10 2021 categories covered.")
return self._mk_result(
"OWASP-002", ComplianceStatus.WARNING, f"Missing OWASP Top 10 categories: {', '.join(missing)}."
)
# ------------------------------------------------------------------
# Authorization management
# ------------------------------------------------------------------
def load_authorization(self, document: AuthorizationDocument) -> None:
"""Load and validate an ROE authorization document."""
if not document.verify_integrity() and document.document_hash:
raise ValueError("Authorization document hash verification failed.")
self.authorization = document
self.logger.info("Authorization loaded for client: %s", document.client_name)
def verify_authorization(self, target: str) -> Tuple[bool, str]:
"""
Verify that *target* falls within the authorized scope.
Supports:
- Exact IP or hostname match
- CIDR range membership (e.g. 192.168.1.0/24)
- Wildcard domain patterns (e.g. *.example.com)
Returns (authorized: bool, reason: str).
"""
if not self.authorization:
return False, "No authorization document loaded."
# Date validity
now = datetime.now()
try:
start = datetime.fromisoformat(self.authorization.start_date)
end = datetime.fromisoformat(self.authorization.end_date)
except (ValueError, TypeError):
return False, "Invalid start/end date in authorization document."
if now < start:
return False, f"Test window starts at {start.isoformat()}."
if now > end:
return False, f"Test window ended at {end.isoformat()}."
# Scope match
for scope_entry in self.authorization.target_scope:
if self._target_matches_scope(target, scope_entry):
return True, f"Target {target} matches scope entry {scope_entry}."
return False, f"Target {target} not in authorized scope."
@staticmethod
def _target_matches_scope(target: str, scope: str) -> bool:
"""Check whether *target* matches a single scope entry."""
# CIDR match
if "/" in scope:
try:
import ipaddress
network = ipaddress.ip_network(scope, strict=False)
addr = ipaddress.ip_address(target)
return addr in network
except (ValueError, ImportError):
pass
# Wildcard domain
if scope.startswith("*."):
domain_suffix = scope[2:]
return target.endswith(domain_suffix) or target == domain_suffix
# Exact match
return target == scope
def generate_authorization_template(self, client_name: str, scope: List[str]) -> str:
"""
Generate a Markdown ROE authorization template ready for signing.
Parameters
----------
client_name: Legal entity requesting the pentest.
scope: List of IPs, CIDR blocks or domains to be tested.
Returns
-------
Markdown-formatted ROE template as string.
"""
today = datetime.now().strftime("%Y-%m-%d")
default_end = (datetime.now() + timedelta(days=30)).strftime("%Y-%m-%d")
scope_lines = "\n".join(f" - {s}" for s in scope)
template = f"""# Rules of Engagement (ROE)
| Field | Value |
|---------------------|--------------------------------|
| **Client** | {client_name} |
| **Created** | {today} |
| **Valid From** | {today} |
| **Valid Until** | {default_end} |
| **Test Types** | blackbox, greybox, whitebox |
| **Emergency Contact**| _____________________________ |
## 1. Scope of Testing
The following systems are explicitly authorized for testing:
{scope_lines}
## 2. Approved Test Methods
- [ ] Vulnerability scanning (non-intrusive)
- [ ] Vulnerability scanning (intrusive)
- [ ] Manual penetration testing
- [ ] Social engineering (with separate approval)
- [ ] Physical security assessment
- [ ] Wireless network testing
## 3. Constraints
- **Out-of-hours testing only**: ___ Yes / ___ No
- **Exclude production data**: ___ Yes / ___ No
- **No denial-of-service tests**: ___ Yes / ___ No
- **Change notification required**: ___ Yes / ___ No
## 4. Data Protection
All data collected during testing will be:
- Encrypted at rest using AES-256
- Transferred only via TLS 1.3
- Retained for a maximum of 90 days after report delivery
- Destroyed securely (cryptographic erasure) after retention period
## 5. Incident Response
- Emergency abort procedure: immediate stop on client request
- Breach notification: within 24h to client DPO
- 72h regulatory notification: GDPR Art. 33 if applicable
## 6. Signatures
| Role | Name | Signature | Date |
|---------------|------|-----------|------|
| Client | | | |
| Lead Tester | | | |
---
*This document was generated by Zen-AI-Pentest Compliance Module.*
"""
return template
# ------------------------------------------------------------------
# Full compliance run
# ------------------------------------------------------------------
def run_full_compliance_check(
self,
session_id: str,
target: str = "unknown",
regulations: Optional[List[Regulation]] = None,
) -> ComplianceReport:
"""
Execute all compliance checks and produce a consolidated report.
Parameters
----------
session_id: Unique identifier for the pentest session.
target: Target system/scope string.
regulations: Subset of frameworks to evaluate. Defaults to all.
Returns
-------
ComplianceReport containing every check result.
"""
if regulations is None:
regulations = list(Regulation)
self.logger.info("Starting full compliance check for session %s", session_id)
checks: List[ComplianceCheck] = []
violations: List[ComplianceCheck] = []
warnings: List[ComplianceCheck] = []
compliant_items: List[ComplianceCheck] = []
# Map regulation -> method names
regulation_methods: Dict[Regulation, List[str]] = {
Regulation.GDPR: [
"check_gdpr_authorization",
"check_gdpr_data_minimization",
"check_gdpr_storage_limitation",
"check_gdpr_security",
"check_gdpr_breach_notification",
],
Regulation.BSI: [
"check_bsi_authorization",
"check_bsi_scope_definition",
"check_bsi_emergency_procedure",
],
Regulation.NIST: [
"check_nist_identify",
"check_nist_protect",
"check_nist_detect",
"check_nist_respond",
"check_nist_recover",
],
Regulation.PTES: [
"check_ptes_pre_engagement",
"check_ptes_intelligence",
"check_ptes_threat_modeling",
"check_ptes_vuln_analysis",
"check_ptes_exploitation",
"check_ptes_post_exploitation",
"check_ptes_reporting",
],
Regulation.OWASP: [
"check_owasp_methodology",
"check_owasp_top10_coverage",
],
Regulation.ISO27001: [], # Reserved for future expansion
Regulation.SOX: [], # Reserved for future expansion
Regulation.HIPAA: [], # Reserved for future expansion
}
for reg in regulations:
for method_name in regulation_methods.get(reg, []):
method = getattr(self, method_name, None)
if method is None:
self.logger.warning("Compliance method %s not implemented", method_name)
continue
try:
result: ComplianceCheck = method(session_id)
checks.append(result)
if result.status == ComplianceStatus.VIOLATION:
violations.append(result)
elif result.status == ComplianceStatus.WARNING:
warnings.append(result)
elif result.status == ComplianceStatus.COMPLIANT:
compliant_items.append(result)
except Exception as exc:
self.logger.error("Check %s raised %s", method_name, exc)
error_check = self._mk_result(
method_name.upper().replace("CHECK_", "").replace("_", "-"),
ComplianceStatus.NOT_APPLICABLE,
f"Check execution failed: {exc}",
)
checks.append(error_check)
overall = ComplianceStatus.COMPLIANT
if violations:
overall = ComplianceStatus.VIOLATION
elif warnings:
overall = ComplianceStatus.WARNING
report = ComplianceReport(
session_id=session_id,
target=target,
overall_status=overall,
checks=checks,
violations=violations,
warnings=warnings,
compliant_items=compliant_items,
regulations_checked=regulations,
)
self.logger.info(
"Compliance check complete: %d total, %d violations, %d warnings, %d compliant",
len(checks),
len(violations),
len(warnings),
len(compliant_items),
)
return report
def generate_compliance_report(
self, session_id: str, target: str = "unknown", regulations: Optional[List[Regulation]] = None
) -> str:
"""
Generate a human-readable Markdown compliance report.
Parameters
----------
session_id: Pentest session identifier.
target: Target string for report header.
regulations: Optional subset of regulations.
Returns
-------
Markdown string.
"""
report = self.run_full_compliance_check(session_id, target, regulations)
lines: List[str] = [
"# Compliance Report",
"",
f"**Session ID**: `{report.session_id}` ",
f"**Target**: {report.target} ",
f"**Generated**: {report.generated_at} ",
f"**Overall Status**: {report.overall_status.value.upper()} ",
"",
"---",
"",
"## Summary",
"",
f"- Total checks: {len(report.checks)}",
f"- Compliant: {len(report.compliant_items)}",
f"- Warnings: {len(report.warnings)}",
f"- Violations: {len(report.violations)}",
"",
]
if report.violations:
lines.extend(
[
"## Violations",
"",
]
)
for v in report.violations:
lines.extend(
[
f"### {v.rule_id} - {v.name} ({v.severity.upper()})",
"",
f"**Regulation**: {v.regulation.value.upper()} ",
f"**Description**: {v.description} ",
f"**Details**: {v.details} ",
f"**Remediation**: {v.remediation} ",
"",
]
)
if report.warnings:
lines.extend(
[
"## Warnings",
"",
]
)
for w in report.warnings:
lines.extend(
[
f"### {w.rule_id} - {w.name} ({w.severity.upper()})",
"",
f"**Regulation**: {w.regulation.value.upper()} ",
f"**Details**: {w.details} ",
f"**Remediation**: {w.remediation} ",
"",
]
)
if report.compliant_items:
lines.extend(
[
"## Compliant Items",
"",
]
)
for c in report.compliant_items:
lines.append(f"- **{c.rule_id}** - {c.name}: {c.details}")
lines.append("")
lines.extend(
[
"---",
"",
"*Report generated by Zen-AI-Pentest Compliance Module*",
]
)
return "\n".join(lines)
def export_compliance_evidence(self, session_id: str, output_dir: str) -> Path:
"""
Export all compliance evidence for external auditors.
Produces:
- compliance_report.json (machine-readable full report)
- compliance_report.md (human-readable report)
- authorization.json (ROE document if loaded)
- session_audit.log (check execution timestamps)
Parameters
----------
session_id: Session to export.
output_dir: Directory path for exported files.
Returns
-------
Path to the output directory.
"""
out = Path(output_dir)
out.mkdir(parents=True, exist_ok=True)
report = self.run_full_compliance_check(session_id)
# JSON report
json_path = out / "compliance_report.json"
with open(json_path, "w", encoding="utf-8") as fh:
json.dump(report.to_dict(), fh, indent=2, ensure_ascii=False)
# Markdown report
md_path = out / "compliance_report.md"
with open(md_path, "w", encoding="utf-8") as fh:
fh.write(self.generate_compliance_report(session_id))
# Authorization document
if self.authorization:
auth_path = out / "authorization.json"
with open(auth_path, "w", encoding="utf-8") as fh:
json.dump(self.authorization.to_dict(), fh, indent=2, ensure_ascii=False)
# Audit log
log_path = out / "session_audit.log"
with open(log_path, "w", encoding="utf-8") as fh:
for check in report.checks:
fh.write(
f"{check.timestamp} | {check.rule_id} | {check.regulation.value} | {check.status.value} | {check.name}\n"
)
self.logger.info("Compliance evidence exported to %s", out.resolve())
return out.resolve()
# ------------------------------------------------------------------
# Session-state helpers (called by scanners / agents)
# ------------------------------------------------------------------
def record_personal_data_access(self, session_id: str, count: int = 1) -> None:
"""Flag that personal data was accessed (triggered by scanners)."""
sd = self._get_session_data(session_id)
sd["personal_data_accessed"] = True
sd["personal_data_records"] += count
self.logger.warning("Session %s accessed %d personal data records", session_id, count)
def record_exploitation(self, session_id: str, approved: bool) -> None:
"""Record exploitation activity and whether it was pre-approved."""
sd = self._get_session_data(session_id)
sd["exploitation_performed"] = True
sd["exploits_approved"] = approved
def record_scope_exceeded(self, session_id: str) -> None:
"""Flag that the scan exceeded authorized scope."""
sd = self._get_session_data(session_id)
sd["scope_exceeded"] = True
self.logger.critical("Session %s exceeded authorized scope!", session_id)
def record_asset(self, session_id: str, asset: str) -> None:
"""Add a target asset to the session inventory."""
sd = self._get_session_data(session_id)
if asset not in sd["target_assets"]:
sd["target_assets"].append(asset)
def record_vulnerability(self, session_id: str, vuln_id: str) -> None:
"""Record a discovered vulnerability."""
sd = self._get_session_data(session_id)
if vuln_id not in sd["vulnerabilities_found"]:
sd["vulnerabilities_found"].append(vuln_id)
def record_threat_model(self, session_id: str) -> None:
"""Mark threat model as documented."""
sd = self._get_session_data(session_id)
sd["threat_model_documented"] = True
def map_owasp_test(self, session_id: str, wstg_id: str) -> None:
"""Map a test case to an OWASP WSTG identifier."""
sd = self._get_session_data(session_id)
if wstg_id not in sd["owasp_tests_mapped"]:
sd["owasp_tests_mapped"].append(wstg_id)
# ---------------------------------------------------------------------------
# Stand-alone helpers
# ---------------------------------------------------------------------------
def create_compliance_manager(config: Optional[Dict[str, Any]] = None) -> ComplianceManager:
"""Factory function to create a configured ComplianceManager."""
return ComplianceManager(config)
def quick_compliance_check(
session_id: str,
target: str = "unknown",
regulations: Optional[List[Regulation]] = None,
config: Optional[Dict[str, Any]] = None,
) -> ComplianceReport:
"""
One-shot compliance check without explicit manager lifecycle.
Parameters
----------
session_id: Session identifier.
target: Target scope string.
regulations: Subset of regulations or None for all.
config: Optional configuration dictionary.
Returns
-------
ComplianceReport with all results.
"""
mgr = ComplianceManager(config)
return mgr.run_full_compliance_check(session_id, target, regulations)
# ---------------------------------------------------------------------------
# Module-level execution guard
# ---------------------------------------------------------------------------
if __name__ == "__main__":
# Simple self-test when executed directly
logging.basicConfig(level=logging.INFO)
mgr = ComplianceManager(
config={
"data_retention_days": 90,
"dpo_contact": "dpo@example.com",
"emergency_contact": "+49-800-123456",
"rate_limit_requests_per_sec": 5,
"use_tls": True,
"require_mfa": True,
"soc_notified": True,
"incident_playbook_agreed": True,
"recovery_plan_documented": True,
"secure_report_delivery": True,
}
)
# Load mock authorization
auth = AuthorizationDocument(
client_name="Example Corp",
target_scope=["192.168.1.0/24", "10.0.0.1", "*.example.com"],
start_date=(datetime.now() - timedelta(days=1)).isoformat(),
end_date=(datetime.now() + timedelta(days=7)).isoformat(),
test_types=["greybox", "whitebox"],
approved_methods=["vuln_scan", "web_pentest"],
emergency_contact="+49-800-123456",
)
auth.sign("John Doe", "AUTH-TOKEN-12345")
mgr.load_authorization(auth)
# Simulate session activity
mgr.record_asset("demo-session", "192.168.1.10")
mgr.record_asset("demo-session", "192.168.1.11")
mgr.record_vulnerability("demo-session", "CVE-2023-1234")
mgr.map_owasp_test("demo-session", "A01:2021-Broken Access Control")
mgr.record_threat_model("demo-session")
report = mgr.run_full_compliance_check("demo-session", target="192.168.1.0/24")
print(json.dumps(report.to_dict(), indent=2))
"""
Compliance Module - Legal and regulatory framework enforcement.
Ensures all pentest activities comply with:
- GDPR (EU General Data Protection Regulation)
- BSI Grundschutz (German Federal Office for Information Security)
- NIST Cybersecurity Framework
- OWASP Testing Guide
- PTES (Penetration Testing Execution Standard)
- ISO 27001
Provides: Compliance checks, Legal document generation,
Scope validation, Data protection enforcement.
Author: Cybersecurity AI Architect
"""
import hashlib
import json
import logging
import os
import re
from dataclasses import asdict, dataclass, field
from datetime import datetime, timedelta
from enum import Enum
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
# ---------------------------------------------------------------------------
# Enums
# ---------------------------------------------------------------------------
class Regulation(Enum):
"""Supported regulatory frameworks."""
GDPR = "gdpr" # EU General Data Protection Regulation
BSI = "bsi" # Germany Federal Office for Information Security
NIST = "nist" # US NIST Cybersecurity Framework
ISO27001 = "iso27001" # International ISO 27001
PTES = "ptes" # Penetration Testing Execution Standard
OWASP = "owasp" # OWASP Testing Guide
SOX = "sox" # US Sarbanes-Oxley Act
HIPAA = "hipaa" # US Health Insurance Portability and Accountability Act
class ComplianceStatus(Enum):
"""Result of a single compliance check."""
COMPLIANT = "compliant"
VIOLATION = "violation"
WARNING = "warning"
NOT_APPLICABLE = "not_applicable"
# ---------------------------------------------------------------------------
# Data classes
# ---------------------------------------------------------------------------
class ComplianceCheck:
"""Single compliance rule with its result."""
rule_id: str
regulation: Regulation
name: str
description: str
check_function: str
severity: str # critical | high | medium | low
remediation: str
status: ComplianceStatus = ComplianceStatus.NOT_APPLICABLE
details: str = ""
timestamp: str = field(default_factory=lambda: datetime.now().isoformat())
def to_dict(self) -> Dict[str, Any]:
"""Serialize to dictionary."""
d = asdict(self)
d["regulation"] = self.regulation.value
d["status"] = self.status.value
return d
class ComplianceReport:
"""Aggregated compliance report for a pentest session."""
session_id: str
target: str
overall_status: ComplianceStatus
checks: List[ComplianceCheck]
violations: List[ComplianceCheck]
warnings: List[ComplianceCheck]
compliant_items: List[ComplianceCheck]
generated_at: str = field(default_factory=lambda: datetime.now().isoformat())
regulations_checked: List[Regulation] = field(default_factory=list)
def to_dict(self) -> Dict[str, Any]:
"""Serialize to dictionary."""
return {
Xet Storage Details
- Size:
- 51 kB
- Xet hash:
- 2875ec78b025450d822435fe77033e9e368fef58bdb1b73404b73877513966d9
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.