Skip to content

fix(k8s): the ollama tier DaemonSets drop privilege escalation and capabilities, use RuntimeDefault seccomp and a read-only root filesystem, and run as non-root where the model directory allows #1060

Closed

Description

@dan-petty

Problem

None of the 9 ollama tier DaemonSets in k8s/llm/profiles/ollama-profiles.yaml sets a pod or container securityContext.

What that leaves:

  • Root. The containers run as root. id in the live ollama-16gib pod returned uid=0 (measured once, during the S10 evaluation), and the pod's securityContext is {}.
  • No other controls. Default capabilities, privilege escalation allowed, no seccomp profile and a writable root filesystem.
  • A writable host directory. The hostPath /var/lib/ollama (DirectoryOrCreate) is mounted at /root/.ollama.
  • An open API. The API listens on 0.0.0.0:11434 with no authentication (OLLAMA_HOST, :53-54).
    • llm-default-perimeter (k8s/llm/networkpolicy.yaml) admits every llm-namespace pod, the monitoring namespace and Traefik, with no port restriction.
    • NetworkPolicies are additive, and k8s/llm/profiles/networkpolicy.yaml selects only provider=vllm, so nothing narrows this.
  • No admission check. Namespace llm enforces Pod Security privileged (k8s/llm/namespace.yaml:7-9), so admission checks nothing.

So a code-execution bug in ollama would run as root, with default capabilities and a writable host directory [inference].

The six first-party workloads in the same stack already set runAsNonRoot: true, allowPrivilegeEscalation: false and readOnlyRootFilesystem: true: cloudflared, llm-gateway, portkey, valkey, valkey-runs and jaeger.

  • For example, k8s/llm/gateway/deployment.yaml:22-28 sets UID/GID 1000 and RuntimeDefault seccomp, pinned by tests/test_k8s_llm_gateway.py:77-100.
  • The Helm values for traefik, qdrant and otel set them too.
  • The DCGM exporter is the documented exception: it needs root and SYS_ADMIN for NVML (docs/SELF_IMPROVEMENT.md:278).

Why ollama runs as root is not recorded. I searched k8s/, docs/, the task files and the manifest's git history and found nothing. Likely reasons [inference]:

  • the ollama/ollama image runs as root and keeps its data in /root/.ollama;
  • kubelet creates a DirectoryOrCreate hostPath owned by root, so a non-root UID cannot write models there without a chown;
  • fsGroup does not change hostPath ownership.

The NVIDIA runtime (runtimeClassName: nvidia) injects the device nodes and does not by itself need root inside the container [inference; to confirm on a node].

How the review saw it. Review session 20261003-034353 (S10, release/v0.2.25 at d6ebe97; .data/review-evaluation-20261003-s10.md, section 4). The golden cases are S10 candidates [1], [11] and [2]-[10].

No open issue covers ollama hardening. #953 covers qdrant's chart securityContext and the single-ollama leftovers only.

Out of scope: memory limits (kube-linter unset-memory-requirements ×9). #209 removed them deliberately.

Acceptance criteria

  • Every ollama DaemonSet's container sets:
    • allowPrivilegeEscalation: false;
    • capabilities.drop: [ALL];
    • seccompProfile.type: RuntimeDefault (pod or container level);
    • readOnlyRootFilesystem: true, with an emptyDir at /tmp and at any other path ollama writes outside its data directory (found by the person-run check).
  • Every ollama DaemonSet runs as a fixed non-root UID and GID with runAsNonRoot: true.
    • The model directory is owned by that UID, set as the key questions propose.
    • OLLAMA_MODELS and the data mount move off /root.
    • If the person-run check shows that the NVIDIA runtime or the hostPath needs root, the DaemonSets keep root with every other control set. A comment in the manifest and k8s/README.md then record the exception and why.
  • An offline test in the style of tests/test_k8s_llm_gateway.py:77-100 loads every DaemonSet in ollama-profiles.yaml and asserts those fields, so a new tier (as feat(llm): add speed-tier service aliases, align 48gib slow routing weights and bump max loaded models #1042 added) cannot ship without them. It fails on the current manifest.
  • (local, recorded in the PR) kube-linter 0.8.3 over ollama-profiles.yaml reports no no-read-only-root-fs and no run-as-non-root, unless the documented exception keeps root. The test suite does not run kube-linter.
  • changelog.d/1060.md records the change under ### Fixed. CHANGELOG.md is not edited.
  • uv run devops ci passes.
  • (person-run) On the homelab, after the deploy, each scheduled tier's pod becomes Ready, sees its GPU (nvidia-smi or ollama's startup log), and loads and answers a model through the gateway. id in the pod shows the non-root UID, or the documented exception. Record the result per tier in the PR.

