network security

Implementing Next-Generation Firewall with Palo Alto

Configure and deploy Palo Alto Networks next-generation firewalls with App-ID, User-ID, zone-based policies, SSL decryption, and threat prevention profiles for enterprise network security.

app-idfirewallnetwork-securityngfwpalo-altossl-decryptionthreat-preventionuser-id
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

Overview

Palo Alto Networks Next-Generation Firewalls (NGFWs) move beyond traditional port-based rule enforcement to application-aware, identity-driven security policies. By leveraging App-ID for traffic classification, User-ID for identity-based enforcement, Content-ID for threat inspection, and SSL decryption for encrypted traffic visibility, organizations gain comprehensive control over network traffic. This skill covers end-to-end deployment from initial configuration through advanced threat prevention profiles.

When to Use

  • When deploying or configuring implementing next generation firewall with palo alto 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

  • Palo Alto Networks PA-series appliance or VM-Series virtual firewall
  • PAN-OS 10.2 or later
  • Valid Threat Prevention, URL Filtering, and WildFire licenses
  • Network topology documentation with zone definitions
  • LDAP/Active Directory integration credentials for User-ID
  • Internal CA certificate for SSL Forward Proxy decryption

Core Concepts

App-ID Technology

App-ID classifies network traffic by application regardless of port, protocol, or encryption. The classification engine uses multiple identification techniques in sequence:

  1. Application Signatures - Pattern matching against known application signatures
  2. SSL/TLS Decryption - Decrypt traffic to identify applications hidden in encrypted tunnels
  3. Application Protocol Decoding - Decode protocols to find applications tunneled within them
  4. Heuristic Analysis - Behavioral analysis for applications that evade other methods

The Policy Optimizer tool assists migration from legacy port-based rules to App-ID rules by analyzing traffic logs and recommending application-specific replacements.

User-ID Integration

User-ID maps IP addresses to user identities through multiple methods:

  • Server Monitoring - Parses Windows Security Event Logs (Event IDs 4624, 4768, 4769)
  • Syslog Listening - Receives authentication events from RADIUS, 802.1X, proxies
  • GlobalProtect - Maps VPN users automatically
  • Captive Portal - Web-based authentication for unknown users
  • XML API - Programmatic user mapping from custom sources

Zone-Based Architecture

Zones represent logical segments of the network. Security policies control traffic between zones (inter-zone) and within zones (intra-zone):

Zone Purpose Trust Level
Trust Internal corporate LAN High
Untrust Internet-facing None
DMZ Public-facing servers Medium
Guest Guest wireless Low
DataCenter Server infrastructure High

Workflow

Step 1: Initial System Configuration

Configure management interface, DNS, NTP, and system settings:

set deviceconfig system hostname PA-FW01
set deviceconfig system domain corp.example.com
set deviceconfig system dns-setting servers primary 10.0.1.10
set deviceconfig system dns-setting servers secondary 10.0.1.11
set deviceconfig system ntp-servers primary-ntp-server ntp-server-address 0.pool.ntp.org
set deviceconfig system timezone US/Eastern
set deviceconfig system login-banner "Authorized access only. All activity is monitored."

Step 2: Configure Network Zones and Interfaces

Define security zones and assign interfaces:

set zone Trust network layer3 ethernet1/1
set zone Untrust network layer3 ethernet1/2
set zone DMZ network layer3 ethernet1/3
set zone Guest network layer3 ethernet1/4
 
set network interface ethernet ethernet1/1 layer3 ip 10.10.0.1/24
set network interface ethernet ethernet1/1 layer3 interface-management-profile allow-ping
set network interface ethernet ethernet1/2 layer3 dhcp-client
 
set network virtual-router default interface [ ethernet1/1 ethernet1/2 ethernet1/3 ethernet1/4 ]

Step 3: Configure Zone Protection Profiles

Protect against reconnaissance and DoS attacks at the zone level:

set network profiles zone-protection-profile Strict-ZP flood tcp-syn enable yes
set network profiles zone-protection-profile Strict-ZP flood tcp-syn alert-rate 100
set network profiles zone-protection-profile Strict-ZP flood tcp-syn activate-rate 500
set network profiles zone-protection-profile Strict-ZP flood tcp-syn maximal-rate 2000
set network profiles zone-protection-profile Strict-ZP flood tcp-syn syn-cookies enable yes
 
set network profiles zone-protection-profile Strict-ZP flood udp enable yes
set network profiles zone-protection-profile Strict-ZP flood icmp enable yes
 
set network profiles zone-protection-profile Strict-ZP scan 8003 action block-ip
set network profiles zone-protection-profile Strict-ZP scan 8003 interval 2
set network profiles zone-protection-profile Strict-ZP scan 8003 threshold 100

Step 4: Configure Threat Prevention Profiles

Create Anti-Virus, Anti-Spyware, Vulnerability Protection, and URL Filtering profiles:

# Anti-Spyware Profile
set profiles spyware Strict-AS botnet-domains lists default-paloalto-dns packet-capture single-packet
set profiles spyware Strict-AS botnet-domains sinkhole ipv4-address pan-sinkhole-default-ip
set profiles spyware Strict-AS rules Block-Critical severity critical action block-ip
 
# Vulnerability Protection Profile
set profiles vulnerability Strict-VP rules Block-Critical-High vendor-id any severity [ critical high ] action block-ip
 
# URL Filtering Profile
set profiles url-filtering Strict-URL credential-enforcement mode ip-user
set profiles url-filtering Strict-URL block [ command-and-control malware phishing ]
set profiles url-filtering Strict-URL alert [ hacking proxy-avoidance-and-anonymizers ]
 
# File Blocking Profile
set profiles file-blocking Strict-FB rules Block-Dangerous application any file-type [ bat exe msi ps1 vbs ] direction both action block
 
# WildFire Analysis Profile
set profiles wildfire-analysis Strict-WF rules Forward-All application any file-type any direction both analysis public-cloud

Step 5: Configure SSL Decryption

Set up SSL Forward Proxy for outbound traffic inspection:

# Generate Forward Trust CA certificate
request certificate generate certificate-name SSL-FP-CA algorithm RSA digest sha256 ca yes
 
# Create Decryption Profile
set profiles decryption Strict-Decrypt ssl-forward-proxy block-expired-certificate yes
set profiles decryption Strict-Decrypt ssl-forward-proxy block-untrusted-issuer yes
set profiles decryption Strict-Decrypt ssl-forward-proxy block-unknown-cert yes
set profiles decryption Strict-Decrypt ssl-forward-proxy restrict-cert-exts yes
 
# Create Decryption Policy
set rulebase decryption rules Decrypt-Outbound from Trust to Untrust source any destination any
set rulebase decryption rules Decrypt-Outbound action decrypt type ssl-forward-proxy
set rulebase decryption rules Decrypt-Outbound profile Strict-Decrypt
 
# Exclude sensitive categories (financial, healthcare)
set rulebase decryption rules No-Decrypt-Sensitive from Trust to Untrust
set rulebase decryption rules No-Decrypt-Sensitive category [ financial-services health-and-medicine ]
set rulebase decryption rules No-Decrypt-Sensitive action no-decrypt

Step 6: Build Security Policies

Create application-aware security policies with security profiles:

# Allow business applications from Trust to Internet
set rulebase security rules Allow-Business from Trust to Untrust
set rulebase security rules Allow-Business source-user any
set rulebase security rules Allow-Business application [ office365-enterprise salesforce-base slack-base zoom ]
set rulebase security rules Allow-Business service application-default
set rulebase security rules Allow-Business action allow
set rulebase security rules Allow-Business profile-setting group Strict-Security-Profiles
 
# Allow web browsing with URL filtering
set rulebase security rules Allow-Web from Trust to Untrust
set rulebase security rules Allow-Web application [ web-browsing ssl ]
set rulebase security rules Allow-Web action allow
set rulebase security rules Allow-Web profile-setting profiles url-filtering Strict-URL
 
