Compiling and classifying#

Compiling turns every rule into an exact set of packets and walks each policy once, as described in Concepts. The result answers every question on the later pages. This page compiles the sample estate, classifies it, and maps each finding back to the rule you wrote.

The full script is below; it reads estate.yaml from the current directory.

compiling.py
"""Compile the sample estate, classify every policy and map findings back to rules."""

from pathlib import Path

import click

from fireman import BDDManager, Pipeline, compile_inventory, file_source, report
from fireman.model import Anomaly, Finding, Rule, RuleId


def describe(rule: Rule) -> str:
    """A rule as one line, the way it was written."""
    services = ", ".join(s if isinstance(s, str) else s.model_dump_json() for s in rule.services)
    return f"{rule.action} {', '.join(rule.sources)} -> {', '.join(rule.destinations)} : {services}"


def listed(values: tuple[str, ...]) -> str:
    """Up to three values, then a count of the rest."""
    more = f" (+{len(values) - 3} more)" if len(values) > 3 else ""
    return ", ".join(values[:3]) + more


# The node count is a ceiling, not an allocation: oxidd grows into it.
bdd = BDDManager()
pipeline = Pipeline()

# run() is load() followed by compile_inventory(), in one manager.
compiled = pipeline.run(file_source(Path("estate.yaml")), bdd=bdd)

# The same in two steps, keeping the validated inventory. Here without the implicit
# deny, in a fresh manager: sets from different managers never mix.
inventory = pipeline.load(file_source(Path("estate.yaml")))
open_ended = compile_inventory(inventory, BDDManager(), implicit_deny=False)

click.echo("== compiled policies")
for (firewall, policy), comp in compiled.policies.items():
    click.echo(f"{firewall}/{policy}: {len(compiled.rules[firewall, policy])} rules, {len(comp.states)} states")
click.echo(f"edge/inbound without the implicit deny: {len(open_ended.policies['edge', 'inbound'].states)} states")

click.echo("== findings")
for key, comp in compiled.policies.items():
    # Findings name rules by RuleId (order_id and name), never by position. RuleId is
    # frozen and hashable, so it keys a dict straight back to the input rules.
    by_id = {RuleId(order_id=rule.order_id, name=rule.name): rule for rule in compiled.rules[key]}
    findings: tuple[Finding, ...] = comp.classify()
    click.echo(f"{'/'.join(key)}: {len(findings)} finding(s)")
    for finding in findings:
        rule = by_id[finding.rule]
        click.echo(f"  {finding.anomaly.value:<14} {report.label(finding.rule)}: {describe(rule)}")
        if finding.related:
            click.echo(f"  {'':<14} related: {', '.join(map(report.label, finding.related))}")
    shadowed = [report.label(f.rule) for f in findings if f.anomaly is Anomaly.SHADOWED]
    if shadowed:
        click.echo(f"  shadowed: {shadowed}")

click.echo("== the walk of edge/inbound")
for state in compiled.policies["edge", "inbound"].states:
    name, action = report.label(state.id), state.rule.action
    if name == "implicit deny":
        click.echo(f"  implicit deny takes the rest: {len(state.effective.rows)} row(s)")
        continue
    if state.effective.is_empty:
        click.echo(f"  {name:<20} {action:<6} never fires")
    for row in state.effective.rows:
        click.echo(
            f"  {name:<20} {action:<6} {listed(row.sources)} -> {listed(row.destinations)} : {listed(row.services)}"
        )

click.echo("== catalogs")
global_catalog = compiled.catalogs[None]
edge_catalog = compiled.catalogs["edge"]
for row in global_catalog.sets["dmz-hosts"].rows:
    click.echo(f"global dmz-hosts sources: {listed(row.sources)}")
for row in edge_catalog.sets["web-servers"].rows:
    click.echo(f"edge web-servers sources: {listed(row.sources)}")
for row in global_catalog.sets["dns"].rows:
    click.echo(f"global dns services: {listed(row.services)}")
users = sorted(global_catalog.used_by_rule["lan"])
click.echo(f"rules using global lan: {[f'{ref.firewall}/{ref.policy}/{ref.order_id}' for ref in users]}")
estate.yaml
# A small estate: one firewall, `edge`, between the internet, a DMZ and the LAN.
# The docs use it throughout. `inbound` is seeded with anomalies; `outbound` is
# clean.

addresses:
  - name: lan
    values: [10.1.0.0/16]
  - name: dmz
    values: [192.168.10.0/24]
  - name: web-servers
    values: [192.168.10.10, 192.168.10.11, 192.168.10.12]