Key questions

  • Why does ollama run as root, and can it stop? (proposed) Nothing in the repo records a reason. Confirm on one node before changing every tier.
    • Run the 16gib tier with the non-root UID and the re-owned directory.
    • If it sees its GPU and loads a model, apply the change to all tiers.
    • If not, keep root as the documented exception, with the other controls set.
  • How does the model directory get its owner? (proposed) Through an initContainer in each DaemonSet.
    • The initContainer runs as root with only CHOWN and FOWNER and re-owns /var/lib/ollama to the fixed UID. Its own controls are allowPrivilegeEscalation: false and a read-only root filesystem.
    • The fix then lives in this repo and does not wait on dan-petty/homelab.
    • fsGroup cannot do it, because it does not apply to hostPath volumes.
  • Which UID? (proposed) 1000/1000, as the gateway uses. Name it once in the manifest and assert it in the test.
  • Does the llm namespace's Pod Security level change? (proposed) Not in this item. Once nothing in llm needs privileged, raising enforce is a separate change.
  • Is this a v0.2.25 critical fix? (proposed) No. It is a hardening gap present since the tiers were added (8 of 9 at v0.2.24), not a regression, and the network perimeter limits who can reach port 11434. P2, backlog.

Depends on: none.
Order: #795 (v0.2.29) also edits ollama-profiles.yaml (selectors and comments). Whichever lands second rebases. The change touches k8s/llm/profiles/ollama-profiles.yaml, k8s/README.md and a new or extended manifest test.
Related:

Update 2026-10-09: re-scope before building (owner decisions)

