zero trust architecture

Deploying Software-Defined Perimeter

Deploy a Software-Defined Perimeter using the CSA v2.0 specification with Single Packet Authorization, mutual TLS, and SDP controller/gateway configuration to enforce zero trust network access.

network-accesssdpsoftware-defined-perimeterzero-trustztna
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

Prerequisites

  • Understanding of zero trust principles (NIST SP 800-207)
  • Knowledge of CSA Software-Defined Perimeter specification
  • Familiarity with PKI and mutual TLS authentication
  • Experience with network security architecture

Overview

A Software-Defined Perimeter (SDP) implements zero trust by creating a dynamically provisioned, identity-centric perimeter around individual resources. Defined by the Cloud Security Alliance (CSA), SDP makes application infrastructure invisible to unauthorized users through a "dark cloud" approach where services are hidden until authenticated and authorized. Unlike traditional VPN, SDP establishes one-to-one encrypted connections between verified users and specific applications.

This skill covers deploying SDP using the CSA v2.0 specification, implementing Single Packet Authorization (SPA), configuring the SDP controller and gateway, and validating the deployment against NIST SP 800-207 requirements.

When to Use

  • When deploying or configuring deploying software defined perimeter capabilities in your environment
  • When establishing security controls aligned to compliance requirements
  • When building or improving security architecture for this domain
  • When conducting security assessments that require this implementation

Prerequisites

  • Familiarity with zero trust architecture concepts and tools
  • Access to a test or lab environment for safe execution
  • Python 3.8+ with required dependencies installed
  • Appropriate authorization for any testing activities

Architecture

SDP Components (CSA Specification)

┌─────────────────────┐
│ SDP Controller       │
│ - Authentication     │
│ - Authorization      │
│ - Policy management  │
│ - Key management     │
└──────────┬──────────┘

    ┌──────┴──────┐
    │             │
    v             v
┌────────┐  ┌────────────┐
│ IH     │  │ AH         │
│(Client)│  │(Gateway)   │
│        │  │            │
│ SPA    │──│ Protected  │
│ mTLS   │  │ Resources  │
└────────┘  └────────────┘
 
IH = Initiating Host (User Device)
AH = Accepting Host (Application Gateway)
SPA = Single Packet Authorization

SDP Deployment Models

  1. Client-to-Gateway: User device connects through SDP gateway to backend applications
  2. Client-to-Server: Direct connection between user and application server
  3. Server-to-Server: Workload-to-workload communication through SDP
  4. Gateway-to-Gateway: Site-to-site connectivity replacing traditional VPN tunnels

Key Concepts

Single Packet Authorization (SPA)

SPA is a network security mechanism where the SDP gateway drops all TCP/UDP packets by default. A cryptographically signed single packet must be sent before any connection is established. The gateway validates the SPA packet, and only then opens a temporary port for the authenticated session. This makes the gateway invisible to port scanners.

Mutual TLS (mTLS)

After SPA validation, both the client and server authenticate each other using X.509 certificates. This bidirectional authentication prevents man-in-the-middle attacks and ensures both endpoints are verified.

Dynamic Provisioning

SDP connections are provisioned on-demand based on real-time policy evaluation. No persistent network tunnels exist; each session is individually authorized and encrypted.

Workflow

Phase 1: SDP Controller Deployment

  1. Deploy SDP Controller

    • Install SDP controller on hardened, redundant infrastructure
    • Configure PKI integration for certificate issuance
    • Set up authentication backend (LDAP, SAML, OIDC)
    • Configure policy database with application definitions
    • Enable audit logging for all controller decisions
  2. Configure Authentication

    • Integrate with enterprise IdP via SAML 2.0 or OIDC
    • Configure device certificate enrollment (SCEP/EST)
    • Enable multi-factor authentication requirements
    • Set up certificate revocation checking (OCSP/CRL)
  3. Define Access Policies

    • Map users/groups to authorized applications
    • Define device posture requirements per application
    • Configure contextual conditions (location, time, risk level)
    • Set session duration and re-authentication intervals

Phase 2: SDP Gateway Deployment

  1. Deploy Accepting Hosts (Gateways)

    • Install SDP gateway instances in front of protected applications
    • Configure default-drop firewall rules (deny all inbound)
    • Enable SPA listener on designated ports
    • Configure mTLS with controller-issued certificates
    • Set up health monitoring and failover
  2. Configure Application Definitions

    • Register each protected application with the controller
    • Define backend server IPs, ports, and protocols
    • Configure load balancing for multi-instance applications
    • Set up application health checks

