Sources#

A source is a group of resources that belong together, such as one export, one system or one team’s rules. It is what you hand to Fireman, from the command line or from Python.

The @source decorator#

Decorate a function that returns or yields resources. Calling it gives a Source:

"""Add a firewall `lab` to the sample estate. Its rules use estate.yaml's global objects.

fireman load estate.yaml --source lab.lab
"""

from fireman import resource, source


@resource("addresses", firewall="lab")
def lab_hosts():
    yield {"name": "test-bench", "values": ["10.1.50.0/24"]}


@resource("rules", firewall="lab", policy="inbound")
def baseline():
    yield {
        "order_id": 10,
        "name": "allow-admin-ssh",
        "action": "accept",
        "sources": ["lan"],
        "destinations": ["test-bench"],
        "services": ["ssh"],
    }
    yield {
        "order_id": 20,
        "name": "isolate-bench",
        "action": "deny",
        "sources": ["any"],
        "destinations": ["test-bench"],
        "services": ["any"],
    }


@resource("rules", firewall="lab", policy="inbound")
def requested():
    """Rules people asked for this week, kept apart from the baseline."""
    yield {
        "order_id": 30,
        "name": "allow-demo-web",
        "action": "accept",
        "sources": ["lan"],
        "destinations": ["test-bench"],
        "services": ["web"],
    }


@source
def lab():
    return baseline(), lab_hosts(), requested()

lab.py adds a firewall lab with one object and one policy. Its rules use lan, ssh and web, which it doesn’t define: they come from the global objects of the sample estate, estate.yaml. Fireman checks names only once everything is merged, so a source may rely on objects that another source or file defines.

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}

Like @resource, the function can take arguments. Source(resources) builds one directly from a tuple of resources, if you’d rather not decorate.

Several resources for one section#

baseline() and requested() both yield rules for lab/inbound. A source may hold any number of resources with the same section and scope; all of them are kept, in order. That lets you read one section from several places: the rule base plus a file of pending requests, or one CSV file per site.

The order rules are matched in is still order_id, never the order the items arrive in, so order_ids must be unique across all the resources of a policy.

Merging with files and other sources#

Pipeline.load takes any number of sources. yaml_file, json_file and file_source (which picks by suffix) turn Fireman’s own files into sources too, so a file and your code mix freely:

"""Load estate.yaml together with lab.py's source, then classify the lab firewall.

Run it from a directory holding estate.yaml, lab.py and this file: python mix.py
"""

from pathlib import Path

import click
from lab import lab

from fireman import BDDManager, Pipeline, file_source

pipeline = Pipeline()
inventory = pipeline.load(file_source(Path("estate.yaml")), lab())

for firewall in inventory.firewalls:
    for policy in firewall.policies:
        names = ", ".join(rule.name or str(rule.order_id) for rule in policy.rules)
        click.echo(f"{firewall.name}/{policy.name}: {names}")


for entry in pipeline.classify(inventory, make_bdd=BDDManager).policies:
    for finding in entry.findings:
        related = ", ".join(rule.name or str(rule.order_id) for rule in finding.related)
        suffix = f" ({related})" if related else ""
        click.echo(f"{entry.firewall}/{entry.policy} {finding.rule.name}: {finding.anomaly.value}{suffix}")

Save it as mix.py next to lab.py and estate.yaml, then run python mix.py:

edge/inbound: block-abusers, allow-web, allow-partner-https, block-scanners, allow-partner-api, allow-admin-ssh
edge/outbound: allow-dns, allow-updates, allow-web-out, allow-ping
lab/inbound: allow-admin-ssh, isolate-bench, allow-demo-web
edge/inbound allow-web: generalization (block-abusers)
edge/inbound allow-web: correlated (block-abusers)
edge/inbound allow-partner-https: redundant (allow-web)
edge/inbound block-scanners: shadowed (allow-web)
edge/inbound allow-partner-api: redundant (allow-web)
lab/inbound isolate-bench: generalization (allow-admin-ssh)
lab/inbound isolate-bench: correlated (allow-admin-ssh)
lab/inbound allow-demo-web: shadowed (isolate-bench)

lab has the classic mistake: isolate-bench denies everything to the test bench, so the later allow-demo-web never fires.

Merge order#

Every resource of every source is merged into one estate by scope:

  • Resources with the same scope and section are concatenated: sources in the order you pass them, and within a source, resources in the order it gives them.

  • Firewalls, and the policies of each firewall, are listed in the order they first appear. Reports follow that order.

  • A firewall or a policy can be split across sources and files; its parts are joined by name.

