Facts, ports, management address, LLDP (per-port and top-level shapes), MAC table and PoE from a UniFi device record, which a controller's stat/device and the device's own mca-dump share. Fixtures from aiounifi (MIT) and abates/napalm-unifi (Apache-2.0), anonymised with tools/sanitize.py. Refs NetOrk/netork#2787
102 lines
3.6 KiB
Python
102 lines
3.6 KiB
Python
"""Anonymise recorded UniFi output before it becomes a test fixture.
|
|
|
|
python tools/sanitize.py IN OUT [--replace OLD=NEW ...]
|
|
|
|
JSON input (controller responses, ``mca-dump``): every value under a secret key is
|
|
replaced -- the ``x_*`` keys a controller keeps (authkeys, passphrases, SSH host key
|
|
fingerprints) and the tokens a device carries. ``running.cfg`` input: the value of
|
|
every line whose key names a key, password or token. ``--replace`` swaps a string
|
|
everywhere, in the same way in every file, so that a MAC address or serial stays
|
|
consistent between the fixtures that mention it. ``--macs`` then maps every other
|
|
MAC address to a locally administered one (``02:00:00:00:..``), the same input to
|
|
the same output.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import pathlib
|
|
import re
|
|
from typing import Any
|
|
|
|
REDACTED = "REDACTED"
|
|
SECRET_KEYS = frozenset(
|
|
{"guest_token", "syslog_key", "anon_id", "hash_id", "stream_token", "x_passphrase"}
|
|
)
|
|
MAC = re.compile(r"\b[0-9a-f]{2}(?::[0-9a-f]{2}){5}\b", re.IGNORECASE)
|
|
KEEP_PREFIX = "02:00:00:00:"
|
|
CFG_SECRET = re.compile(r"(?:^|\.)(key|password|authkey|token|passphrase|x_[a-z_]+)$")
|
|
|
|
|
|
def _is_secret(key: str) -> bool:
|
|
return key.startswith("x_") or key in SECRET_KEYS
|
|
|
|
|
|
def redact(value: Any) -> Any:
|
|
"""*value* with every secret key's value replaced, at any depth."""
|
|
if isinstance(value, dict):
|
|
return {k: (REDACTED if _is_secret(k) else redact(v)) for k, v in value.items()}
|
|
if isinstance(value, list):
|
|
return [redact(item) for item in value]
|
|
return value
|
|
|
|
|
|
def redact_cfg(text: str) -> str:
|
|
"""A ``running.cfg`` with the value of every secret line replaced."""
|
|
lines = []
|
|
for line in text.splitlines():
|
|
key, sep, _ = line.partition("=")
|
|
lines.append(f"{key}={REDACTED}" if sep and CFG_SECRET.search(key) else line)
|
|
return "\n".join(lines) + "\n"
|
|
|
|
|
|
def anonymise_macs(text: str, keep: set[str]) -> str:
|
|
"""Every MAC address in *text* not in *keep* mapped to a locally administered one."""
|
|
mapping: dict[str, str] = {}
|
|
|
|
def _swap(match: re.Match[str]) -> str:
|
|
mac = match.group(0).lower()
|
|
if mac in keep or mac.startswith(KEEP_PREFIX):
|
|
return match.group(0)
|
|
if mac not in mapping:
|
|
n = len(mapping) + 1
|
|
mapping[mac] = f"{KEEP_PREFIX}{n >> 8:02x}:{n & 0xFF:02x}"
|
|
return mapping[mac]
|
|
|
|
return MAC.sub(_swap, text)
|
|
|
|
|
|
def sanitize(
|
|
text: str, replacements: dict[str, str], *, macs: bool = False
|
|
) -> str:
|
|
"""*text* redacted (JSON or ``running.cfg``), then with *replacements* applied.
|
|
|
|
With *macs*, every MAC address the replacements did not set is anonymised.
|
|
"""
|
|
try:
|
|
out = json.dumps(redact(json.loads(text)), indent=1, sort_keys=True) + "\n"
|
|
except json.JSONDecodeError:
|
|
out = redact_cfg(text)
|
|
for old, new in replacements.items():
|
|
out = out.replace(old, new)
|
|
if macs:
|
|
out = anonymise_macs(out, {new.lower() for new in replacements.values()})
|
|
return out
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("source", type=pathlib.Path)
|
|
parser.add_argument("target", type=pathlib.Path)
|
|
parser.add_argument("--replace", action="append", default=[], metavar="OLD=NEW")
|
|
parser.add_argument("--macs", action="store_true", help="anonymise every other MAC")
|
|
args = parser.parse_args()
|
|
replacements = dict(item.split("=", 1) for item in args.replace)
|
|
text = sanitize(args.source.read_text(), replacements, macs=args.macs)
|
|
args.target.write_text(text)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|