Phase 3: Client Deployment

  1. Deploy Initiating Hosts (Clients)

    • Install SDP client software on user endpoints
    • Enroll device certificates through automated provisioning
    • Configure SPA key material distribution
    • Test authentication flow: SPA → mTLS → application access
  2. Validate End-to-End Flow

    • Verify SPA packets are accepted by gateway
    • Confirm mTLS handshake succeeds with valid certificates
    • Test application access through the SDP tunnel
    • Verify unauthorized access is blocked (no SPA = invisible gateway)

Phase 4: Operational Validation

  1. Security Testing

    • Port scan the SDP gateway to confirm invisibility (all ports show filtered/closed)
    • Attempt connection without valid SPA (must fail silently)
    • Test with revoked client certificate (must be denied)
    • Attempt lateral movement from one authorized app to another unauthorized app
    • Validate audit trail completeness
  2. Monitoring and Maintenance

    • Configure SIEM integration for SDP controller and gateway logs
    • Set up alerting for failed SPA attempts and certificate errors
    • Establish certificate rotation schedule
    • Document incident response procedures for SDP events

Validation Checklist

  • SDP Controller deployed with HA and audit logging
  • IdP integration tested with SAML/OIDC and MFA
  • SDP Gateways deployed with default-drop firewall
  • SPA mechanism validated (gateway invisible to port scans)
  • mTLS established between clients and gateways
  • Access policies enforce least-privilege per user/app
  • Device certificate enrollment automated
  • Unauthorized access attempts blocked silently
  • Lateral movement between apps prevented
  • Logs streaming to SIEM with alerting configured
  • Certificate rotation and revocation procedures tested

References

  • CSA Software-Defined Perimeter Architecture Guide v3
  • CSA SDP Specification v2.0
  • NIST SP 800-207: Zero Trust Architecture
  • CISA Zero Trust Maturity Model v2.0
  • fwknop: Single Packet Authorization implementation
Source materials

References and resources

Everything below is rendered for inspection. Script files are read-only and never run.

References 3

api-reference.md1.8 KB

Software-Defined Perimeter — API Reference

Core SDP Concepts

Component Description
SDP Controller Central policy engine managing authentication and authorization
SDP Gateway Enforces access policies, terminates encrypted tunnels
SDP Client End-user agent performing Single Packet Authorization (SPA)
SPA (Single Packet Authorization) Cryptographic knock before TCP connection allowed

Appgate SDP Admin API

Method Endpoint Description
POST /admin/login Authenticate and get Bearer token
GET /admin/sites List configured sites
GET /admin/policies List access policies
GET /admin/entitlements List entitlements (resource access rules)
GET /admin/appliances List SDP gateways and controllers
GET /admin/identity-providers List identity providers
POST /admin/entitlements Create new entitlement

Dark Port Scanning

import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5)
result = sock.connect_ex((host, port))  # Non-zero = port dark (SDP enforced)

Mutual TLS Verification

import ssl
ctx = ssl.create_default_context()
ctx.load_cert_chain("client.crt", "client.key")
with ctx.wrap_socket(socket.socket(), server_hostname=host) as s:
    s.connect((host, 443))

SPA Packet Structure

Field Description
Random Data 16 bytes of random padding
Username SDP client identity
Timestamp Prevents replay attacks
HMAC SHA-256 authentication code

External References

standards.md2.8 KB

Standards and Frameworks Reference

CSA Software-Defined Perimeter Specification v2.0

Core Architecture

  • SDP Controller: Central policy and authentication authority
  • Initiating Host (IH): Client device requesting access
  • Accepting Host (AH): Gateway protecting backend resources
  • Single Packet Authorization (SPA): Pre-authentication mechanism making services invisible

SDP Workflow

  1. IH authenticates to SDP Controller
  2. Controller validates identity, device posture, and policy
  3. Controller instructs AH to accept connection from specific IH
  4. IH sends SPA packet to AH
  5. AH validates SPA and opens temporary port
  6. mTLS tunnel established between IH and AH
  7. Application traffic flows through encrypted tunnel

Deployment Models

