Example: CSV exports#
A data-centre firewall, dc, is managed with a tool that exports everything as
CSV: one file each for hosts, services, groups and the rule base. This page
reads all four into Fireman with one source, loads it from the command line
and from Python, and shows what a broken row reports.
Save these files into one folder: the source csv_source.py, the export
(hosts.csv, services.csv, groups.csv and rules.csv), bad-rules.csv, a
copy of the rule base with broken rows, and classify_csv.py, the Python
version.
csv_source.py
"""Read a data-centre firewall from CSV exports.
Four files: hosts, services and groups become global objects, and rules.csv
becomes the `inbound` policy of the firewall `dc`. Load it with
fireman load --source csv_source.dc
"""
from pathlib import Path
from typing import Annotated, Any, Literal
from pydantic import BaseModel, BeforeValidator, Field
from fireman import Source, csv_file, source
PROTOCOLS = {"icmp": 1, "tcp": 6, "udp": 17, "gre": 47, "esp": 50}
ACTIONS = {"permit": "accept", "deny": "deny"}
def split(cell: str) -> list[str]:
"""Split a semicolon-separated cell: "a; b;" gives ["a", "b"]."""
return [part.strip() for part in cell.split(";") if part.strip()]
type CellListT = Annotated[list[str], BeforeValidator(split)]
# Row schemas: the export's own columns, not Fireman's fields.
class HostRow(BaseModel):
name: str = Field(alias="Name", min_length=1)
addresses: CellListT = Field(alias="Addresses", min_length=1)
class ServiceRow(BaseModel):
name: str = Field(alias="Name", min_length=1)
ports: CellListT = Field(alias="Ports", min_length=1)
class GroupRow(BaseModel):
name: str = Field(alias="Name", min_length=1)
kind: Literal["address", "service"] = Field(alias="Type")
members: CellListT = Field(alias="Members", min_length=1)
excluded: CellListT = Field(alias="Except")
class RuleRow(BaseModel):
seq: int = Field(alias="Seq")
name: str = Field(alias="Rule Name", min_length=1)
action: Literal["permit", "deny"] = Field(alias="Action")
sources: CellListT = Field(alias="Source", min_length=1)
destinations: CellListT = Field(alias="Destination", min_length=1)
services: CellListT = Field(alias="Service", min_length=1)
comment: str = Field(alias="Comment")
# Converters: one row in, one item in Fireman's input format out.
def number(text: str, what: str) -> int:
if not text.isdecimal():
raise ValueError(f"{what} {text!r} is not a number")
return int(text)
def entry(text: str) -> dict[str, Any]:
"""Turn "tcp/443", "tcp/8000-8080", "udp", "icmp/8" or "gre" into a service entry."""
name, _, port = text.partition("/")
if name not in PROTOCOLS:
raise ValueError(f"unknown protocol {name!r} in {text!r}")
protocol = PROTOCOLS[name]
if name in ("tcp", "udp"):
low, _, high = (port or "0-65535").partition("-")
return {"protocol": protocol, "ports": [number(low, "port"), number(high or low, "port")]}
if name == "icmp":
return {"protocol": 1, "icmp_type": number(port, "ICMP type")} if port else {"protocol": 1}
if port:
raise ValueError(f"{name} has no ports: {text!r}")
return {"protocol": protocol}
def to_address(row: HostRow) -> dict[str, Any]:
return {"name": row.name, "values": row.addresses}
def to_service(row: ServiceRow) -> dict[str, Any]:
return {"name": row.name, "entries": [entry(text) for text in row.ports]}
def to_group(row: GroupRow) -> dict[str, Any]:
return {"name": row.name, "kind": row.kind, "include": row.members, "exclude": row.excluded}
def to_rule(row: RuleRow) -> dict[str, Any]:
"""A Service cell with a slash is an inline entry, anything else is a name."""
return {
"order_id": row.seq,
"name": row.name,
"action": ACTIONS[row.action],
"description": row.comment,
"sources": row.sources,
"destinations": row.destinations,
"services": [entry(text) if "/" in text else text for text in row.services],
}
def here(name: str) -> Path:
return Path(__file__).with_name(name)
@source
def dc(rules: str = "rules.csv"):
yield csv_file(here("hosts.csv"), "addresses", schema=HostRow).add_map(to_address)
yield csv_file(here("services.csv"), "services", schema=ServiceRow).add_map(to_service)
yield csv_file(here("groups.csv"), "groups", schema=GroupRow).add_map(to_group)
yield csv_file(here(rules), "rules", schema=RuleRow, firewall="dc", policy="inbound").add_map(to_rule)
def dc_bad() -> Source:
"""The same estate with bad-rules.csv, which has three broken rows."""
return dc("bad-rules.csv")
hosts.csv
Name,Addresses,Comment
dc-web,10.20.1.10;10.20.1.11,Public web servers
dc-app,10.20.3.0/24,Application tier
dc-db,10.20.2.0/24,Database subnet
mgmt,10.99.0.0/24,Jump hosts
partners,203.0.113.0/24;198.51.100.0/24,Partner networks
services.csv
Name,Ports,Comment
http,tcp/80,
https,tcp/443,
ssh,tcp/22,
postgres,tcp/5432,
dns,udp/53;tcp/53,
admin-ui,tcp/8000-8080,Appliance consoles
ping,icmp/8,Echo request
tunnels,gre;esp,Site-to-site VPN
groups.csv
Name,Type,Members,Except
web,service,http;https,
servers,address,dc-web;dc-app;dc-db,
backend,address,servers,dc-web
rules.csv
Seq,Rule Name,Action,Source,Destination,Service,Comment
10,allow-web,permit,any,dc-web,web,Public website
20,allow-partner-https,permit,partners,dc-web,https,Partner portal
30,block-partner-backend,deny,partners,backend,any,Partners never reach the backend
40,allow-app-db,permit,dc-app,dc-db,postgres,
50,allow-mgmt,permit,mgmt,servers,ssh;admin-ui;ping,Jump hosts manage every server
60,block-ssh,deny,any,servers,ssh,
70,block-telnet,deny,any,dc-web,tcp/23,Legacy scanner noise
80,allow-partner-db,permit,partners,dc-db,postgres,Reporting feed
bad-rules.csv
Seq,Rule Name,Action,Source,Destination,Service,Comment
10,allow-web,permit,any,dc-web,web,Public website
20,allow-partner-https,allow,partners,dc-web,https,Partner portal
30,allow-app-db,permit,dc-app,dc-db,tcp/postgres,
40,allow-admin,permit,mgmt,servers,tcp/70000,Typo in the port
classify_csv.py
"""Load the CSV export with the API, classify it, then load the broken variant.
Keep this file next to csv_source.py and its CSV files, and run: python classify_csv.py
"""
import click
from csv_source import dc, dc_bad
from fireman import BDDManager, LoadError, Pipeline
pipeline = Pipeline()
inventory = pipeline.load(dc())
click.echo(f"global objects: {len(inventory.objects.kinds)}")
for firewall in inventory.firewalls:
for policy in firewall.policies:
click.echo(f"{firewall.name}/{policy.name}: {len(policy.rules)} rules")
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)
click.echo(f"{entry.firewall}/{entry.policy} {finding.rule.name}: {finding.anomaly.value} ({related})")
try:
pipeline.load(dc_bad())
except LoadError as exc:
click.echo(f"bad-rules.csv: {len(exc.problems)} problems")
for problem in exc.problems:
click.echo(f" {problem}")
The export#
The tool has its own conventions, and none of them is Fireman’s:
Columns have their own names, some with spaces (
Rule Name).A cell holding several values separates them with semicolons.
Ports are written
proto/port:tcp/443,tcp/8000-8080,udp/53,icmp/8(an ICMP type) or a bare protocol name such asgre.Actions are
permitanddeny.In the rule base, a service with a slash is an inline port; anything else is a service name.
anymeans anything, as in Fireman.
Hosts become address objects. A host may have several addresses:
Name,Addresses,Comment
dc-web,10.20.1.10;10.20.1.11,Public web servers
dc-app,10.20.3.0/24,Application tier
dc-db,10.20.2.0/24,Database subnet
mgmt,10.99.0.0/24,Jump hosts
partners,203.0.113.0/24;198.51.100.0/24,Partner networks
Services:
Name,Ports,Comment
http,tcp/80,
https,tcp/443,
ssh,tcp/22,
postgres,tcp/5432,
dns,udp/53;tcp/53,
admin-ui,tcp/8000-8080,Appliance consoles
ping,icmp/8,Echo request
tunnels,gre;esp,Site-to-site VPN
Groups have a type, members and exceptions. backend is every server except
the web servers:
Name,Type,Members,Except
web,service,http;https,
servers,address,dc-web;dc-app;dc-db,
backend,address,servers,dc-web
The rule base, matched top to bottom by Seq:
Seq,Rule Name,Action,Source,Destination,Service,Comment
10,allow-web,permit,any,dc-web,web,Public website
20,allow-partner-https,permit,partners,dc-web,https,Partner portal
30,block-partner-backend,deny,partners,backend,any,Partners never reach the backend
40,allow-app-db,permit,dc-app,dc-db,postgres,
50,allow-mgmt,permit,mgmt,servers,ssh;admin-ui;ping,Jump hosts manage every server
60,block-ssh,deny,any,servers,ssh,
70,block-telnet,deny,any,dc-web,tcp/23,Legacy scanner noise
80,allow-partner-db,permit,partners,dc-db,postgres,Reporting feed
Three of these rules are mistakes, as classify will show.
The source#
Here is the whole module. It has three parts: schemas that describe the export’s rows, converters that turn a row into Fireman’s input format, and the source that ties each file to a section and a scope.
"""Read a data-centre firewall from CSV exports.
Four files: hosts, services and groups become global objects, and rules.csv
becomes the `inbound` policy of the firewall `dc`. Load it with
fireman load --source csv_source.dc
"""
from pathlib import Path
from typing import Annotated, Any, Literal
from pydantic import BaseModel, BeforeValidator, Field
from fireman import Source, csv_file, source
PROTOCOLS = {"icmp": 1, "tcp": 6, "udp": 17, "gre": 47, "esp": 50}
ACTIONS = {"permit": "accept", "deny": "deny"}
def split(cell: str) -> list[str]:
"""Split a semicolon-separated cell: "a; b;" gives ["a", "b"]."""
return [part.strip() for part in cell.split(";") if part.strip()]
type CellListT = Annotated[list[str], BeforeValidator(split)]
# Row schemas: the export's own columns, not Fireman's fields.
class HostRow(BaseModel):
name: str = Field(alias="Name", min_length=1)
addresses: CellListT = Field(alias="Addresses", min_length=1)
class ServiceRow(BaseModel):
name: str = Field(alias="Name", min_length=1)
ports: CellListT = Field(alias="Ports", min_length=1)
class GroupRow(BaseModel):
name: str = Field(alias="Name", min_length=1)
kind: Literal["address", "service"] = Field(alias="Type")
members: CellListT = Field(alias="Members", min_length=1)
excluded: CellListT = Field(alias="Except")
class RuleRow(BaseModel):
seq: int = Field(alias="Seq")
name: str = Field(alias="Rule Name", min_length=1)
action: Literal["permit", "deny"] = Field(alias="Action")
sources: CellListT = Field(alias="Source", min_length=1)
destinations: CellListT = Field(alias="Destination", min_length=1)
services: CellListT = Field(alias="Service", min_length=1)
comment: str = Field(alias="Comment")
# Converters: one row in, one item in Fireman's input format out.
def number(text: str, what: str) -> int:
if not text.isdecimal():
raise ValueError(f"{what} {text!r} is not a number")
return int(text)
def entry(text: str) -> dict[str, Any]:
"""Turn "tcp/443", "tcp/8000-8080", "udp", "icmp/8" or "gre" into a service entry."""
name, _, port = text.partition("/")
if name not in PROTOCOLS:
raise ValueError(f"unknown protocol {name!r} in {text!r}")
protocol = PROTOCOLS[name]
if name in ("tcp", "udp"):
low, _, high = (port or "0-65535").partition("-")
return {"protocol": protocol, "ports": [number(low, "port"), number(high or low, "port")]}
if name == "icmp":
return {"protocol": 1, "icmp_type": number(port, "ICMP type")} if port else {"protocol": 1}
if port:
raise ValueError(f"{name} has no ports: {text!r}")
return {"protocol": protocol}
def to_address(row: HostRow) -> dict[str, Any]:
return {"name": row.name, "values": row.addresses}
def to_service(row: ServiceRow) -> dict[str, Any]:
return {"name": row.name, "entries": [entry(text) for text in row.ports]}
def to_group(row: GroupRow) -> dict[str, Any]:
return {"name": row.name, "kind": row.kind, "include": row.members, "exclude": row.excluded}
def to_rule(row: RuleRow) -> dict[str, Any]:
"""A Service cell with a slash is an inline entry, anything else is a name."""
return {
"order_id": row.seq,
"name": row.name,
"action": ACTIONS[row.action],
"description": row.comment,
"sources": row.sources,
"destinations": row.destinations,
"services": [entry(text) if "/" in text else text for text in row.services],
}
def here(name: str) -> Path:
return Path(__file__).with_name(name)
@source
def dc(rules: str = "rules.csv"):
yield csv_file(here("hosts.csv"), "addresses", schema=HostRow).add_map(to_address)
yield csv_file(here("services.csv"), "services", schema=ServiceRow).add_map(to_service)
yield csv_file(here("groups.csv"), "groups", schema=GroupRow).add_map(to_group)
yield csv_file(here(rules), "rules", schema=RuleRow, firewall="dc", policy="inbound").add_map(to_rule)
def dc_bad() -> Source:
"""The same estate with bad-rules.csv, which has three broken rows."""
return dc("bad-rules.csv")
Row schemas#
Each schema is a pydantic model of one row, with Field(alias=...) mapping the
export’s column names to Python names. Pydantic does the routine checks, so
the converters don’t have to:
CellListTsplits a semicolon-separated cell into a list before validation, andmin_length=1rejects an empty one.Literal["permit", "deny"]rejects any other action, naming the column.seq: intaccepts the text"10", since your schema can be lenient even though Fireman’s models are not.Columns the schema doesn’t name, such as
Commentinhosts.csv, are ignored.
Converters#
Each to_* function takes a validated row and returns a dictionary laid out
exactly like an item in a YAML file. entry does the real parsing: it turns
tcp/8000-8080 into {"protocol": 6, "ports": [8000, 8080]}, icmp/8 into
{"protocol": 1, "icmp_type": 8} and gre into {"protocol": 47}. A bare
tcp or udp means every port.
Anything it can’t read raises a ValueError with a message for a person, which
becomes a problem for that row. It leaves range checks, such as whether a port
is at most 65535, to Fireman.
The structure: dc()#
dc() yields one csv_file resource per file. The three object files have no
firewall, so they become global objects. The rule base is scoped to
firewall="dc", policy="inbound". Each file is found next to the module with
Path(__file__).with_name(...), so the source works from any directory.
csv_file records each file it reads, so editing a CSV after fireman load
gives the stale-workspace warning.
dc takes the rule file as an argument with a default, so dc() reads the
real export and dc_bad() the broken copy. fireman load --source needs a
function it can call without arguments, and both qualify.
Load it from the command line#
From the folder holding the files:
fireman load --source csv_source.dc
fireman classify
Loaded workspace 'default': 1 firewalls, 1 policies, 8 rules, 16 objects.
Findings
┏━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Firewall ┃ Policy ┃ Rule ┃ Anomaly ┃ Related ┃
┡━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ dc │ inbound │ allow-partner-https (order_id 20) │ redundant │ allow-web (order_id 10) │
│ dc │ inbound │ block-ssh (order_id 60) │ correlated │ allow-mgmt (order_id 50) │
│ dc │ inbound │ allow-partner-db (order_id 80) │ shadowed │ block-partner-backend (order_id 30) │
└──────────┴─────────┴───────────────────────────────────┴────────────┴─────────────────────────────────────┘
0 of 1 firewall from cache
The 16 objects are the 5 hosts, 8 services and 3 groups. What the findings mean:
- Redundant
allow-partner-httpslets partners reach the web servers on HTTPS, butallow-webalready lets anyone do that. Deleting it changes nothing.- Correlated
block-sshdenies SSH to every server, butallow-mgmtcomes first and accepts SSH from the jump hosts. If the intent was “SSH only frommgmt”, the order is right; if it was “no SSH at all”, it isn’t.- Shadowed
allow-partner-dbis meant to let partners reach the database, butblock-partner-backendalready denies partners everything on the backend, which includesdc-db. The rule never fires.
block-telnet uses an inline tcp/23, and the converter turned it into an
entry, so it needs no service object.
Load it from Python#
classify_csv.py imports the source module, loads it, classifies it, then
tries the broken variant:
"""Load the CSV export with the API, classify it, then load the broken variant.
Keep this file next to csv_source.py and its CSV files, and run: python classify_csv.py
"""
import click
from csv_source import dc, dc_bad
from fireman import BDDManager, LoadError, Pipeline
pipeline = Pipeline()
inventory = pipeline.load(dc())
click.echo(f"global objects: {len(inventory.objects.kinds)}")
for firewall in inventory.firewalls:
for policy in firewall.policies:
click.echo(f"{firewall.name}/{policy.name}: {len(policy.rules)} rules")
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)
click.echo(f"{entry.firewall}/{entry.policy} {finding.rule.name}: {finding.anomaly.value} ({related})")
try:
pipeline.load(dc_bad())
except LoadError as exc:
click.echo(f"bad-rules.csv: {len(exc.problems)} problems")
for problem in exc.problems:
click.echo(f" {problem}")
Run it from the same folder with python classify_csv.py:
global objects: 16
dc/inbound: 8 rules
dc/inbound allow-partner-https: redundant (allow-web)
dc/inbound block-ssh: correlated (allow-mgmt)
dc/inbound allow-partner-db: shadowed (block-partner-backend)
bad-rules.csv: 3 problems
dc/inbound/rules[1].Action: Input should be 'permit' or 'deny'
dc/inbound/rules[2]: port 'postgres' is not a number
dc/inbound/rules[3].services.0.entry.port.ports: port 70000 is outside 0-65535
A broken export#
bad-rules.csv has a mistake in each of its last three rows, one for each
layer that checks it:
Seq,Rule Name,Action,Source,Destination,Service,Comment
10,allow-web,permit,any,dc-web,web,Public website
20,allow-partner-https,allow,partners,dc-web,https,Partner portal
30,allow-app-db,permit,dc-app,dc-db,tcp/postgres,
40,allow-admin,permit,mgmt,servers,tcp/70000,Typo in the port
fireman load --source csv_source.dc_bad
dc/inbound/rules[1].Action: Input should be 'permit' or 'deny'
dc/inbound/rules[2]: port 'postgres' is not a number
dc/inbound/rules[3].services.0.entry.port.ports: port 70000 is outside 0-65535
The command exits 1 and stores nothing. Every line starts with the scope and
the row’s index (from 0, so rules[1] is line 3 of the file):
- The schema
rules[1]saysallow. The path ends inAction, the export’s own column name, because the schema found it.- The converter
rules[2]hastcp/postgres.entryraised aValueError, so the message is the converter’s own, with no field path.- Fireman’s models
rules[3]hastcp/70000. The converter passed it on, and Fireman’sRulerejected it. The path is in Fireman’s format: the first service, read as a port entry.
The first row is fine, and the names in the rows are not checked yet: that happens only once every row is valid.