network security

Implementing Network Segmentation with Firewall Zones

Design and implement network segmentation using firewall security zones, VLANs, ACLs, and microsegmentation policies to restrict lateral movement and enforce least-privilege network access.

acleast-west-trafficfirewall-zoneslateral-movementmicrosegmentationnetwork-segmentationpci-dssvlan
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

Overview

Network segmentation divides a flat network into isolated security zones with firewall-enforced boundaries to contain breaches, restrict lateral movement, and enforce least-privilege access between workloads. Segmentation is a foundational control required by PCI DSS, HIPAA, NIST 800-53, and zero trust architectures. Modern segmentation combines traditional VLAN-based approaches with microsegmentation at the workload level for granular east-west traffic control. This skill covers designing zone architectures, configuring inter-zone firewall policies, implementing VLAN segmentation on switches, and deploying microsegmentation for dynamic environments.

When to Use

  • When deploying or configuring implementing network segmentation with firewall zones 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

  • Network topology documentation with asset inventory
  • Firewall supporting zone-based policies (Palo Alto, Fortinet, Cisco Firepower)
  • Managed switches with VLAN support (802.1Q trunking)
  • Traffic flow documentation or NetFlow data for baseline analysis
  • Compliance requirements (PCI DSS scope, HIPAA ePHI boundaries)

Core Concepts

Zone Architecture Tiers

Zone Trust Level Examples Access Policy
Internet None Public internet Default deny inbound
DMZ Low Web servers, mail relays, DNS Limited inbound, restricted outbound
Guest Low Guest WiFi, visitor network Internet only, no internal access
Corporate Medium Employee workstations, printers Controlled access to internal resources
Server/Data Center High Application servers, databases Strict ACLs, limited admin access
PCI CDE Critical Payment systems, card data PCI DSS compliant isolation
Management Critical Network devices, hypervisors, IPMI Highly restricted, jump box only
OT/SCADA Critical Industrial control systems Air-gapped or strictly firewalled

Segmentation Approaches

Approach Scope Granularity Use Case
VLAN Segmentation Layer 2 Subnet-level Department separation, guest isolation
Firewall Zones Layer 3-7 Zone-to-zone Inter-zone policy enforcement
ACLs on Routers Layer 3-4 Subnet/port Quick filtering at routing boundaries
Microsegmentation Layer 3-7 Workload-level Zero trust, container environments
SGT/TrustSec Layer 2-7 Tag-based Identity-based segmentation

Workflow

Step 1: Map Traffic Flows and Define Zones

Before implementing segmentation, capture baseline traffic:

# Capture NetFlow data to understand existing traffic patterns
nfdump -R /var/cache/nfdump/ -s srcip/bytes -n 50
 
# Identify east-west traffic between subnets
nfdump -R /var/cache/nfdump/ -s record/bytes \
  'src net 10.0.0.0/8 and dst net 10.0.0.0/8' -n 100
 
# Map application dependencies
# Document which servers need to communicate with which other servers

Step 2: Configure VLANs on Switches

! Core switch VLAN configuration
vlan 10
 name Management
vlan 20
 name Corporate-Users
vlan 30
 name Servers
vlan 40
 name PCI-CDE
vlan 50
 name Guest
vlan 60
 name DMZ
vlan 99
 name Native-Unused
 
! Trunk port to firewall
interface GigabitEthernet1/0/1
 description Trunk-to-Firewall
 switchport trunk encapsulation dot1q
 switchport mode trunk
 switchport trunk allowed vlan 10,20,30,40,50,60
 switchport trunk native vlan 99
 switchport nonegotiate
 
! Access port for corporate users
interface range GigabitEthernet1/0/2-24
 switchport mode access
 switchport access vlan 20
 spanning-tree portfast
 
! Access port for servers
interface range GigabitEthernet1/0/25-36
 switchport mode access
 switchport access vlan 30
 
! Prevent VLAN hopping
interface range GigabitEthernet1/0/37-48
 switchport mode access
 switchport access vlan 99
 shutdown

Step 3: Configure Firewall Zone Policies

Palo Alto zone-based policy:

# Define zones on firewall sub-interfaces
set network interface ethernet ethernet1/1 layer3 units ethernet1/1.10 tag 10 ip 10.0.10.1/24
set network interface ethernet ethernet1/1 layer3 units ethernet1/1.20 tag 20 ip 10.0.20.1/24
set network interface ethernet ethernet1/1 layer3 units ethernet1/1.30 tag 30 ip 10.0.30.1/24
set network interface ethernet ethernet1/1 layer3 units ethernet1/1.40 tag 40 ip 10.0.40.1/24
 