Model Use Case Architecture
Client-to-Gateway Remote user access IH → AH Gateway → Backend servers
Client-to-Server Direct application access IH → AH (application server)
Server-to-Server Workload communication IH (server) → AH (server)
Gateway-to-Gateway Site-to-site connectivity AH₁ → Controller → AH₂

NIST SP 800-207: SDP as Zero Trust Deployment

SDP Mapping to NIST ZTA Components

NIST Component SDP Equivalent
Policy Engine (PE) SDP Controller policy evaluation
Policy Administrator (PA) SDP Controller session management
Policy Enforcement Point (PEP) SDP Gateway (Accepting Host)

NIST ZTA Tenets Addressed by SDP

  • All communication secured regardless of network location (mTLS tunnels)
  • Per-session access grants (dynamic SDP connections)
  • Dynamic policy evaluation (controller real-time decisions)
  • Asset integrity monitoring (device posture checks)

CISA Zero Trust Maturity Model v2.0

Network Pillar - SDP Alignment

Maturity SDP Capability
Traditional No SDP, perimeter-based VPN
Initial SDP for remote access, basic SPA
Advanced Full SDP with device posture, context-aware
Optimal Dynamic SDP with continuous verification, ML-driven

Single Packet Authorization (SPA) Technical Details

SPA Packet Structure

  • Encrypted with shared key or asymmetric cryptography
  • Contains: source IP, timestamp, HMAC, requested service
  • Single UDP packet (no TCP handshake visible)
  • Anti-replay protection via timestamp and sequence number

fwknop Implementation

  • Open-source SPA implementation
  • Supports AES-256 and GnuPG encryption
  • Integrates with iptables/nftables for firewall rule insertion
  • Temporary rule created for authenticated session only

mTLS Configuration Standards

Certificate Requirements

  • Minimum RSA 2048-bit or ECDSA P-256 keys
  • Short-lived certificates (24-72 hours) preferred
  • OCSP stapling for real-time revocation checking
  • Certificate pinning for additional security
workflows.md5.1 KB

SDP Deployment Workflows

Workflow 1: SDP Connection Establishment

┌────────────┐     ┌──────────────┐     ┌────────────┐
│ IH (Client) │     │ SDP Controller│     │ AH (Gateway)│
└──────┬─────┘     └──────┬───────┘     └──────┬─────┘
       │                   │                     │
       │ 1. Authenticate   │                     │
       │──────────────────>│                     │
       │                   │                     │
       │ 2. Validate ID,   │                     │
       │    device, policy │                     │
       │                   │                     │
       │ 3. Auth response  │                     │
       │<──────────────────│                     │
       │  (SPA key, AH IP) │                     │
       │                   │ 4. Notify AH to     │
       │                   │    expect IH        │
       │                   │────────────────────>│
       │                   │                     │
       │ 5. Send SPA packet│                     │
       │─────────────────────────────────────────>│
       │                   │                     │
       │                   │  6. Validate SPA    │
       │                   │     Open port       │
       │                   │                     │
       │ 7. mTLS handshake │                     │
       │<════════════════════════════════════════>│
       │                   │                     │
       │ 8. Application    │                     │
       │    traffic flows  │                     │
       │<═══════════════════════════════════════=>│

Workflow 2: SDP Deployment Lifecycle

Phase 1: Planning (Weeks 1-2)
├── Inventory protected applications
├── Map user-to-application access requirements
├── Design PKI infrastructure for mTLS
├── Select SDP solution (open-source or commercial)
└── Plan network architecture changes
 
Phase 2: Controller Setup (Weeks 3-4)
├── Deploy SDP controller with HA
├── Integrate with IdP (SAML/OIDC)
├── Configure PKI and certificate templates
├── Define application catalog and policies
└── Test controller authentication flow
 
Phase 3: Gateway Deployment (Weeks 5-6)
├── Deploy gateways in each app environment
├── Configure default-drop firewall rules
├── Enable SPA listeners
├── Register applications with controller
└── Verify gateway invisibility (port scan test)
 
Phase 4: Client Rollout (Weeks 7-10)
├── Package SDP client with certificates
├── Deploy to pilot user group
├── Validate end-to-end connectivity
├── Expand to all user groups
└── Decommission legacy VPN access
 
Phase 5: Operations (Ongoing)
├── Monitor SDP controller and gateway health
├── Rotate certificates on schedule
├── Review and update access policies
├── Conduct quarterly penetration tests
└── Update SDP components for security patches

