[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6H9EYC69MGC1HQ1E5X580CP":3,"skill-same:01M6H9EYC69MGC1HQ1E5X580CP":71},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":38,"linkOnly":39,"markdownContent":40,"markdownBody":41,"frontMatter":42,"refName":49,"commitSha":50,"skillDirectory":51,"forksCount":14,"repositoryHtmlUrl":52,"repositoryHomepageUrl":6,"ownerHtmlUrl":53,"ownerBlogUrl":54,"ownerDescription":55,"updatedAt":56,"install":57,"resources":70},"01M6H9EYC69MGC1HQ1E5X580CP","zero-trust",null,"Expert guidance on implementing zero trust security architectures where no user, device,  or network segment is implicitly trusted. Use for continuous verification of identity,  device health, and context for every access request, microsegmentation of networks,  policy-based access control, and migrating from perimeter-based security to zero trust.","NeuralBlitz\u002FMito","NeuralBlitz","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F79354388?v=4","01M6H8T2TFH477HRS0KTSTKR2E","David Riggs","01M6H8T2YQQDXPYM092P670Z21",0,"MIT","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fcybersecurity\u002Fzero-trust\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,5,32,33,34,35,36,37],"ZeRO","zero trust","trust","access","implementing","architectures","segment","Access Control","expert","opencode","context","security","identity-verification","least-privilege","network","verification","identity","auth","cybersecurity","2026-11-10 10:12:30",false,"---\nname: zero-trust\ndescription: >\n  Expert guidance on implementing zero trust security architectures where no user, device, \n  or network segment is implicitly trusted. Use for continuous verification of identity, \n  device health, and context for every access request, microsegmentation of networks, \n  policy-based access control, and migrating from perimeter-based security to zero trust.\nlicense: MIT\ncompatibility: opencode\nmetadata:\n  audience: security engineers\n  category: cybersecurity\n  tags: [zero-trust, microsegmentation, identity-verification, least-privilege, continuous-auth]\n---\n\n# Zero Trust Architecture — Implementation Guide\n\nCovers: **Identity Verification · Microsegmentation · Device Trust · Policy Engines · Continuous Authentication · Network Security**\n\n-----\n\n## Foundational Principles\n\n### The Core Tenets\n\nZero Trust operates on the principle of \"never trust, always verify.\" Every request must be authenticated and authorized regardless of its origin—whether it comes from inside the corporate network or from an external location. This approach assumes that threats can originate from anywhere, including insider threats and compromised credentials.\n\nThe fundamental shift from traditional perimeter-based security to zero trust involves eliminating the concept of a trusted internal network. In traditional models, once a user gained access to the internal network, they could often access many resources freely. Zero trust requires verification at every step, treating every access request as if it originates from an untrusted network.\n\n**Key Principles:**\n\n1. **Never Trust, Always Verify** — Authenticate and authorize every request regardless of source network, previous authentication, or device status.\n\n2. **Least Privilege Access** — Grant minimum required permissions for the specific task, resource, and time window. Elevate privileges only when necessary and for limited durations.\n\n3. **Assume Breach** — Design systems assuming adversaries are already inside the network. Limit lateral movement and minimize blast radius when compromises occur.\n\n4. **Verify Explicitly** — Base access decisions on all available data points: identity, device health, location, service or workload, data classification, and anomalies.\n\n### Traditional vs Zero Trust Comparison\n\n| Aspect | Traditional Perimeter | Zero Trust |\n|--------|----------------------|------------|\n| Network Trust | Internal network is trusted | No network is implicitly trusted |\n| Authentication | Once at login | Continuous throughout session |\n| Access Model | Role-based, broad | Attribute-based, granular |\n| Network Segmentation | Perimeter firewall | Microsegmentation |\n| Data Protection | Perimeter encryption | Everywhere encryption |\n| Threat Response | Detect and respond | Prevent and limit spread |\n| User Experience | VPN for remote access | Seamless, identity-based |\n\n-----\n\n## Identity & Access Management\n\n### Continuous Authentication\n\nUnlike traditional authentication that occurs only at login, zero trust requires continuous verification throughout a session. This involves analyzing behavioral biometrics, device posture, and contextual signals to detect session hijacking or credential compromise.\n\n```python\nfrom dataclasses import dataclass\nfrom enum import Enum\nfrom typing import List, Optional, Dict\nfrom datetime import datetime\nimport hashlib\n\nclass AuthenticationLevel(Enum):\n    NONE = 0\n    PASSWORD = 1\n    MFA = 2\n    BIOMETRIC = 3\n    HARDWARE_TOKEN = 4\n\nclass RiskLevel(Enum):\n    LOW = \"low\"\n    MEDIUM = \"medium\"\n    HIGH = \"high\"\n    CRITICAL = \"critical\"\n\n@dataclass\nclass UserIdentity:\n    user_id: str\n    username: str\n    email: str\n    department: str\n    role: str\n    authentication_level: AuthenticationLevel\n    registered_devices: List[str]\n    last_authentication: datetime\n    risk_score: float\n\n@dataclass\nclass DeviceState:\n    device_id: str\n    device_type: str\n    os_version: str\n    patch_level: datetime\n    encryption_enabled: bool\n    screen_lock_enabled: bool\n    biometric_enrolled: bool\n    jailbroken: bool\n    endpoint_protection_active: bool\n    last_seen: datetime\n\n@dataclass\nclass AccessContext:\n    user: UserIdentity\n    device: DeviceState\n    source_ip: str\n    source_network: str\n    requested_resource: str\n    requested_action: str\n    time_of_request: datetime\n    historical_behavior: Dict\n    anomaly_score: float\n\ndef calculate_risk_score(ctx: AccessContext) -> RiskLevel:\n    \"\"\"Calculate risk score based on multiple factors\"\"\"\n    score = 0.0\n    \n    # Authentication level factor\n    auth_scores = {\n        AuthenticationLevel.NONE: 0.4,\n        AuthenticationLevel.PASSWORD: 0.3,\n        AuthenticationLevel.MFA: 0.1,\n        AuthenticationLevel.BIOMETRIC: 0.05,\n        AuthenticationLevel.HARDWARE_TOKEN: 0.0\n    }\n    score += auth_scores.get(ctx.user.authentication_level, 0.3)\n    \n    # Device compliance factor\n    if ctx.device.jailbroken:\n        score += 0.4\n    if not ctx.device.encryption_enabled:\n        score += 0.2\n    if not ctx.device.endpoint_protection_active:\n        score += 0.15\n    if not ctx.device.screen_lock_enabled:\n        score += 0.1\n    \n    # Behavioral anomaly factor\n    score += ctx.anomaly_score\n    \n    # Network factor (unknown networks increase risk)\n    if ctx.source_network not in [\"corporate\", \"home\", \"known\"]:\n        score += 0.2\n    \n    # Time factor (unusual hours)\n    hour = ctx.time_of_request.hour\n    if hour \u003C 6 or hour > 22:\n        score += 0.1\n    \n    # Map to risk level\n    if score >= 0.7:\n        return RiskLevel.CRITICAL\n    elif score >= 0.5:\n        return RiskLevel.HIGH\n    elif score >= 0.3:\n        return RiskLevel.MEDIUM\n    else:\n        return RiskLevel.LOW\n```\n\n### Identity Provider Integration\n\n```python\nimport jwt\nfrom typing import Callable\n\nclass ZeroTrustIdentityProvider:\n    def __init__(self, jwks_url: str, audience: str, issuer: str):\n        self.jwks_url = jwks_url\n        self.audience = audience\n        self.issuer = issuer\n        self._jwks_client = None\n    \n    async def validate_token(self, token: str) -> Optional[UserIdentity]:\n        \"\"\"Validate JWT token and extract identity\"\"\"\n        try:\n            # In production, fetch JWKS and validate properly\n            payload = jwt.decode(\n                token,\n                options={\"verify_signature\": False}\n            )\n            \n            return UserIdentity(\n                user_id=payload.get(\"sub\"),\n                username=payload.get(\"preferred_username\"),\n                email=payload.get(\"email\"),\n                department=payload.get(\"department\", \"\"),\n                role=payload.get(\"role\", \"\"),\n                authentication_level=self._map_auth_level(payload.get(\"auth_level\")),\n                registered_devices=payload.get(\"devices\", []),\n                last_authentication=datetime.fromtimestamp(payload.get(\"auth_time\", 0)),\n                risk_score=payload.get(\"risk_score\", 0.0)\n            )\n        except Exception as e:\n            return None\n    \n    def _map_auth_level(self, level: str) -> AuthenticationLevel:\n        mapping = {\n            \"none\": AuthenticationLevel.NONE,\n            \"password\": AuthenticationLevel.PASSWORD,\n            \"mfa\": AuthenticationLevel.MFA,\n            \"biometric\": AuthenticationLevel.BIOMETRIC,\n            \"hardware\": AuthenticationLevel.HARDWARE_TOKEN\n        }\n        return mapping.get(level, AuthenticationLevel.PASSWORD)\n```\n\n-----\n\n## Policy Enforcement Points\n\n### Policy Decision Point\n\nThe Policy Decision Point (PDP) evaluates every access request against defined policies. It considers identity, device state, resource sensitivity, and contextual factors to make access decisions.\n\n```python\nfrom enum import Enum\n\nclass Decision(Enum):\n    ALLOW = \"allow\"\n    DENY = \"deny\"\n    MFA_REQUIRED = \"mfa_required\"\n    QUARANTINE = \"quarantine\"\n    LIMITED_ACCESS = \"limited_access\"\n\nclass ResourceClassification(Enum):\n    PUBLIC = 1\n    INTERNAL = 2\n    CONFIDENTIAL = 3\n    RESTRICTED = 4\n\nclass Action(Enum):\n    READ = \"read\"\n    WRITE = \"write\"\n    DELETE = \"delete\"\n    ADMIN = \"admin\"\n    EXECUTE = \"execute\"\n\n# Policy rules\nPOLICY_RULES = [\n    {\n        \"name\": \"require_mfa_for_sensitive\",\n        \"condition\": lambda ctx: (\n            ctx.user.authentication_level.value \u003C AuthenticationLevel.MFA.value\n            and ctx.requested_resource in [\"financial\", \"health\", \"admin\"]\n        ),\n        \"action\": Decision.MFA_REQUIRED\n    },\n    {\n        \"name\": \"block_compliance_violations\",\n        \"condition\": lambda ctx: (\n            ctx.device.jailbroken \n            or not ctx.device.encryption_enabled\n        ),\n        \"action\": Decision.QUARANTINE\n    },\n    {\n        \"name\": \"high_risk_block\",\n        \"condition\": lambda ctx: (\n            ctx.user.risk_score > 0.8 \n            or ctx.anomaly_score > 0.7\n        ),\n        \"action\": Decision.DENY\n    },\n    {\n        \"name\": \"time_based_access\",\n        \"condition\": lambda ctx: (\n            ctx.time_of_request.hour \u003C 6 \n            or ctx.time_of_request.hour > 22\n            and ctx.requested_action in [Action.DELETE, Action.ADMIN]\n        ),\n        \"action\": Decision.LIMITED_ACCESS\n    }\n]\n\ndef evaluate_policy(ctx: AccessContext, resource_policy: dict) -> Decision:\n    \"\"\"Evaluate access request against policies\"\"\"\n    \n    # Check risk level first\n    risk_level = calculate_risk_score(ctx)\n    \n    if risk_level == RiskLevel.CRITICAL:\n        return Decision.DENY\n    \n    # Evaluate each policy rule\n    for rule in POLICY_RULES:\n        if rule[\"condition\"](ctx):\n            return rule[\"action\"]\n    \n    # Resource-specific policies\n    if resource_policy.get(\"require_mfa\"):\n        if ctx.user.authentication_level.value \u003C AuthenticationLevel.MFA.value:\n            return Decision.MFA_REQUIRED\n    \n    # Check authorization\n    user_roles = ctx.user.role.split(\",\")\n    allowed_roles = resource_policy.get(\"allowed_roles\", [])\n    \n    if not any(role in allowed_roles for role in user_roles):\n        return Decision.DENY\n    \n    return Decision.ALLOW\n```\n\n### Policy Enforcement Point Implementation\n\n```python\nfrom fastapi import Request, HTTPException\nfrom starlette.middleware.base import BaseHTTPMiddleware\nfrom typing import Optional\nimport ipaddress\nimport hashlib\n\nTRUSTED_NETWORKS = [\n    ipaddress.ip_network(\"10.0.0.0\u002F8\"),\n    ipaddress.ip_network(\"172.16.0.0\u002F12\"),\n    ipaddress.ip_network(\"192.168.0.0\u002F16\")\n]\n\nSENSITIVE_RESOURCES = [\n    \"\u002Fapi\u002Fadmin\",\n    \"\u002Fapi\u002Ffinancial\",\n    \"\u002Fapi\u002Fhealth-records\",\n    \"\u002Fapi\u002Fuser-data\"\n]\n\nclass ZeroTrustMiddleware(BaseHTTPMiddleware):\n    def __init__(self, app, policy_engine):\n        super().__init__(app)\n        self.policy_engine = policy_engine\n    \n    async def dispatch(self, request: Request, call_next):\n        # Extract context from request\n        context = await self._build_context(request)\n        \n        # Determine resource and action\n        resource = self._get_resource_path(request)\n        action = self._get_action(request)\n        \n        # Get resource policy\n        resource_policy = self._get_resource_policy(resource)\n        \n        # Evaluate access\n        decision = self.policy_engine.evaluate(context, resource_policy, action)\n        \n        # Handle decision\n        if decision == Decision.DENY:\n            raise HTTPException(status_code=403, detail=\"Access denied\")\n        \n        if decision == Decision.MFA_REQUIRED:\n            raise HTTPException(\n                status_code=401,\n                detail=\"MFA required\",\n                headers={\"X-MFA-Required\": \"true\"}\n            )\n        \n        if decision == Decision.QUARANTINE:\n            raise HTTPException(\n                status_code=403,\n                detail=\"Device compliance required\"\n            )\n        \n        # Add context to request state\n        request.state.security_context = context\n        request.state.decision = decision\n        \n        response = await call_next(request)\n        \n        # Add security headers\n        response.headers[\"X-Content-Type-Options\"] = \"nosniff\"\n        response.headers[\"X-Frame-Options\"] = \"DENY\"\n        response.headers[\"X-XSS-Protection\"] = \"1; mode=block\"\n        \n        return response\n    \n    async def _build_context(self, request: Request) -> AccessContext:\n        # Extract tokens and validate\n        auth_header = request.headers.get(\"Authorization\", \"\")\n        token = auth_header.replace(\"Bearer \", \"\") if auth_header else \"\"\n        \n        # Get device information\n        device_id = request.headers.get(\"X-Device-ID\", \"\")\n        device_state = await self._get_device_state(device_id)\n        \n        # Get user identity\n        user = await self._get_user_from_token(token)\n        \n        # Get client IP and network\n        client_ip = request.client.host if request.client else \"0.0.0.0\"\n        ip = ipaddress.ip_address(client_ip)\n        network = \"internal\" if any(ip in net for net in TRUSTED_NETWORKS) else \"external\"\n        \n        # Build context\n        return AccessContext(\n            user=user,\n            device=device_state,\n            source_ip=client_ip,\n            source_network=network,\n            requested_resource=self._get_resource_path(request),\n            requested_action=self._get_action(request),\n            time_of_request=datetime.now(),\n            historical_behavior={},\n            anomaly_score=0.0\n        )\n    \n    def _get_resource_path(self, request: Request) -> str:\n        return request.url.path\n    \n    def _get_action(self, request: Request) -> Action:\n        method_action_map = {\n            \"GET\": Action.READ,\n            \"POST\": Action.WRITE,\n            \"PUT\": Action.WRITE,\n            \"PATCH\": Action.WRITE,\n            \"DELETE\": Action.DELETE,\n            \"ADMIN\": Action.ADMIN\n        }\n        return method_action_map.get(request.method, Action.READ)\n    \n    def _get_resource_policy(self, resource: str) -> dict:\n        for sensitive in SENSITIVE_RESOURCES:\n            if resource.startswith(sensitive):\n                return {\"require_mfa\": True, \"allowed_roles\": [\"admin\", \"manager\"]}\n        return {\"require_mfa\": False, \"allowed_roles\": [\"user\", \"admin\", \"manager\"]}\n    \n    async def _get_device_state(self, device_id: str) -> DeviceState:\n        # In production, fetch from device management system\n        return DeviceState(\n            device_id=device_id,\n            device_type=\"laptop\",\n            os_version=\"14.0\",\n            patch_level=datetime.now(),\n            encryption_enabled=True,\n            screen_lock_enabled=True,\n            biometric_enrolled=True,\n            jailbroken=False,\n            endpoint_protection_active=True,\n            last_seen=datetime.now()\n        )\n    \n    async def _get_user_from_token(self, token: str) -> UserIdentity:\n        # In production, validate and decode JWT\n        return UserIdentity(\n            user_id=\"user123\",\n            username=\"john.doe\",\n            email=\"john@example.com\",\n            department=\"engineering\",\n            role=\"admin\",\n            authentication_level=AuthenticationLevel.MFA,\n            registered_devices=[\"device1\", \"device2\"],\n            last_authentication=datetime.now(),\n            risk_score=0.1\n        )\n```\n\n-----\n\n## Network Microsegmentation\n\n### Principles of Microsegmentation\n\nMicrosegmentation involves dividing networks into granular zones, each with its own security controls. Unlike traditional network segmentation that focuses on perimeter defense, microsegmentation creates isolated segments at the workload level, controlling traffic between individual services or groups of services.\n\n**Key Implementation Approaches:**\n\n1. **Identity-Based Segmentation** — Assign identity to workloads and enforce policies based on workload identity rather than IP addresses.\n\n2. **Software-Defined Networking** — Use SDN controllers to program network policies dynamically based on workload state and requirements.\n\n3. **Host-Based Firewalls** — Deploy firewalls at the individual host level to control east-west traffic.\n\n### Network Policy Definition\n\n```yaml\n# NetworkPolicy example for Kubernetes\napiVersion: networking.k8s.io\u002Fv1\nkind: NetworkPolicy\nmetadata:\n  name: payment-service-policy\n  namespace: production\nspec:\n  podSelector:\n    matchLabels:\n      app: payment-service\n  policyTypes:\n    - Ingress\n    - Egress\n  ingress:\n    # Allow from API gateway\n    - from:\n        - podSelector:\n            matchLabels:\n              app: api-gateway\n      ports:\n        - protocol: TCP\n          port: 8080\n    # Allow from fraud detection\n    - from:\n        - podSelector:\n            matchLabels:\n              app: fraud-detection\n      ports:\n        - protocol: TCP\n          port: 8081\n    # Allow health checks\n    - from:\n        - namespaceSelector:\n            matchLabels:\n              name: monitoring\n      ports:\n        - protocol: TCP\n          port: 8082\n  egress:\n    # Allow to database\n    - to:\n        - podSelector:\n            matchLabels:\n              app: payment-db\n      ports:\n        - protocol: TCP\n          port: 5432\n    # Allow to external payment processors\n    - to:\n        - ipBlock:\n            cidr: 203.0.113.0\u002F24\n      ports:\n        - protocol: TCP\n          port: 443\n    # Allow DNS\n    - to:\n        - namespaceSelector:\n            matchLabels:\n              name: kube-system\n      ports:\n        - protocol: UDP\n          port: 53\n```\n\n### Service Mesh Implementation\n\n```yaml\n# Istio AuthorizationPolicy example\napiVersion: security.istio.io\u002Fv1beta1\nkind: AuthorizationPolicy\nmetadata:\n  name: shopping-cart-policy\n  namespace: e-commerce\nspec:\n  selector:\n    matchLabels:\n      app: shopping-cart\n  rules:\n    # Allow from frontend\n    - from:\n        - source:\n            principals: [\"cluster.local\u002Fns\u002Ffrontend\u002Fsa\u002Ffrontend-service\"]\n      to:\n        - operation:\n            ports: [\"8080\"]\n    # Allow from recommendation service\n    - from:\n        - source:\n            principals: [\"cluster.local\u002Fns\u002Frecommendations\u002Fsa\u002Frecommendation-service\"]\n      to:\n        - operation:\n            ports: [\"8080\"]\n            methods: [\"GET\"]\n    # Allow health checks\n    - to:\n        - operation:\n            ports: [\"15020\", \"8080\"]\n```\n\n-----\n\n## Service-to-Service Communication\n\n### Mutual TLS Implementation\n\nService-to-service communication in zero trust requires mutual authentication through mTLS, where both the client and server verify each other's certificates.\n\n```go\npackage main\n\nimport (\n\t\"crypto\u002Ftls\"\n\t\"crypto\u002Fx509\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\u002Fhttp\"\n\t\"os\"\n)\n\n\u002F\u002F ServiceIdentity represents the identity of a service\ntype ServiceIdentity struct {\n\tServiceName string\n\tNamespace   string\n\tVersion     string\n}\n\n\u002F\u002F MTLSConfig holds mTLS configuration\ntype MTLSConfig struct {\n\tCertFile       string\n\tKeyFile        string\n\tCAFile         string\n\tMinTLSVersion  uint16\n\tVerifyClient  bool\n}\n\nfunc LoadMTLSConfig() *MTLSConfig {\n\treturn &MTLSConfig{\n\t\tCertFile:      os.Getenv(\"SERVICE_CERT\"),\n\t\tKeyFile:       os.Getenv(\"SERVICE_KEY\"),\n\t\tCAFile:        os.Getenv(\"CA_CERT\"),\n\t\tMinTLSVersion: tls.VersionTLS13,\n\t\tVerifyClient:  true,\n\t}\n}\n\n\u002F\u002F CreateMTLSClient creates an HTTP client with mTLS for service communication\nfunc CreateMTLSClient(config *MTLSConfig) (*http.Client, error) {\n\tcert, err := tls.LoadX509KeyPair(config.CertFile, config.KeyFile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to load client certificate: %w\", err)\n\t}\n\n\tcaCert, err := os.ReadFile(config.CAFile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read CA certificate: %w\", err)\n\t}\n\n\tcaPool := x509.NewCertPool()\n\tif !caPool.AppendCertsFromPEM(caCert) {\n\t\treturn nil, fmt.Errorf(\"failed to append CA certificate\")\n\t}\n\n\ttlsConfig := &tls.Config{\n\t\tCertificates: []tls.Certificate{cert},\n\t\tRootCAs:      caPool,\n\t\tMinVersion:   config.MinTLSVersion,\n\t\tVerifyClient: config.VerifyClient,\n\t\t\u002F\u002F Verify peer certificate\n\t\tVerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {\n\t\t\t\u002F\u002F Additional verification logic\n\t\t\treturn nil\n\t\t},\n\t}\n\n\treturn &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: tlsConfig,\n\t\t\t\u002F\u002F Disable HTTP\u002F2 for mTLS to avoid issues\n\t\t\tTLSNextProto: make(map[string]func(interface{}, *tls.Conn) http.RoundTripper),\n\t\t},\n\t\tTimeout: 30,\n\t}, nil\n}\n\n\u002F\u002F CreateMTLSServer creates an HTTPS server with mTLS\nfunc CreateMTLSServer(config *MTLSConfig) (*http.Server, error) {\n\tcert, err := tls.LoadX509KeyPair(config.CertFile, config.KeyFile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to load server certificate: %w\", err)\n\t}\n\n\tcaCert, err := os.ReadFile(config.CAFile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read CA certificate: %w\", err)\n\t}\n\n\tcaPool := x509.NewCertPool()\n\tif !caPool.AppendCertsFromPEM(caCert) {\n\t\treturn nil, fmt.Errorf(\"failed to append CA certificate\")\n\t}\n\n\ttlsConfig := &tls.Config{\n\t\tCertificates: []tls.Certificate{cert},\n\t\tClientCAs:    caPool,\n\t\tClientAuth:   tls.RequestClientCert,\n\t\tMinVersion:   config.MinTLSVersion,\n\t\t\u002F\u002F Require client certificates\n\t\tVerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {\n\t\t\t\u002F\u002F Extract service identity from client certificate\n\t\t\t\u002F\u002F Verify against service registry\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"\u002Fhealth\", healthHandler)\n\tmux.HandleFunc(\"\u002Fapi\u002Fv1\u002Fdata\", apiHandler)\n\n\treturn &http.Server{\n\t\tAddr:      \":8443\",\n\t\tHandler:   mux,\n\t\tTLSConfig: tlsConfig,\n\t}, nil\n}\n\nfunc healthHandler(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n\tfmt.Fprintf(w, \"OK\")\n}\n\nfunc apiHandler(w http.ResponseWriter, r *http.Request) {\n\t\u002F\u002F Extract client certificate for authorization\n\tif r.TLS != nil && len(r.TLS.PeerCertificates) > 0 {\n\t\tclientCert := r.TLS.PeerCertificates[0]\n\t\tlog.Printf(\"Request from: %s\", clientCert.Subject)\n\t}\n\tw.WriteHeader(http.StatusOK)\n\tfmt.Fprintf(w, \"Data response\")\n}\n```\n\n-----\n\n## Device Trust & Compliance\n\n### Device Posture Assessment\n\n```python\nfrom dataclasses import dataclass\nfrom typing import List, Dict\nfrom datetime import datetime, timedelta\nimport asyncio\n\n@dataclass\nclass ComplianceRequirement:\n    name: str\n    description: str\n    check_interval_minutes: int\n    severity: str\n\nCOMPLIANCE_REQUIREMENTS = [\n    ComplianceRequirement(\n        name=\"antivirus_active\",\n        description=\"Endpoint protection must be active\",\n        check_interval_minutes=60,\n        severity=\"critical\"\n    ),\n    ComplianceRequirement(\n        name=\"encryption_enabled\",\n        description=\"Full disk encryption must be enabled\",\n        check_interval_minutes=60,\n        severity=\"critical\"\n    ),\n    ComplianceRequirement(\n        name=\"os_updated\",\n        description=\"OS must be within 30 days of latest patch\",\n        check_interval_minutes=1440,\n        severity=\"high\"\n    ),\n    ComplianceRequirement(\n        name=\"screen_lock\",\n        description=\"Screen lock must be enabled\",\n        check_interval_minutes=60,\n        severity=\"medium\"\n    ),\n    ComplianceRequirement(\n        name=\"jailbreak_check\",\n        description=\"Device must not be jailbroken\u002Frooted\",\n        check_interval_minutes=30,\n        severity=\"critical\"\n    )\n]\n\nclass DeviceComplianceEngine:\n    def __init__(self, device_api_client):\n        self.device_api = device_api_client\n        self.compliance_cache = {}\n    \n    async def assess_device(self, device_id: str) -> Dict:\n        \"\"\"Assess device compliance posture\"\"\"\n        device_state = await self.device_api.get_device_state(device_id)\n        \n        results = {\n            \"device_id\": device_id,\n            \"timestamp\": datetime.now(),\n            \"overall_status\": \"compliant\",\n            \"checks\": []\n        }\n        \n        for requirement in COMPLIANCE_REQUIREMENTS:\n            check_result = await self._run_compliance_check(\n                device_id, device_state, requirement\n            )\n            results[\"checks\"].append(check_result)\n            \n            if check_result[\"status\"] != \"pass\":\n                if requirement.severity in [\"critical\", \"high\"]:\n                    results[\"overall_status\"] = \"non_compliant\"\n        \n        # Update cache\n        self.compliance_cache[device_id] = results\n        \n        return results\n    \n    async def _run_compliance_check(\n        self, \n        device_id: str, \n        device_state: DeviceState,\n        requirement: ComplianceRequirement\n    ) -> Dict:\n        \"\"\"Run individual compliance check\"\"\"\n        check_map = {\n            \"antivirus_active\": lambda: device_state.endpoint_protection_active,\n            \"encryption_enabled\": lambda: device_state.encryption_enabled,\n            \"os_updated\": lambda: (\n                datetime.now() - device_state.patch_level \u003C timedelta(days=30)\n            ),\n            \"screen_lock\": lambda: device_state.screen_lock_enabled,\n            \"jailbreak_check\": lambda: not device_state.jailbroken\n        }\n        \n        check_func = check_map.get(requirement.name)\n        if check_func is None:\n            return {\n                \"requirement\": requirement.name,\n                \"status\": \"unknown\",\n                \"message\": \"Check not implemented\"\n            }\n        \n        passed = check_func()\n        \n        return {\n            \"requirement\": requirement.name,\n            \"status\": \"pass\" if passed else \"fail\",\n            \"severity\": requirement.severity,\n            \"message\": f\"{requirement.description}: {'OK' if passed else 'FAILED'}\"\n        }\n```\n\n-----\n\n## Monitoring & Analytics\n\n### Security Event Collection\n\n```python\nfrom dataclasses import dataclass, field\nfrom typing import List, Dict, Optional\nfrom datetime import datetime\nimport json\n\n@dataclass\nclass SecurityEvent:\n    timestamp: datetime\n    event_type: str\n    source: str\n    user_id: str\n    device_id: str\n    resource: str\n    action: str\n    decision: str\n    risk_score: float\n    metadata: Dict = field(default_factory=dict)\n\nclass SecurityEventCollector:\n    def __init__(self, event_store):\n        self.event_store = event_store\n    \n    async def collect_access_event(self, context: AccessContext, decision: Decision):\n        \"\"\"Collect access control event\"\"\"\n        event = SecurityEvent(\n            timestamp=datetime.now(),\n            event_type=\"access_attempt\",\n            source=context.source_ip,\n            user_id=context.user.user_id,\n            device_id=context.device.device_id,\n            resource=context.requested_resource,\n            action=context.requested_action,\n            decision=decision.value,\n            risk_score=calculate_risk_score(context),\n            metadata={\n                \"authentication_level\": context.user.authentication_level.value,\n                \"device_compliant\": not context.device.jailbroken,\n                \"network\": context.source_network,\n                \"hour\": context.time_of_request.hour\n            }\n        )\n        \n        await self.event_store.store(event)\n    \n    async def get_risk_indicators(self, user_id: str, time_window_hours: int = 24) -> Dict:\n        \"\"\"Analyze user behavior for risk indicators\"\"\"\n        events = await self.event_store.query(\n            user_id=user_id,\n            since=datetime.now() - timedelta(hours=time_window_hours)\n        )\n        \n        return {\n            \"total_attempts\": len(events),\n            \"failed_attempts\": len([e for e in events if e.decision == \"deny\"]),\n            \"high_risk_attempts\": len([e for e in events if e.risk_score > 0.7]),\n            \"unique_resources\": len(set(e.resource for e in events)),\n            \"unusual_hours\": len([e for e in events if e.timestamp.hour \u003C 6 or e.timestamp.hour > 22]),\n            \"unique_devices\": len(set(e.device_id for e in events))\n        }\n```\n\n-----\n\n## Best Practices Summary\n\n1. **Start with Identity** — Implement strong identity verification before addressing network security.\n\n2. **Deploy Gradually** — Phase in zero trust controls, starting with most critical assets.\n\n3. **Maintain Visibility** — Ensure comprehensive logging and monitoring across all components.\n\n4. **Automate Responses** — Build automated remediation for common compliance and security issues.\n\n5. **Focus on User Experience** — Balance security with usability to ensure adoption.\n\n6. **Continuous Improvement** — Regularly review and update policies based on threat intelligence.\n\n7. **Assume Breach Mentality** — Design for failure containment and rapid detection.\n","# Zero Trust Architecture — Implementation Guide\n\nCovers: **Identity Verification · Microsegmentation · Device Trust · Policy Engines · Continuous Authentication · Network Security**\n\n-----\n\n## Foundational Principles\n\n### The Core Tenets\n\nZero Trust operates on the principle of \"never trust, always verify.\" Every request must be authenticated and authorized regardless of its origin—whether it comes from inside the corporate network or from an external location. This approach assumes that threats can originate from anywhere, including insider threats and compromised credentials.\n\nThe fundamental shift from traditional perimeter-based security to zero trust involves eliminating the concept of a trusted internal network. In traditional models, once a user gained access to the internal network, they could often access many resources freely. Zero trust requires verification at every step, treating every access request as if it originates from an untrusted network.\n\n**Key Principles:**\n\n1. **Never Trust, Always Verify** — Authenticate and authorize every request regardless of source network, previous authentication, or device status.\n\n2. **Least Privilege Access** — Grant minimum required permissions for the specific task, resource, and time window. Elevate privileges only when necessary and for limited durations.\n\n3. **Assume Breach** — Design systems assuming adversaries are already inside the network. Limit lateral movement and minimize blast radius when compromises occur.\n\n4. **Verify Explicitly** — Base access decisions on all available data points: identity, device health, location, service or workload, data classification, and anomalies.\n\n### Traditional vs Zero Trust Comparison\n\n| Aspect | Traditional Perimeter | Zero Trust |\n|--------|----------------------|------------|\n| Network Trust | Internal network is trusted | No network is implicitly trusted |\n| Authentication | Once at login | Continuous throughout session |\n| Access Model | Role-based, broad | Attribute-based, granular |\n| Network Segmentation | Perimeter firewall | Microsegmentation |\n| Data Protection | Perimeter encryption | Everywhere encryption |\n| Threat Response | Detect and respond | Prevent and limit spread |\n| User Experience | VPN for remote access | Seamless, identity-based |\n\n-----\n\n## Identity & Access Management\n\n### Continuous Authentication\n\nUnlike traditional authentication that occurs only at login, zero trust requires continuous verification throughout a session. This involves analyzing behavioral biometrics, device posture, and contextual signals to detect session hijacking or credential compromise.\n\n```python\nfrom dataclasses import dataclass\nfrom enum import Enum\nfrom typing import List, Optional, Dict\nfrom datetime import datetime\nimport hashlib\n\nclass AuthenticationLevel(Enum):\n    NONE = 0\n    PASSWORD = 1\n    MFA = 2\n    BIOMETRIC = 3\n    HARDWARE_TOKEN = 4\n\nclass RiskLevel(Enum):\n    LOW = \"low\"\n    MEDIUM = \"medium\"\n    HIGH = \"high\"\n    CRITICAL = \"critical\"\n\n@dataclass\nclass UserIdentity:\n    user_id: str\n    username: str\n    email: str\n    department: str\n    role: str\n    authentication_level: AuthenticationLevel\n    registered_devices: List[str]\n    last_authentication: datetime\n    risk_score: float\n\n@dataclass\nclass DeviceState:\n    device_id: str\n    device_type: str\n    os_version: str\n    patch_level: datetime\n    encryption_enabled: bool\n    screen_lock_enabled: bool\n    biometric_enrolled: bool\n    jailbroken: bool\n    endpoint_protection_active: bool\n    last_seen: datetime\n\n@dataclass\nclass AccessContext:\n    user: UserIdentity\n    device: DeviceState\n    source_ip: str\n    source_network: str\n    requested_resource: str\n    requested_action: str\n    time_of_request: datetime\n    historical_behavior: Dict\n    anomaly_score: float\n\ndef calculate_risk_score(ctx: AccessContext) -> RiskLevel:\n    \"\"\"Calculate risk score based on multiple factors\"\"\"\n    score = 0.0\n    \n    # Authentication level factor\n    auth_scores = {\n        AuthenticationLevel.NONE: 0.4,\n        AuthenticationLevel.PASSWORD: 0.3,\n        AuthenticationLevel.MFA: 0.1,\n        AuthenticationLevel.BIOMETRIC: 0.05,\n        AuthenticationLevel.HARDWARE_TOKEN: 0.0\n    }\n    score += auth_scores.get(ctx.user.authentication_level, 0.3)\n    \n    # Device compliance factor\n    if ctx.device.jailbroken:\n        score += 0.4\n    if not ctx.device.encryption_enabled:\n        score += 0.2\n    if not ctx.device.endpoint_protection_active:\n        score += 0.15\n    if not ctx.device.screen_lock_enabled:\n        score += 0.1\n    \n    # Behavioral anomaly factor\n    score += ctx.anomaly_score\n    \n    # Network factor (unknown networks increase risk)\n    if ctx.source_network not in [\"corporate\", \"home\", \"known\"]:\n        score += 0.2\n    \n    # Time factor (unusual hours)\n    hour = ctx.time_of_request.hour\n    if hour \u003C 6 or hour > 22:\n        score += 0.1\n    \n    # Map to risk level\n    if score >= 0.7:\n        return RiskLevel.CRITICAL\n    elif score >= 0.5:\n        return RiskLevel.HIGH\n    elif score >= 0.3:\n        return RiskLevel.MEDIUM\n    else:\n        return RiskLevel.LOW\n```\n\n### Identity Provider Integration\n\n```python\nimport jwt\nfrom typing import Callable\n\nclass ZeroTrustIdentityProvider:\n    def __init__(self, jwks_url: str, audience: str, issuer: str):\n        self.jwks_url = jwks_url\n        self.audience = audience\n        self.issuer = issuer\n        self._jwks_client = None\n    \n    async def validate_token(self, token: str) -> Optional[UserIdentity]:\n        \"\"\"Validate JWT token and extract identity\"\"\"\n        try:\n            # In production, fetch JWKS and validate properly\n            payload = jwt.decode(\n                token,\n                options={\"verify_signature\": False}\n            )\n            \n            return UserIdentity(\n                user_id=payload.get(\"sub\"),\n                username=payload.get(\"preferred_username\"),\n                email=payload.get(\"email\"),\n                department=payload.get(\"department\", \"\"),\n                role=payload.get(\"role\", \"\"),\n                authentication_level=self._map_auth_level(payload.get(\"auth_level\")),\n                registered_devices=payload.get(\"devices\", []),\n                last_authentication=datetime.fromtimestamp(payload.get(\"auth_time\", 0)),\n                risk_score=payload.get(\"risk_score\", 0.0)\n            )\n        except Exception as e:\n            return None\n    \n    def _map_auth_level(self, level: str) -> AuthenticationLevel:\n        mapping = {\n            \"none\": AuthenticationLevel.NONE,\n            \"password\": AuthenticationLevel.PASSWORD,\n            \"mfa\": AuthenticationLevel.MFA,\n            \"biometric\": AuthenticationLevel.BIOMETRIC,\n            \"hardware\": AuthenticationLevel.HARDWARE_TOKEN\n        }\n        return mapping.get(level, AuthenticationLevel.PASSWORD)\n```\n\n-----\n\n## Policy Enforcement Points\n\n### Policy Decision Point\n\nThe Policy Decision Point (PDP) evaluates every access request against defined policies. It considers identity, device state, resource sensitivity, and contextual factors to make access decisions.\n\n```python\nfrom enum import Enum\n\nclass Decision(Enum):\n    ALLOW = \"allow\"\n    DENY = \"deny\"\n    MFA_REQUIRED = \"mfa_required\"\n    QUARANTINE = \"quarantine\"\n    LIMITED_ACCESS = \"limited_access\"\n\nclass ResourceClassification(Enum):\n    PUBLIC = 1\n    INTERNAL = 2\n    CONFIDENTIAL = 3\n    RESTRICTED = 4\n\nclass Action(Enum):\n    READ = \"read\"\n    WRITE = \"write\"\n    DELETE = \"delete\"\n    ADMIN = \"admin\"\n    EXECUTE = \"execute\"\n\n# Policy rules\nPOLICY_RULES = [\n    {\n        \"name\": \"require_mfa_for_sensitive\",\n        \"condition\": lambda ctx: (\n            ctx.user.authentication_level.value \u003C AuthenticationLevel.MFA.value\n            and ctx.requested_resource in [\"financial\", \"health\", \"admin\"]\n        ),\n        \"action\": Decision.MFA_REQUIRED\n    },\n    {\n        \"name\": \"block_compliance_violations\",\n        \"condition\": lambda ctx: (\n            ctx.device.jailbroken \n            or not ctx.device.encryption_enabled\n        ),\n        \"action\": Decision.QUARANTINE\n    },\n    {\n        \"name\": \"high_risk_block\",\n        \"condition\": lambda ctx: (\n            ctx.user.risk_score > 0.8 \n            or ctx.anomaly_score > 0.7\n        ),\n        \"action\": Decision.DENY\n    },\n    {\n        \"name\": \"time_based_access\",\n        \"condition\": lambda ctx: (\n            ctx.time_of_request.hour \u003C 6 \n            or ctx.time_of_request.hour > 22\n            and ctx.requested_action in [Action.DELETE, Action.ADMIN]\n        ),\n        \"action\": Decision.LIMITED_ACCESS\n    }\n]\n\ndef evaluate_policy(ctx: AccessContext, resource_policy: dict) -> Decision:\n    \"\"\"Evaluate access request against policies\"\"\"\n    \n    # Check risk level first\n    risk_level = calculate_risk_score(ctx)\n    \n    if risk_level == RiskLevel.CRITICAL:\n        return Decision.DENY\n    \n    # Evaluate each policy rule\n    for rule in POLICY_RULES:\n        if rule[\"condition\"](ctx):\n            return rule[\"action\"]\n    \n    # Resource-specific policies\n    if resource_policy.get(\"require_mfa\"):\n        if ctx.user.authentication_level.value \u003C AuthenticationLevel.MFA.value:\n            return Decision.MFA_REQUIRED\n    \n    # Check authorization\n    user_roles = ctx.user.role.split(\",\")\n    allowed_roles = resource_policy.get(\"allowed_roles\", [])\n    \n    if not any(role in allowed_roles for role in user_roles):\n        return Decision.DENY\n    \n    return Decision.ALLOW\n```\n\n### Policy Enforcement Point Implementation\n\n```python\nfrom fastapi import Request, HTTPException\nfrom starlette.middleware.base import BaseHTTPMiddleware\nfrom typing import Optional\nimport ipaddress\nimport hashlib\n\nTRUSTED_NETWORKS = [\n    ipaddress.ip_network(\"10.0.0.0\u002F8\"),\n    ipaddress.ip_network(\"172.16.0.0\u002F12\"),\n    ipaddress.ip_network(\"192.168.0.0\u002F16\")\n]\n\nSENSITIVE_RESOURCES = [\n    \"\u002Fapi\u002Fadmin\",\n    \"\u002Fapi\u002Ffinancial\",\n    \"\u002Fapi\u002Fhealth-records\",\n    \"\u002Fapi\u002Fuser-data\"\n]\n\nclass ZeroTrustMiddleware(BaseHTTPMiddleware):\n    def __init__(self, app, policy_engine):\n        super().__init__(app)\n        self.policy_engine = policy_engine\n    \n    async def dispatch(self, request: Request, call_next):\n        # Extract context from request\n        context = await self._build_context(request)\n        \n        # Determine resource and action\n        resource = self._get_resource_path(request)\n        action = self._get_action(request)\n        \n        # Get resource policy\n        resource_policy = self._get_resource_policy(resource)\n        \n        # Evaluate access\n        decision = self.policy_engine.evaluate(context, resource_policy, action)\n        \n        # Handle decision\n        if decision == Decision.DENY:\n            raise HTTPException(status_code=403, detail=\"Access denied\")\n        \n        if decision == Decision.MFA_REQUIRED:\n            raise HTTPException(\n                status_code=401,\n                detail=\"MFA required\",\n                headers={\"X-MFA-Required\": \"true\"}\n            )\n        \n        if decision == Decision.QUARANTINE:\n            raise HTTPException(\n                status_code=403,\n                detail=\"Device compliance required\"\n            )\n        \n        # Add context to request state\n        request.state.security_context = context\n        request.state.decision = decision\n        \n        response = await call_next(request)\n        \n        # Add security headers\n        response.headers[\"X-Content-Type-Options\"] = \"nosniff\"\n        response.headers[\"X-Frame-Options\"] = \"DENY\"\n        response.headers[\"X-XSS-Protection\"] = \"1; mode=block\"\n        \n        return response\n    \n    async def _build_context(self, request: Request) -> AccessContext:\n        # Extract tokens and validate\n        auth_header = request.headers.get(\"Authorization\", \"\")\n        token = auth_header.replace(\"Bearer \", \"\") if auth_header else \"\"\n        \n        # Get device information\n        device_id = request.headers.get(\"X-Device-ID\", \"\")\n        device_state = await self._get_device_state(device_id)\n        \n        # Get user identity\n        user = await self._get_user_from_token(token)\n        \n        # Get client IP and network\n        client_ip = request.client.host if request.client else \"0.0.0.0\"\n        ip = ipaddress.ip_address(client_ip)\n        network = \"internal\" if any(ip in net for net in TRUSTED_NETWORKS) else \"external\"\n        \n        # Build context\n        return AccessContext(\n            user=user,\n            device=device_state,\n            source_ip=client_ip,\n            source_network=network,\n            requested_resource=self._get_resource_path(request),\n            requested_action=self._get_action(request),\n            time_of_request=datetime.now(),\n            historical_behavior={},\n            anomaly_score=0.0\n        )\n    \n    def _get_resource_path(self, request: Request) -> str:\n        return request.url.path\n    \n    def _get_action(self, request: Request) -> Action:\n        method_action_map = {\n            \"GET\": Action.READ,\n            \"POST\": Action.WRITE,\n            \"PUT\": Action.WRITE,\n            \"PATCH\": Action.WRITE,\n            \"DELETE\": Action.DELETE,\n            \"ADMIN\": Action.ADMIN\n        }\n        return method_action_map.get(request.method, Action.READ)\n    \n    def _get_resource_policy(self, resource: str) -> dict:\n        for sensitive in SENSITIVE_RESOURCES:\n            if resource.startswith(sensitive):\n                return {\"require_mfa\": True, \"allowed_roles\": [\"admin\", \"manager\"]}\n        return {\"require_mfa\": False, \"allowed_roles\": [\"user\", \"admin\", \"manager\"]}\n    \n    async def _get_device_state(self, device_id: str) -> DeviceState:\n        # In production, fetch from device management system\n        return DeviceState(\n            device_id=device_id,\n            device_type=\"laptop\",\n            os_version=\"14.0\",\n            patch_level=datetime.now(),\n            encryption_enabled=True,\n            screen_lock_enabled=True,\n            biometric_enrolled=True,\n            jailbroken=False,\n            endpoint_protection_active=True,\n            last_seen=datetime.now()\n        )\n    \n    async def _get_user_from_token(self, token: str) -> UserIdentity:\n        # In production, validate and decode JWT\n        return UserIdentity(\n            user_id=\"user123\",\n            username=\"john.doe\",\n            email=\"john@example.com\",\n            department=\"engineering\",\n            role=\"admin\",\n            authentication_level=AuthenticationLevel.MFA,\n            registered_devices=[\"device1\", \"device2\"],\n            last_authentication=datetime.now(),\n            risk_score=0.1\n        )\n```\n\n-----\n\n## Network Microsegmentation\n\n### Principles of Microsegmentation\n\nMicrosegmentation involves dividing networks into granular zones, each with its own security controls. Unlike traditional network segmentation that focuses on perimeter defense, microsegmentation creates isolated segments at the workload level, controlling traffic between individual services or groups of services.\n\n**Key Implementation Approaches:**\n\n1. **Identity-Based Segmentation** — Assign identity to workloads and enforce policies based on workload identity rather than IP addresses.\n\n2. **Software-Defined Networking** — Use SDN controllers to program network policies dynamically based on workload state and requirements.\n\n3. **Host-Based Firewalls** — Deploy firewalls at the individual host level to control east-west traffic.\n\n### Network Policy Definition\n\n```yaml\n# NetworkPolicy example for Kubernetes\napiVersion: networking.k8s.io\u002Fv1\nkind: NetworkPolicy\nmetadata:\n  name: payment-service-policy\n  namespace: production\nspec:\n  podSelector:\n    matchLabels:\n      app: payment-service\n  policyTypes:\n    - Ingress\n    - Egress\n  ingress:\n    # Allow from API gateway\n    - from:\n        - podSelector:\n            matchLabels:\n              app: api-gateway\n      ports:\n        - protocol: TCP\n          port: 8080\n    # Allow from fraud detection\n    - from:\n        - podSelector:\n            matchLabels:\n              app: fraud-detection\n      ports:\n        - protocol: TCP\n          port: 8081\n    # Allow health checks\n    - from:\n        - namespaceSelector:\n            matchLabels:\n              name: monitoring\n      ports:\n        - protocol: TCP\n          port: 8082\n  egress:\n    # Allow to database\n    - to:\n        - podSelector:\n            matchLabels:\n              app: payment-db\n      ports:\n        - protocol: TCP\n          port: 5432\n    # Allow to external payment processors\n    - to:\n        - ipBlock:\n            cidr: 203.0.113.0\u002F24\n      ports:\n        - protocol: TCP\n          port: 443\n    # Allow DNS\n    - to:\n        - namespaceSelector:\n            matchLabels:\n              name: kube-system\n      ports:\n        - protocol: UDP\n          port: 53\n```\n\n### Service Mesh Implementation\n\n```yaml\n# Istio AuthorizationPolicy example\napiVersion: security.istio.io\u002Fv1beta1\nkind: AuthorizationPolicy\nmetadata:\n  name: shopping-cart-policy\n  namespace: e-commerce\nspec:\n  selector:\n    matchLabels:\n      app: shopping-cart\n  rules:\n    # Allow from frontend\n    - from:\n        - source:\n            principals: [\"cluster.local\u002Fns\u002Ffrontend\u002Fsa\u002Ffrontend-service\"]\n      to:\n        - operation:\n            ports: [\"8080\"]\n    # Allow from recommendation service\n    - from:\n        - source:\n            principals: [\"cluster.local\u002Fns\u002Frecommendations\u002Fsa\u002Frecommendation-service\"]\n      to:\n        - operation:\n            ports: [\"8080\"]\n            methods: [\"GET\"]\n    # Allow health checks\n    - to:\n        - operation:\n            ports: [\"15020\", \"8080\"]\n```\n\n-----\n\n## Service-to-Service Communication\n\n### Mutual TLS Implementation\n\nService-to-service communication in zero trust requires mutual authentication through mTLS, where both the client and server verify each other's certificates.\n\n```go\npackage main\n\nimport (\n\t\"crypto\u002Ftls\"\n\t\"crypto\u002Fx509\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\u002Fhttp\"\n\t\"os\"\n)\n\n\u002F\u002F ServiceIdentity represents the identity of a service\ntype ServiceIdentity struct {\n\tServiceName string\n\tNamespace   string\n\tVersion     string\n}\n\n\u002F\u002F MTLSConfig holds mTLS configuration\ntype MTLSConfig struct {\n\tCertFile       string\n\tKeyFile        string\n\tCAFile         string\n\tMinTLSVersion  uint16\n\tVerifyClient  bool\n}\n\nfunc LoadMTLSConfig() *MTLSConfig {\n\treturn &MTLSConfig{\n\t\tCertFile:      os.Getenv(\"SERVICE_CERT\"),\n\t\tKeyFile:       os.Getenv(\"SERVICE_KEY\"),\n\t\tCAFile:        os.Getenv(\"CA_CERT\"),\n\t\tMinTLSVersion: tls.VersionTLS13,\n\t\tVerifyClient:  true,\n\t}\n}\n\n\u002F\u002F CreateMTLSClient creates an HTTP client with mTLS for service communication\nfunc CreateMTLSClient(config *MTLSConfig) (*http.Client, error) {\n\tcert, err := tls.LoadX509KeyPair(config.CertFile, config.KeyFile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to load client certificate: %w\", err)\n\t}\n\n\tcaCert, err := os.ReadFile(config.CAFile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read CA certificate: %w\", err)\n\t}\n\n\tcaPool := x509.NewCertPool()\n\tif !caPool.AppendCertsFromPEM(caCert) {\n\t\treturn nil, fmt.Errorf(\"failed to append CA certificate\")\n\t}\n\n\ttlsConfig := &tls.Config{\n\t\tCertificates: []tls.Certificate{cert},\n\t\tRootCAs:      caPool,\n\t\tMinVersion:   config.MinTLSVersion,\n\t\tVerifyClient: config.VerifyClient,\n\t\t\u002F\u002F Verify peer certificate\n\t\tVerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {\n\t\t\t\u002F\u002F Additional verification logic\n\t\t\treturn nil\n\t\t},\n\t}\n\n\treturn &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: tlsConfig,\n\t\t\t\u002F\u002F Disable HTTP\u002F2 for mTLS to avoid issues\n\t\t\tTLSNextProto: make(map[string]func(interface{}, *tls.Conn) http.RoundTripper),\n\t\t},\n\t\tTimeout: 30,\n\t}, nil\n}\n\n\u002F\u002F CreateMTLSServer creates an HTTPS server with mTLS\nfunc CreateMTLSServer(config *MTLSConfig) (*http.Server, error) {\n\tcert, err := tls.LoadX509KeyPair(config.CertFile, config.KeyFile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to load server certificate: %w\", err)\n\t}\n\n\tcaCert, err := os.ReadFile(config.CAFile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read CA certificate: %w\", err)\n\t}\n\n\tcaPool := x509.NewCertPool()\n\tif !caPool.AppendCertsFromPEM(caCert) {\n\t\treturn nil, fmt.Errorf(\"failed to append CA certificate\")\n\t}\n\n\ttlsConfig := &tls.Config{\n\t\tCertificates: []tls.Certificate{cert},\n\t\tClientCAs:    caPool,\n\t\tClientAuth:   tls.RequestClientCert,\n\t\tMinVersion:   config.MinTLSVersion,\n\t\t\u002F\u002F Require client certificates\n\t\tVerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {\n\t\t\t\u002F\u002F Extract service identity from client certificate\n\t\t\t\u002F\u002F Verify against service registry\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"\u002Fhealth\", healthHandler)\n\tmux.HandleFunc(\"\u002Fapi\u002Fv1\u002Fdata\", apiHandler)\n\n\treturn &http.Server{\n\t\tAddr:      \":8443\",\n\t\tHandler:   mux,\n\t\tTLSConfig: tlsConfig,\n\t}, nil\n}\n\nfunc healthHandler(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n\tfmt.Fprintf(w, \"OK\")\n}\n\nfunc apiHandler(w http.ResponseWriter, r *http.Request) {\n\t\u002F\u002F Extract client certificate for authorization\n\tif r.TLS != nil && len(r.TLS.PeerCertificates) > 0 {\n\t\tclientCert := r.TLS.PeerCertificates[0]\n\t\tlog.Printf(\"Request from: %s\", clientCert.Subject)\n\t}\n\tw.WriteHeader(http.StatusOK)\n\tfmt.Fprintf(w, \"Data response\")\n}\n```\n\n-----\n\n## Device Trust & Compliance\n\n### Device Posture Assessment\n\n```python\nfrom dataclasses import dataclass\nfrom typing import List, Dict\nfrom datetime import datetime, timedelta\nimport asyncio\n\n@dataclass\nclass ComplianceRequirement:\n    name: str\n    description: str\n    check_interval_minutes: int\n    severity: str\n\nCOMPLIANCE_REQUIREMENTS = [\n    ComplianceRequirement(\n        name=\"antivirus_active\",\n        description=\"Endpoint protection must be active\",\n        check_interval_minutes=60,\n        severity=\"critical\"\n    ),\n    ComplianceRequirement(\n        name=\"encryption_enabled\",\n        description=\"Full disk encryption must be enabled\",\n        check_interval_minutes=60,\n        severity=\"critical\"\n    ),\n    ComplianceRequirement(\n        name=\"os_updated\",\n        description=\"OS must be within 30 days of latest patch\",\n        check_interval_minutes=1440,\n        severity=\"high\"\n    ),\n    ComplianceRequirement(\n        name=\"screen_lock\",\n        description=\"Screen lock must be enabled\",\n        check_interval_minutes=60,\n        severity=\"medium\"\n    ),\n    ComplianceRequirement(\n        name=\"jailbreak_check\",\n        description=\"Device must not be jailbroken\u002Frooted\",\n        check_interval_minutes=30,\n        severity=\"critical\"\n    )\n]\n\nclass DeviceComplianceEngine:\n    def __init__(self, device_api_client):\n        self.device_api = device_api_client\n        self.compliance_cache = {}\n    \n    async def assess_device(self, device_id: str) -> Dict:\n        \"\"\"Assess device compliance posture\"\"\"\n        device_state = await self.device_api.get_device_state(device_id)\n        \n        results = {\n            \"device_id\": device_id,\n            \"timestamp\": datetime.now(),\n            \"overall_status\": \"compliant\",\n            \"checks\": []\n        }\n        \n        for requirement in COMPLIANCE_REQUIREMENTS:\n            check_result = await self._run_compliance_check(\n                device_id, device_state, requirement\n            )\n            results[\"checks\"].append(check_result)\n            \n            if check_result[\"status\"] != \"pass\":\n                if requirement.severity in [\"critical\", \"high\"]:\n                    results[\"overall_status\"] = \"non_compliant\"\n        \n        # Update cache\n        self.compliance_cache[device_id] = results\n        \n        return results\n    \n    async def _run_compliance_check(\n        self, \n        device_id: str, \n        device_state: DeviceState,\n        requirement: ComplianceRequirement\n    ) -> Dict:\n        \"\"\"Run individual compliance check\"\"\"\n        check_map = {\n            \"antivirus_active\": lambda: device_state.endpoint_protection_active,\n            \"encryption_enabled\": lambda: device_state.encryption_enabled,\n            \"os_updated\": lambda: (\n                datetime.now() - device_state.patch_level \u003C timedelta(days=30)\n            ),\n            \"screen_lock\": lambda: device_state.screen_lock_enabled,\n            \"jailbreak_check\": lambda: not device_state.jailbroken\n        }\n        \n        check_func = check_map.get(requirement.name)\n        if check_func is None:\n            return {\n                \"requirement\": requirement.name,\n                \"status\": \"unknown\",\n                \"message\": \"Check not implemented\"\n            }\n        \n        passed = check_func()\n        \n        return {\n            \"requirement\": requirement.name,\n            \"status\": \"pass\" if passed else \"fail\",\n            \"severity\": requirement.severity,\n            \"message\": f\"{requirement.description}: {'OK' if passed else 'FAILED'}\"\n        }\n```\n\n-----\n\n## Monitoring & Analytics\n\n### Security Event Collection\n\n```python\nfrom dataclasses import dataclass, field\nfrom typing import List, Dict, Optional\nfrom datetime import datetime\nimport json\n\n@dataclass\nclass SecurityEvent:\n    timestamp: datetime\n    event_type: str\n    source: str\n    user_id: str\n    device_id: str\n    resource: str\n    action: str\n    decision: str\n    risk_score: float\n    metadata: Dict = field(default_factory=dict)\n\nclass SecurityEventCollector:\n    def __init__(self, event_store):\n        self.event_store = event_store\n    \n    async def collect_access_event(self, context: AccessContext, decision: Decision):\n        \"\"\"Collect access control event\"\"\"\n        event = SecurityEvent(\n            timestamp=datetime.now(),\n            event_type=\"access_attempt\",\n            source=context.source_ip,\n            user_id=context.user.user_id,\n            device_id=context.device.device_id,\n            resource=context.requested_resource,\n            action=context.requested_action,\n            decision=decision.value,\n            risk_score=calculate_risk_score(context),\n            metadata={\n                \"authentication_level\": context.user.authentication_level.value,\n                \"device_compliant\": not context.device.jailbroken,\n                \"network\": context.source_network,\n                \"hour\": context.time_of_request.hour\n            }\n        )\n        \n        await self.event_store.store(event)\n    \n    async def get_risk_indicators(self, user_id: str, time_window_hours: int = 24) -> Dict:\n        \"\"\"Analyze user behavior for risk indicators\"\"\"\n        events = await self.event_store.query(\n            user_id=user_id,\n            since=datetime.now() - timedelta(hours=time_window_hours)\n        )\n        \n        return {\n            \"total_attempts\": len(events),\n            \"failed_attempts\": len([e for e in events if e.decision == \"deny\"]),\n            \"high_risk_attempts\": len([e for e in events if e.risk_score > 0.7]),\n            \"unique_resources\": len(set(e.resource for e in events)),\n            \"unusual_hours\": len([e for e in events if e.timestamp.hour \u003C 6 or e.timestamp.hour > 22]),\n            \"unique_devices\": len(set(e.device_id for e in events))\n        }\n```\n\n-----\n\n## Best Practices Summary\n\n1. **Start with Identity** — Implement strong identity verification before addressing network security.\n\n2. **Deploy Gradually** — Phase in zero trust controls, starting with most critical assets.\n\n3. **Maintain Visibility** — Ensure comprehensive logging and monitoring across all components.\n\n4. **Automate Responses** — Build automated remediation for common compliance and security issues.\n\n5. **Focus on User Experience** — Balance security with usability to ensure adoption.\n\n6. **Continuous Improvement** — Regularly review and update policies based on threat intelligence.\n\n7. **Assume Breach Mentality** — Design for failure containment and rapid detection.\n",{"name":5,"license":15,"metadata":43,"description":48,"compatibility":28},{"tags":44,"audience":47,"category":37},[5,45,31,32,46],"microsegmentation","continuous-auth","security engineers","Expert guidance on implementing zero trust security architectures where no user, device,  or network segment is implicitly trusted. Use for continuous verification of identity,  device health, and context for every access request, microsegmentation of networks,  policy-based access control, and migrating from perimeter-based security to zero trust.\n","main","2ea764e153842704d24a2e9aa4170441a7f03081",".opencode\u002Fskills\u002Fcybersecurity\u002Fzero-trust","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito","https:\u002F\u002Fgithub.com\u002FNeuralBlitz","nuralnexus.org","Theoretical and Futuristic AI Nerd 🤓 ","2026-04-21 14:37:05",{"source":8,"skillName":5,"commands":58,"prompt":68,"zipAvailable":69},[59,62,65],{"tool":60,"command":61},"npx","npx skills add NeuralBlitz\u002FMito --skill zero-trust",{"tool":63,"command":64},"bunx","bunx skills add NeuralBlitz\u002FMito --skill zero-trust",{"tool":66,"command":67},"pnpm","pnpm dlx skills add NeuralBlitz\u002FMito --skill zero-trust","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fcybersecurity\u002Fzero-trust\u002FSKILL.md",true,[],[72,88,101,112,120,145],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":38},"01M6HAZSAQK1S27CEZYAYJTQDX","wireless-communications","Wireless systems, mobile networks, and 5G\u002F6G","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fwireless-communications\u002FSKILL.md",[],[79,80,81,82,83,84,85,86,28,87],"communications","wireless communications","wireless","systems","engineering","networks","5G","students","mobile",{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":38},"01M6HAZFX6E8NK3WZWDX5YCKYY","websockets","WebSocket implementation and best practices","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fwebassembly\u002Fwebsockets\u002FSKILL.md",[],[90,95,96,97,28,98,99,100],"websocket implementation","time","implementation","real-time","websocket","best practices",{"skillNo":102,"name":103,"nameZh":6,"description":104,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":105,"categories":106,"keywords":107,"publishedAt":38},"01M6HAZ6DAXBQ7QHXXM1EM7715","vulnerability-auditing","Vulnerability assessment and auditing","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fvulnerability-auditing\u002FSKILL.md",[],[108,109,30,110,28,37,111],"vulnerability","vulnerability auditing","vulnerability assessment","assessment",{"skillNo":113,"name":114,"nameZh":6,"description":115,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":116,"categories":117,"keywords":118,"publishedAt":38},"01M6HAZ3FKF3CS9Z3J96RVE2ZE","vulnerability-assessment","Finding and assessing security vulnerabilities","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fvue\u002Fvulnerability-assessment\u002FSKILL.md",[],[110,108,111,30,119,28],"vulnerabilities",{"skillNo":121,"name":122,"nameZh":6,"description":123,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":124,"categories":125,"keywords":136,"publishedAt":38},"01M6HAYSHM6HKRKEHFP0SGZQX7","vlsi-design","Very-Large-Scale Integration circuit design and semiconductor engineering","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fvlsi-design\u002FSKILL.md",[126,131],{"categoryNo":127,"categoryName":128,"taxonomyType":129,"taxonomyTypeDesc":130},"01JBSEEDCAT000000000000015","视觉设计","SCENARIO","使用场景",{"categoryNo":132,"categoryName":133,"taxonomyType":134,"taxonomyTypeDesc":135},"01JBSEEDCAT000000000000032","设计师","PROFESSION","适用职业",[137,138,139,140,141,83,142,28,143,86,144],"vlsi design","VLSI","design","hardware","integration","computer","scale","circuit",{"skillNo":146,"name":147,"nameZh":6,"description":148,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":149,"categories":150,"keywords":151,"publishedAt":38},"01M6HAYPQ30FFE2JXD7WQJ8R6C","unsupervised","Unsupervised learning concepts","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fvisualization\u002Funsupervised\u002FSKILL.md",[],[147,152,28,153,154,155,156,157],"learning","intelligence","unsupervised learning","machine","concepts","machine-learning"]