The v0.2.32 assessment and its challenge found every criterion buildable except AC4 ("kube-linter reports nothing" for these DaemonSets): some container must run as root once to give the model directory to the ollama user, because fsGroup does not apply to hostPath volumes, a non-root container loses an added CAP_CHOWN at execve (containerd sets no ambient capabilities), and a DaemonSet cannot use per-node PVCs. The owner decided:

  • AC4 becomes: kube-linter 0.8.3 over ollama-profiles.yaml reports no no-read-only-root-fs and no new report of any kind, and reports run-as-non-root only for the root chown initContainer own-model-directory, one per DaemonSet. That initContainer holds only CAP_CHOWN, has no privilege escalation and a read-only root filesystem, and exits before ollama starts; the manifest header comment and k8s/README.md record it as the one exception. No ignore-check annotation. (unset-memory-requirements on the ollama container stays out of scope, fix(k8s): uncap ollama memory limits and elevate daemonset/deployment resource thresholds #209.) This follows the Grafana chart's own initChownData pattern.
  • UID: ollama runs as a dedicated UID and GID, 10001, which no host login account uses, so neither the model directory's owner nor an escaped process maps to a person's account on the GPU nodes.
  • AC2 clarification: CAP_CHOWN alone is enough (no FOWNER). HOME is /home/ollama, which keeps the key and the models on the existing hostPath, so nothing is downloaded again.
  • Naming the UID once: YAML anchors don't cross --- documents and deploy-stack's kubectl apply -f would skip a kustomize patch, so the test names the UID once and asserts it for all 9 tiers.
  • Every other criterion stands as written.

Activity

  1. added
    type/bug
    scope/k8s
    scope/security
    priority/p2-medium
    on Oct 3, 2026
  2. added this to the v0.2.32 milestone on Oct 8, 2026
  3. dan-petty commented on Oct 8, 2026

    @dan-petty
    OwnerAuthor

    Placed in v0.2.32 on 2026-10-08 at the owner's request ("Populate 10 security and ci issues into each v0.2.30, v0.2.31, and v0.2.32 milestone"). This is a person's placement. Release theme: URLs and host keys read by the library that dials, ollama hardening, and pull-request test-quality tooling. Position 6 of 10 in the release's planned merge order. Its board Status is set to Ready, so the release-start fill keeps it.

  4. dan-petty-bot commented on Oct 9, 2026

    @dan-petty-bot
    Collaborator

    What changed

    #1508, merged into release/v0.2.32 as eeb544b.

    Summary

    • Every ollama tier DaemonSet in k8s/llm/profiles/ollama-profiles.yaml (all 9) now runs ollama as UID/GID 10001, which no host login account uses. The pod sets runAsNonRoot: true and seccompProfile: RuntimeDefault. The ollama container sets allowPrivilegeEscalation: false, readOnlyRootFilesystem: true and capabilities.drop: [ALL], with /tmp on an emptyDir.
    • HOME=/home/ollama, the hostPath is mounted at /home/ollama/.ollama, and OLLAMA_MODELS=/home/ollama/.ollama/models. The hostPath itself is unchanged (/var/lib/ollama, DirectoryOrCreate), so the key and models/ stay where they are and nothing is downloaded again.
    • A new root initContainer, own-model-directory, gives that directory to 10001 at every start with chown -R. It uses the same ollama/ollama:0.34.4 image, holds CAP_CHOWN only, runs with no privilege escalation and a read-only root filesystem, and requests cpu: 10m with a memory: 64Mi limit.
      • A root step is unavoidable: fsGroup does not apply to hostPath, a non-root container loses an added CAP_CHOWN at execve, and a DaemonSet cannot use per-node PVCs.
      • This is the re-scope (Option A) the owner accepted on 2026-10-09, the Grafana chart's initChownData pattern.
      • The manifest header and k8s/README.md ("GPU Placement: Ollama tiers") record it as the one kube-linter exception. There is no ignore annotation.
    • New test_every_ollama_tier_runs_unprivileged in tests/test_k8s_llm_gateway.py names the…

    5 file(s) changed.

    How it was verified

    Check runs at fe4d74a:

    • Prune PR DevContainer Images: pass
    • CodeQL: pass
    • Analyze (actions): pass
    • Analyze (python): pass
    • Tests & Coverage: pass
    • Static Analysis: pass
    • DevContainer Image: skipping
    • Service Image: skipping
    • Dependency Freshness: skipping

    Acceptance Criteria of docs/agent/tasks/task-1060-ollama-daemonset-hardening.md:

    • Every ollama DaemonSet's ollama container sets allowPrivilegeEscalation: false, capabilities.drop: [ALL] and readOnlyRootFilesystem: true, with seccompProfile: RuntimeDefault at pod level and an emptyDir at /tmp. No other emptyDir is added: the person-run checks below look for "read-only file system" errors, and each such path gets an emptyDir.

    • Every ollama DaemonSet runs as UID and GID 10001 with runAsNonRoot: true. The model directory is given to that UID by own-model-directory, which holds CAP_CHOWN alone. OLLAMA_MODELS and the data mount moved off /root, and HOME=/home/ollama keeps the existing hostPath layout.

    • test_every_ollama_tier_runs_unprivileged in tests/test_k8s_llm_gateway.py loads every DaemonSet in ollama-profiles.yaml. For each one, it asserts:

      • the pod and container security contexts;
      • HOME and OLLAMA_MODELS;
      • the container's mounts;
      • the volumes, including the unchanged hostPath /var/lib/ollama (DirectoryOrCreate);
      • exactly one initContainer, own-model-directory, with the ollama container's image, its chown command, its security context and its mount.

      A new tier is covered without editing the test, and test_ollama_profiles_define_standard_vram_tiers still pins the 9 names. On the previous manifest the test failed with an assertion diff for every tier, not a KeyError. It runs no kubectl, kube-linter or network call.

    • kube-linter 0.8.3 over k8s/llm/profiles/ollama-profiles.yaml (run locally; the suite does not run it):

      • Before: 27 reports, no-read-only-root-fs x9, run-as-non-root x9 and unset-memory-requirements x9.
      • After: 18 reports, run-as-non-root x9, all container "own-model-directory" (the recorded exception), and unset-memory-requirements x9, all container "ollama" (out of scope: fix(k8s): uncap ollama memory limits and elevate daemonset/deployment resource thresholds #209 removed the memory limits on purpose).
      • no-read-only-root-fs is 0, nothing new appears, and no ignore-check annotation is used.
    • changelog.d/1060.md records the change under ### Fixed. CHANGELOG.md and docs/ROADMAP.md are not edited.

    • Locally, these pass:

      • the tests that read this manifest or scan every manifest: tests/test_k8s_llm_gateway.py, tests/test_k8s_gpu_matrix.py, tests/test_ai_gateway_portkey.py, tests/test_k8s.py::test_k8s_workload_resource_limits_and_probes, tests/test_k8s_valkey_stack.py, tests/test_k8s_push_secrets.py, tests/test_k8s_manifest_validation.py, tests/test_k8s_network_policies.py and tests/test_review_project_conventions.py;
      • tests/test_agent_task_files.py and tests/test_release_changelog_fragments.py;
      • ruff check and ruff format --check on the test file, and devops docs check.

      No src/ file changed, so mypy has nothing new to check. uv run devops ci runs as the pull request's CI check.

    • Pending a person: the canary on one node, after this PR merges into release/v0.2.32 and before the v0.2.32 release PR merges into main (Argo CD rolls every tier at once from main):

      1. From a checkout of release/v0.2.32, record each scheduled tier's models for the later comparison, and confirm that the 16gib tier has no model loaded (ollama ps lists none), so the canary has the GPU to itself:
        for t in ollama-16gib ollama-48gib ollama-48gib-slow ollama-64gib; do kubectl -n llm exec ds/$t -c ollama -- ollama list | awk '{print $1, $2}' > /tmp/$t.models; done
        kubectl -n llm exec ds/ollama-16gib -c ollama -- ollama ps
      2. Create the canary as a bare Pod named and labelled ollama-canary, with restartPolicy: Never. It must not carry the template's labels: the DaemonSet would adopt and delete a pod matching its selector, and the ollama-16gib Services would send gateway traffic to it. If it stays Pending for lack of CPU or memory next to the live pod, the canary cannot run on that node: delete it (kubectl -n llm delete pod ollama-canary) and rely on the rollout checks.
        uv run python -c 'import json,yaml; ds=next(d for d in yaml.safe_load_all(open("k8s/llm/profiles/ollama-profiles.yaml")) if d and d["metadata"]["name"]=="ollama-16gib"); print(json.dumps({"apiVersion":"v1","kind":"Pod","metadata":{"name":"ollama-canary","namespace":"llm","labels":{"app.kubernetes.io/name":"ollama-canary"}},"spec":{**ds["spec"]["template"]["spec"],"restartPolicy":"Never"}}))' | kubectl apply -f -
        kubectl -n llm wait --for=condition=Ready pod/ollama-canary --timeout=10m
        kubectl -n llm get pod ollama-canary -o jsonpath='{.status.initContainerStatuses[0].state.terminated.exitCode}'   # 0
        kubectl -n llm exec ollama-canary -c ollama -- id                    # uid=10001 gid=10001
        kubectl -n llm exec ollama-canary -c ollama -- sh -c 'ls -ln /dev/nvidia*'   # crw-rw-rw-, or a group the pod is in
        kubectl -n llm exec ollama-canary -c ollama -- ollama list | awk '{print $1, $2}' | diff /tmp/ollama-16gib.models -   # no output
        kubectl -n llm exec ollama-canary -c ollama -- ollama run gpt-oss:20b 'Reply with ok'
        kubectl -n llm exec ollama-canary -c ollama -- ollama ps             # PROCESSOR shows GPU
        kubectl -n llm logs ollama-canary -c ollama | grep -E 'inference compute|read-only|permission denied'   # a CUDA line, no errors
        kubectl -n llm delete pod ollama-canary
        The canary leaves that node's directory owned by 10001 while the live pod still runs as root, which keeps writing it (root holds CAP_DAC_OVERRIDE).
      3. If the canary fails, fix it in release/v0.2.32 before the release PR merges, and change the test with it:
        • /dev/nvidia* is 0660 to a group and the log shows no CUDA line: add pod supplementalGroups: [<that gid>] to all 9 tiers.
        • A "read-only file system" error at a path: add an emptyDir at that path.
        • Only a demonstrated need for root: keep root with every other control set, with a manifest comment and a k8s/README.md note. The initContainer must stay and chown to 0:0, because root with all capabilities dropped cannot write the 10001-owned directory the canary left.
        • Anything else, such as the NVIDIA hook failing on a read-only root: stop and return it to the owner.
    • Pending a person: the rollout, after the v0.2.32 release PR merges and Argo CD syncs llm:

      1. Argo CD and the DaemonSets:
        kubectl -n argocd get application llm -o jsonpath='{.status.sync.status} {.status.health.status} {.status.sync.revision}{"\n"}'   # Synced Healthy <release merge commit>
        kubectl -n llm get ds -l llm.devops.io/provider=ollama   # READY == DESIRED; 16gib, 48gib, 48gib-slow and 64gib at 1
      2. Each scheduled tier's pod is Ready, runs as 10001, sees its GPU and still has its models. Expected per tier: 0 0 (init exit code, restarts), uid=10001 gid=10001, a GPU name, no diff output, and a CUDA inference compute line with no "read-only" or "permission denied":
        for t in ollama-16gib ollama-48gib ollama-48gib-slow ollama-64gib; do
          kubectl -n llm get pods -l app.kubernetes.io/name=$t -o jsonpath='{.items[0].status.initContainerStatuses[0].state.terminated.exitCode} {.items[0].status.containerStatuses[0].restartCount}{"\n"}'
          kubectl -n llm exec ds/$t -c ollama -- id
          kubectl -n llm exec ds/$t -c ollama -- nvidia-smi --query-gpu=name,memory.total --format=csv,noheader
          kubectl -n llm exec ds/$t -c ollama -- ollama list | awk '{print $1, $2}' | diff /tmp/$t.models -
          kubectl -n llm logs ds/$t -c ollama | grep -E 'inference compute|read-only|permission denied'
        done
      3. A restart re-owns a directory that 10001 already owns: kubectl -n llm rollout restart ds/ollama-16gib && kubectl -n llm rollout status ds/ollama-16gib --timeout=10m completes, and the first command of step 2 then prints 0 0 for ollama-16gib.
      4. Each tier loads and answers a model through the gateway. Use models that each route to one tier only (k8s/llm/gateway/configmap.yaml): gpt-oss:20b (16gib), devops-coder (48gib), deepseek-r1:70b (64gib), and devops-background and bge-m3:latest (48gib-slow). Each call returns a choices entry (the embedding, a vector length), and kubectl -n llm exec ds/<tier> -c ollama -- ollama ps then shows the model on 100% GPU:
        kubectl -n llm port-forward svc/llm-gateway 4000:4000 &
        KEY=$(kubectl -n llm get secret llm-gateway-secrets -o jsonpath='{.data.master-key}' | base64 -d)
        for m in gpt-oss:20b devops-coder deepseek-r1:70b devops-background; do
          curl -s localhost:4000/v1/chat/completions -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \
            -d "{\"model\":\"$m\",\"max_tokens\":64,\"messages\":[{\"role\":\"user\",\"content\":\"Reply with ok\"}]}" | jq '.choices[0].message // .error'
        done
        curl -s localhost:4000/v1/embeddings -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \
          -d '{"model":"bge-m3:latest","input":"ok"}' | jq '.data[0].embedding | length'
      5. Record the result per tier in this item's pull request.
  5. dan-petty commented on Oct 9, 2026

    @dan-petty
    OwnerAuthor

    Canary passed (2026-10-09, before the v0.2.32 release PR)

    Ran the task file's canary on the 16 GiB tier's node from release/v0.2.32 (after #1508): a bare Pod ollama-canary built from the merged ollama-16gib template, without the DaemonSet's labels, with restartPolicy: Never. One deviation: the template's 8Gi memory request did not fit next to the live pod (FailedScheduling, Insufficient memory), so the canary requested 4Gi and 1 CPU; nothing it checks depends on the request.

    • initContainer own-model-directory exit 0; /home/ollama/.ollama and models/ now owned by 10001:10001.
    • id: uid=10001 gid=10001.
    • /dev/nvidia* are crw-rw-rw-, so no supplementalGroups is needed.
    • ollama list identical to the live tier's (no re-download).
    • ollama run qwen2.5-coder:7b answered; ollama ps shows 100% GPU; the log has the CUDA inference compute line (RTX 5070 Ti, driver 13.4) and no "read-only" or "permission denied".
    • The canary was deleted; the live ollama-16gib pod kept running throughout.

    The NVIDIA runtime hook works with the read-only root filesystem. The post-merge rollout checks in the task file still apply when v0.2.32 reaches main.

  6. added a commit that references this issue on Oct 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority/p2-mediumscope/k8sscope/securitytype/bug

    Type

    No type

    Projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions