Example: an XML export#
A branch office firewall, branch, comes from a management system that
exports XML. The format below is made up for this page, but it has what real
exports have: object sections, nested firewalls with their own objects, one
ruleset per policy, and inline values in rules. This page reads it with the
standard library’s xml.etree.ElementTree, loads it from the command line and
from Python, and shows how broken elements and broken files are reported.
Save these files into one folder: the source xml_source.py, the export
export.xml, bad-export.xml, a copy with broken elements, and
classify_xml.py, the Python version.
xml_source.py
"""Read a site firewall from a fictional XML policy export.
The export holds global <addresses>, <services> and <groups>, then one
<device> per firewall with its own object sections and one <ruleset> per
policy. Load it with
fireman load --source xml_source.branch
"""
import functools
import xml.etree.ElementTree as ET
from collections.abc import Iterator
from pathlib import Path
from typing import Any
from fireman import LoadError, Resource, Source, source
from fireman.model import Problem
VERDICTS = {"allow": "accept", "block": "deny"}
def describe(el: ET.Element) -> str:
"""Name an element in messages: <host name="nas">, or just <tcp>."""
name = el.get("name")
return f'<{el.tag} name="{name}">' if name else f"<{el.tag}>"
def attr(el: ET.Element, key: str) -> str:
value = el.get(key)
if value is None:
raise ValueError(f"{describe(el)} has no {key!r} attribute")
return value
def number(el: ET.Element, key: str, text: str | None = None) -> int:
text = attr(el, key) if text is None else text
if not text.isdecimal():
raise ValueError(f"{describe(el)} {key} {text!r} is not a number")
return int(text)
def texts(el: ET.Element, tag: str) -> list[str]:
return [(child.text or "").strip() for child in el.iterfind(tag)]
# Converters: one element in, one item in Fireman's input format out.
def entry(el: ET.Element) -> dict[str, Any]:
"""A service entry: <tcp port="443"/>, <udp port="1-1024"/>, <icmp type="8"/>, <proto number="50"/>."""
match el.tag:
case "tcp" | "udp":
low, _, high = attr(el, "port").partition("-")
protocol = 6 if el.tag == "tcp" else 17
return {"protocol": protocol, "ports": [number(el, "port", low), number(el, "port", high or low)]}
case "icmp":
found = {key: number(el, key) for key in ("type", "code") if key in el.attrib}
return {"protocol": 1, **{f"icmp_{key}": value for key, value in found.items()}}
case "proto":
return {"protocol": number(el, "number")}
raise ValueError(f"unknown service entry {describe(el)}")
def to_address(el: ET.Element) -> dict[str, Any]:
match el.tag:
case "host":
return {"name": attr(el, "name"), "values": [attr(el, "ip")]}
case "network":
return {"name": attr(el, "name"), "values": [attr(el, "prefix")]}
raise ValueError(f"unknown address element {describe(el)}")
def to_service(el: ET.Element) -> dict[str, Any]:
if el.tag != "service":
raise ValueError(f"unknown service element {describe(el)}")
return {"name": attr(el, "name"), "entries": [entry(child) for child in el]}
def to_group(el: ET.Element) -> dict[str, Any]:
if el.tag != "group":
raise ValueError(f"unknown group element {describe(el)}")
return {
"name": attr(el, "name"),
"kind": attr(el, "kind"),
"include": texts(el, "member"),
"exclude": texts(el, "except"),
}
def field(rule: ET.Element, tag: str) -> tuple[list[Any], bool]:
"""The values of <sources>, <destinations> or <services>, and whether they are negated."""
node = rule.find(tag)
if node is None:
raise ValueError(f"{describe(rule)} has no <{tag}>")
values = [(child.text or "").strip() if child.tag == "ref" else entry(child) for child in node]
return values, node.get("negate") == "true"
def to_rule(el: ET.Element) -> dict[str, Any]:
verdict = attr(el, "verdict")
if verdict not in VERDICTS:
raise ValueError(f"{describe(el)} verdict {verdict!r} is not one of allow, block")
sources, source_negate = field(el, "sources")
destinations, destination_negate = field(el, "destinations")
services, service_negate = field(el, "services")
return {
"order_id": number(el, "seq"),
"name": el.get("name"),
"action": VERDICTS[verdict],
"description": (el.findtext("comment") or "").strip(),
"sources": sources,
"destinations": destinations,
"services": services,
"source_negate": source_negate,
"destination_negate": destination_negate,
"service_negate": service_negate,
}
# Reading the file: the structure is checked here, each item in the resources.
def children(node: ET.Element) -> Iterator[ET.Element]:
"""Yield the elements of one section, unconverted."""
yield from node
def problem(path: Path, message: str) -> Problem:
return Problem(resource=path.name, index=None, message=message)
def resources(path: Path, node: ET.Element, firewall: str | None, problems: list[Problem]) -> Iterator[Resource]:
"""Resources for the export's top level (firewall None) or for one <device>."""
for child in node:
fn = functools.partial(children, child)
match child.tag:
case "addresses":
yield Resource("addresses", fn, firewall=firewall).add_map(to_address).reads(path)
case "services":
yield Resource("services", fn, firewall=firewall).add_map(to_service).reads(path)
case "groups":
yield Resource("groups", fn, firewall=firewall).add_map(to_group).reads(path)
case "device" if firewall is None:
name = child.get("name")
if not name:
problems.append(problem(path, "<device> needs a name"))
continue
yield from resources(path, child, name, problems)
case "ruleset" if firewall is not None:
name = child.get("name")
if not name:
problems.append(problem(path, f'<ruleset> in <device name="{firewall}"> needs a name'))
continue
yield Resource("rules", fn, firewall=firewall, policy=name).add_map(to_rule).reads(path)
case _:
problems.append(problem(path, f"unexpected {describe(child)} in {describe(node)}"))
@source
def branch(file: str = "export.xml") -> list[Resource]:
path = Path(__file__).with_name(file)
try:
root = ET.parse(path).getroot() # noqa: S314 # your own export, not untrusted input
except ET.ParseError as exc:
raise LoadError((problem(path, f"not well-formed XML: {exc}"),)) from exc
if root.tag != "policy-export":
raise LoadError((problem(path, f"expected <policy-export>, found {describe(root)}"),))
problems: list[Problem] = []
found = list(resources(path, root, None, problems))
if problems:
raise LoadError(tuple(problems))
return found
def branch_bad() -> Source:
"""The same export with broken elements, from bad-export.xml."""
return branch("bad-export.xml")
export.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- A fictional policy export: global objects, then one site firewall,
`branch`, with its own objects and two rulesets. -->
<policy-export version="1">
<addresses>
<network name="hq-lan" prefix="10.1.0.0/16"/>
<network name="branch-lan" prefix="10.40.0.0/16"/>
<host name="mail" ip="10.40.5.25"/>
<host name="printer" ip="10.40.5.30"/>
<host name="nas" ip="10.40.5.40"/>
</addresses>
<services>
<service name="web"><tcp port="80"/><tcp port="443"/></service>
<service name="smtp"><tcp port="25"/></service>
<service name="dns"><udp port="53"/><tcp port="53"/></service>
<service name="ipp"><tcp port="631"/></service>
<service name="ping"><icmp type="8"/></service>
<service name="ipsec"><proto number="50"/><udp port="500"/><udp port="4500"/></service>
</services>
<groups>
<group name="servers" kind="address">
<member>mail</member><member>printer</member><member>nas</member>
</group>
<group name="office-hosts" kind="address">
<member>branch-lan</member>
<except>servers</except>
</group>
</groups>
<device name="branch">
<addresses>
<host name="scanner" ip="10.40.5.31"/>
</addresses>
<services>
<service name="consoles"><tcp port="8000-8080"/></service>
</services>
<ruleset name="wan-in">
<rule seq="10" name="allow-mail" verdict="allow">
<sources><ref>any</ref></sources>
<destinations><ref>mail</ref></destinations>
<services><ref>smtp</ref></services>
</rule>
<rule seq="20" name="block-spam-net" verdict="block">
<sources><ref>192.0.2.0/24</ref></sources>
<destinations><ref>mail</ref></destinations>
<services><ref>smtp</ref></services>
<comment>Added after the spam wave</comment>
</rule>
<rule seq="30" name="allow-ipsec" verdict="allow">
<sources><ref>198.51.100.7</ref></sources>
<destinations><ref>10.40.0.1</ref></destinations>
<services><ref>ipsec</ref></services>
<comment>Tunnel to head office</comment>
</rule>
<rule seq="40" name="allow-ping" verdict="allow">
<sources><ref>hq-lan</ref></sources>
<destinations><ref>servers</ref></destinations>
<services><ref>ping</ref></services>
</rule>
</ruleset>
<ruleset name="lan-out">
<rule seq="10" name="allow-dns" verdict="allow">
<sources><ref>branch-lan</ref></sources>
<destinations><ref>any</ref></destinations>
<services><ref>dns</ref></services>
</rule>
<rule seq="20" name="allow-hq" verdict="allow">
<sources><ref>branch-lan</ref></sources>
<destinations><ref>hq-lan</ref></destinations>
<services><ref>any</ref></services>
</rule>
<rule seq="30" name="allow-hq-print" verdict="allow">
<sources><ref>branch-lan</ref></sources>
<destinations><ref>hq-lan</ref></destinations>
<services><ref>ipp</ref></services>
</rule>
<rule seq="40" name="allow-web-out" verdict="allow">
<sources><ref>office-hosts</ref></sources>
<destinations negate="true"><ref>branch-lan</ref><ref>hq-lan</ref></destinations>
<services><ref>web</ref><tcp port="8443"/></services>
<comment>Internet only</comment>
</rule>
<rule seq="50" name="block-devices-out" verdict="block">
<sources><ref>printer</ref><ref>scanner</ref></sources>
<destinations><ref>any</ref></destinations>
<services><ref>any</ref></services>
</rule>
</ruleset>
</device>
</policy-export>
bad-export.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- export.xml with four broken elements, to show what each layer reports. -->
<policy-export version="1">
<addresses>
<network name="hq-lan" prefix="10.1.0.0/16"/>
<network name="branch-lan" prefix="10.40.0.0/16"/>
<host name="mail" ip="10.40.5.25"/>
<host name="printer" ip="10.40.5.30"/>
<host name="nas"/>
</addresses>
<services>
<service name="web"><tcp port="80"/><tcp port="443"/></service>
<service name="smtp"><tcp port="25"/></service>
<service name="dns"><udp port="53"/><tcp port="53"/></service>
<service name="ipp"><tcp port="631"/></service>
<service name="ping"><icmp type="300"/></service>
<service name="ipsec"><proto number="50"/><udp port="500"/><udp port="4500"/></service>
</services>
<groups>
<group name="servers" kind="address">
<member>mail</member><member>printer</member><member>nas</member>
</group>
<group name="office-hosts" kind="address">
<member>branch-lan</member>
<except>servers</except>
</group>
</groups>
<device name="branch">
<addresses>
<host name="scanner" ip="10.40.5.31"/>
</addresses>
<services>
<service name="consoles"><tcp port="8000-http"/></service>
</services>
<ruleset name="wan-in">
<rule seq="10" name="allow-mail" verdict="allow">
<sources><ref>any</ref></sources>
<destinations><ref>mail</ref></destinations>
<services><ref>smtp</ref></services>
</rule>
<rule seq="20" name="block-spam-net" verdict="deny">
<sources><ref>192.0.2.0/24</ref></sources>
<destinations><ref>mail</ref></destinations>
<services><ref>smtp</ref></services>
<comment>Added after the spam wave</comment>
</rule>
<rule seq="30" name="allow-ipsec" verdict="allow">
<sources><ref>198.51.100.7</ref></sources>
<destinations><ref>10.40.0.1</ref></destinations>
<services><ref>ipsec</ref></services>
<comment>Tunnel to head office</comment>
</rule>
<rule seq="40" name="allow-ping" verdict="allow">
<sources><ref>hq-lan</ref></sources>
<destinations><ref>servers</ref></destinations>
<services><ref>ping</ref></services>
</rule>
</ruleset>
<ruleset name="lan-out">
<rule seq="10" name="allow-dns" verdict="allow">
<sources><ref>branch-lan</ref></sources>
<destinations><ref>any</ref></destinations>
<services><ref>dns</ref></services>
</rule>
<rule seq="20" name="allow-hq" verdict="allow">
<sources><ref>branch-lan</ref></sources>
<destinations><ref>hq-lan</ref></destinations>
<services><ref>any</ref></services>
</rule>
<rule seq="30" name="allow-hq-print" verdict="allow">
<sources><ref>branch-lan</ref></sources>
<destinations><ref>hq-lan</ref></destinations>
<services><ref>ipp</ref></services>
</rule>
<rule seq="40" name="allow-web-out" verdict="allow">
<sources><ref>office-hosts</ref></sources>
<destinations negate="true"><ref>branch-lan</ref><ref>hq-lan</ref></destinations>
<services><ref>web</ref><tcp port="8443"/></services>
<comment>Internet only</comment>
</rule>
<rule seq="50" name="block-devices-out" verdict="block">
<sources><ref>printer</ref><ref>scanner</ref></sources>
<destinations><ref>any</ref></destinations>
<services><ref>any</ref></services>
</rule>
</ruleset>
</device>
</policy-export>
classify_xml.py
"""Load the XML export with the API, classify it, then load the broken variant.
Keep this file next to xml_source.py, export.xml and bad-export.xml, and run: python classify_xml.py
"""
import click
from xml_source import branch, branch_bad
from fireman import BDDManager, LoadError, Pipeline
pipeline = Pipeline()
inventory = pipeline.load(branch())
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(branch_bad())
except LoadError as exc:
click.echo(f"bad-export.xml: {len(exc.problems)} problems")
for problem in exc.problems:
click.echo(f" {problem}")
The export#
<?xml version="1.0" encoding="utf-8"?>
<!-- A fictional policy export: global objects, then one site firewall,
`branch`, with its own objects and two rulesets. -->
<policy-export version="1">
<addresses>
<network name="hq-lan" prefix="10.1.0.0/16"/>
<network name="branch-lan" prefix="10.40.0.0/16"/>
<host name="mail" ip="10.40.5.25"/>
<host name="printer" ip="10.40.5.30"/>
<host name="nas" ip="10.40.5.40"/>
</addresses>
<services>
<service name="web"><tcp port="80"/><tcp port="443"/></service>
<service name="smtp"><tcp port="25"/></service>
<service name="dns"><udp port="53"/><tcp port="53"/></service>
<service name="ipp"><tcp port="631"/></service>
<service name="ping"><icmp type="8"/></service>
<service name="ipsec"><proto number="50"/><udp port="500"/><udp port="4500"/></service>
</services>
<groups>
<group name="servers" kind="address">
<member>mail</member><member>printer</member><member>nas</member>
</group>
<group name="office-hosts" kind="address">
<member>branch-lan</member>
<except>servers</except>
</group>
</groups>
<device name="branch">
<addresses>
<host name="scanner" ip="10.40.5.31"/>
</addresses>
<services>
<service name="consoles"><tcp port="8000-8080"/></service>
</services>
<ruleset name="wan-in">
<rule seq="10" name="allow-mail" verdict="allow">
<sources><ref>any</ref></sources>
<destinations><ref>mail</ref></destinations>
<services><ref>smtp</ref></services>
</rule>
<rule seq="20" name="block-spam-net" verdict="block">
<sources><ref>192.0.2.0/24</ref></sources>
<destinations><ref>mail</ref></destinations>
<services><ref>smtp</ref></services>
<comment>Added after the spam wave</comment>
</rule>
<rule seq="30" name="allow-ipsec" verdict="allow">
<sources><ref>198.51.100.7</ref></sources>
<destinations><ref>10.40.0.1</ref></destinations>
<services><ref>ipsec</ref></services>
<comment>Tunnel to head office</comment>
</rule>
<rule seq="40" name="allow-ping" verdict="allow">
<sources><ref>hq-lan</ref></sources>
<destinations><ref>servers</ref></destinations>
<services><ref>ping</ref></services>
</rule>
</ruleset>
<ruleset name="lan-out">
<rule seq="10" name="allow-dns" verdict="allow">
<sources><ref>branch-lan</ref></sources>
<destinations><ref>any</ref></destinations>
<services><ref>dns</ref></services>
</rule>
<rule seq="20" name="allow-hq" verdict="allow">
<sources><ref>branch-lan</ref></sources>
<destinations><ref>hq-lan</ref></destinations>
<services><ref>any</ref></services>
</rule>
<rule seq="30" name="allow-hq-print" verdict="allow">
<sources><ref>branch-lan</ref></sources>
<destinations><ref>hq-lan</ref></destinations>
<services><ref>ipp</ref></services>
</rule>
<rule seq="40" name="allow-web-out" verdict="allow">
<sources><ref>office-hosts</ref></sources>
<destinations negate="true"><ref>branch-lan</ref><ref>hq-lan</ref></destinations>
<services><ref>web</ref><tcp port="8443"/></services>
<comment>Internet only</comment>
</rule>
<rule seq="50" name="block-devices-out" verdict="block">
<sources><ref>printer</ref><ref>scanner</ref></sources>
<destinations><ref>any</ref></destinations>
<services><ref>any</ref></services>
</rule>
</ruleset>
</device>
</policy-export>
The format, element by element:
- Sections
<addresses>,<services>and<groups>hold objects. At the top level they are global; inside a<device>they belong to that firewall.- Addresses
<host name ip>is one address,<network name prefix>one network.- Services
A
<service name>holds entries:<tcp port>and<udp port>with a port or alow-highrange,<icmp>with optionaltypeandcode, and<proto number>for any other protocol.- Groups
A
<group name kind>lists<member>names and, optionally,<except>names.- Devices and rulesets
A
<device name>is a firewall, and each<ruleset name>in it a policy.- Rules
A
<rule seq name verdict>, where the verdict isalloworblock, has<sources>,<destinations>and<services>. Each holds<ref>elements with a name,anyor an address, and<services>may also hold inline entries like<tcp port="8443"/>.negate="true"on a list matches everything except it. An optional<comment>becomes the description.
The source#
"""Read a site firewall from a fictional XML policy export.
The export holds global <addresses>, <services> and <groups>, then one
<device> per firewall with its own object sections and one <ruleset> per
policy. Load it with
fireman load --source xml_source.branch
"""
import functools
import xml.etree.ElementTree as ET
from collections.abc import Iterator
from pathlib import Path
from typing import Any
from fireman import LoadError, Resource, Source, source
from fireman.model import Problem
VERDICTS = {"allow": "accept", "block": "deny"}
def describe(el: ET.Element) -> str:
"""Name an element in messages: <host name="nas">, or just <tcp>."""
name = el.get("name")
return f'<{el.tag} name="{name}">' if name else f"<{el.tag}>"
def attr(el: ET.Element, key: str) -> str:
value = el.get(key)
if value is None:
raise ValueError(f"{describe(el)} has no {key!r} attribute")
return value
def number(el: ET.Element, key: str, text: str | None = None) -> int:
text = attr(el, key) if text is None else text
if not text.isdecimal():
raise ValueError(f"{describe(el)} {key} {text!r} is not a number")
return int(text)
def texts(el: ET.Element, tag: str) -> list[str]:
return [(child.text or "").strip() for child in el.iterfind(tag)]
# Converters: one element in, one item in Fireman's input format out.
def entry(el: ET.Element) -> dict[str, Any]:
"""A service entry: <tcp port="443"/>, <udp port="1-1024"/>, <icmp type="8"/>, <proto number="50"/>."""
match el.tag:
case "tcp" | "udp":
low, _, high = attr(el, "port").partition("-")
protocol = 6 if el.tag == "tcp" else 17
return {"protocol": protocol, "ports": [number(el, "port", low), number(el, "port", high or low)]}
case "icmp":
found = {key: number(el, key) for key in ("type", "code") if key in el.attrib}
return {"protocol": 1, **{f"icmp_{key}": value for key, value in found.items()}}
case "proto":
return {"protocol": number(el, "number")}
raise ValueError(f"unknown service entry {describe(el)}")
def to_address(el: ET.Element) -> dict[str, Any]:
match el.tag:
case "host":
return {"name": attr(el, "name"), "values": [attr(el, "ip")]}
case "network":
return {"name": attr(el, "name"), "values": [attr(el, "prefix")]}
raise ValueError(f"unknown address element {describe(el)}")
def to_service(el: ET.Element) -> dict[str, Any]:
if el.tag != "service":
raise ValueError(f"unknown service element {describe(el)}")
return {"name": attr(el, "name"), "entries": [entry(child) for child in el]}
def to_group(el: ET.Element) -> dict[str, Any]:
if el.tag != "group":
raise ValueError(f"unknown group element {describe(el)}")
return {
"name": attr(el, "name"),
"kind": attr(el, "kind"),
"include": texts(el, "member"),
"exclude": texts(el, "except"),
}
def field(rule: ET.Element, tag: str) -> tuple[list[Any], bool]:
"""The values of <sources>, <destinations> or <services>, and whether they are negated."""
node = rule.find(tag)
if node is None:
raise ValueError(f"{describe(rule)} has no <{tag}>")
values = [(child.text or "").strip() if child.tag == "ref" else entry(child) for child in node]
return values, node.get("negate") == "true"
def to_rule(el: ET.Element) -> dict[str, Any]:
verdict = attr(el, "verdict")
if verdict not in VERDICTS:
raise ValueError(f"{describe(el)} verdict {verdict!r} is not one of allow, block")
sources, source_negate = field(el, "sources")
destinations, destination_negate = field(el, "destinations")
services, service_negate = field(el, "services")
return {
"order_id": number(el, "seq"),
"name": el.get("name"),
"action": VERDICTS[verdict],
"description": (el.findtext("comment") or "").strip(),
"sources": sources,
"destinations": destinations,
"services": services,
"source_negate": source_negate,
"destination_negate": destination_negate,
"service_negate": service_negate,
}
# Reading the file: the structure is checked here, each item in the resources.
def children(node: ET.Element) -> Iterator[ET.Element]:
"""Yield the elements of one section, unconverted."""
yield from node
def problem(path: Path, message: str) -> Problem:
return Problem(resource=path.name, index=None, message=message)
def resources(path: Path, node: ET.Element, firewall: str | None, problems: list[Problem]) -> Iterator[Resource]:
"""Resources for the export's top level (firewall None) or for one <device>."""
for child in node:
fn = functools.partial(children, child)
match child.tag:
case "addresses":
yield Resource("addresses", fn, firewall=firewall).add_map(to_address).reads(path)
case "services":
yield Resource("services", fn, firewall=firewall).add_map(to_service).reads(path)
case "groups":
yield Resource("groups", fn, firewall=firewall).add_map(to_group).reads(path)
case "device" if firewall is None:
name = child.get("name")
if not name:
problems.append(problem(path, "<device> needs a name"))
continue
yield from resources(path, child, name, problems)
case "ruleset" if firewall is not None:
name = child.get("name")
if not name:
problems.append(problem(path, f'<ruleset> in <device name="{firewall}"> needs a name'))
continue
yield Resource("rules", fn, firewall=firewall, policy=name).add_map(to_rule).reads(path)
case _:
problems.append(problem(path, f"unexpected {describe(child)} in {describe(node)}"))
@source
def branch(file: str = "export.xml") -> list[Resource]:
path = Path(__file__).with_name(file)
try:
root = ET.parse(path).getroot() # noqa: S314 # your own export, not untrusted input
except ET.ParseError as exc:
raise LoadError((problem(path, f"not well-formed XML: {exc}"),)) from exc
if root.tag != "policy-export":
raise LoadError((problem(path, f"expected <policy-export>, found {describe(root)}"),))
problems: list[Problem] = []
found = list(resources(path, root, None, problems))
if problems:
raise LoadError(tuple(problems))
return found
def branch_bad() -> Source:
"""The same export with broken elements, from bad-export.xml."""
return branch("bad-export.xml")
It reads the file in two passes, at two levels.
The structure: branch()#
branch() parses the file and walks its outline: which sections, devices and
rulesets there are. That decides the resources and their scopes, so it has to
happen before any item is read. Problems at this level aren’t tied to one
item: a file that isn’t XML, an unknown element, a device without a name.
branch() collects them and raises one LoadError with all of them, the same
way Fireman’s own YAML reader reports file problems.
The scopes come from the data (the device and ruleset names), so the
resources are built with Resource(...) directly rather than with
@resource. Each gets functools.partial(children, element) as its fn:
a generator that yields the section’s elements as they are. Each resource also
calls reads(path), so editing
export.xml after a load gives the stale-workspace warning.
The items: converters#
Each element is converted by add_map: to_address, to_service,
to_group or to_rule turns it into a dictionary in Fireman’s
input format. They raise a ValueError for anything
they can’t read, which becomes a problem for that element only, so one bad
element doesn’t hide the others.
The generator does no checking on purpose. An error raised while generating items is reported once for the whole section and stops it, so a bad element would hide the ones after it. Keep the generator to “yield what is there” and put every check in a converter.
describe names the element in each message, since an index alone, like
rules[1], is hard to find in a large XML file.
Load it from the command line#
From the folder holding the files:
fireman load --source xml_source.branch
fireman classify
Loaded workspace 'default': 1 firewalls, 2 policies, 9 rules, 15 objects.
Findings
┏━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Firewall ┃ Policy ┃ Rule ┃ Anomaly ┃ Related ┃
┡━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ branch │ wan-in │ block-spam-net (order_id 20) │ shadowed │ allow-mail (order_id 10) │
│ branch │ lan-out │ allow-hq-print (order_id 30) │ redundant │ allow-hq (order_id 20) │
│ branch │ lan-out │ block-devices-out (order_id 50) │ correlated │ allow-dns (order_id 10), allow-hq (order_id 20), │
│ │ │ │ │ allow-web-out (order_id 40) │
└──────────┴─────────┴─────────────────────────────────┴────────────┴──────────────────────────────────────────────────┘
0 of 1 firewall from cache
The 15 objects are 5 addresses, 6 services and 2 groups global, plus the
device’s own scanner and consoles. What the findings mean:
- Shadowed
block-spam-netwas added to stop a spam network, butallow-mailabove it already accepts SMTP tomailfrom anywhere. The block never fires.- Redundant
allow-hq-printallows printing to head office, whichallow-hqalready allows along with everything else.- Correlated
block-devices-outblocks the printer and scanner, but three earlier rules already accept some of their traffic: DNS, anything to head office, and, for the scanner, the web. The printer is one of theservers, whichoffice-hostsleaves out, but the scanner’s address is inbranch-lanand not inservers, soallow-web-outcovers it. If the devices should be blocked, the rule has to come first.
Load it from Python#
classify_xml.py loads and classifies the export, then tries the broken one:
"""Load the XML export with the API, classify it, then load the broken variant.
Keep this file next to xml_source.py, export.xml and bad-export.xml, and run: python classify_xml.py
"""
import click
from xml_source import branch, branch_bad
from fireman import BDDManager, LoadError, Pipeline
pipeline = Pipeline()
inventory = pipeline.load(branch())
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(branch_bad())
except LoadError as exc:
click.echo(f"bad-export.xml: {len(exc.problems)} problems")
for problem in exc.problems:
click.echo(f" {problem}")
global objects: 13
branch/wan-in: 4 rules
branch/lan-out: 5 rules
branch/wan-in block-spam-net: shadowed (allow-mail)
branch/lan-out allow-hq-print: redundant (allow-hq)
branch/lan-out block-devices-out: correlated (allow-dns, allow-hq, allow-web-out)
bad-export.xml: 4 problems
global/addresses[4]: <host name="nas"> has no 'ip' attribute
global/services[4].entries.0.icmp.icmp_type: ICMP value 300 is outside 0-255
branch/services[0]: <tcp> port 'http' is not a number
branch/wan-in/rules[1]: <rule name="block-spam-net"> verdict 'deny' is not one of allow, block
Broken elements#
bad-export.xml is the same export with four broken elements:
<host name="nas"/>has noip.pinghas<icmp type="300"/>, beyond the largest ICMP type, 255.The device’s
consolesservice has<tcp port="8000-http"/>.block-spam-netsaysverdict="deny", which isn’t this format’s word.
fireman load --source xml_source.branch_bad
global/addresses[4]: <host name="nas"> has no 'ip' attribute
global/services[4].entries.0.icmp.icmp_type: ICMP value 300 is outside 0-255
branch/services[0]: <tcp> port 'http' is not a number
branch/wan-in/rules[1]: <rule name="block-spam-net"> verdict 'deny' is not one of allow, block
All four come out in one run, and the command exits 1 and stores nothing.
Three come from the converters and carry their own messages. The ICMP type
passed the converter, which only checks that it is a number, and Fireman’s
ServiceObject rejected it; its path points into the converted item.
Every line starts with the scope, so you can tell the global services[4]
(ping, the fifth global service) from the device’s services[0].
A broken file#
Problems with the file itself come from branch() before any item is read.
Copy export.xml to truncated.xml, delete its last line, and call the
source directly:
import click
from xml_source import branch
from fireman import LoadError
try:
branch("truncated.xml")
except LoadError as exc:
click.echo(exc)
truncated.xml: not well-formed XML: no element found: line 92, column 0
These problems have no scope or index, only the file name, like the file
problems of Input format. An unknown element reads the same way, for
example export.xml: unexpected <rulesets name="lan-out"> in <device name="branch">.
fireman load --source prints them and exits 1.