set zone Management network layer3 ethernet1/1.10
set zone Corporate network layer3 ethernet1/1.20
set zone Servers network layer3 ethernet1/1.30
set zone PCI-CDE network layer3 ethernet1/1.40
 
# Inter-zone policies (deny by default, explicitly allow)
 
# Corporate -> Servers (only specific apps)
set rulebase security rules Corp-to-Servers from Corporate to Servers
set rulebase security rules Corp-to-Servers application [ web-browsing ssl dns smtp ]
set rulebase security rules Corp-to-Servers action allow
set rulebase security rules Corp-to-Servers profile-setting group Standard-Profiles
 
# Corporate -> PCI (DENY)
set rulebase security rules Corp-to-PCI from Corporate to PCI-CDE
set rulebase security rules Corp-to-PCI action deny log-end yes
 
# Servers -> PCI (only payment processing)
set rulebase security rules Servers-to-PCI from Servers to PCI-CDE
set rulebase security rules Servers-to-PCI source [ 10.0.30.10 ]
set rulebase security rules Servers-to-PCI destination [ 10.0.40.10 ]
set rulebase security rules Servers-to-PCI application [ ssl ]
set rulebase security rules Servers-to-PCI service service-https
set rulebase security rules Servers-to-PCI action allow
 
# Management -> All (admin access via jump box)
set rulebase security rules Mgmt-Admin from Management to [ Servers PCI-CDE ]
set rulebase security rules Mgmt-Admin source [ 10.0.10.50 ]
set rulebase security rules Mgmt-Admin application [ ssh rdp ]
set rulebase security rules Mgmt-Admin source-user [ admin-group ]
set rulebase security rules Mgmt-Admin action allow
 
# Intra-zone deny (prevent lateral movement within zone)
set rulebase security rules Deny-Intrazone from Corporate to Corporate
set rulebase security rules Deny-Intrazone action deny log-end yes
 
# Default deny all
set rulebase security rules Deny-All from any to any
set rulebase security rules Deny-All action deny log-end yes

Step 4: Implement Inter-VLAN Routing ACLs

For additional layer 3 filtering on the router/L3 switch:

! ACL: Corporate can only reach specific server ports
ip access-list extended CORP-TO-SERVERS
 permit tcp 10.0.20.0 0.0.0.255 10.0.30.0 0.0.0.255 eq 80
 permit tcp 10.0.20.0 0.0.0.255 10.0.30.0 0.0.0.255 eq 443
 permit tcp 10.0.20.0 0.0.0.255 10.0.30.0 0.0.0.255 eq 25
 permit udp 10.0.20.0 0.0.0.255 10.0.30.10 0.0.0.0 eq 53
 deny ip 10.0.20.0 0.0.0.255 10.0.30.0 0.0.0.255 log
 
! ACL: PCI CDE isolation
ip access-list extended PCI-ISOLATION
 permit tcp host 10.0.30.10 host 10.0.40.10 eq 443
 permit tcp 10.0.10.50 0.0.0.0 10.0.40.0 0.0.0.255 eq 22
 deny ip any 10.0.40.0 0.0.0.255 log
 
! Apply ACLs to VLAN interfaces
interface Vlan20
 ip address 10.0.20.1 255.255.255.0
 ip access-group CORP-TO-SERVERS out
 
interface Vlan40
 ip address 10.0.40.1 255.255.255.0
 ip access-group PCI-ISOLATION in

Step 5: Validate Segmentation

#!/usr/bin/env python3
"""Network segmentation validation - tests connectivity between zones."""
 
