#!/usr/bin/env python3 """Capture goCoax MA2500D management traffic for use as test seed data. For each ``name;url`` line in the config file (by default ``.private/gocoax-exporter.cfg``) this replays the request sequence the exporter performs and records, per request, the method, path, and POST body together with the response status and a raw response body file: testdata//capture.json testdata//bodies/NN-name.{html,json} The HTTP Basic auth credentials and the rotating CSRF cookie/token are used on the wire but never written to disk, so the captured tree contains no secrets. Usage: python3 scripts/capture.py [--config PATH] [--out DIR] """ import argparse import datetime import json import pathlib import subprocess import sys import tempfile import urllib.parse DEFAULT_CONFIG = pathlib.Path(".private", "gocoax-exporter.cfg") DEFAULT_OUT = pathlib.Path("testdata") def log(msg): print(msg, file=sys.stderr) def parse_config(path): """Return [(name, url)] from a name;url config file, skipping blanks/#.""" devices = [] for lineno, raw in enumerate(path.read_text().splitlines(), start=1): line = raw.strip() if not line or line.startswith("#"): continue name, sep, url = line.partition(";") if not sep or not name.strip(): raise SystemExit(f"{path}:{lineno}: want name;url") devices.append((name.strip(), url.strip())) return devices def split_url(url): """Return (scheme, host:port, base_path, username, password).""" p = urllib.parse.urlparse(url) if p.scheme not in ("http", "https") or not p.hostname: raise SystemExit(f"bad device URL: {url!r}") netloc = p.hostname if ":" in netloc and not netloc.startswith("["): netloc = f"[{netloc}]" if p.port is not None: netloc = f"{netloc}:{p.port}" user = urllib.parse.unquote(p.username or "") pw = urllib.parse.unquote(p.password or "") return p.scheme, netloc, p.path, user, pw def endpoint(prefix, path): """Join an absolute path under the device base path.""" return prefix.rstrip("/") + "/" + path.lstrip("/") def csrf_token(jar): """Read the csrf_token value out of a Netscape-format cookie jar.""" for line in jar.read_text().splitlines(): if not line or line.startswith("#"): continue fields = line.split("\t") if len(fields) >= 7 and fields[5] == "csrf_token": return fields[6] raise SystemExit("no csrf_token cookie after session request") def parse_hex(s): s = s.strip().removeprefix("0x").removeprefix("0X") return int(s, 16) def read_data(path): """Return the decoded list of hex strings from a {"data":[...]} response.""" return json.loads(path.read_text())["data"] def run_curl(url, user, pw, jar, token, out_file, body): """POST (or GET when body is None) via curl; return the HTTP status.""" cmd = [ "curl", "-s", "-S", "-o", str(out_file), "-w", "%{http_code}", "-c", str(jar), "-b", str(jar), "-u", f"{user}:{pw}", "-H", "Content-Type: application/x-www-form-urlencoded", ] if token is not None: cmd += ["-H", f"X-CSRF-TOKEN: {token}"] if body is None: cmd += ["-X", "GET", url] else: cmd += ["--data", body, url] r = subprocess.run(cmd, capture_output=True, text=True) if r.returncode != 0: raise SystemExit(f"curl failed for {url}: {r.stderr.strip()}") return int(r.stdout.strip() or 0) def capture_device(name, url, out_dir): dev_dir = out_dir / name bodies = dev_dir / "bodies" bodies.mkdir(parents=True, exist_ok=True) scheme, netloc, base_path, user, pw = split_url(url) prefix = f"{scheme}://{netloc}{base_path}" entries = [] counter = 0 def add(ident, method, path, body, status, rel): nonlocal counter counter += 1 entries.append({ "name": ident, "method": method, "path": path, "body": body, "response": {"status": status, "file": rel}, }) with tempfile.TemporaryDirectory() as tmp: jar = pathlib.Path(tmp) / "cookies.txt" jar.touch() # curl's -b needs the jar to exist on the first request # Session: fetch a page to obtain the CSRF cookie, like initSession. # Never add /security.html (or any page that renders the MoCA preshared # keys) here: those pages contain on-the-wire secrets and must not be # written into testdata. out = bodies / "00-session.html" status = run_curl(endpoint(prefix, "/phyRates.html"), user, pw, jar, None, out, None) add("session", "GET", "/phyRates.html", "", status, "bodies/00-session.html") def post(ident, path, body): out = bodies / f"{counter:02d}-{ident}.json" status = run_curl(endpoint(prefix, path), user, pw, jar, csrf_token(jar), out, body) add(ident, "POST", path, body, status, f"bodies/{out.name}") return out # LocalInfo drives the rest of the flow: node IDs, versions, bitmask. li_file = post("local-info", "/ms/0/0x15", '{"data":[]}') li = read_data(li_file) my_node = parse_hex(li[0]) nc_node = parse_hex(li[1]) & 0xff bitmask = parse_hex(li[12]) active = [n for n in range(16) if bitmask & (1 << n)] node_versions = {} for n in active: nf = post(f"node-{n}", "/ms/0/0x16", f'{{"data":[{n}]}}') node_versions[n] = parse_hex(read_data(nf)[4]) & 0xff post("mac", "/ms/1/0x103/GET", f'{{"data":[{my_node}]}}') post("ip", "/ms/1/0x20b/GET", "") post("chip-id", "/ms/1/0x303/GET", '{"data":[0]}') post("frame-info", "/ms/0/0x14", '{"data":[0]}') post("misc-phy", "/ms/0/0x24", '{"data":[]}') post("misc-phy25", "/ms/0/0x7f", '{"data":[]}') post("lof", "/ms/0/0x1003/GET", "") nc_ver = node_versions.get(nc_node, 0) for n in active: version = 2 if min(nc_ver, node_versions.get(n, 0)) >= 0x20 else 1 post(f"fmr-{n}", "/ms/0/0x1D", f'{{"data":[{1 << n},{version}]}}') capture = { "device": name, "captured_at": datetime.datetime.now(datetime.timezone.utc).isoformat(), "note": ( "One-shot capture of MA2500D management endpoints for test " "mocking. HTTP Basic auth and the rotating CSRF cookie/token were " "used on the wire but are not recorded." ), "requests": entries, } (dev_dir / "capture.json").write_text(json.dumps(capture, indent=2) + "\n") def main(argv): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--config", type=pathlib.Path, default=DEFAULT_CONFIG) parser.add_argument("--out", type=pathlib.Path, default=DEFAULT_OUT) args = parser.parse_args(argv) devices = parse_config(args.config) if not devices: raise SystemExit(f"no devices in {args.config}") for name, url in devices: log(f"capturing {name}") capture_device(name, url, args.out) log("done") if __name__ == "__main__": main(sys.argv[1:])