zero trust architecture

Configuring Microsegmentation for Zero Trust

Configure microsegmentation policies to enforce least-privilege workload-to-workload access using tools like VMware NSX, Illumio, and Calico, preventing lateral movement in zero trust architectures.

lateral-movementmicrosegmentationnetwork-accessnetwork-securityzero-trust
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

Prerequisites

  • Understanding of zero trust principles (NIST SP 800-207)
  • Knowledge of network segmentation concepts
  • Familiarity with firewall and SDN technologies
  • Experience with VMware NSX, Illumio, Guardicore, or Cisco ACI

Overview

Microsegmentation divides a network into granular security zones, enforcing least-privilege access between workloads at the application layer rather than relying on traditional VLAN-based segmentation. In a zero trust architecture, microsegmentation eliminates implicit trust between workloads within the same network segment, preventing lateral movement even after an attacker gains initial access.

This skill covers designing microsegmentation policies using workload identity, implementing host-based and network-based enforcement, and validating segmentation effectiveness with tools like Illumio Core and VMware NSX.

When to Use

  • When deploying or configuring configuring microsegmentation for zero trust 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

Microsegmentation Models

  1. Network-Based (VMware NSX, Cisco ACI): Distributed firewall rules enforced at the hypervisor or network fabric level
  2. Host-Based (Illumio, Guardicore): Agent-based enforcement at the OS level using iptables/WFP rules
  3. Container-Based (Calico, Cilium): Network policies enforced at the pod/container level in Kubernetes
  4. Application-Based (Zscaler Workload Segmentation): Identity-based segmentation based on software identity rather than IP addresses

Enforcement Points

Traditional Segmentation        Microsegmentation
┌─────────────────┐            ┌──────────────────────┐
│  VLAN 10        │            │  Workload A ←policy→ │
│  ┌───┐ ┌───┐   │            │  Workload B ←policy→ │
│  │ A │ │ B │   │            │  Workload C ←policy→ │
│  └───┘ └───┘   │            │  Workload D ←policy→ │
│  (trust each    │            │  (zero trust between  │
│   other)        │            │   every pair)         │
└─────────────────┘            └──────────────────────┘

Key Concepts

Application Dependency Mapping

Before creating segmentation policies, discover actual communication flows between workloads using traffic telemetry. Tools like Illumio, Guardicore, and AppDynamics provide application dependency maps showing which workloads communicate, over which ports, and how frequently.

Policy Modeling

Draft policies in monitor/visibility mode before enforcement. This allows validation that proposed rules will not break legitimate traffic while identifying unnecessary or risky communication paths.

Label-Based Policy

Modern microsegmentation uses labels (role, application, environment, location) instead of IP-based rules. Label-based policies are portable across environments and survive IP changes during migrations.

Ring-Fencing

Isolate critical applications (PCI cardholder data environment, SWIFT financial systems, healthcare PHI) with strict allow-list policies that deny all traffic not explicitly permitted.

Workflow

Phase 1: Discovery and Mapping

  1. Deploy Visibility Agents

    • Install lightweight agents on all workloads (servers, VMs, containers)
    • Configure agents to report real-time traffic telemetry to the management console
    • Allow 2-4 weeks of traffic collection to build a comprehensive flow map
  2. Build Application Dependency Map

    • Review auto-discovered communication flows in the management console
    • Identify application tiers: web servers, app servers, databases, middleware
    • Map legitimate communication paths and flag unexpected connections
    • Document data flows for compliance scope (PCI, HIPAA)
  3. Assign Labels

    • Create a labeling taxonomy: Role (web, app, db), Application (ERP, CRM), Environment (prod, dev, staging), Location (dc1, aws-east)
    • Apply labels to all workloads via the management console or API
    • Validate label accuracy against CMDB and application owner input