fqdns:
  - name: update-server
    fqdn: updates.example.com
    addresses: [203.0.113.10]
    resolved_at: 2026-11-20T08:00:00Z
  - name: partner-api
    fqdn: api.partner.example
    addresses: [203.0.113.50]
    resolved_at: 2026-11-20T08:00:00Z

services:
  - name: web
    entries:
      - {protocol: 6, ports: [80, 80]}
      - {protocol: 6, ports: [443, 443]}
  - name: ssh
    entries:
      - {protocol: 6, ports: [22, 22]}
  - name: dns
    entries:
      - {protocol: 17, ports: [53, 53]}
      - {protocol: 6, ports: [53, 53]}

groups:
  # Every DMZ host except the web servers. A global group sees the global
  # `web-servers`, even inside `edge`, which has its own.
  - name: dmz-hosts
    kind: address
    include: [dmz]
    exclude: [web-servers]

firewalls:
  - name: edge
    addresses:
      # edge publishes only two of the three web servers.
      - name: web-servers
        values: [192.168.10.10, 192.168.10.11]
    policies:
      - name: inbound
        rules:
          - order_id: 10
            name: block-abusers
            action: deny
            sources: [198.51.100.0/24]
            destinations: [web-servers]
            services: [web]
          - order_id: 20
            name: allow-web
            action: accept
            sources: [any]
            destinations: [web-servers]
            services: [web]
          - order_id: 30
            name: allow-partner-https
            action: accept
            sources: [203.0.113.0/24]
            destinations: [web-servers]
            services:
              - {protocol: 6, ports: [443, 443]}
          - order_id: 40
            name: block-scanners
            action: deny
            sources: [192.0.2.0/24]
            destinations: [web-servers]
            services: [web]
          - order_id: 50
            name: allow-partner-api
            action: accept
            sources: [partner-api]
            destinations: [web-servers]
            services: [web]
          - order_id: 60
            name: allow-admin-ssh
            action: accept
            sources: [lan]
            destinations: [dmz-hosts]
            services: [ssh]
      - name: outbound
        rules:
          - order_id: 10
            name: allow-dns
            action: accept
            sources: [lan]
            destinations: [any]
            services: [dns]
          - order_id: 20
            name: allow-updates
            action: accept
            sources: [dmz-hosts]
            destinations: [update-server]
            services: [web]
          - order_id: 30
            name: allow-web-out
            action: accept
            sources: [lan]
            destinations: [lan, dmz]
            destination_negate: true
            services: [web]
          - order_id: 40
            name: allow-ping
            action: accept
            sources: [lan]
            destinations: [any]
            services:
              - {protocol: 1, icmp_type: 8}

A BDD manager#

Every traffic set lives in a BDDManager, which owns one oxidd BDD manager. BDDManager() is fine for most work; to size it yourself, pass any of three keyword arguments:

Nodes

The most BDD nodes the manager may hold. It is a ceiling, not an allocation, so a generous value costs nothing up front. Default 1 << 26, the same as the CLI.

Cache

Entries in the operation cache. Bigger can be faster on large estates, at the cost of memory. Default 1 << 20, as in the CLI.

Threads

Worker threads for oxidd. Default 1, as in the CLI.

If a manager runs out of nodes, oxidd raises oxidd.util.DDMemoryError; give it more nodes. bdd.gc() frees nodes no set uses any more and returns how many it removed. Sets from different managers can never be combined, so build everything that meets in one manager.

Compile#

# The node count is a ceiling, not an allocation: oxidd grows into it.
bdd = BDDManager()
pipeline = Pipeline()

# run() is load() followed by compile_inventory(), in one manager.
compiled = pipeline.run(file_source(Path("estate.yaml")), bdd=bdd)

# The same in two steps, keeping the validated inventory. Here without the implicit
# deny, in a fresh manager: sets from different managers never mix.
inventory = pipeline.load(file_source(Path("estate.yaml")))
open_ended = compile_inventory(inventory, BDDManager(), implicit_deny=False)

click.echo("== compiled policies")
for (firewall, policy), comp in compiled.policies.items():
    click.echo(f"{firewall}/{policy}: {len(compiled.rules[firewall, policy])} rules, {len(comp.states)} states")
click.echo(f"edge/inbound without the implicit deny: {len(open_ended.policies['edge', 'inbound'].states)} states")

Pipeline.run(*sources, bdd=..., implicit_deny=True) is load followed by compile_inventory(inventory, bdd, implicit_deny=True). Call them separately when you want to keep the inventory, compile it more than once, or compile one you built or changed yourself. With implicit_deny=False no deny-all rule is added at the end, so a policy has one state per rule.

