Skip to content

Version 0.1.0 is a first version, for trial. See what is not proven →

bogolang
FR

← Documentation

Configurations, audit rules and templates

The configuration as an object, audit rules, templates.

All documentation pages

This page covers what a program can do with a device configuration once it has one: read it as an object, compare two of them, check it against house rules with rule and audit, and write device lines from templates. None of this changes a device.

Examples: audit_rules, backup_diff.

Where a configuration comes from

Call Result
backup(d) The running configuration, read from the device (see devices.md)
load_config(path, platform="ios") A saved file, such as a nightly backup. Reads no device
Config(device, text, taken) A configuration made from a text, as in a test
snapshot(d).config The configuration inside a snapshot
Bogolang
cfg: Config = load_config("configs/core-sw1.cfg", platform="iosxe")
print(cfg.hostname, len(cfg.lines))

load_config names the device after the hostname line of the file, or after the file name when there is none. The platform word decides how the file is read: junos reads the Junos forms (below), every other word reads blocks by indentation, as IOS, IOS-XE, ASA and NX-OS write them. The configuration object works on ios, iosxe, asa, nxos and junos; on aireos it is refused.

The configuration as an object

On a Config Result
.text, .lines The whole text, and its lines
.hostname str, from the hostname line
.find(start) list[str]: every line that starts with this text, at any depth
.has(start) bool: is there such a line
.section(start) list[Section]: every block whose first line starts with this text
.interfaces list[InterfaceConfig]: one per interface block
.save(path) Writes the text to a file
.warnings list[str]: what a reader of this configuration must know. Empty on most

A Section is one block: .line is its first line, .lines the lines under it with the block's own indentation removed, and it has its own .find, .has and .section for the blocks inside it.

Bogolang
cfg: Config = load_config("configs/core-sw1.cfg", platform="iosxe")
for vty in cfg.section("line vty"):
    if vty.find("transport input") != ["transport input ssh"]:
        print(f"{vty.line}: {vty.lines}")
print(cfg.has("service password-encryption"))

On a file with two line vty blocks, the second allowing telnet, this prints:

line vty 5 15: ['transport input ssh telnet']
True

How lines are matched:

  • A match looks at the start of a line, after the spaces in front. Capitals count as written.
  • find and section search at every depth. cfg.section("address-family") also finds the blocks under router bgp.
  • Lines that start with !, empty lines, and the two lines IOS writes on top of show running-config are not content.
  • The text of a banner is kept under its banner line and is never searched, so a banner that holds lines that look like configuration gives no false match.
  • An interface is never read as inside another interface, even where IOS-XE writes one a space in.

Interfaces

An InterfaceConfig is a Section with these fields, read once:

Field Type Meaning
.name Intf Gi1/0/1 and GigabitEthernet1/0/1 are the same name
.description str Empty when there is none
.shutdown bool
.address IfAddr or None The primary IPv4 address. Not a secondary, not dhcp
.mode str "access", "trunk", "routed" or empty
.access_vlan int or None
.trunk_vlans VlanSet or None None when there is no allowed vlan line, which on IOS means every VLAN. add, remove and except lines are followed
Bogolang
cfg: Config = load_config("configs/core-sw1.cfg", platform="iosxe")
for i in cfg.interfaces:
    if not i.shutdown and i.description == "":
        print(f"{i.name}: no description, mode {i.mode or 'not set'}")

Read on a small file:

Gi1/0/1 'uplink to edge-rt1' False None 'trunk' None 10,20
Gi1/0/2 '' False None 'access' 10 None
Gi1/0/3 '' True None '' None None
Vl10 '' False 192.0.2.1/24 'routed' None None

(name, description, shutdown, address, mode, access VLAN, trunk VLANs). An interface whose name cannot be read is left out of .interfaces; cfg.section("interface ...") still finds it. A line of an interface that cannot be read leaves its field empty.

diff

diff(a: Config, b: Config) -> ConfigDiff

diff compares two configurations section by section. A ConfigDiff has .removed and .added, each a list of lines written with their section in front: interface GigabitEthernet1/0/3 / shutdown. A line that only moved, the ! lines and the byte count on top are not changes. It is false when nothing changed, and prints as - and + lines, or No difference..

Bogolang
old: Config = load_config("backups/core-sw1.cfg", platform="iosxe")
new: Config = load_config("configs/core-sw1.cfg", platform="iosxe")
changes: ConfigDiff = diff(old, new)
print(f"{len(changes.removed)} removed, {len(changes.added)} added")
print(changes)

The output of backup_diff is on devices.md.

Junos configurations

Junos writes its configuration with braces or as set lines. load_config(path, platform="junos") reads either form and sees by itself which one it is. backup(d) on Junos keeps the form with braces.

The object works on paths: each statement is one path of words, as in the set form without the word set. A search may start at any level, and words are matched whole.

On a Junos Config Result
.has("system services telnet") Is there a statement whose path starts with these words
.find("system services") The statements whose path starts so, as full paths
.section("interfaces ge-0/0/1") The blocks at that path, as Sections
.hostname From system host-name
.set_lines The whole configuration in the set form
.inactive The statements that are switched off
.interfaces One per interface and one per unit, such as ge-0/0/0.0
Bogolang
j: Config = load_config("edge-sw2.conf", platform="junos")
print(j.hostname, j.has("system services telnet"), j.inactive)

On a file with set system services telnet and deactivate system services telnet, this prints edge-sw2 False ['system services telnet'].

  • A statement that is switched off is not in effect. has, find and section leave it out; it is listed in .inactive. An audit rule never passes on a line the device ignores.
  • Statements under groups are patterns, not in effect: a search leaves them out, unless it starts with the word groups.
  • Groups. A saved file shows apply-groups but not what the device inherits. When a file uses it, .warnings says that inherited statements are not counted, and every audit row of that device carries the same sentence. A live audit reads show configuration | display inheritance no-comments, which shows them.
  • A line the reader cannot turn into a path stops it with an error that names the line by its number and never shows the line, because a configuration holds secrets.
  • diff of two Junos configurations compares their set lines.
  • On interfaces, .shutdown is true for disable; .mode comes from the switching family, or is "routed" when the unit has an address. VLANs named by name are found through the vlans block; when one name is not found, .trunk_vlans is empty.

.set_lines and .inactive on a configuration of another platform are refused.

Audit rules

A rule is a list of tests, one per line, each true or false. audit(devices) runs every rule on every device it is for and gives one row per device and rule.

Bogolang
edition 2027


class HouseRules:
    rule "vty takes ssh only" for d:
        config.section("line vty") != []
        all(v.find("transport input") == ["transport input ssh"] for v in config.section("line vty"))

    rule "passwords are encrypted" for d:
        config.has("service password-encryption")

    rule "clock from ntp" for d where d.role != "lab":
        config.has("ntp server")  # every device but the lab ones

    @staticmethod
    def main(args: list[str]) -> None:
        devices: list[Device] = inventory("devices.csv")
        result: AuditResult = audit(devices, configs="configs")
        print(result)
        for row in result.failed:
            print(f"{row.device} fails '{row.rule}': {row.detail}")
  • Inside a rule three names exist: the device (d here, the word after for), config (its configuration, read once per device) and show(...), which reads the live device.
  • where says which devices a rule is for. A where that raises an error gives a failed row for that device and rule.
  • A device fails a rule at its first false test. That test is the detail of the row.
  • A test that raises an error counts as failed, with the error as the detail. It does not stop the audit.
  • A comment at the end of a test line is allowed and is not part of the detail.
  • A rule holds no blocks: each test is written on one line.
  • A rule stands in a class body or in a method. In a class body, a field of the class is reached through the class: HouseRules.servers.
  • Two rules with the same name stop the program when it runs.