Phase 2: Policy Design

  1. Define Segmentation Zones

    • Environment isolation: Production cannot communicate with Development
    • Tier isolation: Database tier only accepts connections from application tier
    • Application ring-fencing: PCI applications isolated from non-PCI workloads
    • Administrative access: Jump servers are the only management path
  2. Create Allow-List Policies

    • For each application, define explicit allow rules for required communication
    • Use label-based rules rather than IP-based where possible
    • Include process-level restrictions where supported (e.g., only httpd on port 443)
    • Set default-deny for all unlisted communication
  3. Model Policies in Test Mode

    • Enable policies in visibility/test mode (do not enforce)
    • Monitor for would-be blocked legitimate traffic
    • Refine policies based on test results over 1-2 weeks
    • Get application owner sign-off before enforcement

Phase 3: Enforcement

  1. Enforce Incrementally

    • Start with the most isolated, lowest-risk application
    • Switch policy from test mode to enforce mode
    • Monitor for application issues in the first 24-48 hours
    • Proceed to next application after validation
  2. Validate Segmentation

    • Run penetration tests attempting lateral movement between segments
    • Verify that blocked traffic generates alerts in the management console
    • Test emergency override procedures (break-glass)
    • Document enforcement status for each application zone

Phase 4: Operational Maintenance

  1. Ongoing Policy Management
    • Integrate with CI/CD: auto-label new workloads from deployment pipelines
    • Review policy violations weekly and investigate anomalies
    • Update policies when applications change or new services deploy
    • Perform quarterly segmentation effectiveness reviews

Validation Checklist

  • Agents deployed on all in-scope workloads
  • Application dependency map reviewed and approved by app owners
  • Labels assigned and validated against CMDB
  • Policies modeled in test mode with no false positives for 2+ weeks
  • Policies enforced incrementally with monitoring
  • Default-deny active for all segmented zones
  • Lateral movement tests confirm blocked unauthorized traffic
  • Alerting configured for policy violations
  • Break-glass procedure documented and tested
  • Compliance auditor sign-off for regulated environments

References

  • NIST SP 800-207: Zero Trust Architecture
  • CISA Zero Trust Maturity Model v2.0 - Network Pillar
  • Illumio Core Administration Guide
  • VMware NSX Distributed Firewall Configuration Guide
  • Forrester Zero Trust eXtended (ZTX) Framework
Source materials

References and resources

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

References 3

api-reference.md1.4 KB

Microsegmentation for Zero Trust — API Reference

Libraries

Library Install Purpose
boto3 pip install boto3 AWS security group audit
requests pip install requests Illumio / Guardicore API client

Key boto3 EC2 Methods

Method Description
describe_security_groups() List SGs with inbound/outbound rules
authorize_security_group_ingress() Add inbound rule
revoke_security_group_ingress() Remove inbound rule

Illumio PCE API Endpoints

Method Endpoint Description
GET /api/v2/orgs/{id}/workloads List managed workloads
GET /api/v2/orgs/{id}/sec_policy/draft/rule_sets List rule sets
PUT /api/v2/orgs/{id}/workloads/{id} Update workload enforcement mode

Segmentation Enforcement Modes

Mode Description
Visibility Only Monitor traffic without blocking
Selective Block specific flows, allow rest
Full Deny all, allow by policy (zero trust)

External References

standards.md3.5 KB

Standards and Frameworks Reference

NIST SP 800-207: Zero Trust Architecture

Microsegmentation as ZTA Deployment Model

NIST SP 800-207 identifies microsegmentation as one of three primary deployment approaches for zero trust:

  • Places individual or groups of resources on a unique network segment protected by a gateway security component
  • The enterprise places infrastructure devices such as intelligent switches, next-generation firewalls, or special-purpose gateway devices to act as PEPs protecting each resource or group of resources
  • This approach can be implemented using software-defined networking (SDN) or hypervisor-level enforcement

Applicable Controls

  • AC-4 (Information Flow Enforcement): Microsegmentation enforces approved information flows between workloads
  • SC-7 (Boundary Protection): Each microsegment boundary acts as a security boundary
  • SI-4 (Information System Monitoring): Microsegmentation tools provide flow telemetry for monitoring

CISA Zero Trust Maturity Model v2.0

Network Pillar - Microsegmentation Maturity

Level Network Segmentation Microsegmentation Traffic Management
Traditional Large, macro-segmented perimeters None Static ACLs
Initial Defined architecture with some isolation Initial workload isolation Basic flow visibility
Advanced Ingress/egress micro-perimeters Workload-level microsegmentation Identity-based traffic rules
Optimal Full microsegmentation, dynamically defined Automated, adaptive policies ML-driven anomaly detection

Cross-Cutting: Visibility and Analytics

  • Flow telemetry from microsegmentation agents feeds into SIEM/SOAR
  • Application dependency maps provide baseline for anomaly detection
  • Policy violation alerts enable real-time incident detection

PCI DSS v4.0

Microsegmentation for Scope Reduction

  • Requirement 1.3: Network controls restrict access to and from the cardholder data environment (CDE)
  • Requirement 1.4: Network connections between trusted and untrusted networks are controlled
  • Microsegmentation can reduce PCI scope by isolating CDE workloads from non-CDE systems
  • Compensating control: host-based microsegmentation validated by QSA as equivalent to network segmentation

Forrester Zero Trust eXtended (ZTX) Framework

Workload Security Pillar

  • Microsegmentation is a core capability for securing workloads
  • Policies should be based on workload identity and context, not network location
  • Continuous monitoring of east-west traffic for anomaly detection
  • Integration with DevOps pipelines for automated policy management

VMware NSX Distributed Firewall

Architecture

  • Stateful Layer 4-7 firewall embedded in the hypervisor kernel
  • Policies evaluated at the vNIC level before traffic reaches the physical network
  • Context-aware rules using Active Directory groups, VM tags, and application identification
  • No network topology changes required for deployment

Illumio Core Platform

Architecture

  • Virtual Enforcement Node (VEN) agents installed on workloads
  • Policy Compute Engine (PCE) centralizes policy management and visualization
  • Enforcement via native OS firewall (iptables on Linux, WFP on Windows)
  • Label-based policy model: Role, Application, Environment, Location

Guardicore (Akamai)

Architecture

  • Lightweight agents provide process-level visibility and enforcement
  • Reveal module builds application dependency maps
  • Centra management platform for policy creation and monitoring
  • Supports bare-metal, VM, container, and cloud workloads
workflows.md6.9 KB

Microsegmentation Implementation Workflows

Workflow 1: Microsegmentation Deployment Lifecycle

┌──────────────────────┐
│ 1. Discovery          │
│ - Deploy agents       │
│ - Collect traffic     │
│   telemetry (2-4 wks)│
│ - Build flow map      │
└──────────┬───────────┘
           v
┌──────────────────────┐
│ 2. Classification     │
│ - Assign workload     │
│   labels (role, app,  │
│   env, location)      │
│ - Validate with CMDB  │
│ - Group by app tier   │
└──────────┬───────────┘
           v
┌──────────────────────┐
│ 3. Policy Design      │
│ - Define zones        │
│ - Create allow-list   │
│   rules per app       │
│ - Set default-deny    │
│ - Document exceptions │
└──────────┬───────────┘
           v
┌──────────────────────┐
│ 4. Test Mode          │
│ - Enable policies in  │
│   visibility mode     │
│ - Monitor would-block │
│   events (1-2 weeks)  │
│ - Refine rules        │
└──────────┬───────────┘
           v
┌──────────────────────┐
│ 5. Enforcement        │
│ - Enforce per-app,    │
│   starting low-risk   │
│ - Monitor 24-48 hrs   │
│ - Proceed to next app │
└──────────┬───────────┘
           v
┌──────────────────────┐
│ 6. Continuous Ops     │
│ - Weekly violation    │
│   review              │
│ - Quarterly audits    │
│ - CI/CD integration   │
│ - Incident response   │
└──────────────────────┘

Workflow 2: Policy Creation Flow

Identify Application

    v
┌─────────────────────┐
│ Map Dependencies     │
│ - Inbound sources    │
│ - Outbound targets   │
│ - Ports/protocols    │
│ - Process names      │
└──────────┬──────────┘
           v
┌─────────────────────┐
│ Define Labels        │
│ Role: web/app/db     │
│ App: erp/crm/hr      │
│ Env: prod/dev/stg    │
│ Loc: dc1/aws/azure   │
└──────────┬──────────┘
           v
┌─────────────────────┐
│ Create Rules         │
│ Allow: web→app:8080  │
│ Allow: app→db:3306   │
│ Allow: mon→all:9090  │
│ Deny: all other      │
└──────────┬──────────┘
           v
┌─────────────────────┐
│ Test and Validate    │
│ - Simulate in test   │
│ - Check flow map     │
│ - App owner sign-off │
└──────────┬──────────┘
           v
┌─────────────────────┐
│ Enforce and Monitor  │
│ - Switch to enforce  │
│ - Alert on violations│
│ - Log to SIEM        │
└─────────────────────┘

Workflow 3: Ring-Fencing Critical Assets

Identify Critical Asset (e.g., PCI CDE Database)

    v
┌──────────────────────────────────────┐
│ 1. Baseline Traffic                   │
│ - Observe all inbound/outbound flows │
│ - Document legitimate connections    │
│ - Identify unnecessary connections   │
└──────────────┬───────────────────────┘
               v
┌──────────────────────────────────────┐
│ 2. Define Ring-Fence Rules            │
│ - Allow: app-server → db:5432        │
│ - Allow: backup-agent → db:5432      │
│ - Allow: monitoring → db:9100        │
│ - Deny: ALL other inbound            │
│ - Deny: ALL outbound (except DNS,NTP)│
└──────────────┬───────────────────────┘
               v
┌──────────────────────────────────────┐
│ 3. Test with Production Traffic       │
│ - Enable in test mode                 │
│ - Verify zero false positives         │
│ - Validate backup and monitoring work │
└──────────────┬───────────────────────┘
               v
┌──────────────────────────────────────┐
│ 4. Enforce and Lock Down              │
│ - Switch to enforcement               │
│ - Enable alerting on any violation    │
│ - Review violations daily             │
│ - QSA validation for PCI scope       │
└──────────────────────────────────────┘

Workflow 4: Incident Response with Microsegmentation

Alert: Unusual East-West Traffic Detected

    v
┌─────────────────────────┐
│ 1. Investigate           │
│ - Review flow in console │
│ - Check source workload  │
│ - Identify destination   │
│ - Cross-ref with SIEM    │
└──────────┬──────────────┘
           v
┌──────────────────────────────┐
│ 2. Contain                    │
│ - Apply quarantine policy     │
│   (deny all except forensic) │
│ - Isolate compromised         │
│   workload instantly          │
└──────────┬───────────────────┘
           v
┌─────────────────────────┐
│ 3. Assess Impact         │
│ - Check if lateral move  │
│   was blocked by policy  │
│ - Review adjacent zones  │
│ - Determine blast radius │
└──────────┬──────────────┘
           v
┌─────────────────────────┐
│ 4. Remediate             │
│ - Patch/reimagevworkload │
│ - Strengthen policies    │
│ - Remove quarantine      │
│ - Post-incident review   │
└─────────────────────────┘

Scripts 2

