# Kubernetes 密钥因缺少编码或转义，通过 Pod 规范在环境变量中暴露

- **ID:** `security/kubernetes-secret-exposed-in-environment-variable-via-pod-spec`
- **领域:** security
- **类别:** config_error
- **验证级别:** ai_generated
- **修复率:** 89%

## 根因

Kubernetes 密钥值包含特殊字符（如 $、\、换行符），在 Pod 规范中注入到环境变量时未进行正确的编码或转义，导致 shell 或应用程序错误地解释该值，可能在日志或错误消息中泄露密钥。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Kubernetes 1.29.0 | active | — | — |
| kubectl 1.29.0 | active | — | — |
| Helm 3.14.0 | active | — | — |
| Docker 25.0.0 | active | — | — |

## 解决方案

1. ```
   在 Pod 规范中使用 `env` 字段和 `valueFrom` 及 `secretKeyRef` 直接注入密钥，避免 shell 解释。示例：`env:
- name: DB_PASSWORD
  valueFrom:
    secretKeyRef:
      name: db-secret
      key: password`。这确保值按原样传递，无需 shell 转义。
   ```
2. ```
   如果使用 Helm，确保在模板中对密钥值加引号以防止 YAML 解析问题。使用 `{{ .Values.secret.password | quote }}` 添加引号，并在 values 文件中使用反斜杠转义特殊字符。例如，包含 $ 的密码应为 `password: "pa\$sword"`。
   ```
3. ```
   使用专门的密钥管理工具，如 HashiCorp Vault 和 Vault Agent Injector，将密钥作为文件或环境变量注入，而无需在 Pod 规范中暴露。示例注解：`vault.hashicorp.com/agent-inject: "true"` 和 `vault.hashicorp.com/agent-inject-secret-db-password: "secret/data/db"`。
   ```

## 无效尝试

- **Use a ConfigMap instead of a Secret for the environment variable** — ConfigMaps are not designed for sensitive data and store values in plain text. This actually increases the risk of exposure. (90% 失败率)
- **Encode the secret value in base64 and decode it in the application** — Base64 is not encryption; it can be easily decoded by anyone with access to the pod spec or logs. This provides no real security. (70% 失败率)
- **Remove special characters from the secret value** — This may break the application if the secret requires those characters (e.g., a password with $). It is not a general solution. (50% 失败率)
