Traffic sets by hand#
Under every rule, request and object is a TrafficSet: an exact set of
packets, stored as one BDD over four axes (source and destination address,
port, protocol). You can build and combine sets yourself, and even walk a
policy that never came from an inventory. That is handy for tests, for
rules from a source Fireman can’t read, and for questions the CLI doesn’t ask.
The full script is below; it reads no files.
traffic_sets.py
"""Traffic sets by hand: build, combine and inspect them, then walk a policy with no inventory."""
from functools import partial
from ipaddress import IPv4Address, IPv4Network
import click
from fireman import (
ANY,
ICMP_ANY,
TCP_ANY,
UDP_ANY,
BDDManager,
CompiledPolicy,
TrafficRule,
icmp,
report,
tcp,
traffic,
udp,
)
from fireman.model import Insert, ProtocolEntry, RuleId, TrafficSet, Widen
def show(title: str, traffic_set: TrafficSet) -> None:
"""Print a set as formatted rows, or say it is empty."""
click.echo(f"{title}:")
if traffic_set.is_empty:
click.echo(" (empty)")
for row in traffic_set.rows:
click.echo(f" {', '.join(row.sources)} > {', '.join(row.destinations)} : {', '.join(row.services)}")
# A small manager is plenty for hand-built sets. Every set below comes from it.
bdd = BDDManager(nodes=1 << 20, cache=1 << 16, threads=1)
everything = TrafficSet.everything(bdd)
nothing = TrafficSet.nothing(bdd)
show("everything", everything)
show("nothing", nothing)
# from_blocks takes validated values: ipaddress objects and service entries, or ANY.
dns = TrafficSet.from_blocks(
bdd,
[IPv4Network("10.1.0.0/16")],
[IPv4Address("192.168.10.53")],
[udp(53), tcp(53)],
)
show("from_blocks", dns)
# traffic() parses CIDR strings for you; bind the manager once.
flow = partial(traffic, bdd)
web = flow(["10.1.0.0/16"], ["192.168.10.0/24"], tcp(80), tcp(443))
ssh = flow(["10.1.0.0/16"], ["192.168.10.0/24"], tcp(22))
admin_net = flow(["10.1.5.0/24"], [ANY], ANY)
show("web | ssh", web | ssh)
show("web & admin_net", web & admin_net)
show("web - admin_net", web - admin_net)
click.echo(f"(web & ssh).is_empty: {(web & ssh).is_empty}")
click.echo(f"web is inside web | ssh: {(web - (web | ssh)).is_empty}")
show("(web - admin_net).project('src')", (web - admin_net).project("src"))
show("web.project('service')", web.project("service"))
# widen() adds another set's values to each field, like editing a rule.
ping = flow(["10.2.0.0/16"], ["192.168.10.0/24"], icmp(8))
show("web.widen(ping)", web.widen(ping))
show("web | ping (for comparison)", web | ping)
# Whole protocols: the *_ANY constants, and ProtocolEntry for protocols without ports.
gre = ProtocolEntry(protocol=47)
show("whole protocols to one host", flow([ANY], ["192.168.10.5"], TCP_ANY, UDP_ANY, ICMP_ANY, gre))
# A port range with tcp(lo, hi), and one ICMP code with icmp(type, code): 3/4 is "fragmentation needed".
show("a port range and one ICMP code", flow(["10.1.0.0/16"], ["192.168.10.5"], tcp(8000, 8080), icmp(3, 4)))
# A policy with no inventory: TrafficRules in order, each with an optional RuleId.
rules = (
TrafficRule("deny", flow(["10.1.5.0/24"], ["192.168.10.0/24"], tcp(22)), id=RuleId(order_id=10, name="no-ssh")),
TrafficRule("accept", flow(["10.1.0.0/16"], ["192.168.10.0/24"], tcp(22)), id=RuleId(order_id=20, name="ssh")),
TrafficRule("accept", flow(["10.1.5.0/24"], ["192.168.10.0/24"], tcp(22)), id=RuleId(order_id=30)),
TrafficRule("accept", flow(["10.1.0.0/16"], ["192.168.10.0/24"], tcp(80), tcp(443))),
)
policy = CompiledPolicy(bdd, rules)
click.echo("== states")
for state in policy.states:
# The fourth rule was built without an id: the walk gave it its position, order_id 4.
click.echo(f" {report.label(state.id)}: {state.rule.action}, fires: {not state.effective.is_empty}")
click.echo("== classify")
for finding in policy.classify():
click.echo(
f" {report.label(finding.rule)} {finding.anomaly.value}, related {[report.label(r) for r in finding.related]}"
)
click.echo("== place")
request = TrafficRule("accept", flow(["10.1.5.7"], ["192.168.10.9"], tcp(22)))
placement = policy.place(request)
click.echo(f" covered: {policy.is_covered(request)}")
click.echo(f" missing: {[report.label(decision.rule) for decision in placement.missing]}")
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)}"
click.echo(f" {where}, overrides {[report.label(r) for r in option.overrides]}")
# universe limits the traffic the walk starts from; without the implicit deny,
# what no rule matches stays undecided.
lan_tcp = CompiledPolicy(bdd, rules, universe=flow(["10.1.0.0/16"], ["192.168.10.0/24"], TCP_ANY), implicit_deny=False)
show("undecided LAN to DMZ TCP", lan_tcp.states[-1].residual)
coverage = lan_tcp.coverage(TrafficRule("accept", flow(["10.1.9.9"], ["192.168.10.9"], tcp(8080))))
click.echo(f"tcp 8080 covered: {coverage.covered}, missing: {[report.label(d.rule) for d in coverage.missing]}")
Building sets#
from functools import partial
from ipaddress import IPv4Address, IPv4Network
import click
from fireman import (
ANY,
ICMP_ANY,
TCP_ANY,
UDP_ANY,
BDDManager,
CompiledPolicy,
TrafficRule,
icmp,
report,
tcp,
traffic,
udp,
)
from fireman.model import Insert, ProtocolEntry, RuleId, TrafficSet, Widen
def show(title: str, traffic_set: TrafficSet) -> None:
"""Print a set as formatted rows, or say it is empty."""
click.echo(f"{title}:")
if traffic_set.is_empty:
click.echo(" (empty)")
for row in traffic_set.rows:
click.echo(f" {', '.join(row.sources)} > {', '.join(row.destinations)} : {', '.join(row.services)}")
# A small manager is plenty for hand-built sets. Every set below comes from it.
bdd = BDDManager(nodes=1 << 20, cache=1 << 16, threads=1)
everything = TrafficSet.everything(bdd)
nothing = TrafficSet.nothing(bdd)
show("everything", everything)
show("nothing", nothing)
# from_blocks takes validated values: ipaddress objects and service entries, or ANY.
dns = TrafficSet.from_blocks(
bdd,
[IPv4Network("10.1.0.0/16")],
[IPv4Address("192.168.10.53")],
[udp(53), tcp(53)],
)
show("from_blocks", dns)
Every set is built in a BDDManager (see Compiling and classifying for sizing) and
keeps a reference to it. There are three constructors:
TrafficSet.everything(bdd)All traffic.
TrafficSet.nothing(bdd)The empty set.
TrafficSet.from_blocks(bdd, sources, destinations, services)Each argument is a sequence, and the set is the union within each axis, intersected across axes. Sources and destinations are
IPv4AddressorIPv4Networkvalues, services are entries (PortEntry,IcmpEntry,ProtocolEntry).ANYin a sequence leaves that axis free. An empty sequence is an empty union, so the result is empty.
from_blocks takes values that are already validated. To write sets from
strings, use the traffic(bdd, sources, destinations, *services) builder:
addresses are CIDR strings parsed strictly as networks (a bare address is a
/32, host bits set raise ValueError), and services follow as arguments.
Bind the manager once with functools.partial, as the script does with
flow = partial(traffic, bdd), and every later call reads like
flow(["10.1.0.0/16"], ["192.168.10.0/24"], tcp(22)).
The service builders return entries:
tcp(lo, hi=None),udp(lo, hi=None)One port, or the range
lotohi.icmp(icmp_type=None, icmp_code=None)One ICMP type, optionally one code; no arguments is all of ICMP.
TCP_ANY,UDP_ANY,ICMP_ANYEvery TCP port, every UDP port, all of ICMP.
ProtocolEntry(protocol=N)A protocol without ports, such as GRE (47) or ESP (50).
ANYThe string
"any": every address, or every service.
Fireman is IPv4 only, so IPv6 addresses and IPv6-only protocols are rejected.
Combining and inspecting#
# traffic() parses CIDR strings for you; bind the manager once.
flow = partial(traffic, bdd)
web = flow(["10.1.0.0/16"], ["192.168.10.0/24"], tcp(80), tcp(443))
ssh = flow(["10.1.0.0/16"], ["192.168.10.0/24"], tcp(22))
admin_net = flow(["10.1.5.0/24"], [ANY], ANY)
show("web | ssh", web | ssh)
show("web & admin_net", web & admin_net)
show("web - admin_net", web - admin_net)
click.echo(f"(web & ssh).is_empty: {(web & ssh).is_empty}")
click.echo(f"web is inside web | ssh: {(web - (web | ssh)).is_empty}")
show("(web - admin_net).project('src')", (web - admin_net).project("src"))
show("web.project('service')", web.project("service"))
# widen() adds another set's values to each field, like editing a rule.
ping = flow(["10.2.0.0/16"], ["192.168.10.0/24"], icmp(8))
show("web.widen(ping)", web.widen(ping))
show("web | ping (for comparison)", web | ping)
# Whole protocols: the *_ANY constants, and ProtocolEntry for protocols without ports.
gre = ProtocolEntry(protocol=47)
show("whole protocols to one host", flow([ANY], ["192.168.10.5"], TCP_ANY, UDP_ANY, ICMP_ANY, gre))
# A port range with tcp(lo, hi), and one ICMP code with icmp(type, code): 3/4 is "fragmentation needed".
show("a port range and one ICMP code", flow(["10.1.0.0/16"], ["192.168.10.5"], tcp(8000, 8080), icmp(3, 4)))
a | b,a & b,a - bUnion, intersection and difference, also as
union,intersectionanddifference. Both sets must come from the same manager, orValueError.is_emptyWhether the set holds no traffic. Test this, not
== nothing. Subset tests are differences:(a - b).is_emptymeansais insideb.project(axis)Keep one axis (
"src","dst"or"service", which is port and protocol together) and free the others. Exact for a set that is a product of axes, as everyfrom_blocksset and every single rule is; not for a union of several rules.widen(other)Add
other’s values to each axis, as if you added them to a rule’s fields. The result can be larger thanself | other, as the output shows: the new source also gets the old services.rowsThe set formatted as rows with
sources,destinationsandserviceslists, merged so there are few of them. Computed once per set.repr(set)shows the same.
Sets compare and hash by their BDD node, so two sets with the same traffic are equal however they were built.
A policy with no inventory#
CompiledPolicy(bdd, rules, universe=None, implicit_deny=True) takes
TrafficRule(action, traffic, id=None, negated=False) tuples in policy order
and walks them at once. id is the RuleId model that findings and placements
use; negated marks a rule with a negated list, which is never widened.
Note
A rule without an id is named by its 1-based position in rules: the third
rule becomes RuleId(order_id=3), shown as order_id 3. Findings,
placements and its state’s id all use that, so report.label(state.id)
reads like a report. Give rules an id when their position isn’t their
order_id, or the names won’t match your firewall.
# A policy with no inventory: TrafficRules in order, each with an optional RuleId.
rules = (
TrafficRule("deny", flow(["10.1.5.0/24"], ["192.168.10.0/24"], tcp(22)), id=RuleId(order_id=10, name="no-ssh")),
TrafficRule("accept", flow(["10.1.0.0/16"], ["192.168.10.0/24"], tcp(22)), id=RuleId(order_id=20, name="ssh")),
TrafficRule("accept", flow(["10.1.5.0/24"], ["192.168.10.0/24"], tcp(22)), id=RuleId(order_id=30)),
TrafficRule("accept", flow(["10.1.0.0/16"], ["192.168.10.0/24"], tcp(80), tcp(443))),
)
policy = CompiledPolicy(bdd, rules)
click.echo("== states")
for state in policy.states:
# The fourth rule was built without an id: the walk gave it its position, order_id 4.
click.echo(f" {report.label(state.id)}: {state.rule.action}, fires: {not state.effective.is_empty}")
click.echo("== classify")
for finding in policy.classify():
click.echo(
f" {report.label(finding.rule)} {finding.anomaly.value}, related {[report.label(r) for r in finding.related]}"
)
click.echo("== place")
request = TrafficRule("accept", flow(["10.1.5.7"], ["192.168.10.9"], tcp(22)))
placement = policy.place(request)
click.echo(f" covered: {policy.is_covered(request)}")
click.echo(f" missing: {[report.label(decision.rule) for decision in placement.missing]}")
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)}"
click.echo(f" {where}, overrides {[report.label(r) for r in option.overrides]}")
# universe limits the traffic the walk starts from; without the implicit deny,
# what no rule matches stays undecided.
lan_tcp = CompiledPolicy(bdd, rules, universe=flow(["10.1.0.0/16"], ["192.168.10.0/24"], TCP_ANY), implicit_deny=False)
show("undecided LAN to DMZ TCP", lan_tcp.states[-1].residual)
coverage = lan_tcp.coverage(TrafficRule("accept", flow(["10.1.9.9"], ["192.168.10.9"], tcp(8080))))
click.echo(f"tcp 8080 covered: {coverage.covered}, missing: {[report.label(d.rule) for d in coverage.missing]}")
universe limits the traffic the walk starts with, so the first residual is
the universe instead of all traffic, and place, coverage and is_covered only look at
the part of a request inside it. With implicit_deny=False, what no rule
matches stays undecided: it
is left in the last state’s residual and shows up in missing with
rule=None.
report.label turns a RuleId into the name the tables use, implicit deny and
undecided included:
def show(title: str, traffic_set: TrafficSet) -> None:
"""Print a set as formatted rows, or say it is empty."""
click.echo(f"{title}:")
if traffic_set.is_empty:
click.echo(" (empty)")
for row in traffic_set.rows:
click.echo(f" {', '.join(row.sources)} > {', '.join(row.destinations)} : {', '.join(row.services)}")
Output#
everything:
0.0.0.0/0 > 0.0.0.0/0 : any
nothing:
(empty)
from_blocks:
10.1.0.0/16 > 192.168.10.53/32 : tcp 53, udp 53
web | ssh:
10.1.0.0/16 > 192.168.10.0/24 : tcp 22, tcp 80, tcp 443
web & admin_net:
10.1.5.0/24 > 192.168.10.0/24 : tcp 80, tcp 443
web - admin_net:
10.1.0.0/22, 10.1.4.0/24, 10.1.6.0/23, 10.1.8.0/21, 10.1.16.0/20, 10.1.32.0/19, 10.1.64.0/18, 10.1.128.0/17 > 192.168.10.0/24 : tcp 80, tcp 443
(web & ssh).is_empty: True
web is inside web | ssh: True
(web - admin_net).project('src'):
10.1.0.0/22, 10.1.4.0/24, 10.1.6.0/23, 10.1.8.0/21, 10.1.16.0/20, 10.1.32.0/19, 10.1.64.0/18, 10.1.128.0/17 > 0.0.0.0/0 : any
web.project('service'):
0.0.0.0/0 > 0.0.0.0/0 : tcp 80, tcp 443
web.widen(ping):
10.1.0.0/16, 10.2.0.0/16 > 192.168.10.0/24 : icmp type 8, tcp 80, tcp 443
web | ping (for comparison):
10.1.0.0/16 > 192.168.10.0/24 : tcp 80, tcp 443
10.2.0.0/16 > 192.168.10.0/24 : icmp type 8
whole protocols to one host:
0.0.0.0/0 > 192.168.10.5/32 : icmp, tcp, udp, gre
a port range and one ICMP code:
10.1.0.0/16 > 192.168.10.5/32 : icmp type 3 code 4, tcp 8000-8080
== states
no-ssh (order_id 10): deny, fires: True
ssh (order_id 20): accept, fires: True
order_id 30: accept, fires: False
order_id 4: accept, fires: True
implicit deny: deny, fires: True
== classify
ssh (order_id 20) generalization, related ['no-ssh (order_id 10)']
ssh (order_id 20) correlated, related ['no-ssh (order_id 10)']
order_id 30 shadowed, related ['no-ssh (order_id 10)']
== place
covered: False
missing: ['no-ssh (order_id 10)']
insert after top, before no-ssh (order_id 10), overrides ['no-ssh (order_id 10)']
undecided LAN to DMZ TCP:
10.1.0.0/16 > 192.168.10.0/24 : tcp 0-21, tcp 23-79, tcp 81-442, tcp 444-65535
tcp 8080 covered: False, missing: ['undecided']
Addresses are never shortened: web - admin_net is written as the eight
prefixes that make up 10.1.0.0/16 without 10.1.5.0/24.