compile_inventory returns a CompiledInventory. Its mappings are read-only:

Policies

A CompiledPolicy per (firewall, policy) key, in inventory order.

Rules

The Rule models per key, sorted by order_id, so rules[key][i] is the rule behind policies[key].states[i].

Catalogs

A Catalog per scope, keyed by firewall name or None for global: each object’s traffic set in sets, names sharing a set in by_set, and who uses each name in used_by_group and used_by_rule.

BDD

The manager every set was built in, for building more sets that meet them.

It also has request(), covered in Placing and checking requests.

Classify and map back to rules#

CompiledPolicy.classify() returns a tuple of Finding models, in rule order. A finding names its rule and its related rules by RuleId(order_id, name), never by position, and the RuleId model is hashable, so a dict maps it straight back to the Rule model you wrote:

click.echo("== findings")
for key, comp in compiled.policies.items():
    # Findings name rules by RuleId (order_id and name), never by position. RuleId is
    # frozen and hashable, so it keys a dict straight back to the input rules.
    by_id = {RuleId(order_id=rule.order_id, name=rule.name): rule for rule in compiled.rules[key]}
    findings: tuple[Finding, ...] = comp.classify()
    click.echo(f"{'/'.join(key)}: {len(findings)} finding(s)")
    for finding in findings:
        rule = by_id[finding.rule]
        click.echo(f"  {finding.anomaly.value:<14} {report.label(finding.rule)}: {describe(rule)}")
        if finding.related:
            click.echo(f"  {'':<14} related: {', '.join(map(report.label, finding.related))}")
    shadowed = [report.label(f.rule) for f in findings if f.anomaly is Anomaly.SHADOWED]
    if shadowed:
        click.echo(f"  shadowed: {shadowed}")

The helpers it uses (report.label names a rule the way the tables do):

def describe(rule: Rule) -> str:
    """A rule as one line, the way it was written."""
    services = ", ".join(s if isinstance(s, str) else s.model_dump_json() for s in rule.services)
    return f"{rule.action} {', '.join(rule.sources)} -> {', '.join(rule.destinations)} : {services}"


def listed(values: tuple[str, ...]) -> str:
    """Up to three values, then a count of the rest."""
    more = f" (+{len(values) - 3} more)" if len(values) > 3 else ""
    return ", ".join(values[:3]) + more


Anomaly is a string enum (shadowed, redundant, correlated, generalization, empty), so compare with is or print .value. A rule can have several findings, such as generalization with correlated, while an empty rule gets that one only. The implicit deny is never classified and never appears in related.

The walk itself#

policy.states holds one State per rule, plus a last one for the implicit deny. Each keeps its rule (a TrafficRule), its id (the RuleId reports use) and four traffic sets: accept and deny so far, what this rule decided (effective), and what is still unmatched (residual). An empty effective means the rule never fires.

click.echo("== the walk of edge/inbound")
for state in compiled.policies["edge", "inbound"].states:
    name, action = report.label(state.id), state.rule.action
    if name == "implicit deny":
        click.echo(f"  implicit deny takes the rest: {len(state.effective.rows)} row(s)")
        continue
    if state.effective.is_empty:
        click.echo(f"  {name:<20} {action:<6} never fires")
    for row in state.effective.rows:
        click.echo(
            f"  {name:<20} {action:<6} {listed(row.sources)} -> {listed(row.destinations)} : {listed(row.services)}"
        )

Catalogs#

A catalog answers “what does this object match?” without any rule. Address sets are on the source axis:

click.echo("== catalogs")
global_catalog = compiled.catalogs[None]
edge_catalog = compiled.catalogs["edge"]
for row in global_catalog.sets["dmz-hosts"].rows:
    click.echo(f"global dmz-hosts sources: {listed(row.sources)}")
for row in edge_catalog.sets["web-servers"].rows:
    click.echo(f"edge web-servers sources: {listed(row.sources)}")
for row in global_catalog.sets["dns"].rows:
    click.echo(f"global dns services: {listed(row.services)}")
users = sorted(global_catalog.used_by_rule["lan"])
click.echo(f"rules using global lan: {[f'{ref.firewall}/{ref.policy}/{ref.order_id}' for ref in users]}")

Note the scopes: the global dmz-hosts excludes all three global web servers, while edge’s own web-servers is just two.

Output#

