From 0c554fdd24cac50a45ad358d63ee8eed769f481a Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Mon, 23 Nov 2026 11:41:17 +0100 Subject: [PATCH 01/29] refactor(debian): name the maintainer files after their binary package Prepares a second binary package from the same source: debian/install, links, preinst, postinst, prerm and postrm only apply to the first package, so they become debian/linuxmuster-squid.*. No content change. --- debian/{install => linuxmuster-squid.install} | 0 debian/{links => linuxmuster-squid.links} | 0 debian/{postinst => linuxmuster-squid.postinst} | 0 debian/{postrm => linuxmuster-squid.postrm} | 0 debian/{preinst => linuxmuster-squid.preinst} | 0 debian/{prerm => linuxmuster-squid.prerm} | 0 6 files changed, 0 insertions(+), 0 deletions(-) rename debian/{install => linuxmuster-squid.install} (100%) rename debian/{links => linuxmuster-squid.links} (100%) rename debian/{postinst => linuxmuster-squid.postinst} (100%) rename debian/{postrm => linuxmuster-squid.postrm} (100%) rename debian/{preinst => linuxmuster-squid.preinst} (100%) rename debian/{prerm => linuxmuster-squid.prerm} (100%) diff --git a/debian/install b/debian/linuxmuster-squid.install similarity index 100% rename from debian/install rename to debian/linuxmuster-squid.install diff --git a/debian/links b/debian/linuxmuster-squid.links similarity index 100% rename from debian/links rename to debian/linuxmuster-squid.links diff --git a/debian/postinst b/debian/linuxmuster-squid.postinst similarity index 100% rename from debian/postinst rename to debian/linuxmuster-squid.postinst diff --git a/debian/postrm b/debian/linuxmuster-squid.postrm similarity index 100% rename from debian/postrm rename to debian/linuxmuster-squid.postrm diff --git a/debian/preinst b/debian/linuxmuster-squid.preinst similarity index 100% rename from debian/preinst rename to debian/linuxmuster-squid.preinst diff --git a/debian/prerm b/debian/linuxmuster-squid.prerm similarity index 100% rename from debian/prerm rename to debian/linuxmuster-squid.prerm From 313365e0055ac3196d3b051c3c08694b4284e79c Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Mon, 23 Nov 2026 11:41:41 +0100 Subject: [PATCH 02/29] feat(controlplane): optional TLS listener, bulk status and schema for API clients With tls_bind_host set in config.yml a second uvicorn server serves the same app over TLS on that management address (default port 8443), next to the unchanged plain listener on 127.0.0.1 that the CLI and the maintainer scripts use. Without it the service starts exactly as before. tls_bind_host must be an IP literal and never 0.0.0.0/::; a missing certificate or key, a port clash or a bad tls_allowed_clients entry stop the service with a reason in the journal. tls_allowed_clients answers 403 to every other peer of the TLS listener. The postinst makes a self-signed EC certificate once (tls/api.key 0600, api.crt), never replacing an existing one; `lmnsquid tls fingerprint` prints its SHA-256 fingerprint for clients to pin. GET /v1/status (state of all instances in one call) and GET /v1/schema (the instance model's JSON schema with its defaults) are added for the WebUI plugin; no existing endpoint changes. Docs and ADR-018 follow with the plugin. --- controlplane/lmnsquid/api.py | 16 ++ controlplane/lmnsquid/cli.py | 19 ++ controlplane/lmnsquid/config.py | 7 + controlplane/lmnsquid/main.py | 93 +++++++++- controlplane/lmnsquid/tls.py | 147 ++++++++++++++++ controlplane/tests/test_api.py | 21 +++ controlplane/tests/test_tls.py | 283 ++++++++++++++++++++++++++++++ debian/linuxmuster-squid.postinst | 36 +++- 8 files changed, 615 insertions(+), 7 deletions(-) create mode 100644 controlplane/lmnsquid/tls.py create mode 100644 controlplane/tests/test_tls.py diff --git a/controlplane/lmnsquid/api.py b/controlplane/lmnsquid/api.py index 1abf79f..3ca6046 100644 --- a/controlplane/lmnsquid/api.py +++ b/controlplane/lmnsquid/api.py @@ -133,6 +133,22 @@ def update_all() -> dict[str, Any]: audit.info("update-all to default image=%s", DEFAULT_IMAGE) return {"results": updater.update_all(DEFAULT_IMAGE)} + @app.get("/v1/status", dependencies=auth) + def all_status() -> list[dict[str, Any]]: + """Container state of every stored instance in one call (overview of the WebUI plugin).""" + return [docker.status(inst.name) for inst in store.list()] + + @app.get("/v1/schema", dependencies=auth) + async def schema() -> dict[str, Any]: + """JSON schema of the instance model (fields, types, defaults), for client-side forms. + + Validation stays here: a client shows the 422 this API answers per field. + """ + return { + "instance": Instance.model_json_schema(), + "instance_patch": InstancePatch.model_json_schema(), + } + # --------------------------------------------------------------- instances @app.post( "/v1/instances", diff --git a/controlplane/lmnsquid/cli.py b/controlplane/lmnsquid/cli.py index b3f4b38..de3f3e9 100644 --- a/controlplane/lmnsquid/cli.py +++ b/controlplane/lmnsquid/cli.py @@ -12,6 +12,7 @@ import typer from .config import load_settings +from .tls import fingerprint_sha256 app = typer.Typer( help="linuxmuster-squid control-plane CLI (thin REST client).", @@ -431,6 +432,24 @@ def reconcile() -> None: _fail_if(resp.json().get("failed", []), "reconcile") +tls_app = typer.Typer( + help="The optional TLS listener for off-host clients such as the WebUI plugin (ADR-018).", + no_args_is_help=True, +) +app.add_typer(tls_app, name="tls") + + +@tls_app.command("fingerprint") +def tls_fingerprint() -> None: + """Print the SHA-256 fingerprint of the API certificate (tls_cert_file) to pin in a client.""" + settings = load_settings() + try: + typer.echo(fingerprint_sha256(settings.tls_cert_file)) + except (OSError, ValueError) as exc: + typer.secho(f"error: {exc}", fg=typer.colors.RED, err=True) + raise typer.Exit(1) from None + + def main() -> None: app() diff --git a/controlplane/lmnsquid/config.py b/controlplane/lmnsquid/config.py index 448d44d..7f0859f 100644 --- a/controlplane/lmnsquid/config.py +++ b/controlplane/lmnsquid/config.py @@ -35,6 +35,13 @@ class Settings(BaseSettings): # Narrow to a specific IP if the host has an untrusted interface. log_max_size: str = "20m" # docker json-log cap per container (live view) log_max_file: int = 5 + # Optional TLS listener for off-host clients such as the WebUI plugin (ADR-018). Off while + # tls_bind_host is unset; the plain listener on bind_host stays as it is either way. + tls_bind_host: str | None = None + tls_bind_port: int = 8443 + tls_cert_file: str = "/etc/linuxmuster-squid/tls/api.crt" + tls_key_file: str = "/etc/linuxmuster-squid/tls/api.key" + tls_allowed_clients: list[str] = [] # addresses/CIDRs; empty = any peer that reaches it model_config = SettingsConfigDict(env_prefix=_ENV_PREFIX) diff --git a/controlplane/lmnsquid/main.py b/controlplane/lmnsquid/main.py index 707ea59..efddbff 100644 --- a/controlplane/lmnsquid/main.py +++ b/controlplane/lmnsquid/main.py @@ -4,29 +4,37 @@ from __future__ import annotations +import asyncio import logging +import signal +from contextlib import contextmanager +from typing import Any, Iterator import uvicorn +from fastapi import FastAPI from .api import create_app -from .config import load_settings +from .config import Settings, load_settings from .docker_service import DockerService from .reconciler import Reconciler from .store import Store +from .tls import ClientAllowlist, Network, TLSConfigError, check_tls_settings from .updater import Updater +log = logging.getLogger("lmnsquid") + def _warn_if_insecure_bind(bind_host: str) -> None: """Warn if the API is bound off-loopback — the token would travel in cleartext. - In-app TLS is intentionally not implemented; off-host access must go through an - operator-managed TLS reverse proxy (see docs/architecture.md, threat-model T5). + Off-host clients belong on the optional TLS listener (``tls_bind_host``, ADR-018), not on + a plain listener off loopback (see docs/architecture.md, threat-model T5). """ if bind_host not in ("127.0.0.1", "localhost", "::1"): logging.getLogger("lmnsquid").warning( "API is bound to non-loopback %s over plain HTTP: the bearer token " - "(root-equivalent) travels in cleartext. Bind 127.0.0.1, or put an " - "operator-managed TLS reverse proxy in front — in-app TLS is not implemented.", + "(root-equivalent) travels in cleartext. Bind 127.0.0.1 and use the TLS " + "listener (tls_bind_host) for off-host clients.", bind_host, ) @@ -35,6 +43,14 @@ def main() -> None: """Load settings, wire the components together and run the uvicorn server.""" logging.basicConfig(level=logging.INFO) settings = load_settings() + # TLS settings are checked before anything else starts (Docker, the plain listener). + networks: list[Network] = [] + if settings.tls_bind_host: + try: + networks = check_tls_settings(settings) + except TLSConfigError as exc: + log.error("TLS listener not started, service stops: %s", exc) + raise SystemExit(2) from None store = Store(settings.instances_dir) docker = DockerService( settings.docker_host, @@ -48,7 +64,72 @@ def main() -> None: updater = Updater(store, docker, reconciler) app = create_app(settings, store, reconciler, docker, updater) _warn_if_insecure_bind(settings.bind_host) - uvicorn.run(app, host=settings.bind_host, port=settings.bind_port) + if not settings.tls_bind_host: + # Without TLS settings exactly the listener of every release before ADR-018. + uvicorn.run(app, host=settings.bind_host, port=settings.bind_port) + return + asyncio.run(serve_all(build_servers(settings, app, networks))) + + +class _Server(uvicorn.Server): + """A uvicorn server that leaves signal handling to :func:`serve_all`. + + Each uvicorn server would install its own SIGTERM/SIGINT handler and the second would + replace the first; one handler stops both instead. + """ + + @contextmanager + def capture_signals(self) -> Iterator[None]: + yield + + +def build_servers( + settings: Settings, app: FastAPI, networks: list[Network] +) -> list[uvicorn.Server]: + """The unchanged plain listener on ``bind_host`` plus the TLS listener (ADR-018).""" + if not settings.tls_bind_host: + raise ValueError("build_servers needs tls_bind_host (checked by check_tls_settings)") + plain = uvicorn.Config(app, host=settings.bind_host, port=settings.bind_port) + tls_app: Any = ClientAllowlist(app, networks) if networks else app + tls = uvicorn.Config( + tls_app, + host=settings.tls_bind_host, + port=settings.tls_bind_port, + ssl_certfile=settings.tls_cert_file, + ssl_keyfile=settings.tls_key_file, + lifespan="off", # the app's lifespan runs once, in the plain server + ) + log.info( + "TLS listener on %s:%s (clients: %s)", + settings.tls_bind_host, + settings.tls_bind_port, + ", ".join(str(n) for n in networks) or "any", + ) + return [_Server(plain), _Server(tls)] + + +async def serve_all(servers: list[uvicorn.Server]) -> None: + """Run ``servers`` together; SIGTERM/SIGINT or one server ending stops all of them.""" + loop = asyncio.get_running_loop() + + def stop() -> None: + for server in servers: + server.should_exit = True + + for sig in (signal.SIGTERM, signal.SIGINT): + loop.add_signal_handler(sig, stop) + tasks = [asyncio.create_task(server.serve()) for server in servers] + try: + done, _ = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) + stop() + await asyncio.gather(*tasks, return_exceptions=True) + for task in done: + task.result() # a server that failed to start (port taken) fails the service + if not all(server.started for server in servers): + raise SystemExit(1) + finally: + for sig in (signal.SIGTERM, signal.SIGINT): + loop.remove_signal_handler(sig) if __name__ == "__main__": diff --git a/controlplane/lmnsquid/tls.py b/controlplane/lmnsquid/tls.py new file mode 100644 index 0000000..c537d19 --- /dev/null +++ b/controlplane/lmnsquid/tls.py @@ -0,0 +1,147 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""Optional TLS listener of the control plane (ADR-018). + +Off unless ``tls_bind_host`` is set. Then a second uvicorn server serves the same app over +TLS on that management address, next to the unchanged plain listener on ``bind_host`` +(127.0.0.1, which the CLI and the maintainer scripts use). The certificate is the self-signed +one the postinst made; clients pin its SHA-256 fingerprint (``lmnsquid tls fingerprint``). +""" + +from __future__ import annotations + +import hashlib +import ipaddress +import json +import logging +import os +import re +import ssl +from pathlib import Path +from typing import Any, Awaitable, Callable, MutableMapping + +from .config import Settings + +log = logging.getLogger("lmnsquid") + +_PEM_CERT = re.compile(r"-----BEGIN CERTIFICATE-----.+?-----END CERTIFICATE-----", re.DOTALL) + +Network = ipaddress.IPv4Network | ipaddress.IPv6Network +Scope = MutableMapping[str, Any] +Message = MutableMapping[str, Any] +Receive = Callable[[], Awaitable[Message]] +Send = Callable[[Message], Awaitable[None]] +ASGIApp = Callable[[Scope, Receive, Send], Awaitable[None]] + + +class TLSConfigError(ValueError): + """The TLS settings cannot be used; the service refuses to start (no silent fallback).""" + + +def fingerprint_sha256(cert_file: str) -> str: + """SHA-256 over the DER form of the first certificate in ``cert_file``, as ``AA:BB:...``. + + The same value ``openssl x509 -noout -fingerprint -sha256`` prints. + """ + match = _PEM_CERT.search(Path(cert_file).read_text(encoding="ascii")) + if match is None: + raise ValueError(f"{cert_file}: no PEM certificate found") + digest = hashlib.sha256(ssl.PEM_cert_to_DER_cert(match.group(0))).hexdigest().upper() + return ":".join(digest[i : i + 2] for i in range(0, len(digest), 2)) + + +def check_tls_settings(settings: Settings) -> list[Network]: + """Validate the TLS listener settings; return the client allowlist (empty = everyone). + + Raises :class:`TLSConfigError` with a sentence for the journal. Only called when + ``tls_bind_host`` is set. + """ + host = settings.tls_bind_host or "" + try: + addr = ipaddress.ip_address(host) + except ValueError: + raise TLSConfigError( + f"tls_bind_host {host!r} is not an IP address: name the management address" + ) from None + if addr.is_unspecified: + # Every interface would expose a root-equivalent API (Docker socket); the listener + # must be pinned to the management network on purpose. + raise TLSConfigError( + f"tls_bind_host {host} binds every interface: refused, name the management address" + ) + if not 1 <= settings.tls_bind_port <= 65535: + raise TLSConfigError(f"tls_bind_port {settings.tls_bind_port} out of range") + if host == settings.bind_host and settings.tls_bind_port == settings.bind_port: + raise TLSConfigError("tls_bind_host:tls_bind_port is the same as bind_host:bind_port") + for label, path in ( + ("tls_cert_file", settings.tls_cert_file), + ("tls_key_file", settings.tls_key_file), + ): + if not os.access(path, os.R_OK): + raise TLSConfigError(f"{label} {path} is missing or not readable") + key_mode = os.stat(settings.tls_key_file).st_mode + if key_mode & 0o077: + log.warning( + "TLS key %s is group/world accessible (mode %o): chmod 600", + settings.tls_key_file, + key_mode & 0o777, + ) + try: + fingerprint_sha256(settings.tls_cert_file) + except (OSError, ValueError) as exc: + raise TLSConfigError(f"tls_cert_file: {exc}") from exc + networks: list[Network] = [] + for entry in settings.tls_allowed_clients: + try: + networks.append(ipaddress.ip_network(str(entry), strict=False)) + except ValueError: + raise TLSConfigError( + f"tls_allowed_clients: {entry!r} is not an address or CIDR" + ) from None + return networks + + +class ClientAllowlist: + """ASGI middleware for the TLS listener: answer 403 unless the peer is in ``networks``. + + Wraps only the TLS server's app; the loopback listener is not affected. + """ + + def __init__(self, app: ASGIApp, networks: list[Network]) -> None: + self.app = app + self.networks = networks + + def allowed(self, host: str | None) -> bool: + if host is None: + return False + try: + addr = ipaddress.ip_address(host) + except ValueError: + return False + if isinstance(addr, ipaddress.IPv6Address) and addr.ipv4_mapped is not None: + addr = addr.ipv4_mapped + return any(addr in net for net in self.networks) + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] in ("http", "websocket"): + client = scope.get("client") + host = client[0] if client else None + if not self.allowed(host): + log.warning("TLS listener: refused client %s (not in tls_allowed_clients)", host) + if scope["type"] == "websocket": + await send({"type": "websocket.close", "code": 1008}) + return + body = json.dumps({"detail": "client address not allowed"}).encode() + await send( + { + "type": "http.response.start", + "status": 403, + "headers": [ + (b"content-type", b"application/json"), + (b"content-length", str(len(body)).encode()), + ], + } + ) + await send({"type": "http.response.body", "body": body}) + return + await self.app(scope, receive, send) diff --git a/controlplane/tests/test_api.py b/controlplane/tests/test_api.py index 6e39105..22dcf9f 100644 --- a/controlplane/tests/test_api.py +++ b/controlplane/tests/test_api.py @@ -130,3 +130,24 @@ def test_patch_merges_onto_existing( stored = client.get(f"/v1/instances/{name}", headers=auth_headers).json() assert stored["cache_size_mb"] == 4096 + + +def test_status_of_all_instances( + client: TestClient, auth_headers: dict[str, str], instance_data: dict[str, Any] +) -> None: + assert client.get("/v1/status", headers=auth_headers).json() == [] + assert client.post("/v1/instances", json=instance_data, headers=auth_headers).status_code == 201 + body = client.get("/v1/status", headers=auth_headers).json() + assert [(s["name"], s["running"]) for s in body] == [("default-school-teachers", True)] + assert client.get("/v1/status").status_code == 401 + + +def test_schema_names_fields_and_defaults(client: TestClient, auth_headers: dict[str, str]) -> None: + resp = client.get("/v1/schema", headers=auth_headers) + assert resp.status_code == 200 + props = resp.json()["instance"]["properties"] + assert props["http_port"]["default"] == 3128 + assert props["krb5_clockskew_seconds"]["default"] == 300 + assert "name" not in props # computed, not an input + assert "school" not in resp.json()["instance_patch"]["properties"] + assert client.get("/v1/schema").status_code == 401 diff --git a/controlplane/tests/test_tls.py b/controlplane/tests/test_tls.py new file mode 100644 index 0000000..4216bf7 --- /dev/null +++ b/controlplane/tests/test_tls.py @@ -0,0 +1,283 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""The optional TLS listener (ADR-018): settings checks, allowlist, fingerprint, real servers.""" + +from __future__ import annotations + +import asyncio +import hashlib +import json +import shutil +import socket +import ssl +import subprocess +import urllib.request +from pathlib import Path +from typing import Any + +import pytest +from typer.testing import CliRunner + +from lmnsquid import cli, main +from lmnsquid.config import Settings +from lmnsquid.tls import ClientAllowlist, TLSConfigError, check_tls_settings, fingerprint_sha256 + +needs_openssl = pytest.mark.skipif(shutil.which("openssl") is None, reason="openssl missing") + + +def make_cert(directory: Path, cn: str = "proxy.example") -> tuple[Path, Path]: + """A self-signed certificate the way the postinst makes it.""" + key, crt = directory / "api.key", directory / "api.crt" + subprocess.run( + ["openssl", "req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1", + "-nodes", "-days", "30", "-subj", f"/CN={cn}", "-addext", f"subjectAltName=DNS:{cn}", + "-keyout", str(key), "-out", str(crt)], + check=True, capture_output=True, + ) # fmt: skip + key.chmod(0o600) + return crt, key + + +def free_port() -> int: + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return int(s.getsockname()[1]) + + +def tls_settings(tmp_path: Path, **kw: Any) -> Settings: + crt, key = make_cert(tmp_path) + values: dict[str, Any] = { + "api_token": "t", + "tls_bind_host": "127.0.0.1", + "tls_bind_port": 18443, + "tls_cert_file": str(crt), + "tls_key_file": str(key), + } + values.update(kw) + return Settings(**values) + + +@needs_openssl +def test_fingerprint_matches_openssl(tmp_path: Path) -> None: + crt, _ = make_cert(tmp_path) + out = subprocess.run( + ["openssl", "x509", "-in", str(crt), "-noout", "-fingerprint", "-sha256"], + check=True, capture_output=True, text=True, + ).stdout # fmt: skip + assert fingerprint_sha256(str(crt)) == out.strip().split("=", 1)[1] + + +def test_fingerprint_rejects_non_certificate(tmp_path: Path) -> None: + bad = tmp_path / "x.pem" + bad.write_text("not a certificate\n") + with pytest.raises(ValueError): + fingerprint_sha256(str(bad)) + + +@needs_openssl +@pytest.mark.parametrize( + ("override", "message"), + [ + ({"tls_bind_host": "0.0.0.0"}, "every interface"), + ({"tls_bind_host": "::"}, "every interface"), + ({"tls_bind_host": "proxy.example"}, "not an IP address"), + ({"tls_bind_port": 0}, "out of range"), + ({"tls_bind_port": 8080}, "same as bind_host"), + ({"tls_cert_file": "/nonexistent/api.crt"}, "missing"), + ({"tls_key_file": "/nonexistent/api.key"}, "missing"), + ({"tls_allowed_clients": ["10.0.0.0/33"]}, "not an address or CIDR"), + ], +) +def test_bad_tls_settings_are_refused( + tmp_path: Path, override: dict[str, Any], message: str +) -> None: + with pytest.raises(TLSConfigError, match=message): + check_tls_settings(tls_settings(tmp_path, **override)) + + +@needs_openssl +def test_valid_tls_settings_return_the_allowlist(tmp_path: Path) -> None: + s = tls_settings( + tmp_path, tls_bind_host="10.0.0.5", tls_allowed_clients=["10.0.0.1", "fd00::/64"] + ) + assert [str(n) for n in check_tls_settings(s)] == ["10.0.0.1/32", "fd00::/64"] + + +def test_without_tls_settings_the_old_listener_runs_unchanged( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + calls: list[dict[str, Any]] = [] + cfg = tmp_path / "config.yml" + cfg.write_text(f"api_token: t\ninstances_dir: {tmp_path}/i\nbind_port: 8081\n") + cfg.chmod(0o600) + monkeypatch.setenv("LMNSQUID_CONFIG", str(cfg)) + monkeypatch.setattr(main, "DockerService", lambda *a, **k: object()) + monkeypatch.setattr(main.uvicorn, "run", lambda app, **kw: calls.append(kw)) + main.main() + assert calls == [{"host": "127.0.0.1", "port": 8081}] + + +def test_unusable_tls_settings_stop_the_service( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + cfg = tmp_path / "config.yml" + cfg.write_text(f"api_token: t\ninstances_dir: {tmp_path}/i\ntls_bind_host: 0.0.0.0\n") + cfg.chmod(0o600) + monkeypatch.setenv("LMNSQUID_CONFIG", str(cfg)) + monkeypatch.setattr(main, "DockerService", lambda *a, **k: object()) + monkeypatch.setattr(main.uvicorn, "run", lambda *a, **k: pytest.fail("must not start")) + with pytest.raises(SystemExit) as exc: + main.main() + assert exc.value.code == 2 + + +async def _call(app: ClientAllowlist, client: tuple[str, int] | None) -> int: + sent: list[dict[str, Any]] = [] + + async def inner(scope: Any, receive: Any, send: Any) -> None: + await send({"type": "http.response.start", "status": 200, "headers": []}) + + async def receive() -> dict[str, Any]: + return {"type": "http.request"} + + async def send(msg: Any) -> None: + sent.append(msg) + + app.app = inner + await app({"type": "http", "client": client}, receive, send) + return int(sent[0]["status"]) + + +@pytest.mark.parametrize( + ("client", "status"), + [ + (("10.0.0.1", 5000), 200), + (("::ffff:10.0.0.1", 5000), 200), + (("10.0.0.2", 5000), 403), + (("fd00::1", 5000), 403), + (None, 403), + ], +) +async def test_client_allowlist(client: tuple[str, int] | None, status: int) -> None: + import ipaddress + + mw = ClientAllowlist(lambda *a: None, [ipaddress.ip_network("10.0.0.1/32")]) # type: ignore[arg-type,return-value] + assert await _call(mw, client) == status + + +def _get(url: str, pin: str | None, token: str | None) -> tuple[int, Any, str | None]: + """GET ``url``; with ``pin`` over TLS without CA trust, checking the certificate hash.""" + ctx = None + seen = None + if url.startswith("https"): + ctx = ssl.create_default_context() + ctx.check_hostname = False + ctx.verify_mode = ssl.CERT_NONE + req = urllib.request.Request(url) + if token: + req.add_header("Authorization", f"Bearer {token}") + if ctx is not None: + host, port = url.split("/")[2].split(":") + with socket.create_connection((host, int(port)), timeout=5) as raw: + with ctx.wrap_socket(raw) as tls: + der = tls.getpeercert(binary_form=True) + assert der is not None + seen = hashlib.sha256(der).hexdigest() + if pin is not None: + assert seen == pin + try: + with urllib.request.urlopen(req, timeout=5, context=ctx) as resp: + return resp.status, json.loads(resp.read()), seen + except urllib.error.HTTPError as exc: + return exc.code, json.loads(exc.read()), seen + + +@needs_openssl +async def test_real_servers_plain_and_tls(tmp_path: Path, app: Any, token: str) -> None: + """Both listeners serve the same app; the TLS one with the postinst-style certificate.""" + plain_port, tls_port = free_port(), free_port() + s = tls_settings(tmp_path, api_token=token, bind_port=plain_port, tls_bind_port=tls_port) + networks = check_tls_settings(s) + servers = main.build_servers(s, app, networks) + task = asyncio.create_task(main.serve_all(servers)) + for _ in range(100): + if all(srv.started for srv in servers): + break + await asyncio.sleep(0.05) + try: + assert all(srv.started for srv in servers) + pin = fingerprint_sha256(s.tls_cert_file).replace(":", "").lower() + status, body, _ = await asyncio.to_thread( + _get, f"http://127.0.0.1:{plain_port}/v1/instances", None, token + ) + assert (status, body) == (200, []) + status, body, seen = await asyncio.to_thread( + _get, f"https://127.0.0.1:{tls_port}/v1/instances", pin, token + ) + assert (status, body, seen) == (200, [], pin) + status, _, _ = await asyncio.to_thread( + _get, f"https://127.0.0.1:{tls_port}/v1/instances", pin, None + ) + assert status == 401 + # Plain HTTP on the TLS port gets no answer from the app. + with pytest.raises(Exception): + await asyncio.to_thread(_get, f"http://127.0.0.1:{tls_port}/v1/health", None, None) + finally: + for srv in servers: + srv.should_exit = True + await asyncio.wait_for(task, 10) + + +@needs_openssl +async def test_tls_allowlist_on_the_real_listener(tmp_path: Path, app: Any, token: str) -> None: + plain_port, tls_port = free_port(), free_port() + s = tls_settings( + tmp_path, + api_token=token, + bind_port=plain_port, + tls_bind_port=tls_port, + tls_allowed_clients=["192.0.2.1"], + ) + servers = main.build_servers(s, app, check_tls_settings(s)) + task = asyncio.create_task(main.serve_all(servers)) + for _ in range(100): + if all(srv.started for srv in servers): + break + await asyncio.sleep(0.05) + try: + status, body, _ = await asyncio.to_thread( + _get, f"https://127.0.0.1:{tls_port}/v1/health", None, None + ) + assert (status, body) == (403, {"detail": "client address not allowed"}) + # The loopback listener is not restricted by the TLS allowlist. + status, _, _ = await asyncio.to_thread( + _get, f"http://127.0.0.1:{plain_port}/v1/health", None, None + ) + assert status == 200 + finally: + for srv in servers: + srv.should_exit = True + await asyncio.wait_for(task, 10) + + +@needs_openssl +def test_cli_tls_fingerprint(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + crt, _ = make_cert(tmp_path) + cfg = tmp_path / "config.yml" + cfg.write_text(f"api_token: t\ntls_cert_file: {crt}\n") + cfg.chmod(0o600) + monkeypatch.setenv("LMNSQUID_CONFIG", str(cfg)) + result = CliRunner().invoke(cli.app, ["tls", "fingerprint"]) + assert result.exit_code == 0, result.output + assert result.output.strip() == fingerprint_sha256(str(crt)) + + +def test_cli_tls_fingerprint_without_certificate( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + cfg = tmp_path / "config.yml" + cfg.write_text(f"api_token: t\ntls_cert_file: {tmp_path}/missing.crt\n") + cfg.chmod(0o600) + monkeypatch.setenv("LMNSQUID_CONFIG", str(cfg)) + result = CliRunner().invoke(cli.app, ["tls", "fingerprint"]) + assert result.exit_code == 1 diff --git a/debian/linuxmuster-squid.postinst b/debian/linuxmuster-squid.postinst index 08077ce..d90b52c 100644 --- a/debian/linuxmuster-squid.postinst +++ b/debian/linuxmuster-squid.postinst @@ -29,11 +29,45 @@ blocklists_dir: /etc/linuxmuster-squid/blocklists bind_host: 127.0.0.1 bind_port: 8080 api_url: http://127.0.0.1:8080 +# Optional TLS listener for the WebUI plugin on the school server (docs/install.md, +# ADR-018). Off while tls_bind_host is unset; the listener above stays as it is. +# tls_bind_host: 10.0.0.5 # the management address of this host, never 0.0.0.0 +# tls_bind_port: 8443 +# tls_allowed_clients: ["10.0.0.1"] # only the school server EOF ) chmod 600 "$CFG" fi +# Self-signed certificate of the optional TLS listener (ADR-018), made once and never replaced: +# clients pin its fingerprint (`lmnsquid tls fingerprint`), so a new one would break them. +# Made on every installation, used only once tls_bind_host is set. Renewal: docs/install.md. +# A failure does not fail the configure (the listener is opt-in); it says what to do instead. +TLS_DIR=/etc/linuxmuster-squid/tls +mkdir -p "$TLS_DIR" +if [ ! -e "$TLS_DIR/api.key" ] && [ ! -e "$TLS_DIR/api.crt" ]; then + CN="$(hostname -f 2>/dev/null || true)" + case "$CN" in + "" | *[!A-Za-z0-9.-]*) CN="$(hostname 2>/dev/null || true)" ;; + esac + case "$CN" in + "" | *[!A-Za-z0-9.-]*) CN=linuxmuster-squid ;; + esac + tls_rc=0 + ( umask 077 + openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 3650 \ + -subj "/CN=$CN" -addext "subjectAltName=DNS:$CN" \ + -keyout "$TLS_DIR/api.key" -out "$TLS_DIR/api.crt" >/dev/null 2>&1 ) || tls_rc=$? + if [ "$tls_rc" = 0 ]; then + chmod 600 "$TLS_DIR/api.key" + chmod 644 "$TLS_DIR/api.crt" + else + rm -f "$TLS_DIR/api.key" "$TLS_DIR/api.crt" + echo "WARNING: linuxmuster-squid: could not create the TLS certificate (openssl exit" \ + "$tls_rc); the TLS listener needs one, see docs/install.md" >&2 + fi +fi + INST_DIR=/var/lib/linuxmuster-squid/instances # The updater's rollback notes are not part of the change log. [ -f "$INST_DIR/.gitignore" ] || printf '*.prev\n' > "$INST_DIR/.gitignore" @@ -45,7 +79,7 @@ INST_DIR=/var/lib/linuxmuster-squid/instances # caught by the 7.3.3 release gate). Running first, the chown also repairs root-owned # files those versions left in the repository, before git touches it as lmnsquid below. chown -R lmnsquid:lmnsquid /etc/linuxmuster-squid /var/lib/linuxmuster-squid -chmod 700 /etc/linuxmuster-squid/secrets +chmod 700 /etc/linuxmuster-squid/secrets "$TLS_DIR" # Git change log of the instance definitions (docs/operations.md). Every git command runs # AS lmnsquid, the owner of the repository and the user the service commits as, so git From b40c8f4b7fca7303bcd3bbd3efb58715571b67af Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Mon, 23 Nov 2026 11:41:50 +0100 Subject: [PATCH 03/29] feat(webui): WebUI plugin lmn_squid as second binary package linuxmuster-squid-webui The plugin for linuxmuster-webui7 (lmn73) manages one or more control planes from the school server: a connection list (name, display name, URL, token, pinned certificate fingerprint, optional school tags) in /etc/linuxmuster-squid-webui/config.yml (0600 root, atomic, locked), and for each server everything the API offers: instances with state, create/edit/ delete (keep logs), start/stop/restart, update/rollback, update-all, reconcile, logs and access log, blocklist and noauth list with reload, version. Every endpoint names its connection in the path; an unknown one is 404. Access is for global administrators only, twice: lm:squid:list/change and the sidebar entry are true for globaladministrator only (permissions.yml), and every endpoint checks the session's sophomorixRole again. Tokens never go back to the browser. The client is standard library only: with a fingerprint no CA is trusted and the certificate hash must match before anything is sent; without one the system CAs and the host name are checked; plain http to loopback only. Control-plane 401/403 reach the browser as 502 (a 401 would log the admin out). Packaging: Architecture all, Depends linuxmuster-webui7 (>= 7.3), (<< 7.4); debian/rules builds resources/build/all.js and the locale JSON with webui/build_plugin.py (ES5 sources, no node/babel in the build, ES2015 syntax is refused); postinst runs merge-permissions.py, sophomorix-ui and try-restarts the WebUI, postrm undoes that, purge removes the connection list. German and English. Docs: ADR-018 (TLS listener), ADR-019 (plugin), threat model T5/T18, architecture, install (9a), operations, README, test strategy, changelog. --- .gitignore | 1 + README.md | 16 +- debian/changelog | 21 + debian/control | 15 +- debian/linuxmuster-squid-webui.postinst | 52 +++ debian/linuxmuster-squid-webui.postrm | 30 ++ debian/linuxmuster-squid-webui.prerm | 13 + debian/rules | 12 +- docs/architecture.md | 24 +- docs/decisions.md | 63 ++- docs/install.md | 49 ++ docs/operations.md | 17 +- docs/test-strategy.md | 16 + docs/threat-model.md | 3 +- webui/build_plugin.py | 164 +++++++ webui/lmn_squid/__init__.py | 8 + webui/lmn_squid/client.py | 211 +++++++++ webui/lmn_squid/connections.py | 245 ++++++++++ webui/lmn_squid/locale/de/LC_MESSAGES/app.po | 294 ++++++++++++ webui/lmn_squid/main.py | 47 ++ webui/lmn_squid/permissions.yml | 30 ++ webui/lmn_squid/plugin.yml | 19 + .../js/controllers/index.controller.es | 417 ++++++++++++++++++ webui/lmn_squid/resources/js/module.es | 6 + webui/lmn_squid/resources/js/routing.es | 8 + webui/lmn_squid/resources/partial/index.html | 301 +++++++++++++ webui/lmn_squid/views.py | 359 +++++++++++++++ webui/pyproject.toml | 26 ++ webui/tests/conftest.py | 334 ++++++++++++++ webui/tests/test_build.py | 95 ++++ webui/tests/test_connections.py | 139 ++++++ webui/tests/test_control_plane.py | 174 ++++++++ webui/tests/test_permissions.py | 107 +++++ 33 files changed, 3305 insertions(+), 11 deletions(-) create mode 100644 debian/linuxmuster-squid-webui.postinst create mode 100644 debian/linuxmuster-squid-webui.postrm create mode 100644 debian/linuxmuster-squid-webui.prerm create mode 100644 webui/build_plugin.py create mode 100644 webui/lmn_squid/__init__.py create mode 100644 webui/lmn_squid/client.py create mode 100644 webui/lmn_squid/connections.py create mode 100644 webui/lmn_squid/locale/de/LC_MESSAGES/app.po create mode 100644 webui/lmn_squid/main.py create mode 100644 webui/lmn_squid/permissions.yml create mode 100644 webui/lmn_squid/plugin.yml create mode 100644 webui/lmn_squid/resources/js/controllers/index.controller.es create mode 100644 webui/lmn_squid/resources/js/module.es create mode 100644 webui/lmn_squid/resources/js/routing.es create mode 100644 webui/lmn_squid/resources/partial/index.html create mode 100644 webui/lmn_squid/views.py create mode 100644 webui/pyproject.toml create mode 100644 webui/tests/conftest.py create mode 100644 webui/tests/test_build.py create mode 100644 webui/tests/test_connections.py create mode 100644 webui/tests/test_control_plane.py create mode 100644 webui/tests/test_permissions.py diff --git a/.gitignore b/.gitignore index ad018d5..9ed170a 100644 --- a/.gitignore +++ b/.gitignore @@ -30,6 +30,7 @@ debian/files debian/*.substvars debian/debhelper-build-stamp debian/linuxmuster-squid/ +debian/linuxmuster-squid-webui/ *.deb *.buildinfo *.changes diff --git a/README.md b/README.md index 89c64f9..9c78ea1 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,18 @@ the same AD/Kerberos infrastructure the school already operates. **updates digest-pinned with health-check auto-rollback**. Shipped as a signed `.deb`. +- **WebUI plugin (optional):** `linuxmuster-squid-webui` adds the page *Squid proxy* to the + linuxmuster.net 7.3 WebUI for global administrators; it manages one or more proxy hosts over + their opt-in TLS listener with a pinned certificate. + +| Package | Install on | What | +|---|---|---| +| `linuxmuster-squid` (amd64) | the proxy host (Docker VM) | control plane, CLI, service | +| `linuxmuster-squid-webui` (all) | the linuxmuster server (WebUI) | the WebUI plugin `lmn_squid` | + +Both come from this repository with the same version; they talk over HTTPS, neither depends on +the other being installed on the same host. + Details: [`docs/architecture.md`](docs/architecture.md). ## Usage @@ -132,7 +144,9 @@ Docker**. Aggregator: Keytabs are domain credentials (secret/tmpfs, least-privilege). **No HTTPS decryption** (privacy-friendly, no client CA rollout). Control-plane Docker socket access is **root-equivalent** — API only on -localhost/mgmt network, token/TLS, behind a socket proxy. More: +localhost, or the opt-in TLS listener on the management network (pinned certificate, client +allowlist), token, behind a socket proxy. The WebUI plugin holds those tokens: global +administrators only. More: [`docs/threat-model.md`](docs/threat-model.md) · [`docs/keytab-and-dns.md`](docs/keytab-and-dns.md). ## License diff --git a/debian/changelog b/debian/changelog index b89f8b4..deab550 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,3 +1,24 @@ +linuxmuster-squid (7.3.11) lmn73; urgency=medium + + * New package linuxmuster-squid-webui (same version, from this source): + the page "Squid proxy" in the linuxmuster.net 7.3 WebUI on the school + server, for global administrators only. It manages one or more proxy + hosts: instances with their state, create/edit/delete, start/stop/ + restart, update/rollback, update-all, reconcile, logs, blocklist and + noauth list. Install it on the linuxmuster server, not on the proxy + host; log out and in again after installing (docs/install.md, 9a). + * Optional TLS listener of the control plane for the WebUI plugin: with + tls_bind_host (an address of the proxy host, never 0.0.0.0) in + config.yml the API is also served over TLS on that address (port 8443), + optionally only to the addresses in tls_allowed_clients. The plain + listener on 127.0.0.1:8080 and the CLI stay as they are; nothing + changes until you set tls_bind_host. The package makes a self-signed + certificate once (/etc/linuxmuster-squid/tls/); "lmnsquid tls + fingerprint" prints the fingerprint to enter in the plugin. + * New API endpoints for clients: GET /v1/status (state of all instances) + and GET /v1/schema (fields and defaults of an instance). + + -- Kevin Stenzel Sat, 28 Nov 2026 03:59:40 +0100 linuxmuster-squid (7.3.10) lmn73; urgency=medium * Fix the rotation of the access and cache log, which never worked in the diff --git a/debian/control b/debian/control index 1482f87..76a9146 100644 --- a/debian/control +++ b/debian/control @@ -5,7 +5,8 @@ Maintainer: Kevin Stenzel Build-Depends: debhelper-compat (= 13), python3 (>= 3.12), python3 (<< 3.13), - python3-venv + python3-venv, + python3-yaml Standards-Version: 4.6.2 Rules-Requires-Root: no Homepage: https://github.com/faircomp/linuxmuster-squid @@ -24,3 +25,15 @@ Description: Control plane for containerized linuxmuster-squid proxies REST API + CLI to manage per-school Squid proxy containers (Kerberos SSO, AD group ACLs, SNI filtering) with digest-pinned, health-checked, auto-rolling updates. Ships a self-contained Python virtualenv under /opt/linuxmuster-squid. + +Package: linuxmuster-squid-webui +Architecture: all +Depends: ${misc:Depends}, + linuxmuster-webui7 (>= 7.3), + linuxmuster-webui7 (<< 7.4) +Description: linuxmuster.net WebUI plugin for linuxmuster-squid proxy servers + Plugin "lmn_squid" for the linuxmuster.net 7.3 WebUI on the school server: + manage one or more linuxmuster-squid control planes (instances, lifecycle, + logs, blocklist and noauth list, updates) over their TLS listener with a + pinned certificate. Global administrators only. Install linuxmuster-squid + on the proxy host itself. diff --git a/debian/linuxmuster-squid-webui.postinst b/debian/linuxmuster-squid-webui.postinst new file mode 100644 index 0000000..114c82d --- /dev/null +++ b/debian/linuxmuster-squid-webui.postinst @@ -0,0 +1,52 @@ +#!/bin/sh +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +set -e + +# The WebUI only knows a plugin's permissions after three steps, the same ones +# linuxmuster-webui7's own postinst runs on an update: merge every plugin's permissions.yml +# into default-ui-permissions.ini (merge-permissions.py), write the result into each user's +# LDAP entry (sophomorix-ui; without it even a global administrator gets 403, because the +# WebUI reads the permissions from LDAP), and restart the WebUI so it loads the plugin. +# Each step is best effort but never silent: a failure prints a WARNING where apt shows it +# and names the command to run by hand; the package configure itself does not fail over it. +refresh_webui() { + MERGE=/usr/lib/linuxmuster-webui/etc/update_scripts/merge-permissions.py + PY=/opt/linuxmuster/bin/python3 + [ -x "$PY" ] || PY=/usr/bin/python3 + if [ -f "$MERGE" ]; then + "$PY" "$MERGE" || echo "WARNING: linuxmuster-squid-webui: '$PY $MERGE' failed;" \ + "run it by hand, then sophomorix-ui" >&2 + fi + if command -v sophomorix-ui >/dev/null 2>&1; then + sophomorix-ui >/dev/null || echo "WARNING: linuxmuster-squid-webui: 'sophomorix-ui'" \ + "failed; run it by hand so the global administrators get the plugin" >&2 + fi + if [ -d /run/systemd/system ]; then + # try-restart: a running WebUI loads the plugin, a stopped one stays stopped. + deb-systemd-invoke try-restart linuxmuster-webui.service || echo "WARNING:" \ + "linuxmuster-squid-webui: restart linuxmuster-webui to load the plugin" >&2 + fi +} + +case "$1" in + configure) + # The connection list holds the control planes' tokens: root only. + mkdir -p /etc/linuxmuster-squid-webui + chmod 700 /etc/linuxmuster-squid-webui + if [ -f /etc/linuxmuster-squid-webui/config.yml ]; then + chmod 600 /etc/linuxmuster-squid-webui/config.yml + fi + refresh_webui + echo "linuxmuster-squid-webui: log out of the WebUI and in again to see 'Squid proxy'" + ;; + abort-upgrade | abort-remove | abort-deconfigure) + ;; + *) + echo "postinst called with unknown argument '$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# +exit 0 diff --git a/debian/linuxmuster-squid-webui.postrm b/debian/linuxmuster-squid-webui.postrm new file mode 100644 index 0000000..862ebe9 --- /dev/null +++ b/debian/linuxmuster-squid-webui.postrm @@ -0,0 +1,30 @@ +#!/bin/sh +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +set -e + +case "$1" in + remove) + # The plugin files are gone: drop its permissions from the merged file and LDAP and + # restart the WebUI without it (the same three steps as the postinst, best effort). + MERGE=/usr/lib/linuxmuster-webui/etc/update_scripts/merge-permissions.py + PY=/opt/linuxmuster/bin/python3 + [ -x "$PY" ] || PY=/usr/bin/python3 + if [ -f "$MERGE" ]; then + "$PY" "$MERGE" || echo "WARNING: linuxmuster-squid-webui: '$PY $MERGE' failed" >&2 + fi + if command -v sophomorix-ui >/dev/null 2>&1; then + sophomorix-ui >/dev/null || echo "WARNING: linuxmuster-squid-webui: 'sophomorix-ui' failed" >&2 + fi + if [ -d /run/systemd/system ]; then + deb-systemd-invoke try-restart linuxmuster-webui.service || true + fi + ;; + purge) + # The connection list with the control planes' tokens. + rm -rf /etc/linuxmuster-squid-webui + ;; +esac + +#DEBHELPER# +exit 0 diff --git a/debian/linuxmuster-squid-webui.prerm b/debian/linuxmuster-squid-webui.prerm new file mode 100644 index 0000000..0366276 --- /dev/null +++ b/debian/linuxmuster-squid-webui.prerm @@ -0,0 +1,13 @@ +#!/bin/sh +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +set -e + +# The WebUI (root) compiles the plugin's .py files into __pycache__ next to them; dpkg does +# not know those files and would leave the plugin directory behind on remove. +if [ "$1" = remove ] || [ "$1" = upgrade ] || [ "$1" = deconfigure ]; then + rm -rf /usr/lib/linuxmuster-webui/plugins/lmn_squid/__pycache__ +fi + +#DEBHELPER# +exit 0 diff --git a/debian/rules b/debian/rules index fff552f..ac68ec0 100755 --- a/debian/rules +++ b/debian/rules @@ -12,6 +12,8 @@ include /usr/share/dpkg/pkg-info.mk PKG := linuxmuster-squid DEST := /opt/$(PKG)/venv ROOT := $(CURDIR)/debian/$(PKG) +# The WebUI plugin package (Architecture: all): files assembled by webui/build_plugin.py. +WEBUI_PLUGIN := $(CURDIR)/debian/$(PKG)-webui/usr/lib/linuxmuster-webui/plugins/lmn_squid # make splits paths at whitespace, and build-venv.sh starts with `rm -rf` on the venv path: a # build directory containing a space (a TMPDIR like "/work/odd dir") would turn part of it into @@ -28,12 +30,18 @@ endif override_dh_auto_configure override_dh_auto_build override_dh_auto_test: @: -override_dh_auto_install: +override_dh_auto_install-arch: bash packaging/build-venv.sh "$(ROOT)$(DEST)" debian/venv-relocate "$(ROOT)" "$(DEST)" +# The bundle and locale files the WebUI serves are built here, from the ES5 sources and .po +# files (webui7 commits them, made by ajenti-dev-multitool with babel; see build_plugin.py). +override_dh_auto_install-indep: + /usr/bin/python3 -I webui/build_plugin.py webui/lmn_squid "$(WEBUI_PLUGIN)" + override_dh_auto_clean: rm -rf controlplane/build controlplane/*.egg-info + find webui -name __pycache__ -prune -exec rm -rf {} + # Stripping, dwz and strip-nondeterminism would change files pip recorded in RECORD; # dh_makeshlibs must not publish the wheels' private libraries as shlibs. @@ -49,5 +57,5 @@ override_dh_installsystemd: override_dh_fixperms: dh_fixperms -X$(DEST) -execute_before_dh_builddeb: +execute_before_dh_builddeb-arch: debian/venv-relocate --verify "$(ROOT)" "$(DEST)" diff --git a/docs/architecture.md b/docs/architecture.md index ae646ee..10d1a0c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -111,9 +111,13 @@ Status document. Keep it up to date with every substantive change (see `DELETE /v1/instances/{name}` removes container, cache + log volumes and both lists (`?keep_logs=true` keeps the log volume). `HTTPBearer(auto_error=False)` + `hmac.compare_digest`; app-wide dependency; - bind **127.0.0.1 only** (in-app TLS is NOT implemented; off-host only via - an operator-owned TLS reverse proxy — on a non-loopback bind `main.py` warns, because the - token would otherwise travel in cleartext); secret in `config.yml` `chmod 600`; **audit log** of every mutation. + plain listener on **127.0.0.1** (on a non-loopback `bind_host` `main.py` warns, the token + would travel in cleartext); optionally a **second, TLS listener** on the management address + (`tls_bind_host`, ADR-018: self-signed certificate from the postinst, pinned by clients, + `0.0.0.0` refused, optional `tls_allowed_clients`) for off-host clients such as the WebUI + plugin; secret in `config.yml` `chmod 600`; **audit log** of every mutation. + For clients: `GET /v1/status` (container state of all instances in one call) and + `GET /v1/schema` (JSON schema of the instance model with its defaults). - **Reconciler:** declarative, git-versioned state (`instances/*.yaml`) → renders config, reconciles actual against desired state (docker-py). - **Updater:** pull-by-**digest** (`image@sha256:`), health-gated, **auto-rollback** @@ -121,6 +125,20 @@ Status document. Keep it up to date with every substantive change (see `automerge:false`; raised by hand while Renovate is disabled) + CI image publish. No Watchtower. - **CLI (Typer/httpx):** exclusively via the REST-API — **one** audited path to the Docker daemon. +- **WebUI plugin (package `linuxmuster-squid-webui`, ADR-019):** runs inside + linuxmuster-webui7 on the school server, not on the proxy host. Keeps a list of control planes + (`/etc/linuxmuster-squid-webui/config.yml`, 0600 root), talks to each over its TLS listener + with the pinned fingerprint and the bearer token, and offers what the API offers, for + global administrators only: + ``` + Browser ──WebUI session──▶ linuxmuster-webui7 (school server) ── plugin lmn_squid + │ /api/lmn/squid//... (globaladministrator) + TLS, pinned ┌──┴──────────────┐ TLS, pinned + ▼ ▼ + control plane proxy-a:8443 control plane proxy-b:8443 (one per host) + ``` + Each server is queried on its own request with short timeouts, so one that is down does + not block the page. - **Docker access:** docker-py; **socket access is root-equivalent** → behind `docker-socket-proxy`/rootless Docker, API never public. diff --git a/docs/decisions.md b/docs/decisions.md index 4bc70e4..db290c3 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -133,8 +133,8 @@ run instances — with that a compromised caller can create a container **with a host bind mount** = still host root. The proxy **reduces the surface, but does not downgrade below root**; the real answer is **rootless Docker**. Moreover the proxy listens on `127.0.0.1:2375` without auth → any local process has the same -access (like the `docker` group with the direct socket). In-app TLS is NOT implemented; -off-host only via an operator-owned TLS reverse proxy. The host is the +access (like the `docker` group with the direct socket). Off-host access only over the +optional in-app TLS listener on the management address (ADR-018). The host is the trust boundary. **Side effect:** `access-logs` (historical) uses `docker exec` → does **not** work behind the proxy with `EXEC:0`, and neither does `blocklist reload` (`squid -k reconfigure` via exec, ADR-014); the live `logs` path (container.logs) does. @@ -302,6 +302,65 @@ the replay cache (in the container's tmpfs, entries kept for the same skew) does the CI image built after the merge, the setting is accepted and stored but has no effect on instances running the pinned image. +### ADR-018 — Optional TLS listener in the control plane for off-host clients +**Status:** Proposed (2026-11-23, Kevin: the linuxmuster WebUI on the school server is to manage +the proxies over the management network, with TLS in uvicorn, no reverse proxy, no SSH tunnel). +Replaces the earlier statement "in-app TLS is not implemented; off-host only through an +operator-owned TLS reverse proxy" (ADR-012, T5). **Decision:** `config.yml` may name +`tls_bind_host` (an IP address of this host, the management address); then a **second** uvicorn +server serves the same app over TLS on `tls_bind_host:tls_bind_port` (default 8443) with +`tls_cert_file`/`tls_key_file` (default `/etc/linuxmuster-squid/tls/api.{crt,key}`), next to the +plain listener on `bind_host:bind_port`, which stays as it is (127.0.0.1:8080; the CLI and the +maintainer scripts keep using it). Without `tls_bind_host` the service starts exactly as before +(`uvicorn.run` on `bind_host`), so an upgrade changes nothing until the admin turns TLS on. +**Bind rules:** `tls_bind_host` must be an IP literal and must not be `0.0.0.0`/`::` (the +service refuses to start with a sentence in the journal, exit 2): the listener is pinned to one +network on purpose. The plain listener keeps its old rule (a non-loopback `bind_host` only +warns), so existing configurations do not stop. Missing/unreadable certificate or key, a bad +port, a clash with the plain listener or a bad allowlist entry also refuse the start; a +group/world-readable key warns. **Certificate:** self-signed (EC P-256, 10 years, CN/SAN = the +host's FQDN), made **once** by the postinst on every installation (`openssl`, already a +dependency), key 0600, never overwritten; clients pin its SHA-256 fingerprint, printed by +`lmnsquid tls fingerprint` (= `openssl x509 -noout -fingerprint -sha256`). A CA-issued +certificate works too (replace both files; a client then may verify against its CAs instead of +pinning). Renewal = new files + restart + new fingerprint in every client (docs/install.md). +**Optional source allowlist:** `tls_allowed_clients` (addresses/CIDRs) answers 403 to every +other peer of the TLS listener (ASGI middleware on that listener only). It complements, not +replaces, a host/network firewall rule. **Token:** unchanged, one bearer token +(`compare_digest`); whoever holds it — now also the WebUI server — has full control of the +control plane, which is root-equivalent on the proxy host (Docker socket, ADR-012). No +per-client tokens or scopes in v1 (the API has one role). **Why not a reverse proxy:** one +more service to install, configure and keep patched on every proxy host, for the same +transport; **why not SSH tunnels:** the WebUI would need SSH keys into the proxy hosts and a +tunnel manager. **Price:** the API is reachable from the management network (threat model T5, +T18): the token, the allowlist and a firewall rule "only the school server" are the gates. + +### ADR-019 — WebUI plugin as a second binary package of this repository +**Status:** Proposed (2026-11-23, Kevin). **Decision:** the plugin `lmn_squid` for +linuxmuster-webui7 (lmn73) lives in `webui/` and ships as `linuxmuster-squid-webui` +(Architecture: all) from the same source package, same version, same tag. It depends on +`linuxmuster-webui7 (>= 7.3), (<< 7.4)` and NOT on `linuxmuster-squid` (other host). It manages +a **list of control-plane connections** (name, display name, URL, token, pinned fingerprint, +optional school tags for filtering) in `/etc/linuxmuster-squid-webui/config.yml` (0600 root, +written atomically under a lock); every plugin endpoint names its connection in the path, an +unknown one is 404. Tokens are never sent back to the browser. **Access:** global +administrators only, twice: the WebUI permissions `lm:squid:list`/`lm:squid:change` and the +sidebar entry are `true` for `globaladministrator` only (permissions.yml, merged by the +postinst with the WebUI's `merge-permissions.py` and written to LDAP by `sophomorix-ui`, which +the WebUI reads the permissions from), and every endpoint checks the session's +`sophomorixRole` on the server again, so a permission granted to another role by hand still +gets 403. **Client:** standard library only (`http.client`, `ssl`): with a fingerprint the +TLS handshake trusts no CA and the certificate hash must equal the pin before the request and +its token are sent; without one the certificate must verify against the system CAs; plain +http only to a loopback address. No new Python dependency inside the WebUI's venv. +**Frontend build:** webui7 commits `resources/build/all.js` made by `ajenti-dev-multitool` +(babel, node). Here the `.es` sources are ES5 and `webui/build_plugin.py` makes the bundle and +the locale JSON at package build time (no node, no npm in the build: ADR-015); it refuses +ES2015 syntax instead of shipping it untranspiled. **Why one repo:** plugin and API change +together (the plugin uses `/v1/status` and `/v1/schema`, added for it); one version says which +plugin matches which control plane. A third package can join the same way (`debian/.*`, +a directory beside `controlplane/` and `webui/`). + --- ## Site facts to be verified (P0, enter with source/date) diff --git a/docs/install.md b/docs/install.md index f60ab6e..826ec29 100644 --- a/docs/install.md +++ b/docs/install.md @@ -214,6 +214,55 @@ list; a package release whose pinned image supports it moves the instances onto Assign the proxy per role by GPO (silent Kerberos SSO) and force the proxy at the firewall: [`deployment-gpo.md`](deployment-gpo.md). Clients must use the **FQDN**, never the IP. +## 9a. Manage the proxies from the linuxmuster WebUI (optional) + +The package `linuxmuster-squid-webui` adds the page *Squid proxy* to the linuxmuster.net 7.3 +WebUI on the **school server** (global administrators only). It talks to the control plane of +each proxy host over the control plane's TLS listener (ADR-018, ADR-019); one WebUI can manage +several proxy hosts (several schools or sites). + +**On every proxy host** — turn the TLS listener on (it is off after installing or upgrading). +Add to `/etc/linuxmuster-squid/config.yml` (the management address of this host, the school +server's address as the only client): +```yaml +tls_bind_host: 10.0.0.5 +tls_bind_port: 8443 +tls_allowed_clients: ["10.0.0.1"] +``` +```bash +systemctl restart linuxmuster-squid +journalctl -u linuxmuster-squid -n 5 # "TLS listener on 10.0.0.5:8443 (clients: 10.0.0.1/32)" +lmnsquid tls fingerprint # AB:CD:... -> into the plugin +grep '^api_token' /etc/linuxmuster-squid/config.yml # the token -> into the plugin +``` +- `tls_bind_host` must be an address of this host; `0.0.0.0` is refused (the service does not + start and says why in the journal). The plain listener on 127.0.0.1:8080 stays for the CLI. +- Allow the port in the host/network firewall **from the school server only**. The token is + root-equivalent on the proxy host (threat model T5, T18). +- The certificate is self-signed and made once by the package (`/etc/linuxmuster-squid/tls/`, + key 0600). **Renewing it** (after a host rename, or before it expires after 10 years): + ```bash + rm /etc/linuxmuster-squid/tls/api.key /etc/linuxmuster-squid/tls/api.crt + dpkg-reconfigure linuxmuster-squid # makes a new pair (and restarts the service) + lmnsquid tls fingerprint # enter the new fingerprint in the plugin + ``` + A CA-issued certificate can replace both files instead (then the plugin may leave the + fingerprint empty and verify against the system CAs). + +**On the school server:** +```bash +gh release download -R faircomp/linuxmuster-squid -p 'linuxmuster-squid-webui_*.deb' +apt-get install -y ./linuxmuster-squid-webui__all.deb +``` +The postinst merges the plugin's permissions (`merge-permissions.py`), writes them to LDAP +(`sophomorix-ui`, takes a moment) and restarts the WebUI. **Log out and in again**, then open +*Squid proxy* and *Add proxy server*: a name (`schule-a`), the URL `https://10.0.0.5:8443`, the +token and the fingerprint, optionally the schools the server belongs to (for the filter only). +*Test connection* checks reachability and token. The connections are stored in +`/etc/linuxmuster-squid-webui/config.yml` (0600 root); the token is never shown again. +Removing the package removes the page and its permissions; `apt-get purge` also removes the +connection list. + ## 10. Updates ```bash diff --git a/docs/operations.md b/docs/operations.md index 41a67ac..9b6abc7 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -364,6 +364,19 @@ and starts `linuxmuster-squid`; after that, upgrades keep what the admin decided - **Without a running systemd** (an image build, a chroot) a new installation only enables the service; it starts with the next boot. +## From the linuxmuster WebUI (optional) + +With `linuxmuster-squid-webui` on the school server (install.md, 9a) the page *Squid proxy* +offers what the CLI offers, per connected proxy server: instances with their state, create / +edit / delete (with "keep the access logs"), start / stop / restart, update / rollback, +update-all, reconcile, logs and access log, blocklist and noauth list with *Reload (apply)*, +and the version. Global administrators only. The warnings of the noauth list (exam mode, +Internetsperre, no user in the log, client subnets) are shown above the list. A server that +does not answer shows "not reachable" in its own panel; the others load normally. Error +messages name the cause: not reachable, timeout, certificate does not match the pinned +fingerprint (nothing was sent), token refused, or the control plane's own answer (404, 409, +422 per form field, 5xx). + ## Observing ``` @@ -374,7 +387,9 @@ lmnsquid logs --tail 100 --grep teacher1 # live: access + Squid, option lmnsquid logs --since 1783000000 # from Unix epoch second lmnsquid access-logs --grep blocked.example --since 1782900000 # HISTORY (days/months) ``` -API mutations go to the audit log (`logger "lmnsquid.audit"`). If the Docker daemon +API mutations go to the audit log (`logger "lmnsquid.audit"`); changes made through the WebUI +plugin are logged on the school server too (`lmn_squid.audit`, in the WebUI's log, with the +WebUI user). If the Docker daemon is gone, the API responds with **503** (not a raw 500). ### Alerting & auth health (without a monitoring stack) diff --git a/docs/test-strategy.md b/docs/test-strategy.md index 8a9a877..f9e3c55 100644 --- a/docs/test-strategy.md +++ b/docs/test-strategy.md @@ -22,6 +22,22 @@ from the caller's PATH. - **Python:** `ruff check`, `ruff format --check`, `mypy`, `pytest` (control-plane logic, API handlers with the httpx TestClient, CLI client). CI runs them against the locked dependency versions the `.deb` ships (`controlplane/requirements.lock`). +- **WebUI plugin (`pytest -q webui/tests`, `mypy` on `webui/`):** the plugin against + stand-ins of the WebUI's `aj`/`jadi` modules (`webui/tests/conftest.py`, modelled on aj + 2.2.17): every endpoint authorized and global-admin-only, other roles 403 on every endpoint + (also with the permission granted by hand), tokens never in an answer, connection file + 0600/atomic, unknown connection 404; and against real control planes (the lmnsquid app with + the fake Docker service) on a TLS listener with a self-signed certificate: two connections + with one down (fast 502, the other answers), wrong fingerprint sends nothing, no pin = CA + check fails for a self-signed certificate, wrong token 502 (never 401), the whole lifecycle, + both lists, bad instance names/domains never reach the API. The build script: bundle order, + ES2015 refused, PO parsing, every text translated to German, `node --check` when node is + present. The control plane's TLS listener (`controlplane/tests/test_tls.py`): refused binds + and files, the unchanged start without TLS settings, allowlist, fingerprint = `openssl`, + both real listeners. Package: `scripts/tests/webui_deb_smoke.sh` (CI install-smoke) + installs the plugin package without linuxmuster-webui7 next to recording stand-ins of + `merge-permissions.py`/`sophomorix-ui`. The WebUI itself (menu, 403 in a real session, LDAP + permissions) needs the lab. - **Lock files:** `bash packaging/lock-deps.sh --gate`, the first step of the fast tier and of every package build (`packaging/build-venv.sh`), before anything from a lock is installed anywhere: every line is one uv writes; `packaging/requirements-uv.lock` pins uv and nothing diff --git a/docs/threat-model.md b/docs/threat-model.md index f291fc2..f881645 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -25,7 +25,7 @@ Risks + countermeasures. Grows per roadmap phase; the negative tests for it live | T2 | **Proxy bypass** (non-inline) | OPNsense blocks direct 80/443 egress (force-proxy); client subnets = `SCHOOL_SUBNETS` | E2E + firewall review | | T3 | **Authorization bypass** (student on the teacher proxy, wrong group assignment) | group ACL enforced server-side; GPO groups == ACL groups; prefix rule correct | E2E: student→403; multischool matrix | | T4 | **HTTPS privacy** | no SSL-bump MITM of traffic to a real target: allowed CONNECTs are spliced (SNI peek, CONNECT `dstdomain`); the peek certificate is never distributed or trusted. A CONNECT denied by `http_access` gets squid's own 403 inside TLS with that untrusted throwaway certificate (squid's error delivery on an ssl-bump port; the target is never contacted); a client that clicks through the certificate warning reveals the path and headers of that denied request to the proxy (ADR-002, clarification) | `squid.conf` review (`ssl_bump` only peek/splice/terminate); E2E: denied HTTPS → not 200 behind the tunnel (`curl -k`; the noauth case asserts `200 403`), allowed → spliced; the throwaway certificate itself is not asserted, only checked by hand in the lab (2026-10-30) | -| T5 | **Control-plane RCE = host root** (Docker socket) | API **only `127.0.0.1`** + token (`compare_digest`), hardened systemd service, audit log. The socket proxy reduces the endpoint surface, **but does NOT downgrade below host root** (`container create` with host bind is inherently root-equivalent) → the real answer is **rootless Docker**. In-app TLS not implemented; off-host only via an operator-provided TLS reverse proxy (`main.py` warns on non-loopback bind) | API 401/403 tests; bind check ≠ 0.0.0.0 | +| T5 | **Control-plane RCE = host root** (Docker socket) | API **only `127.0.0.1`** + token (`compare_digest`), hardened systemd service, audit log. The socket proxy reduces the endpoint surface, **but does NOT downgrade below host root** (`container create` with host bind is inherently root-equivalent) → the real answer is **rootless Docker**. Off-host only over the optional TLS listener (ADR-018): opt-in, pinned to one management IP (`0.0.0.0`/`::` refused), self-signed certificate pinned by the client, optional `tls_allowed_clients`; plus a firewall rule that lets only the school server reach the port. The plain listener stays on 127.0.0.1 (`main.py` warns on a non-loopback `bind_host`) | API 401/403 tests; TLS listener tests (refused binds, allowlist 403, plain HTTP on the TLS port gets nothing) | | T6 | **Auth all-or-nothing / SSO outage** | auth never globally disableable by default; fallback Kerberos→Basic/LDAP (no NTLM); monitor SSO health | E2E: no ticket→407 | | T7 | **DNS/SPN misconfig** (silent Kerberos fail) | fwd+rev DNS resp. `rdns=false`; FQDN==SPN==`VISIBLE_HOSTNAME`; NTP<5min (the proxy's tolerance is per instance, T17); AES enctypes | E2E canonicalization; `klist -k` | | T8 | **Blocklist rot / tampering** (supply chain) | per-instance list on the host (`/etc/linuxmuster-squid/blocklists//blocked.domains`, mounted read-only into the container, writable only by root/`lmnsquid`), maintained via `lmnsquid blocklist` + `reload`; category lists via `blocklist-refresh.sh` from a host cron with a fail-closed size floor (a truncated download never replaces the list); make outage visible. A list squid 6 cannot load (a covered name before its parent: `FATAL: Bungled`) would take the instance down at the next start: squid reads a copy without such entries (`lists-sync.sh`), and neither the API nor the refresh writes them. **HTTPS limit:** no usable block page for HTTPS: a blocked CONNECT host gets squid's 403 inside TLS with an untrusted throwaway certificate (browser: certificate warning; the target is never contacted), a blocked SNI behind an allowed CONNECT host is cut during the handshake (`ssl_bump terminate`); HTTP gets 403 | blocklist smoke; lab proof 7.3.1 (HTTP 403, HTTPS no block page), re-measured 2026-10-30: blocked CONNECT host → `200`, then 403 inside TLS (E2E: `200 403`), with the throwaway certificate (checked by hand in the lab, not asserted) | @@ -38,6 +38,7 @@ Risks + countermeasures. Grows per roadmap phase; the negative tests for it live | T15 | **Poisoned build input** (supply chain of the `.deb`, installed as root) — a compromised or silently changed PyPI release, build image or GitHub Action lands in the package | Python deps (pip included) only from `controlplane/requirements.lock` with SHA-256 hashes (`--require-hashes --no-deps --only-binary :all:`, wheels only), nothing younger than 7 days picked (`--exclude-newer=P7D`), own wheel built without build isolation from a hashed setuptools; build container, data-plane base image and actions pinned by digest/commit SHA; changes only via human-merged PRs (raised by hand while Renovate is disabled); releases published draft-first (immutable releases) with the asset hash checked against the build (ADR-015) | `lock-deps.sh --gate` first in the fast tier AND in every build, before anything from a lock is installed or run (no venv `bin/` on PATH; `/usr/bin/python3 -I`; every entry point restarts itself under `env -i` through `/bin/bash -p` with an allowlist, `packaging/clean-env.sh`: fixed PATH and `LC_ALL`, the caller's `HOME`, `TMPDIR`, proxies, CA bundles (`SSL_CERT_FILE`, `SSL_CERT_DIR`, `REQUESTS_CA_BUNDLE`, `PIP_CERT`) and the repository's own switches, nothing else; not undone, because it ran before the restart: the caller's first bash for `bash