PromptHub
Back to Blog
Open Source Tools Network Security

Stop Drawing Firewall Diagrams by Hand! PyFRC2G Automates It

B

Bright Coding

Author

13 min read 65 views
Stop Drawing Firewall Diagrams by Hand! PyFRC2G Automates It

Stop Drawing Firewall Diagrams by Hand! PyFRC2G Automates It

How many hours have you wasted this quarter manually documenting firewall rules? If you're a network engineer, security auditor, or DevOps↗ Bright Coding Blog professional managing pfSense or OPNSense firewalls, that number is probably embarrassing. We've all been there—screenshotting web interfaces, copy-pasting rules into Visio, drawing arrows that never quite align, only to have everything outdated the moment someone adds a new VLAN rule.

Here's the brutal truth: firewall documentation is compliance theater without automation. Auditors demand visual evidence. CISOs need proof of network segmentation. Yet most teams are still creating these diagrams by hand, burning precious hours on work that a machine should handle instantly.

Enter PyFRC2G—the open-source Python↗ Bright Coding Blog toolkit that transforms your pfSense and OPNSense firewall configurations into professional, color-coded flow diagrams with a single command. No more manual drudgery. No more stale documentation. No more explaining to auditors why your network diagrams don't match reality.

In this deep dive, I'll show you exactly how PyFRC2G works, why it's becoming the secret weapon of top network security professionals, and how you can deploy it in under 10 minutes. The days of hand-crafted firewall diagrams are officially over.


What is PyFRC2G?

PyFRC2G (Python Firewall Rules to Graph) is a unified, open-source Python package created by developer Olivier B. that automatically converts pfSense and OPNSense firewall rule sets into graphical flow diagrams and structured documentation. Hosted on GitHub, this tool bridges the critical gap between raw firewall configurations and human-readable network security documentation.

The project emerged from a universal pain point in network administration: firewalls accumulate hundreds of rules across multiple interfaces, VLANs, and floating configurations, yet there's no native visualization capability in either pfSense or OPNSense. Security teams were forced to either maintain expensive commercial documentation platforms or resort to manual diagramming—both approaches guaranteed obsolescence.

PyFRC2G solves this through dual-mode architecture. It can either connect directly to your firewall via REST API (for live, always-current documentation) or parse XML backup files (for offline analysis, auditing, or disaster recovery planning). This flexibility makes it equally valuable for operational monitoring and compliance evidence collection.

The tool has gained rapid traction in the network security community because it addresses two non-negotiable requirements simultaneously: operational clarity (engineers need to understand traffic flows) and regulatory compliance (frameworks like ISO 27001, SOC 2, and NIST demand documented network controls). With built-in CISO Assistant integration, PyFRC2G can even automatically upload generated evidence to governance platforms—transforming a manual compliance burden into an automated pipeline.

What truly distinguishes PyFRC2G from ad-hoc scripting approaches is its production-ready engineering: modular architecture, intelligent change detection, automatic alias resolution, and per-interface PDF generation. This isn't a quick hack—it's a maintainable solution designed for enterprise environments.


Key Features That Make PyFRC2G Insanely Powerful

PyFRC2G packs capabilities that would cost thousands in commercial alternatives. Here's what separates it from basic graphing scripts:

Dual Input Modes for Maximum Flexibility

  • API Mode: Live connection to pfSense (via REST API package) or OPNSense (native API) for real-time documentation
  • Backup Mode: Parse config.xml files without any network connectivity—perfect for air-gapped environments or historical analysis

Intelligent Interface Handling

  • Auto-detection: Automatically discovers all enabled interfaces on OPNSense and pfSense (skipping system interfaces like lo0, enc0, pflog0)
  • Manual override: Specify exact interfaces when auto-detection isn't suitable
  • Floating rules support: Properly categorizes and visualizes floating rules that apply across multiple interfaces

Smart Alias Resolution

  • Automatically fetches all alias types from API: interface names, network aliases, address aliases, and port aliases
  • Maps cryptic internal identifiers to human-readable labels in generated diagrams
  • In backup mode, extracts aliases directly from XML structure

Production-Grade Output Generation

  • Per-interface PDFs: Separate A4 PDF documents for each interface, plus a global consolidated view
  • Color-coded visualization: Green for PASS rules, red for BLOCK rules, yellow for disabled rules—immediate visual threat assessment
  • CSV exports: Structured data for further analysis or import into other tools

Change Detection & Efficiency

  • MD5-based comparison: Only regenerates outputs when firewall rules actually change, saving processing time and storage
  • Force regeneration: Delete md5sum.txt to override when needed
  • Automatic cleanup: Temporary CSV and PNG files removed after PDF generation