Workflow 3: SPA Validation

Incoming Packet to Gateway

    v
┌─────────────────────┐
│ Is it a SPA packet?  │
│ (Check magic bytes)  │
└───┬──────────┬──────┘
    │          │
   YES        NO
    │          │
    v          v
┌──────────┐  ┌──────────┐
│ Decrypt  │  │ DROP     │
│ SPA data │  │ silently │
└────┬─────┘  └──────────┘
     v
┌─────────────────────┐
│ Validate timestamp   │
│ (within 60s window)  │
└───┬──────────┬──────┘
   VALID    EXPIRED
    │          │
    v          v
┌──────────┐  ┌──────────┐
│ Check    │  │ DROP +   │
│ HMAC     │  │ Log      │
└────┬─────┘  └──────────┘
     v
┌─────────────────────┐
│ Verify replay        │
│ (check sequence DB)  │
└───┬──────────┬──────┘
   NEW      REPLAY
    │          │
    v          v
┌──────────┐  ┌──────────┐
│ Open port │  │ DROP +   │
│ for src IP│  │ Alert    │
│ (30s TTL) │  └──────────┘
└──────────┘

Scripts 2

agent.py6.6 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Software-Defined Perimeter (SDP) deployment audit agent."""

import json
import sys
import argparse
import socket
import ssl
from datetime import datetime

try:
    import requests
except ImportError:
    print("Install: pip install requests")
    sys.exit(1)


def check_spa_port(host, port, timeout=5):
    """Check if a port responds to standard TCP connect (should be dark in SDP)."""
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(timeout)
        result = sock.connect_ex((host, port))
        sock.close()
        return {"host": host, "port": port, "open": result == 0}
    except socket.error as e:
        return {"host": host, "port": port, "open": False, "error": str(e)}


def audit_dark_ports(host, ports):
    """Verify SDP ports are invisible to unauthorized scanners."""
    results = []
    for port in ports:
        scan = check_spa_port(host, port)
        if scan.get("open"):
            scan["finding"] = "Port visible without SPA — SDP not enforced"
            scan["severity"] = "HIGH"
        else:
            scan["finding"] = "Port dark — SDP enforced"
            scan["severity"] = "INFO"
        results.append(scan)
    return results


def check_tls_mutual_auth(host, port, client_cert=None, client_key=None):
    """Verify mutual TLS authentication on SDP controller."""
    result = {"host": host, "port": port}
    try:
        ctx = ssl.create_default_context()
        if client_cert and client_key:
            ctx.load_cert_chain(client_cert, client_key)
        with ctx.wrap_socket(socket.socket(), server_hostname=host) as s:
            s.settimeout(10)
            s.connect((host, port))
            cert = s.getpeercert()
            result["tls_version"] = s.version()
            result["cipher"] = s.cipher()[0]
            result["server_cn"] = dict(x[0] for x in cert.get("subject", ()))
            result["mtls_enforced"] = client_cert is not None
    except ssl.SSLError as e:
        result["error"] = str(e)
        if "CERTIFICATE_REQUIRED" in str(e):
            result["mtls_enforced"] = True
            result["finding"] = "Server requires client certificate — mTLS enforced"
    except Exception as e:
        result["error"] = str(e)
    return result


class SDPControllerClient:
    """Client for SDP controller REST API (e.g., Appgate SDP)."""

    def __init__(self, controller_url, username, password):
        self.base_url = controller_url.rstrip("/")
        self.session = requests.Session()
        self._authenticate(username, password)

    def _authenticate(self, username, password):
        resp = self.session.post(f"{self.base_url}/admin/login", json={
            "providerName": "local",
            "username": username,
            "password": password,
        }, timeout=15, verify=True)
        resp.raise_for_status()
        token = resp.json().get("token", "")
        self.session.headers.update({"Authorization": f"Bearer {token}"})

    def list_sites(self):
        resp = self.session.get(f"{self.base_url}/admin/sites", timeout=15)
        resp.raise_for_status()
        return resp.json().get("data", [])

    def list_policies(self):
        resp = self.session.get(f"{self.base_url}/admin/policies", timeout=15)
        resp.raise_for_status()
        return resp.json().get("data", [])

    def list_entitlements(self):
        resp = self.session.get(f"{self.base_url}/admin/entitlements", timeout=15)
        resp.raise_for_status()
        return resp.json().get("data", [])

    def list_appliances(self):
        resp = self.session.get(f"{self.base_url}/admin/appliances", timeout=15)
        resp.raise_for_status()
        return resp.json().get("data", [])


def run_audit(args):
    """Execute SDP deployment audit."""
    print(f"\n{'='*60}")
    print(f"  SOFTWARE-DEFINED PERIMETER AUDIT")
    print(f"  Generated: {datetime.utcnow().isoformat()} UTC")
    print(f"{'='*60}\n")

    report = {}

    if args.scan_host:
        ports = [int(p) for p in args.ports.split(",")] if args.ports else [22, 443, 8443, 3389]
        dark_results = audit_dark_ports(args.scan_host, ports)
        report["dark_port_scan"] = dark_results
        print(f"--- DARK PORT SCAN ({args.scan_host}) ---")
        for r in dark_results:
            status = "OPEN" if r["open"] else "DARK"
            print(f"  Port {r['port']}: {status}{r['finding']}")

    if args.mtls_host:
        mtls = check_tls_mutual_auth(args.mtls_host, args.mtls_port or 443,
                                      args.client_cert, args.client_key)
        report["mtls_check"] = mtls
        print(f"\n--- MUTUAL TLS CHECK ---")
        print(f"  Host: {mtls['host']}:{mtls['port']}")
        print(f"  mTLS Enforced: {mtls.get('mtls_enforced', 'unknown')}")
        if mtls.get("tls_version"):
            print(f"  TLS Version: {mtls['tls_version']}")

    if args.controller_url and args.username and args.password:
        client = SDPControllerClient(args.controller_url, args.username, args.password)
        appliances = client.list_appliances()
        report["appliances"] = len(appliances)
        print(f"\n--- SDP APPLIANCES ({len(appliances)}) ---")
        for a in appliances[:10]:
            print(f"  {a.get('name', '')}: {a.get('function', '')} ({a.get('state', '')})")

        entitlements = client.list_entitlements()
        report["entitlements"] = len(entitlements)
        print(f"\n--- ENTITLEMENTS ({len(entitlements)}) ---")
        for e in entitlements[:10]:
            print(f"  {e.get('name', '')}: {e.get('site', '')} -> {e.get('actions', [])}")

    return report


def main():
    parser = argparse.ArgumentParser(description="SDP Deployment Audit")
    parser.add_argument("--scan-host", help="Host to scan for dark ports")
    parser.add_argument("--ports", help="Comma-separated ports to scan (default: 22,443,8443,3389)")
    parser.add_argument("--mtls-host", help="Host to check mutual TLS")
    parser.add_argument("--mtls-port", type=int, default=443, help="mTLS port")
    parser.add_argument("--client-cert", help="Client certificate for mTLS test")
    parser.add_argument("--client-key", help="Client key for mTLS test")
    parser.add_argument("--controller-url", help="SDP controller URL (Appgate)")
    parser.add_argument("--username", help="Controller admin username")
    parser.add_argument("--password", help="Controller admin password")
    parser.add_argument("--output", help="Save report to JSON file")
    args = parser.parse_args()

    report = run_audit(args)
    if args.output:
        with open(args.output, "w") as f:
            json.dump(report, f, indent=2, default=str)
        print(f"\n[+] Report saved to {args.output}")


if __name__ == "__main__":
    main()
process.py10.2 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""
Software-Defined Perimeter Deployment Validator

Validates SDP deployment readiness, tests SPA mechanisms,
verifies gateway invisibility, and generates deployment reports.
"""

import json
import socket
import hashlib
import hmac
import struct
import time
import ssl
import subprocess
import sys
from datetime import datetime
from pathlib import Path
from typing import Optional


def check_gateway_invisibility(host: str, port_range: tuple = (1, 1024), timeout: float = 0.5) -> dict:
    """Scan gateway ports to verify SDP invisibility (all ports should appear closed/filtered)."""
    result = {
        "host": host,
        "scanned_range": f"{port_range[0]}-{port_range[1]}",
        "open_ports": [],
        "closed_ports": 0,
        "filtered_ports": 0,
        "invisible": True,
        "timestamp": datetime.now().isoformat(),
    }

    for port in range(port_range[0], port_range[1] + 1):
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(timeout)
            conn_result = sock.connect_ex((host, port))
            if conn_result == 0:
                result["open_ports"].append(port)
                result["invisible"] = False
            else:
                result["filtered_ports"] += 1
            sock.close()
        except socket.timeout:
            result["filtered_ports"] += 1
        except OSError:
            result["closed_ports"] += 1

    return result


def generate_spa_packet(
    source_ip: str,
    destination_service: str,
    shared_key: str,
    timestamp: Optional[float] = None
) -> bytes:
    """Generate a Single Packet Authorization payload (demonstration)."""
    if timestamp is None:
        timestamp = time.time()

    payload = json.dumps({
        "version": 2,
        "source_ip": source_ip,
        "service": destination_service,
        "timestamp": timestamp,
        "nonce": hashlib.sha256(f"{time.time()}{source_ip}".encode()).hexdigest()[:16],
    }).encode()

    mac = hmac.new(shared_key.encode(), payload, hashlib.sha256).digest()
    packet = struct.pack("!I", len(payload)) + payload + mac

    return packet