agent.py5.0 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Microsegmentation audit agent for zero trust network enforcement."""

import json
import os
import sys
import argparse
from datetime import datetime

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


def audit_aws_security_groups(session):
    """Audit AWS security groups for microsegmentation compliance."""
    import boto3
    ec2 = session.client("ec2")
    findings = []
    for sg in ec2.describe_security_groups()["SecurityGroups"]:
        for rule in sg.get("IpPermissions", []):
            for ip_range in rule.get("IpRanges", []):
                cidr = ip_range.get("CidrIp", "")
                if cidr == "0.0.0.0/0":
                    findings.append({
                        "sg_id": sg["GroupId"],
                        "sg_name": sg.get("GroupName", ""),
                        "port": rule.get("FromPort", "all"),
                        "cidr": cidr,
                        "severity": "HIGH",
                        "recommendation": "Restrict to specific CIDR blocks",
                    })
                elif "/" in cidr:
                    prefix = int(cidr.split("/")[1])
                    if prefix < 24:
                        findings.append({
                            "sg_id": sg["GroupId"],
                            "sg_name": sg.get("GroupName", ""),
                            "port": rule.get("FromPort", "all"),
                            "cidr": cidr,
                            "severity": "MEDIUM",
                            "recommendation": f"Narrow CIDR from /{prefix} to /32 or workload-specific range",
                        })
    return findings


def check_illumio_workloads(base_url, api_key, org_id):
    """Check Illumio workload segmentation status."""
    headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
    try:
        resp = requests.get(f"{base_url}/api/v2/orgs/{org_id}/workloads",
                            headers=headers, verify=not os.environ.get("SKIP_TLS_VERIFY", "").lower() == "true", timeout=30)  # Set SKIP_TLS_VERIFY=true for self-signed certs in lab environments
        resp.raise_for_status()
        workloads = resp.json()
        return [{
            "hostname": w.get("hostname", ""),
            "enforcement_mode": w.get("enforcement_mode", ""),
            "visibility_level": w.get("visibility_level", ""),
            "online": w.get("online", False),
        } for w in workloads[:20]]
    except Exception as e:
        return [{"error": str(e)}]


def generate_segmentation_policy(app_tiers):
    """Generate microsegmentation policy recommendations."""
    policies = []
    for tier in app_tiers:
        policies.append({
            "tier": tier["name"],
            "allowed_inbound": tier.get("inbound_from", []),
            "allowed_ports": tier.get("ports", []),
            "deny_default": True,
            "enforcement": "block",
        })
    return {
        "principle": "Zero Trust — deny all, allow by exception",
        "policies": policies,
        "example_tiers": [
            {"name": "web", "inbound_from": ["load-balancer"], "ports": [443]},
            {"name": "app", "inbound_from": ["web"], "ports": [8080]},
            {"name": "db", "inbound_from": ["app"], "ports": [5432]},
        ],
    }


def run_audit(profile=None, region="us-east-1"):
    """Execute microsegmentation audit."""
    import boto3
    session = boto3.Session(profile_name=profile, region_name=region)
    print(f"\n{'='*60}")
    print(f"  MICROSEGMENTATION ZERO TRUST AUDIT")
    print(f"  Generated: {datetime.utcnow().isoformat()} UTC")
    print(f"{'='*60}\n")

    sg_findings = audit_aws_security_groups(session)
    print(f"--- SECURITY GROUP FINDINGS ({len(sg_findings)}) ---")
    for f in sg_findings[:15]:
        print(f"  [{f['severity']}] {f['sg_id']} ({f['sg_name']}): port {f['port']} from {f['cidr']}")

    policy = generate_segmentation_policy([])
    print(f"\n--- RECOMMENDED SEGMENTATION MODEL ---")
    print(f"  Principle: {policy['principle']}")
    for tier in policy["example_tiers"]:
        print(f"  {tier['name']}: allow from {tier['inbound_from']} on ports {tier['ports']}")

    return {"sg_findings": sg_findings, "policy": policy}


def main():
    parser = argparse.ArgumentParser(description="Microsegmentation Audit Agent")
    parser.add_argument("--profile", help="AWS CLI profile")
    parser.add_argument("--region", default="us-east-1", help="AWS region")
    parser.add_argument("--audit", action="store_true", help="Run audit")
    parser.add_argument("--output", help="Save report to JSON file")
    args = parser.parse_args()

    if args.audit:
        report = run_audit(args.profile, args.region)
        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}")
    else:
        parser.print_help()


if __name__ == "__main__":
    main()
process.py12.1 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""
Microsegmentation Policy Analyzer and Flow Validator

Analyzes network flow data to identify microsegmentation opportunities,
validates policies against observed traffic, and generates segmentation reports.
"""

