Files
lucioandClaude Opus 5 dd608e6a20 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 <data name=".."> 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 <[email protected]>
2026-07-27 03:58:14 -07:00

1083 lines
38 KiB
Python

#!/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=.. -> <sid>..</sid>
show opcode=show cmd="show cert all"
config opcode=config cmd="<CLI lines>"
action opcode=action cmd="<CLI lines>"
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 <name>
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 <name>.crt
# (leaf + chain) and <name>.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 <data name="Operation State ">value</data>
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 <data name=..> 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: <data name=..>value</data> scalars, and <t>
tables built from <th><h>headers and <r><c>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.
# "<error>Abort because Cert with same digest already exists as X</error>".
body = r.content.lstrip()
if body.startswith(b"<?xml") or body.startswith(b"<re"):
self._parse(r.content)
# Do NOT trust opcode=upload_status here. Despite the web UI polling it
# with the upload's id, this AP returns not_available for every id --
# including uploads that demonstrably succeeded. Confirm by looking the
# certificate up instead, which is authoritative either way.
return self._confirm_upload(cert_name, cert_type, poll_timeout)
def _confirm_upload(self, cert_name: str, cert_type: str, timeout: int) -> 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 <data> 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())