Placing and checking requests#

These are the calls behind fireman place and fireman covered: is some traffic already allowed (or blocked), and if not, where does a rule go? A request is checked against one compiled policy as it stands; nothing is changed.

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

placement.py
"""Ask where new traffic fits in edge/inbound: placement, coverage and a table of requests."""

from pathlib import Path

import click
import yaml
from pydantic import TypeAdapter
from rich.console import Console

from fireman import ANY, BDDManager, FormattedTraffic, Pipeline, TrafficRule, file_source, icmp, report, tcp
from fireman.model import Insert, PlacedRequest, Placement, PlaceRequest, Widen


def flows(rows: tuple[FormattedTraffic, ...]) -> str:
    """Traffic rows as ``sources > destinations : services``."""
    return "; ".join(f"{', '.join(r.sources)} > {', '.join(r.destinations)} : {', '.join(r.services)}" for r in rows)


def show(placement: Placement) -> None:
    """Print a placement the long way, field by field."""
    for decision in placement.granted:
        click.echo(f"  granted by {report.label(decision.rule)}: {flows(decision.traffic)}")
    for decision in placement.missing:
        click.echo(f"  missing, decided by {report.label(decision.rule)}: {flows(decision.traffic)}")
    if not placement.options:
        click.echo("  nothing to do")
    for option in placement.options:
        match option:
            case Insert(after=after, before=before):
                start = report.label(after) if after else "top"
                end = report.label(before) if before else "end"
                where = f"insert after {start}, before {end}"
            case Widen(rule=rule):
                where = f"widen {report.label(rule)}"
        overrides = ", ".join(map(report.label, option.overrides)) or "nothing"
        left = flows(option.left) or "nothing"
        click.echo(f"  option: {where}; overrides {overrides}; left {left}")


bdd = BDDManager()
compiled = Pipeline().run(file_source(Path("estate.yaml")), bdd=bdd)
inbound = compiled.policies["edge", "inbound"]

# Names resolve as they would in a rule of edge: its own web-servers, the global lan.
https = compiled.request("edge", ["198.51.100.0/24"], ["web-servers"], [tcp(443)])
click.echo(f"request: {flows(https.rows)}")
click.echo("== accept HTTPS from a range block-abusers denies")
show(inbound.place(TrafficRule("accept", https)))

click.echo("== accept ping and SSH from the LAN to one DMZ host")
admin = compiled.request("edge", ["lan"], ["192.168.10.20"], [icmp(8), "ssh"])
show(inbound.place(TrafficRule("accept", admin)))

click.echo("== deny web traffic from 192.0.2.0/24")
scanners = TrafficRule("deny", compiled.request("edge", ["192.0.2.0/24"], ["web-servers"], ["web"]))
show(inbound.place(scanners))

click.echo("== coverage")
anyone_web = TrafficRule("accept", compiled.request("edge", [ANY], ["web-servers"], ["web"]))
coverage = inbound.coverage(anyone_web)
click.echo(f"web from anywhere covered: {coverage.covered} (is_covered: {inbound.is_covered(anyone_web)})")
for decision in coverage.granted:
    click.echo(f"  granted by {report.label(decision.rule)}")
for decision in coverage.missing:
    click.echo(f"  missing, decided by {report.label(decision.rule)}: {flows(decision.traffic)}")
admin_ssh = TrafficRule("accept", compiled.request("edge", ["lan"], ["dmz-hosts"], ["ssh"]))
click.echo(f"ssh from lan to dmz-hosts covered: {inbound.is_covered(admin_ssh)}")

click.echo("== bad requests")
try:
    compiled.request("core", ["lan"], ["dmz"], ["ssh"])
except KeyError as exc:
    click.echo(f"KeyError: unknown firewall {exc}")
try:
    compiled.request("edge", ["lab", "ssh"], ["dmz"], ["http"])
except ValueError as exc:
    click.echo(f"ValueError, one line per bad value: {len(str(exc).splitlines())} lines")

click.echo("== requests.yaml as a table")
requests = TypeAdapter(list[PlaceRequest]).validate_python(
    yaml.safe_load(Path("requests.yaml").read_text(encoding="utf-8"))
)
placed = []
for item in requests:
    traffic = compiled.request("edge", item.sources, item.destinations, item.services)
    placement = inbound.place(TrafficRule(item.action or "accept", traffic))
    placed.append(PlacedRequest(name=item.name, placement=placement))
Console().print(report.to_place_table(tuple(placed)))
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}
requests.yaml
# Requests against edge/inbound, for `fireman place` and `fireman covered`.
- name: partner-https
  action: accept
  sources: [203.0.113.0/24]
  destinations: [web-servers]
  services:
    - {protocol: 6, ports: [443, 443]}
- name: admin-ssh
  action: accept
  sources: [lan]
  destinations: [dmz-hosts]
  services: [ssh]
- name: monitoring-ping
  action: accept
  sources: [10.1.20.0/24]
  destinations: [dmz]
  services:
    - {protocol: 1, icmp_type: 8}
- name: block-scanners
  action: deny
  sources: [192.0.2.0/24]
  destinations: [web-servers]
  services: [web]

From values to a request#

CompiledInventory.request(firewall, sources, destinations, services) turns values into one TrafficSet in the inventory’s own manager, so it can meet the compiled rules:

Sources and destinations

ANY, a name visible from firewall (its own objects first, then global ones, as in its rules), or an address literal such as "10.1.2.3" or "10.1.0.0/16". A name wins over a literal that looks the same.

Services

ANY, a visible service name, or a service entry: tcp(443), udp(53), tcp(8000, 8080), icmp(8), icmp(3, 4), or any PortEntry, IcmpEntry or ProtocolEntry model.

Each list is a union, and the three are intersected, just like a rule. Wrap the result in TrafficRule(action, traffic) to get a request the policy can answer.

bdd = BDDManager()
compiled = Pipeline().run(file_source(Path("estate.yaml")), bdd=bdd)
inbound = compiled.policies["edge", "inbound"]

# Names resolve as they would in a rule of edge: its own web-servers, the global lan.
https = compiled.request("edge", ["198.51.100.0/24"], ["web-servers"], [tcp(443)])
click.echo(f"request: {flows(https.rows)}")
click.echo("== accept HTTPS from a range block-abusers denies")
show(inbound.place(TrafficRule("accept", https)))

request raises KeyError for an unknown firewall. Every bad value (an unknown name, a name of the wrong kind, an invalid literal) is collected into one ValueError, one field: message line per value:

click.echo("== bad requests")
try:
    compiled.request("core", ["lan"], ["dmz"], ["ssh"])
except KeyError as exc:
    click.echo(f"KeyError: unknown firewall {exc}")
try:
    compiled.request("edge", ["lab", "ssh"], ["dmz"], ["http"])
except ValueError as exc:
    click.echo(f"ValueError, one line per bad value: {len(str(exc).splitlines())} lines")

Placement#

CompiledPolicy.place(rule) returns a Placement model:

Granted

Decision(rule, traffic) entries for the parts of the request that already get the action, one per deciding rule.

Missing

The same for the parts that don’t. rule is RuleId() for the implicit deny, and None for traffic no rule decides (only with implicit_deny=False).

Options

Ways to grant the missing part, best first: whole request granted, then fewest overrides, then widen before insert, then policy order. Empty when nothing is missing.

Each option is an Insert or a Widen model, told apart by kind or with match:

Insert(after, before)

Add a new rule anywhere between rule after and rule before; every spot in that band has the same effect. after=None is the top, before=None the end.

Widen(rule)

Add the request’s sources, destinations and services to an existing rule with the same action. Only offered when that adds no traffic beyond the request, and never for an empty rule or one with a negated list.

Both carry overrides, the explicit rules that would lose traffic to the change (check these: overriding a deny opens what someone closed), and left, the part of the request still not granted afterwards. Traffic in decisions and in left is already formatted as rows of sources, destinations and services.

def flows(rows: tuple[FormattedTraffic, ...]) -> str:
    """Traffic rows as ``sources > destinations : services``."""
    return "; ".join(f"{', '.join(r.sources)} > {', '.join(r.destinations)} : {', '.join(r.services)}" for r in rows)


def show(placement: Placement) -> None:
    """Print a placement the long way, field by field."""
    for decision in placement.granted:
        click.echo(f"  granted by {report.label(decision.rule)}: {flows(decision.traffic)}")
    for decision in placement.missing:
        click.echo(f"  missing, decided by {report.label(decision.rule)}: {flows(decision.traffic)}")
    if not placement.options:
        click.echo("  nothing to do")
    for option in placement.options:
        match option:
            case Insert(after=after, before=before):
                start = report.label(after) if after else "top"
                end = report.label(before) if before else "end"
                where = f"insert after {start}, before {end}"
            case Widen(rule=rule):
                where = f"widen {report.label(rule)}"
        overrides = ", ".join(map(report.label, option.overrides)) or "nothing"
        left = flows(option.left) or "nothing"
        click.echo(f"  option: {where}; overrides {overrides}; left {left}")


click.echo("== accept ping and SSH from the LAN to one DMZ host")
admin = compiled.request("edge", ["lan"], ["192.168.10.20"], [icmp(8), "ssh"])
show(inbound.place(TrafficRule("accept", admin)))

click.echo("== deny web traffic from 192.0.2.0/24")
scanners = TrafficRule("deny", compiled.request("edge", ["192.0.2.0/24"], ["web-servers"], ["web"]))
show(inbound.place(scanners))

Coverage#

coverage(rule) is place without the options, so it is cheaper: a Coverage(action, covered, granted, missing) model. is_covered(rule) is just the yes or no. Both ignore traffic outside the policy’s universe. Neither needs the request to be in the policy.

click.echo("== coverage")
anyone_web = TrafficRule("accept", compiled.request("edge", [ANY], ["web-servers"], ["web"]))
coverage = inbound.coverage(anyone_web)
click.echo(f"web from anywhere covered: {coverage.covered} (is_covered: {inbound.is_covered(anyone_web)})")
for decision in coverage.granted:
    click.echo(f"  granted by {report.label(decision.rule)}")
for decision in coverage.missing:
    click.echo(f"  missing, decided by {report.label(decision.rule)}: {flows(decision.traffic)}")
admin_ssh = TrafficRule("accept", compiled.request("edge", ["lan"], ["dmz-hosts"], ["ssh"]))
click.echo(f"ssh from lan to dmz-hosts covered: {inbound.is_covered(admin_ssh)}")

Many requests and a table#

PlaceRequest is the model of one entry in a requests file. Validate a list of them, resolve each, and wrap the answers in PlacedRequest(name, placement) models for report.to_place_table, the table fireman place prints. A request’s action may be None, meaning “use the default”, so the script falls back to accept.

click.echo("== requests.yaml as a table")
requests = TypeAdapter(list[PlaceRequest]).validate_python(
    yaml.safe_load(Path("requests.yaml").read_text(encoding="utf-8"))
)
placed = []
for item in requests:
    traffic = compiled.request("edge", item.sources, item.destinations, item.services)
    placement = inbound.place(TrafficRule(item.action or "accept", traffic))
    placed.append(PlacedRequest(name=item.name, placement=placement))
Console().print(report.to_place_table(tuple(placed)))

For covered, wrap Coverage results in CoveredRequest(name, coverage) models and use report.to_covered_table. report.to_json and report.to_yaml take either tuple too, with the traffic of every decision in full.

Output#

request: 198.51.100.0/24 > 192.168.10.10/31 : tcp 443
== accept HTTPS from a range block-abusers denies
  missing, decided by block-abusers (order_id 10): 198.51.100.0/24 > 192.168.10.10/31 : tcp 443
  option: insert after top, before block-abusers (order_id 10); overrides block-abusers (order_id 10); left nothing
== accept ping and SSH from the LAN to one DMZ host
  granted by allow-admin-ssh (order_id 60): 10.1.0.0/16 > 192.168.10.20/32 : tcp 22
  missing, decided by implicit deny: 10.1.0.0/16 > 192.168.10.20/32 : icmp type 8
  option: insert after top, before allow-admin-ssh (order_id 60); overrides nothing; left nothing
  option: insert after allow-admin-ssh (order_id 60), before end; overrides nothing; left nothing
== deny web traffic from 192.0.2.0/24
  missing, decided by allow-web (order_id 20): 192.0.2.0/24 > 192.168.10.10/31 : tcp 80, tcp 443
  option: widen block-abusers (order_id 10); overrides allow-web (order_id 20); left nothing
  option: insert after top, before allow-web (order_id 20); overrides allow-web (order_id 20); left nothing
== coverage
web from anywhere covered: False (is_covered: False)
  granted by allow-web (order_id 20)
  missing, decided by block-abusers (order_id 10): 198.51.100.0/24 > 192.168.10.10/31 : tcp 80, tcp 443
ssh from lan to dmz-hosts covered: True
== bad requests
KeyError: unknown firewall 'core'
ValueError, one line per bad value: 3 lines
== requests.yaml as a table
                                                       Placement
┏━━━━━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━┳━━━━━━┓
┃ Request         ┃ Action ┃ Granted            ┃ Missing            ┃ Option              ┃ Overrides          ┃ Left ┃
┡━━━━━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━╇━━━━━━┩
│ partner-https   │ accept │ allow-web          │                    │ none needed         │                    │      │
│                 │        │ (order_id 20)      │                    │                     │                    │      │
│ admin-ssh       │ accept │ allow-admin-ssh    │                    │ none needed         │                    │      │
│                 │        │ (order_id 60)      │                    │                     │                    │      │
│ monitoring-ping │ accept │                    │ implicit deny      │ insert after top,   │                    │      │
│                 │        │                    │                    │ before end          │                    │      │
│ block-scanners  │ deny   │                    │ allow-web          │ widen block-abusers │ allow-web          │      │
│                 │        │                    │ (order_id 20)      │ (order_id 10)       │ (order_id 20)      │      │
│                 │        │                    │                    │ insert after top,   │ allow-web          │      │
│                 │        │                    │                    │ before allow-web    │ (order_id 20)      │      │
│                 │        │                    │                    │ (order_id 20)       │                    │      │
└─────────────────┴────────┴────────────────────┴────────────────────┴─────────────────────┴────────────────────┴──────┘

A few things to read off it:

  • HTTPS from 198.51.100.0/24 can only be allowed by a new rule above block-abusers, which then loses that traffic.

  • For ping and SSH to 192.168.10.20, SSH is already granted by allow-admin-ssh. Widening that rule with ICMP is not offered, because the rule covers all of dmz-hosts, so it would also allow ping to every other host.

  • Blocking 192.0.2.0/24 can widen block-abusers (adding the range to its sources adds nothing else), or insert a deny above allow-web. Both override allow-web; widening comes first since it adds no rule.

  • Web traffic from anywhere is not covered: block-abusers denies part of it.

The flow#

        sequenceDiagram
    participant You
    participant CI as CompiledInventory
    participant Policy as CompiledPolicy

    You->>CI: request(firewall, sources, destinations, services)
    alt unknown firewall
        CI-->>You: raise KeyError
    else bad values
        CI-->>You: raise ValueError (one line per value)
    else
        CI-->>You: TrafficSet (in CI.bdd)
    end
    You->>You: TrafficRule(action, traffic)
    You->>Policy: place(rule)
    Policy->>Policy: split the request by deciding state
    Policy->>Policy: one Insert per band, Widen per same-action rule
    Policy->>Policy: rank options
    Policy-->>You: Placement
    You->>Policy: coverage(rule) / is_covered(rule)
    Policy-->>You: Coverage / bool
    

The CLI compiles only the chosen policy for each run, from an inventory with the global objects and that one firewall holding that one policy. Do the same when your estate is large and you only need one policy: build that Inventory model and pass it to compile_inventory.