Above, estate.yaml comes first, so edge is listed before lab.

From the command line#

fireman load --source MODULE.FUNC imports the module MODULE and calls FUNC(), the same dotted path you would write in an import. The current folder is on the import path while it loads, so lab.py here is lab and can import helper modules next to it. A crash in FUNC or in the module’s own code is reported as Error: --source MODULE.FUNC: ValueError: message and exits 1.

The command line reads every --source first, then FILES, each in the order given, whatever their order on the line. The merge order above then applies, so here lab is listed before edge. Download lab.py and estate.yaml into one folder, then:

fireman load estate.yaml --source lab.lab
fireman classify
Loaded workspace 'default': 2 firewalls, 3 policies, 13 rules, 11 objects.
                                                 Findings
┏━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Firewall ┃ Policy  ┃ Rule                              ┃ Anomaly        ┃ Related                       ┃
┡━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ lab      │ inbound │ isolate-bench (order_id 20)       │ generalization │ allow-admin-ssh (order_id 10) │
│ lab      │ inbound │ isolate-bench (order_id 20)       │ correlated     │ allow-admin-ssh (order_id 10) │
│ lab      │ inbound │ allow-demo-web (order_id 30)      │ shadowed       │ isolate-bench (order_id 20)   │
│ edge     │ inbound │ allow-web (order_id 20)           │ generalization │ block-abusers (order_id 10)   │
│ edge     │ inbound │ allow-web (order_id 20)           │ correlated     │ block-abusers (order_id 10)   │
│ edge     │ inbound │ allow-partner-https (order_id 30) │ redundant      │ allow-web (order_id 20)       │
│ edge     │ inbound │ block-scanners (order_id 40)      │ shadowed       │ allow-web (order_id 20)       │
│ edge     │ inbound │ allow-partner-api (order_id 50)   │ redundant      │ allow-web (order_id 20)       │
└──────────┴─────────┴───────────────────────────────────┴────────────────┴───────────────────────────────┘
0 of 2 firewalls from cache

The findings are the same as from Python, but lab now comes first: fireman load reads every --source before the FILES, wherever they sit on the command line.

Things to know about --source:

  • FUNC is called with no arguments and must return a Source. A function with parameters needs defaults, or a small no-argument wrapper; both examples in this part have one for their broken variant.

  • --source can be repeated, and mixes with FILES.

  • The module is imported by name, with the current folder on the import path only while it loads and FUNC runs. A module elsewhere must be installed or on PYTHONPATH. Import helpers at the top of the module, not lazily inside a generator.

  • Give the module a name Python doesn’t already use. A module that is already imported wins over your file, so a local csv.py is the standard library’s csv and --source csv.dc fails with module 'csv' has no function 'dc'. Call it csv_source.py instead.

  • Find data files relative to the module, with Path(__file__).with_name("rules.csv"), not relative to the current directory, so the source works from wherever fireman runs.

  • A LoadError raised by your function is printed like any other load problem and exits 1. Any other exception is reported as Error: --source MODULE.FUNC: Type: message and exits 1.

  • Later commands warn when a loaded file has changed. Fireman watches the module’s file and every data file a resource declares in paths (csv_file does it for you, Resource.reads for your own readers; see Resources). A file your code reads without declaring it is not watched: run fireman load again after it changes.

Mistakes in MODULE.FUNC exit 2 and store nothing:

Message

Cause

Invalid value for '--source': 'lab.py:lab' must look like MODULE.FUNC

Not a dotted path

Invalid value for '--source': module 'lab' has no function 'py'

A file name instead of lab.lab

Invalid value for '--source': no module named 'labs'

The module is not importable

Invalid value for '--source': module 'lab' has no function 'labs'

FUNC is misspelled

Invalid value for '--source': lab_hosts() must return a Source, got Resource

FUNC returns something else

From Python#

Pipeline().load(*sources) returns the validated Inventory, or raises LoadError with every problem. From there, everything in Python API applies: Pipeline.classify as in mix.py above, or Pipeline.run to compile the estate in one BDD manager.

from pathlib import Path

import click
from fireman import LoadError, Pipeline, file_source
from lab import lab

try:
    inventory = Pipeline().load(file_source(Path("estate.yaml")), lab())
except LoadError as exc:
    for problem in exc.problems:
        click.echo(problem)

A Problem has the fields resource, index, loc, message and scope, so you can also sort or filter problems rather than print them.

The two worked examples put all of this together: Example: CSV exports and Example: an XML export.