audit

audit(devices: list[Device], configs: str = '', parallel: int = 10) -> AuditResult
  • With configs="folder", each configuration is read from folder/NAME.cfg and no device is contacted. A rule that calls show then fails on that device, with a sentence that says why. A missing file fails every rule of that device.
  • Without configs, each device is read over SSH, up to parallel at a time, with the login stored by bogo login. A device that cannot be read fails all its rules; the others go on.
  • A device whose platform has no configuration object fails its rules with the sentence of the platform table.
On an AuditResult Result
.rows list[AuditRow], one per device and rule, in the order of the devices
.failed The rows that failed
.passed True when none failed. bool(result) is the same
print(result) A table, and a last line such as 2 of 3 failed

An AuditRow has .device, .rule, .passed and .detail. table(result.failed, ["device", "rule", "detail"]) prints the failed rows as a table, as audit_rules does:

bogo run audit_rules.bogo
device      rule                        detail
----------  --------------------------  ---------------------------------------------------------------
core-sw1    vty takes ssh only          all(AuditRules.ssh_only(v) for v in config.section("line vty"))
core-sw1    ports in use are described  AuditRules.undescribed(config) == []
access-sw2  vty takes ssh only          all(AuditRules.ssh_only(v) for v in config.section("line vty"))
access-sw2  passwords are encrypted     config.has("service password-encryption")
access-sw2  logs go to a server         config.has("logging host")
access-sw2  clock from ntp              config.has("ntp server")
access-sw2  ports in use are described  AuditRules.undescribed(config) == []

7 of 14 checks failed.
core-sw1: no description on Gi1/0/3
access-sw2: no description on Vl10

Templates

A template is a text file of device lines with holes written {name}, the same form as in a change block.

template(path: str) -> Template
Template.fill(d: Device, **values) -> str

A file access-port.txt:

interface {port}
 description {what}
 switchport mode access
 switchport access vlan {vlan}
 snmp-server location {site}
Bogolang
t: Template = template("access-port.txt")
d: Device = Device(name="core-sw1", ip=192.0.2.11, platform="iosxe", site="north")
lines: str = t.fill(d, port=Intf("Gi1/0/7"), what="camera", vlan=30)
print(lines)
print(t.holes)
interface Gi1/0/7
 description camera
 switchport mode access
 switchport access vlan 30
 snmp-server location north
  • A hole takes its value from the names given to fill first, then from the device: name, ip, site, role, platform and every extra column of the inventory.
  • A value may be text, a whole number, or an address type (IP, Net, IfAddr, MAC, Intf, VlanSet). A Secret cannot fill a hole.
  • A hole with no value is an error that names the hole and the device:
ValueError: access-port.txt, line 4: the hole {vlan} has no value for device core-sw1. Give it as fill(d, vlan=...) or fill the 'vlan' column of the inventory.

An empty inventory cell counts as no value. An empty text given on purpose to fill is accepted. - A hole is a plain name. {vlan + 1} is refused when the file is read: work the value out in Bogolang and pass it by name. A template has no loops and no conditions. - {{ and }} are real braces. A lone } or an unclosed { is refused when the file is read, with the line number. - The holes are checked when the program runs, not before.

A filled template goes into a change block on a line of its own and is sent as several lines:

Bogolang
t: Template = template("access-port.txt")
for d in inventory("devices.csv"):
    change on d:
        apply:
            {t.fill(d, port=Intf("Gi1/0/7"), what="camera", vlan=30)}
        rollback:
            default interface Gi1/0/7
        verify:
            "camera" in show("interfaces Gi1/0/7 description")

See changes.md.

Not proven

The configuration object read 86 real backup files with no error, and five audit rules were run over the 78 IOS and IOS-XE devices among them. The layouts of ASA, NX-OS and AireOS were left out of that trial. The Junos reader was tried on the configurations of virtual Junos switches only. See not-proven.md.