# Block high-risk applications
set rulebase security rules Block-HighRisk from any to any
set rulebase security rules Block-HighRisk application [ bittorrent tor anonymizer ]
set rulebase security rules Block-HighRisk action deny
set rulebase security rules Block-HighRisk log-end yes
 
# Default deny rule (explicit)
set rulebase security rules Deny-All from any to any source any destination any
set rulebase security rules Deny-All application any service any action deny
set rulebase security rules Deny-All log-end yes

Step 7: Configure Logging and SIEM Integration

Forward logs to a SIEM for correlation:

# Configure Syslog Server Profile
set shared log-settings syslog SIEM-Server server SIEM transport UDP port 514 server 10.0.5.100
set shared log-settings syslog SIEM-Server server SIEM facility LOG_USER
 
# Configure Log Forwarding Profile
set shared log-settings profiles SIEM-Forward match-list Threats log-type threat
set shared log-settings profiles SIEM-Forward match-list Threats send-syslog SIEM-Server
set shared log-settings profiles SIEM-Forward match-list Traffic log-type traffic
set shared log-settings profiles SIEM-Forward match-list Traffic send-syslog SIEM-Server
set shared log-settings profiles SIEM-Forward match-list URL log-type url
set shared log-settings profiles SIEM-Forward match-list URL send-syslog SIEM-Server

Validation and Testing

  1. Policy Audit - Review with show running security-policy and check for shadowed rules
  2. Traffic Verification - Monitor Traffic logs for application classification accuracy
  3. Threat Simulation - Use EICAR test file and known-bad URLs to validate threat profiles
  4. SSL Decryption Test - Verify certificate chain in browser matches Forward Trust CA
  5. Zone Protection Test - Run controlled SYN flood to verify SYN cookie activation
  6. Policy Optimizer - Run Policy Optimizer to identify remaining port-based rules
# Verify active sessions
show session all filter application web-browsing
 
# Check threat log entries
show log threat direction equal backward
 
# Verify App-ID classification
show running application-override
 
# Check system resources
show system resources

Best Practices

  • Least Privilege - Start with deny-all and explicitly allow only required applications
  • App-ID Over Port - Replace port-based rules with application-specific rules using Policy Optimizer
  • Decryption Coverage - Decrypt at least 80% of SSL traffic with appropriate privacy exclusions
  • Security Profile Groups - Apply Anti-Virus, Anti-Spyware, Vulnerability, URL Filtering, File Blocking, and WildFire as a group
  • Signature Updates - Enable automatic daily content updates for Applications and Threats
  • HA Configuration - Deploy in active/passive HA pair for production environments
  • Commit Validation - Always validate configuration before committing: validate full

References

Source materials

References and resources

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

References 3

api-reference.md1.1 KB

API Reference: Palo Alto Networks NGFW (PAN-OS)

PAN-OS XML API

Endpoint Method Description
/api/?type=keygen GET Generate API key
/api/?type=config&action=get GET Get configuration
/api/?type=config&action=set GET Set configuration
/api/?type=op POST Operational commands

Authentication

GET https://<fw>/api/?type=keygen&user=admin&password=admin

Configuration XPaths

XPath Description
/config/devices/.../vsys/.../rulebase/security/rules Security rules
/config/devices/.../vsys/.../profiles Security profiles
/config/devices/.../deviceconfig/system System config

pan-python Library

pip install pan-python
Method Description
pan.xapi.PanXapi(hostname, api_key) Create API client
xapi.get(xpath) Get config element
xapi.set(xpath, element) Set config element

Key Libraries

Library Use
requests REST API calls
pan-python PAN-OS SDK
xml.etree XML response parsing
standards.md1.5 KB

Standards and Frameworks - Palo Alto NGFW

