From ebcd166186775a6f52a7e1e3992475118684b88e Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Thu, 19 Nov 2026 10:21:47 +0100 Subject: [PATCH 1/4] fix(api): answer an edit with an invalid value with 422, not 500 PATCH /v1/instances/{name} re-validates the merged instance, but the ValidationError of that step was not handled: an edit such as "lmnsquid edit --http-port 0" answered "500 Internal Server Error" without a reason. It is now a 422 in FastAPI's validation format, naming the field, like a bad POST body; nothing is changed, as before. --- controlplane/lmnsquid/api.py | 14 +++++++++++--- controlplane/tests/test_validation.py | 15 +++++++++++++++ debian/changelog | 8 ++++++++ 3 files changed, 34 insertions(+), 3 deletions(-) diff --git a/controlplane/lmnsquid/api.py b/controlplane/lmnsquid/api.py index 19b23a2..1abf79f 100644 --- a/controlplane/lmnsquid/api.py +++ b/controlplane/lmnsquid/api.py @@ -11,7 +11,9 @@ from docker.errors import DockerException from fastapi import Depends, FastAPI, HTTPException, Request, status +from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse +from pydantic import ValidationError from .blocklist import Blocklist, noauth_list from .config import Settings @@ -156,9 +158,15 @@ def patch_instance(name: str, patch: InstancePatch) -> dict[str, Any]: updates = patch.model_dump(exclude_unset=True) # Re-validate the merged instance through Instance validators; school/role # are not in InstancePatch, so the identity/name stays immutable. - merged = Instance.model_validate( - {**existing.model_dump(exclude={"name", "container_name"}), **updates} - ) + try: + merged = Instance.model_validate( + {**existing.model_dump(exclude={"name", "container_name"}), **updates} + ) + except ValidationError as exc: + # A 422 naming the field, like a bad POST body (it was a bare 500 before). + raise RequestValidationError( + exc.errors(include_url=False, include_context=False) + ) from exc result = _apply(merged) audit.info( "patch instance name=%s fields=%s", diff --git a/controlplane/tests/test_validation.py b/controlplane/tests/test_validation.py index 554c79d..86166e9 100644 --- a/controlplane/tests/test_validation.py +++ b/controlplane/tests/test_validation.py @@ -122,6 +122,21 @@ def test_patch_cannot_change_identity( assert resp.json()["instance"]["name"] == "default-school-teachers" +@pytest.mark.parametrize(("field", "bad"), [("http_port", 0), ("realm", "lower.case")]) +def test_patch_with_an_invalid_value_is_422( + client: Any, auth_headers: dict[str, str], instance_data: dict[str, Any], field: str, bad: Any +) -> None: + client.post("/v1/instances", json=instance_data, headers=auth_headers) + resp = client.patch( + "/v1/instances/default-school-teachers", json={field: bad}, headers=auth_headers + ) + # The merged instance fails validation: a 422 naming the field (it was a bare 500). + assert resp.status_code == 422 + assert resp.json()["detail"][0]["loc"] == [field] + shown = client.get("/v1/instances/default-school-teachers", headers=auth_headers).json() + assert shown[field] == instance_data[field] + + def test_dockerd_down_returns_503( client: Any, auth_headers: dict[str, str], diff --git a/debian/changelog b/debian/changelog index b3c356b..b6fd235 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,3 +1,11 @@ +linuxmuster-squid (7.3.9) lmn73; urgency=medium + + * "lmnsquid edit" with a value the instance does not accept now answers + 422 with the field and the reason instead of "500 Internal Server + Error"; nothing is changed, as before. + + -- Kevin Stenzel Thu, 19 Nov 2026 10:20:12 +0100 + linuxmuster-squid (7.3.8) lmn73; urgency=medium * New per-instance list of domains reachable without proxy login, for From fd8bdafd3e59a807267e27ea1b28e28c388da407 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Thu, 19 Nov 2026 10:21:56 +0100 Subject: [PATCH 2/4] feat: Kerberos clock skew per instance (krb5_clockskew_seconds) A school's Windows clients run 1 h ahead of the proxy after a LINBO sync until W32Time corrects them; their authenticators are then refused with "Clock skew too great" (MIT default 300 s) and users get login popups. Until the clients are fixed, an instance can now tolerate more (ADR-017): lmnsquid edit --krb5-clockskew-seconds 5400 (also on create) PATCH /v1/instances/{name} {"krb5_clockskew_seconds": 5400} krb5_clockskew_seconds: 5400 in the instance definition + reconcile 300-7200 s, default 300. The value is part of the instance definition, so update, update-all, rollback and reconcile keep it. The control plane passes it as KRB5_CLOCKSKEW_SECONDS, only when it differs from 300: the env of an instance at the default stays that of 7.3.8, so its spec fingerprint does not move and the upgrade replaces no container. The entrypoint validates it again (plain decimal 300-7200, else FATAL and exit 1 before anything is rendered; libkrb5 itself would silently fall back to 300 on a value it cannot parse) and writes "clockskew = n" into [libdefaults] of the krb5.conf it renders. MIT applies clockskew on the acceptor side (krb5_check_clockskew on the authenticator time, krb5int_validate_times on the ticket times); the replay cache keeps its entries for the same skew (docs/references.md). Per instance only: config.yml configures the control plane and has no instance defaults to inherit from. Docs: operations.md (how, when, trade-off), ADR-017, threat model T17, architecture, references, the instance field table. --- controlplane/lmnsquid/cli.py | 13 + controlplane/lmnsquid/docker_service.py | 9 +- controlplane/lmnsquid/models.py | 18 ++ controlplane/tests/conftest.py | 16 +- controlplane/tests/test_clockskew.py | 291 ++++++++++++++++++++++ controlplane/tests/test_docker_service.py | 3 + debian/changelog | 14 ++ deploy/instances/README.md | 1 + docs/architecture.md | 3 + docs/decisions.md | 30 +++ docs/operations.md | 57 +++++ docs/references.md | 27 ++ docs/threat-model.md | 3 +- image/entrypoint.sh | 17 +- 14 files changed, 485 insertions(+), 17 deletions(-) create mode 100644 controlplane/tests/test_clockskew.py diff --git a/controlplane/lmnsquid/cli.py b/controlplane/lmnsquid/cli.py index d8308d7..b3f4b38 100644 --- a/controlplane/lmnsquid/cli.py +++ b/controlplane/lmnsquid/cli.py @@ -89,6 +89,11 @@ def create( access_log_enabled: bool = typer.Option( True, help="log requests (privacy: --no-access-log-enabled)" ), + krb5_clockskew_seconds: int = typer.Option( + 300, + help="Kerberos clock skew the proxy accepts, 300-7200 s (krb5.conf clockskew); " + "raise only while client clocks are off, it widens the window for stolen tickets", + ), ) -> None: """Create (and reconcile) an instance.""" body: dict[str, Any] = { @@ -103,6 +108,7 @@ def create( "cache_size_mb": cache_size_mb, "log_retention_days": log_retention_days, "access_log_enabled": access_log_enabled, + "krb5_clockskew_seconds": krb5_clockskew_seconds, } if image is not None: body["image"] = image @@ -347,6 +353,11 @@ def edit( cache_size_mb: Optional[int] = typer.Option(None), log_retention_days: Optional[int] = typer.Option(None), access_log_enabled: Optional[bool] = typer.Option(None), + krb5_clockskew_seconds: Optional[int] = typer.Option( + None, + help="Kerberos clock skew the proxy accepts, 300-7200 s; 300 = the default " + "(replaces the container)", + ), ) -> None: """Change fields of an existing instance without rm+create (re-validated + reconciled). @@ -375,6 +386,8 @@ def edit( body["log_retention_days"] = log_retention_days if access_log_enabled is not None: body["access_log_enabled"] = access_log_enabled + if krb5_clockskew_seconds is not None: + body["krb5_clockskew_seconds"] = krb5_clockskew_seconds if not body: typer.secho( "nothing to change — pass at least one option", fg=typer.colors.YELLOW, err=True diff --git a/controlplane/lmnsquid/docker_service.py b/controlplane/lmnsquid/docker_service.py index 86cc0cc..c888175 100644 --- a/controlplane/lmnsquid/docker_service.py +++ b/controlplane/lmnsquid/docker_service.py @@ -17,7 +17,7 @@ from docker.types import LogConfig from .blocklist import CONTAINER_DIR, Blocklist, noauth_list -from .models import Instance +from .models import KRB5_CLOCKSKEW_DEFAULT, Instance logger = logging.getLogger("lmnsquid.docker") @@ -118,7 +118,7 @@ def _pull(self, image: str) -> None: def env_for(self, inst: Instance) -> dict[str, str]: """Build the environment variables consumed by entrypoint.sh.""" - return { + env = { "INSTANCE": inst.name, "VISIBLE_HOSTNAME": inst.visible_hostname, "REALM": inst.realm, @@ -131,6 +131,11 @@ def env_for(self, inst: Instance) -> dict[str, str]: "LOG_RETENTION_DAYS": str(inst.log_retention_days), "ACCESS_LOG_ENABLED": "1" if inst.access_log_enabled else "0", } + # Only when it differs from the default (the entrypoint's too): an unchanged env keeps + # the spec fingerprint, so instances at the default are not replaced on upgrade. + if inst.krb5_clockskew_seconds != KRB5_CLOCKSKEW_DEFAULT: + env["KRB5_CLOCKSKEW_SECONDS"] = str(inst.krb5_clockskew_seconds) + return env def spec_for(self, inst: Instance) -> dict[str, Any]: """Everything the container is created from (JSON-able), except its name. diff --git a/controlplane/lmnsquid/models.py b/controlplane/lmnsquid/models.py index 959598f..e9b4670 100644 --- a/controlplane/lmnsquid/models.py +++ b/controlplane/lmnsquid/models.py @@ -41,6 +41,12 @@ "@sha256:0f59a1d47b090de4c2e89b14b929751e5c422126a7d507fa6ac955d25a0b0fd7" ) +# Kerberos clock skew the proxy accepts (krb5.conf [libdefaults] clockskew, seconds; ADR-017). +# 300 is MIT's own default: an instance at it gets no KRB5_CLOCKSKEW_SECONDS in its env, so +# its container spec stays as before and an upgrade replaces no container for it. +KRB5_CLOCKSKEW_DEFAULT = 300 +KRB5_CLOCKSKEW_MAX = 7200 + def _normalize_cidr_list(value: str) -> str: """Split on commas/whitespace, validate each part as a CIDR, and return the @@ -72,6 +78,7 @@ class Instance(BaseModel): image: str = DEFAULT_IMAGE log_retention_days: int = 30 access_log_enabled: bool = True + krb5_clockskew_seconds: int = KRB5_CLOCKSKEW_DEFAULT @field_validator("school", "role") @classmethod @@ -152,6 +159,16 @@ def _v_retention(cls, v: int) -> int: raise ValueError("log_retention_days must be between 1 and 3650") return v + @field_validator("krb5_clockskew_seconds") + @classmethod + def _v_clockskew(cls, v: int) -> int: + if not KRB5_CLOCKSKEW_DEFAULT <= v <= KRB5_CLOCKSKEW_MAX: + raise ValueError( + f"krb5_clockskew_seconds must be between {KRB5_CLOCKSKEW_DEFAULT} " + f"and {KRB5_CLOCKSKEW_MAX}" + ) + return v + @computed_field # type: ignore[prop-decorator] @property def name(self) -> str: @@ -184,6 +201,7 @@ class InstancePatch(BaseModel): image: str | None = None log_retention_days: int | None = None access_log_enabled: bool | None = None + krb5_clockskew_seconds: int | None = None class UpdateRequest(BaseModel): diff --git a/controlplane/tests/conftest.py b/controlplane/tests/conftest.py index 9c37da8..6333320 100644 --- a/controlplane/tests/conftest.py +++ b/controlplane/tests/conftest.py @@ -17,6 +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.models import Instance from lmnsquid.reconciler import Reconciler from lmnsquid.store import Store @@ -51,19 +52,8 @@ def __init__( self.reloaded: list[str] = [] def env_for(self, inst: Instance) -> dict[str, str]: - return { - "INSTANCE": inst.name, - "VISIBLE_HOSTNAME": inst.visible_hostname, - "REALM": inst.realm, - "AD_GROUP": inst.ad_group, - "INTERNET_GROUP": inst.internet_group or "", - "SCHOOL_SUBNETS": inst.school_subnets, - "KEYTAB": f"/run/secrets/{inst.keytab_secret}", - "CACHE_SIZE_MB": str(inst.cache_size_mb), - "HTTP_PORT": str(inst.http_port), - "LOG_RETENTION_DAYS": str(inst.log_retention_days), - "ACCESS_LOG_ENABLED": "1" if inst.access_log_enabled else "0", - } + # 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]: self.ensure_calls.append(inst.name) diff --git a/controlplane/tests/test_clockskew.py b/controlplane/tests/test_clockskew.py new file mode 100644 index 0000000..7b370eb --- /dev/null +++ b/controlplane/tests/test_clockskew.py @@ -0,0 +1,291 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""Kerberos clock skew per instance (ADR-017): validation, env, persistence, entrypoint.""" + +from __future__ import annotations + +import shutil +import subprocess +from pathlib import Path +from typing import Any + +import pytest +import yaml +from pydantic import ValidationError +from starlette.testclient import TestClient +from typer.testing import CliRunner + +from lmnsquid import cli +from lmnsquid.docker_service import DockerService +from lmnsquid.models import Instance, InstancePatch +from lmnsquid.reconciler import Reconciler +from lmnsquid.store import Store +from lmnsquid.updater import Updater + +ENTRYPOINT = Path(__file__).resolve().parents[2] / "image" / "entrypoint.sh" +NAME = "default-school-teachers" +# What env_for gave every instance before the setting existed (7.3.8): an instance at the +# default must get exactly this, or its spec fingerprint moves and an upgrade replaces it. +ENV_KEYS_738 = { + "INSTANCE", + "VISIBLE_HOSTNAME", + "REALM", + "AD_GROUP", + "INTERNET_GROUP", + "SCHOOL_SUBNETS", + "KEYTAB", + "CACHE_SIZE_MB", + "HTTP_PORT", + "LOG_RETENTION_DAYS", + "ACCESS_LOG_ENABLED", +} + + +def _env(inst: Instance) -> dict[str, str]: + return DockerService.env_for(DockerService.__new__(DockerService), inst) + + +# ------------------------------------------------------------------ model / validation +@pytest.mark.parametrize("bad", [299, 7201, 0, -300, "abc", "", 5400.5, None]) +def test_rejects_out_of_range_and_non_numbers(instance_data: dict[str, Any], bad: Any) -> None: + with pytest.raises(ValidationError): + Instance(**instance_data, krb5_clockskew_seconds=bad) + + +@pytest.mark.parametrize("good", [300, 5400, 7200]) +def test_accepts_the_range(instance_data: dict[str, Any], good: int) -> None: + assert Instance(**instance_data, krb5_clockskew_seconds=good).krb5_clockskew_seconds == good + + +def test_default_is_mit_default_and_patchable(instance_data: dict[str, Any]) -> None: + assert Instance(**instance_data).krb5_clockskew_seconds == 300 + assert InstancePatch(krb5_clockskew_seconds=5400).model_dump(exclude_unset=True) == { + "krb5_clockskew_seconds": 5400 + } + + +# ------------------------------------------------------------------ env / container spec +def test_env_at_default_is_unchanged(instance_data: dict[str, Any]) -> None: + for inst in ( + Instance(**instance_data), + Instance(**instance_data, krb5_clockskew_seconds=300), + ): + assert set(_env(inst)) == ENV_KEYS_738 + + +def test_env_carries_a_raised_value(instance_data: dict[str, Any]) -> None: + env = _env(Instance(**instance_data, krb5_clockskew_seconds=5400)) + assert env["KRB5_CLOCKSKEW_SECONDS"] == "5400" + assert set(env) == ENV_KEYS_738 | {"KRB5_CLOCKSKEW_SECONDS"} + + +# ------------------------------------------------------------------ API: set, keep, refuse +def test_patch_sets_persists_and_reaches_the_container( + client: TestClient, + auth_headers: dict[str, str], + instance_data: dict[str, Any], + store: Store, + docker: Any, +) -> None: + assert client.post("/v1/instances", json=instance_data, headers=auth_headers).status_code == 201 + assert "KRB5_CLOCKSKEW_SECONDS" not in docker.containers[NAME]["env"] + + r = client.patch( + f"/v1/instances/{NAME}", json={"krb5_clockskew_seconds": 5400}, headers=auth_headers + ) + assert r.status_code == 200, r.text + assert r.json()["instance"]["krb5_clockskew_seconds"] == 5400 + assert docker.containers[NAME]["env"]["KRB5_CLOCKSKEW_SECONDS"] == "5400" + # persisted in the instance definition (YAML), read back by a fresh store + raw = yaml.safe_load((Path(store.path) / f"{NAME}.yaml").read_text(encoding="utf-8")) + assert raw["krb5_clockskew_seconds"] == 5400 + assert Store(str(store.path)).get(NAME).krb5_clockskew_seconds == 5400 # type: ignore[union-attr] + + # back to the default: the env loses the variable again + r = client.patch( + f"/v1/instances/{NAME}", json={"krb5_clockskew_seconds": 300}, headers=auth_headers + ) + assert r.status_code == 200, r.text + assert "KRB5_CLOCKSKEW_SECONDS" not in docker.containers[NAME]["env"] + + +@pytest.mark.parametrize("bad", [299, 7201, "abc", None]) +def test_patch_refuses_invalid_and_changes_nothing( + client: TestClient, + auth_headers: dict[str, str], + instance_data: dict[str, Any], + store: Store, + docker: Any, + bad: Any, +) -> None: + client.post( + "/v1/instances", + json={**instance_data, "krb5_clockskew_seconds": 5400}, + headers=auth_headers, + ) + calls = len(docker.ensure_calls) + r = client.patch( + f"/v1/instances/{NAME}", json={"krb5_clockskew_seconds": bad}, headers=auth_headers + ) + assert r.status_code == 422 # a clear error, not a 500 + assert "krb5_clockskew_seconds" in r.text + assert store.get(NAME).krb5_clockskew_seconds == 5400 # type: ignore[union-attr] + assert len(docker.ensure_calls) == calls # no container touched + + +def test_create_refuses_invalid( + client: TestClient, auth_headers: dict[str, str], instance_data: dict[str, Any] +) -> None: + r = client.post( + "/v1/instances", + json={**instance_data, "krb5_clockskew_seconds": 7201}, + headers=auth_headers, + ) + assert r.status_code == 422 + assert "krb5_clockskew_seconds" in r.text + + +def test_kept_by_update_update_all_rollback_and_reconcile( + store: Store, + docker: Any, + reconciler: Reconciler, + updater: Updater, + instance_data: dict[str, Any], +) -> None: + reconciler.apply(Instance(**instance_data, krb5_clockskew_seconds=5400)) + + def kept() -> None: + assert store.get(NAME).krb5_clockskew_seconds == 5400 # type: ignore[union-attr] + assert docker.containers[NAME]["env"]["KRB5_CLOCKSKEW_SECONDS"] == "5400" + + assert updater.update(NAME, "ghcr.io/example/lmnsquid:v2")["updated"] is True + kept() + assert updater.update(NAME, "ghcr.io/example/lmnsquid:bad")["updated"] is False # rolled back + kept() + updater.rollback(NAME) + kept() + assert updater.update_all("ghcr.io/example/lmnsquid:v3")[0]["updated"] is True + kept() + docker.containers.clear() # a fresh host: reconcile recreates from the store + reconciler.reconcile_all() + kept() + + +def test_definition_from_before_loads_with_the_default( + store: Store, instance_data: dict[str, Any] +) -> None: + # A YAML written by 7.3.8 has no such key. + (Path(store.path) / f"{NAME}.yaml").write_text(yaml.safe_dump(instance_data), encoding="utf-8") + assert store.get(NAME).krb5_clockskew_seconds == 300 # type: ignore[union-attr] + + +def test_hand_edited_definition_is_picked_up_by_reconcile_and_update( + store: Store, docker: Any, reconciler: Reconciler, updater: Updater, instance: Instance +) -> None: + reconciler.apply(instance) + assert "KRB5_CLOCKSKEW_SECONDS" not in docker.containers[NAME]["env"] + path = Path(store.path) / f"{NAME}.yaml" + + def hand_edit(value: object) -> None: + data = yaml.safe_load(path.read_text(encoding="utf-8")) + data["krb5_clockskew_seconds"] = value + path.write_text(yaml.safe_dump(data), encoding="utf-8") + + hand_edit(5400) + reconciler.reconcile_all() + assert docker.containers[NAME]["env"]["KRB5_CLOCKSKEW_SECONDS"] == "5400" + + hand_edit(7200) + updater.update(NAME, "ghcr.io/example/lmnsquid:v2") + assert docker.containers[NAME]["env"]["KRB5_CLOCKSKEW_SECONDS"] == "7200" + + +def test_invalid_hand_edit_leaves_the_running_container_alone( + store: Store, docker: Any, reconciler: Reconciler, instance_data: dict[str, Any], caplog: Any +) -> None: + reconciler.apply(Instance(**instance_data, krb5_clockskew_seconds=5400)) + path = Path(store.path) / f"{NAME}.yaml" + data = yaml.safe_load(path.read_text(encoding="utf-8")) + data["krb5_clockskew_seconds"] = 9000 + path.write_text(yaml.safe_dump(data), encoding="utf-8") + calls = len(docker.ensure_calls) + + reconciler.reconcile_all() + + assert len(docker.ensure_calls) == calls # skipped, not applied with a bad value + assert docker.containers[NAME]["env"]["KRB5_CLOCKSKEW_SECONDS"] == "5400" + assert f"invalid instance record in {NAME}.yaml" in caplog.text + + +# ------------------------------------------------------------------ CLI +def test_cli_create_and_edit( + monkeypatch: pytest.MonkeyPatch, app: Any, token: str, instance_data: dict[str, Any] +) -> None: + def factory() -> TestClient: + tc = TestClient(app) + tc.headers.update({"Authorization": f"Bearer {token}"}) + return tc + + monkeypatch.setattr(cli, "_get_client", factory) + runner = CliRunner() + args = ["create"] + for key in ("school", "role", "ad_group", "realm", "visible_hostname", "keytab_secret"): + args += [f"--{key.replace('_', '-')}", instance_data[key]] + r = runner.invoke(cli.app, [*args, "--krb5-clockskew-seconds", "5400"]) + assert r.exit_code == 0, r.output + assert '"krb5_clockskew_seconds": 5400' in runner.invoke(cli.app, ["show", NAME]).output + + r = runner.invoke(cli.app, ["edit", NAME, "--krb5-clockskew-seconds", "7200"]) + assert r.exit_code == 0, r.output + assert '"krb5_clockskew_seconds": 7200' in runner.invoke(cli.app, ["show", NAME]).output + + r = runner.invoke(cli.app, ["edit", NAME, "--krb5-clockskew-seconds", "299"]) + assert r.exit_code == 1 + assert '"krb5_clockskew_seconds": 7200' in runner.invoke(cli.app, ["show", NAME]).output + + +# ------------------------------------------------------------------ entrypoint +def _entrypoint(tmp_path: Path, value: str) -> subprocess.CompletedProcess[str]: + """Run image/entrypoint.sh until its first side effect. + + ``mkdir`` (the first command after the checks) is a stub that exits 97, so the script + never touches the host: 97 = the value passed the check, 1 + FATAL = refused. + """ + stubs = tmp_path / "stubs" + stubs.mkdir(exist_ok=True) + (stubs / "mkdir").write_text("#!/bin/sh\nexit 97\n", encoding="utf-8") + (stubs / "mkdir").chmod(0o755) + env = { + "PATH": f"{stubs}:/usr/bin:/bin", + "VISIBLE_HOSTNAME": "proxy.example.lan", + "REALM": "EXAMPLE.LAN", + "AD_GROUP": "teachers", + "KRB5_CLOCKSKEW_SECONDS": value, + } + return subprocess.run( + ["sh", str(ENTRYPOINT)], env=env, capture_output=True, text=True, timeout=30 + ) + + +@pytest.mark.skipif(not shutil.which("sh"), reason="needs sh") +@pytest.mark.parametrize("bad", ["299", "7201", "abc", "0300", "-300", "300 ", "5400s", "99999"]) +def test_entrypoint_refuses_invalid(tmp_path: Path, bad: str) -> None: + done = _entrypoint(tmp_path, bad) + assert done.returncode == 1, done.stderr + assert "FATAL: KRB5_CLOCKSKEW_SECONDS=" in done.stderr + + +@pytest.mark.skipif(not shutil.which("sh"), reason="needs sh") +@pytest.mark.parametrize("good", ["300", "5400", "7200", ""]) +def test_entrypoint_accepts_the_range(tmp_path: Path, good: str) -> None: + done = _entrypoint(tmp_path, good) + assert done.returncode == 97, done.stderr + assert "FATAL" not in done.stderr + + +def test_entrypoint_writes_the_value_into_krb5_conf() -> None: + # The heredoc that renders krb5.conf (the full render is asserted in the E2E). + text = ENTRYPOINT.read_text(encoding="utf-8") + block = text.split('cat > "${KRB5_CONFIG}" < None: assert base != ds.fingerprint(ds.spec_for(_inst(image="ghcr.io/x/y:2"))) assert base != ds.fingerprint(ds.spec_for(_inst(http_port=3129))) assert base != ds.fingerprint(ds.spec_for(_inst(keytab_secret="other.keytab"))) + # The clock skew at its default adds nothing to the spec (no container replaced on upgrade). + assert base == ds.fingerprint(ds.spec_for(_inst(krb5_clockskew_seconds=300))) + assert base != ds.fingerprint(ds.spec_for(_inst(krb5_clockskew_seconds=5400))) spec = ds.spec_for(_inst()) blocklist_dir = str(tmp_path / "blocklists" / "s-teachers") assert spec["volumes"][blocklist_dir]["bind"] == "/etc/squid/lists" diff --git a/debian/changelog b/debian/changelog index b6fd235..17d7578 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,5 +1,19 @@ linuxmuster-squid (7.3.9) lmn73; urgency=medium + * New per-instance setting for the Kerberos clock skew the proxy accepts, + for clients whose clock is off after they got their tickets (login + popups with "Clock skew too great" in the container log): + "lmnsquid edit --krb5-clockskew-seconds 5400" (also on create, + in the API as krb5_clockskew_seconds, or by hand in + /var/lib/linuxmuster-squid/instances/.yaml followed by + "lmnsquid reconcile"). 300 to 7200 seconds, default 300 (the Kerberos + default, so nothing changes until you set it; instances at the default + are not restarted by the upgrade). The value goes to the container as + KRB5_CLOCKSKEW_SECONDS and into its krb5.conf as "clockskew"; an + invalid value is refused by the API and by the container. A higher + value lets a captured login token be accepted for longer: use it as a + stopgap and fix the client clocks (docs/operations.md). Needs a + data-plane image that knows the setting; an older one ignores it. * "lmnsquid edit" with a value the instance does not accept now answers 422 with the field and the reason instead of "500 Internal Server Error"; nothing is changed, as before. diff --git a/deploy/instances/README.md b/deploy/instances/README.md index 81aef0d..48ff157 100644 --- a/deploy/instances/README.md +++ b/deploy/instances/README.md @@ -24,6 +24,7 @@ reconciles the actual against the desired state. File name convention: | `keytab_secret` | Name of the mounted keytab secret. | | `cache_size_mb` | Cache size. | | `image` | **Digest-pinned** image (`…@sha256:…`, P5). | +| `krb5_clockskew_seconds` | Kerberos clock skew the proxy accepts, 300–7200 s (default 300; env `KRB5_CLOCKSKEW_SECONDS`, `krb5.conf` `clockskew`). ADR-017, [operations.md](../../docs/operations.md#kerberos-clock-skew-per-instance). | **Verified (P3, crabbox E2E):** two instances with different `ad_group` (default `teachers` vs. `schule2-teachers`) isolate cleanly — the teacher of one diff --git a/docs/architecture.md b/docs/architecture.md index 59baf59..ae646ee 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -93,6 +93,9 @@ Status document. Keep it up to date with every substantive change (see `noauth reload` refuses (409) when the running container does not read the list (an image from before ADR-016). Price: no identity for these requests (exam mode, Internetsperre; threat model T16). +- **Kerberos clock skew per instance (ADR-017):** `KRB5_CLOCKSKEW_SECONDS` (300–7200, default + 300) → `clockskew` in the rendered `krb5.conf`; validated in the API model and again in the + entrypoint (`FATAL` before anything is rendered). - **Hardening:** `cache_effective_user proxy`; Keytab as a secret (tmpfs, readable by `proxy`); `KRB5CCNAME=FILE:` (the kernel-keyring ccache fails when unprivileged); `read_only` rootfs + tmpfs; `cap_drop: ALL` (+ minimal SETUID/SETGID/DAC_OVERRIDE); diff --git a/docs/decisions.md b/docs/decisions.md index 5d9e72b..e80ed07 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -268,6 +268,36 @@ changes nothing (it checks the rendered `squid.conf` in the container). An image template next to a directory without `noauth.domains` (an older control plane) uses an empty list until the file appears and the next reload reads it. +### ADR-017 — Kerberos clock skew per instance +**Status:** Proposed (2026-11-19, Kevin's request: a school whose Windows clients run 1 h ahead +after a LINBO sync until W32Time corrects them; the proxy is to tolerate 90 min until the +clients are fixed). **Decision:** each instance carries `krb5_clockskew_seconds` (default 300, +MIT's own; range 300–7200), set with `lmnsquid create|edit --krb5-clockskew-seconds`, the API +or by hand in the instance definition, and kept by `update`, `update-all`, `rollback` and +`reconcile` like every other field. The control plane passes it as `KRB5_CLOCKSKEW_SECONDS`; +the entrypoint validates it again (plain decimal 300–7200, else `FATAL`, exit 1) and writes +`clockskew = ` into the `[libdefaults]` of the `krb5.conf` it renders. **Names:** the +field and the CLI option follow the existing unit-suffixed fields (`cache_size_mb`, +`log_retention_days`) and MIT's own relation name (`clockskew`), `krb5_` says which +configuration it lands in; the env var is the field in upper case like the others +(libkrb5 reads no variable of that name). **Per instance, no global default in +`config.yml`:** that file configures the control plane (token, paths, Docker), it has no +instance defaults; an inherited default would need an "unset" state in the model and a +resolution step for one setting. **Validation twice:** libkrb5 reads the relation with +`profile_get_integer` and ignores a parse error (`init_ctx.c`), so an invalid value would +silently become 300; the entrypoint check covers containers started without the control +plane. **Default stays out of the env:** at 300 the container env is the one of 7.3.8, so the +spec fingerprint does not move and the upgrade replaces no container for it. +**Why:** MIT applies `clockskew` on the acceptor side — the authenticator time +(`krb5_check_clockskew` from `rd_req_decoded_opt`) and the ticket's start/end time +(`krb5int_validate_times`) — so it is the one knob for "Clock skew too great" from +`negotiate_kerberos_auth` (`gss_accept_sec_context`). Fixing the clients is the root-cause fix +and happens separately; this bridges the time until then. +**Price (threat model T17):** a captured authenticator stays usable for the whole window where +the replay cache (in the container's tmpfs, entries kept for the same skew) does not see it. +**Rollout:** the entrypoint change is in the data-plane image; until `DEFAULT_IMAGE` points at +an image built with it, the setting has no effect on instances running the pinned image. + --- ## Site facts to be verified (P0, enter with source/date) diff --git a/docs/operations.md b/docs/operations.md index 4434687..199fbf5 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -59,6 +59,63 @@ The keytab must already be present as secret `` in `secrets_dir` the log volume, e.g. for a retention obligation; delete it later with `docker volume rm lmnsquid-logs-`. The keytab in `secrets/` stays (operator-managed). +## Kerberos clock skew (per instance) + +The proxy accepts a Kerberos authenticator only if the client's clock is within the +**clock skew** of its own (MIT `krb5.conf` `[libdefaults] clockskew`, default **300 s**). +A client whose clock is further off gets a login popup (407) until it logs off; the container +log shows `gss_accept_sec_context() failed ... Clock skew too great`. The setting applies to +the proxy (the acceptor) only; the KDC keeps its own limit, so a client that is off by more +than that cannot get new tickets anyway — the raised value helps clients whose clock jumped +**after** they got their tickets (e.g. a Windows image that boots with the wrong time zone and +corrects itself minutes later). + +Per instance, in seconds, **300–7200** (default 300 = the old behaviour): + +| Where | Name | +|---|---| +| instance definition (`/var/lib/linuxmuster-squid/instances/.yaml`) | `krb5_clockskew_seconds` | +| CLI | `lmnsquid create` / `lmnsquid edit ` with `--krb5-clockskew-seconds ` | +| API | `krb5_clockskew_seconds` in `POST /v1/instances` and `PATCH /v1/instances/{name}` | +| container env (read by the entrypoint) | `KRB5_CLOCKSKEW_SECONDS` | + +Example, 90 minutes on a running instance (replaces its container, health-gated): + +``` +lmnsquid edit default-school-teachers --krb5-clockskew-seconds 5400 +docker exec lmnsquid-default-school-teachers grep clockskew /run/lmnsquid/krb5.conf +# clockskew = 5400 +lmnsquid edit default-school-teachers --krb5-clockskew-seconds 300 # back to the default +``` + +Or by hand in the definition, then apply it with `lmnsquid reconcile` (or `lmnsquid update +`; `update-all` leaves instances alone that already run the pinned image): + +``` +# /var/lib/linuxmuster-squid/instances/default-school-teachers.yaml +krb5_clockskew_seconds: 5400 +``` + +The value stays in the definition across `update`, `update-all`, `rollback` and `reconcile`. +A value outside 300–7200 or not a whole number is refused: the API/CLI answer 422 and change +nothing; a hand-edited definition with such a value is skipped by `reconcile`/`update-all` +(`invalid instance record in .yaml` in `journalctl -u linuxmuster-squid`) and the running +container stays as it was; a container started with such a `KRB5_CLOCKSKEW_SECONDS` stops +with `FATAL` before it renders its config. At 300 the container gets no +`KRB5_CLOCKSKEW_SECONDS` at all, so instances that never set it are not replaced by the +upgrade that brings the setting. The setting needs a data-plane image that knows it; an older +image ignores it (its `krb5.conf` has no `clockskew` line, and its startup line in the container +log lacks `krb5_clockskew=`). + +**When:** only as a stopgap while client clocks are known to be off, and back to 300 once they +are fixed — the clocks are the root cause (Windows: `RealTimeIsUniversal`, W32Time against the +DC). **Price:** a captured authenticator (proxy authentication travels in clear HTTP on the +LAN) stays acceptable for the whole window instead of 5 minutes. The replay cache still +refuses the same authenticator twice at the same instance — MIT keeps its entries for the same +clock skew — but it lives in the container's tmpfs: after a container restart, or at another +instance that accepts the same key, a captured token could be replayed within the window +(threat model T17). + ## Blocklist (per instance) Each instance has its own domain list, `/etc/linuxmuster-squid/blocklists//blocked.domains` diff --git a/docs/references.md b/docs/references.md index 23ad187..44ebb3c 100644 --- a/docs/references.md +++ b/docs/references.md @@ -145,3 +145,30 @@ research workflows on **2026-07-02** (confidence in parentheses). template), `localhost` appends a `127.0.1.1` entry every boot, `false` (default) leaves the file alone. Ubuntu 24.04 (cloud-init 26.2) uses `/etc/cloud/templates/hosts.debian.tmpl` with `127.0.1.1 {{fqdn}} {{hostname}}`. (high) — https://docs.cloud-init.io/en/latest/reference/modules.html + +## Kerberos clock skew (ADR-017, checked 2026-11-19) + +- `krb5.conf` `[libdefaults] clockskew`: "maximum allowable amount of clockskew in seconds that + the library will tolerate before assuming that a Kerberos message is invalid. The default + value is 300 seconds". (high) — https://web.mit.edu/kerberos/krb5-latest/doc/admin/conf_files/krb5_conf.html +- It applies to the acceptor: `rd_req_decoded_opt()` calls `krb5_check_clockskew(context, + authenticator ctime)` (→ `KRB5KRB_AP_ERR_SKEW`, "Clock skew too great" when outside + `context->clockskew`); `krb5int_validate_times()` allows `starttime - clockskew` and + `endtime + clockskew` for the ticket. (high, MIT source) — + https://github.com/krb5/krb5/blob/master/src/lib/krb5/krb/rd_req_dec.c · + https://github.com/krb5/krb5/blob/master/src/lib/krb5/os/timeofday.c · + https://github.com/krb5/krb5/blob/master/src/lib/krb5/krb/valid_times.c +- Parsing: `init_ctx.c` reads it with `get_integer(ctx, KRB5_CONF_CLOCKSKEW, + DEFAULT_CLOCKSKEW /* 300 */, …)` and does not check the result; `profile_get_integer` parses + base 10 and fails on trailing garbage, so a malformed value leaves the default. (high, MIT + source) — https://github.com/krb5/krb5/blob/master/src/lib/krb5/krb/init_ctx.c · + https://github.com/krb5/krb5/blob/master/src/util/profile/prof_get.c +- Replay cache: entries count as live until `timestamp + context->clockskew` (`rc_file2.c` + `expired()`), so a larger skew keeps them longer; directory from `KRB5RCACHEDIR`. (high) — + https://github.com/krb5/krb5/blob/master/src/lib/krb5/rcache/rc_file2.c · + https://web.mit.edu/kerberos/krb5-latest/doc/basic/rcache_def.html +- `negotiate_kerberos_auth` keeps the replay cache on by default (`-t` type, default `dfl`; + `none` disables it) and does not mention clock skew. (high) — + https://www.squid-cache.org/Versions/v6/manuals/negotiate_kerberos_auth.html +- libfaketime (Ubuntu 24.04 `faketime` 0.9.10) shifts the client clock in the E2E + (`faketime -f '+60m' curl …`). (measured) diff --git a/docs/threat-model.md b/docs/threat-model.md index 78a34dd..420f2bb 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -27,7 +27,7 @@ Risks + countermeasures. Grows per roadmap phase; the negative tests for it live | 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 | | 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; AES enctypes | E2E canonicalization; `klist -k` | +| 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) | | T9 | **Unattended bad update → dead school** | digest pin, human-merge (no automerge; bumps by hand while Renovate is disabled), health-gated update + auto-rollback, known-good persisted | E2E: bad image → rollback | | T10 | **DC/LDAP outage stalls every request** | external ACL `ttl/negative_ttl/grace` + tune helper concurrency | load test P10 | @@ -37,6 +37,7 @@ Risks + countermeasures. Grows per roadmap phase; the negative tests for it live | T14 | **SNI filter bypass: ECH / QUIC / DoH** | **ECH** (Encrypted Client Hello) encrypts the SNI → splice filter blind; **QUIC/HTTP3** runs over **UDP 443**, bypassing the TCP forward proxy; **DoH** circumvents the DNS view. Limit of name-based filtering — the proxy alone does not close this. **Mitigate at the network edge:** OPNsense **block UDP 443** (forces TCP/443 through the proxy), block known DoH resolvers + `use-application-dns.net` (canary disables Firefox DoH); observe ECH adoption. For real completeness you would need SSL interception (a deliberate non-goal, ADR-002). | firewall review at the site; documented limit | | 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