import json
import csv
import sys
from collections import defaultdict
from datetime import datetime
from pathlib import Path
from typing import Optional


def parse_flow_data(flow_file: str) -> list:
    """Parse network flow data from CSV or JSON format."""
    flows = []
    path = Path(flow_file)
    if path.suffix == ".csv":
        with open(flow_file) as f:
            reader = csv.DictReader(f)
            for row in reader:
                flows.append({
                    "src_ip": row.get("src_ip", ""),
                    "dst_ip": row.get("dst_ip", ""),
                    "src_port": int(row.get("src_port", 0)),
                    "dst_port": int(row.get("dst_port", 0)),
                    "protocol": row.get("protocol", "tcp").lower(),
                    "bytes": int(row.get("bytes", 0)),
                    "packets": int(row.get("packets", 0)),
                    "timestamp": row.get("timestamp", ""),
                    "src_label": row.get("src_label", ""),
                    "dst_label": row.get("dst_label", ""),
                })
    elif path.suffix == ".json":
        with open(flow_file) as f:
            flows = json.load(f)
    return flows


def build_dependency_map(flows: list) -> dict:
    """Build an application dependency map from flow data."""
    dep_map = defaultdict(lambda: defaultdict(lambda: {
        "ports": set(), "protocols": set(), "total_bytes": 0,
        "total_packets": 0, "flow_count": 0
    }))

    for flow in flows:
        src = flow.get("src_label") or flow["src_ip"]
        dst = flow.get("dst_label") or flow["dst_ip"]
        port = flow["dst_port"]
        proto = flow["protocol"]

        dep_map[src][dst]["ports"].add(port)
        dep_map[src][dst]["protocols"].add(proto)
        dep_map[src][dst]["total_bytes"] += flow.get("bytes", 0)
        dep_map[src][dst]["total_packets"] += flow.get("packets", 0)
        dep_map[src][dst]["flow_count"] += 1

    serializable = {}
    for src, destinations in dep_map.items():
        serializable[src] = {}
        for dst, stats in destinations.items():
            serializable[src][dst] = {
                "ports": sorted(list(stats["ports"])),
                "protocols": sorted(list(stats["protocols"])),
                "total_bytes": stats["total_bytes"],
                "total_packets": stats["total_packets"],
                "flow_count": stats["flow_count"],
            }
    return serializable


def generate_segmentation_rules(dep_map: dict, default_action: str = "deny") -> list:
    """Generate microsegmentation rules from dependency map."""
    rules = []
    rule_id = 1

    for src, destinations in dep_map.items():
        for dst, stats in destinations.items():
            for port in stats["ports"]:
                for proto in stats["protocols"]:
                    rules.append({
                        "id": rule_id,
                        "action": "allow",
                        "src": src,
                        "dst": dst,
                        "port": port,
                        "protocol": proto,
                        "justification": f"Observed {stats['flow_count']} flows, {stats['total_bytes']} bytes",
                        "status": "proposed",
                    })
                    rule_id += 1

    rules.append({
        "id": rule_id,
        "action": default_action,
        "src": "any",
        "dst": "any",
        "port": "any",
        "protocol": "any",
        "justification": "Default deny - zero trust baseline",
        "status": "proposed",
    })
    return rules


