From dd608e6a206e85990654e3c4b69be7dccc9ee26f Mon Sep 17 00:00:00 2001 From: Lucio Chen Date: Mon, 27 Jul 2026 03:58:14 -0700 Subject: [PATCH] Add Aruba InstantOS certificate update tool and hermes skill Automates pushing a renewed TLS certificate to an Aruba InstantOS AP and pointing the Web UI certificate usage at it, replacing the manual Maintenance -> Certificates flow. Commands: status, check-caddy, check-ap, update. `update` is idempotent, so it is safe to run on a schedule. The /swarm.cgi API was reverse-engineered from the InstantOS 8.x web UI bundle and verified against live hardware. Four behaviours documented in the README each silently break a naive implementation: - scalars return as rather than named tags, including the login sid - cert types are ServerCert/TrustedCA/ClientCert/PublicCert; the server_cert values in the bundle are overwritten at runtime - uploads are synchronous and the POST body is the only real result; upload_status returns not_available even for uploads that succeeded - the AP closes TLS without close_notify, which OpenSSL 3 rejects Credentials are read from ~/.config/aruba-ap-cert/.env, outside the repo. Co-Authored-By: Claude Opus 5 --- .env.example | 14 + .gitattributes | 2 + .gitignore | 12 + README.md | 200 +++++++++ SKILL.md | 113 +++++ aruba_cert.py | 1082 ++++++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 1423 insertions(+) create mode 100644 .env.example create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 README.md create mode 100644 SKILL.md create mode 100644 aruba_cert.py diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..806deed --- /dev/null +++ b/.env.example @@ -0,0 +1,14 @@ +# Copy to ~/.config/aruba-ap-cert/.env and fill in. Never commit the real file. +# mkdir -p ~/.config/aruba-ap-cert && chmod 700 ~/.config/aruba-ap-cert +# cp .env.example ~/.config/aruba-ap-cert/.env +# chmod 600 ~/.config/aruba-ap-cert/.env + +# AP portal address -- IP or hostname, with port (InstantOS uses 4343). +ARUBA_HOST=10.0.0.2:4343 + +# The same login you use for the AP's web portal. +ARUBA_USERNAME=admin +ARUBA_PASSWORD= + +# Only if the private key file is encrypted. +#ARUBA_KEY_PASSPHRASE= diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..871723e --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +* text=auto eol=lf +*.py text eol=lf diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1831622 --- /dev/null +++ b/.gitignore @@ -0,0 +1,12 @@ +# Credentials -- never commit +.env +.env.local + +# Private keys and combined bundles (a bundle contains the key) +*.key +*.pem +*.combined.crt +wildcard_* + +__pycache__/ +*.pyc diff --git a/README.md b/README.md new file mode 100644 index 0000000..0244c6e --- /dev/null +++ b/README.md @@ -0,0 +1,200 @@ +# aruba-cert + +Push a renewed TLS certificate to an Aruba InstantOS AP / Virtual Controller and +point the Web UI at it — the scripted version of **Maintenance → Certificates → +Upload New Certificate**, followed by **Certificate Usage → +**. + +Built for a setup where Caddy renews a wildcard certificate via Let's Encrypt +and the AP needs to be updated by hand afterwards. + +## Requirements + +```bash +pip install requests cryptography +``` + +Python 3.9+. Works with `cryptography` 41 and newer. + +## Commands + +```bash +python3 aruba_cert.py status # compare Caddy against the AP +python3 aruba_cert.py check-caddy # expiry of the cert in Caddy's store +python3 aruba_cert.py check-ap # expiry of the cert live on the AP +python3 aruba_cert.py update # combine, upload, re-point the usage +``` + +`update` is idempotent: if the AP already serves a certificate as new as the +source, it reports that and exits 0 without changing anything. `--force` +overrides, `--dry-run` previews. + +`check-caddy` needs no credentials. + +## Credential setup + +The script needs the AP's admin login. It is never passed on the command line. + +**1. Create the credential file.** It lives outside the repo so it can never be +committed: + +```bash +mkdir -p ~/.config/aruba-ap-cert && chmod 700 ~/.config/aruba-ap-cert +cp .env.example ~/.config/aruba-ap-cert/.env +chmod 600 ~/.config/aruba-ap-cert/.env +``` + +**2. Fill it in** with the same username and password you use to log in to the +AP's web portal at `https://:4343`: + +```ini +ARUBA_HOST=10.0.0.2:4343 +ARUBA_USERNAME=admin +ARUBA_PASSWORD=your-password +``` + +`ARUBA_HOST` takes an IP or hostname **with port** — the InstantOS portal +normally listens on 4343. These two values are the only things that change +between deployments. + +**3. Check it works:** + +```bash +python3 aruba_cert.py check-ap +``` + +A wrong password gives `login failed -- the AP did not return a session id`. + +### Where credentials are read from + +In order, first match wins: + +1. `--password-file ` +2. `$ARUBA_PASSWORD` — a real environment variable beats the file +3. `~/.config/aruba-ap-cert/.env` +4. `.env` beside the script, then `./.env` +5. an interactive prompt, only if stdin is a terminal + +`--env-file` points somewhere else entirely. If the private key is encrypted, +set `ARUBA_KEY_PASSPHRASE` the same way. + +> **Never commit `.env`.** It is gitignored here, but the safest habit is to +> keep it in `~/.config/` as above and leave the repo copy as `.env.example`. + +## Where the certificate comes from + +By default, a Caddy ACME storage directory holding `.crt` (leaf + chain) +and `.key`: + +``` +/mnt/lu-nas/docker/caddy/data/caddy/certificates/acme-v02.api.letsencrypt.org-directory/wildcard_.luci.ooo/ +``` + +Override with `--caddy-dir `, `$CADDY_CERT_DIR`, or an arbitrary pair via +`--cert` / `--key`. + +## What `update` does + +1. Loads the certificate and key, and confirms the key actually matches the + certificate — refusing to upload a mismatched pair. Warns if the matching + certificate is a CA certificate, which usually means the wrong key. +2. Concatenates them as **cert, chain, key**. The private key must come *after* + the certificate for InstantOS. +3. Skips the upload if the AP already has something this new, unless `--force`. +4. Uploads via multipart POST to `/swarm.cgi`, naming the certificate after its + expiry in local time — `Sep2_2026` — then confirms it appears in + `show cert all`. +5. Pushes the certificate usage: + + ``` + wlan cert-assignment-profile + pki-cert-assign application ui cert-type ServerCert certname + exit + ``` + +6. Prints `show cert assignment`, and deletes the temporary bundle, which + contains the private key. + +## Useful flags + +| Flag | Effect | +| --- | --- | +| `--dry-run` | Build the bundle and print the plan; no AP contact. | +| `--force` | Upload even if the AP already has a certificate this new. | +| `--no-assign` | Upload only, leave Certificate Usage alone. | +| `--application` | Which usage to set. Default `ui`. Also `radius`, `captive-portal`, `radsec`, `datatunnel`, `clearpass`, `webcc`. | +| `--upload-type` | Certificate slot: `server` (default), `ca`, `client`, `public`. | +| `--cert-name` | Override the expiry-derived name. | +| `--replace` | Delete an existing certificate of the same name first. | +| `--keep-bundle` | Do not delete the combined bundle afterwards. | +| `--verify` | Verify the AP's TLS certificate. Off by default — you are usually replacing the very certificate you would verify against. | + +## Automation + +Safe to run on a schedule, since it exits 0 without side effects when the AP is +already current: + +```bash +python3 aruba_cert.py update +``` + +Exit code is `0` on success (including "nothing to do") and `1` on failure. + +## Notes and caveats + +- **The Web UI certificate takes effect when the AP's web server restarts.** If + the portal still serves the old certificate after a successful update, reboot + the virtual controller. +- **`ui` and `captive-portal` are independent usages** pointing at independent + certificates. Updating one leaves the other alone. +- `--replace` deletes before uploading. If the upload then fails, that + certificate is gone from the AP. Prefer letting the expiry-based naming create + a new entry instead. +- The AP rejects a re-upload of an identical certificate with + `Abort because Cert with same digest already exists as `. + +## Protocol reference + +Reverse-engineered from the InstantOS 8.x web UI bundle (`/jscripts/app.js`) and +verified against a live AP. All calls go to `/swarm.cgi`; responses are XML +rooted at ``, with errors in ``. + +| Operation | Request | +| --- | --- | +| Login | `opcode=login user=.. passwd=..` | +| Show | `opcode=show cmd="show cert all"` | +| Config push | `opcode=config cmd=""` | +| Action | `opcode=action cmd="crypto pki-remove ..."` | +| Upload | multipart, `opcode=cert-upload-new`, file field `cert`, plus `cert_name`, `cert_type`, `cert_format`, `psk`, `upload_id` | + +Four things about this API are not obvious, and each one silently breaks a +straightforward implementation: + +**Scalars are not returned as named tags.** They arrive as +`success`, and the UI derives a +key by stripping quotes, trimming, collapsing whitespace to `_`, mapping `-` to +`_`, and lowercasing — giving `operation_state`. The login `sid` arrives this +way too, so looking for a `` element finds nothing and every login appears +to fail. Tables use a separate `....` shape. + +**Certificate types are `ServerCert` / `TrustedCA` / `ClientCert` / +`PublicCert`.** The bundle appears to offer `server_cert`, `ca_cert` and friends, +but that option list is overwritten at runtime via babel's `_defineProperty` +helper. Sending `server_cert` fails with `Cert Path: cert type is unknown`. + +**Uploads are synchronous, and the POST body is the only real result.** The web +UI polls `opcode=upload_status&oper_id=..`, but at least this AP answers +`not_available` for every id — including uploads that demonstrably succeeded. +Trusting that poll reports working uploads as failures. Read the POST body for +``, then confirm via `show cert all`. + +**The AP closes TLS without a `close_notify` alert.** OpenSSL 3 treats that as a +truncated response and discards the body, so every request fails with +`ChunkedEncodingError`. The client sets `OP_IGNORE_UNEXPECTED_EOF`, which is what +curl and the AP's own web UI effectively do. + +A failed login returns `` with no `sid`; an expired session returns +`Invalid Session ID`. + +`show supported-cert-formats` on this hardware reports **PEM as the only +supported server-certificate format**, so a combined PEM bundle is the required +upload shape — PKCS#12 is not available for server certificates. diff --git a/SKILL.md b/SKILL.md new file mode 100644 index 0000000..58af6bd --- /dev/null +++ b/SKILL.md @@ -0,0 +1,113 @@ +--- +name: aruba-ap-cert +description: Check and update the TLS certificate on the Aruba InstantOS AP portal (aruba.luci.ooo:4343) from Caddy's Let's Encrypt store on LU-NAS. Use for checking cert expiry on either side, or pushing a renewed wildcard cert to the AP Web UI. +version: 1.0 +author: hermes +tags: [aruba, instantos, tls, certificate, caddy, luci.ooo, letsencrypt] +--- + +# Aruba AP Certificate Update + +## Overview + +Caddy on LU-NAS renews the `*.luci.ooo` wildcard certificate via Let's Encrypt. +The Aruba AP does **not** pick this up automatically — the cert must be combined +with its private key and uploaded to the AP portal by hand. This skill automates +that. + +Everything is in `aruba_cert.py` next to this file. Run it on **luhpe**, where +`/mnt/lu-nas` is mounted. + +## The three operations + +```bash +# 1. Expiry of the certificate Caddy has (no credentials needed) +python3 aruba_cert.py check-caddy + +# 2. Expiry of the certificate live on the AP Web UI +python3 aruba_cert.py check-ap + +# 3. Compare both side by side — start here +python3 aruba_cert.py status + +# 4. Push Caddy's certificate to the AP and point the Web UI at it +python3 aruba_cert.py update +``` + +`update` is **idempotent**: if the AP already serves a certificate as new as +Caddy's, it reports that and exits 0 without touching anything. Use `--force` +to override. Always sanity-check with `--dry-run` first when unsure. + +## Configuration + +Only two things ever change. Both live in `~/.config/aruba-ap-cert/.env` +(mode 600, deliberately outside the skills tree so it is never published): + +```ini +ARUBA_HOST=10.233.33.2:4343 +ARUBA_USERNAME=admin +ARUBA_PASSWORD=... +``` + +`ARUBA_HOST` accepts an IP or hostname, with port. Override per-run with +`--host`. A real environment variable beats the file; `--env-file` points +elsewhere. + +Everything else is baked in: the Caddy path, PEM format, the `cert,chain,key` +bundle order, and the `ui` certificate usage. + +## What `update` actually does + +1. Reads `wildcard_.luci.ooo.crt` + `.key` from Caddy's ACME store: + `/mnt/lu-nas/docker/caddy/data/caddy/certificates/acme-v02.api.letsencrypt.org-directory/wildcard_.luci.ooo/` +2. Verifies the key matches the certificate, then concatenates them as + **cert, chain, key** — the private key must come *after* the certificate. +3. Skips the upload if the AP already has something this new (unless `--force`). +4. Uploads to `/swarm.cgi` (`opcode=cert-upload-new`, PEM, server slot), naming + it after its expiry in local time — e.g. `Sep2_2026`, matching the existing + convention on the AP. +5. Pushes the certificate usage: + ``` + wlan cert-assignment-profile + pki-cert-assign application ui cert-type ServerCert certname + exit + ``` +6. Prints `show cert assignment` to confirm, and deletes the temporary bundle + (it contains the private key). + +## Gotchas + +- **The Web UI cert only takes effect when the AP's web server restarts.** If + `https://aruba.luci.ooo:4343` still serves the old cert after a successful + update, reboot the virtual controller. +- **The AP rejects a re-upload of an identical certificate**, replying + `Abort because Cert with same digest already exists as `. This is normal + when Caddy has not renewed yet — the idempotency check avoids hitting it. +- **`ui` and `captive-portal` are separate usages** pointing at separate certs. + This skill manages `ui` by default; pass `--application captive-portal` to + move that one too. +- The AP closes TLS without a `close_notify`, which OpenSSL 3 treats as a + truncated response. The script sets `OP_IGNORE_UNEXPECTED_EOF`; do not + "simplify" that adapter away or every call breaks. +- InstantOS returns scalars as ``, not as named tags. The + parser normalizes those keys; the login `sid` arrives the same way. +- **Uploads are synchronous and the POST body is the only real result.** The web + UI polls `opcode=upload_status&oper_id=...`, but this AP answers + `not_available` for *every* id — including uploads that demonstrably + succeeded. Trusting that poll reports working uploads as failures. The script + reads the POST body for ``, then confirms by looking the certificate up + in `show cert all`. Do not reintroduce polling. +- **Certificate types are `ServerCert` / `TrustedCA` / `ClientCert` / + `PublicCert`.** The UI bundle appears to offer `server_cert`, `ca_cert` etc., + but that option list is overwritten at runtime. Sending `server_cert` fails + with "Cert Path: cert type is unknown". + +## When to run + +Caddy renews roughly 30 days before expiry (the ACME renewal window is in +`wildcard_.luci.ooo.json`). A weekly `status` is enough to catch it; run +`update` once Caddy shows a newer date than the AP. + +```bash +python3 aruba_cert.py status && python3 aruba_cert.py update +``` diff --git a/aruba_cert.py b/aruba_cert.py new file mode 100644 index 0000000..952dc76 --- /dev/null +++ b/aruba_cert.py @@ -0,0 +1,1082 @@ +#!/usr/bin/env python3 +""" +Combine a TLS certificate + private key into a single PEM bundle and deploy it +to an Aruba InstantOS AP / Virtual Controller, then point the Web UI at it. + +Protocol notes (derived from the InstantOS 8.x web UI bundle, /jscripts/app.js): + + All backend calls go to POST|GET /swarm.cgi with an ``opcode`` parameter and, + after login, a ``sid`` session token. Responses are XML. + + login opcode=login user=.. passwd=.. -> .. + show opcode=show cmd="show cert all" + config opcode=config cmd="" + action opcode=action cmd="" + upload multipart POST, opcode=cert-upload-new, file field named "cert" + (upload_status/oper_id exists but always returns not_available here, + even for uploads that succeeded -- the POST body is the real result) + + The certificate -> application binding ("Certificate Usage" in the UI) is a + config push, not an upload parameter: + + wlan cert-assignment-profile + pki-cert-assign application ui cert-type ServerCert certname + exit + +Usage: + python aruba_cert.py combine --cert fullchain.pem --key privkey.pem \ + --out wildcard.crt + + python aruba_cert.py deploy --cert fullchain.pem --key privkey.pem \ + --host 10.233.33.2:4343 --cert-name wildcard-luci-ooo + +Credentials are read from $ARUBA_USERNAME / $ARUBA_PASSWORD, or --password-file, +or an interactive prompt. Never pass the password on the command line. +""" + +from __future__ import annotations + +import argparse +import datetime +import getpass +import os +import re +import ssl +import sys +import tempfile +import time +import uuid +import xml.etree.ElementTree as ET +from dataclasses import dataclass +from pathlib import Path + +import requests +import urllib3 +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization + +urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) + +DEFAULT_HOST = "10.233.33.2:4343" +CERT_NAME_RE = re.compile(r"^[A-Za-z0-9_.-]{1,64}$") + +# Caddy's ACME storage on LU-NAS, mounted on luhpe. Caddy writes .crt +# (leaf + chain) and .key next to each other, named after the directory. +DEFAULT_CADDY_DIR = Path( + "/mnt/lu-nas/docker/caddy/data/caddy/certificates" + "/acme-v02.api.letsencrypt.org-directory/wildcard_.luci.ooo" +) + +# Which certificate usage this tool manages by default. +DEFAULT_APPLICATION = "ui" + + +def cert_not_after(cert: x509.Certificate) -> datetime.datetime: + """Timezone-aware expiry, across cryptography versions. + + not_valid_after_utc arrived in cryptography 42; luhpe ships 41, where the + equivalent attribute is naive UTC. + """ + value = getattr(cert, "not_valid_after_utc", None) + if value is not None: + return value + return cert.not_valid_after.replace(tzinfo=datetime.timezone.utc) + + +def parse_ap_date(text: str) -> datetime.datetime | None: + """Parse the AP's date format, e.g. 'Sep 3 05:59:11 2026 GMT'.""" + cleaned = re.sub(r"\s+", " ", (text or "").strip()).replace(" GMT", "") + for fmt in ("%b %d %H:%M:%S %Y", "%b %d %Y"): + try: + return datetime.datetime.strptime(cleaned, fmt).replace( + tzinfo=datetime.timezone.utc + ) + except ValueError: + continue + return None + + +def days_left(when: datetime.datetime) -> int: + return (when - datetime.datetime.now(datetime.timezone.utc)).days + + +def caddy_pair(directory: Path) -> tuple[Path, Path]: + """Return (cert, key) paths inside a Caddy certificate directory.""" + stem = directory.name + cert, key = directory / f"{stem}.crt", directory / f"{stem}.key" + if not cert.is_file(): + found = sorted(directory.glob("*.crt")) + if not found: + raise ArubaError(f"no .crt found in {directory}") + cert = found[0] + key = cert.with_suffix(".key") + if not key.is_file(): + raise ArubaError(f"no key file alongside {cert}") + return cert, key + +PEM_CERT_RE = re.compile( + rb"-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----\s*", re.DOTALL +) +PEM_KEY_RE = re.compile( + rb"-----BEGIN (?:RSA |EC |ENCRYPTED )?PRIVATE KEY-----" + rb".*?" + rb"-----END (?:RSA |EC |ENCRYPTED )?PRIVATE KEY-----\s*", + re.DOTALL, +) + +# Certificate-type tokens. The web UI's upload dialog appears to offer +# ca_cert/server_cert/... but that inline option list is overwritten via babel's +# _defineProperty helper, so the values actually submitted are these -- the same +# tokens used by "show cert all", cert assignment, and pki-remove. Sending +# server_cert instead makes the AP drop the upload without recording an error. +CERT_TYPES = { + "server": "ServerCert", + "ca": "TrustedCA", + "client": "ClientCert", + "public": "PublicCert", +} + +# Certificate-usage applications, and the cert type each one accepts. +APPLICATION_CERT_TYPE = { + "radius": "ServerCert", + "captive-portal": "ServerCert", + "radsec": "ClientCert", + "ui": "ServerCert", + "datatunnel": "ClientCert", + "clearpass": "TrustedCA", + "webcc": "TrustedCA", +} + + +class ArubaError(RuntimeError): + pass + + +def log(msg: str) -> None: + print(msg, file=sys.stderr, flush=True) + + +# -------------------------------------------------------------------------- +# .env loading +# -------------------------------------------------------------------------- + + +def load_env_file(path: Path | None = None) -> Path | None: + """Load KEY=VALUE pairs from a .env file into os.environ. + + Real environment variables win over the file, so an inline + ARUBA_PASSWORD=... still overrides whatever the file says. Returns the file + that was loaded, or None. + """ + if path: + candidates = [path] + else: + # ~/.config first, deliberately: the skill directory can be published to + # GitHub, so the credential must not live beside the script. + candidates = [ + Path.home() / ".config" / "aruba-ap-cert" / ".env", + Path(__file__).resolve().parent / ".env", + Path(".env"), + ] + for candidate in candidates: + if not candidate or not candidate.is_file(): + continue + for raw in candidate.read_text(encoding="utf-8").splitlines(): + line = raw.strip() + if not line or line.startswith("#"): + continue + if line.lower().startswith("export "): + line = line[7:].lstrip() + key, sep, value = line.partition("=") + if not sep: + continue + key = key.strip() + value = value.strip() + if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'": + value = value[1:-1] + os.environ.setdefault(key, value) + return candidate + return None + + +# -------------------------------------------------------------------------- +# Certificate bundling +# -------------------------------------------------------------------------- + + +@dataclass +class Bundle: + leaf: x509.Certificate + chain: list[x509.Certificate] + key_pem: bytes + cert_pems: list[bytes] + + +def _load_key(key_bytes: bytes, passphrase: bytes | None): + return serialization.load_pem_private_key(key_bytes, password=passphrase) + + +def build_bundle(cert_path: Path, key_path: Path, key_passphrase: bytes | None) -> Bundle: + """Parse cert + key, verify they belong together, return the pieces.""" + cert_blob = cert_path.read_bytes() + key_blob = key_path.read_bytes() + + cert_pems = [m.group(0) for m in PEM_CERT_RE.finditer(cert_blob)] + if not cert_pems: + raise ArubaError(f"no PEM certificate found in {cert_path}") + + # The key may live in its own file or be embedded in the cert file already. + key_match = PEM_KEY_RE.search(key_blob) or PEM_KEY_RE.search(cert_blob) + if not key_match: + raise ArubaError(f"no PEM private key found in {key_path}") + key_pem = key_match.group(0) + + certs = [x509.load_pem_x509_certificate(p) for p in cert_pems] + key = _load_key(key_pem, key_passphrase) + + # Leaf = the cert whose public key matches the private key. + key_pub = key.public_key().public_bytes( + serialization.Encoding.DER, + serialization.PublicFormat.SubjectPublicKeyInfo, + ) + leaf_idx = None + for i, c in enumerate(certs): + c_pub = c.public_key().public_bytes( + serialization.Encoding.DER, + serialization.PublicFormat.SubjectPublicKeyInfo, + ) + if c_pub == key_pub: + leaf_idx = i + break + if leaf_idx is None: + raise ArubaError( + "private key does not match any certificate in the cert file -- " + "check that --cert and --key are a matching pair" + ) + + leaf = certs[leaf_idx] + chain = [c for i, c in enumerate(certs) if i != leaf_idx] + + # If the key happens to match a CA in the chain rather than the server + # certificate, the bundle would look valid but serve the wrong identity. + try: + bc = leaf.extensions.get_extension_for_class(x509.BasicConstraints).value + if bc.ca: + log( + "[!] warning: the certificate matching this key is a CA " + "certificate (basicConstraints CA:TRUE). Confirm you passed the " + "server key, not a CA key." + ) + except x509.ExtensionNotFound: + pass + + ordered_pems = [cert_pems[leaf_idx]] + [ + p for i, p in enumerate(cert_pems) if i != leaf_idx + ] + return Bundle(leaf=leaf, chain=chain, key_pem=key_pem, cert_pems=ordered_pems) + + +def describe(bundle: Bundle) -> str: + leaf = bundle.leaf + try: + cn = leaf.subject.get_attributes_for_oid(x509.oid.NameOID.COMMON_NAME)[0].value + except IndexError: + cn = "(no CN)" + try: + sans = leaf.extensions.get_extension_for_class( + x509.SubjectAlternativeName + ).value.get_values_for_type(x509.DNSName) + except x509.ExtensionNotFound: + sans = [] + not_after = cert_not_after(leaf) + days = days_left(not_after) + fp = leaf.fingerprint(hashes.SHA256()).hex(":") + return ( + f" subject CN : {cn}\n" + f" SANs : {', '.join(sans) if sans else '(none)'}\n" + f" issuer : {leaf.issuer.rfc4514_string()}\n" + f" not after : {not_after.isoformat()} ({days} days left)\n" + f" chain certs: {len(bundle.chain)}\n" + f" sha256 : {fp}" + ) + + +def render_bundle(bundle: Bundle, order: str) -> bytes: + """Concatenate key/leaf/chain in the requested order.""" + parts: list[bytes] = [] + for token in order.split(","): + token = token.strip() + if token == "key": + parts.append(bundle.key_pem) + elif token == "cert": + parts.append(bundle.cert_pems[0]) + elif token == "chain": + parts.extend(bundle.cert_pems[1:]) + else: + raise ArubaError(f"unknown --order component {token!r}") + out = b"".join(p if p.endswith(b"\n") else p + b"\n" for p in parts) + return out + + +def write_bundle(data: bytes, out_path: Path) -> None: + out_path.write_bytes(data) + try: + os.chmod(out_path, 0o600) + except OSError: + pass # best effort; Windows ACLs are not POSIX modes + + +# -------------------------------------------------------------------------- +# InstantOS client +# -------------------------------------------------------------------------- + + +class InstantAdapter(requests.adapters.HTTPAdapter): + """TLS adapter tolerating InstantOS's unclean connection shutdown. + + The AP finishes a response by closing the TLS connection without sending a + close_notify alert. OpenSSL 3 treats that as a truncation attack and raises, + which loses a response body that in fact arrived intact -- so every call + would fail with ChunkedEncodingError. OP_IGNORE_UNEXPECTED_EOF restores the + lenient behaviour that curl and the AP's own web UI rely on. + """ + + def __init__(self, verify: bool, **kwargs): + self._verify = verify + super().__init__(**kwargs) + + def _context(self) -> ssl.SSLContext: + ctx = ssl.create_default_context() + if not self._verify: + ctx.check_hostname = False + ctx.verify_mode = ssl.CERT_NONE + ctx.options |= getattr(ssl, "OP_IGNORE_UNEXPECTED_EOF", 0) + return ctx + + def init_poolmanager(self, *args, **kwargs): + kwargs["ssl_context"] = self._context() + return super().init_poolmanager(*args, **kwargs) + + def proxy_manager_for(self, *args, **kwargs): + kwargs["ssl_context"] = self._context() + return super().proxy_manager_for(*args, **kwargs) + + +class InstantClient: + def __init__(self, host: str, verify: bool = False, timeout: int = 60): + if "://" in host: + self.base = host.rstrip("/") + else: + self.base = f"https://{host}" + self.url = f"{self.base}/swarm.cgi" + self.timeout = timeout + self.sid: str | None = None + self.session = requests.Session() + self.session.verify = verify + self.session.mount("https://", InstantAdapter(verify)) + + # -- transport --------------------------------------------------------- + + def _params(self, extra: dict) -> dict: + nosid = extra.pop("nosid", False) + p = {"ip": "127.0.0.1", "nocache": str(time.time())} + if self.sid and not nosid: + p["sid"] = self.sid + p.update(extra) + return p + + def _call(self, method: str, **params) -> ET.Element: + data = self._params(params) + if isinstance(data.get("cmd"), (list, tuple)): + data["cmd"] = "\n".join(data["cmd"]) + try: + if method == "post": + r = self.session.post(self.url, data=data, timeout=self.timeout) + else: + r = self.session.get(self.url, params=data, timeout=self.timeout) + except requests.RequestException as e: + raise ArubaError(f"request to {self.url} failed: {e}") from e + r.raise_for_status() + return self._parse(r.content) + + @staticmethod + def _parse(body: bytes) -> ET.Element: + try: + root = ET.fromstring(body) + except ET.ParseError as e: + snippet = body[:400].decode("utf-8", "replace") + raise ArubaError(f"could not parse XML response: {e}\n{snippet}") from e + err = root.find(".//error") + if err is not None and (err.text or "").strip(): + raise ArubaError(f"AP returned an error: {err.text.strip()}") + return root + + @staticmethod + def _norm_key(name: str) -> str: + """Mirror the web UI's XML key normalisation. + + InstantOS returns scalars as value + rather than as named tags, and the UI derives its property names by + stripping quotes, trimming, collapsing whitespace to underscores, and + lowercasing. " Operation State " therefore becomes operation_state. + """ + key = name.replace('"', "").strip() + key = re.sub(r"\s+", "_", key) + return key.replace("-", "_").lower() + + @classmethod + def _fields(cls, root: ET.Element) -> dict[str, str]: + fields: dict[str, str] = {} + for el in root.iter("data"): + name = el.get("name") + if name is None: + continue + fields.setdefault(cls._norm_key(name), (el.text or "").strip()) + return fields + + @classmethod + def _text(cls, root: ET.Element, key: str) -> str | None: + """Look up a scalar by key, falling back to a real tag.""" + value = cls._fields(root).get(key) + if value: + return value + node = root.find(f".//{key}") + return node.text.strip() if node is not None and node.text else None + + # -- operations -------------------------------------------------------- + + def login(self, user: str, password: str) -> None: + root = self._call("post", opcode="login", nosid=True, user=user, passwd=password) + sid = self._text(root, "sid") + if not sid: + raise ArubaError( + "login failed -- the AP did not return a session id. " + "Check the username and password." + ) + self.sid = sid + log(f"[+] logged in to {self.base} as {user}") + + def logout(self) -> None: + if not self.sid: + return + try: + self._call("post", opcode="logout") + except Exception: + pass + self.sid = None + + def show(self, cmd: str) -> ET.Element: + return self._call("get", opcode="show", cmd=cmd) + + def show_text(self, cmd: str) -> str: + return self.render(self.show(cmd)) + + @staticmethod + def render(root: ET.Element) -> str: + """Render an InstantOS response readably. + + Responses mix two shapes: value scalars, and + tables built from headers and cells. Flattening the text + loses the table structure, so handle each shape explicitly. + """ + lines: list[str] = [] + for el in root: + if el.tag == "data": + name = (el.get("name") or "").strip() + value = (el.text or "").strip() + if name and value: + lines.append(f"{name}: {value}") + elif value: + lines.append(value) + elif name: + lines.append(f"{name}:") + elif el.tag == "t": + lines.extend(InstantClient._render_table(el)) + return "\n".join(lines) + + @staticmethod + def _render_table(table: ET.Element) -> list[str]: + headers = [(h.text or "").strip() for h in table.findall("./th/h")] + rows = [ + [(c.text or "").strip() for c in r.findall("./c")] + for r in table.findall("./r") + ] + if not headers and not rows: + return [] + widths = [len(h) for h in headers] + for row in rows: + for i, cell in enumerate(row): + if i < len(widths): + widths[i] = max(widths[i], len(cell)) + else: + widths.append(len(cell)) + + def fmt(cells: list[str]) -> str: + return " ".join(c.ljust(widths[i]) for i, c in enumerate(cells)).rstrip() + + out = [] + name = (table.get("tn") or "").strip() + if name: + out.append(f"{name}:") + if headers: + out.append(" " + fmt(headers)) + out.append(" " + " ".join("-" * w for w in widths).rstrip()) + for row in rows: + out.append(" " + fmt(row)) + return out + + def config(self, cmd: str) -> ET.Element: + return self._call("post", opcode="config", cmd=cmd) + + def action(self, cmd: str) -> ET.Element: + return self._call("post", opcode="action", cmd=cmd) + + def remove_cert(self, cert_type: str, cert_name: str) -> None: + log(f"[*] removing existing certificate {cert_name} ({cert_type})") + self.action(f"crypto pki-remove cert-type {cert_type} certname {cert_name}\n") + + def upload_cert( + self, + data: bytes, + filename: str, + cert_name: str, + cert_type: str = "server_cert", + cert_format: str = "pem_format", + passphrase: str = "", + poll_timeout: int = 180, + ) -> str: + """Multipart upload, then poll upload_status until it settles.""" + if not self.sid: + raise ArubaError("not logged in") + oper_id = str(uuid.uuid4()) + + # Field order mirrors the web UI: hidden inputs first, file last. + fields = [ + ("upload_id", oper_id), + ("opcode", "cert-upload-new"), + ("sid", self.sid), + ("psk", passphrase if passphrase else '""'), + ("cert_type", cert_type), + ("cert_format", cert_format), + ("cert_name", cert_name), + ] + parts: list = [(k, (None, v)) for k, v in fields] + parts.append(("cert", (filename, data, "application/octet-stream"))) + + log(f"[*] uploading {filename} as certificate '{cert_name}' ({cert_type})") + try: + r = self.session.post(self.url, files=parts, timeout=self.timeout) + r.raise_for_status() + except requests.RequestException as e: + raise ArubaError(f"upload POST failed: {e}") from e + + # The upload is synchronous: the POST body carries the outcome, e.g. + # "Abort because Cert with same digest already exists as X". + body = r.content.lstrip() + if body.startswith(b" str: + deadline = time.time() + max(timeout, 10) + while True: + for record in self.cert_records(): + if record["cert_name"] == cert_name and record["cert_type"] == cert_type: + log(f"[+] upload confirmed: '{cert_name}' is installed") + return "installed" + if time.time() >= deadline: + raise ArubaError( + f"upload returned no error, but '{cert_name}' ({cert_type}) " + "did not appear in 'show cert all'" + ) + time.sleep(2) + + def assign_cert(self, application: str, cert_name: str, cert_type: str) -> None: + cmd = ( + "wlan cert-assignment-profile\n" + f"pki-cert-assign application {application} " + f"cert-type {cert_type} certname {cert_name}\n" + "exit\n" + ) + log(f"[*] assigning '{cert_name}' to application '{application}' ({cert_type})") + self.config(cmd) + + def list_certs(self) -> str: + return self.show_text("show cert all") + + def list_assignments(self) -> str: + return self.show_text("show cert assignment") + + def cert_records(self) -> list[dict]: + """Parse 'show cert all' into one record per installed certificate. + + The AP emits a flat stream where each installed certificate opens + with "Cert type"/"Cert name" and is followed by one block per + certificate in its chain. The leaf is the first block, so the first + Subject/Expires On after the name is the one that matters. + """ + records: list[dict] = [] + current: dict | None = None + for el in self.show("show cert all").iter("data"): + key = self._norm_key(el.get("name") or "") + value = (el.text or "").strip() + if key == "cert_type": + current = { + "cert_type": value, + "cert_name": None, + "subject": None, + "expires_on": None, + } + records.append(current) + elif current is None: + continue + elif key == "cert_name": + current["cert_name"] = value + elif key == "subject" and not current["subject"]: + current["subject"] = value + elif key == "expires_on" and not current["expires_on"]: + current["expires_on"] = value + return records + + def cert_assignments(self) -> list[dict]: + """Parse 'show cert assignment' into application/cert_type/cert_name.""" + root = self.show("show cert assignment") + rows: list[dict] = [] + for table in root.iter("t"): + for r in table.findall("./r"): + cells = [(c.text or "").strip() for c in r.findall("./c")] + if len(cells) >= 3: + rows.append( + { + "application": cells[0], + "cert_type": cells[1], + "cert_name": cells[2], + } + ) + return rows + + def assigned_cert(self, application: str) -> dict | None: + """The certificate record currently bound to an application.""" + match = next( + (a for a in self.cert_assignments() if a["application"] == application), + None, + ) + if not match: + return None + record = next( + ( + c + for c in self.cert_records() + if c["cert_name"] == match["cert_name"] + and c["cert_type"] == match["cert_type"] + ), + None, + ) + return {**match, **(record or {})} + + +# -------------------------------------------------------------------------- +# Credentials +# -------------------------------------------------------------------------- + + +def resolve_password(args) -> str: + if args.password_file: + return Path(args.password_file).read_text(encoding="utf-8").strip() + env = os.environ.get("ARUBA_PASSWORD") + if env: + return env + if not sys.stdin.isatty(): + raise ArubaError( + "no password available. Set ARUBA_PASSWORD in " + f"{Path.home() / '.config' / 'aruba-ap-cert' / '.env'}, " + "or export $ARUBA_PASSWORD, or pass --password-file " + "(stdin is not a terminal, so cannot prompt)" + ) + return getpass.getpass(f"Password for {args.username}@{args.host}: ") + + +# -------------------------------------------------------------------------- +# CLI +# -------------------------------------------------------------------------- + + +def resolve_source(args) -> tuple[Path, Path]: + """Where the certificate comes from: explicit paths, else the Caddy store.""" + if args.cert and args.key: + return Path(args.cert), Path(args.key) + if args.cert or args.key: + raise ArubaError("pass both --cert and --key, or neither") + directory = Path(args.caddy_dir) + if not directory.is_dir(): + raise ArubaError( + f"Caddy certificate directory not found: {directory}\n" + " (this path lives on luhpe, where /mnt/lu-nas is mounted)" + ) + return caddy_pair(directory) + + +def load_source(args) -> Bundle: + cert_path, key_path = resolve_source(args) + passphrase = os.environ.get("ARUBA_KEY_PASSPHRASE") + log(f"[*] source: {cert_path}") + return build_bundle( + cert_path, key_path, passphrase.encode() if passphrase else None + ) + + +def default_cert_name(bundle: Bundle) -> str: + """Name a certificate after its expiry in local time, e.g. Sep2_2026. + + This reproduces the existing convention on the AP, where a cert expiring + 2026-09-03 05:59 UTC is named Sep2_2026 (local time in America/Los_Angeles). + """ + when = cert_not_after(bundle.leaf).astimezone() + return f"{when:%b}{when.day}_{when.year}" + + +def cmd_check_caddy(args) -> int: + bundle = load_source(args) + not_after = cert_not_after(bundle.leaf) + left = days_left(not_after) + print("Caddy certificate") + print(describe(bundle)) + print(f" would upload as: {default_cert_name(bundle)}") + if left < 0: + log("[!] this certificate has EXPIRED") + return 1 + return 0 + + +def cmd_check_ap(args) -> int: + password = resolve_password(args) + client = InstantClient(args.host, verify=args.verify, timeout=args.timeout) + try: + client.login(args.username, password) + assigned = client.assigned_cert(args.application) + finally: + client.logout() + + if not assigned: + log(f"[!] no certificate is assigned to application '{args.application}'") + return 1 + + expires = parse_ap_date(assigned.get("expires_on") or "") + print(f"Aruba AP certificate ({args.host}, application '{args.application}')") + print(f" cert name : {assigned.get('cert_name')}") + print(f" cert type : {assigned.get('cert_type')}") + print(f" subject : {assigned.get('subject') or '(unknown)'}") + if expires: + print(f" not after : {expires.isoformat()} ({days_left(expires)} days left)") + if days_left(expires) < 0: + log("[!] the certificate on the AP has EXPIRED") + return 1 + else: + print(f" not after : {assigned.get('expires_on') or '(unknown)'}") + return 0 + + +def cmd_status(args) -> int: + """Compare the Caddy certificate against the one live on the AP.""" + bundle = load_source(args) + caddy_expiry = cert_not_after(bundle.leaf) + caddy_name = default_cert_name(bundle) + + password = resolve_password(args) + client = InstantClient(args.host, verify=args.verify, timeout=args.timeout) + try: + client.login(args.username, password) + assigned = client.assigned_cert(args.application) + finally: + client.logout() + + ap_expiry = parse_ap_date((assigned or {}).get("expires_on") or "") + + print() + print(f"{'':10} {'certificate':22} {'expires':26} days") + print(f"{'-'*10} {'-'*22} {'-'*26} ----") + print( + f"{'Caddy':10} {caddy_name:22} {caddy_expiry.isoformat():26} " + f"{days_left(caddy_expiry)}" + ) + if assigned: + name = assigned.get("cert_name") or "(unknown)" + when = ap_expiry.isoformat() if ap_expiry else (assigned.get("expires_on") or "?") + left = str(days_left(ap_expiry)) if ap_expiry else "?" + print(f"{'Aruba AP':10} {name:22} {when:26} {left}") + else: + print(f"{'Aruba AP':10} (nothing assigned to '{args.application}')") + print() + + if ap_expiry and caddy_expiry <= ap_expiry: + print("=> AP is up to date; nothing to do.") + return 0 + print("=> Caddy has a newer certificate. Run 'update' to push it.") + return 0 + + +def cmd_combine(args) -> int: + bundle = load_source(args) + log("[+] certificate and key match") + log(describe(bundle)) + data = render_bundle(bundle, args.order) + out = Path(args.out) + write_bundle(data, out) + log(f"[+] wrote {out} ({len(data)} bytes, order: {args.order})") + return 0 + + +def cmd_update(args) -> int: + bundle = load_source(args) + log("[+] certificate and key match") + log(describe(bundle)) + data = render_bundle(bundle, args.order) + + # The bundle contains the private key, so keep it out of the Caddy store. + out = Path(args.out) if args.out else Path(tempfile.gettempdir()) / "aruba-upload.crt" + write_bundle(data, out) + log(f"[+] wrote {out} ({len(data)} bytes, order: {args.order})") + + cert_name = args.cert_name or default_cert_name(bundle) + cert_name = cert_name.replace(".", "-").replace("*", "wildcard") + if not CERT_NAME_RE.match(cert_name): + raise ArubaError( + f"derived certificate name {cert_name!r} is invalid; " + "pass --cert-name with 1-64 chars of [A-Za-z0-9_.-]" + ) + + upload_type = CERT_TYPES[args.upload_type] + assign_type = APPLICATION_CERT_TYPE[args.application] + + if args.dry_run: + log("[dry-run] would upload and assign:") + log(f" host : {args.host}") + log(f" file : {out}") + log(f" cert name : {cert_name}") + log(f" upload type : {upload_type} / pem_format") + log(f" assignment : application {args.application} cert-type {assign_type}") + if not args.keep_bundle: + out.unlink(missing_ok=True) + return 0 + + password = resolve_password(args) + client = InstantClient(args.host, verify=args.verify, timeout=args.timeout) + try: + client.login(args.username, password) + + # Idempotency: the AP rejects a re-upload of an identical certificate + # anyway, so skip early and keep scheduled runs quiet and side-effect + # free. --force pushes regardless. + assigned = client.assigned_cert(args.application) + ap_expiry = parse_ap_date((assigned or {}).get("expires_on") or "") + caddy_expiry = cert_not_after(bundle.leaf) + if assigned and ap_expiry and caddy_expiry <= ap_expiry and not args.force: + log( + f"[=] AP already serves '{assigned.get('cert_name')}' expiring " + f"{ap_expiry.date()} ({days_left(ap_expiry)} days left); " + "Caddy has nothing newer. Use --force to push anyway." + ) + return 0 + + if args.replace: + try: + client.remove_cert(CERT_TYPES[args.upload_type], cert_name) + except ArubaError as e: + log(f"[!] remove skipped: {e}") + + client.upload_cert( + data=data, + filename=out.name, + cert_name=cert_name, + cert_type=upload_type, + passphrase=args.upload_passphrase or "", + poll_timeout=args.poll_timeout, + ) + + if args.no_assign: + log("[*] --no-assign given; skipping certificate usage") + else: + client.assign_cert(args.application, cert_name, assign_type) + + log("\n=== show cert assignment ===") + print(client.list_assignments()) + finally: + client.logout() + # The bundle on disk contains the private key. + if not args.keep_bundle: + try: + out.unlink(missing_ok=True) + except OSError: + pass + + if not args.no_assign and args.application == "ui": + log( + "\n[i] The Web UI certificate is applied when the AP's web server " + "restarts. If https://%s still serves the old certificate, reboot " + "the virtual controller." % args.host + ) + return 0 + + +def cmd_show(args) -> int: + password = resolve_password(args) + client = InstantClient(args.host, verify=args.verify, timeout=args.timeout) + try: + client.login(args.username, password) + print("=== show cert all ===") + print(client.list_certs()) + print("\n=== show cert assignment ===") + print(client.list_assignments()) + finally: + client.logout() + return 0 + + +def build_parser() -> argparse.ArgumentParser: + p = argparse.ArgumentParser( + description="Combine a cert + key and deploy it to an Aruba InstantOS AP.", + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + sub = p.add_subparsers(dest="command", required=True) + + def add_source(sp): + sp.add_argument( + "--caddy-dir", + default=os.environ.get("CADDY_CERT_DIR", str(DEFAULT_CADDY_DIR)), + help="Caddy certificate directory (default: the LU-NAS ACME store)", + ) + sp.add_argument("--cert", help="override: certificate or fullchain PEM") + sp.add_argument("--key", help="override: private key PEM") + sp.add_argument( + "--order", + default="cert,chain,key", + help="component order in the bundle (default: cert,chain,key -- the " + "key must follow the certificate for InstantOS)", + ) + + def add_conn(sp): + sp.add_argument("--host", default=os.environ.get("ARUBA_HOST", DEFAULT_HOST)) + sp.add_argument( + "--username", default=os.environ.get("ARUBA_USERNAME", "admin") + ) + sp.add_argument("--password-file", help="file containing the password") + sp.add_argument( + "--env-file", + help="path to a .env file (default: .env beside this script, then ./.env)", + ) + sp.add_argument( + "--verify", + action="store_true", + help="verify the AP's TLS certificate (off by default -- you are " + "usually replacing an untrusted self-signed cert)", + ) + sp.add_argument("--timeout", type=int, default=60) + + def add_application(sp): + sp.add_argument( + "--application", + choices=sorted(APPLICATION_CERT_TYPE), + default=DEFAULT_APPLICATION, + help=f"certificate usage (default: {DEFAULT_APPLICATION} = Web UI)", + ) + + cc = sub.add_parser( + "check-caddy", help="expiry of the certificate in Caddy's store" + ) + add_source(cc) + cc.set_defaults(func=cmd_check_caddy) + + ca = sub.add_parser("check-ap", help="expiry of the certificate live on the AP") + add_conn(ca) + add_application(ca) + ca.set_defaults(func=cmd_check_ap) + + st = sub.add_parser("status", help="compare Caddy against the AP") + add_source(st) + add_conn(st) + add_application(st) + st.set_defaults(func=cmd_status) + + c = sub.add_parser("combine", help="only build the combined .crt file") + add_source(c) + c.add_argument("--out", required=True, help="output .crt path") + c.set_defaults(func=cmd_combine) + + d = sub.add_parser( + "update", help="combine, upload, and point the usage at the new certificate" + ) + add_source(d) + add_conn(d) + add_application(d) + d.add_argument("--out", help="combined .crt path (default: a temp file)") + d.add_argument( + "--cert-name", help="name on the AP (default: expiry-based, e.g. Sep2_2026)" + ) + d.add_argument( + "--force", + action="store_true", + help="upload even if the AP already has a certificate this new", + ) + d.add_argument( + "--keep-bundle", + action="store_true", + help="do not delete the combined bundle (it contains the private key)", + ) + d.add_argument( + "--upload-type", + choices=sorted(CERT_TYPES), + default="server", + help="upload slot (default: server)", + ) + d.add_argument( + "--upload-passphrase", + default=os.environ.get("ARUBA_UPLOAD_PASSPHRASE", ""), + help="passphrase for the uploaded bundle (leave empty for an " + "unencrypted key)", + ) + d.add_argument( + "--replace", + action="store_true", + help="delete an existing certificate with the same name first", + ) + d.add_argument("--no-assign", action="store_true", help="upload only") + d.add_argument("--poll-timeout", type=int, default=180) + d.add_argument("--dry-run", action="store_true") + d.set_defaults(func=cmd_update) + + s = sub.add_parser("show", help="list certificates and usages on the AP") + add_conn(s) + s.set_defaults(func=cmd_show) + + return p + + +def main() -> int: + # .env must be loaded before the parser is built, because argparse bakes the + # environment-derived defaults in at construction time. + pre = argparse.ArgumentParser(add_help=False) + pre.add_argument("--env-file") + known, _ = pre.parse_known_args() + loaded = load_env_file(Path(known.env_file) if known.env_file else None) + + args = build_parser().parse_args() + if loaded: + log(f"[+] loaded credentials from {loaded}") + elif known.env_file: + log(f"[!] --env-file {known.env_file} not found") + try: + return args.func(args) + except ArubaError as e: + log(f"[!] {e}") + return 1 + except KeyboardInterrupt: + return 130 + + +if __name__ == "__main__": + sys.exit(main())