import subprocess
import sys
import json
from datetime import datetime
 
 
class SegmentationValidator:
    """Test network segmentation controls between zones."""
 
    def __init__(self):
        self.results = []
 
    def test_connectivity(self, src_desc: str, dst_ip: str, port: int,
                          protocol: str = "tcp", expected: str = "blocked"):
        """Test if connectivity exists between source and destination."""
        try:
            if protocol == "tcp":
                cmd = ["nc", "-z", "-w", "3", dst_ip, str(port)]
            elif protocol == "udp":
                cmd = ["nc", "-z", "-u", "-w", "3", dst_ip, str(port)]
            elif protocol == "icmp":
                cmd = ["ping", "-c", "1", "-W", "3", dst_ip]
            else:
                return
 
            result = subprocess.run(cmd, capture_output=True, timeout=5)
            actual = "open" if result.returncode == 0 else "blocked"
 
        except subprocess.TimeoutExpired:
            actual = "blocked"
        except FileNotFoundError:
            actual = "error"
 
        status = "PASS" if actual == expected else "FAIL"
 
        self.results.append({
            "source": src_desc,
            "destination": f"{dst_ip}:{port}/{protocol}",
            "expected": expected,
            "actual": actual,
            "status": status,
        })
 
        symbol = "[+]" if status == "PASS" else "[!]"
        print(f"  {symbol} {src_desc} -> {dst_ip}:{port}/{protocol} "
              f"| Expected: {expected} | Actual: {actual} | {status}")
 
    def run_validation(self):
        """Run segmentation validation tests."""
        print(f"\n{'='*70}")
        print("NETWORK SEGMENTATION VALIDATION")
        print(f"{'='*70}")
        print(f"Date: {datetime.now().isoformat()}\n")
 
        # Tests that SHOULD be blocked
        print("[*] Testing controls that should BLOCK traffic:")
        self.test_connectivity("Corporate", "10.0.40.10", 443, "tcp", "blocked")
        self.test_connectivity("Corporate", "10.0.40.10", 22, "tcp", "blocked")
        self.test_connectivity("Guest", "10.0.30.10", 80, "tcp", "blocked")
        self.test_connectivity("Guest", "10.0.20.1", 0, "icmp", "blocked")
 
        # Tests that SHOULD be allowed
        print("\n[*] Testing controls that should ALLOW traffic:")
        self.test_connectivity("Corporate", "10.0.30.10", 443, "tcp", "open")
        self.test_connectivity("Corporate", "10.0.30.10", 80, "tcp", "open")
        self.test_connectivity("Management", "10.0.30.10", 22, "tcp", "open")
 
        # Summary
        passed = sum(1 for r in self.results if r["status"] == "PASS")
        failed = sum(1 for r in self.results if r["status"] == "FAIL")
        print(f"\n{'='*70}")
        print(f"Results: {passed} PASSED, {failed} FAILED out of {len(self.results)} tests")
 
        if failed > 0:
            print(f"\n[!] FAILED TESTS:")
            for r in self.results:
                if r["status"] == "FAIL":
                    print(f"  - {r['source']} -> {r['destination']}: "
                          f"expected {r['expected']}, got {r['actual']}")
 
        # Save report
        report = {
            "date": datetime.now().isoformat(),
            "total_tests": len(self.results),
            "passed": passed,
            "failed": failed,
            "results": self.results,
        }
        report_path = f"segmentation_test_{datetime.now().strftime('%Y%m%d')}.json"
        with open(report_path, 'w') as f:
            json.dump(report, f, indent=2)
        print(f"\nReport saved to: {report_path}")
 
 
if __name__ == "__main__":
    validator = SegmentationValidator()
    validator.run_validation()

Best Practices

  • Default Deny - Start with deny-all inter-zone rules and explicitly allow required traffic
  • Document Flows - Map all legitimate traffic flows before implementing restrictions
  • Segment by Sensitivity - Group assets by data classification and compliance scope
  • Intra-Zone Control - Block lateral movement within zones, not just between zones
  • Limit Management Access - Restrict management plane to a dedicated zone with jump boxes
  • Regular Validation - Test segmentation controls quarterly with automated tools
  • Monitor Denied Traffic - Log and review denied inter-zone traffic for policy refinement
  • PCI Scope Reduction - Use segmentation to minimize PCI DSS Cardholder Data Environment scope

References

Source materials

References and resources

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

References 1

api-reference.md2.4 KB

API Reference: Implementing Network Segmentation with Firewall Zones

Zone Trust Levels

Zone Trust Level Typical VLANs Default Policy
Internet 0 (Untrusted) N/A Deny all inbound
DMZ 1 (Low) 10-19 Permit specific inbound services
Guest 1 (Low) 50-59 Internet-only, deny internal
Corporate 3 (Medium) 100-199 Permit outbound, restricted inbound
Server/DC 4 (High) 200-299 Strict ACL, limited admin
PCI CDE 5 (Critical) 300-309 PCI DSS compliant isolation
Management 5 (Critical) 900-909 Jump box only
OT/SCADA 5 (Critical) 400-409 Air-gapped or strictly firewalled

Palo Alto Zone-Based CLI

# Create security zone
set network zone trust network layer3 ethernet1/2
set network zone untrust network layer3 ethernet1/1
set network zone dmz network layer3 ethernet1/3
 
# Inter-zone security policy
set rulebase security rules Allow-Corp-to-DMZ from trust to dmz \
  application web-browsing action allow log-end yes
 
# Default deny rule
set rulebase security rules Deny-All from any to any application any action deny log-start yes

Cisco ASA Zone Commands

# Define nameif and security level
interface GigabitEthernet0/0
  nameif outside
  security-level 0
interface GigabitEthernet0/1
  nameif inside
  security-level 100