== compiled policies
edge/inbound: 6 rules, 7 states
edge/outbound: 4 rules, 5 states
edge/inbound without the implicit deny: 6 states
== findings
edge/inbound: 5 finding(s)
  generalization allow-web (order_id 20): accept any -> web-servers : web
                 related: block-abusers (order_id 10)
  correlated     allow-web (order_id 20): accept any -> web-servers : web
                 related: block-abusers (order_id 10)
  redundant      allow-partner-https (order_id 30): accept 203.0.113.0/24 -> web-servers : {"protocol":6,"ports":[443,443]}
                 related: allow-web (order_id 20)
  shadowed       block-scanners (order_id 40): deny 192.0.2.0/24 -> web-servers : web
                 related: allow-web (order_id 20)
  redundant      allow-partner-api (order_id 50): accept partner-api -> web-servers : web
                 related: allow-web (order_id 20)
  shadowed: ['block-scanners (order_id 40)']
edge/outbound: 0 finding(s)
== the walk of edge/inbound
  block-abusers (order_id 10) deny   198.51.100.0/24 -> 192.168.10.10/31 : tcp 80, tcp 443
  allow-web (order_id 20) accept 0.0.0.0/1, 128.0.0.0/2, 192.0.0.0/6 (+21 more) -> 192.168.10.10/31 : tcp 80, tcp 443
  allow-partner-https (order_id 30) accept never fires
  block-scanners (order_id 40) deny   never fires
  allow-partner-api (order_id 50) accept never fires
  allow-admin-ssh (order_id 60) accept 10.1.0.0/16 -> 192.168.10.0/29, 192.168.10.8/31, 192.168.10.13/32 (+5 more) : tcp 22
  implicit deny takes the rest: 5 row(s)
== catalogs
global dmz-hosts sources: 192.168.10.0/29, 192.168.10.8/31, 192.168.10.13/32 (+5 more)
edge web-servers sources: 192.168.10.10/31
global dns services: tcp 53, udp 53
rules using global lan: ['edge/inbound/60', 'edge/outbound/10', 'edge/outbound/30', 'edge/outbound/40']

allow-web decides everything to the web servers except 198.51.100.0/24, which block-abusers took first; the formatter writes that as 24 prefixes. allow-partner-https and allow-partner-api never fire because allow-web already accepts their traffic, so both are redundant.

What run does#

        sequenceDiagram
    participant You
    participant Pipeline
    participant Compiler as compile_inventory
    participant Resolver as name resolver
    participant Policy as CompiledPolicy

    You->>Pipeline: run(source, bdd=bdd)
    Pipeline->>Pipeline: load(source) → Inventory
    Pipeline->>Compiler: compile_inventory(inventory, bdd)
    loop each firewall, each policy
        loop each rule, by order_id
            Compiler->>Resolver: traffic(firewall, rule)
            Resolver-->>Compiler: TrafficSet (names cached per scope)
        end
        Compiler->>Policy: CompiledPolicy(bdd, TrafficRules, implicit_deny)
        Policy->>Policy: walk rules into states
    end
    Compiler->>Resolver: one catalog per scope
    Compiler-->>Pipeline: CompiledInventory
    Pipeline-->>You: CompiledInventory
    You->>Policy: classify()
    Policy-->>You: Finding tuple
    

The result models#

classify, place and coverage return frozen pydantic models from fireman.model, so they dump to JSON and compare by value.

        classDiagram
    direction LR
    class Finding {
        rule: RuleId
        anomaly: Anomaly
        related: RuleId[]
    }
    class Anomaly {
        <<enumeration>>
        SHADOWED
        REDUNDANT
        CORRELATED
        GENERALIZATION
        EMPTY
    }
    class RuleId {
        order_id: int | None
        name: str | None
    }
    class Placement {
        action: accept | deny
        granted: Decision[]
        missing: Decision[]
        options: Insert or Widen[]
    }
    class Coverage {
        action: accept | deny
        covered: bool
        granted: Decision[]
        missing: Decision[]
    }
    class Decision {
        rule: RuleId | None
        traffic: FormattedTraffic[]
    }
    class Insert {
        kind = insert
        after: RuleId | None
        before: RuleId | None
        overrides: RuleId[]
        left: FormattedTraffic[]
    }
    class Widen {
        kind = widen
        rule: RuleId
        overrides: RuleId[]
        left: FormattedTraffic[]
    }
    Finding --> Anomaly
    Finding --> RuleId
    Placement *-- Decision
    Placement *-- Insert
    Placement *-- Widen
    Coverage *-- Decision
    Decision --> RuleId
    Insert --> RuleId
    Widen --> RuleId
    

RuleId(), with both fields None, is the implicit deny. A Decision with rule=None is traffic no rule decides, possible only without the implicit deny.