def validate_spa_packet(packet: bytes, shared_key: str, max_age_seconds: int = 60) -> dict:
    """Validate a received SPA packet."""
    result = {"valid": False, "errors": [], "payload": None}

    try:
        payload_len = struct.unpack("!I", packet[:4])[0]
        payload = packet[4:4 + payload_len]
        received_mac = packet[4 + payload_len:]

        expected_mac = hmac.new(shared_key.encode(), payload, hashlib.sha256).digest()
        if not hmac.compare_digest(received_mac, expected_mac):
            result["errors"].append("HMAC verification failed")
            return result

        data = json.loads(payload.decode())
        result["payload"] = data

        age = time.time() - data.get("timestamp", 0)
        if age > max_age_seconds:
            result["errors"].append(f"Packet expired ({age:.0f}s old, max {max_age_seconds}s)")
            return result

        if age < -5:
            result["errors"].append("Packet timestamp is in the future")
            return result

        result["valid"] = True

    except (struct.error, json.JSONDecodeError, KeyError) as e:
        result["errors"].append(f"Packet parse error: {str(e)}")

    return result


def validate_mtls_certificate(host: str, port: int, ca_cert_path: Optional[str] = None) -> dict:
    """Validate mTLS certificate configuration on SDP gateway."""
    result = {
        "host": host,
        "port": port,
        "tls_configured": False,
        "certificate": None,
        "errors": [],
    }

    try:
        context = ssl.create_default_context()
        if ca_cert_path:
            context.load_verify_locations(ca_cert_path)

        with socket.create_connection((host, port), timeout=10) as sock:
            with context.wrap_socket(sock, server_hostname=host) as ssock:
                cert = ssock.getpeercert()
                result["tls_configured"] = True
                result["certificate"] = {
                    "subject": dict(x[0] for x in cert.get("subject", [])),
                    "issuer": dict(x[0] for x in cert.get("issuer", [])),
                    "version": cert.get("version"),
                    "not_before": cert.get("notBefore"),
                    "not_after": cert.get("notAfter"),
                    "serial": cert.get("serialNumber"),
                }

                not_after = cert.get("notAfter", "")
                if not_after:
                    expiry = datetime.strptime(not_after, "%b %d %H:%M:%S %Y %Z")
                    days_remaining = (expiry - datetime.utcnow()).days
                    result["certificate"]["days_remaining"] = days_remaining
                    if days_remaining < 30:
                        result["errors"].append(f"Certificate expires in {days_remaining} days")

    except ssl.SSLError as e:
        result["errors"].append(f"SSL error: {str(e)}")
    except Exception as e:
        result["errors"].append(f"Connection error: {str(e)}")

    return result