interface GigabitEthernet0/2
  nameif dmz
  security-level 50
 
# ACL for inter-zone traffic
access-list OUTSIDE_IN extended permit tcp any host 192.168.10.5 eq 443
access-group OUTSIDE_IN in interface outside

PCI DSS Segmentation Requirements

Requirement Control
Req 1.2 Restrict connections between untrusted and CDE
Req 1.3 Prohibit direct public access to CDE
Req 1.4 Personal firewall on portable devices
Req 11.3.4 Penetration testing validates segmentation

VLAN Trunking (802.1Q)

# Cisco switch VLAN configuration
vlan 100
  name Corporate
vlan 200
  name Servers
vlan 300
  name PCI_CDE
 
interface GigabitEthernet0/1
  switchport mode trunk
  switchport trunk allowed vlan 100,200,300

References

Scripts 1

agent.py4.2 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Firewall Zone Segmentation Agent - audits zone-based firewall rules and inter-zone traffic policies."""

import json
import argparse
import logging
import subprocess
from collections import defaultdict
from datetime import datetime

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)


def parse_firewall_config(config_file):
    with open(config_file) as f:
        return json.load(f)


def get_iptables_zones():
    cmd = ["iptables", "-L", "-n", "-v", "--line-numbers"]
    result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
    chains = defaultdict(list)
    current_chain = ""
    for line in result.stdout.split("\n"):
        if line.startswith("Chain"):
            current_chain = line.split()[1]
        elif line.strip() and not line.startswith("num"):
            chains[current_chain].append(line.strip())
    return dict(chains)


def audit_zone_rules(config):
    findings = []
    rules = config.get("rules", [])
    for rule in rules:
        src_zone = rule.get("source_zone", "")
        dst_zone = rule.get("destination_zone", "")
        action = rule.get("action", "")
        service = rule.get("service", "any")
        if action == "allow" and service == "any":
            findings.append({"rule_id": rule.get("id", ""), "source_zone": src_zone, "dest_zone": dst_zone,
                           "issue": "Allows all services between zones", "severity": "high"})
        if action == "allow" and src_zone == "untrust" and dst_zone == "trust":
            findings.append({"rule_id": rule.get("id", ""), "issue": "Inbound from untrust to trust zone", "severity": "critical"})
        if rule.get("log") is False and action == "allow":
            findings.append({"rule_id": rule.get("id", ""), "issue": "Allow rule without logging", "severity": "medium"})
    return findings


def check_default_zone_policies(config):
    issues = []
    for zone in config.get("zones", []):
        if zone.get("default_action", "deny") != "deny":
            issues.append({"zone": zone.get("name"), "default_action": zone.get("default_action"),
                         "issue": "Default zone policy is not deny", "severity": "critical"})
    return issues


def analyze_rule_shadowing(rules):
    shadowed = []
    for i, rule in enumerate(rules):
        for j in range(i):
            prev = rules[j]
            if (prev.get("source_zone") == rule.get("source_zone") and
                prev.get("destination_zone") == rule.get("destination_zone") and
                prev.get("service") == "any" and prev.get("action") == "allow"):
                shadowed.append({"rule_id": rule.get("id"), "shadowed_by": prev.get("id"), "severity": "low"})
                break
    return shadowed


def generate_report(config, zone_findings, default_issues, shadowed):
    all_findings = zone_findings + default_issues + shadowed
    report = {
        "timestamp": datetime.utcnow().isoformat(),
        "total_zones": len(config.get("zones", [])),
        "total_rules": len(config.get("rules", [])),
        "zone_rule_findings": zone_findings,
        "default_policy_issues": default_issues,
        "shadowed_rules": shadowed,
        "total_findings": len(all_findings),
        "critical_findings": sum(1 for f in all_findings if f.get("severity") == "critical"),
    }
    return report


def main():
    parser = argparse.ArgumentParser(description="Firewall Zone Segmentation Audit Agent")
    parser.add_argument("--config", required=True, help="Firewall zone config JSON file")
    parser.add_argument("--output", default="zone_segmentation_report.json")
    args = parser.parse_args()

    config = parse_firewall_config(args.config)
    zone_findings = audit_zone_rules(config)
    default_issues = check_default_zone_policies(config)
    shadowed = analyze_rule_shadowing(config.get("rules", []))
    report = generate_report(config, zone_findings, default_issues, shadowed)
    with open(args.output, "w") as f:
        json.dump(report, f, indent=2, default=str)
    logger.info("Zone audit: %d zones, %d rules, %d findings", report["total_zones"], report["total_rules"], report["total_findings"])
    print(json.dumps(report, indent=2, default=str))


if __name__ == "__main__":
    main()
Keep exploring