diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index aaa62a6..85215bc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -102,10 +102,16 @@ jobs: ruff format --check --line-length 100 debian/venv-relocate - name: mypy run: mypy --config-file controlplane/pyproject.toml controlplane/lmnsquid + - name: mypy (WebUI plugin) + run: mypy --config-file webui/pyproject.toml webui/lmn_squid webui/build_plugin.py - name: pytest run: pytest -q controlplane/tests + # The plugin against stand-ins of the WebUI's aj/jadi modules and against real control + # planes (lmnsquid app, fake Docker) on a TLS listener with a self-signed certificate. + - name: pytest (WebUI plugin) + run: pytest -q webui/tests - name: shellcheck - run: sudo apt-get update -qq && sudo apt-get install -y -qq shellcheck && shellcheck --severity=warning $(git ls-files '*.sh') debian/preinst debian/postinst debian/prerm debian/postrm + run: sudo apt-get update -qq && sudo apt-get install -y -qq shellcheck && shellcheck --severity=warning $(git ls-files '*.sh') debian/*.preinst debian/*.postinst debian/*.prerm debian/*.postrm - name: reuse (license compliance) run: reuse lint - name: blocklist smoke @@ -145,11 +151,14 @@ jobs: # dpkg-buildpackage writes one level above the source tree. mkdir -p output && mv ../*.deb ../*.changes ../*.buildinfo ../*.dsc ../*.tar.xz output/ # DEBIAN/md5sums must cover every shipped regular file, or `dpkg --verify` is a no-op. - deb=$(ls output/*.deb) - dpkg-deb -I "$deb" - dpkg-deb --ctrl-tarfile "$deb" | tar -tf - | grep -qx './md5sums' - test "$(dpkg-deb -c "$deb" | grep -c '^-')" = "$(dpkg-deb --ctrl-tarfile "$deb" | tar -xOf - ./md5sums | wc -l)" - echo "md5sums: $(dpkg-deb --ctrl-tarfile "$deb" | tar -xOf - ./md5sums | wc -l) files" + # Two binary packages: linuxmuster-squid (amd64) and linuxmuster-squid-webui (all). + test "$(ls output/*.deb | wc -l)" = 2 + for deb in output/linuxmuster-squid_*_amd64.deb output/linuxmuster-squid-webui_*_all.deb; do + dpkg-deb -I "$deb" + dpkg-deb --ctrl-tarfile "$deb" | tar -tf - | grep -qx './md5sums' + test "$(dpkg-deb -c "$deb" | grep -c '^-')" = "$(dpkg-deb --ctrl-tarfile "$deb" | tar -xOf - ./md5sums | wc -l)" + echo "$deb md5sums: $(dpkg-deb --ctrl-tarfile "$deb" | tar -xOf - ./md5sums | wc -l) files" + done - name: Lintian (the .deb only) run: | # Never lint the .changes: `lmn73` is not a known distribution, which makes lintian @@ -239,7 +248,7 @@ jobs: gh release download "$tag" --repo "$GITHUB_REPOSITORY" --pattern '*.deb' --dir previous && break echo "download attempt $i failed, retrying"; sleep 10 done - test -n "$(ls previous/*.deb 2>/dev/null)" + test -n "$(ls previous/linuxmuster-squid_*_amd64.deb 2>/dev/null)" echo "tag=$tag" >> "$GITHUB_OUTPUT" - name: Compare the file tree with the released package if: steps.prev.outputs.skip != '1' @@ -251,8 +260,8 @@ jobs: # unnoticed in a file-only comparison); a symlink prints "path -> target", so a # retargeted link (/usr/bin/lmnsquid, the venv's python and lib64) is drift too. norm() { dpkg-deb -c "$1" | awk '{t = ($7 == "->" ? " " $7 " " $8 : ""); print $1, $2, $6 t}' | LC_ALL=C sort; } - norm previous/*.deb > old.txt - norm packages/*.deb > new.txt + norm previous/linuxmuster-squid_*_amd64.deb > old.txt + norm packages/linuxmuster-squid_*_amd64.deb > new.txt python3 - old.txt new.txt linuxmuster-squid lmnsquid "$PREV_TAG" <<'PY' | tee -a "$GITHUB_STEP_SUMMARY" import re import sys @@ -318,7 +327,7 @@ jobs: run: | set -eux sudo apt-get update -qq - sudo apt-get install -y ./packages/*.deb + sudo apt-get install -y ./packages/linuxmuster-squid_*_amd64.deb test "$(command -v lmnsquid)" = /usr/bin/lmnsquid sudo lmnsquid --help >/dev/null # postinst enabled + started the service; the API must answer like the docs promise. @@ -347,6 +356,12 @@ jobs: # race, so the same .deb is configured 30 more times, failing on the first error. - name: Configure loop (15x purge + fresh install, 15x reinstall/dpkg-reconfigure) run: sudo bash scripts/tests/install_loop.sh packages/linuxmuster-squid_*_amd64.deb 15 + # The WebUI plugin package depends on linuxmuster-webui7, which only a school server has: + # installed with --force-depends next to recording stand-ins of merge-permissions.py and + # sophomorix-ui (file tree, permissions.yml, configure/remove/purge). The WebUI itself is + # tested in the lab. + - name: WebUI plugin package (without linuxmuster-webui7) + run: sudo bash scripts/tests/webui_deb_smoke.sh packages/linuxmuster-squid-webui_*_all.deb # Kevin's rule: a release must still install cleanly ON TOP OF the version that is # already running on a school server. This job installs the newest published release @@ -402,7 +417,7 @@ jobs: gh release download "$tag" --repo "$GITHUB_REPOSITORY" --pattern '*.deb' --dir previous && break echo "download attempt $i failed, retrying"; sleep 10 done - test -n "$(ls previous/*.deb 2>/dev/null)" + test -n "$(ls previous/linuxmuster-squid_*_amd64.deb 2>/dev/null)" echo "tag=$tag" >> "$GITHUB_OUTPUT" echo "::notice::upgrading from $tag" @@ -411,7 +426,7 @@ jobs: run: | set -eux sudo apt-get update -qq - sudo apt-get install -y ./previous/*.deb + sudo apt-get install -y ./previous/linuxmuster-squid_*_amd64.deb # v1.3.0 (the pre-conventions line) ships no /usr/bin/lmnsquid, so the OLD # version is always driven through its venv entry point. LMN=/opt/linuxmuster-squid/venv/bin/lmnsquid @@ -541,7 +556,7 @@ jobs: # to the release, and a plain install would say "already the newest version" # and test nothing. dpkg must run the postinst with $2 set, or its upgrade # branch (restart, update-all, reconcile) never runs. - sudo apt-get install -y --reinstall --allow-downgrades ./packages/*.deb 2>&1 \ + sudo apt-get install -y --reinstall --allow-downgrades ./packages/linuxmuster-squid_*_amd64.deb 2>&1 \ | tee upgrade.log - name: Assert that nothing was lost @@ -586,6 +601,15 @@ jobs: sudo test -f "$noauth_file" || { echo "missing: $noauth_file"; exit 1; } if sudo test -s "$noauth_file"; then echo "not empty: $noauth_file"; exit 1; fi done < <(awk '$3 ~ /^\/etc\/linuxmuster-squid\/blocklists\/[^\/]+\/blocked\.domains$/' before/etc-modes) + # (since 7.3.11, ADR-018) the postinst makes the TLS listener's self-signed + # certificate once: tls/ (0700) with api.key (0600) and api.crt (0644), owned like + # the tree, where the previous release had none. + if ! awk '$3 == "/etc/linuxmuster-squid/tls" { f = 1 } END { exit !f }' before/etc-modes; then + owner=$(awk '$3 == "/etc/linuxmuster-squid" { print $2 }' before/etc-modes) + printf '%s\n' "700 $owner /etc/linuxmuster-squid/tls" \ + "600 $owner /etc/linuxmuster-squid/tls/api.key" \ + "644 $owner /etc/linuxmuster-squid/tls/api.crt" >> before/etc-modes.expected + fi sort -o before/etc-modes.expected before/etc-modes.expected diff -u before/etc-modes.expected after/etc-modes @@ -677,14 +701,14 @@ jobs: STATE=/var/lib/systemd/deb-systemd-helper-enabled/$U.dsh-also sudo apt-get purge -y linuxmuster-squid test ! -e "$STATE" # purge forgot the state: the release starts from scratch - sudo apt-get install -y ./previous/*.deb + sudo apt-get install -y ./previous/linuxmuster-squid_*_amd64.deb test "$(systemctl is-enabled $U)" = enabled sudo systemctl disable --now $U test "$(systemctl is-active $U || true)" = inactive for pass in 1 2; do cursor="$(sudo journalctl -q -n 0 --show-cursor | sed -n 's/^-- cursor: //p')" test -n "$cursor" - sudo apt-get install -y --reinstall --allow-downgrades ./packages/*.deb 2>&1 \ + sudo apt-get install -y --reinstall --allow-downgrades ./packages/linuxmuster-squid_*_amd64.deb 2>&1 \ | tee "disabled-$pass.log" grep -E 'Unpacking linuxmuster-squid \([^)]+\) over \([^)]+\)' "disabled-$pass.log" test "$(systemctl is-enabled $U || true)" = disabled diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index be05e2f..564ba82 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -89,10 +89,14 @@ jobs: # dpkg-buildpackage writes one level above the source tree. mkdir -p output && mv ../*.deb ../*.changes ../*.buildinfo ../*.dsc ../*.tar.xz output/ # DEBIAN/md5sums must cover every shipped regular file, or `dpkg --verify` is a no-op. - deb=$(ls output/*.deb) - dpkg-deb -I "$deb" - dpkg-deb --ctrl-tarfile "$deb" | tar -tf - | grep -qx './md5sums' - test "$(dpkg-deb -c "$deb" | grep -c '^-')" = "$(dpkg-deb --ctrl-tarfile "$deb" | tar -xOf - ./md5sums | wc -l)" + # Two binary packages: linuxmuster-squid (amd64) and linuxmuster-squid-webui (all). + test "$(ls output/*.deb | wc -l)" = 2 + for deb in output/linuxmuster-squid_*_amd64.deb output/linuxmuster-squid-webui_*_all.deb; do + dpkg-deb -I "$deb" + dpkg-deb --ctrl-tarfile "$deb" | tar -tf - | grep -qx './md5sums' + test "$(dpkg-deb -c "$deb" | grep -c '^-')" = "$(dpkg-deb --ctrl-tarfile "$deb" | tar -xOf - ./md5sums | wc -l)" + echo "$deb md5sums: $(dpkg-deb --ctrl-tarfile "$deb" | tar -xOf - ./md5sums | wc -l) files" + done - name: Lintian (the .deb only) run: | # Never lint the .changes: `lmn73` is not a known distribution (see ci.yml). @@ -153,7 +157,7 @@ jobs: gh release download "$tag" --repo "$GITHUB_REPOSITORY" --pattern '*.deb' --dir previous && break echo "download attempt $i failed, retrying"; sleep 10 done - test -n "$(ls previous/*.deb 2>/dev/null)" + test -n "$(ls previous/linuxmuster-squid_*_amd64.deb 2>/dev/null)" echo "tag=$tag" >> "$GITHUB_OUTPUT" - name: Compare the file tree with the released package if: steps.prev.outputs.skip != '1' @@ -165,8 +169,8 @@ jobs: # unnoticed in a file-only comparison); a symlink prints "path -> target", so a # retargeted link (/usr/bin/lmnsquid, the venv's python and lib64) is drift too. norm() { dpkg-deb -c "$1" | awk '{t = ($7 == "->" ? " " $7 " " $8 : ""); print $1, $2, $6 t}' | LC_ALL=C sort; } - norm previous/*.deb > old.txt - norm packages/*.deb > new.txt + norm previous/linuxmuster-squid_*_amd64.deb > old.txt + norm packages/linuxmuster-squid_*_amd64.deb > new.txt python3 - old.txt new.txt linuxmuster-squid lmnsquid "$PREV_TAG" <<'PY' | tee -a "$GITHUB_STEP_SUMMARY" import re import sys @@ -231,7 +235,7 @@ jobs: run: | set -eux sudo apt-get update -qq - sudo apt-get install -y ./packages/*.deb + sudo apt-get install -y ./packages/linuxmuster-squid_*_amd64.deb test "$(command -v lmnsquid)" = /usr/bin/lmnsquid sudo lmnsquid --help >/dev/null ok=0 @@ -257,6 +261,12 @@ jobs: # race, so the same .deb is configured 30 more times, failing on the first error. - name: Configure loop (15x purge + fresh install, 15x reinstall/dpkg-reconfigure) run: sudo bash scripts/tests/install_loop.sh packages/linuxmuster-squid_*_amd64.deb 15 + # The WebUI plugin package depends on linuxmuster-webui7, which only a school server has: + # installed with --force-depends next to recording stand-ins of merge-permissions.py and + # sophomorix-ui (file tree, permissions.yml, configure/remove/purge). The WebUI itself is + # tested in the lab. + - name: WebUI plugin package (without linuxmuster-webui7) + run: sudo bash scripts/tests/webui_deb_smoke.sh packages/linuxmuster-squid-webui_*_all.deb # Kevin's rule: a release must still install cleanly ON TOP OF the version that is # already running on a school server. This job installs the newest published release @@ -313,7 +323,7 @@ jobs: gh release download "$tag" --repo "$GITHUB_REPOSITORY" --pattern '*.deb' --dir previous && break echo "download attempt $i failed, retrying"; sleep 10 done - test -n "$(ls previous/*.deb 2>/dev/null)" + test -n "$(ls previous/linuxmuster-squid_*_amd64.deb 2>/dev/null)" echo "tag=$tag" >> "$GITHUB_OUTPUT" echo "::notice::upgrading from $tag" @@ -322,7 +332,7 @@ jobs: run: | set -eux sudo apt-get update -qq - sudo apt-get install -y ./previous/*.deb + sudo apt-get install -y ./previous/linuxmuster-squid_*_amd64.deb # v1.3.0 (the pre-conventions line) ships no /usr/bin/lmnsquid, so the OLD # version is always driven through its venv entry point. LMN=/opt/linuxmuster-squid/venv/bin/lmnsquid @@ -452,7 +462,7 @@ jobs: # to the release, and a plain install would say "already the newest version" # and test nothing. dpkg must run the postinst with $2 set, or its upgrade # branch (restart, update-all, reconcile) never runs. - sudo apt-get install -y --reinstall --allow-downgrades ./packages/*.deb 2>&1 \ + sudo apt-get install -y --reinstall --allow-downgrades ./packages/linuxmuster-squid_*_amd64.deb 2>&1 \ | tee upgrade.log - name: Assert that nothing was lost @@ -497,6 +507,15 @@ jobs: sudo test -f "$noauth_file" || { echo "missing: $noauth_file"; exit 1; } if sudo test -s "$noauth_file"; then echo "not empty: $noauth_file"; exit 1; fi done < <(awk '$3 ~ /^\/etc\/linuxmuster-squid\/blocklists\/[^\/]+\/blocked\.domains$/' before/etc-modes) + # (since 7.3.11, ADR-018) the postinst makes the TLS listener's self-signed + # certificate once: tls/ (0700) with api.key (0600) and api.crt (0644), owned like + # the tree, where the previous release had none. + if ! awk '$3 == "/etc/linuxmuster-squid/tls" { f = 1 } END { exit !f }' before/etc-modes; then + owner=$(awk '$3 == "/etc/linuxmuster-squid" { print $2 }' before/etc-modes) + printf '%s\n' "700 $owner /etc/linuxmuster-squid/tls" \ + "600 $owner /etc/linuxmuster-squid/tls/api.key" \ + "644 $owner /etc/linuxmuster-squid/tls/api.crt" >> before/etc-modes.expected + fi sort -o before/etc-modes.expected before/etc-modes.expected diff -u before/etc-modes.expected after/etc-modes @@ -588,14 +607,14 @@ jobs: STATE=/var/lib/systemd/deb-systemd-helper-enabled/$U.dsh-also sudo apt-get purge -y linuxmuster-squid test ! -e "$STATE" # purge forgot the state: the release starts from scratch - sudo apt-get install -y ./previous/*.deb + sudo apt-get install -y ./previous/linuxmuster-squid_*_amd64.deb test "$(systemctl is-enabled $U)" = enabled sudo systemctl disable --now $U test "$(systemctl is-active $U || true)" = inactive for pass in 1 2; do cursor="$(sudo journalctl -q -n 0 --show-cursor | sed -n 's/^-- cursor: //p')" test -n "$cursor" - sudo apt-get install -y --reinstall --allow-downgrades ./packages/*.deb 2>&1 \ + sudo apt-get install -y --reinstall --allow-downgrades ./packages/linuxmuster-squid_*_amd64.deb 2>&1 \ | tee "disabled-$pass.log" grep -E 'Unpacking linuxmuster-squid \([^)]+\) over \([^)]+\)' "disabled-$pass.log" test "$(systemctl is-enabled $U || true)" = disabled 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/controlplane/lmnsquid/api.py b/controlplane/lmnsquid/api.py index 1abf79f..99bb28d 100644 --- a/controlplane/lmnsquid/api.py +++ b/controlplane/lmnsquid/api.py @@ -12,12 +12,12 @@ from docker.errors import DockerException from fastapi import Depends, FastAPI, HTTPException, Request, status from fastapi.exceptions import RequestValidationError -from fastapi.responses import JSONResponse +from fastapi.responses import JSONResponse, Response from pydantic import ValidationError from .blocklist import Blocklist, noauth_list from .config import Settings -from .docker_service import DockerService +from .docker_service import DockerService, KeytabMissing, keytab_problem from .models import ( DEFAULT_IMAGE, BlocklistEntry, @@ -27,6 +27,8 @@ UpdateRequest, ) from .reconciler import Reconciler +from .secrets import MAX_BYTES as SECRET_MAX_BYTES +from .secrets import SecretError, describe_secret, write_secret from .security import make_verify_token from .store import Store from .updater import Updater @@ -58,6 +60,11 @@ async def _docker_unreachable(_request: Request, exc: DockerException) -> JSONRe content={"detail": f"docker daemon unreachable: {exc}"}, ) + @app.exception_handler(KeytabMissing) + async def _keytab_missing(_request: Request, exc: KeytabMissing) -> JSONResponse: + # No container was made; a create/edit has stored the definition all the same. + return JSONResponse(status_code=status.HTTP_409_CONFLICT, content={"detail": str(exc)}) + auth = [Depends(verify)] def _require(name: str) -> Instance: @@ -87,6 +94,27 @@ def _apply(inst: Instance) -> dict[str, Any]: status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(exc) ) from exc + def _status(inst: Instance) -> dict[str, Any]: + """Container state plus what keeps the definition from running (additive fields). + + ``problem`` is ``"keytab"`` (with ``problem_detail``) when the keytab is not a usable + file in secrets_dir, else ``None``. + """ + result = docker.status(inst.name) + problem = keytab_problem(docker.secrets_dir, inst.keytab_secret) + result["problem"] = "keytab" if problem else None + result["problem_detail"] = problem + return result + + def _ensure(inst: Instance) -> dict[str, Any]: + """Create (or re-create) the container of a stored definition, health-gated.""" + try: + return docker.ensure_running(inst) + except RuntimeError as exc: + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(exc) + ) from exc + def _check_log_params(tail: int, grep: str | None) -> None: if not 1 <= tail <= 10000: raise HTTPException( @@ -102,7 +130,10 @@ def _check_log_params(tail: int, grep: str | None) -> None: # ------------------------------------------------------------------ health @app.get("/v1/health") async def health() -> dict[str, str]: - return {"status": "ok"} + # "tls" only when a TLS listener is configured: "ok" or "failed: " (the + # loopback API keeps running when the TLS listener cannot, see main.serve_all). + tls = getattr(app.state, "tls", None) + return {"status": "ok", "tls": tls} if tls else {"status": "ok"} @app.get("/v1/version", dependencies=auth) async def version() -> dict[str, str]: @@ -133,6 +164,65 @@ 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 [_status(inst) 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(), + } + + # ---------------------------------------------------- write-only secrets (ADR-020) + @app.put( + "/v1/secrets/{name}", + dependencies=auth, + status_code=status.HTTP_204_NO_CONTENT, + ) + async def put_secret(name: str, request: Request) -> Response: + """Write the keytab ``name`` into secrets_dir (raw body, 0600). Never readable back. + + Instances using it pick it up on their next (re)start: the container entrypoint + copies the mounted file at start. + """ + # The limit while reading, not after: a client cannot make us buffer a large body. + declared = request.headers.get("content-length", "") + if declared.isdigit() and int(declared) > SECRET_MAX_BYTES: + raise HTTPException( + status_code=413, detail=f"secret larger than {SECRET_MAX_BYTES} bytes" + ) + chunks: list[bytes] = [] + size = 0 + async for chunk in request.stream(): + size += len(chunk) + if size > SECRET_MAX_BYTES: + raise HTTPException( + status_code=413, detail=f"secret larger than {SECRET_MAX_BYTES} bytes" + ) + chunks.append(chunk) + body = b"".join(chunks) + try: + write_secret(settings.secrets_dir, name, body) + except SecretError as exc: + raise HTTPException(status_code=exc.status, detail=str(exc)) from exc + audit.info("secret written name=%s bytes=%d", name, len(body)) + return Response(status_code=status.HTTP_204_NO_CONTENT) + + @app.get("/v1/secrets/{name}", dependencies=auth) + async def get_secret(name: str) -> dict[str, Any]: + """Only whether the secret exists and its mtime, never the content.""" + try: + return describe_secret(settings.secrets_dir, name) + except SecretError as exc: + raise HTTPException(status_code=exc.status, detail=str(exc)) from exc + # --------------------------------------------------------------- instances @app.post( "/v1/instances", @@ -297,10 +387,15 @@ def reload_noauth(name: str) -> dict[str, Any]: ) from exc # ----------------------------------------------------------- lifecycle ops + # start/restart of an instance WITHOUT a container (never created, its creation failed, e.g. + # for a missing keytab, or removed by hand) create it from the stored definition, like + # reconcile does for this one instance; before, start answered 200 and did nothing. @app.post("/v1/instances/{name}/start", dependencies=auth) - async def start_instance(name: str) -> dict[str, Any]: - _require(name) + def start_instance(name: str) -> dict[str, Any]: + inst = _require(name) audit.info("start instance name=%s", name) + if not docker.status(name).get("exists"): + return _ensure(inst) return docker.start(name) @app.post("/v1/instances/{name}/stop", dependencies=auth) @@ -310,15 +405,16 @@ async def stop_instance(name: str) -> dict[str, Any]: return docker.stop(name) @app.post("/v1/instances/{name}/restart", dependencies=auth) - async def restart_instance(name: str) -> dict[str, Any]: - _require(name) + def restart_instance(name: str) -> dict[str, Any]: + inst = _require(name) audit.info("restart instance name=%s", name) + if not docker.status(name).get("exists"): + return _ensure(inst) return docker.restart(name) @app.get("/v1/instances/{name}/status", dependencies=auth) - async def instance_status(name: str) -> dict[str, Any]: - _require(name) - return docker.status(name) + def instance_status(name: str) -> dict[str, Any]: + return _status(_require(name)) @app.get("/v1/instances/{name}/logs", dependencies=auth) async def instance_logs( diff --git a/controlplane/lmnsquid/cli.py b/controlplane/lmnsquid/cli.py index b3f4b38..9b93a34 100644 --- a/controlplane/lmnsquid/cli.py +++ b/controlplane/lmnsquid/cli.py @@ -4,7 +4,13 @@ from __future__ import annotations +import contextlib +import ipaddress import json +import os +import stat +import tempfile +from pathlib import Path from typing import Any, Optional from urllib.parse import quote @@ -12,6 +18,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 +438,82 @@ 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 + + +_TLS_KEYS = ("tls_bind_host", "tls_bind_port", "tls_allowed_clients") + + +def set_tls_config(path: str, bind_host: str, port: int, allow: list[str]) -> None: + """Set the three TLS listener keys in ``path``, keeping every other line and comment. + + Lines of an earlier ``tls_*`` setting are replaced; the file keeps its mode and owner and + is replaced atomically. + """ + addr = ipaddress.ip_address(bind_host) + if addr.is_unspecified: + raise ValueError("the TLS listener needs the management address, not 0.0.0.0/::") + if not 1 <= port <= 65535: + raise ValueError(f"port {port} out of range") + clients = [str(ipaddress.ip_network(a, strict=False)) for a in allow] + cfg = Path(path) + st = cfg.stat() + kept = [ + line + for line in cfg.read_text(encoding="utf-8").splitlines() + if line.split(":", 1)[0].strip() not in _TLS_KEYS # comments keep their "# " prefix + ] + kept += [ + f"tls_bind_host: {addr}", + f"tls_bind_port: {port}", + f"tls_allowed_clients: {json.dumps(clients)}", + ] + fd, tmp = tempfile.mkstemp(dir=cfg.parent, prefix=".config.", suffix=".tmp") + try: + os.fchmod(fd, stat.S_IMODE(st.st_mode)) + os.fchown(fd, st.st_uid, st.st_gid) + with os.fdopen(fd, "w", encoding="utf-8") as fh: + fh.write("\n".join(kept) + "\n") + os.replace(tmp, cfg) + except BaseException: + with contextlib.suppress(FileNotFoundError): + os.unlink(tmp) + raise + + +@tls_app.command("enable") +def tls_enable( + bind_host: str = typer.Option(..., help="management address of this host (never 0.0.0.0)"), + port: int = typer.Option(8443, help="port of the TLS listener"), + allow: list[str] = typer.Option( + [], "--allow", help="client address/CIDR allowed on the TLS listener; repeat" + ), +) -> None: + """Turn the TLS listener on in config.yml; restart the service afterwards.""" + path = os.environ.get("LMNSQUID_CONFIG", "/etc/linuxmuster-squid/config.yml") + try: + set_tls_config(path, bind_host, port, allow) + except (OSError, ValueError) as exc: + typer.secho(f"error: {exc}", fg=typer.colors.RED, err=True) + raise typer.Exit(1) from None + typer.echo(f"TLS listener set in {path}: systemctl restart linuxmuster-squid") + + 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/docker_service.py b/controlplane/lmnsquid/docker_service.py index c888175..8e72a7d 100644 --- a/controlplane/lmnsquid/docker_service.py +++ b/controlplane/lmnsquid/docker_service.py @@ -8,19 +8,62 @@ import json import logging import os +import stat import time from typing import Any, Optional import docker from docker.errors import APIError, ImageNotFound, NotFound from docker.models.containers import Container -from docker.types import LogConfig +from docker.types import LogConfig, Mount from .blocklist import CONTAINER_DIR, Blocklist, noauth_list from .models import KRB5_CLOCKSKEW_DEFAULT, Instance logger = logging.getLogger("lmnsquid.docker") + +class KeytabMissing(Exception): + """The keytab an instance names is not a usable file in secrets_dir: no container is made. + + The API answers 409 with the reason; the instance definition stays stored, so the admin + can provision the keytab and start the instance (docs/keytab-and-dns.md). + """ + + +def keytab_problem(secrets_dir: str, keytab_secret: str) -> Optional[str]: + """Why ``keytab_secret`` cannot be mounted, or ``None`` when it is a regular, non-empty file. + + Checked before any container is created: a bind mount of a missing source makes Docker + create a root-owned DIRECTORY there, squid then fails and the error says only "not + healthy". A symlink is refused too (it could point anywhere on the host). + """ + path = os.path.join(secrets_dir, keytab_secret) + hint = "provision it first, see docs/keytab-and-dns.md" + try: + st = os.lstat(path) + except FileNotFoundError: + return f"keytab secret {keytab_secret!r} missing in {secrets_dir}: {hint}" + except OSError as exc: + return f"keytab secret {keytab_secret!r} in {secrets_dir} cannot be checked: {exc.strerror}" + if stat.S_ISLNK(st.st_mode): + return f"keytab secret {keytab_secret!r} in {secrets_dir} is a symlink: put the file itself there" + if not stat.S_ISREG(st.st_mode): + return ( + f"keytab secret {keytab_secret!r} in {secrets_dir} is not a regular file (a " + f"directory?): remove it and {hint}" + ) + if st.st_size == 0: + return f"keytab secret {keytab_secret!r} in {secrets_dir} is empty: {hint}" + if st.st_mode & 0o077: + logger.warning( + "keytab %s is group/world accessible (mode %o): chmod 600", + path, + st.st_mode & 0o777, + ) + return None + + # The config entrypoint.sh renders and starts squid with (`squid -k` must read the same # file to find pid_filename). _SQUID_CONF = "/run/lmnsquid/squid.conf" @@ -195,6 +238,9 @@ def ensure_running(self, inst: Instance) -> dict[str, Any]: one restarted, and a ``RuntimeError`` says so. Only a healthy replacement removes the previous container. """ + problem = keytab_problem(self.secrets_dir, inst.keytab_secret) + if problem is not None: + raise KeytabMissing(problem) try: self._pull(inst.image) except (ImageNotFound, APIError): @@ -224,6 +270,12 @@ def ensure_running(self, inst: Instance) -> dict[str, Any]: if stale is not None: stale.remove(force=True) + # The keytab as a Mount, not a volume bind: a bind of a missing source path makes + # Docker create a directory there, a Mount fails instead. The spec (and so the + # fingerprint of running containers) keeps the volume form. + keytab_target = spec["environment"]["KEYTAB"] + volumes = {k: v for k, v in spec["volumes"].items() if v["bind"] != keytab_target} + keytab_source = next(k for k, v in spec["volumes"].items() if v["bind"] == keytab_target) # Create first: an unpullable image, a full disk or a daemon error leaves the # old container untouched and still serving. new = self.client.containers.create( @@ -238,7 +290,8 @@ def ensure_running(self, inst: Instance) -> dict[str, Any]: cap_add=spec["cap_add"], security_opt=spec["security_opt"], log_config=LogConfig(type="json-file", config=spec["log_config"]), - volumes=spec["volumes"], + volumes=volumes, + mounts=[Mount(keytab_target, keytab_source, type="bind", read_only=True)], ports={k: tuple(v) for k, v in spec["ports"].items()}, labels={SPEC_LABEL: digest}, ) diff --git a/controlplane/lmnsquid/main.py b/controlplane/lmnsquid/main.py index 707ea59..f97dcac 100644 --- a/controlplane/lmnsquid/main.py +++ b/controlplane/lmnsquid/main.py @@ -4,29 +4,38 @@ from __future__ import annotations +import asyncio import logging +import signal +import socket +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 +44,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 +65,132 @@ 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), app)) + + +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)] + + +def _bind(host: str, port: int) -> socket.socket: + """Bind the TLS listener's socket ourselves: uvicorn ends the whole process on a bind + error (sys.exit), which would take the loopback listener down with it.""" + family = socket.AF_INET6 if ":" in host else socket.AF_INET + sock = socket.socket(family, socket.SOCK_STREAM) + try: + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + sock.bind((host, port)) + except BaseException: + sock.close() + raise + return sock + + +def _set_tls_state(app: Any, state: str) -> None: + if app is not None: + app.state.tls = state + + +async def serve_all(servers: list[uvicorn.Server], app: Any = None) -> None: + """Run the plain listener (``servers[0]``) and the TLS listener(s) together. + + SIGTERM/SIGINT, or the plain listener ending, stops all of them. A TLS listener that cannot + start (address not on this host any more, port taken, unusable certificate) or that ends on + its own is logged as an ERROR and reported in ``/v1/health`` (``tls``) while the loopback + API keeps running: the CLI, the package scripts and the containers' management stay usable + (configuration errors are still refused at start by ``check_tls_settings``). + """ + loop = asyncio.get_running_loop() + stopping = False + + def stop() -> None: + nonlocal stopping + stopping = True + for server in servers: + server.should_exit = True + + for sig in (signal.SIGTERM, signal.SIGINT): + loop.add_signal_handler(sig, stop) + plain, *others = servers + tasks: dict[asyncio.Task[None], uvicorn.Server] = {asyncio.create_task(plain.serve()): plain} + try: + for server in others: + config = server.config + try: + if not config.loaded: + config.load() + sock = _bind(config.host, config.port) + except Exception as exc: # noqa: BLE001 - OSError, ssl.SSLError, ...: all reported + log.error( + "TLS listener %s:%s not started, the API stays on %s:%s only: %s", + config.host, + config.port, + plain.config.host, + plain.config.port, + exc, + ) + _set_tls_state(app, f"failed: {exc}") + continue + tasks[asyncio.create_task(server.serve(sockets=[sock]))] = server + _set_tls_state(app, "ok") + pending = set(tasks) + while pending: + done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED) + plain_done = any(tasks[t] is plain for t in done) + for task in done: + if tasks[task] is not plain and not stopping: + error = task.exception() + log.error("TLS listener stopped, the loopback API keeps running: %s", error) + _set_tls_state(app, f"failed: stopped ({error})") + if plain_done or stopping: + stop() + await asyncio.gather(*pending, return_exceptions=True) + for task in done: + if tasks[task] is plain: + task.result() # the plain listener failed to start (port taken) + break + if not plain.started: + raise SystemExit(1) + finally: + for sig in (signal.SIGTERM, signal.SIGINT): + loop.remove_signal_handler(sig) if __name__ == "__main__": diff --git a/controlplane/lmnsquid/secrets.py b/controlplane/lmnsquid/secrets.py new file mode 100644 index 0000000..8e62419 --- /dev/null +++ b/controlplane/lmnsquid/secrets.py @@ -0,0 +1,81 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""Write-only secrets (keytabs) in secrets_dir, for ``PUT /v1/secrets/{name}`` (ADR-020). + +A secret is written, replaced or reported as present; it is never read back through the API. +Files are created ``0600`` by the service user (lmnsquid), atomically (temporary file in the +same directory, fsync, rename), so a container never mounts a half-written keytab. +""" + +from __future__ import annotations + +import contextlib +import os +import re +import stat +import tempfile +from pathlib import Path +from typing import Any + +# Same rule as Instance.keytab_secret: a file name inside secrets_dir, nothing else. +NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$") +MAX_BYTES = 64 * 1024 # a keytab of one account with a few enctypes is about 1 KiB + + +class SecretError(Exception): + """The secret cannot be written; ``status`` is the HTTP status to answer with.""" + + def __init__(self, status: int, message: str) -> None: + super().__init__(message) + self.status = status + + +def check_name(name: str) -> None: + if ".." in name or not NAME_RE.match(name): + raise SecretError(422, "invalid secret name (a file name: letters, digits, . _ -)") + + +def write_secret(secrets_dir: str, name: str, data: bytes) -> None: + check_name(name) + if not data: + raise SecretError(422, "empty secret") + if len(data) > MAX_BYTES: + raise SecretError(413, f"secret larger than {MAX_BYTES} bytes") + root = Path(secrets_dir) + root.mkdir(mode=0o700, parents=True, exist_ok=True) + target = root / name + try: + st = os.lstat(target) + except FileNotFoundError: + st = None + if st is not None and stat.S_ISDIR(st.st_mode): + # What Docker left behind when it bound a missing keytab (up to 7.3.9): an empty + # directory. Removed so the file can take its place; anything else is the admin's. + try: + os.rmdir(target) + except OSError: + raise SecretError(409, f"{target} is a directory that is not empty") from None + fd, tmp = tempfile.mkstemp(dir=root, prefix=".secret-", suffix=".tmp") + try: + os.fchmod(fd, 0o600) + with os.fdopen(fd, "wb") as fh: + fh.write(data) + fh.flush() + os.fsync(fh.fileno()) + # os.replace renames over a symlink (replaces the link, never writes through it). + os.replace(tmp, target) + except BaseException: + with contextlib.suppress(FileNotFoundError): + os.unlink(tmp) + raise + + +def describe_secret(secrets_dir: str, name: str) -> dict[str, Any]: + """Whether the secret is there and when it was written; never its content or size.""" + check_name(name) + try: + st = os.lstat(Path(secrets_dir) / name) + except FileNotFoundError: + return {"name": name, "exists": False, "mtime": None} + regular = stat.S_ISREG(st.st_mode) and st.st_size > 0 + return {"name": name, "exists": regular, "mtime": int(st.st_mtime) if regular else None} 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/conftest.py b/controlplane/tests/conftest.py index 6333320..5754505 100644 --- a/controlplane/tests/conftest.py +++ b/controlplane/tests/conftest.py @@ -17,7 +17,7 @@ from lmnsquid.api import create_app from lmnsquid.blocklist import Blocklist, noauth_list from lmnsquid.config import Settings -from lmnsquid.docker_service import DockerService +from lmnsquid.docker_service import DockerService, KeytabMissing, keytab_problem from lmnsquid.models import Instance from lmnsquid.reconciler import Reconciler from lmnsquid.store import Store @@ -50,12 +50,19 @@ def __init__( self.ensure_calls: list[str] = [] self.removed: list[str] = [] self.reloaded: list[str] = [] + # Opt-in: refuse a missing keytab like the real ensure_running (most tests name + # keytabs that do not exist on disk). + self.check_secrets = False def env_for(self, inst: Instance) -> dict[str, str]: # The real one (it touches no Docker), so API tests see the env a container gets. return DockerService.env_for(self, inst) # type: ignore[arg-type] def ensure_running(self, inst: Instance) -> dict[str, Any]: + if self.check_secrets: + problem = keytab_problem(self.secrets_dir, inst.keytab_secret) + if problem: + raise KeytabMissing(problem) self.ensure_calls.append(inst.name) if "unpullable" in inst.image: # Mirror the real service: the replacement is created first, so a failure 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_docker_service.py b/controlplane/tests/test_docker_service.py index 4ed86b6..4097255 100644 --- a/controlplane/tests/test_docker_service.py +++ b/controlplane/tests/test_docker_service.py @@ -21,6 +21,10 @@ def _service(tmp_path: Path) -> DockerService: ds = DockerService.__new__(DockerService) # bypass __init__ (no docker daemon) ds.client = MagicMock() ds.secrets_dir = str(tmp_path / "secrets") + # ensure_running refuses an instance whose keytab is not a file (keytab_problem) + (tmp_path / "secrets").mkdir(exist_ok=True) + (tmp_path / "secrets" / "proxy.keytab").write_bytes(b"keytab") + (tmp_path / "secrets" / "proxy.keytab").chmod(0o600) ds.blocklist = Blocklist(str(tmp_path / "blocklists")) ds.noauth = noauth_list(str(tmp_path / "blocklists")) ds.container_bind_ip = "0.0.0.0" diff --git a/controlplane/tests/test_keytab_check.py b/controlplane/tests/test_keytab_check.py new file mode 100644 index 0000000..d94d543 --- /dev/null +++ b/controlplane/tests/test_keytab_check.py @@ -0,0 +1,149 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""A missing keytab never reaches Docker; start/restart create a missing container (lab finds).""" + +from __future__ import annotations + +import logging +from pathlib import Path +from typing import Any + +import pytest +from starlette.testclient import TestClient +from test_docker_service import _container, _inst, _registry, _service + +from lmnsquid.docker_service import KeytabMissing, keytab_problem + + +def test_keytab_problem(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None: + d = tmp_path / "secrets" + d.mkdir() + assert "missing in" in (keytab_problem(str(d), "a.keytab") or "") + (d / "dir.keytab").mkdir() # what Docker leaves behind after binding a missing path + assert "not a regular file" in (keytab_problem(str(d), "dir.keytab") or "") + (d / "empty.keytab").write_bytes(b"") + assert "empty" in (keytab_problem(str(d), "empty.keytab") or "") + (tmp_path / "elsewhere").write_bytes(b"x") + (d / "link.keytab").symlink_to(tmp_path / "elsewhere") + assert "symlink" in (keytab_problem(str(d), "link.keytab") or "") + ok = d / "ok.keytab" + ok.write_bytes(b"keytab") + ok.chmod(0o600) + assert keytab_problem(str(d), "ok.keytab") is None + ok.chmod(0o644) + with caplog.at_level(logging.WARNING, logger="lmnsquid.docker"): + assert keytab_problem(str(d), "ok.keytab") is None + assert "chmod 600" in caplog.text + # the message tells the admin what to do, and never shows file content + assert "docs/keytab-and-dns.md" in (keytab_problem(str(d), "a.keytab") or "") + + +def test_missing_keytab_creates_no_container(tmp_path: Path) -> None: + ds = _service(tmp_path) + _registry(ds, {}) + with pytest.raises(KeytabMissing, match="'missing.keytab' missing"): + ds.ensure_running(_inst(keytab_secret="missing.keytab")) + ds.client.containers.create.assert_not_called() + ds.client.images.pull.assert_not_called() + + +def test_keytab_is_a_mount_that_fails_on_a_missing_source(tmp_path: Path) -> None: + """A Mount (not a volume bind): Docker refuses a missing source instead of making a dir.""" + ds = _service(tmp_path) + _registry(ds, {}) + ds.client.containers.create.return_value = _container("lmnsquid-s-teachers.new") + ds.ensure_running(_inst()) + kwargs = ds.client.containers.create.call_args.kwargs + keytab = str((tmp_path / "secrets" / "proxy.keytab").resolve()) + assert keytab not in kwargs["volumes"] + [mount] = kwargs["mounts"] + assert (mount["Type"], mount["Source"], mount["Target"], mount["ReadOnly"]) == ( + "bind", + keytab, + "/run/secrets/proxy.keytab", + True, + ) + # the spec (fingerprint of running containers) is unchanged: no forced replacement + assert keytab in ds.spec_for(_inst())["volumes"] + + +@pytest.fixture +def strict(docker: Any, settings: Any) -> Path: + docker.check_secrets = True + secrets = Path(settings.secrets_dir) + secrets.mkdir(parents=True, exist_ok=True) + return secrets + + +def test_create_without_keytab_is_409_and_stored( + client: TestClient, + auth_headers: dict[str, str], + instance_data: dict[str, Any], + strict: Path, +) -> None: + name = "default-school-teachers" + resp = client.post("/v1/instances", json=instance_data, headers=auth_headers) + assert resp.status_code == 409 + assert "missing in" in resp.json()["detail"] + assert "docs/keytab-and-dns.md" in resp.json()["detail"] + # the definition is stored: provision the keytab, then start + assert client.get(f"/v1/instances/{name}", headers=auth_headers).status_code == 200 + st = client.get(f"/v1/instances/{name}/status", headers=auth_headers).json() + assert (st["exists"], st["problem"]) == (False, "keytab") + [bulk] = client.get("/v1/status", headers=auth_headers).json() + assert bulk["problem"] == "keytab" and "missing in" in bulk["problem_detail"] + assert client.post(f"/v1/instances/{name}/start", headers=auth_headers).status_code == 409 + + (strict / instance_data["keytab_secret"]).write_bytes(b"keytab") + resp = client.post(f"/v1/instances/{name}/start", headers=auth_headers) + assert resp.status_code == 200 + assert (resp.json()["exists"], resp.json()["running"]) == (True, True) + st = client.get(f"/v1/instances/{name}/status", headers=auth_headers).json() + assert (st["problem"], st["problem_detail"]) == (None, None) + + +def test_update_with_missing_keytab_is_409( + client: TestClient, + auth_headers: dict[str, str], + instance_data: dict[str, Any], + strict: Path, +) -> None: + keytab = strict / instance_data["keytab_secret"] + keytab.write_bytes(b"keytab") + assert client.post("/v1/instances", json=instance_data, headers=auth_headers).status_code == 201 + keytab.unlink() + resp = client.post( + "/v1/instances/default-school-teachers/update", json={}, headers=auth_headers + ) + assert resp.status_code == 409 + + +@pytest.mark.parametrize("action", ["start", "restart"]) +def test_start_without_container_creates_it( + client: TestClient, + auth_headers: dict[str, str], + instance_data: dict[str, Any], + docker: Any, + action: str, +) -> None: + """Before: 200 with exists false and nothing done.""" + name = "default-school-teachers" + assert client.post("/v1/instances", json=instance_data, headers=auth_headers).status_code == 201 + docker.containers.pop(name) # removed by hand / its creation failed + calls = len(docker.ensure_calls) + resp = client.post(f"/v1/instances/{name}/{action}", headers=auth_headers) + assert resp.status_code == 200 + assert (resp.json()["exists"], resp.json()["running"]) == (True, True) + assert len(docker.ensure_calls) == calls + 1 + + +def test_start_of_a_stopped_container_only_starts_it( + client: TestClient, auth_headers: dict[str, str], instance_data: dict[str, Any], docker: Any +) -> None: + name = "default-school-teachers" + assert client.post("/v1/instances", json=instance_data, headers=auth_headers).status_code == 201 + client.post(f"/v1/instances/{name}/stop", headers=auth_headers) + calls = len(docker.ensure_calls) + resp = client.post(f"/v1/instances/{name}/start", headers=auth_headers) + assert resp.json()["running"] is True + assert len(docker.ensure_calls) == calls # no new container diff --git a/controlplane/tests/test_secrets.py b/controlplane/tests/test_secrets.py new file mode 100644 index 0000000..b21c1f1 --- /dev/null +++ b/controlplane/tests/test_secrets.py @@ -0,0 +1,180 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""Write-only secrets endpoint (ADR-020) and `lmnsquid tls enable`.""" + +from __future__ import annotations + +import stat +from pathlib import Path +from typing import Any + +import pytest +import yaml +from starlette.testclient import TestClient +from typer.testing import CliRunner + +from lmnsquid import cli +from lmnsquid.config import load_settings + + +def test_put_writes_0600_and_never_reads_back( + client: TestClient, auth_headers: dict[str, str], settings: Any +) -> None: + resp = client.put( + "/v1/secrets/proxy.keytab", content=b"\x05\x02SECRETBYTES", headers=auth_headers + ) + assert resp.status_code == 204 + path = Path(settings.secrets_dir) / "proxy.keytab" + assert path.read_bytes() == b"\x05\x02SECRETBYTES" + assert stat.S_IMODE(path.stat().st_mode) == 0o600 + info = client.get("/v1/secrets/proxy.keytab", headers=auth_headers).json() + assert info["exists"] is True and isinstance(info["mtime"], int) + assert set(info) == {"name", "exists", "mtime"} # no content, no size + assert ( + b"SECRETBYTES" not in client.get("/v1/secrets/proxy.keytab", headers=auth_headers).content + ) + # replaced atomically, nothing left over + assert ( + client.put("/v1/secrets/proxy.keytab", content=b"new", headers=auth_headers).status_code + == 204 + ) + assert path.read_bytes() == b"new" + assert [p.name for p in path.parent.iterdir()] == ["proxy.keytab"] + missing = client.get("/v1/secrets/other.keytab", headers=auth_headers).json() + assert (missing["exists"], missing["mtime"]) == (False, None) + + +@pytest.mark.parametrize( + ("name", "body", "status"), + [ + ("a..b", b"x", 422), + (".hidden", b"x", 422), + ("a b", b"x", 422), + ("ok.keytab", b"", 422), + ("ok.keytab", b"x" * (64 * 1024 + 1), 413), + ], +) +def test_put_refuses( + client: TestClient, auth_headers: dict[str, str], name: str, body: bytes, status: int +) -> None: + assert ( + client.put(f"/v1/secrets/{name}", content=body, headers=auth_headers).status_code == status + ) + + +def test_put_size_limit_while_reading(client: TestClient, auth_headers: dict[str, str]) -> None: + """The limit is enforced on the declared length and on the streamed body (chunked, no + Content-Length), never after buffering the whole upload.""" + declared = {**auth_headers, "Content-Length": str(10 * 1024 * 1024)} + resp = client.put("/v1/secrets/ok.keytab", content=b"x", headers=declared) + assert resp.status_code == 413 + + # chunked upload without Content-Length, straight through ASGI: reading stops at the limit + import asyncio + + app = client.app + sent: list[int] = [] + + async def receive() -> dict[str, Any]: + sent.append(1) + return {"type": "http.request", "body": b"x" * 16384, "more_body": len(sent) < 1000} + + answer: dict[str, Any] = {} + + async def send(message: dict[str, Any]) -> None: + if message["type"] == "http.response.start": + answer["status"] = message["status"] + + token = auth_headers["Authorization"].encode() + scope = { + "type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": "PUT", + "scheme": "http", "path": "/v1/secrets/ok.keytab", "raw_path": b"/v1/secrets/ok.keytab", + "query_string": b"", "root_path": "", "client": ("127.0.0.1", 1), "server": ("t", 80), + "headers": [(b"authorization", token), (b"transfer-encoding", b"chunked")], + } # fmt: skip + asyncio.run(app(scope, receive, send)) + assert answer["status"] == 413 + assert len(sent) <= 64 * 1024 // 16384 + 1 # not the 16 MB the client offered + + +def test_put_needs_the_token(client: TestClient) -> None: + assert client.put("/v1/secrets/proxy.keytab", content=b"x").status_code == 401 + assert client.get("/v1/secrets/proxy.keytab").status_code == 401 + + +def test_put_replaces_dockers_empty_directory_but_not_a_full_one( + client: TestClient, auth_headers: dict[str, str], settings: Any +) -> None: + root = Path(settings.secrets_dir) + (root / "students.keytab").mkdir(parents=True) # left behind by a bind of a missing file + resp = client.put("/v1/secrets/students.keytab", content=b"kt", headers=auth_headers) + assert resp.status_code == 204 + assert (root / "students.keytab").is_file() + (root / "full").mkdir() + (root / "full" / "x").write_text("x") + assert client.put("/v1/secrets/full", content=b"kt", headers=auth_headers).status_code == 409 + + +def test_put_replaces_a_symlink_without_writing_through_it( + client: TestClient, auth_headers: dict[str, str], settings: Any, tmp_path: Path +) -> None: + root = Path(settings.secrets_dir) + root.mkdir(parents=True) + victim = tmp_path / "victim" + victim.write_text("keep") + (root / "proxy.keytab").symlink_to(victim) + assert ( + client.put("/v1/secrets/proxy.keytab", content=b"kt", headers=auth_headers).status_code + == 204 + ) + assert victim.read_text() == "keep" + assert not (root / "proxy.keytab").is_symlink() + + +CONFIG = """api_token: "t0ken" +bind_host: 127.0.0.1 +# Optional TLS listener (comment kept) +# tls_bind_host: 10.0.0.5 +tls_bind_host: 10.9.9.9 +tls_bind_port: 9443 +""" + + +def test_tls_enable_edits_only_the_tls_keys( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + cfg = tmp_path / "config.yml" + cfg.write_text(CONFIG) + cfg.chmod(0o600) + monkeypatch.setenv("LMNSQUID_CONFIG", str(cfg)) + result = CliRunner().invoke( + cli.app, ["tls", "enable", "--bind-host", "10.0.0.5", "--allow", "10.0.0.1"] + ) + assert result.exit_code == 0, result.output + text = cfg.read_text() + assert "# tls_bind_host: 10.0.0.5" in text and "comment kept" in text + data = yaml.safe_load(text) + assert (data["api_token"], data["tls_bind_host"], data["tls_bind_port"]) == ( + "t0ken", + "10.0.0.5", + 8443, + ) + assert data["tls_allowed_clients"] == ["10.0.0.1/32"] + assert stat.S_IMODE(cfg.stat().st_mode) == 0o600 + settings = load_settings(str(cfg)) + assert settings.tls_bind_host == "10.0.0.5" and settings.tls_allowed_clients == ["10.0.0.1/32"] + # idempotent + CliRunner().invoke(cli.app, ["tls", "enable", "--bind-host", "10.0.0.5", "--allow", "10.0.0.1"]) + assert cfg.read_text() == text + + +@pytest.mark.parametrize("bad", [["--bind-host", "0.0.0.0"], ["--bind-host", "proxy.lan"]]) +def test_tls_enable_refuses( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, bad: list[str] +) -> None: + cfg = tmp_path / "config.yml" + cfg.write_text(CONFIG) + monkeypatch.setenv("LMNSQUID_CONFIG", str(cfg)) + result = CliRunner().invoke(cli.app, ["tls", "enable", *bad]) + assert result.exit_code == 1 + assert cfg.read_text() == CONFIG diff --git a/controlplane/tests/test_tls.py b/controlplane/tests/test_tls.py new file mode 100644 index 0000000..483bdd1 --- /dev/null +++ b/controlplane/tests/test_tls.py @@ -0,0 +1,348 @@ +# 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 +@pytest.mark.parametrize("cause", ["address not on this host", "port taken"]) +async def test_tls_bind_failure_keeps_the_loopback_api( + tmp_path: Path, app: Any, token: str, cause: str +) -> None: + """M1: a TLS listener that cannot bind is an ERROR and a field in /v1/health; the plain + listener (CLI, package scripts) keeps running instead of the whole service restarting.""" + plain_port, tls_port = free_port(), free_port() + blocker = None + host = "127.0.0.1" + if cause == "port taken": + blocker = socket.socket() + blocker.bind(("127.0.0.1", tls_port)) + blocker.listen() + else: + host = "192.0.2.77" # TEST-NET-1: not an address of this machine + s = tls_settings( + tmp_path, api_token=token, bind_port=plain_port, tls_bind_port=tls_port, + tls_bind_host=host, + ) # fmt: skip + servers = main.build_servers(s, app, check_tls_settings(s)) + task = asyncio.create_task(main.serve_all(servers, app)) + try: + for _ in range(100): + if servers[0].started: + break + await asyncio.sleep(0.05) + assert servers[0].started and not servers[1].started + status, body, _ = await asyncio.to_thread( + _get, f"http://127.0.0.1:{plain_port}/v1/health", None, None + ) + assert status == 200 and body["status"] == "ok" and body["tls"].startswith("failed: ") + status, _, _ = await asyncio.to_thread( + _get, f"http://127.0.0.1:{plain_port}/v1/instances", None, token + ) + assert status == 200 + assert not task.done() + finally: + servers[0].should_exit = True + await asyncio.wait_for(task, 10) + if blocker is not None: + blocker.close() + + +@needs_openssl +async def test_health_reports_a_working_tls_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) + servers = main.build_servers(s, app, check_tls_settings(s)) + task = asyncio.create_task(main.serve_all(servers, app)) + try: + for _ in range(100): + if all(srv.started for srv in servers): + break + await asyncio.sleep(0.05) + status, body, _ = await asyncio.to_thread( + _get, f"http://127.0.0.1:{plain_port}/v1/health", None, None + ) + assert (status, body) == (200, {"status": "ok", "tls": "ok"}) + 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/changelog b/debian/changelog index b89f8b4..d91644d 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,3 +1,103 @@ +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). + * An instance whose keytab is missing in /etc/linuxmuster-squid/secrets + (or is a directory, empty or a symlink) no longer gets a container: + create, edit, update and start answer 409 with the reason, the + definition is kept and "lmnsquid status" shows "problem": "keytab". + Before, Docker created an empty directory with the keytab's name and + the container failed as "not healthy"; remove such a directory, put the + keytab there and run "lmnsquid start ". + * "lmnsquid start" and "restart" of an instance without a container now + create it from its definition (health-gated) instead of doing nothing. + * WebUI plugin: "Add proxy server → Set up a new VM (SSH)" turns a fresh + Ubuntu 24.04 VM into a connected proxy server. It first checks on the + school server (read only) that the proxy is in devices.csv with a role + without computer account and was imported; then it asks you to confirm + the VM's SSH host key, installs docker.io and linuxmuster-squid of this + release (shipped in the plugin package), turns the TLS listener on for + the school server only, creates the connection and the keytab. The + password is used once and not stored. A "Keytab" button creates and + sends the keytab of an existing host and restarts its instances. The + plugin package now contains the linuxmuster-squid .deb (about 16 MB). + * New write-only API endpoint PUT /v1/secrets/ for keytabs (0600, + replaced atomically, never readable; GET only says whether it exists), + used by the WebUI plugin to deliver keytabs. "lmnsquid tls enable + --bind-host --allow " turns the TLS listener on in + config.yml without hand editing. + * WebUI plugin, keytab button: for an existing service account it now + sets a new random password before the export (new key version), so a + leaked copy of the old keytab gets no tickets any more. The new keytab + keeps the previous key until issued tickets expire; tick "invalidate + the previous key at once" after a compromise. Instances are restarted + one after another and count only when healthy. An existing account + squid- is used only if the plugin created it and it is not + privileged. Removing a connection can disable the account in AD + (optional); accounts and SPNs are never deleted automatically. A new + key re-enables a disabled account (samba-tool does that); the job says + so. + Before anything changes in AD the button checks that the host name is + the proxy of the chosen connection (A record on its address, PTR, + inside the domain, no computer account or foreign SPN) and that the + proxy answers and can receive keytabs (control plane 7.3.11 or newer; + an older one is reported as "zu alt"). The transfer is retried; if it + still fails, the job says that the key was changed and the button must + be pressed again. The service account gets AES only + (msDS-SupportedEncryptionTypes 24): before, its service tickets were + RC4. provision-keytab.sh --rotate/--rotate-keep-previous do the same. + * WebUI plugin, setup of a new VM: waits for cloud-init and finishes an + interrupted dpkg run first, retries apt-get update while apt is busy, + keeps an existing Docker (docker-ce or docker.io) instead of replacing + it, runs the package steps as systemd units on the VM so a dropped SSH + session never leaves dpkg half done, keeps changed config files, keeps + the host name against cloud-init, checks that the address is on the + VM, and says why the TLS listener did not start. Release candidates + (7.3.N~rcM) no longer fail the version check. A newer linuxmuster-squid + on the VM stops the setup before apt (no downgrade). Starting the setup + again after any failure is safe; temporary files on the VM, also those + of earlier killed runs, are removed after every run. + * WebUI plugin, jobs: setup and keytab jobs run outside the WebUI's + service (systemd-run), so restarting or upgrading the WebUI no longer + kills them; a job whose process died is shown as failed instead of + running forever; one job per proxy host at a time, and a page reloaded + during a job finds it again ("Show progress"). + * WebUI plugin, security: requests that change something must come from + the plugin's own page (JSON content type, same origin), since the + WebUI core has no CSRF protection. Changing the address or the + certificate fingerprint of a connection needs the token again. + * WebUI plugin: a damaged connection file gives a German message with + file and line instead of an error page; one invalid entry no longer + blocks the others and can be removed from the page. The file now + carries a format version. Editing a connection no longer clears its + proxy host name (FQDN); the form has a field for it. + * WebUI plugin: long dialogs (instance details with block lists, the + instance form, the setup wizard, ...) can be scrolled again: the + dialog fits the window, its buttons stay visible and only its content + scrolls. The package depends on samba-common-bin and + ldb-tools (samba-tool, ldbsearch; present on every linuxmuster server) + and warns when the WebUI does not come back after its restart. + * Control plane: a TLS listener that cannot start (address gone, port + taken) no longer stops the service; the loopback API keeps running and + "lmnsquid health" shows "tls": "failed: ". PUT /v1/secrets + enforces its 64 KiB limit while reading the body. + + -- 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..301e076 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,17 @@ 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), + samba-common-bin, + ldb-tools +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.install b/debian/linuxmuster-squid-webui.install new file mode 100644 index 0000000..cdc949b --- /dev/null +++ b/debian/linuxmuster-squid-webui.install @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# +# The keytab logic the plugin runs on the DC (ADR-020); the plugin files themselves are +# assembled by webui/build_plugin.py (debian/rules), the bundled control-plane .deb by +# execute_before_dh_builddeb-indep. +scripts/provision-keytab.sh usr/share/linuxmuster-squid-webui/ diff --git a/debian/linuxmuster-squid-webui.postinst b/debian/linuxmuster-squid-webui.postinst new file mode 100644 index 0000000..2e465fd --- /dev/null +++ b/debian/linuxmuster-squid-webui.postinst @@ -0,0 +1,76 @@ +#!/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 + # Rewrites the permissions of every user whose list changes: on a large school this + # takes a few minutes (webui7's own updates run the same command). + echo "linuxmuster-squid-webui: updating the WebUI permissions (sophomorix-ui)..." + 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. + was_active=no + systemctl is-active -q linuxmuster-webui.service && was_active=yes + deb-systemd-invoke try-restart linuxmuster-webui.service || echo "WARNING:" \ + "linuxmuster-squid-webui: restart linuxmuster-webui to load the plugin" >&2 + if [ "$was_active" = yes ]; then + up=no + for _ in 1 2 3 4 5 6 7 8 9 10; do + if systemctl is-active -q linuxmuster-webui.service; then up=yes; break; fi + sleep 1 + done + if [ "$up" = no ]; then + echo "WARNING: linuxmuster-squid-webui: linuxmuster-webui did not come back after" \ + "the restart. See 'journalctl -u linuxmuster-webui -n 50'; to get the WebUI" \ + "back without the plugin: apt-get remove linuxmuster-squid-webui" >&2 + fi + fi + 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 + # Builds before the fix created /run/lmn_squid world-writable (0777): anything in it + # may have been planted by a local user. Drop it unless it is a private root directory; + # the tmpfiles.d entry (debhelper snippet below) creates it again 0700 root. + if [ -L /run/lmn_squid ] || { [ -e /run/lmn_squid ] && \ + [ "$(stat -c '%u %a %F' /run/lmn_squid)" != "0 700 directory" ]; }; then + rm -rf /run/lmn_squid + 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..7dbe425 --- /dev/null +++ b/debian/linuxmuster-squid-webui.postrm @@ -0,0 +1,33 @@ +#!/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 + # job states and logs (tmpfs, root only) + rm -rf /run/lmn_squid + ;; + purge) + # The connection list with the control planes' tokens. The service accounts + # squid- and their SPNs in AD stay: remove them with samba-tool (docs/install.md). + rm -rf /etc/linuxmuster-squid-webui /run/lmn_squid + ;; +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/linuxmuster-squid-webui.tmpfiles b/debian/linuxmuster-squid-webui.tmpfiles new file mode 100644 index 0000000..06550f3 --- /dev/null +++ b/debian/linuxmuster-squid-webui.tmpfiles @@ -0,0 +1,5 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# +# Runtime directory of the plugin's jobs and keytab exports: root only. +d /run/lmn_squid 0700 root root - 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 85% rename from debian/postinst rename to debian/linuxmuster-squid.postinst index 08077ce..d90b52c 100644 --- a/debian/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 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 diff --git a/debian/rules b/debian/rules index fff552f..3c8e742 100755 --- a/debian/rules +++ b/debian/rules @@ -12,6 +12,10 @@ 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 +WEBUI_SHARE := $(CURDIR)/debian/$(PKG)-webui/usr/share/$(PKG)-webui +BUNDLED := $(PKG)_$(DEB_VERSION)_amd64.deb # 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 +32,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 +59,16 @@ 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)" + +# The setup of a new proxy host from the WebUI (ADR-021) installs exactly this build's control +# plane: its .deb, made from the finished arch tree of this same run, goes into the plugin +# package with its sha256, so it works without any download (the lab has no release). +execute_before_dh_builddeb-indep: + @test -f "$(ROOT)/DEBIAN/control" || { echo "linuxmuster-squid-webui needs linuxmuster-squid from the same run (build both)" >&2; exit 1; } + mkdir -p "$(WEBUI_SHARE)" + dpkg-deb --root-owner-group --build "$(ROOT)" "$(WEBUI_SHARE)/$(BUNDLED)" + cd "$(WEBUI_SHARE)" && sha256sum "$(BUNDLED)" > "$(BUNDLED).sha256" + chmod 0644 "$(WEBUI_SHARE)/$(BUNDLED)" "$(WEBUI_SHARE)/$(BUNDLED).sha256" + dh_md5sums -p$(PKG)-webui diff --git a/docs/architecture.md b/docs/architecture.md index ae646ee..9b9cd5f 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,24 @@ 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. It can also **set up a new host** (ADR-021: read-only precheck on the DC, + SSH with a confirmed host key, fixed idempotent steps, the bundled `linuxmuster-squid` .deb of + the same build) and **deliver keytabs** (ADR-020: service account per host, export on the DC + into tmpfs, `PUT /v1/secrets` over the pinned connection). Long steps run as detached jobs + with a progress file. - **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..0a9b465 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -94,7 +94,8 @@ simplest DNS/keytab maintenance; each instance still enforces its group. firewall separation) — on demand. ### ADR-009 — Keytabs supplied by the AD admin (default) -**Status:** Accepted (default 2026-07-02; changeable at any time). **Decision:** the control plane consumes externally supplied +**Status:** Superseded for the WebUI path by ADR-020 (2026-11-23); the manual path stays as +described (default 2026-07-02). **Decision:** the control plane consumes externally supplied keytabs (secret mount). Auto-provisioning (`msktutil`/`samba-tool`) remains a **disabled** optional feature. **Why:** fewer privileges/attack surface, safer MVP. @@ -133,8 +134,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 +303,185 @@ 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. **Amendment (2026-11-24):** a TLS listener that passes these checks +but cannot start at run time (its address is no longer on the host after a renumbering, the +port is taken, the key does not load) no longer stops the service: the error goes to the +journal, `/v1/health` reports `"tls": "failed: "` (else `"ok"`), and the loopback +listener keeps the CLI and the package scripts working. **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/`). + +### ADR-020 — Keytab from the WebUI: made on the DC, sent write-only over the pinned connection +**Status:** Proposed (2026-11-23, Kevin: "Keytab per Knopf"). Supersedes ADR-009 for hosts +managed from the WebUI. **Decision:** the plugin (running as root on the school server, which +is the Samba AD DC) creates one service account per proxy host, `squid-` +(AD's 20-character sAMAccountName limit: longer names keep 9 characters plus 4 hex digits of a +hash of the FQDN; unique because the short host name is unique in the domain's DNS), with a +random password nobody knows (`samba-tool user create --random-password`) and no expiry +(`setexpiry --noexpiry`, KDC_ERR_KEY_EXP otherwise). The keytab is exported by the same +`provision-keytab.sh` the manual path uses (SPN conflict checks incl. the `host/` alias, +idempotent SPN add, fresh export), shipped in the plugin package and called with an argument +list (no shell), into a private directory on `/run` (tmpfs), read into memory and deleted. +It goes to the control plane with `PUT /v1/secrets/`: write-only (name checked like +`keytab_secret`, at most 64 KiB, `0600` as `lmnsquid`, atomic replace, audit log with name and +size only; `GET` answers only `exists` and `mtime`, there is no read path). It is written under +every keytab name the host's instances use (default `proxy.keytab`), and the instances of the +host are restarted **one after another**, each counted only when its status is healthy within +180 s (missing containers are created, see the start rule of 7.3.11); the job names every +instance that did not come back. **Rotation (2026-11-24):** an export alone changes nothing in +AD (same key, same KVNO; `keytab-and-dns.md`), so a leaked keytab could never be revoked. For an +account that exists already the button therefore sets a new random password first +(`samba-tool user setpassword --random-password`, KVNO + 1, `provision-keytab.sh +--rotate-keep-previous`): older keytabs get no tickets any more; the new keytab also carries the +previous key so service tickets clients already hold keep working until they expire. The +option "invalidate the previous key at once" (`--rotate`) leaves it out, for a suspected +compromise (clients with a ticket must log in again). **Account reuse:** an existing +`squid-` account is used only if its description is the plugin's marker and it is not +privileged (adminCount, membership in an admin/operator group); otherwise the job refuses, so +no foreign or privileged account's key ends up in a container. **Remove:** deleting a +connection can disable the account (optional, default off, again only the plugin's account); +accounts and SPNs are never deleted automatically and survive `apt-get purge` of the plugin. +`samba-tool user setpassword` enables a disabled account as a side effect (Samba's +`samdb.setpassword` calls `enable_account`, python3-samba 4.19): a keytab job or a re-setup on a +disabled plugin account therefore re-enables it and says so in its output ("war deaktiviert und +wurde wieder aktiviert"); the admin started it on purpose. **Before anything in AD changes +(2026-11-24, cold verification):** the FQDN must belong to the proxy of the chosen connection +(its A record points to the connection's address, and it equals the connection's stored FQDN if +there is one) and pass the setup's rules (inside the AD DNS domain, matching PTR, no computer +account, no foreign `HTTP/`/`host/` SPN), checked in the endpoint and again in the job; then the +control plane is asked over the pinned connection (version with the token, instances, `GET +/v1/secrets/`, which an older control plane without the secrets endpoint answers 404: +"Control Plane zu alt"). Only then the key is rotated; the PUT is retried three times, and a +transfer that still fails says that the key in AD changed, what that means for the instances +(issued tickets work until they expire, new logins get 407) and that the button must be pressed +again on this proxy's connection. A free write test of `secrets_dir` does not exist (the API +has no delete), so a full disk on the proxy is found only by the PUT itself. **AES only:** the +plugin sets `msDS-SupportedEncryptionTypes = 24` (AES128 + AES256) on a new account, +`provision-keytab.sh` does it in its rotate modes before the new password; without it the KDC +issued RC4 service tickets for the account (seen in the e2e Samba DC: `tkt: arcfour-hmac`). An +exported keytab without AES keys is not sent. **Why:** the key leaves the DC only over the TLS connection whose +certificate the admin pinned, never via a workstation, a shell history or an SSH copy; the +token holder could already replace the whole host, so a write-only secret path adds no power. +**Price:** the WebUI process creates AD accounts and SPNs; that is the global administrator's +right anyway (threat model T18, T20). + +### ADR-021 — Set up a new proxy host over SSH from the WebUI (paramiko, once) +**Status:** Proposed (2026-11-23, Kevin: both stages, paramiko, this PR). **Decision:** the +plugin turns a fresh Ubuntu 24.04 VM into a connected proxy host. **Precheck first (D0), +read-only:** the proxy's row in the school's `devices.csv` (path as sophomorix names it), its +role without a computer account (`COMPUTER_ACCOUNT` of `sophomorix.ini`), A/PTR records, no +computer account and no foreign `HTTP/`/`host/` SPN, the target is not the DC and not yet a +connection. `devices.csv` is never written by the plugin (Kevin): a failed check names the fix. +**Trust on first use with confirmation:** step 1 fetches the SSH host key and shows its +SHA256 fingerprint; step 2 runs only after the admin confirmed it (compared on the VM's +console), with that key as the only known host key and `RejectPolicy` (never +`AutoAddPolicy`), `allow_agent=False`, `look_for_keys=False`, timeouts; the key stays on the +server, the browser only confirms the fingerprint, and a confirmation is used once within 15 +minutes. **Credentials:** root or a sudo user with a password; the password reaches the job +process on stdin only and `sudo -S -k -p ''` reads it from the SSH channel; never in a +command line, a file, the environment, a log or an answer to the browser (aj does not log +request bodies, see "Logging" below; they pass gate → worker in memory). The job's progress file is scrubbed of +the passwords and the API token as a second line of defence. **Fixed steps** in the package, +every input checked against a pattern and passed through `shlex.quote`: preflight (Ubuntu +24.04, amd64, RAM ≥ 2 GB, disk ≥ 3 GB, clock), time from the DC (timesyncd or chrony), DNS on +the DC if the DC's name does not resolve, host name, `/etc/hosts` and the cloud-init template +(install.md), `docker.io`, the `linuxmuster-squid` .deb **bundled in the plugin package from the +same build** (no download; sha256 checked on the DC and on the target, version must equal the +plugin's), `lmnsquid tls enable` with the school server as the only client, the token and +certificate fingerprint read over the same SSH session, the connection created and tested, +the keytab (ADR-020). Every step is idempotent, so a failed setup is simply started again. +**No residual access:** no key is generated or copied, temp files are removed, `sudo -K` drops +a cached credential, the SSH session is closed; afterwards only the token and the pinned TLS +connection remain (as for a host connected by hand). **Jobs** run detached from the WebUI +worker, progress in `/run/lmn_squid/jobs/.json` (0600). **Hardening (2026-11-24):** the +runner is started with `systemd-run --pipe --collect` as the transient unit +`lmn-squid-job-` outside the WebUI's cgroup (fallback without systemd: a child in its own +session), so a WebUI restart or upgrade does not kill a setup; SIGTERM and an overall limit of +90 min end a job cleanly (running step failed with the reason); a job whose state says +`running` while its locks are free lost its process and is shown as failed ("abgebrochen"). +One flock per host key (address and FQDN), shared by setup and keytab jobs; the lock file names +the job, a refused start answers 409 with that job's id and the page shows its progress again +(`GET /jobs` after a reload). On the target a `settle` step waits for cloud-init and finishes an +interrupted dpkg run; `settle`, `docker` and `package` run as transient units +`lmn-squid-setup-` polled over SSH, so a dropped session never leaves dpkg half done and +a new run waits for a unit still working; `apt-get update` is retried while the lists lock is +held; dpkg keeps changed conffiles (`--force-confdef --force-confold`); a working Docker +(docker-ce or docker.io) is left alone and apt never removes packages (`--no-remove`); the .deb +is copied into a root-only directory and checked and installed from there; cloud-init keeps the +host name (`preserve_hostname`); the preflight refuses an address that is not on the target; +the `tls` step checks the listener itself and shows the journal on failure; a +`linuxmuster-squid` on the VM newer than the bundled one stops the `package` step before +apt with a German sentence (no downgrade); the status files of the detached steps are root-only +(0700/0600) and, like the staged .deb, removed after every job, successful or failed, unless a +step of it still works; a dropped SSH session is reported in German with "start again"; every SSH channel +has a read timeout, the transport a keepalive, SFTP a timeout; the script's stdin is +`/dev/null`, so a password sudo did not read cannot reach a command. The pre-release version of +the API (`7.3.11rc1`) is compared with the package's (`7.3.11~rc1`) by the rule of +`controlplane/setup.py`. **Browser requests:** aj has no CSRF protection (verified in aj 2.2.16 +on the lab server: no token, session cookie without SameSite, JSON parsed whatever the +Content-Type, no CORS headers), so every state-changing endpoint of the plugin requires +`Content-Type: application/json` and a same-origin `Origin`/`Referer` when the browser sends +one (aj's `trusted_domains` are accepted as well). **Logging (verified 2026-11-24, aj 2.2.16 on +the lab server):** aj logs per request only method, path, status and size, never the body, so +the passwords of `setup/start` do not reach a log. **Why paramiko:** already in the WebUI's Python (5.0.0), the password stays in +memory; Ansible would need ansible-core and sshpass on the DC and the password in a file or +the environment. **Price:** threat model T19 (password over the network, TOFU) and T20. + --- ## Site facts to be verified (P0, enter with source/date) diff --git a/docs/install.md b/docs/install.md index f60ab6e..1349409 100644 --- a/docs/install.md +++ b/docs/install.md @@ -17,6 +17,44 @@ UPPERCASE, `` = the proxy host's FQDN (`proxy.`), `` client network(s), `` = a school short name other than the default school (its groups are prefixed, e.g. `-internet`). All commands as root. +## 0. The WebUI way (fresh VM, optional) + +With `linuxmuster-squid-webui` on the school server (section 9a) a fresh Ubuntu 24.04 VM can be +set up from the WebUI: *Squid proxy → Add proxy server → Set up a new VM (SSH)* (ADR-021). + +1. Put the proxy into the school's `devices.csv` with the **role `iponly`** and run + `linuxmuster-import-devices` (the plugin checks this but never edits devices.csv). +2. In the wizard: school, FQDN, IP → *Run the precheck* (devices.csv row, role without + computer account, A/PTR, no computer account, no foreign SPN; every failure names the fix). +3. SSH user (root or a sudo user) and password → *Fetch the SSH host key* → compare the + SHA256 fingerprint with `ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub` on the VM's + console → tick → *Start the setup*. +4. The steps run in the background (wait for cloud-init and running package jobs, time and + DNS on the DC, `/etc/hosts`, Docker (an existing docker-ce or docker.io is kept), this + release's `linuxmuster-squid` from the plugin package, TLS listener for the school server + only, connection with pinned certificate, keytab). Then *New proxy instance*. + +The password is used once and never stored; no SSH key is left on the VM. The setup keeps +running when the browser tab is closed or the WebUI restarts; reopening *Squid proxy* shows a +running job with *Show progress*. A failed setup can simply be started again: every step is +idempotent, and the package steps wait for an apt/dpkg run of an earlier attempt that is still +working on the VM. The manual way below does the same by hand; for an existing host connected +by hand the *Keytab* button of the server creates and sends the keytab (ADR-020). + +**Keytab button = new key.** For an existing service account it sets a new random password +(the key version goes up): a copy of the old keytab, e.g. on a retired VM's disk, gets no +tickets any more. The instances of the host are restarted one after another, each until it is +healthy. By default the new keytab keeps the previous key as well, so clients do not lose SSO +until their tickets expire; tick *invalidate the previous key at once* after a compromise +(clients with a ticket then must log in again). The plugin only uses an account +`squid-` it created itself (description "linuxmuster-squid proxy service account") and +never a privileged one. Before it changes anything in AD it checks that the FQDN is the proxy of +this connection (A record on the connection's address, same as a stored FQDN, PTR, inside the +domain, no computer account or foreign SPN) and that the proxy answers with the token and knows +the keytab endpoint (control plane 7.3.11 or newer). The account is set to AES only +(`msDS-SupportedEncryptionTypes = 24`, no RC4 tickets; check with `klist -e`, +[`keytab-and-dns.md`](keytab-and-dns.md)). + ## 1. Prerequisites (proxy host) - Ubuntu 24.04 VM in the school network — **not** the linuxmuster server. 2 cores / 4 GB are @@ -214,6 +252,65 @@ 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`: it rewrites every user whose permission list changes, which can take a few +minutes on a large school; webui7's own updates do the same) and restarts the WebUI; if the +WebUI does not come back it prints a WARNING with the command to look at. **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. **AD objects stay:** the service accounts `squid-` and their SPNs that +the plugin created are not removed by removing a connection or the package (*Remove +connection* can disable the account, optionally). Delete them by hand when the host is gone: +`samba-tool user delete squid-` (removes the SPN with it). + +If the TLS listener cannot start (the address is no longer on the host, the port is taken), +the service keeps running on 127.0.0.1 for the CLI: `lmnsquid health` shows +`"tls": "failed: …"` and the journal says why; the WebUI cannot reach the host until it is +fixed. + ## 10. Updates ```bash @@ -235,6 +332,12 @@ Verify with `docker inspect -f '{{range .Mounts}}{{.Destination}} {{end}}' lmnsq `journalctl -t linuxmuster-squid` and print a `WARNING:` in the apt output naming any instance that could not be brought up; the apt transaction itself never fails over them. +**Downgrading the control plane** below 7.3.11 (the release with the TLS listener): older +versions do not know the `tls_*` keys in `/etc/linuxmuster-squid/config.yml` and do not start +with them. Remove the lines `tls_bind_host`, `tls_bind_port`, `tls_allowed_clients` (and +`tls_cert_file`/`tls_key_file` if set) before installing the older package; the WebUI then +cannot reach that host any more. The WebUI setup never downgrades (it stops with a message). + ## 11. Removing ```bash diff --git a/docs/keytab-and-dns.md b/docs/keytab-and-dns.md index 09eb400..414acc7 100644 --- a/docs/keytab-and-dns.md +++ b/docs/keytab-and-dns.md @@ -43,7 +43,10 @@ file; the control plane does **not** provision it itself (least privilege). - Store it as a **Docker secret**: file in `secrets_dir` (default `/etc/linuxmuster-squid/secrets`), filename == the instance's `keytab_secret`. The control plane mounts it **read-only** under `/run/secrets/` - (= `KEYTAB` in the container). + (= `KEYTAB` in the container). The file must exist before the instance starts: the + control plane refuses (409) a missing, empty, symlinked or directory keytab instead of + letting Docker create a directory in its place (bind mount as a `Mount`, which fails on a + missing source). - **Permissions:** `0600` on the host, mounted read-only. The container entrypoint (as root, with `DAC_OVERRIDE`) copies the keytab once to `/run/lmnsquid/keytab` (proxy-readable, `0600`), so that Squid, running as `proxy`, can read it — the @@ -54,6 +57,31 @@ file; the control plane does **not** provision it itself (least privilege). → `msktutil --auto-update` or re-export; re-export service-account keytabs on a password change. After rotation, recreate the instance (re-mount the secret) or `restart` it. +- **Rotation of the proxy's service account (revoking a keytab):** exporting again does + **not** revoke anything (same key, see below). `provision-keytab.sh + --rotate` sets a new random password first (`samba-tool user setpassword --random-password`, + KVNO + 1) and exports only the new key: every older copy of the keytab gets no tickets any + more, and clients holding a service ticket of the old KVNO fail until they get a new one + (log off/on or `klist purge`). `--rotate-keep-previous` exports the current key first and + appends the new one, so the keytab holds both KVNOs and tickets already issued keep working + until they expire (default ticket lifetime 10 h); the old key then still decrypts and could + forge tickets for this proxy until the next rotation, but cannot obtain tickets (no kinit). + The WebUI's *Keytab* button uses `--rotate-keep-previous` for an existing account and + `--rotate` when "invalidate at once" is ticked; a newly created account needs no rotation. + Verified on the e2e Samba DC (scripts/tests/provision_keytab_smoke.sh, case I) and in the lab. +- **AES only (`msDS-SupportedEncryptionTypes`):** a user account without this attribute gets + **RC4** service tickets from the Samba KDC (e2e DC: `klist -e` shows `Etype (skey, tkt): + aes256-cts-hmac-sha1-96, DEPRECATED:arcfour-hmac`). Both rotate modes of + `provision-keytab.sh` set it to `24` (AES128 0x08 + AES256 0x10) before the new password, the + WebUI plugin sets it on every account it creates. An account whose password predates AES keys + (very old domains) needs a new password after setting it, which the rotation does. Check: + ```bash + ldbsearch -H /var/lib/samba/private/sam.ldb '(sAMAccountName=squid-)' msDS-SupportedEncryptionTypes + klist -ke /etc/linuxmuster-squid/secrets/proxy.keytab # on the proxy: aes256-cts entries + kinit ; kvno HTTP/; klist -e # on a client: "tkt: aes256-cts-hmac-sha1-96" + ``` + For a hand-made account (`svc-squid`, section 3 of install.md) run the script with `--rotate` + once, or set the attribute by hand (`ldbmodify`) and reset the password. ## KVNO & SPN pitfalls (verified) diff --git a/docs/operations.md b/docs/operations.md index 41a67ac..9eed7ab 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -41,7 +41,17 @@ lmnsquid logs default-school-teachers --tail 100 lmnsquid rm default-school-teachers # + cache/log volumes, both lists, .prev; --keep-logs keeps the log volume ``` The keytab must already be present as secret `` in `secrets_dir` -(`/etc/linuxmuster-squid/secrets`) — see `keytab-and-dns.md`. +(`/etc/linuxmuster-squid/secrets`) — see `keytab-and-dns.md`. It is checked before any +container is made (a regular, non-empty file, no symlink, no directory): otherwise `create`, +`edit`, `update` and `start` answer **409** with `keytab secret '' missing in …`, no +container is created, and `create`/`edit` keep the definition — `lmnsquid status ` shows +`"problem": "keytab"`. Provision the keytab, then `lmnsquid start `. A group/world-readable +keytab only warns in the journal (`chmod 600`). (Up to 7.3.9 Docker created an empty +*directory* with the keytab's name on the host and the container failed as "not healthy"; +remove such a directory before provisioning the file.) +`start` and `restart` of an instance without a container (never created, its creation +failed, removed by hand) create it from the stored definition, health-gated, like `reconcile` +for that one instance (up to 7.3.9 they answered `exists: false` and did nothing). - **`--image` is optional:** it defaults to the maintained, digest-pinned data-plane image; pass `--image ghcr.io/…@sha256:` only to override a specific instance. @@ -364,6 +374,22 @@ 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. A switch at the top shows the page **by proxy +server** (one panel per server) or **by school** (one panel per school with its instances from +every server, plus a compact list of the servers with their own actions); the browser remembers +the choice. 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 +400,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..8cde901 100644 --- a/docs/test-strategy.md +++ b/docs/test-strategy.md @@ -22,6 +22,49 @@ 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. +- **Setup and keytab from the WebUI (`webui/tests/test_precheck.py`, `test_setup.py`, + `test_setup_views.py`, `controlplane/tests/test_secrets.py`):** every abort condition of the + read-only precheck (devices.csv row missing/double/mismatched, role with computer account or + unknown, no A/PTR, computer account, foreign HTTP/ or host/ SPN, target is the DC, already a + connection, bad input); the SSH setup against a fake paramiko and a real control plane on TLS + (RejectPolicy with the confirmed key, no agent/key files, password only on sudo's stdin and + never in a command or the job file, bundled .deb with sha256, keytab through + `PUT /v1/secrets`, wrong OS / wrong sudo password / rejected host key / bad payload stop + early); the job runner bootstraps without the WebUI; the endpoints refuse an unconfirmed or + different host key and a failed precheck; the secrets endpoint is write-only. The real + end-to-end run on a fresh VM is a lab test. +- **Hardening of setup, jobs and keytab (`webui/tests/test_jobs.py`, `test_remote.py`, + `test_csrf.py`, `test_connections.py`; `controlplane/tests/test_tls.py`, `test_secrets.py`):** + a runner killed with SIGKILL is reported as aborted, SIGTERM and the time limit end a job + cleanly, a runner that cannot start leaves a failed job, the systemd-run command line, one + lock per host shared by setup and keytab (the 409 names the running job), clean-up of + `.json`/`.log`/`.lock`; the remote scripts run for real under `/bin/sh` with stubbed apt, + dpkg, docker, systemctl, cloud-init (working Docker untouched, apt lists lock retried, + `--no-remove`, interrupted dpkg finished, TLS step shows the journal), detached steps (wait, + failure, lost unit, timeout), the sudo password cannot reach the script's stdin, missing exit + status and SFTP timeouts, pre-release version comparison, allowlist 403 apart from a bad + token; keytab rotation flags, foreign/privileged accounts refused, health-gated restarts one + by one, a keytab job does not undo a concurrent edit, disabling the account on remove; + cross-site requests (text/plain, foreign/`null` Origin, foreign Referer) refused on every + state-changing endpoint; a YAML error, one bad entry, the format version; the control plane + keeps its loopback API when the TLS listener cannot bind, and the secret size limit holds + while reading. `provision_keytab_smoke.sh` case I (rotation, KVNOs) needs the e2e Samba DC. - **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..8a73268 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -21,11 +21,11 @@ Risks + countermeasures. Grows per roadmap phase; the negative tests for it live | # | Risk | Countermeasure | Verification | |---|---|---|---| -| T1 | **Keytab theft** | Secret (tmpfs, `:ro`), `0600` host, readable only by `proxy`, isolated per instance, never in env/log; Compose file secrets not encrypted at rest → harden the host | perms test; no keytab in `docker inspect`/logs | +| T1 | **Keytab theft** | Secret (tmpfs, `:ro`), `0600` host, readable only by `proxy`, isolated per instance, never in env/log; Compose file secrets not encrypted at rest → harden the host; the control plane mounts only a regular, non-empty file from `secrets_dir` (no symlink, no directory; checked before any container is made, mounted as a `Mount` that fails on a missing source, so Docker never creates a host path) | perms test; no keytab in `docker inspect`/logs | | 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,9 @@ 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