Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /zen_security /__init__.py
| """ | |
| Zen-AI-Pentest Zero-Trust Security Framework | |
| A comprehensive security architecture for AI-powered penetration testing | |
| supporting 100 concurrent agents with defense-in-depth principles. | |
| Components: | |
| - Temporal Credential Manager: Short-lived credentials with auto-rotation | |
| - mTLS Service Mesh: Mutual TLS for all inter-service communication | |
| - Enhanced Guardrails: IP/domain filtering, command validation, rate limiting | |
| - ML Risk Engine: CVSS/EPSS scoring with Bayesian false positive reduction | |
| - Tamper-Proof Audit: Digital signatures and chain of custody | |
| - Adversarial Testing: Red team framework for security validation | |
| Example: | |
| >>> from zen_security import ZeroTrustSecurity | |
| >>> | |
| >>> # Initialize security framework | |
| >>> security = ZeroTrustSecurity() | |
| >>> await security.initialize() | |
| >>> | |
| >>> # Provision agent | |
| >>> agent = await security.provision_agent( | |
| ... agent_id="agent-001", | |
| ... role=AgentRole.SCANNER | |
| ... ) | |
| >>> | |
| >>> # Validate action | |
| >>> decision = await security.guardrails.validate_action( | |
| ... agent_id="agent-001", | |
| ... action_type=ActionType.PORT_SCAN, | |
| ... target="example.com", | |
| ... risk_level=RiskLevel.LOW | |
| ... ) | |
| """ | |
| from datetime import datetime | |
| from typing import Dict, Optional, Set | |
| __version__ = "1.0.0" | |
| __author__ = "Zen Security Team" | |
| from .adversarial.red_team_framework import ( | |
| AdversarialTest, | |
| AttackVector, | |
| AuthenticationBypassTests, | |
| FuzzingEngine, | |
| InjectionTests, | |
| RedTeamOrchestrator, | |
| SecurityTestResult, | |
| TestSeverity, | |
| ) | |
| from .audit.tamper_proof_logger import ( | |
| AuditEvent, | |
| AuditEventType, | |
| ComplianceFramework, | |
| DigitalSignatureManager, | |
| EvidenceChain, | |
| TamperProofAuditLogger, | |
| ) | |
| from .core.mtls_auth import ( | |
| CertificateAuthority, | |
| CertificateBundle, | |
| CertificateStatus, | |
| SecureServiceMesh, | |
| ServiceIdentity, | |
| mTLSContextManager, | |
| ) | |
| from .core.temporal_credentials import ( | |
| ROLE_PERMISSIONS, | |
| AgentIdentity, | |
| AgentRole, | |
| CredentialStatus, | |
| TemporalCredential, | |
| TemporalCredentialManager, | |
| create_agent_identity, | |
| ) | |
| from .guardrails.enhanced_validator import ( | |
| ActionType, | |
| BudgetConfig, | |
| BudgetManager, | |
| CommandValidator, | |
| EnhancedGuardrailsValidator, | |
| GuardrailDecision, | |
| IPDomainFilter, | |
| RateLimitConfig, | |
| RateLimiter, | |
| RiskLevel, | |
| ValidationResult, | |
| ) | |
| from .risk_engine.ml_risk_engine import ( | |
| BayesianFalsePositiveReducer, | |
| BehavioralAnalyzer, | |
| BehavioralProfile, | |
| CVSSScore, | |
| EPSSScore, | |
| RiskScoringEngine, | |
| Severity, | |
| VulnerabilityFinding, | |
| VulnerabilityType, | |
| calculate_cvss_score, | |
| ) | |
| class ZeroTrustSecurity: | |
| """ | |
| Main entry point for the zero-trust security framework. | |
| This class provides a unified interface to all security components | |
| for easy integration with the Zen-AI-Pentest framework. | |
| Attributes: | |
| credential_manager: Manages temporal credentials for agents | |
| service_mesh: Provides mTLS for inter-service communication | |
| guardrails: Validates and enforces security policies | |
| risk_engine: Scores and analyzes security risks | |
| audit_logger: Records tamper-proof audit trails | |
| Example: | |
| >>> security = ZeroTrustSecurity() | |
| >>> await security.initialize() | |
| >>> | |
| >>> # Provision new agent | |
| >>> agent = await security.provision_agent( | |
| ... agent_id="scanner-001", | |
| ... role=AgentRole.SCANNER | |
| ... ) | |
| """ | |
| def __init__( | |
| self, | |
| redis_url: str = "redis://localhost:6379", | |
| config_path: Optional[str] = None, | |
| ): | |
| """ | |
| Initialize the zero-trust security framework. | |
| Args: | |
| redis_url: Redis connection URL for distributed state | |
| config_path: Path to security configuration file | |
| """ | |
| self.redis_url = redis_url | |
| self.config_path = config_path | |
| # Initialize components (not connected yet) | |
| self.credential_manager = TemporalCredentialManager(redis_url=redis_url) | |
| self.service_mesh = SecureServiceMesh(redis_url=redis_url) | |
| self.guardrails = EnhancedGuardrailsValidator(redis_url=redis_url) | |
| self.risk_engine = RiskScoringEngine(redis_url=redis_url) | |
| self.audit_logger = TamperProofAuditLogger(redis_url=redis_url) | |
| self._initialized = False | |
| async def initialize(self): | |
| """ | |
| Initialize all security components. | |
| This method must be called before using any security features. | |
| """ | |
| if self._initialized: | |
| return | |
| # Connect to Redis | |
| await self.credential_manager.connect() | |
| await self.service_mesh.initialize() | |
| await self.guardrails.initialize() | |
| await self.risk_engine.initialize() | |
| await self.audit_logger.connect() | |
| # Set up audit callback for guardrails | |
| self.guardrails.set_audit_callback(self._audit_guardrail_decision) | |
| # Log initialization | |
| await self.audit_logger.log_event( | |
| event_type=AuditEventType.CONFIG_CHANGED, | |
| action="security_framework_initialized", | |
| result="success", | |
| metadata={"version": __version__}, | |
| ) | |
| self._initialized = True | |
| async def provision_agent( | |
| self, | |
| agent_id: str, | |
| role: AgentRole, | |
| custom_permissions: Optional[Set[str]] = None, | |
| ttl: int = 3600, | |
| ) -> Dict: | |
| """ | |
| Provision a new agent with all security credentials. | |
| Args: | |
| agent_id: Unique agent identifier | |
| role: Agent role (determines permissions) | |
| custom_permissions: Additional permissions beyond role defaults | |
| ttl: Credential time-to-live in seconds | |
| Returns: | |
| Dictionary containing: | |
| - identity: AgentIdentity object | |
| - credential: TemporalCredential object | |
| - certificate: CertificateBundle object | |
| - spiffe_id: SPIFFE service identifier | |
| Example: | |
| >>> agent = await security.provision_agent( | |
| ... agent_id="scanner-001", | |
| ... role=AgentRole.SCANNER, | |
| ... ttl=7200 | |
| ... ) | |
| """ | |
| if not self._initialized: | |
| raise RuntimeError("Security framework not initialized. Call initialize() first.") | |
| # Create identity | |
| identity = await create_agent_identity(agent_id=agent_id, role=role, custom_permissions=custom_permissions) | |
| # Issue temporal credential | |
| credential = await self.credential_manager.issue_credential(identity, ttl=ttl, scope=list(identity.permissions)) | |
| # Provision mTLS certificate | |
| service_info = await self.service_mesh.register_service( | |
| service_id=agent_id, | |
| service_type=role.value, | |
| host=f"{agent_id}.zen-pentest.svc.cluster.local", | |
| port=8443, | |
| ) | |
| # Log provisioning | |
| await self.audit_logger.log_event( | |
| event_type=AuditEventType.AGENT_CREATED, | |
| action="provision_agent", | |
| result="success", | |
| agent_id=agent_id, | |
| metadata={ | |
| "role": role.value, | |
| "credential_id": credential.credential_id, | |
| "spiffe_id": service_info["spiffe_id"], | |
| }, | |
| ) | |
| return { | |
| "identity": identity, | |
| "credential": credential, | |
| "certificate": service_info["certificate"], | |
| "spiffe_id": service_info["spiffe_id"], | |
| } | |
| async def revoke_agent(self, agent_id: str, reason: str = "manual_revocation"): | |
| """ | |
| Revoke all credentials for an agent. | |
| Args: | |
| agent_id: Agent identifier to revoke | |
| reason: Reason for revocation | |
| """ | |
| # Revoke all credentials | |
| await self.credential_manager.revoke_all_agent_credentials(agent_id, reason) | |
| # Revoke mTLS certificate | |
| self.service_mesh.ca.revoke_certificate(agent_id) | |
| # Log revocation | |
| await self.audit_logger.log_event( | |
| event_type=AuditEventType.AGENT_DESTROYED, | |
| action="revoke_agent", | |
| result="success", | |
| agent_id=agent_id, | |
| metadata={"reason": reason}, | |
| ) | |
| async def validate_agent_action( | |
| self, | |
| agent_id: str, | |
| action_type: ActionType, | |
| target: Optional[str] = None, | |
| command: Optional[str] = None, | |
| risk_level: RiskLevel = RiskLevel.LOW, | |
| estimated_cost: Optional[Dict[str, float]] = None, | |
| ) -> GuardrailDecision: | |
| """ | |
| Validate an agent action against all guardrails. | |
| Args: | |
| agent_id: Agent attempting the action | |
| action_type: Type of action being attempted | |
| target: Target IP/domain (if applicable) | |
| command: Command to execute (if applicable) | |
| risk_level: Current risk level context | |
| estimated_cost: Estimated resource consumption | |
| Returns: | |
| GuardrailDecision with result and metadata | |
| """ | |
| return await self.guardrails.validate_action( | |
| agent_id=agent_id, | |
| action_type=action_type, | |
| target=target, | |
| command=command, | |
| risk_level=risk_level, | |
| estimated_cost=estimated_cost, | |
| ) | |
| async def score_vulnerability(self, finding: VulnerabilityFinding, context: Optional[Dict] = None) -> VulnerabilityFinding: | |
| """ | |
| Score a vulnerability finding with all risk components. | |
| Args: | |
| finding: The vulnerability finding to score | |
| context: Additional context for scoring | |
| Returns: | |
| Enriched finding with all scores | |
| """ | |
| return await self.risk_engine.score_finding(finding, context) | |
| async def create_evidence( | |
| self, | |
| finding_id: str, | |
| evidence_type: str, | |
| description: str, | |
| files: Dict[str, bytes], | |
| collected_by: str, | |
| ) -> EvidenceChain: | |
| """ | |
| Create an evidence chain with custody tracking. | |
| Args: | |
| finding_id: Associated finding identifier | |
| evidence_type: Type of evidence | |
| description: Evidence description | |
| files: Dictionary of filename -> content | |
| collected_by: Agent/user collecting evidence | |
| Returns: | |
| EvidenceChain object with integrity hash | |
| """ | |
| return await self.audit_logger.create_evidence_chain( | |
| finding_id=finding_id, | |
| evidence_type=evidence_type, | |
| description=description, | |
| files=files, | |
| collected_by=collected_by, | |
| ) | |
| async def verify_audit_integrity(self) -> Dict: | |
| """ | |
| Verify the integrity of the audit log chain. | |
| Returns: | |
| Verification result with statistics | |
| """ | |
| return await self.audit_logger.verify_integrity() | |
| async def generate_compliance_report( | |
| self, | |
| framework: ComplianceFramework, | |
| start_date: datetime, | |
| end_date: datetime, | |
| ) -> Dict: | |
| """ | |
| Generate a compliance report for the specified framework. | |
| Args: | |
| framework: Compliance framework (ISO27001, SOC2, etc.) | |
| start_date: Report period start | |
| end_date: Report period end | |
| Returns: | |
| Compliance report dictionary | |
| """ | |
| return await self.audit_logger.generate_compliance_report(framework, start_date, end_date) | |
| async def get_statistics(self) -> Dict: | |
| """ | |
| Get statistics for all security components. | |
| Returns: | |
| Dictionary with component statistics | |
| """ | |
| return { | |
| "credentials": self.credential_manager.get_statistics(), | |
| "audit": await self.audit_logger.get_statistics(), | |
| "risk_engine": self.risk_engine.get_statistics(), | |
| } | |
| async def _audit_guardrail_decision(self, decision: GuardrailDecision): | |
| """Internal callback to audit guardrail decisions""" | |
| event_type = AuditEventType.ACTION_APPROVED | |
| if decision.result == ValidationResult.DENIED: | |
| event_type = AuditEventType.ACTION_DENIED | |
| elif decision.result == ValidationResult.ESCALATION_REQUIRED: | |
| event_type = AuditEventType.SECURITY_ALERT | |
| await self.audit_logger.log_event( | |
| event_type=event_type, | |
| action=decision.action_type.value, | |
| result=decision.result.value, | |
| agent_id=decision.agent_id, | |
| metadata={ | |
| "reason": decision.reason, | |
| "risk_level": decision.risk_level.value, | |
| "target": decision.metadata.get("target"), | |
| }, | |
| ) | |
| async def close(self): | |
| """Close all connections and cleanup resources""" | |
| await self.credential_manager.disconnect() | |
| if self.audit_logger.redis: | |
| await self.audit_logger.redis.close() | |
| if self.guardrails.ip_filter.redis: | |
| await self.guardrails.ip_filter.redis.close() | |
| # Type imports for public API | |
| __all__ = [ | |
| # Main class | |
| "ZeroTrustSecurity", | |
| # Credentials | |
| "TemporalCredentialManager", | |
| "AgentIdentity", | |
| "AgentRole", | |
| "CredentialStatus", | |
| "TemporalCredential", | |
| "create_agent_identity", | |
| "ROLE_PERMISSIONS", | |
| # mTLS | |
| "CertificateAuthority", | |
| "mTLSContextManager", | |
| "ServiceIdentity", | |
| "CertificateBundle", | |
| "CertificateStatus", | |
| "SecureServiceMesh", | |
| # Guardrails | |
| "EnhancedGuardrailsValidator", | |
| "RiskLevel", | |
| "ActionType", | |
| "ValidationResult", | |
| "GuardrailDecision", | |
| "IPDomainFilter", | |
| "CommandValidator", | |
| "RateLimiter", | |
| "BudgetManager", | |
| "RateLimitConfig", | |
| "BudgetConfig", | |
| # Risk Engine | |
| "RiskScoringEngine", | |
| "CVSSScore", | |
| "EPSSScore", | |
| "VulnerabilityFinding", | |
| "VulnerabilityType", | |
| "Severity", | |
| "BehavioralProfile", | |
| "BayesianFalsePositiveReducer", | |
| "BehavioralAnalyzer", | |
| "calculate_cvss_score", | |
| # Audit | |
| "TamperProofAuditLogger", | |
| "AuditEvent", | |
| "AuditEventType", | |
| "EvidenceChain", | |
| "ComplianceFramework", | |
| "DigitalSignatureManager", | |
| # Adversarial Testing | |
| "RedTeamOrchestrator", | |
| "AdversarialTest", | |
| "SecurityTestResult", | |
| "AttackVector", | |
| "TestSeverity", | |
| "AuthenticationBypassTests", | |
| "InjectionTests", | |
| "FuzzingEngine", | |
| ] | |
Xet Storage Details
- Size:
- 14.6 kB
- Xet hash:
- c582136ef0ea30f5fa4a38757d98a9448000e85939a9559e2084156866ff59d1
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.