def validate_sdp_config(config: dict) -> dict:
    """Validate SDP deployment configuration."""
    findings = []
    score = 100

    controller = config.get("controller", {})
    if not controller.get("ha_enabled"):
        findings.append({"severity": "high", "finding": "Controller HA not enabled"})
        score -= 15

    if not controller.get("idp_integration"):
        findings.append({"severity": "critical", "finding": "No IdP integration configured"})
        score -= 25

    if not controller.get("audit_logging"):
        findings.append({"severity": "high", "finding": "Audit logging not enabled on controller"})
        score -= 10

    gateways = config.get("gateways", [])
    if not gateways:
        findings.append({"severity": "critical", "finding": "No SDP gateways deployed"})
        score -= 25
    for gw in gateways:
        if not gw.get("default_drop"):
            findings.append({"severity": "critical", "finding": f"Gateway {gw.get('name')}: default-drop not enabled"})
            score -= 20
        if not gw.get("spa_enabled"):
            findings.append({"severity": "critical", "finding": f"Gateway {gw.get('name')}: SPA not enabled"})
            score -= 15
        if not gw.get("mtls_enabled"):
            findings.append({"severity": "high", "finding": f"Gateway {gw.get('name')}: mTLS not configured"})
            score -= 10

    pki = config.get("pki", {})
    cert_lifetime_hours = pki.get("client_cert_lifetime_hours", 8760)
    if cert_lifetime_hours > 72:
        findings.append({
            "severity": "warning",
            "finding": f"Client certificate lifetime is {cert_lifetime_hours}h (recommend <=72h for zero trust)"
        })
        score -= 5

    if not pki.get("ocsp_enabled") and not pki.get("crl_enabled"):
        findings.append({"severity": "high", "finding": "No certificate revocation checking enabled"})
        score -= 10

    monitoring = config.get("monitoring", {})
    if not monitoring.get("siem_integration"):
        findings.append({"severity": "warning", "finding": "No SIEM integration for SDP events"})
        score -= 5

    return {
        "score": max(score, 0),
        "findings": findings,
        "status": "ready" if score >= 80 else "needs_work" if score >= 50 else "not_ready",
        "timestamp": datetime.now().isoformat(),
    }


def generate_sdp_deployment_report(config: dict) -> dict:
    """Generate comprehensive SDP deployment report."""
    validation = validate_sdp_config(config)

    applications = config.get("applications", [])
    users = config.get("authorized_users", [])

    return {
        "generated": datetime.now().isoformat(),
        "deployment_status": validation["status"],
        "security_score": validation["score"],
        "findings": validation["findings"],
        "summary": {
            "controller_ha": config.get("controller", {}).get("ha_enabled", False),
            "gateways_deployed": len(config.get("gateways", [])),
            "applications_protected": len(applications),
            "authorized_users": len(users),
            "spa_enabled": all(g.get("spa_enabled") for g in config.get("gateways", [])),
            "mtls_enabled": all(g.get("mtls_enabled") for g in config.get("gateways", [])),
        },
        "recommendations": [f["finding"] for f in validation["findings"] if f["severity"] in ("critical", "high")],
    }


def main():
    import argparse
    parser = argparse.ArgumentParser(description="SDP Deployment Validator")
    parser.add_argument("--config", type=str, help="Path to SDP configuration JSON")
    parser.add_argument("--scan", type=str, help="Gateway host to scan for invisibility")
    parser.add_argument("--scan-ports", type=str, default="1-1024", help="Port range to scan")
    parser.add_argument("--check-tls", type=str, help="Host:port to check TLS certificate")
    parser.add_argument("--output", type=str, default="sdp_report.json")
    args = parser.parse_args()

    if args.config:
        with open(args.config) as f:
            config = json.load(f)
        report = generate_sdp_deployment_report(config)
        with open(args.output, "w") as f:
            json.dump(report, f, indent=2)
        print(f"SDP Status: {report['deployment_status']} (Score: {report['security_score']})")
        for r in report["recommendations"]:
            print(f"  - {r}")

    elif args.scan:
        start, end = args.scan_ports.split("-")
        result = check_gateway_invisibility(args.scan, (int(start), int(end)))
        with open(args.output, "w") as f:
            json.dump(result, f, indent=2)
        status = "INVISIBLE" if result["invisible"] else "EXPOSED"
        print(f"Gateway {args.scan}: {status}")
        if result["open_ports"]:
            print(f"  Open ports: {result['open_ports']}")

    elif args.check_tls:
        parts = args.check_tls.split(":")
        host = parts[0]
        port = int(parts[1]) if len(parts) > 1 else 443
        result = validate_mtls_certificate(host, port)
        with open(args.output, "w") as f:
            json.dump(result, f, indent=2)
        print(f"TLS on {host}:{port}: {'configured' if result['tls_configured'] else 'not configured'}")

    else:
        parser.print_help()


if __name__ == "__main__":
    main()

Assets 1

template.mdtext/markdown · 1.5 KB
Keep exploring