diff --git a/README.md b/README.md index ac1a0df..51a2e45 100644 --- a/README.md +++ b/README.md @@ -145,7 +145,6 @@ Implemented and tested in Phase 1: - Matrix positive rows run against a feature-enabled test binary, not the release binary - Live run of the K8s pod on a cluster is not in CI: the validator checks the manifest only - The signature check on the runtime proof is not a constant-time comparison. The design note explains why; revisit if the proof path changes. -- The manifest validator does not catch the runtime proof seed being exposed through env or secretKeyRef. Add a check. - The 503 error code on the hello path is `unavailable` in the code and `broker_unavailable` elsewhere in the design. Align them. - The final checks summary lists one test target with 0 passed; the workspace total (289) appears only in the report. @@ -244,6 +243,45 @@ flowchart TB - **Names come from `deploy/k8s/pod.yaml`:** container, volume and port names match that file. Image references are placeholders until a release pins digests. +### Runtime container hardening + +The runtime container holds the Ed25519 proof seed, so its surface is the smallest in the pod +(issue #24). The settings below are in `deploy/k8s/pod.yaml`. `deploy/k8s/validate_manifests.py` +fails on each rule, and each rule has a bad-manifest test. Evidence: +[docs/evidence/runtime-hardening.md](docs/evidence/runtime-hardening.md). + +| Setting | Value | Why it is safe | +|---|---|---| +| Seccomp | pod-level `RuntimeDefault`, inherited by every init and app container; no container overrides it | The shim started, said `hello`, registered and revoked a session under it, with no denial. A custom profile is not needed, and a `Localhost` profile would need a file on every node. | +| Root filesystem | `readOnlyRootFilesystem: true` | The shim writes only `runtime.sock`. No `/tmp` and no other path. Measured: `touch` fails on `/`, on the seed directory and on `session-plane`. | +| Writable mounts | `agent-runtime` only | `session-plane` is mounted `readOnly: true`: connecting to `session.sock` needs write permission on the socket file, not on its directory. Measured: `hello`, register and renew work with the read-only mount. | +| Privileges | `allowPrivilegeEscalation: false`, `capabilities.drop: [ALL]`, no `add`, not privileged | `CapEff` and `CapBnd` are all zero, `NoNewPrivs` is 1. | +| User | UID and GID 1002, `runAsNonRoot: true` | Fixed, distinct from the agent (1000), the proxy (1001) and egress (1003). | +| Seed file | Secret volume, `defaultMode` 0444, owned by root, mounted read-only into `runtime` only | The kubelet writes Secret files as root, and the validator forbids `fsGroup`, so 0444 is the only mode UID 1002 can read. The agent cannot read it because it does not mount the volume and shares no process namespace. Measured: the file is absent in the agent container. Not a mode protection: any process in the runtime container can read the seed. | +| Env, ports | none | The seed is never in an env var. | +| PID namespace | `shareProcessNamespace: false` | Other containers cannot reach the runtime's `/proc//root`. | +| Service account | `automountServiceAccountToken: false` | A compromised runtime has no API token. | +| Termination | `terminationGracePeriodSeconds: 10` | The binaries run as PID 1 without a SIGTERM handler, so deletion takes about the full grace period (10.8 s measured, 30 s by default). | +| AppArmor | not set in the manifest | A node without AppArmor refuses a pod that names a profile. containerd applies its default profile (`cri-containerd.apparmor.d`, enforce) on a node that has AppArmor, with or without a field. To pin it, add `appArmorProfile: {type: RuntimeDefault}` to the container. The validator accepts `RuntimeDefault` or `Localhost` and refuses `Unconfined`. | + +Validator rules added for this (names as printed): `every-container-has-an-enforcing-seccomp-profile`, +`apparmor-profile-if-set-is-not-unconfined`, `every-container-drops-all-and-is-read-only-root` +(no capability beyond `CHOWN` and `FSETID` for `volume-prep` and `NET_ADMIN` for `netinit` and +`netcheck`; no privileged, no hostPort, no non-default procMount), +`only-volume-prep-netinit-netcheck-run-as-root`, `non-root-containers-have-a-fixed-uid-and-gid`, +`runtime-only-writable-mount-is-the-agent-socket-dir`, `runtime-has-no-env-port-or-envfrom`, +`runtime-seed-flag-is-the-secret-item`, `runtime-key-not-in-any-other-container-list` (init and +ephemeral containers included), `runtime-key-not-referenced-by-env`, +`termination-grace-period-is-short` (1 to 15 s) and +`no-service-account-token-and-no-service-links`. The existing seed rules still apply: mode 0444, +one Secret volume, mounted only into `runtime`, read-only, no `fsGroup`. + +**Residual risk.** A compromised runtime container can still sign `hello` and session calls with +the seed for as long as that container runs, and it can read the seed. Hardening limits what the attacker can do from there: no +network (netinit gives UID 1002 no route), no writable filesystem, no capability, no API token, no +view of the other containers. It does not stop forged proofs from inside the container. Threshold +shares and per-start derived seeds are out of scope. + ### Credential Secret at-rest requirements The real credential lives in the Secret `auth-proxy-kiro`. The file the proxy reads is not a plain @@ -354,7 +392,10 @@ verified against a cluster. Minimum principal: grant none of `pods/exec`, `pods/attach`, `pods/ephemeralcontainers` and `nodes/proxy` in `auth-proxy` (or on its node, for `nodes/proxy`) to anyone, apart from a named break-glass administrator, and treat each like `get` on `auth-proxy-kiro`. - **[untested]** + The seed has the same run-time exposure: a principal that can create a `pods/ephemeralcontainers` + entry with `targetContainerName: runtime` (or run `kubectl debug --target=runtime`) can read it + through the shared process namespace, so treat that verb like `get` on `auth-proxy-runtime-key` + too. **[untested]** - Backups and snapshots: etcd snapshots, Velero-style namespace backups and node disk snapshots must be encrypted, or must exclude `auth-proxy-kiro`. This is repo policy and no cited page states it. **[untested]** @@ -370,6 +411,13 @@ verified against a cluster. - [ ] `python3 deploy/k8s/validate_manifests.py` passes (credential mount, volume type, mode, read-only and env rules). +- [ ] The same run passes the runtime-hardening rules listed under "Runtime container hardening": + seccomp on every container, read-only root filesystems, no capability beyond the three + allowed, fixed UID and GID, the runtime's only writable mount is `agent-runtime`, the seed + mounted only into `runtime`, a short grace period. +- [ ] On the target node, `kubectl exec` into the agent container shows `CapEff` zero, `Seccomp: 2` + and a read-only root, and the seed path does not exist there. If the node has AppArmor, + `/proc//attr/current` of the runtime shows an enforcing profile. - [ ] Etcd encryption at rest is on for `secrets` in the target cluster with a provider that is not `identity` and not `aescbc` (`secretbox` or `kms` v2), `k3s secrets-encrypt status` shows `Enabled`, and `auth-proxy-kiro` was written or rewritten after it was enabled and diff --git a/deploy/k8s/pod.yaml b/deploy/k8s/pod.yaml index 4aa2efd..218c3e0 100644 --- a/deploy/k8s/pod.yaml +++ b/deploy/k8s/pod.yaml @@ -58,6 +58,19 @@ spec: automountServiceAccountToken: false enableServiceLinks: false shareProcessNamespace: false + # Short on purpose: the proxy and the runtime hold no state that needs a long drain (the expiry + # store is on its own volume), and a compromised runtime should not outlive its pod by the default + # 30 s. See "Runtime container hardening" in the README. + terminationGracePeriodSeconds: 10 + # Seccomp: the pod-level profile applies to every init and app container, and no container + # overrides it (the validator fails on an override or on Unconfined). RuntimeDefault is enough for + # the runtime shim (measured on a k3s node, see the README). AppArmor is not set here, because a node without AppArmor refuses a pod that names + # a profile. To opt in on a node that has it, add to each container's securityContext (or to this + # pod-level one): + # appArmorProfile: + # type: RuntimeDefault + # The validator accepts RuntimeDefault or Localhost and refuses Unconfined, here or as a + # container.apparmor.security.beta.kubernetes.io/* annotation. securityContext: seccompProfile: type: RuntimeDefault @@ -133,6 +146,7 @@ spec: fi securityContext: runAsUser: 1001 + runAsGroup: 1001 runAsNonRoot: true allowPrivilegeEscalation: false readOnlyRootFilesystem: true @@ -256,6 +270,9 @@ spec: readOnly: true # The runtime: the hello proof and the only client of session.sock. It serves runtime.sock to the # agent. It runs only ap-runtime-shim and has no network (netinit gives UID 1002 no route out). + # Its only writable path is agent-runtime, where it creates runtime.sock. Its root filesystem is + # read-only, session-plane is mounted read-only (connecting to session.sock needs no write access + # to the directory), and the proof seed is read-only. It has no env, no port and no capability. - name: runtime image: REPLACE_RUNTIME_IMAGE command: @@ -279,6 +296,7 @@ spec: volumeMounts: - name: session-plane mountPath: /run/auth-proxy-session + readOnly: true - name: agent-runtime mountPath: /run/auth-proxy-agent # The proof seed. Only this container mounts the Secret, read-only. @@ -413,7 +431,10 @@ spec: - key: api_key path: api_key # The hello proof seed (base64 of 32 bytes). Only the runtime mounts it. Mode 0444, as for - # kiro-secret. The validator fails if any other container or init container mounts it. + # kiro-secret: the kubelet writes the file as root, and with no fsGroup (the validator forbids + # one) 0444 is the only mode UID 1002 can read. The agent UID cannot read it because the agent + # container does not mount the volume and shares no process namespace, not because of the mode. + # The validator fails if any other container, init container or ephemeral container mounts it. - name: runtime-key secret: secretName: auth-proxy-runtime-key diff --git a/deploy/k8s/test_validate_manifests.py b/deploy/k8s/test_validate_manifests.py index 6fa3e65..e8f0013 100644 --- a/deploy/k8s/test_validate_manifests.py +++ b/deploy/k8s/test_validate_manifests.py @@ -314,6 +314,19 @@ def mutate(pod): copy.edit_pod(mutate) self.assert_fails(copy, "runtime-key-mode-0444") + def test_runtime_key_through_a_projected_volume_in_the_agent_is_refused(self): + copy = Copy(self) + + def mutate(pod): + pod["spec"]["volumes"].append({"name": "pj", "projected": {"sources": [ + {"secret": {"name": "auth-proxy-runtime-key"}}]}}) + copy.container(pod, "agent")["volumeMounts"].append( + {"name": "pj", "mountPath": "/k", "readOnly": True}) + + copy.edit_pod(mutate) + self.assert_fails(copy, "runtime-key-volume-is-secret-type") + self.assert_fails(copy, "runtime-key-not-in-any-other-container-list") + def test_hostpath_volume_is_refused(self): copy = Copy(self) @@ -649,6 +662,145 @@ def mutate(pod): copy.edit_pod(mutate) self.assert_fails(copy, "containers-agent-proxy-runtime-egress") + # ---- Runtime container hardening (issue #24): one minimal bad manifest per rule ---- + + def init_container(self, pod, name): + return next(c for c in pod["spec"]["initContainers"] if c["name"] == name) + + def test_pod_seccomp_unconfined_is_refused(self): + copy = Copy(self) + copy.edit_pod(lambda pod: pod["spec"]["securityContext"].__setitem__( + "seccompProfile", {"type": "Unconfined"})) + self.assert_fails(copy, "every-container-has-an-enforcing-seccomp-profile") + + def test_missing_pod_seccomp_is_refused(self): + copy = Copy(self) + copy.edit_pod(lambda pod: pod["spec"]["securityContext"].pop("seccompProfile")) + self.assert_fails(copy, "every-container-has-an-enforcing-seccomp-profile") + + def test_runtime_container_seccomp_unconfined_is_refused(self): + copy = Copy(self) + copy.edit_pod(lambda pod: copy.container(pod, "runtime")["securityContext"].__setitem__( + "seccompProfile", {"type": "Unconfined"})) + self.assert_fails(copy, "every-container-has-an-enforcing-seccomp-profile") + + def test_localhost_seccomp_without_a_profile_name_is_refused(self): + copy = Copy(self) + copy.edit_pod(lambda pod: pod["spec"]["securityContext"].__setitem__( + "seccompProfile", {"type": "Localhost"})) + self.assert_fails(copy, "every-container-has-an-enforcing-seccomp-profile") + + def test_apparmor_runtime_default_on_the_runtime_is_accepted(self): + copy = Copy(self) + copy.edit_pod(lambda pod: copy.container(pod, "runtime")["securityContext"].__setitem__( + "appArmorProfile", {"type": "RuntimeDefault"})) + code, out = run_validator(copy.root) + self.assertEqual(code, 0, out) + + def test_apparmor_unconfined_field_is_refused(self): + copy = Copy(self) + copy.edit_pod(lambda pod: copy.container(pod, "runtime")["securityContext"].__setitem__( + "appArmorProfile", {"type": "Unconfined"})) + self.assert_fails(copy, "apparmor-profile-if-set-is-not-unconfined") + + def test_apparmor_unconfined_annotation_is_refused(self): + copy = Copy(self) + copy.edit_pod(lambda pod: pod["metadata"].setdefault("annotations", {}).__setitem__( + "container.apparmor.security.beta.kubernetes.io/runtime", "unconfined")) + self.assert_fails(copy, "apparmor-profile-if-set-is-not-unconfined") + + def test_init_container_with_a_writable_root_is_refused(self): + copy = Copy(self) + copy.edit_pod(lambda pod: self.init_container(pod, "expiry-store-bootstrap")[ + "securityContext"].__setitem__("readOnlyRootFilesystem", False)) + self.assert_fails(copy, "every-container-drops-all-and-is-read-only-root") + + def test_privileged_egress_is_refused(self): + copy = Copy(self) + copy.edit_pod(lambda pod: copy.container(pod, "egress")["securityContext"].__setitem__( + "privileged", True)) + self.assert_fails(copy, "every-container-drops-all-and-is-read-only-root") + + def test_extra_capability_on_the_runtime_is_refused(self): + copy = Copy(self) + copy.edit_pod(lambda pod: copy.container(pod, "runtime")["securityContext"][ + "capabilities"].__setitem__("add", ["NET_BIND_SERVICE"])) + self.assert_fails(copy, "every-container-drops-all-and-is-read-only-root") + + def test_extra_capability_on_volume_prep_is_refused(self): + copy = Copy(self) + copy.edit_pod(lambda pod: self.init_container(pod, "volume-prep")["securityContext"][ + "capabilities"].__setitem__("add", ["CHOWN", "FSETID", "DAC_OVERRIDE"])) + self.assert_fails(copy, "every-container-drops-all-and-is-read-only-root") + + def test_bootstrap_running_as_root_is_refused(self): + copy = Copy(self) + copy.edit_pod(lambda pod: self.init_container(pod, "expiry-store-bootstrap")[ + "securityContext"].__setitem__("runAsUser", 0)) + self.assert_fails(copy, "only-volume-prep-netinit-netcheck-run-as-root") + + def test_bootstrap_without_a_group_is_refused(self): + copy = Copy(self) + copy.edit_pod(lambda pod: self.init_container(pod, "expiry-store-bootstrap")[ + "securityContext"].pop("runAsGroup")) + self.assert_fails(copy, "non-root-containers-have-a-fixed-uid-and-gid") + + def test_runtime_with_a_writable_session_plane_is_refused(self): + copy = Copy(self) + + def mutate(pod): + for m in copy.container(pod, "runtime")["volumeMounts"]: + if m["name"] == "session-plane": + m.pop("readOnly") + + copy.edit_pod(mutate) + self.assert_fails(copy, "runtime-only-writable-mount-is-the-agent-socket-dir") + + def test_runtime_with_an_env_var_is_refused(self): + copy = Copy(self) + copy.edit_pod(lambda pod: copy.container(pod, "runtime").__setitem__( + "env", [{"name": "X", "value": "1"}])) + self.assert_fails(copy, "runtime-has-no-env-port-or-envfrom") + + def test_seed_flag_naming_another_file_is_refused(self): + copy = Copy(self) + + def mutate(pod): + cmd = copy.container(pod, "runtime")["command"] + cmd[cmd.index("--seed-file") + 1] = "/var/run/auth-proxy-runtime/other.seed" + + copy.edit_pod(mutate) + self.assert_fails(copy, "runtime-seed-flag-is-the-secret-item") + + def test_ephemeral_container_mounting_the_seed_is_refused(self): + copy = Copy(self) + copy.edit_pod(lambda pod: pod["spec"].__setitem__("ephemeralContainers", [{ + "name": "dbg", "image": "x", + "volumeMounts": [{"name": "runtime-key", "mountPath": "/k", "readOnly": True}]}])) + self.assert_fails(copy, "runtime-key-not-in-any-other-container-list") + + def test_seed_secret_as_env_is_refused(self): + copy = Copy(self) + copy.edit_pod(lambda pod: copy.container(pod, "egress").__setitem__("env", [{ + "name": "SEED", "valueFrom": {"secretKeyRef": { + "name": "auth-proxy-runtime-key", "key": "runtime_ed25519.seed"}}}])) + self.assert_fails(copy, "runtime-key-not-referenced-by-env") + + def test_missing_grace_period_is_refused(self): + copy = Copy(self) + copy.edit_pod(lambda pod: pod["spec"].pop("terminationGracePeriodSeconds")) + self.assert_fails(copy, "termination-grace-period-is-short") + + def test_long_grace_period_is_refused(self): + copy = Copy(self) + copy.edit_pod(lambda pod: pod["spec"].__setitem__("terminationGracePeriodSeconds", 300)) + self.assert_fails(copy, "termination-grace-period-is-short") + + def test_service_account_token_automount_is_refused(self): + copy = Copy(self) + copy.edit_pod(lambda pod: pod["spec"].__setitem__("automountServiceAccountToken", True)) + self.assert_fails(copy, "no-service-account-token-and-no-service-links") + if __name__ == "__main__": unittest.main() diff --git a/deploy/k8s/validate_manifests.py b/deploy/k8s/validate_manifests.py index 160e366..a0c1038 100755 --- a/deploy/k8s/validate_manifests.py +++ b/deploy/k8s/validate_manifests.py @@ -314,6 +314,19 @@ def mount_names(container_name): ] check("runtime-key-secret-volume-present", len(runtime_key_vols) == 1) rk_name = runtime_key_vols[0] if len(runtime_key_vols) == 1 else None + # Any volume that names the seed Secret anywhere must be a plain `secret` volume, as the + # credential rule requires (cred_named). A projected or other volume would otherwise carry the + # seed past the holder checks below, which only look at the one secret volume. + rk_named = sorted( + n for n, v in volumes.items() + if any(isinstance(x, str) and x == RUNTIME_KEY_SECRET for _, x in walk(v)) + ) + rk_not_secret = [n for n in rk_named if "secret" not in volumes[n]] + check( + "runtime-key-volume-is-secret-type", + not rk_not_secret, + "volumes %s name %s but are not secret volumes" % (rk_not_secret, RUNTIME_KEY_SECRET), + ) if rk_name: rk = volumes[rk_name]["secret"] check( @@ -331,8 +344,8 @@ def mount_names(container_name): ) holders = sorted( [c.get("name") for c in containers.values() - if rk_name in mount_names_of(c)] - + [c.get("name") for c in inits if rk_name in mount_names_of(c)] + if mount_names_of(c) & set(rk_named)] + + [c.get("name") for c in inits if mount_names_of(c) & set(rk_named)] ) if rk_name else [] check( "runtime-key-mounted-only-by-runtime", @@ -882,6 +895,162 @@ def mount_path_of(c, vol): % (runtime_est, runtime_rej, non_lo), ) + # ---- Runtime container hardening (issue #24) ---- + # These rules add to the ones above and relax none of them. Every rule here fails on a minimal + # bad manifest in test_validate_manifests.py. + pod_sc = spec.get("securityContext", {}) or {} + runtime = containers.get("runtime", {}) + + # Seccomp: every init, app and ephemeral container ends up with RuntimeDefault (or a node-local + # Localhost profile). Unconfined is refused at the pod and at each container. + def effective_seccomp(c): + return (c.get("securityContext", {}) or {}).get("seccompProfile") or pod_sc.get( + "seccompProfile" + ) or {} + + bad_seccomp = sorted( + "%s=%s" % (c.get("name"), effective_seccomp(c).get("type")) + for c in all_ctrs + if effective_seccomp(c).get("type") not in ("RuntimeDefault", "Localhost") + or ( + effective_seccomp(c).get("type") == "Localhost" + and not effective_seccomp(c).get("localhostProfile") + ) + ) + check( + "every-container-has-an-enforcing-seccomp-profile", + not bad_seccomp, + "containers without RuntimeDefault or Localhost: %s" % bad_seccomp, + ) + + # AppArmor is optional, because a node without it refuses a pod that names a profile. When a + # profile is named, in the field or in the annotation, it must not be Unconfined. + aa_bad = [] + for scope, sc_ in [("pod", pod_sc)] + [ + (c.get("name"), c.get("securityContext", {}) or {}) for c in all_ctrs + ]: + prof = sc_.get("appArmorProfile") + if prof is not None and ( + prof.get("type") not in ("RuntimeDefault", "Localhost") + or (prof.get("type") == "Localhost" and not prof.get("localhostProfile")) + ): + aa_bad.append("%s appArmorProfile %s" % (scope, prof.get("type"))) + for k, v in (pods[0].get("metadata", {}).get("annotations", {}) or {}).items(): + if k.startswith("container.apparmor.security.beta.kubernetes.io/") and not ( + v == "runtime/default" or str(v).startswith("localhost/") + ): + aa_bad.append("annotation %s=%s" % (k, v)) + check("apparmor-profile-if-set-is-not-unconfined", not aa_bad, "; ".join(aa_bad)) + + # Every container, init and ephemeral included: no capability beyond the one the design gives + # it, no escalation, a read-only root filesystem, nothing privileged. + CAP_ALLOWLIST = { + PREP_NAME: ["CHOWN", "FSETID"], + "netinit": ["NET_ADMIN"], + "netcheck": ["NET_ADMIN"], + } + hard_problems = [] + for c in all_ctrs: + s_ = c.get("securityContext", {}) or {} + n_ = c.get("name") + if (s_.get("capabilities", {}) or {}).get("drop") != ["ALL"]: + hard_problems.append("%s: capabilities.drop is not [ALL]" % n_) + if caps_added(c) != CAP_ALLOWLIST.get(n_, []): + hard_problems.append("%s: capabilities.add is %s" % (n_, caps_added(c))) + if s_.get("allowPrivilegeEscalation") is not False: + hard_problems.append("%s: allowPrivilegeEscalation is not false" % n_) + if s_.get("readOnlyRootFilesystem") is not True: + hard_problems.append("%s: readOnlyRootFilesystem is not true" % n_) + if s_.get("privileged"): + hard_problems.append("%s: privileged" % n_) + if s_.get("procMount") not in (None, "Default"): + hard_problems.append("%s: procMount %s" % (n_, s_.get("procMount"))) + if any(p_.get("hostPort") for p_ in c.get("ports", []) or []): + hard_problems.append("%s: hostPort" % n_) + check("every-container-drops-all-and-is-read-only-root", not hard_problems, "; ".join(hard_problems)) + + # Fixed UID and GID: only the three containers that need root run as root, and every other + # container sets a non-root UID and a GID of its own (no inherited GID 0). + ROOT_CONTAINERS = [PREP_NAME, "netinit", "netcheck"] + root_holders = sorted( + c.get("name") for c in all_ctrs if (c.get("securityContext", {}) or {}).get("runAsUser") == 0 + ) + check( + "only-volume-prep-netinit-netcheck-run-as-root", + root_holders == sorted(ROOT_CONTAINERS), + "root containers: %s" % root_holders, + ) + loose_ids = [] + for c in all_ctrs: + if c.get("name") in ROOT_CONTAINERS: + continue + s_ = c.get("securityContext", {}) or {} + uid_, gid_ = s_.get("runAsUser"), s_.get("runAsGroup") + if not (isinstance(uid_, int) and uid_ >= 1000 and s_.get("runAsNonRoot") is True): + loose_ids.append("%s: runAsUser %s runAsNonRoot %s" % (c.get("name"), uid_, s_.get("runAsNonRoot"))) + if not (isinstance(gid_, int) and gid_ >= 1000): + loose_ids.append("%s: runAsGroup %s" % (c.get("name"), gid_)) + check("non-root-containers-have-a-fixed-uid-and-gid", not loose_ids, "; ".join(loose_ids)) + + # The runtime holds the proof seed, so its surface is the smallest in the pod: the only writable + # mount is the agent socket directory, and it has no env, port or Secret-backed env. + rt_writable = sorted( + m.get("name") for m in runtime.get("volumeMounts", []) if not m.get("readOnly") + ) + check( + "runtime-only-writable-mount-is-the-agent-socket-dir", + rt_writable == [agent_vol], + "runtime writable mounts: %s" % rt_writable, + ) + check( + "runtime-has-no-env-port-or-envfrom", + not runtime.get("env") and not runtime.get("envFrom") and not runtime.get("ports"), + "runtime has env/envFrom/ports", + ) + check( + "runtime-seed-flag-is-the-secret-item", + rt_seed == "%s/%s" % (rt_key_mount, RUNTIME_KEY_ITEM) + and all( + "subPath" not in m and "subPathExpr" not in m + for m in runtime_mounts + if m.get("name") == rk_name + ), + "--seed-file %s, mount %s" % (rt_seed, rt_key_mount), + ) + seed_holders = sorted( + c.get("name") for c in all_ctrs if rk_name and mount_names_of(c) & set(rk_named) + ) + check( + "runtime-key-not-in-any-other-container-list", + seed_holders == ["runtime"], + "runtime-key is mounted by %s (init and ephemeral containers included)" % seed_holders, + ) + seed_env = [ + c.get("name") + for c in all_ctrs + for e in c.get("env", []) or [] + if (e.get("valueFrom", {}).get("secretKeyRef", {}) or {}).get("name") == RUNTIME_KEY_SECRET + ] + [ + c.get("name") + for c in all_ctrs + for ef in c.get("envFrom", []) or [] + if (ef.get("secretRef", {}) or {}).get("name") == RUNTIME_KEY_SECRET + ] + check("runtime-key-not-referenced-by-env", not seed_env, "referenced by env in %s" % seed_env) + + # Pod level: a short grace period, no API token, no service-link env. + grace = spec.get("terminationGracePeriodSeconds") + check( + "termination-grace-period-is-short", + isinstance(grace, int) and not isinstance(grace, bool) and 1 <= grace <= 15, + "terminationGracePeriodSeconds is %s" % grace, + ) + check( + "no-service-account-token-and-no-service-links", + spec.get("automountServiceAccountToken") is False + and spec.get("enableServiceLinks") is False, + ) + print() if FAILURES: print("%d check(s) failed: %s" % (len(FAILURES), ", ".join(FAILURES))) diff --git a/docs/design/runtime-split.md b/docs/design/runtime-split.md index 7b3e17b..b55df0d 100644 --- a/docs/design/runtime-split.md +++ b/docs/design/runtime-split.md @@ -95,6 +95,9 @@ Rules the codes depend on: `auth-proxy-runtime-key`, key `runtime_ed25519.seed`. The runtime container mounts it read-only at `/var/run/auth-proxy-runtime/runtime_ed25519.seed`, mode `0444`. No other container mounts the Secret, and the validator enforces that. + The container's own surface (seccomp, read-only root, one writable mount, no capability, no env) + is set in `pod.yaml` and enforced by the validator; see README "Runtime container hardening". + A compromised runtime container can still sign for as long as it runs. - The proxy holds only the public key: `runtime_pubkey` (standard base64, 32 bytes) on each `[[identity]]`. It is not a secret. A malformed key makes the proxy refuse to start. - Ed25519 rather than HMAC: an HMAC proxy would hold the same secret as the runtime, and the diff --git a/docs/evidence/runtime-hardening.md b/docs/evidence/runtime-hardening.md new file mode 100644 index 0000000..28caf1e --- /dev/null +++ b/docs/evidence/runtime-hardening.md @@ -0,0 +1,46 @@ +# Evidence: runtime container hardening on a real k3s node (issue #24) + +Settings and rules: README "Runtime container hardening". + +## Setup + +- Node: one single-node k3s v1.36.2 host (Ubuntu 24.04, amd64, AppArmor enabled). Namespace `ap-hard`, PSA `privileged`. +- Pod: `deploy/k8s/pod.yaml` at the commit under test. Test-only edits: namespace name, `storageClassName: local-path`, image references (`imagePullPolicy: Never`), and a `sleep infinity` command for the agent. No `securityContext` line was touched. +- Binaries: `cargo build --release --locked -p ap-proxy -p ap-egress -p ap-runtime-shim -p ap-netprobe` on the node, with a throwaway `CARGO_HOME` and target directory. Images built on a separate macOS builder (`gcr.io/distroless/cc-debian12` for the four Rust images as in `Containerfile`, `alpine:3.22` for `volume-prep`, `expiry-store-bootstrap`, `netinit` and `netcheck`, `alpine` plus curl for the agent), moved as a tar, imported with `ctr`. +- Secrets: random dummy values generated on the node; the seed and public key came from `openssl` (Ed25519). No value was printed. +- The runtime image is distroless and has no shell, so its process was inspected from the node through `crictl inspect` and `/proc/`. The agent was inspected through `kubectl exec`. + +## Results + +| Check | Result | +|---|---| +| Start | 6/6 containers ready, restarts 0. `volume-prep`, `netinit`, `expiry-store-bootstrap` exit 0. Proxy log: `netfilter self-check ready: ok`. Runtime log: `serving identity pty-team-a`. Proxy audit: `hello_challenge` 200, `hello` 201. | +| Runtime under the settings | From the agent (UID 1000) through `runtime.sock`: register 201, status lists the session, revoke 204, status empty. `POST /v1/hello` through `runtime.sock` 404. The proxy audit shows `register` 201. The runtime has `session-plane` mounted read-only (`ro,relatime` in its mountinfo), so connect, hello, register and renew work without write access to that directory. | +| Seccomp | Every container (init excluded, already exited) shows `Seccomp: 2`, `Seccomp_filters: 1`, `NoNewPrivs: 1`. The runtime ran hello, register, renew with no denial. No custom profile was needed. | +| Capabilities | Runtime, proxy, egress, netprobe, agent: `CapEff` and `CapBnd` 0000000000000000. `netcheck`: `0000000000001000` (`NET_ADMIN` only). Agent through `kubectl exec`: `CapInh`, `CapPrm`, `CapEff`, `CapBnd`, `CapAmb` all zero. | +| Read-only root | Agent through `kubectl exec`: `touch /rootfs-probe` gives "Read-only file system", mountinfo `/` is `ro`; `/tmp` and `/home/agent` (emptyDirs) are writable. Runtime, proxy, egress, netprobe, netcheck: `touch /proc//root/rootfs-probe` gives "Read-only file system". Runtime mounts: `/` ro, `/run/auth-proxy-session` ro, `/run/auth-proxy-agent` rw, `/var/run/auth-proxy-runtime` ro. A write to `/tmp`, to the seed directory and to `session-plane` in the runtime all fail with "Read-only file system". | +| Seed file | As seen by the runtime: `runtime_ed25519.seed` mode 444, owner 0:0 (kubelet-written, `..data` symlink). In the agent container: `cat /var/run/auth-proxy-runtime/runtime_ed25519.seed` gives "No such file or directory", `find / -name 'runtime_ed25519*'` finds nothing, `/var/run/auth-proxy-runtime` is not in its mountinfo, `/run/auth-proxy-session` does not exist. Scan of the agent's process environments and its writable paths for the seed and the credential: 0 hits. The seed's protection is the missing mount, not the file mode. | +| PID namespace | Runtime and proxy are in different PID namespaces and the same network namespace. The agent sees 5 PIDs (its own). | +| AppArmor | containerd's default profile is applied with no field set: `/proc//attr/current` of every container reads `cri-containerd.apparmor.d (enforce)`. A test pod with `appArmorProfile: {type: RuntimeDefault}` reads the same; one with `Unconfined` reads `unconfined`. The manifest does not set the field, because a node without AppArmor refuses it; the validator refuses `Unconfined`. | +| Black-box pod checks | Agent: proxy gate answers `403 surrogate_missing`; egress listener `405`; other loopback ports refused (curl exit 7); direct `https://1.1.1.1` refused (exit 7); DNS "no servers could be reached". Log scan of all seven containers for the credential, caller key and seed: 0 hits. | +| Expiry store | Owned 1001:1001 mode 0600 (`runAsGroup: 1001` added to `expiry-store-bootstrap`). Same sha256 before pod delete, after delete and after recreate. The recreated pod reached 6/6 and got `hello` 201. | +| Grace period | `terminationGracePeriodSeconds: 10`. Pod delete to gone: 10.8 s. The binaries run as PID 1 with no SIGTERM handler, so deletion waits for the whole grace period; the default is 30 s. | + +Not run: the sidecar and passthrough matrices on the node (they run on the build host, see the PR), the real upstream, and a node without AppArmor. + +## Cleanup check + +Snapshot before and after: namespaces, `ctr -n k8s.io images` listing, host `iptables -S OUTPUT`, PVs, home listing, tailscale status header. + +``` +namespaces : default kube-node-lease kube-public kube-system openab (same) +ctr images md5 / count : 1b52afe0a10081120714dbf0a88a6778 / 44, before and after +host iptables OUTPUT md5 : 6aa9113fa8015deb4c7a93b5c2f03524 before and after +PV listing md5 : 0f73001170936388d9f59096cba1bbea before and after +home listing md5 : 5c05b4b1648ffcef6269785cda708d68 before and after +tailscale : state never touched; header identical +build directory, scripts : removed from the node's temp directory +crictl containers (all) : 13 before, 14 after: one exited local-path `helper-pod` in kube-system (the claim cleanup), garbage-collected by the kubelet +``` + +Created and removed: namespace `ap-hard` (pod, claim and its volume, Secrets, ConfigMap), the seven imported image names and the seven index entries the import added, the build and run directories on the node, and the builder's image context.