def validate_policy_against_flows(policy_rules: list, flows: list) -> dict:
    """Validate segmentation policy against observed flows. Identify blocks and gaps."""
    results = {
        "allowed_flows": 0,
        "blocked_flows": 0,
        "unmatched_flows": 0,
        "blocked_details": [],
        "unmatched_details": [],
    }

    allow_rules = [r for r in policy_rules if r["action"] == "allow"]
    has_default_deny = any(
        r["action"] == "deny" and r.get("src") == "any" and r.get("dst") == "any"
        for r in policy_rules
    )

    for flow in flows:
        src = flow.get("src_label") or flow["src_ip"]
        dst = flow.get("dst_label") or flow["dst_ip"]
        port = flow["dst_port"]
        proto = flow["protocol"]

        matched = False
        for rule in allow_rules:
            src_match = rule["src"] in (src, "any")
            dst_match = rule["dst"] in (dst, "any")
            port_match = rule["port"] in (port, "any")
            proto_match = rule["protocol"] in (proto, "any")

            if src_match and dst_match and port_match and proto_match:
                results["allowed_flows"] += 1
                matched = True
                break

        if not matched:
            if has_default_deny:
                results["blocked_flows"] += 1
                results["blocked_details"].append({
                    "src": src, "dst": dst, "port": port, "protocol": proto,
                    "timestamp": flow.get("timestamp", ""),
                })
            else:
                results["unmatched_flows"] += 1
                results["unmatched_details"].append({
                    "src": src, "dst": dst, "port": port, "protocol": proto,
                })

    return results


def identify_segmentation_zones(flows: list, workload_labels: dict) -> dict:
    """Identify natural segmentation zones from flow patterns and labels."""
    zones = defaultdict(lambda: {"workloads": set(), "internal_flows": 0, "external_flows": 0})

    for flow in flows:
        src_ip = flow["src_ip"]
        dst_ip = flow["dst_ip"]

        src_zone = workload_labels.get(src_ip, {}).get("application", "unknown")
        dst_zone = workload_labels.get(dst_ip, {}).get("application", "unknown")

        zones[src_zone]["workloads"].add(src_ip)
        zones[dst_zone]["workloads"].add(dst_ip)

        if src_zone == dst_zone:
            zones[src_zone]["internal_flows"] += 1
        else:
            zones[src_zone]["external_flows"] += 1
            zones[dst_zone]["external_flows"] += 1

    serializable = {}
    for zone_name, stats in zones.items():
        serializable[zone_name] = {
            "workloads": sorted(list(stats["workloads"])),
            "workload_count": len(stats["workloads"]),
            "internal_flows": stats["internal_flows"],
            "external_flows": stats["external_flows"],
            "isolation_ratio": round(
                stats["internal_flows"] / max(stats["internal_flows"] + stats["external_flows"], 1),
                2
            ),
        }
    return serializable


def detect_anomalous_flows(flows: list, policy_rules: list) -> list:
    """Detect flows that violate segmentation policy and may indicate lateral movement."""
    anomalies = []
    allow_set = set()

    for rule in policy_rules:
        if rule["action"] == "allow":
            allow_set.add((rule["src"], rule["dst"], rule["port"], rule["protocol"]))

    for flow in flows:
        src = flow.get("src_label") or flow["src_ip"]
        dst = flow.get("dst_label") or flow["dst_ip"]
        port = flow["dst_port"]
        proto = flow["protocol"]

        is_allowed = (
            (src, dst, port, proto) in allow_set
            or ("any", dst, port, proto) in allow_set
            or (src, "any", port, proto) in allow_set
            or (src, dst, "any", proto) in allow_set
        )

        if not is_allowed:
            anomalies.append({
                "src": src,
                "dst": dst,
                "port": port,
                "protocol": proto,
                "bytes": flow.get("bytes", 0),
                "timestamp": flow.get("timestamp", ""),
                "severity": "high" if port in [22, 3389, 445, 135] else "medium",
                "reason": "Flow not covered by any allow rule",
            })

    return sorted(anomalies, key=lambda x: x["severity"])