Industry Standards

  • NIST SP 800-41 Rev 1 - Guidelines on Firewalls and Firewall Policy
  • NIST SP 800-53 Rev 5 - SC-7 (Boundary Protection), AC-4 (Information Flow Enforcement)
  • CIS Controls v8 - Control 4 (Secure Configuration), Control 9 (Email and Web Browser Protections), Control 13 (Network Monitoring and Defense)
  • PCI DSS v4.0 - Requirement 1 (Install and Maintain Network Security Controls)
  • ISO 27001:2022 - A.13.1 (Network Security Management)

Palo Alto Specific Standards

  • PAN-OS Security Configuration Benchmark - CIS Benchmark for Palo Alto firewalls
  • Best Practices for Completing NGFW Deployment - docs.paloaltonetworks.com
  • Security Policy Best Practices - Application-based rules, zone segmentation
  • SSL Decryption Best Practices - Certificate management, excluded categories
  • Threat Prevention Best Practices - Profile configuration for AV, AS, VP, URL, WildFire

Compliance Mapping

Control PAN-OS Feature
Access Control (AC-4) Security Policies with App-ID and User-ID
Boundary Protection (SC-7) Zone-based architecture with inter-zone policies
Malicious Code Protection (SI-3) WildFire, Anti-Virus, Anti-Spyware profiles
Audit and Accountability (AU-3) Traffic, Threat, URL, WildFire logging
Encryption (SC-8) SSL/TLS decryption and inspection
DoS Protection (SC-5) Zone Protection profiles with flood thresholds
workflows.md2.3 KB

Workflows - Palo Alto NGFW Implementation

Deployment Workflow

Phase 1: Planning
├── Document network topology and traffic flows
├── Define security zones and trust levels
├── Inventory applications and required access
├── Plan IP addressing and interface assignments
└── Define decryption policy scope and exclusions
 
Phase 2: Base Configuration
├── Configure management interface and system settings
├── Set up HA pair (active/passive)
├── Configure network interfaces and zones
├── Set up Zone Protection profiles
├── Configure routing (static or dynamic)
└── Integrate with DNS, NTP, LDAP/AD
 
Phase 3: Security Policy Development
├── Create Security Profile Groups (AV, AS, VP, URL, FB, WF)
├── Build application-based Security Policies
├── Configure SSL Decryption policies
├── Set up User-ID integration with AD
├── Create NAT policies
└── Configure DoS Protection policies
 
Phase 4: Logging and Monitoring
├── Configure Syslog/SIEM forwarding
├── Set up log forwarding profiles
├── Configure SNMP monitoring
├── Enable Cortex Data Lake integration
└── Create custom reports and dashboards
 
Phase 5: Testing and Validation
├── Validate application classification with Policy Optimizer
├── Test threat prevention with EICAR and test URLs
├── Verify SSL decryption certificate chain
├── Conduct penetration test against firewall
├── Review and remediate audit findings
└── Document final configuration baseline
 
Phase 6: Operations
├── Schedule automatic content updates
├── Monitor threat and traffic dashboards
├── Review Security Policy rule hit counts monthly
├── Conduct quarterly firewall rule review
├── Test HA failover quarterly
└── Upgrade PAN-OS per vendor schedule

Change Management Workflow

1. Submit change request with business justification
2. Review impact analysis (affected zones, applications, users)
3. Approve through CAB (Change Advisory Board)
4. Clone current configuration as backup
5. Implement change in maintenance window
6. Validate with `validate full` before commit
7. Commit changes and monitor logs for 24 hours
8. Document changes in configuration management database

Scripts 2

