Buckets:

download
raw
68.1 kB
""" Guardrails - Safety layer for the MCP Pentest Suite. Prevents unauthorized access, out-of-scope testing, and ensures all activities are logged and approved. Implements: Scope validation, Authorization checks, Rate limiting, Sandbox isolation, Human approval gates, Audit logging. Author: Senior Cybersecurity AI Architect """ import hashlib import ipaddress import json import logging import os import re import subprocess import time import uuid from dataclasses import asdict, dataclass, field from datetime import datetime, timedelta from enum import Enum from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union logger = logging.getLogger("guardrails") # ============================================================================ # ENUMS # ============================================================================ class RiskLevel(Enum): """Risk classification for pentest operations.""" SAFE = "safe" # No risk (e.g., reconnaissance) LOW = "low" # Minimal risk (e.g., passive scanning) MEDIUM = "medium" # Moderate risk (e.g., active scanning) HIGH = "high" # Significant risk (e.g., exploitation) CRITICAL = "critical" # Severe risk (e.g., post-exploitation) def __lt__(self, other: "RiskLevel") -> bool: order = [RiskLevel.SAFE, RiskLevel.LOW, RiskLevel.MEDIUM, RiskLevel.HIGH, RiskLevel.CRITICAL] return order.index(self) < order.index(other) def __le__(self, other: "RiskLevel") -> bool: return self == other or self < other def __gt__(self, other: "RiskLevel") -> bool: return not self <= other def __ge__(self, other: "RiskLevel") -> bool: return not self < other class ApprovalStatus(Enum): """Approval status for critical operations.""" AUTO_APPROVED = "auto_approved" APPROVED = "approved" PENDING = "pending" DENIED = "denied" EXPIRED = "expired" # ============================================================================ # DATA CLASSES # ============================================================================ @dataclass class GuardrailDecision: """Decision returned by the guardrails system.""" allowed: bool risk_level: RiskLevel approval_required: bool approval_status: ApprovalStatus reason: str rule_triggered: Optional[str] = None timestamp: str = field(default_factory=lambda: datetime.now().isoformat()) action_id: str = "" def to_dict(self) -> Dict[str, Any]: return { "allowed": self.allowed, "risk_level": self.risk_level.value, "approval_required": self.approval_required, "approval_status": self.approval_status.value, "reason": self.reason, "rule_triggered": self.rule_triggered, "timestamp": self.timestamp, "action_id": self.action_id, } @dataclass class AuditLogEntry: """Immutable audit log entry with tamper-evident hashing.""" timestamp: str action: str tool: str target: str user: str parameters: Dict[str, Any] result: str decision: GuardrailDecision session_id: str hash: str = "" previous_hash: str = "0" * 16 # Hash chain for integrity def __post_init__(self): if not self.hash: data = f"{self.timestamp}{self.action}{self.target}{self.user}{self.previous_hash}" self.hash = hashlib.sha256(data.encode()).hexdigest()[:16] def to_dict(self) -> Dict[str, Any]: return { "timestamp": self.timestamp, "action": self.action, "tool": self.tool, "target": self.target, "user": self.user, "parameters": self.parameters, "result": self.result, "decision": self.decision.to_dict(), "session_id": self.session_id, "hash": self.hash, "previous_hash": self.previous_hash, } # ============================================================================ # SCOPE VALIDATOR # ============================================================================ class ScopeValidator: """ Validates that targets are within authorized scope. Supports: - Domain validation (exact match and wildcard) - IP range validation (CIDR notation) - Port filtering (allowed/blocked ports) - URL validation """ def __init__(self, config: Optional[Dict[str, Any]] = None): self.config = config or {} self.allowed_hosts: Set[str] = set() self.allowed_ips: Set[ipaddress.ip_network] = set() self.allowed_ports: Set[int] = set() self.blocked_hosts: Set[str] = {"localhost", "127.0.0.1", "::1"} self.blocked_ips: Set[ipaddress.ip_network] = { ipaddress.ip_network("127.0.0.0/8"), ipaddress.ip_network("::1/128"), ipaddress.ip_network("10.0.0.0/8"), ipaddress.ip_network("172.16.0.0/12"), ipaddress.ip_network("192.168.0.0/16"), ipaddress.ip_network("fc00::/7"), ipaddress.ip_network("169.254.0.0/16"), # Link-local } self.blocked_ports: Set[int] = {22, 25, 53, 110, 143, 161, 162} self.wildcard_hosts: List[str] = [] # Load from config self._load_config() def _load_config(self) -> None: """Load scope configuration from config dict.""" scope_config = self.config.get("scope", {}) for host in scope_config.get("allowed_hosts", []): self.add_scope(host) for ip_range in scope_config.get("allowed_ips", []): try: self.allowed_ips.add(ipaddress.ip_network(ip_range, strict=False)) except ValueError: logger.warning(f"Invalid IP range in config: {ip_range}") for port in scope_config.get("allowed_ports", []): self.allowed_ports.add(int(port)) for port in scope_config.get("blocked_ports", []): self.blocked_ports.add(int(port)) def validate_target(self, target: str) -> Tuple[bool, str]: """ Check if target is within scope. Args: target: Target string (IP, domain, or URL) Returns: Tuple of (is_valid, reason) """ if not target or not target.strip(): return False, "Empty target not allowed" target = target.strip().lower() # Check blocked hosts (exact match) if target in self.blocked_hosts: return False, f"Target '{target}' is in blocked hosts list" # Extract hostname/IP from URL hostname = self._extract_hostname(target) if not hostname: return False, f"Could not parse target: {target}" # Check blocked hosts again with extracted hostname if hostname in self.blocked_hosts: return False, f"Host '{hostname}' is in blocked hosts list" # Check if IP is_ip, ip_obj = self._parse_ip(hostname) if is_ip and ip_obj: return self._validate_ip(ip_obj) # Check domain return self._validate_domain(hostname) def _extract_hostname(self, target: str) -> str: """Extract hostname from URL or raw target string.""" # URL pattern url_pattern = re.compile(r"^(?:https?://)?(?:[^@/\n]+@)?([^:/\n?]+)(?::(\d+))?") match = url_pattern.match(target) if match: return match.group(1).lower() return target.lower() def _parse_ip(self, hostname: str) -> Tuple[bool, Optional[ipaddress.ip_address]]: """Try to parse hostname as IP address.""" try: return True, ipaddress.ip_address(hostname) except ValueError: return False, None def _validate_ip(self, ip_obj: ipaddress.ip_address) -> Tuple[bool, str]: """Validate an IP address against scope rules.""" # Check blocked IP ranges for blocked_net in self.blocked_ips: if ip_obj in blocked_net: return False, (f"IP {ip_obj} is in blocked range {blocked_net}") # Check allowed IP ranges if self.allowed_ips: for allowed_net in self.allowed_ips: if ip_obj in allowed_net: return True, f"IP {ip_obj} is within allowed range {allowed_net}" return False, f"IP {ip_obj} is not in any allowed range" # No explicit allowed ranges means all non-blocked are OK return True, f"IP {ip_obj} is not in any blocked range" def _validate_domain(self, hostname: str) -> Tuple[bool, str]: """Validate a domain against scope rules.""" # Check blocked hosts for blocked in self.blocked_hosts: if hostname == blocked or hostname.endswith(f".{blocked}"): return False, f"Domain '{hostname}' matches blocked pattern" # Check allowed hosts (exact match) if hostname in self.allowed_hosts: return True, f"Domain '{hostname}' is explicitly allowed" # Check wildcard patterns for pattern in self.wildcard_hosts: if self._matches_wildcard(hostname, pattern): return True, f"Domain '{hostname}' matches wildcard '{pattern}'" # If allowed_hosts is configured, reject anything not in scope if self.allowed_hosts or self.wildcard_hosts or self.allowed_ips: return False, ( f"Domain '{hostname}' is not in the allowed scope. Allowed: {self.allowed_hosts | set(self.wildcard_hosts)}" ) # No scope restriction configured return True, f"Domain '{hostname}' accepted (no scope restrictions)" def _matches_wildcard(self, hostname: str, pattern: str) -> bool: """Check if hostname matches a wildcard pattern.""" if pattern.startswith("*."): domain_suffix = pattern[2:] return hostname == domain_suffix or hostname.endswith(f".{domain_suffix}") return hostname == pattern def validate_port(self, port: int) -> Tuple[bool, str]: """Check if port is allowed.""" if not isinstance(port, int) or port < 1 or port > 65535: return False, f"Invalid port number: {port}" if port in self.blocked_ports: return False, f"Port {port} is blocked" if self.allowed_ports and port not in self.allowed_ports: return False, (f"Port {port} is not in allowed ports: {sorted(self.allowed_ports)}") return True, f"Port {port} is allowed" def validate_ip_range(self, ip_range: str) -> Tuple[bool, str]: """Check if an IP range does not overlap with blocked ranges.""" try: network = ipaddress.ip_network(ip_range, strict=False) except ValueError as e: return False, f"Invalid IP range '{ip_range}': {e}" for blocked_net in self.blocked_ips: if network.overlaps(blocked_net): return False, (f"Range {ip_range} overlaps with blocked range {blocked_net}") return True, f"Range {ip_range} is valid" def add_scope(self, host: str) -> None: """Add host to allowed scope. Supports wildcards.""" host = host.strip().lower() if host.startswith("*."): self.wildcard_hosts.append(host) else: self.allowed_hosts.add(host) logger.info(f"Added '{host}' to allowed scope") def remove_scope(self, host: str) -> None: """Remove host from allowed scope.""" host = host.strip().lower() self.allowed_hosts.discard(host) if host in self.wildcard_hosts: self.wildcard_hosts.remove(host) logger.info(f"Removed '{host}' from allowed scope") def is_in_scope(self, target: str) -> bool: """Quick check if target is in scope.""" valid, _ = self.validate_target(target) return valid # ============================================================================ # RATE LIMITER # ============================================================================ class RateLimiter: """ Sliding window rate limiter for pentest operations. Tracks requests per identifier (IP, user, session) and enforces configurable rate limits with automatic cleanup of expired entries. """ def __init__(self, max_requests_per_minute: int = 60): self.max_requests = max_requests_per_minute self.requests: Dict[str, List[float]] = {} self.blocked: Dict[str, float] = {} # Temporarily blocked identifiers self.block_duration: int = 300 # 5 minutes block self.logger = logging.getLogger("guardrails.rate_limiter") def check_rate_limit(self, identifier: str) -> Tuple[bool, int]: """ Check if request is within rate limit. Args: identifier: Unique identifier (user_id, session_id, IP) Returns: Tuple of (allowed, remaining_requests) """ now = time.time() # Check if identifier is temporarily blocked if identifier in self.blocked: unblock_time = self.blocked[identifier] if now < unblock_time: remaining = int(unblock_time - now) self.logger.warning(f"Rate limit exceeded for {identifier}. Blocked for {remaining}s more.") return False, 0 else: del self.blocked[identifier] # Clean old requests (sliding window) window_start = now - 60 # 1 minute window if identifier in self.requests: self.requests[identifier] = [ts for ts in self.requests[identifier] if ts > window_start] else: self.requests[identifier] = [] current_count = len(self.requests[identifier]) remaining = max(0, self.max_requests - current_count) if current_count >= self.max_requests: self.blocked[identifier] = now + self.block_duration self.logger.warning( f"Rate limit exceeded for {identifier}: {current_count}/{self.max_requests} requests in last 60s" ) return False, 0 return True, remaining def record_request(self, identifier: str) -> None: """Record a request timestamp.""" now = time.time() if identifier not in self.requests: self.requests[identifier] = [] self.requests[identifier].append(now) def get_request_count(self, identifier: str) -> int: """Get current request count for identifier in the window.""" window_start = time.time() - 60 if identifier not in self.requests: return 0 return len([ts for ts in self.requests[identifier] if ts > window_start]) def reset(self, identifier: str) -> None: """Reset rate limit for an identifier.""" self.requests.pop(identifier, None) self.blocked.pop(identifier, None) def set_max_requests(self, max_requests: int) -> None: """Update the maximum requests per minute.""" self.max_requests = max_requests # ============================================================================ # APPROVAL GATE # ============================================================================ class ApprovalGate: """ Human approval system for critical operations. Manages the approval workflow for high-risk actions, including: - Requesting approval with detailed context - Approving/denying actions - Automatic expiration of pending approvals - Persistence of approval decisions """ def __init__(self, config: Optional[Dict[str, Any]] = None): self.config = config or {} self.pending_approvals: Dict[str, Dict[str, Any]] = {} self.approved_actions: Set[str] = set() self.denied_actions: Set[str] = set() self.approval_timeout: int = self.config.get("approval_timeout", 600) self.persistence_file: Optional[Path] = None # Set up persistence if self.config.get("persistence_dir"): self.persistence_file = Path(self.config["persistence_dir"]) / "approvals.json" self._load_approvals() self.logger = logging.getLogger("guardrails.approval_gate") def request_approval( self, action_id: str, action: str, tool: str, target: str, parameters: Dict[str, Any], risk_level: RiskLevel = RiskLevel.HIGH, ) -> ApprovalStatus: """ Request human approval for a critical action. Args: action_id: Unique action identifier action: Description of the action tool: Tool being used target: Target of the action parameters: Tool parameters risk_level: Risk level of the action Returns: ApprovalStatus enum value """ # Check if already decided if action_id in self.approved_actions: return ApprovalStatus.APPROVED if action_id in self.denied_actions: return ApprovalStatus.DENIED # Check if already pending if action_id in self.pending_approvals: pending = self.pending_approvals[action_id] elapsed = time.time() - pending.get("requested_at", 0) if elapsed > self.approval_timeout: pending["status"] = ApprovalStatus.EXPIRED.value return ApprovalStatus.EXPIRED return ApprovalStatus.PENDING # Create approval request approval_request = { "action_id": action_id, "action": action, "tool": tool, "target": target, "parameters": parameters, "risk_level": risk_level.value, "status": ApprovalStatus.PENDING.value, "requested_at": time.time(), "requested_at_iso": datetime.now().isoformat(), "approved_at": None, "approved_by": None, "denied_at": None, "denied_reason": None, } self.pending_approvals[action_id] = approval_request self.logger.warning( f"Approval requested for {action} (tool={tool}, target={target}, risk={risk_level.value}) - Action ID: {action_id}" ) self._save_approvals() return ApprovalStatus.PENDING def approve(self, action_id: str, approved_by: str = "operator") -> bool: """ Approve a pending action. Args: action_id: The action ID to approve approved_by: Name/identifier of approver Returns: True if approved, False if not found """ if action_id not in self.pending_approvals: self.logger.warning(f"Approval request {action_id} not found") return False request = self.pending_approvals[action_id] request["status"] = ApprovalStatus.APPROVED.value request["approved_at"] = time.time() request["approved_by"] = approved_by self.approved_actions.add(action_id) self.pending_approvals.pop(action_id, None) self.logger.info(f"Action {action_id} approved by {approved_by}") self._save_approvals() return True def deny(self, action_id: str, reason: str = "") -> bool: """ Deny a pending action. Args: action_id: The action ID to deny reason: Reason for denial Returns: True if denied, False if not found """ if action_id not in self.pending_approvals: self.logger.warning(f"Approval request {action_id} not found") return False request = self.pending_approvals[action_id] request["status"] = ApprovalStatus.DENIED.value request["denied_at"] = time.time() request["denied_reason"] = reason self.denied_actions.add(action_id) self.pending_approvals.pop(action_id, None) self.logger.info(f"Action {action_id} denied. Reason: {reason}") self._save_approvals() return True def check_approval(self, action_id: str) -> ApprovalStatus: """ Check approval status of an action. Args: action_id: The action ID to check Returns: Current ApprovalStatus """ if action_id in self.approved_actions: return ApprovalStatus.APPROVED if action_id in self.denied_actions: return ApprovalStatus.DENIED if action_id in self.pending_approvals: request = self.pending_approvals[action_id] elapsed = time.time() - request.get("requested_at", 0) if elapsed > self.approval_timeout: return ApprovalStatus.EXPIRED return ApprovalStatus.PENDING return ApprovalStatus.DENIED def get_pending_approvals(self) -> List[Dict[str, Any]]: """Get all pending approvals.""" now = time.time() pending = [] expired_ids = [] for action_id, request in self.pending_approvals.items(): elapsed = now - request.get("requested_at", 0) if elapsed > self.approval_timeout: expired_ids.append(action_id) else: pending.append(request) # Clean expired for action_id in expired_ids: self.pending_approvals[action_id]["status"] = ApprovalStatus.EXPIRED.value return pending def _save_approvals(self) -> None: """Persist approvals to disk.""" if not self.persistence_file: return try: self.persistence_file.parent.mkdir(parents=True, exist_ok=True) data = { "pending": dict(self.pending_approvals), "approved": list(self.approved_actions), "denied": list(self.denied_actions), } with open(self.persistence_file, "w") as f: json.dump(data, f, indent=2, default=str) except Exception as e: self.logger.error(f"Failed to save approvals: {e}") def _load_approvals(self) -> None: """Load persisted approvals from disk.""" if not self.persistence_file or not self.persistence_file.exists(): return try: with open(self.persistence_file, "r") as f: data = json.load(f) self.pending_approvals = data.get("pending", {}) self.approved_actions = set(data.get("approved", [])) self.denied_actions = set(data.get("denied", [])) except Exception as e: self.logger.error(f"Failed to load approvals: {e}") # ============================================================================ # SANDBOX MANAGER # ============================================================================ class SandboxManager: """ Sandbox isolation for dangerous operations using Docker. Creates isolated container environments to execute potentially dangerous commands without affecting the host system. """ def __init__(self, config: Optional[Dict[str, Any]] = None): self.config = config or {} self.active_sandboxes: Dict[str, Dict[str, Any]] = {} self.docker_available = self._check_docker() self.image = self.config.get("sandbox_image", "alpine:latest") self.network_mode = self.config.get("sandbox_network", "none") self.max_runtime = self.config.get("sandbox_max_runtime", 300) self.logger = logging.getLogger("guardrails.sandbox") def _check_docker(self) -> bool: """Check if Docker is available.""" try: result = subprocess.run( ["docker", "info"], capture_output=True, timeout=5, ) available = result.returncode == 0 if available: self.logger.info("Docker is available for sandboxing") else: self.logger.warning("Docker not available - sandboxing disabled") return available except (subprocess.TimeoutExpired, FileNotFoundError): self.logger.warning("Docker command not found - sandboxing disabled") return False def create_sandbox(self, session_id: str) -> str: """ Create an isolated sandbox environment. Args: session_id: Session identifier Returns: Container ID or empty string if Docker unavailable """ if not self.docker_available: self.logger.info("Sandbox creation skipped - Docker not available") self.active_sandboxes[session_id] = { "container_id": None, "created_at": time.time(), "mode": "fallback", } return "" container_name = f"zenai-sandbox-{session_id[:8]}" try: result = subprocess.run( [ "docker", "run", "-d", "--name", container_name, "--network", self.network_mode, "--rm", "--memory", "256m", "--cpus", "0.5", "--pids-limit", "50", "--read-only", "--security-opt", "no-new-privileges:true", "--cap-drop", "ALL", self.image, "sleep", str(self.max_runtime + 60), ], capture_output=True, text=True, timeout=30, ) if result.returncode == 0: container_id = result.stdout.strip() self.active_sandboxes[session_id] = { "container_id": container_id, "container_name": container_name, "created_at": time.time(), "mode": "docker", } self.logger.info(f"Sandbox created: {container_name} ({container_id[:12]})") return container_id else: self.logger.error(f"Failed to create sandbox: {result.stderr}") return "" except subprocess.TimeoutExpired: self.logger.error("Sandbox creation timed out") return "" except Exception as e: self.logger.error(f"Sandbox creation error: {e}") return "" def execute_in_sandbox( self, command: List[str], session_id: str, timeout: Optional[int] = None, ) -> Dict[str, Any]: """ Execute a command inside the sandbox. Args: command: Command and arguments as list session_id: Session identifier timeout: Execution timeout in seconds Returns: Dict with stdout, stderr, returncode """ timeout = timeout or self.max_runtime # Fallback mode (no Docker) if session_id not in self.active_sandboxes or self.active_sandboxes[session_id].get("mode") == "fallback": self.logger.warning("Executing without sandbox isolation!") return self._execute_fallback(command, timeout) sandbox = self.active_sandboxes[session_id] container_id = sandbox.get("container_id") if not container_id: return { "stdout": "", "stderr": "Sandbox container not found", "returncode": -1, "sandboxed": False, } try: result = subprocess.run( ["docker", "exec", container_id] + command, capture_output=True, text=True, timeout=timeout, ) return { "stdout": result.stdout, "stderr": result.stderr, "returncode": result.returncode, "sandboxed": True, "container": container_id[:12], } except subprocess.TimeoutExpired: self.logger.error(f"Sandbox execution timed out after {timeout}s") return { "stdout": "", "stderr": f"Execution timed out after {timeout}s", "returncode": -1, "sandboxed": True, } except Exception as e: self.logger.error(f"Sandbox execution error: {e}") return { "stdout": "", "stderr": str(e), "returncode": -1, "sandboxed": True, } def _execute_fallback( self, command: List[str], timeout: int, ) -> Dict[str, Any]: """Execute command without sandbox (fallback).""" try: result = subprocess.run( command, capture_output=True, text=True, timeout=timeout, ) return { "stdout": result.stdout, "stderr": result.stderr, "returncode": result.returncode, "sandboxed": False, } except subprocess.TimeoutExpired: return { "stdout": "", "stderr": f"Execution timed out after {timeout}s", "returncode": -1, "sandboxed": False, } except Exception as e: return { "stdout": "", "stderr": str(e), "returncode": -1, "sandboxed": False, } def destroy_sandbox(self, session_id: str) -> bool: """ Destroy a sandbox environment. Args: session_id: Session identifier Returns: True if destroyed successfully """ if session_id not in self.active_sandboxes: return True sandbox = self.active_sandboxes[session_id] if sandbox.get("mode") == "fallback": self.active_sandboxes.pop(session_id, None) return True container_id = sandbox.get("container_id") if not container_id: self.active_sandboxes.pop(session_id, None) return True try: subprocess.run( ["docker", "kill", container_id], capture_output=True, timeout=10, ) subprocess.run( ["docker", "rm", "-f", container_id], capture_output=True, timeout=10, ) self.logger.info(f"Sandbox destroyed: {container_id[:12]}") except Exception as e: self.logger.error(f"Error destroying sandbox: {e}") finally: self.active_sandboxes.pop(session_id, None) return True def cleanup_all(self) -> None: """Destroy all active sandboxes.""" session_ids = list(self.active_sandboxes.keys()) for session_id in session_ids: self.destroy_sandbox(session_id) # ============================================================================ # AUDIT LOGGER # ============================================================================ class AuditLogger: """ Tamper-evident audit logging system. Maintains a chain of hashed log entries to detect tampering. Each entry includes a hash of the previous entry, creating a blockchain-style integrity chain. """ def __init__(self, log_file: str = "logs/audit.log"): self.log_file = Path(log_file) self.log_file.parent.mkdir(parents=True, exist_ok=True) self.entries: List[AuditLogEntry] = [] self._last_hash = "0" * 16 self._load_existing() self.logger = logging.getLogger("guardrails.audit") def _load_existing(self) -> None: """Load existing audit log entries.""" if not self.log_file.exists(): return try: with open(self.log_file, "r") as f: for line in f: line = line.strip() if not line: continue try: data = json.loads(line) entry = AuditLogEntry( timestamp=data["timestamp"], action=data["action"], tool=data["tool"], target=data["target"], user=data["user"], parameters=data.get("parameters", {}), result=data.get("result", ""), decision=GuardrailDecision( allowed=data["decision"]["allowed"], risk_level=RiskLevel(data["decision"]["risk_level"]), approval_required=data["decision"]["approval_required"], approval_status=ApprovalStatus(data["decision"]["approval_status"]), reason=data["decision"]["reason"], rule_triggered=data["decision"].get("rule_triggered"), timestamp=data["decision"]["timestamp"], action_id=data["decision"].get("action_id", ""), ), session_id=data["session_id"], hash=data["hash"], previous_hash=data.get("previous_hash", "0" * 16), ) self.entries.append(entry) self._last_hash = entry.hash except (json.JSONDecodeError, KeyError) as e: self.logger.warning(f"Skipping malformed audit log line: {e}") except Exception as e: self.logger.error(f"Error loading audit log: {e}") def log(self, entry: AuditLogEntry) -> None: """ Log an audit entry with hash chain integrity. Args: entry: AuditLogEntry to log """ # Link to previous entry entry.previous_hash = self._last_hash # Recompute hash with previous_hash included data = f"{entry.timestamp}{entry.action}{entry.target}{entry.user}{entry.previous_hash}" entry.hash = hashlib.sha256(data.encode()).hexdigest()[:16] self.entries.append(entry) self._last_hash = entry.hash # Append to file try: with open(self.log_file, "a") as f: f.write(json.dumps(entry.to_dict()) + "\n") self.logger.debug(f"Audit log: {entry.action} on {entry.target} by {entry.user}") except Exception as e: self.logger.error(f"Failed to write audit log: {e}") def get_logs( self, session_id: Optional[str] = None, start_time: Optional[str] = None, end_time: Optional[str] = None, tool: Optional[str] = None, user: Optional[str] = None, ) -> List[AuditLogEntry]: """ Get audit logs with filters. Args: session_id: Filter by session ID start_time: ISO format start time end_time: ISO format end time tool: Filter by tool name user: Filter by user Returns: Filtered list of audit log entries """ filtered = self.entries if session_id: filtered = [e for e in filtered if e.session_id == session_id] if tool: filtered = [e for e in filtered if e.tool == tool] if user: filtered = [e for e in filtered if e.user == user] if start_time: filtered = [e for e in filtered if e.timestamp >= start_time] if end_time: filtered = [e for e in filtered if e.timestamp <= end_time] return filtered def export_logs(self, output_path: str) -> str: """ Export logs to a JSON file. Args: output_path: Path for the export file Returns: Absolute path of exported file """ output = Path(output_path) output.parent.mkdir(parents=True, exist_ok=True) export_data = { "exported_at": datetime.now().isoformat(), "total_entries": len(self.entries), "integrity_verified": self.verify_integrity(), "entries": [e.to_dict() for e in self.entries], } with open(output, "w") as f: json.dump(export_data, f, indent=2) self.logger.info(f"Audit log exported to {output}") return str(output.absolute()) def verify_integrity(self) -> bool: """ Verify log integrity using hash chain. Each entry's previous_hash must match the previous entry's hash. Returns: True if integrity is verified """ if not self.entries: return True previous_hash = "0" * 16 for i, entry in enumerate(self.entries): if entry.previous_hash != previous_hash: self.logger.error(f"Hash chain broken at entry {i}: expected={previous_hash}, got={entry.previous_hash}") return False # Recompute hash data = f"{entry.timestamp}{entry.action}{entry.target}{entry.user}{entry.previous_hash}" expected_hash = hashlib.sha256(data.encode()).hexdigest()[:16] if entry.hash != expected_hash: self.logger.error(f"Hash mismatch at entry {i}: expected={expected_hash}, got={entry.hash}") return False previous_hash = entry.hash self.logger.info("Audit log integrity verified") return True # ============================================================================ # MAIN GUARDRAILS COORDINATOR # ============================================================================ class PentestGuardrails: """ Main guardrails coordinator combining all safety systems. Orchestrates scope validation, rate limiting, approval gates, sandbox isolation, and audit logging into a unified safety layer. Usage: guardrails = PentestGuardrails(config) result = guardrails.execute_with_guardrails( tool_name="nmap_port_scan", target="example.com", parameters={"ports": "80,443"}, user="pentester1", session_id="sess_123", executor=my_tool_function ) """ def __init__(self, config: Optional[Dict[str, Any]] = None): self.config = config or {} self.scope_validator = ScopeValidator(config) self.rate_limiter = RateLimiter(config.get("max_requests_per_minute", 60)) self.approval_gate = ApprovalGate(config) self.sandbox_manager = SandboxManager(config) self.audit_logger = AuditLogger(config.get("audit_log_file", "logs/audit.log")) self.logger = logging.getLogger("guardrails") self._risk_map = self._build_risk_map() self._auto_approve_below = RiskLevel[config.get("auto_approve_below", "LOW").upper()] self._require_sandbox_above = RiskLevel[config.get("require_sandbox_above", "HIGH").upper()] # ------------------------------------------------------------------ # RISK MAP (150+ Tools) # ------------------------------------------------------------------ def _build_risk_map(self) -> Dict[str, RiskLevel]: """ Map each tool to its risk level. Covers 150+ tools across reconnaissance, scanning, exploitation, post-exploitation, and AI-assisted tools. """ risk_map = { # ============================================================ # RECONNAISSANCE - SAFE / LOW # ============================================================ # Subdomain enumeration "subfinder_enum": RiskLevel.SAFE, "subfinder_passive": RiskLevel.SAFE, "subfinder_active": RiskLevel.LOW, "amass_enum": RiskLevel.LOW, "amass_passive": RiskLevel.SAFE, "assetfinder": RiskLevel.SAFE, "findomain": RiskLevel.SAFE, "chaos": RiskLevel.SAFE, # DNS enumeration "dns_enum": RiskLevel.SAFE, "dnsrecon": RiskLevel.LOW, "dnsx": RiskLevel.SAFE, "dig": RiskLevel.SAFE, "nslookup": RiskLevel.SAFE, # Certificate transparency "crtsh_cert_search": RiskLevel.SAFE, "censys_search": RiskLevel.SAFE, "certspotter": RiskLevel.SAFE, # Web crawling "katana_crawl": RiskLevel.SAFE, "gospider": RiskLevel.LOW, "hakrawler": RiskLevel.LOW, "waybackurls": RiskLevel.SAFE, "gau": RiskLevel.SAFE, # Probing "httpx_probe": RiskLevel.SAFE, "httprobe": RiskLevel.SAFE, "ffuf_vhost": RiskLevel.LOW, # WHOIS & OSINT "whois_lookup": RiskLevel.SAFE, "shodan_search": RiskLevel.SAFE, "shodan_host": RiskLevel.SAFE, "theharvester": RiskLevel.SAFE, "reconng": RiskLevel.SAFE, "maltego": RiskLevel.SAFE, "spiderfoot": RiskLevel.SAFE, # Social media OSINT "sherlock": RiskLevel.SAFE, "social_analyzer": RiskLevel.SAFE, # Cloud recon "cloud_enum": RiskLevel.SAFE, "s3scanner": RiskLevel.LOW, "cloudbrute": RiskLevel.LOW, "scout_suite": RiskLevel.LOW, # Git recon "gitrob": RiskLevel.SAFE, "gitleaks": RiskLevel.SAFE, "trufflehog": RiskLevel.SAFE, # ============================================================ # SCANNING - LOW / MEDIUM # ============================================================ # Port scanning "nmap_port_scan": RiskLevel.MEDIUM, "nmap_version_scan": RiskLevel.MEDIUM, "nmap_os_detect": RiskLevel.MEDIUM, "nmap_scripts": RiskLevel.MEDIUM, "masscan": RiskLevel.MEDIUM, "naabu": RiskLevel.MEDIUM, "rustscan": RiskLevel.MEDIUM, "unimap": RiskLevel.MEDIUM, # Web vulnerability scanning "nuclei_scan": RiskLevel.LOW, "nuclei_template": RiskLevel.LOW, "nikto_scan": RiskLevel.LOW, "zap_spider": RiskLevel.LOW, "zap_active_scan": RiskLevel.MEDIUM, "zap_passive_scan": RiskLevel.LOW, "burp_scan": RiskLevel.LOW, "acunetix_scan": RiskLevel.LOW, "arachni": RiskLevel.LOW, "w3af": RiskLevel.MEDIUM, "skipfish": RiskLevel.LOW, # Directory/file brute force "dirb": RiskLevel.LOW, "dirbuster": RiskLevel.LOW, "gobuster_dir": RiskLevel.LOW, "feroxbuster": RiskLevel.LOW, "wfuzz": RiskLevel.LOW, "ffuf_dir": RiskLevel.LOW, # SSL/TLS scanning "sslscan": RiskLevel.LOW, "testssl": RiskLevel.LOW, "sslyze": RiskLevel.LOW, # API scanning "arjun": RiskLevel.LOW, "postman_scan": RiskLevel.LOW, "swagger_scan": RiskLevel.LOW, # Technology fingerprinting "wappalyzer": RiskLevel.SAFE, "whatweb": RiskLevel.SAFE, "webtech": RiskLevel.SAFE, "builtwith": RiskLevel.SAFE, # ============================================================ # EXPLOITATION - HIGH / CRITICAL # ============================================================ # SQL Injection "sqlmap_scan": RiskLevel.HIGH, "sqlmap_dump": RiskLevel.CRITICAL, "sqlmap_shell": RiskLevel.CRITICAL, "sqlmap_tamper": RiskLevel.HIGH, # XSS exploitation "xsstrike": RiskLevel.HIGH, "dalfox": RiskLevel.HIGH, "xsser": RiskLevel.HIGH, # Command injection "commix": RiskLevel.HIGH, "command_injection_scan": RiskLevel.HIGH, # SSRF exploitation "ssrfmap": RiskLevel.HIGH, "gopherus": RiskLevel.HIGH, # File inclusion/path traversal "dotdotpwn": RiskLevel.HIGH, "lfi_scan": RiskLevel.HIGH, "rfi_scan": RiskLevel.HIGH, # Brute force "hydra_bruteforce": RiskLevel.HIGH, "medusa": RiskLevel.HIGH, "patator": RiskLevel.HIGH, "crowbar": RiskLevel.HIGH, "john_crack": RiskLevel.HIGH, "hashcat": RiskLevel.HIGH, # Metasploit "metasploit_exploit": RiskLevel.CRITICAL, "metasploit_auxiliary": RiskLevel.HIGH, "metasploit_post": RiskLevel.CRITICAL, "metasploit_meterpreter": RiskLevel.CRITICAL, "msfconsole": RiskLevel.CRITICAL, "msfvenom": RiskLevel.CRITICAL, # Exploit frameworks "searchsploit": RiskLevel.MEDIUM, "exploitdb_lookup": RiskLevel.MEDIUM, "routersploit": RiskLevel.HIGH, "armitage": RiskLevel.CRITICAL, # CMS exploitation "wpscan": RiskLevel.LOW, "wpscan_exploit": RiskLevel.HIGH, "droopescan": RiskLevel.LOW, "joomscan": RiskLevel.LOW, "cmsmap": RiskLevel.LOW, # Authentication attacks "jwt_tool": RiskLevel.HIGH, "jwt_tool_exploit": RiskLevel.HIGH, "oauth_scan": RiskLevel.LOW, "saml_scan": RiskLevel.LOW, # ============================================================ # POST-EXPLOITATION - CRITICAL # ============================================================ # Privilege escalation "privesc_linux": RiskLevel.CRITICAL, "privesc_windows": RiskLevel.CRITICAL, "linpeas": RiskLevel.CRITICAL, "winpeas": RiskLevel.CRITICAL, "linux_exploit_suggester": RiskLevel.CRITICAL, # Lateral movement "bloodhound": RiskLevel.CRITICAL, "crackmapexec": RiskLevel.CRITICAL, "impacket": RiskLevel.CRITICAL, "psexec": RiskLevel.CRITICAL, "wmiexec": RiskLevel.CRITICAL, "smbexec": RiskLevel.CRITICAL, "evil_winrm": RiskLevel.CRITICAL, # Credential harvesting "mimikatz": RiskLevel.CRITICAL, "responder": RiskLevel.CRITICAL, "hashdump": RiskLevel.CRITICAL, "secretsdump": RiskLevel.CRITICAL, "lsa_secrets": RiskLevel.CRITICAL, # Persistence "weevely": RiskLevel.CRITICAL, "webacoo": RiskLevel.CRITICAL, "pwncat": RiskLevel.CRITICAL, "revshell_gen": RiskLevel.CRITICAL, # Data exfiltration "exfiltration": RiskLevel.CRITICAL, "dns_exfil": RiskLevel.CRITICAL, "icmp_exfil": RiskLevel.CRITICAL, # ============================================================ # WIRELESS - HIGH / CRITICAL # ============================================================ "aircrack_ng": RiskLevel.HIGH, "wifite": RiskLevel.HIGH, "kismet": RiskLevel.LOW, "reaver": RiskLevel.HIGH, "bully": RiskLevel.HIGH, # ============================================================ # MOBILE - MEDIUM / HIGH # ============================================================ "mob_sf": RiskLevel.LOW, "drozer": RiskLevel.MEDIUM, "frida": RiskLevel.MEDIUM, "objection": RiskLevel.MEDIUM, "jadx": RiskLevel.SAFE, "apktool": RiskLevel.SAFE, # ============================================================ # NETWORK - MEDIUM / HIGH # ============================================================ "ettercap": RiskLevel.HIGH, "bettercap": RiskLevel.HIGH, "mitmproxy": RiskLevel.MEDIUM, "burp_proxy": RiskLevel.MEDIUM, "wireshark_capture": RiskLevel.MEDIUM, "tcpdump": RiskLevel.MEDIUM, # ============================================================ # AI-ASSISTED TOOLS - SAFE / LOW # ============================================================ "pentestgpt_reasoning": RiskLevel.SAFE, "pentestgpt_generate": RiskLevel.SAFE, "pentestgpt_analyze": RiskLevel.SAFE, "garak_probe_llm": RiskLevel.LOW, "garak_scan": RiskLevel.LOW, "ai_vuln_analysis": RiskLevel.SAFE, "ai_report_gen": RiskLevel.SAFE, "ai_threat_model": RiskLevel.SAFE, "ai_exploit_suggest": RiskLevel.MEDIUM, "ai_payload_gen": RiskLevel.HIGH, # ============================================================ # REPORTING - SAFE # ============================================================ "report_generate": RiskLevel.SAFE, "report_dradis": RiskLevel.SAFE, "report_farinade": RiskLevel.SAFE, "report_defectdojo": RiskLevel.SAFE, "cvss_calculate": RiskLevel.SAFE, # ============================================================ # UTILITY - SAFE / LOW # ============================================================ "base64_encode": RiskLevel.SAFE, "base64_decode": RiskLevel.SAFE, "url_encode": RiskLevel.SAFE, "hash_calculate": RiskLevel.SAFE, "jwt_decode": RiskLevel.SAFE, "curl_request": RiskLevel.LOW, "wget_download": RiskLevel.LOW, "netcat": RiskLevel.MEDIUM, "socat": RiskLevel.MEDIUM, } return risk_map def get_tool_risk(self, tool_name: str) -> RiskLevel: """Get the risk level for a tool.""" return self._risk_map.get(tool_name, RiskLevel.MEDIUM) # ------------------------------------------------------------------ # EVALUATION # ------------------------------------------------------------------ def evaluate( self, tool_name: str, target: str, parameters: Dict[str, Any], user: str, session_id: str, ) -> GuardrailDecision: """ Main evaluation method - checks all guardrails. Args: tool_name: Name of the tool to evaluate target: Target of the operation parameters: Tool parameters user: User identifier session_id: Session identifier Returns: GuardrailDecision with allow/deny and reason """ action_id = str(uuid.uuid4())[:12] risk_level = self.get_tool_risk(tool_name) # 1. Check scope scope_ok, scope_reason = self.check_scope(target) if not scope_ok: decision = GuardrailDecision( allowed=False, risk_level=risk_level, approval_required=False, approval_status=ApprovalStatus.DENIED, reason=f"Scope validation failed: {scope_reason}", rule_triggered="scope_validation", action_id=action_id, ) self._log_decision(tool_name, target, parameters, user, session_id, decision) return decision # 2. Check rate limit rate_ok, rate_reason = self.check_rate(session_id) if not rate_ok: decision = GuardrailDecision( allowed=False, risk_level=risk_level, approval_required=False, approval_status=ApprovalStatus.DENIED, reason=f"Rate limit exceeded: {rate_reason}", rule_triggered="rate_limiting", action_id=action_id, ) self._log_decision(tool_name, target, parameters, user, session_id, decision) return decision # 3. Check approval requirements approval_required = risk_level >= self._auto_approve_below if approval_required: approval_ok, approval_reason = self.check_approval(tool_name, target, parameters, risk_level) if not approval_ok: decision = GuardrailDecision( allowed=False, risk_level=risk_level, approval_required=True, approval_status=ApprovalStatus.PENDING, reason=f"Approval required: {approval_reason}", rule_triggered="approval_gate", action_id=action_id, ) self._log_decision( tool_name, target, parameters, user, session_id, decision, ) return decision approval_status = ApprovalStatus.APPROVED else: approval_status = ApprovalStatus.AUTO_APPROVED # 4. Check sandbox availability for high-risk if risk_level >= self._require_sandbox_above: sandbox_ok, sandbox_reason = self.check_sandbox(tool_name) if not sandbox_ok: decision = GuardrailDecision( allowed=False, risk_level=risk_level, approval_required=True, approval_status=approval_status, reason=f"Sandbox required: {sandbox_reason}", rule_triggered="sandbox_isolation", action_id=action_id, ) self._log_decision( tool_name, target, parameters, user, session_id, decision, ) return decision # All checks passed decision = GuardrailDecision( allowed=True, risk_level=risk_level, approval_required=approval_required, approval_status=approval_status, reason="All guardrail checks passed", action_id=action_id, ) self._log_decision(tool_name, target, parameters, user, session_id, decision) return decision def _log_decision( self, tool_name: str, target: str, parameters: Dict[str, Any], user: str, session_id: str, decision: GuardrailDecision, ) -> None: """Log a guardrail decision to the audit log.""" entry = AuditLogEntry( timestamp=datetime.now().isoformat(), action="guardrail_evaluation", tool=tool_name, target=target, user=user, parameters=parameters, result=decision.to_dict(), decision=decision, session_id=session_id, ) self.audit_logger.log(entry) # ------------------------------------------------------------------ # INDIVIDUAL CHECKS # ------------------------------------------------------------------ def check_scope(self, target: str) -> Tuple[bool, str]: """Check if target is in scope.""" valid, reason = self.scope_validator.validate_target(target) return valid, reason def check_rate(self, identifier: str) -> Tuple[bool, str]: """Check rate limit.""" allowed, remaining = self.rate_limiter.check_rate_limit(identifier) if not allowed: return False, "Rate limit exceeded. Try again later." return True, f"{remaining} requests remaining" def check_approval( self, tool_name: str, target: str, parameters: Dict[str, Any], risk_level: RiskLevel = RiskLevel.HIGH, ) -> Tuple[bool, str]: """Check if human approval is required and obtained.""" action_hash = hashlib.sha256(f"{tool_name}:{target}:{json.dumps(parameters, sort_keys=True)}".encode()).hexdigest()[ :12 ] status = self.approval_gate.check_approval(action_hash) if status == ApprovalStatus.APPROVED: return True, "Action approved" elif status == ApprovalStatus.DENIED: return False, "Action was previously denied" elif status == ApprovalStatus.PENDING: return False, f"Approval pending for {action_hash}" elif status == ApprovalStatus.EXPIRED: # Re-request self.approval_gate.request_approval( action_id=action_hash, action=f"Execute {tool_name} on {target}", tool=tool_name, target=target, parameters=parameters, risk_level=risk_level, ) return False, f"Approval expired, re-requested: {action_hash}" # No previous decision - request approval self.approval_gate.request_approval( action_id=action_hash, action=f"Execute {tool_name} on {target}", tool=tool_name, target=target, parameters=parameters, risk_level=risk_level, ) return False, f"Approval requested: {action_hash}" def check_sandbox(self, tool_name: str) -> Tuple[bool, str]: """Check if sandbox is required and available.""" risk_level = self.get_tool_risk(tool_name) if risk_level < self._require_sandbox_above: return True, "Sandbox not required for this risk level" if not self.sandbox_manager.docker_available: return False, ("Sandbox required but Docker not available. High-risk tools need sandbox isolation.") return True, "Sandbox available" # ------------------------------------------------------------------ # EXECUTION WITH GUARDRAILS # ------------------------------------------------------------------ def execute_with_guardrails( self, tool_name: str, target: str, parameters: Dict[str, Any], user: str, session_id: str, executor: Callable[..., Any], ) -> Dict[str, Any]: """ Execute a tool with full guardrail protection. Workflow: 1. Evaluate guardrails (scope, rate, approval, sandbox) 2. Request approval if needed 3. Create sandbox if needed 4. Execute the tool 5. Log results 6. Return results Args: tool_name: Name of the tool to execute target: Target of the operation parameters: Tool parameters user: User identifier session_id: Session identifier executor: Callable that performs the actual tool execution Returns: Dict with execution results and guardrail metadata """ # 1. Evaluate all guardrails decision = self.evaluate( tool_name=tool_name, target=target, parameters=parameters, user=user, session_id=session_id, ) # If not allowed, return decision if not decision.allowed: self.rate_limiter.record_request(session_id) return { "success": False, "error": decision.reason, "guardrails": decision.to_dict(), "output": None, } # 2. Create sandbox if needed risk_level = decision.risk_level sandbox_info = {} if risk_level >= self._require_sandbox_above: if session_id not in self.sandbox_manager.active_sandboxes: container_id = self.sandbox_manager.create_sandbox(session_id) sandbox_info = { "sandboxed": True, "container_id": container_id, } else: sandbox_info = { "sandboxed": True, "container_id": (self.sandbox_manager.active_sandboxes[session_id].get("container_id", "")), } # Record rate limit usage self.rate_limiter.record_request(session_id) # 3. Execute the tool execution_result = None error = None try: execution_result = executor( tool_name=tool_name, target=target, parameters=parameters, session_id=session_id, ) except Exception as e: error = str(e) self.logger.error(f"Execution error for {tool_name}: {e}") # 4. Log the execution log_entry = AuditLogEntry( timestamp=datetime.now().isoformat(), action="tool_execution", tool=tool_name, target=target, user=user, parameters=parameters, result="success" if error is None else f"error: {error}", decision=decision, session_id=session_id, ) self.audit_logger.log(log_entry) # 5. Return results return { "success": error is None, "error": error, "output": execution_result, "guardrails": decision.to_dict(), "sandbox": sandbox_info, "timestamp": datetime.now().isoformat(), } # ------------------------------------------------------------------ # UTILITY METHODS # ------------------------------------------------------------------ def get_risk_summary(self) -> Dict[str, Any]: """Get a summary of risk mappings.""" counts = {level: 0 for level in RiskLevel} for tool, level in self._risk_map.items(): counts[level] += 1 return { "total_tools": len(self._risk_map), "risk_distribution": {level.value: count for level, count in counts.items()}, "auto_approve_below": self._auto_approve_below.value, "require_sandbox_above": self._require_sandbox_above.value, "tools": {tool: level.value for tool, level in self._risk_map.items()}, } def add_risk_mapping(self, tool_name: str, risk_level: RiskLevel) -> None: """Add or update a risk mapping for a tool.""" self._risk_map[tool_name] = risk_level self.logger.info(f"Risk mapping updated: {tool_name} = {risk_level.value}") def get_pending_approvals(self) -> List[Dict[str, Any]]: """Get all pending approvals.""" return self.approval_gate.get_pending_approvals() def approve_action(self, action_id: str, approved_by: str = "operator") -> bool: """Approve a pending action.""" return self.approval_gate.approve(action_id, approved_by) def deny_action(self, action_id: str, reason: str = "") -> bool: """Deny a pending action.""" return self.approval_gate.deny(action_id, reason) def cleanup(self, session_id: Optional[str] = None) -> None: """ Clean up resources (sandboxes, etc.). Args: session_id: Specific session to clean up, or all if None """ if session_id: self.sandbox_manager.destroy_sandbox(session_id) else: self.sandbox_manager.cleanup_all() def verify_audit_integrity(self) -> bool: """Verify the integrity of the audit log.""" return self.audit_logger.verify_integrity() def export_audit_log(self, output_path: str) -> str: """Export the audit log to a file.""" return self.audit_logger.export_logs(output_path) # ============================================================================ # FACTORY / HELPERS # ============================================================================ def create_guardrails( scope_config: Optional[Dict[str, Any]] = None, max_requests_per_minute: int = 60, auto_approve_below: str = "LOW", require_sandbox_above: str = "HIGH", audit_log_file: str = "logs/audit.log", approval_timeout: int = 600, persistence_dir: str = "data", ) -> PentestGuardrails: """ Factory function to create a fully configured PentestGuardrails instance. Args: scope_config: Scope validation configuration max_requests_per_minute: Rate limit threshold auto_approve_below: Auto-approve tools below this risk level require_sandbox_above: Require sandbox for tools above this risk audit_log_file: Path to audit log file approval_timeout: Approval request timeout in seconds persistence_dir: Directory for persistent data Returns: Configured PentestGuardrails instance """ config = { "scope": scope_config or {}, "max_requests_per_minute": max_requests_per_minute, "auto_approve_below": auto_approve_below, "require_sandbox_above": require_sandbox_above, "audit_log_file": audit_log_file, "approval_timeout": approval_timeout, "persistence_dir": persistence_dir, } return PentestGuardrails(config) # ============================================================================ # CLI INTERFACE # ============================================================================ if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description="Zen AI Pentest Guardrails System") parser.add_argument( "--risk-summary", action="store_true", help="Show risk mapping summary", ) parser.add_argument( "--verify-integrity", action="store_true", help="Verify audit log integrity", ) parser.add_argument( "--export-audit", type=str, help="Export audit log to file", ) parser.add_argument( "--pending-approvals", action="store_true", help="Show pending approvals", ) parser.add_argument( "--approve", type=str, help="Approve action by ID", ) parser.add_argument( "--deny", type=str, help="Deny action by ID", ) args = parser.parse_args() guardrails = create_guardrails() if args.risk_summary: summary = guardrails.get_risk_summary() print(json.dumps(summary, indent=2)) if args.verify_integrity: result = guardrails.verify_audit_integrity() print(f"Audit integrity: {'VERIFIED' if result else 'FAILED'}") if args.export_audit: path = guardrails.export_audit_log(args.export_audit) print(f"Audit log exported to: {path}") if args.pending_approvals: pending = guardrails.get_pending_approvals() print(f"Pending approvals: {len(pending)}") for req in pending: print(f" - {req['action_id']}: {req['action']} (risk={req['risk_level']})") if args.approve: guardrails.approve_action(args.approve) print(f"Action {args.approve} approved") if args.deny: guardrails.deny_action(args.deny) print(f"Action {args.deny} denied")
"""
Guardrails - Safety layer for the MCP Pentest Suite.
Prevents unauthorized access, out-of-scope testing, and ensures
all activities are logged and approved.
Implements: Scope validation, Authorization checks, Rate limiting,
Sandbox isolation, Human approval gates, Audit logging.
Author: Senior Cybersecurity AI Architect
"""
import hashlib
import ipaddress
import json
import logging
import os
import re
import subprocess
import time
import uuid
from dataclasses import asdict, dataclass, field
from datetime import datetime, timedelta
from enum import Enum
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
logger = logging.getLogger("guardrails")
# ============================================================================
# ENUMS
# ============================================================================
class RiskLevel(Enum):
"""Risk classification for pentest operations."""
SAFE = "safe" # No risk (e.g., reconnaissance)
LOW = "low" # Minimal risk (e.g., passive scanning)
MEDIUM = "medium" # Moderate risk (e.g., active scanning)
HIGH = "high" # Significant risk (e.g., exploitation)
CRITICAL = "critical" # Severe risk (e.g., post-exploitation)
def __lt__(self, other: "RiskLevel") -> bool:
order = [RiskLevel.SAFE, RiskLevel.LOW, RiskLevel.MEDIUM, RiskLevel.HIGH, RiskLevel.CRITICAL]
return order.index(self) < order.index(other)
def __le__(self, other: "RiskLevel") -> bool:
return self == other or self < other
def __gt__(self, other: "RiskLevel") -> bool:
return not self <= other
def __ge__(self, other: "RiskLevel") -> bool:
return not self < other
class ApprovalStatus(Enum):
"""Approval status for critical operations."""
AUTO_APPROVED = "auto_approved"
APPROVED = "approved"
PENDING = "pending"
DENIED = "denied"
EXPIRED = "expired"
# ============================================================================
# DATA CLASSES
# ============================================================================
@dataclass
class GuardrailDecision:
"""Decision returned by the guardrails system."""
allowed: bool
risk_level: RiskLevel
approval_required: bool
approval_status: ApprovalStatus
reason: str
rule_triggered: Optional[str] = None
timestamp: str = field(default_factory=lambda: datetime.now().isoformat())
action_id: str = ""
def to_dict(self) -> Dict[str, Any]:
return {
"allowed": self.allowed,
"risk_level": self.risk_level.value,
"approval_required": self.approval_required,
"approval_status": self.approval_status.value,
"reason": self.reason,
"rule_triggered": self.rule_triggered,
"timestamp": self.timestamp,
"action_id": self.action_id,
}
@dataclass
class AuditLogEntry:

Xet Storage Details

Size:
68.1 kB
·
Xet hash:
c303989d27b9907a2510195622e88b641811cfc81324960b9f174e4555418602

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.