Compliance Integration

  • CISO Assistant upload: Optional automatic submission of PDF evidence revisions to governance platforms
  • Timestamped evidence: Each upload creates a new revision, maintaining complete audit history of firewall state changes

Robust Configuration Management

  • Pre-flight validation: config_checker.py verifies API credentials aren't placeholders before attempting connection
  • Skip option: --skip-config-check for scripted deployments where validation is handled externally
  • Debug verbosity: --debug and --verbose flags for troubleshooting complex environments

Real-World Use Cases Where PyFRC2G Shines

1. SOC 2 / ISO 27001 Audit Preparation

Compliance auditors invariably request network diagrams proving segmentation between environments. With PyFRC2G, you generate current evidence in minutes rather than scrambling for weeks. The color-coded PASS/BLOCK visualization immediately demonstrates control effectiveness to assessors.

2. Firewall Migration Planning

Moving from pfSense to OPNSense (or vice versa)? Parse both configurations into identical visual formats to compare rule logic side-by-side. The unified CSV output enables diff-based analysis of policy differences before cutover.

3. Incident Response Documentation

Post-breach, investigators need to understand exactly what traffic was permitted. XML backup mode lets you analyze historical configurations without touching production systems, generating diagrams that become permanent case evidence.

4. DevOps Network Automation Pipelines

Integrate PyFRC2G into CI/CD workflows: automatically generate and archive documentation whenever infrastructure-as-code commits modify firewall rules. The MD5 change detection prevents unnecessary rebuilds while ensuring documentation stays synchronized.

5. Multi-Tenant Service Provider Environments

Managed security providers supporting numerous client firewalls can standardize documentation across heterogeneous pfSense/OPNSense deployments. The --gateway-name parameter ensures clear labeling in multi-customer outputs.


Step-by-Step Installation & Setup Guide

Prerequisites

Before installation, ensure your system has Python 3.7+ and Graphviz installed:

Graphviz Installation:

# Debian/Ubuntu
sudo apt-get install graphviz

# RHEL/CentOS
sudo yum install graphviz

# macOS
brew install graphviz

# Windows: Download installer from https://graphviz.org/download/
# Ensure Graphviz bin directory is in your system PATH

Firewall API Setup (for API mode):

pfSense:

  1. Install the pfSense REST API Package
  2. Configure listening interfaces
  3. Generate API key for authentication

OPNSense:

  1. Navigate to System > Access > Users
  2. Create or edit a user
  3. Generate API key and secret in the API Keys section

Installation

Recommended: Install as Package

# Clone the repository
git clone https://github.com/olivierb46/PyFRC2G.git
cd PyFRC2G

# Install setuptools (required by setup.py)
pip install setuptools

# Install in development mode (allows editing)
pip install -e .

# Or install directly for production use
pip install .

Alternative: Direct Usage Without Installation

# Install dependencies only
pip install -r requirements.txt

# Run script directly
pyfrc2g

Configuration

Edit pyfrc2g/config.py for your environment:

pfSense Configuration:

GATEWAY_TYPE = "pfsense"

PFS_BASE_URL = "https://pfs01.domain.lan"
PFS_TOKEN = "YOUR_API_KEY_GENERATED_WITH_PFSENSE_REST_API"

GATEWAY_NAME = "PFS01"

OPNSense Configuration:

GATEWAY_TYPE = "opnsense"

OPNS_BASE_URL = "https://opnsense.domain.lan"
OPNS_KEY = "YOUR_API_KEY"
OPNS_SECRET = "YOUR_API_SECRET"

# Auto-detection (recommended)
INTERFACES = []

# Or manual specification
# INTERFACES = ["wan", "lan", "opt1", "opt2"]

GATEWAY_NAME = "OPNS01"

Optional CISO Assistant Integration:

CISO_URL = "https://ciso-assistant.example.com"
CISO_TOKEN = "YOUR_CISO_ASSISTANT_API_TOKEN"
CISO_EVIDENCE_PATH = f"{CISO_URL}/api/evidence-revisions/"
CISO_FORLDER_ID = "<CISO_FOLDER_ID>"
CISO_EVIDENCE_ID = "<CISO_EVIDENCE_ID>"

REAL Code Examples from the Repository

PyFRC2G's power becomes clear when you examine its actual implementation patterns. Here are production-ready examples extracted directly from the codebase:

Example 1: Basic CLI Usage Patterns

The command-line interface supports multiple operational modes through argparse:

# Default API mode (requires config.py setup)
pyfrc2g

# Explicit API mode with debug output
pyfrc2g --api --debug

# XML backup mode (no API configuration needed)
pyfrc2g --backup config-backup.xml

# Backup mode with custom gateway labeling
pyfrc2g --backup config-backup.xml --gateway-name prod-firewall-01

# Bypass configuration validation (use in automation scripts)
pyfrc2g --api --skip-config-check

# Verbose output for troubleshooting
pyfrc2g --backup config.xml --verbose

What's happening here? The tool uses argparse to handle multiple operational modes. API mode connects live to your firewall; backup mode parses static XML. The --skip-config-check flag is critical for automation scenarios where config validation occurs in pre-deployment pipelines rather than at runtime.

Example 2: Programmatic API Usage

For integration into larger Python applications or custom workflows:

from pyfrc2g import Config, APIClient, GraphGenerator
from pyfrc2g.main import main

# Option 1: Use the built-in main function for standard execution
main()

# Option 2: Direct component access for custom workflows
config = Config()                    # Load configuration from config.py
api_client = APIClient(config)       # Initialize API connection handler
graph_generator = GraphGenerator(config)  # Initialize visualization engine

# Fetch all alias definitions from firewall API
# This resolves interface names, network aliases, address aliases, port aliases
api_client.fetch_aliases()

# Retrieve complete firewall rule set
rules = api_client.fetch_rules()

# Generate visualizations and PDF outputs
# csv_path: temporary working file for rule data
# output_dir: destination for generated PDFs and CSVs
graph_generator.generate_graphs(csv_path, output_dir)

Deep dive: This reveals PyFRC2G's clean separation of concerns. The Config class centralizes settings; APIClient handles all firewall communication with automatic alias resolution; GraphGenerator manages the visualization pipeline. You can inject custom logic between any stage—perhaps filtering rules before visualization or post-processing PDFs.

Example 3: Configuration-Driven Firewall Selection

The config.py structure enables single-tool management of heterogeneous environments:

# For pfSense deployments
GATEWAY_TYPE = "pfsense"

PFS_BASE_URL = "https://pfs01.domain.lan"
PFS_TOKEN = "YOUR_API_KEY_GENERATED_WITH_PFSENSE_REST_API"

GATEWAY_NAME = "PFS01"  # Used in output filenames and diagram labels
# For OPNSense deployments
GATEWAY_TYPE = "opnsense"

OPNS_BASE_URL = "https://opnsense.domain.lan"
OPNS_KEY = "YOUR_API_KEY"
OPNS_SECRET = "YOUR_API_SECRET"

# Option 1: Auto-detection discovers all enabled interfaces automatically
INTERFACES = []

# Option 2: Manual control for specific interface analysis
INTERFACES = ["wan", "lan", "opt1", "opt2"]

GATEWAY_NAME = "OPNS01"  # Display name for gateway (used in labels)

Critical insight: The INTERFACES array behavior differs strategically between platforms. Empty array triggers auto-detection—OPNSense uses /api/core/interfaces/listAll or /api/core/interfaces/list, with fallback to rule-based extraction. For pfSense, it tries API v2 interfaces endpoint first, then v1 firewall interface endpoint, then rule-derived extraction. This cascading fallback ensures robust operation even with API version variations.

Example 4: Generated Output Structure

Understanding the output format helps integrate PyFRC2G into documentation pipelines:

results/PFS01/
├── PFS01_FLOW_MATRIX.pdf              # Global PDF: all interfaces, one per page
├── PFS01_wan_FLOW_MATRIX.pdf          # WAN-specific flow diagram
├── PFS01_wan_flows.csv                # WAN rules in structured CSV format
├── PFS01_lan_FLOW_MATRIX.pdf          # LAN-specific flow diagram
├── PFS01_lan_flows.csv                # LAN rules in structured CSV format
├── PFS01_opt1_FLOW_MATRIX.pdf         # OPT1-specific flow diagram
└── md5sum.txt                         # MD5 hash for change detection

The CSV structure contains these columns: SOURCE (mapped from aliases), GATEWAY (gateway name with interfaces), ACTION (Pass/Block/Reject), PROTOCOL (e.g., IPv4 tcp, IPv6 Any), PORT, DESTINATION, COMMENT, DISABLED (True/False), FLOATING (True/False), and RULE ORDER (index for sequence validation).


Advanced Usage & Best Practices