agent.py4.5 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Palo Alto NGFW Agent - audits security policies, threat prevention, and App-ID usage via XML API."""

import json
import argparse
import logging
import subprocess
import xml.etree.ElementTree as ET
from datetime import datetime

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


def pan_api_request(firewall_ip, api_key, cmd_type, cmd):
    url = f"https://{firewall_ip}/api/?type={cmd_type}&cmd={cmd}&key={api_key}"
    result = subprocess.run(["curl", "-s", "-k", url], capture_output=True, text=True, timeout=120)
    return result.stdout


def get_security_rules(fw_ip, api_key):
    cmd = "<show><running><security-policy></security-policy></running></show>"
    xml_data = pan_api_request(fw_ip, api_key, "op", cmd)
    rules = []
    try:
        root = ET.fromstring(xml_data)
        for entry in root.iter("entry"):
            rule = {
                "name": entry.get("name", ""),
                "source_zone": [z.text for z in entry.findall(".//from/member")] or ["any"],
                "dest_zone": [z.text for z in entry.findall(".//to/member")] or ["any"],
                "application": [a.text for a in entry.findall(".//application/member")] or ["any"],
                "action": entry.findtext(".//action", ""),
                "log_end": entry.findtext(".//log-end", "no"),
                "profile_group": entry.findtext(".//profile-setting/group/member", ""),
            }
            rules.append(rule)
    except ET.ParseError:
        logger.error("Failed to parse security rules XML")
    return rules


def audit_security_rules(rules):
    findings = []
    for rule in rules:
        name = rule["name"]
        if "any" in rule["application"]:
            findings.append({"rule": name, "issue": "Uses any application instead of App-ID", "severity": "high"})
        if not rule.get("profile_group"):
            findings.append({"rule": name, "issue": "No security profile group attached", "severity": "high"})
        if rule["log_end"] != "yes":
            findings.append({"rule": name, "issue": "End logging not enabled", "severity": "medium"})
        if rule["action"] == "allow" and "any" in rule["source_zone"] and "any" in rule["dest_zone"]:
            findings.append({"rule": name, "issue": "Allow any-to-any zones", "severity": "critical"})
    return findings


def calculate_appid_coverage(rules):
    total = len(rules)
    appid_rules = sum(1 for r in rules if "any" not in r["application"])
    return {"total_rules": total, "appid_enabled": appid_rules,
            "coverage_percent": round(appid_rules / max(total, 1) * 100, 1)}


def check_system_health(fw_ip, api_key):
    cmd = "<show><system><info></info></system></show>"
    xml_data = pan_api_request(fw_ip, api_key, "op", cmd)
    info = {}
    try:
        root = ET.fromstring(xml_data)
        info["hostname"] = root.findtext(".//hostname", "")
        info["model"] = root.findtext(".//model", "")
        info["sw_version"] = root.findtext(".//sw-version", "")
        info["threat_version"] = root.findtext(".//threat-version", "")
        info["app_version"] = root.findtext(".//app-version", "")
    except ET.ParseError:
        pass
    return info


def generate_report(rules, findings, appid, health):
    return {
        "timestamp": datetime.utcnow().isoformat(),
        "system_health": health,
        "total_rules": len(rules),
        "appid_coverage": appid,
        "security_findings": findings,
        "total_findings": len(findings),
        "critical_findings": sum(1 for f in findings if f.get("severity") == "critical"),
    }


def main():
    parser = argparse.ArgumentParser(description="Palo Alto NGFW Audit Agent")
    parser.add_argument("--firewall", required=True, help="Firewall IP/hostname")
    parser.add_argument("--api-key", required=True, help="PAN-OS API key")
    parser.add_argument("--output", default="panos_ngfw_report.json")
    args = parser.parse_args()

    health = check_system_health(args.firewall, args.api_key)
    rules = get_security_rules(args.firewall, args.api_key)
    findings = audit_security_rules(rules)
    appid = calculate_appid_coverage(rules)
    report = generate_report(rules, findings, appid, health)
    with open(args.output, "w") as f:
        json.dump(report, f, indent=2, default=str)
    logger.info("PAN-OS: %d rules, App-ID %.1f%%, %d findings",
                len(rules), appid["coverage_percent"], len(findings))
    print(json.dumps(report, indent=2, default=str))


if __name__ == "__main__":
    main()
process.py9.3 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""
Palo Alto NGFW Security Policy Audit Script.
Connects to Palo Alto firewall via XML API and audits security policies
for common misconfigurations and best practice violations.
"""

import xml.etree.ElementTree as ET
import json
import sys
import urllib.request
import urllib.parse
import ssl
from datetime import datetime
from typing import Optional


class PaloAltoAuditor:
    """Audit Palo Alto NGFW security configuration against best practices."""

    def __init__(self, host: str, api_key: str, verify_ssl: bool = False):
        self.host = host
        self.api_key = api_key
        self.base_url = f"https://{host}/api/"
        self.findings = []

        if not verify_ssl:
            self.ssl_context = ssl.create_default_context()
            self.ssl_context.check_hostname = False
            self.ssl_context.verify_mode = ssl.CERT_NONE
        else:
            self.ssl_context = ssl.create_default_context()

    def _api_request(self, params: dict) -> Optional[ET.Element]:
        """Make API request to Palo Alto firewall."""
        params['key'] = self.api_key
        query = urllib.parse.urlencode(params)
        url = f"{self.base_url}?{query}"

        try:
            req = urllib.request.Request(url)
            response = urllib.request.urlopen(req, context=self.ssl_context)
            xml_response = response.read()
            return ET.fromstring(xml_response)
        except Exception as e:
            print(f"API request failed: {e}")
            return None

    def get_security_rules(self) -> Optional[ET.Element]:
        """Retrieve security policy rules."""
        params = {
            'type': 'config',
            'action': 'get',
            'xpath': "/config/devices/entry[@name='localhost.localdomain']"
                     "/vsys/entry[@name='vsys1']/rulebase/security/rules"
        }
        return self._api_request(params)

    def get_decryption_rules(self) -> Optional[ET.Element]:
        """Retrieve decryption policy rules."""
        params = {
            'type': 'config',
            'action': 'get',
            'xpath': "/config/devices/entry[@name='localhost.localdomain']"
                     "/vsys/entry[@name='vsys1']/rulebase/decryption/rules"
        }
        return self._api_request(params)

    def get_zone_protection_profiles(self) -> Optional[ET.Element]:
        """Retrieve zone protection profiles."""
        params = {
            'type': 'config',
            'action': 'get',
            'xpath': "/config/devices/entry[@name='localhost.localdomain']"
                     "/network/profiles/zone-protection-profile"
        }
        return self._api_request(params)

    def add_finding(self, severity: str, category: str, rule_name: str,
                    description: str, recommendation: str):
        """Add an audit finding."""
        self.findings.append({
            'severity': severity,
            'category': category,
            'rule_name': rule_name,
            'description': description,
            'recommendation': recommendation,
            'timestamp': datetime.now().isoformat(),
        })

    def audit_security_rules(self, rules_xml: ET.Element):
        """Audit security rules for best practice violations."""
        if rules_xml is None:
            return

        rules = rules_xml.findall('.//entry')
        for rule in rules:
            name = rule.get('name', 'Unknown')

            # Check for any/any rules
            from_zones = [z.text for z in rule.findall('.//from/member')]
            to_zones = [z.text for z in rule.findall('.//to/member')]
            if 'any' in from_zones and 'any' in to_zones:
                self.add_finding(
                    'HIGH', 'Overly Permissive', name,
                    'Rule uses "any" for both source and destination zones',
                    'Specify explicit source and destination zones'
                )

            # Check for application "any"
            apps = [a.text for a in rule.findall('.//application/member')]
            if 'any' in apps:
                action = rule.findtext('.//action')
                if action == 'allow':
                    self.add_finding(
                        'HIGH', 'Application Control', name,
                        'Rule allows "any" application (port-based rule)',
                        'Use App-ID to specify allowed applications. '
                        'Use Policy Optimizer to identify actual applications.'
                    )

            # Check for missing security profiles
            profile_setting = rule.find('.//profile-setting')
            action = rule.findtext('.//action')
            if action == 'allow' and profile_setting is None:
                self.add_finding(
                    'HIGH', 'Threat Prevention', name,
                    'Allow rule has no Security Profile Group attached',
                    'Attach Anti-Virus, Anti-Spyware, Vulnerability, '
                    'URL Filtering, File Blocking, and WildFire profiles'
                )

            # Check for disabled rules
            disabled = rule.findtext('.//disabled')
            if disabled == 'yes':
                self.add_finding(
                    'LOW', 'Hygiene', name,
                    'Rule is disabled',
                    'Remove disabled rules to reduce policy complexity'
                )

            # Check for logging disabled
            log_end = rule.findtext('.//log-end')
            if log_end == 'no' and action == 'allow':
                self.add_finding(
                    'MEDIUM', 'Logging', name,
                    'Rule does not log at session end',
                    'Enable log-at-session-end for all allow rules'
                )

            # Check for service "any" instead of application-default
            services = [s.text for s in rule.findall('.//service/member')]
            if 'any' in services and 'any' not in apps:
                self.add_finding(
                    'MEDIUM', 'Service Enforcement', name,
                    'Rule uses "any" service instead of "application-default"',
                    'Use "application-default" to enforce standard ports for identified applications'
                )

    def audit_decryption(self, decryption_xml: ET.Element):
        """Audit SSL decryption coverage."""
        if decryption_xml is None:
            self.add_finding(
                'HIGH', 'SSL Decryption', 'N/A',
                'No SSL decryption policy is configured',
                'Configure SSL Forward Proxy for outbound traffic inspection '
                'and SSL Inbound Inspection for critical servers'
            )
            return

        rules = decryption_xml.findall('.//entry')
        has_decrypt = any(
            rule.findtext('.//action') == 'decrypt'
            for rule in rules
        )
        if not has_decrypt:
            self.add_finding(
                'HIGH', 'SSL Decryption', 'N/A',
                'No active decryption rules found',
                'Enable SSL Forward Proxy to inspect encrypted traffic'
            )

    def generate_report(self) -> dict:
        """Generate audit report."""
        severity_counts = {'CRITICAL': 0, 'HIGH': 0, 'MEDIUM': 0, 'LOW': 0}
        for finding in self.findings:
            severity_counts[finding['severity']] = \
                severity_counts.get(finding['severity'], 0) + 1

        report = {
            'audit_date': datetime.now().isoformat(),
            'firewall_host': self.host,
            'summary': {
                'total_findings': len(self.findings),
                'by_severity': severity_counts,
            },
            'findings': self.findings,
        }
        return report

    def run_audit(self):
        """Execute full audit."""
        print(f"[*] Starting audit of {self.host}...")

        print("[*] Auditing security rules...")
        security_rules = self.get_security_rules()
        self.audit_security_rules(security_rules)

        print("[*] Auditing decryption policy...")
        decryption_rules = self.get_decryption_rules()
        self.audit_decryption(decryption_rules)

        report = self.generate_report()

        print(f"\n{'='*70}")
        print(f"PALO ALTO NGFW SECURITY AUDIT REPORT")
        print(f"{'='*70}")
        print(f"Host: {report['firewall_host']}")
        print(f"Date: {report['audit_date']}")
        print(f"\nTotal Findings: {report['summary']['total_findings']}")
        for sev, count in report['summary']['by_severity'].items():
            print(f"  {sev}: {count}")

        print(f"\n{'='*70}")
        for finding in self.findings:
            print(f"\n[{finding['severity']}] {finding['category']} - {finding['rule_name']}")
            print(f"  Issue: {finding['description']}")
            print(f"  Fix: {finding['recommendation']}")

        # Save JSON report
        report_path = f"paloalto_audit_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
        with open(report_path, 'w') as f:
            json.dump(report, f, indent=2)
        print(f"\nReport saved to: {report_path}")

        return report


if __name__ == '__main__':
    if len(sys.argv) < 3:
        print("Usage: python process.py <firewall_host> <api_key>")
        print("Example: python process.py 10.0.1.1 LUFRPT1234567890==")
        sys.exit(1)

    host = sys.argv[1]
    api_key = sys.argv[2]

    auditor = PaloAltoAuditor(host, api_key)
    auditor.run_audit()

Assets 1

template.mdtext/markdown · 2.4 KB
Keep exploring