def generate_segmentation_report(flows: list, policy_rules: list, workload_labels: dict) -> dict:
    """Generate comprehensive microsegmentation report."""
    dep_map = build_dependency_map(flows)
    zones = identify_segmentation_zones(flows, workload_labels)
    validation = validate_policy_against_flows(policy_rules, flows)
    anomalies = detect_anomalous_flows(flows, policy_rules)

    unique_sources = set(f.get("src_label") or f["src_ip"] for f in flows)
    unique_dests = set(f.get("dst_label") or f["dst_ip"] for f in flows)
    unique_ports = set(f["dst_port"] for f in flows)

    return {
        "generated": datetime.now().isoformat(),
        "summary": {
            "total_flows": len(flows),
            "unique_sources": len(unique_sources),
            "unique_destinations": len(unique_dests),
            "unique_ports": len(unique_ports),
            "segmentation_zones": len(zones),
            "policy_rules": len(policy_rules),
            "allowed_flows": validation["allowed_flows"],
            "blocked_flows": validation["blocked_flows"],
            "anomalies_detected": len(anomalies),
        },
        "zones": zones,
        "validation": validation,
        "anomalies": anomalies[:50],
        "dependency_map_summary": {
            src: len(dsts) for src, dsts in dep_map.items()
        },
    }


def main():
    import argparse

    parser = argparse.ArgumentParser(description="Microsegmentation Policy Analyzer")
    parser.add_argument("--flows", type=str, help="Path to flow data (CSV or JSON)")
    parser.add_argument("--policy", type=str, help="Path to policy rules JSON")
    parser.add_argument("--labels", type=str, help="Path to workload labels JSON")
    parser.add_argument("--action", choices=["map", "rules", "validate", "report", "anomalies"],
                        default="report", help="Action to perform")
    parser.add_argument("--output", type=str, default="segmentation_report.json", help="Output file")
    args = parser.parse_args()

    if not args.flows:
        parser.print_help()
        return

    flows = parse_flow_data(args.flows)
    print(f"Loaded {len(flows)} flows")

    policy_rules = []
    if args.policy:
        with open(args.policy) as f:
            policy_rules = json.load(f)

    workload_labels = {}
    if args.labels:
        with open(args.labels) as f:
            workload_labels = json.load(f)

    if args.action == "map":
        dep_map = build_dependency_map(flows)
        with open(args.output, "w") as f:
            json.dump(dep_map, f, indent=2)
        print(f"Dependency map: {len(dep_map)} sources mapped")

    elif args.action == "rules":
        dep_map = build_dependency_map(flows)
        rules = generate_segmentation_rules(dep_map)
        with open(args.output, "w") as f:
            json.dump(rules, f, indent=2)
        print(f"Generated {len(rules)} proposed rules")

    elif args.action == "validate":
        if not policy_rules:
            print("Error: --policy required for validation")
            return
        results = validate_policy_against_flows(policy_rules, flows)
        with open(args.output, "w") as f:
            json.dump(results, f, indent=2)
        print(f"Allowed: {results['allowed_flows']}, Blocked: {results['blocked_flows']}")

    elif args.action == "anomalies":
        if not policy_rules:
            print("Error: --policy required for anomaly detection")
            return
        anomalies = detect_anomalous_flows(flows, policy_rules)
        with open(args.output, "w") as f:
            json.dump(anomalies, f, indent=2)
        print(f"Detected {len(anomalies)} anomalous flows")

    elif args.action == "report":
        report = generate_segmentation_report(flows, policy_rules, workload_labels)
        with open(args.output, "w") as f:
            json.dump(report, f, indent=2)
        print(f"Report generated: {args.output}")
        print(f"  Zones: {report['summary']['segmentation_zones']}")
        print(f"  Anomalies: {report['summary']['anomalies_detected']}")

    print(f"Output saved to {args.output}")


if __name__ == "__main__":
    main()

Assets 1

template.mdtext/markdown · 2.4 KB
Keep exploring