Optimize Your Workflow

  1. Version Control Your Configurations: Store pyfrc2g/config.py templates per environment in Git. Use environment variables or secret management for credentials rather than hardcoding tokens.

  2. Schedule Automated Generation: Combine cron jobs or systemd timers with --api mode to maintain always-current documentation. The MD5 change detection ensures you only process when rules actually change.

  3. Archive for Compliance: Implement a retention policy for generated PDFs. The CISO Assistant integration automates this, but even manual archiving satisfies most audit requirements.

  4. Pre-Change Visualization: Before modifying firewall rules, generate current state documentation. After changes, regenerate and diff the CSV outputs to validate intended modifications.

  5. Troubleshooting Interface Detection: When auto-detection fails (common in complex VLAN setups), explicitly define INTERFACES. The logs clearly indicate detection attempts and fallbacks.

  6. Performance Considerations: Large rule sets (500+ rules) may take several minutes. Run during maintenance windows or use backup mode for offline analysis of production configurations.


Comparison with Alternatives

Feature PyFRC2G Manual Diagramming Commercial Tools (e.g., Lucidchart) Custom Scripts
Cost Free (Open Source) Labor-intensive $$$ subscription fees Development time
pfSense Support Native, with API + XML Manual entry Generic, manual import Requires building
OPNSense Support Native, with API + XML Manual entry Generic, manual import Requires building
Auto-alias Resolution Yes, from API/XML No No Manual implementation
Change Detection Built-in MD5 comparison None None Manual implementation
Compliance Integration CISO Assistant native None None Custom development
Color-coded Output Automatic (Pass/Block/Disabled) Manual formatting Manual formatting Custom coding
Per-interface PDFs Automatic generation Painstaking Manual page creation Significant effort
Maintenance Burden Low (community maintained) Very High Medium High (self-maintained)
Learning Curve Low (Python CLI) Medium Medium High

The verdict? PyFRC2G eliminates the false choice between expensive commercial platforms and unmaintainable custom scripts. It provides enterprise-grade automation with zero licensing costs.


FAQ: Common Developer Concerns

Q: Does PyFRC2G modify my firewall configuration? A: Absolutely not. It operates in read-only mode—fetching rules via API or parsing XML backups. No write operations are performed on your firewall.

Q: Can I use this in air-gapped or offline environments? A: Yes. The --backup mode requires only a config.xml file. No network connectivity to the firewall or external services is needed.

Q: What Python versions are supported? A: Python 3.7 or higher. The package uses modern Python features while maintaining reasonable backward compatibility.

Q: How do I handle SSL certificate errors? A: The API client uses verify=False to ignore SSL verification errors—common with self-signed certificates on internal firewalls. For production hardening, consider deploying proper certificates.

Q: Can I customize the graph appearance? A: The Graphviz-based generation supports customization through the graph_generator.py module. Advanced users can modify DOT attributes for styling adjustments.

Q: Is Windows fully supported? A: Yes, with proper Graphviz installation and PATH configuration. The Python components are cross-platform.

Q: How does the MD5 change detection work? A: After each run, PyFRC2G stores an MD5 hash of the generated CSV in md5sum.txt. Subsequent runs compare against this hash—if identical, PDF generation is skipped. Delete this file to force regeneration.


Conclusion: Your Firewall Documentation Just Became Effortless

PyFRC2G represents a fundamental shift in how we approach network security documentation. What was once a tedious, error-prone manual process—guaranteed to produce outdated diagrams—is now a single-command automation that keeps pace with your evolving infrastructure.

The dual-mode architecture (API + XML backup) ensures flexibility across any operational scenario. The intelligent alias resolution eliminates cryptic internal identifiers. The color-coded, per-interface PDF outputs satisfy both engineering clarity and compliance evidence requirements. And the CISO Assistant integration transforms documentation from a reactive chore into a proactive governance pipeline.

For teams managing pfSense or OPNSense at scale, this isn't just a convenience tool—it's operational leverage. The hours reclaimed from manual diagramming compound into meaningful capacity for higher-value security work.

Ready to stop drawing firewall diagrams by hand? Head to the PyFRC2G GitHub repository, clone it, configure your first gateway, and run pyfrc2g. Your first automated flow diagram will render in minutes. Your future self—facing the next audit, the next incident, the next architecture review—will thank you.

The repository welcomes contributions. Whether you're improving visualization styling, adding new firewall platform support, or enhancing the compliance integrations, this is a community resource that grows stronger with participation. Submit a pull request, open an issue, or simply star the project to show your support.

Made with ❤️ for network administrators and security professionals—and now, made effortless for you.

Comments (0)

Comments are moderated before appearing.

No comments yet. Be the first to share your thoughts!