# Detecting Container Drift At Runtime

> 通过监控二进制执行偏移、文件系统变更以及与原始容器镜像的配置偏差，检测对运行中容器的未授权修改。

- Skill: `killvxk/detecting-container-drift-at-runtime` (Agent Skill, multi-file: 8 files)
- Install (CLI): `npx skillmds@latest add killvxk/detecting-container-drift-at-runtime`
- Raw SKILL.md: https://api.skillmd.com/api/skills/killvxk/detecting-container-drift-at-runtime/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Coding & Dev Tools
- License: Apache-2.0
- Author: killvxk (https://skillmd.com/u/killvxk)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/killvxk/detecting-container-drift-at-runtime

---


# 检测运行时容器偏移

## 概述

容器偏移是指运行中的容器通过未授权的文件修改、意外的二进制执行、配置变更或软件包安装，偏离其原始镜像状态的现象。由于容器应被视为不可变基础设施，任何偏移都是潜在的入侵指标。检测技术利用 DIE（检测、隔离、驱逐）模型——不可变工作负载在运行期间不应发生变化，因此任何观察到的变化都可能是恶意活动的证据。

## 前提条件

- Kubernetes 集群 v1.24+，并配备运行时安全工具
- Falco 或 Sysdig 用于运行时偏移检测
- 可获取镜像清单的容器镜像仓库
- 熟悉 Linux 文件系统层和 OverlayFS

## 核心概念

### 容器偏移类型

1. **二进制偏移**：执行原始镜像中不存在的二进制文件（下载的恶意软件、编译的工具）
2. **文件偏移**：在容器文件系统中创建、修改或删除文件
3. **配置偏移**：对环境变量、挂载的 Secret 或运行时参数的更改
4. **包偏移**：在运行时通过 apt、yum、pip 或 npm 安装新软件包
5. **网络偏移**：工作负载预期之外的新监听端口或出站连接

### 检测方法

**基于镜像的比对**：将运行中容器的文件系统与源镜像进行比较，识别已添加、修改或删除的文件。

**行为监控**：使用 eBPF 或内核级监控来检测偏离预期行为的进程执行、文件访问和网络活动。

**摘要验证**：持续验证运行中的容器镜像摘要是否与已批准的部署清单匹配。

## 使用 Falco 实施

### 检测新的二进制执行

```yaml
- rule: Drift Detected (Container Image Modified Binary)
  desc: 检测执行原始容器镜像中不存在的二进制文件
  condition: >
    spawned_process and
    container and
    not proc.pname in (container_entrypoint) and
    proc.is_exe_upper_layer = true
  output: >
    检测到偏移：容器中执行了新的二进制文件
    (user=%user.name command=%proc.cmdline container=%container.name
     image=%container.image.repository:%container.image.tag
     exe_path=%proc.exepath)
  priority: WARNING
  tags: [container, drift]

- rule: Container Shell Spawned
  desc: 检测应不可变容器中的交互式 shell
  condition: >
    spawned_process and
    container and
    proc.name in (bash, sh, dash, zsh, csh, ksh) and
    not proc.pname in (container_entrypoint)
  output: >
    容器中启动了 shell (user=%user.name shell=%proc.name
     container=%container.name image=%container.image.repository)
  priority: WARNING
  tags: [container, drift, shell]
```

### 检测包管理器使用

```yaml
- rule: Package Manager Execution in Container
  desc: 检测包管理器的使用，表明存在偏移
  condition: >
    spawned_process and
    container and
    proc.name in (apt, apt-get, yum, dnf, apk, pip, pip3, npm, gem, cargo)
  output: >
    容器中执行了包管理器 (user=%user.name
     command=%proc.cmdline container=%container.name
     image=%container.image.repository)
  priority: ERROR
  tags: [container, drift, package-manager]
```

### 检测文件系统修改

```yaml
- rule: Container File System Write
  desc: 检测对容器上层文件系统的写入操作
  condition: >
    open_write and
    container and
    fd.typechar = 'f' and
    not fd.name startswith /tmp and
    not fd.name startswith /var/log and
    not fd.name startswith /proc
  output: >
    容器中发生文件写入 (user=%user.name file=%fd.name
     container=%container.name)
  priority: NOTICE
  tags: [container, drift, filesystem]
```

## 使用 Kubernetes 强制执行

### 只读根文件系统

通过使容器文件系统不可变来防止偏移：

```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: immutable-app
spec:
  template:
    spec:
      containers:
        - name: app
          image: app:v1.0@sha256:abc123...
          securityContext:
            readOnlyRootFilesystem: true
            allowPrivilegeEscalation: false
            runAsNonRoot: true
          volumeMounts:
            - name: tmp
              mountPath: /tmp
            - name: cache
              mountPath: /var/cache
      volumes:
        - name: tmp
          emptyDir:
            sizeLimit: 100Mi
        - name: cache
          emptyDir:
            sizeLimit: 50Mi
```

### Pod 安全标准执行

```yaml
apiVersion: v1
kind: Namespace
metadata:
  name: production
  labels:
    pod-security.kubernetes.io/enforce: restricted
    pod-security.kubernetes.io/audit: restricted
    pod-security.kubernetes.io/warn: restricted
```

## 镜像摘要验证

### 持续摘要监控

```bash
#!/bin/bash
# 将运行中容器的摘要与已批准清单进行比对

NAMESPACE="production"

kubectl get pods -n "$NAMESPACE" -o json | jq -r '
  .items[] |
  .spec.containers[] |
  "\(.image) \(.imageID)"
' | while read IMAGE IMAGE_ID; do
  APPROVED_DIGEST=$(kubectl get deploy -n "$NAMESPACE" -o json | \
    jq -r ".items[].spec.template.spec.containers[] | select(.image==\"$IMAGE\") | .image")

  if [[ "$IMAGE" != *"@sha256:"* ]]; then
    echo "[WARN] 容器使用了可变标签: $IMAGE"
  fi
done
```

## Microsoft Defender for Containers 集成

对于 Azure Kubernetes 环境，Microsoft Defender 提供内置的二进制偏移检测：

```json
{
  "alertType": "K8S.NODE_ImageBinaryDrift",
  "severity": "Medium",
  "description": "执行了原始容器镜像中不存在的二进制文件",
  "remediationSteps": [
    "调查二进制文件的来源和用途",
    "检查容器是否已被入侵",
    "从干净镜像重建容器",
    "启用 readOnlyRootFilesystem"
  ]
}
```

## 偏移响应手册

1. **检测**：偏移事件触发告警（Falco、Defender、Sysdig）
2. **验证**：确认偏移不是来自已批准的进程（init 容器、配置重载）
3. **隔离**：对受影响的 Pod 应用拒绝所有流量的 NetworkPolicy
4. **调查**：捕获容器文件系统差异和进程列表
5. **驱逐**：删除偏移的 Pod（ReplicaSet 将从干净镜像重新创建）
6. **修复**：修复根本原因（修补漏洞、更新镜像、收紧 RBAC）

## 参考资料

- [使用 Falco 进行容器偏移检测 - Sysdig](https://www.sysdig.com/blog/container-drift-detection-with-falco)
- [Microsoft Defender for Containers 偏移检测](https://techcommunity.microsoft.com/blog/microsoftdefendercloudblog/detect-container-drift-with-microsoft-defender-for-containers/4232044)
- [确保运行时容器的不可变性](https://notes.kodekloud.com/docs/Certified-Kubernetes-Security-Specialist-CKS/Monitoring-Logging-and-Runtime-Security/Ensure-Immutability-of-Containers-at-Runtime/)
- [Falco 运行时安全](https://falco.org/)

