Skip to content

容器安全完整指南

容器安全是云原生安全的核心组成部分,涵盖从镜像构建到运行时监控的完整生命周期。容器技术在带来灵活性和可移植性的同时,也引入了新的安全挑战,需要建立系统性的安全防护体系。

🛡️ 容器安全生命周期

安全左移策略

yaml
development_security:
  secure_coding_practices:
    base_image_selection:
      criteria:
        - "官方镜像优先选择"
        - "最小化基础镜像"
        - "定期更新维护"
        - "已知漏洞数量"
      
      recommended_images:
        distroless: "Google Distroless镜像"
        alpine: "Alpine Linux镜像"
        scratch: "空白镜像(静态编译)"
        chainguard: "Chainguard强化镜像"
      
      evaluation_matrix: |
        镜像类型    | 安全性 | 大小 | 维护性 | 兼容性
        ----------|--------|------|--------|-------
        Distroless|  高    | 小   |  高    |  中
        Alpine    |  高    | 小   |  高    |  高
        Ubuntu    |  中    | 大   |  高    |  高
        CentOS    |  中    | 大   |  中    |  高
        Scratch   |  最高  | 最小 |  低    |  低
    
    dockerfile_security:
      best_practices:
        - "多阶段构建减少攻击面"
        - "非root用户运行"
        - "最小权限原则"
        - "敏感信息处理"
      
      secure_dockerfile: |
        # 安全的Dockerfile示例
        # 多阶段构建
        FROM node:16-alpine AS builder
        WORKDIR /app
        COPY package*.json ./
        RUN npm ci --only=production
        
        # 运行时镜像
        FROM gcr.io/distroless/nodejs:16
        
        # 创建非root用户
        USER 1001:1001
        
        # 复制应用文件
        WORKDIR /app
        COPY --from=builder --chown=1001:1001 /app/node_modules ./node_modules
        COPY --chown=1001:1001 src/ ./src/
        
        # 健康检查
        HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
          CMD node healthcheck.js
        
        # 启动应用
        EXPOSE 3000
        CMD ["src/index.js"]
      
      anti_patterns: |
        # 应避免的不安全实践
        
        # ❌ 以root用户运行
        USER root
        
        # ❌ 安装不必要的包
        RUN apt-get update && apt-get install -y curl vim nano
        
        # ❌ 硬编码敏感信息
        ENV DATABASE_PASSWORD=supersecret
        
        # ❌ 复制整个文件系统
        COPY . .
        
        # ❌ 使用latest标签
        FROM ubuntu:latest
        
        # ❌ 不清理包管理缓存
        RUN apt-get update && apt-get install -y package
    
    secret_management:
      buildtime_secrets:
        docker_buildkit: |
          # 使用BuildKit处理构建时密钥
          # syntax=docker/dockerfile:1.4
          FROM alpine
          RUN --mount=type=secret,id=api_key \
            API_KEY=$(cat /run/secrets/api_key) && \
            echo "Using API key for build process"
          
          # 构建命令
          # echo "secret_api_key" | docker build --secret id=api_key,src=- .
        
        multistage_cleanup: |
          # 多阶段构建清理密钥
          FROM alpine AS secrets
          COPY secrets.txt /tmp/
          
          FROM alpine AS final
          COPY --from=secrets /tmp/processed_data /app/
          # 密钥不会包含在最终镜像中
      
      runtime_secrets:
        kubernetes_secrets: |
          # Kubernetes Secret挂载
          apiVersion: v1
          kind: Secret
          metadata:
            name: app-secrets
          type: Opaque
          data:
            database-password: <base64-encoded>
            api-key: <base64-encoded>
          ---
          apiVersion: apps/v1
          kind: Deployment
          metadata:
            name: secure-app
          spec:
            template:
              spec:
                containers:
                - name: app
                  image: myapp:v1.0
                  env:
                  - name: DB_PASSWORD
                    valueFrom:
                      secretKeyRef:
                        name: app-secrets
                        key: database-password
                  volumeMounts:
                  - name: api-certs
                    mountPath: /etc/ssl/certs
                    readOnly: true
                volumes:
                - name: api-certs
                  secret:
                    secretName: app-secrets
                    items:
                    - key: api-key
                      path: api.key
        
        external_secrets: |
          # External Secrets Operator
          apiVersion: external-secrets.io/v1beta1
          kind: ExternalSecret
          metadata:
            name: vault-secret
          spec:
            refreshInterval: 15s
            secretStoreRef:
              name: vault-backend
              kind: SecretStore
            target:
              name: app-secret
              creationPolicy: Owner
            data:
            - secretKey: password
              remoteRef:
                key: secret/database
                property: password

supply_chain_security:
  image_provenance:
    sbom_generation:
      description: "软件物料清单生成"
      tools:
        - "Syft (Anchore)"
        - "Trivy SBOM"
        - "Docker Buildx"
        - "SPDX格式"
      
      implementation: |
        # Syft SBOM生成
        syft packages docker:myapp:latest -o spdx-json > myapp-sbom.json
        
        # Docker Buildx SBOM
        docker buildx build --sbom=true -t myapp:latest .
        
        # 集成到CI/CD
        stages:
          - name: Generate SBOM
            script:
              - syft packages $IMAGE_NAME -o spdx-json > sbom.json
              - grype sbom:sbom.json # 漏洞扫描
    
    image_signing:
      cosign_implementation: |
        # Cosign镜像签名
        # 生成密钥对
        cosign generate-key-pair
        
        # 签名镜像
        cosign sign --key cosign.key myregistry/myapp:v1.0
        
        # 验证签名
        cosign verify --key cosign.pub myregistry/myapp:v1.0
        
        # Kubernetes准入控制器验证
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: cosign-verification
        data:
          policy.yaml: |
            apiVersion: v1alpha1
            kind: ClusterImagePolicy
            metadata:
              name: require-signed-images
            spec:
              images:
              - glob: "myregistry/**"
              authorities:
              - key:
                  data: |
                    -----BEGIN PUBLIC KEY-----
                    MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...
                    -----END PUBLIC KEY-----
      
      notary_v2: |
        # Notary v2 (TUF)实现
        # 初始化仓库
        notation cert generate-test "wabbit-networks.io"
        notation sign myregistry/myapp:v1.0
        
        # 验证策略
        {
          "version": "1.0",
          "trustPolicies": [
            {
              "name": "wabbit-networks-images",
              "registryScopes": [ "myregistry/myapp" ],
              "signatureVerification": {
                "level": "strict"
              },
              "trustStores": ["ca:wabbit-networks.io"],
              "trustedIdentities": ["*"]
            }
          ]
        }
  
  dependency_management:
    vulnerability_scanning:
      continuous_monitoring: |
        # 持续漏洞监控流水线
        name: Container Security Scan
        on:
          push:
            branches: [main]
          schedule:
            - cron: '0 6 * * *'  # 每日扫描
        
        jobs:
          security-scan:
            runs-on: ubuntu-latest
            steps:
              - uses: actions/checkout@v3
              
              - name: Build image
                run: docker build -t ${{ github.repository }}:${{ github.sha }} .
              
              - name: Run Trivy vulnerability scanner
                uses: aquasecurity/trivy-action@master
                with:
                  image-ref: ${{ github.repository }}:${{ github.sha }}
                  format: 'sarif'
                  output: 'trivy-results.sarif'
              
              - name: Upload Trivy scan results
                uses: github/codeql-action/upload-sarif@v2
                with:
                  sarif_file: 'trivy-results.sarif'
              
              - name: Security gate
                run: |
                  CRITICAL=$(trivy image --severity CRITICAL --format json ${{ github.repository }}:${{ github.sha }} | jq '.Results[].Vulnerabilities | length')
                  if [ "$CRITICAL" -gt 0 ]; then
                    echo "Critical vulnerabilities found: $CRITICAL"
                    exit 1
                  fi
    
    license_compliance:
      automated_checking: |
        # 许可证合规检查
        # FOSSA扫描
        fossa analyze
        fossa test
        
        # License Finder
        license_finder --decisions-file=doc/dependency_decisions.yml
        
        # Scancode Toolkit
        scancode --license --copyright --summary myproject/
    
    update_automation:
      dependabot_config: |
        # .github/dependabot.yml
        version: 2
        updates:
          - package-ecosystem: "docker"
            directory: "/"
            schedule:
              interval: "weekly"
            open-pull-requests-limit: 10
            reviewers:
              - "security-team"
            labels:
              - "security"
              - "dependencies"
      
      renovate_config: |
        # renovate.json
        {
          "extends": ["config:base"],
          "dockerfile": {
            "enabled": true
          },
          "vulnerabilityAlerts": {
            "enabled": true
          },
          "osvVulnerabilityAlerts": true,
          "separateMinorPatch": true,
          "prConcurrentLimit": 3
        }
yaml
build_security:
  secure_build_environment:
    build_isolation:
      principles:
        - "隔离的构建环境"
        - "最小权限构建用户"
        - "临时性构建实例"
        - "构建缓存安全"
      
      implementation: |
        # GitHub Actions安全构建
        name: Secure Build
        jobs:
          build:
            runs-on: ubuntu-latest
            permissions:
              contents: read
              packages: write
              security-events: write
            
            steps:
              - name: Harden Runner
                uses: step-security/harden-runner@v2
                with:
                  egress-policy: audit
                  allowed-endpoints: >
                    api.github.com:443
                    github.com:443
                    registry-1.docker.io:443
              
              - uses: actions/checkout@v3
              
              - name: Build with security scanning
                run: |
                  # 构建镜像
                  docker build -t temp-image .
                  
                  # 立即扫描
                  trivy image --exit-code 1 --severity HIGH,CRITICAL temp-image
    
    build_attestation:
      slsa_provenance: |
        # SLSA构建证明
        name: SLSA Generic generator
        on:
          workflow_call:
            inputs:
              image:
                required: true
                type: string
        
        jobs:
          build:
            outputs:
              image: ${{ steps.image.outputs.image }}
              digest: ${{ steps.image.outputs.digest }}
            runs-on: ubuntu-latest
            steps:
              - name: Checkout
                uses: actions/checkout@v3
              
              - name: Build image
                id: image
                run: |
                  docker build -t ${{ inputs.image }} .
                  DIGEST=$(docker inspect --format='{{index .RepoDigests 0}}' ${{ inputs.image }})
                  echo "digest=${DIGEST}" >> $GITHUB_OUTPUT
          
          provenance:
            needs: [build]
            permissions:
              id-token: write
              contents: read
              actions: read
            uses: slsa-framework/slsa-github-generator/.github/workflows/generator_container_slsa3.yml@v1.7.0
            with:
              image: ${{ needs.build.outputs.image }}
              digest: ${{ needs.build.outputs.digest }}
      
      in_toto_attestation: |
        # in-toto软件供应链证明
        in-toto-run --step-name build \
          --products myapp \
          --key build-key.pem \
          -- docker build -t myapp .
        
        in-toto-run --step-name test \
          --materials myapp \
          --products test-results.xml \
          --key test-key.pem \
          -- pytest tests/
        
        # 验证供应链
        in-toto-verify --verification-key release-key.pem \
          --layout root.layout \
          --link-dir .
  
  registry_security:
    harbor_configuration:
      vulnerability_scanning: |
        # Harbor项目配置
        {
          "project_name": "secure-apps",
          "metadata": {
            "auto_scan": "true",
            "severity": "high",
            "reuse_sys_cve_allowlist": "false",
            "retention_policy": {
              "rules": [{
                "disabled": false,
                "action": "retain",
                "template": "always",
                "tag_selectors": [{
                  "kind": "doublestar",
                  "decoration": "matches",
                  "pattern": "release-**"
                }],
                "scope_selectors": [{
                  "kind": "repository",
                  "decoration": "repoMatches",
                  "pattern": "**"
                }]
              }]
            }
          }
        }
      
      access_control: |
        # Harbor RBAC配置
        # 项目级权限
        - 项目管理员: 完全控制权限
        - 开发者: 推送/拉取权限
        - 访客: 仅拉取权限
        
        # 机器人账户
        robot_account:
          name: "ci-robot"
          permissions:
            - "push"
            - "pull"
          expires_at: "2024-12-31T23:59:59Z"
    
    content_trust:
      docker_content_trust: |
        # Docker Content Trust配置
        export DOCKER_CONTENT_TRUST=1
        export DOCKER_CONTENT_TRUST_SERVER=https://notary.example.com
        
        # 初始化仓库
        docker trust key generate mykey
        docker trust signer add --key mykey.pub myuser myregistry/myapp
        
        # 签名推送
        docker push myregistry/myapp:v1.0
        
        # 验证拉取
        docker pull myregistry/myapp:v1.0
      
      verification_policy: |
        # Kubernetes镜像策略
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: image-policy
        data:
          policy.json: |
            {
              "default": [
                {
                  "type": "reject"
                }
              ],
              "transports": {
                "docker": {
                  "myregistry.com": [
                    {
                      "type": "signedBy",
                      "keyType": "GPGKeys",
                      "keyPath": "/etc/pki/trust.gpg"
                    }
                  ]
                }
              }
            }
  
  ci_cd_integration:
    security_gates:
      quality_gates: |
        # GitLab CI安全门禁
        security_scan:
          stage: security
          image: aquasec/trivy:latest
          script:
            - trivy filesystem --exit-code 1 --severity HIGH,CRITICAL .
            - trivy image --exit-code 1 --severity HIGH,CRITICAL $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
          artifacts:
            reports:
              container_scanning: trivy-report.json
          rules:
            - if: $CI_COMMIT_BRANCH == "main"
            - if: $CI_PIPELINE_SOURCE == "merge_request_event"
        
        policy_check:
          stage: security
          image: openpolicyagent/conftest:latest
          script:
            - conftest verify --policy docker-security.rego Dockerfile
            - conftest test --policy k8s-security.rego k8s/
          rules:
            - exists:
              - Dockerfile
              - k8s/*.yaml
      
      automated_remediation: |
        # 自动化修复流程
        vulnerability_remediation:
          stage: remediation
          script:
            - |
              # 检查可修复漏洞
              FIXABLE=$(trivy image --format json $IMAGE | jq '.Results[].Vulnerabilities[] | select(.FixedVersion != "") | .VulnerabilityID' | wc -l)
              
              if [ "$FIXABLE" -gt 0 ]; then
                echo "Found $FIXABLE fixable vulnerabilities"
                
                # 创建修复PR
                git checkout -b "security/fix-vulnerabilities-$(date +%Y%m%d)"
                
                # 更新基础镜像
                sed -i 's/FROM alpine:3.14/FROM alpine:3.16/' Dockerfile
                
                # 提交并创建PR
                git add Dockerfile
                git commit -m "Security: Update base image to fix vulnerabilities"
                git push origin HEAD
                
                # 创建PR(使用API)
                curl -X POST \
                  -H "Authorization: token $GITHUB_TOKEN" \
                  -d '{"title":"Security: Fix container vulnerabilities","head":"security/fix-vulnerabilities-$(date +%Y%m%d)","base":"main"}' \
                  https://api.github.com/repos/$CI_PROJECT_PATH/pulls
              fi
          when: on_failure
          only:
            - schedules

🔍 容器运行时安全

运行时威胁检测

yaml
runtime_monitoring:
  behavioral_analysis:
    process_monitoring:
      falco_rules: |
        # Falco运行时检测规则
        - rule: Shell in container
          desc: Detect shell execution in container
          condition: >
            spawned_process and container and
            shell_procs and proc.tty != 0
          output: >
            Shell spawned in container
            (user=%user.name command=%proc.cmdline container_id=%container.id image=%container.image.repository)
          priority: WARNING
        
        - rule: File below etc opened for writing
          desc: Detect attempt to write to /etc directory
          condition: >
            open_write and container and
            fd.filename startswith /etc
          output: >
            File below /etc opened for writing
            (user=%user.name command=%proc.cmdline file=%fd.name container_id=%container.id image=%container.image.repository)
          priority: ERROR
        
        - rule: Unexpected outbound connection
          desc: Detect unexpected outbound network connection
          condition: >
            outbound and container and
            not fd.sport in (http_port, https_port, dns_port) and
            not fd.dip in (allowed_outbound_ips)
          output: >
            Unexpected outbound connection
            (user=%user.name command=%proc.cmdline dest=%fd.dip port=%fd.dport container_id=%container.id)
          priority: WARNING
      
      custom_rules: |
        # 自定义安全规则
        - rule: Cryptocurrency Mining Detection
          desc: Detect potential cryptocurrency mining activity
          condition: >
            spawned_process and container and
            (proc.name in (cryptomining_processes) or
             proc.cmdline contains "stratum" or
             proc.cmdline contains "mining")
          output: >
            Potential cryptocurrency mining detected
            (user=%user.name command=%proc.cmdline container_id=%container.id)
          priority: CRITICAL
        
        - rule: Privilege Escalation Attempt
          desc: Detect attempts to escalate privileges
          condition: >
            spawned_process and container and
            (proc.name in (privilege_escalation_binaries) or
             proc.cmdline contains "sudo" or
             proc.cmdline contains "su -")
          output: >
            Privilege escalation attempt detected
            (user=%user.name command=%proc.cmdline container_id=%container.id)
          priority: HIGH
    
    network_monitoring:
      istio_security_policies: |
        # Istio安全策略监控
        apiVersion: security.istio.io/v1beta1
        kind: AuthorizationPolicy
        metadata:
          name: deny-suspicious-traffic
          namespace: production
        spec:
          rules:
          - to:
            - operation:
                methods: ["GET", "POST"]
          - when:
            - key: source.ip
              notValues: ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"]
            then:
            - key: custom.action
              values: ["DENY"]
      
      network_policies: |
        # Kubernetes网络策略
        apiVersion: networking.k8s.io/v1
        kind: NetworkPolicy
        metadata:
          name: default-deny-all
          namespace: production
        spec:
          podSelector: {}
          policyTypes:
          - Ingress
          - Egress
        ---
        apiVersion: networking.k8s.io/v1
        kind: NetworkPolicy
        metadata:
          name: allow-frontend-backend
          namespace: production
        spec:
          podSelector:
            matchLabels:
              app: backend
          policyTypes:
          - Ingress
          ingress:
          - from:
            - podSelector:
                matchLabels:
                  app: frontend
            ports:
            - protocol: TCP
              port: 8080
          - from: []
            ports:
            - protocol: TCP
              port: 8090  # 健康检查端口
  
  container_isolation:
    security_contexts:
      secure_pod_config: |
        # 安全的Pod配置
        apiVersion: v1
        kind: Pod
        metadata:
          name: secure-app
        spec:
          securityContext:
            runAsNonRoot: true
            runAsUser: 1000
            runAsGroup: 1000
            fsGroup: 1000
            seccompProfile:
              type: RuntimeDefault
            supplementalGroups: [1000]
          
          containers:
          - name: app
            image: myapp:v1.0
            securityContext:
              allowPrivilegeEscalation: false
              readOnlyRootFilesystem: true
              runAsNonRoot: true
              runAsUser: 1000
              capabilities:
                drop:
                - ALL
                add:
                - NET_BIND_SERVICE  # 仅添加必需的能力
            
            resources:
              limits:
                cpu: "1"
                memory: "512Mi"
                ephemeral-storage: "1Gi"
              requests:
                cpu: "100m"
                memory: "128Mi"
                ephemeral-storage: "100Mi"
            
            volumeMounts:
            - name: tmp-volume
              mountPath: /tmp
            - name: cache-volume
              mountPath: /app/cache
          
          volumes:
          - name: tmp-volume
            emptyDir: {}
          - name: cache-volume
            emptyDir: {}
      
      pod_security_standards: |
        # Pod Security Standards配置
        apiVersion: v1
        kind: Namespace
        metadata:
          name: secure-workloads
          labels:
            pod-security.kubernetes.io/enforce: restricted
            pod-security.kubernetes.io/audit: restricted
            pod-security.kubernetes.io/warn: restricted
        
        # 自定义PSS策略
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: pss-policy
        data:
          policy: |
            apiVersion: pod-security.kubernetes.io/v1beta1
            kind: PodSecurityPolicy
            metadata:
              name: restricted-psp
            spec:
              privileged: false
              allowPrivilegeEscalation: false
              requiredDropCapabilities:
                - ALL
              volumes:
                - configMap
                - emptyDir
                - projected
                - secret
                - downwardAPI
                - persistentVolumeClaim
              runAsUser:
                rule: MustRunAsNonRoot
              seLinux:
                rule: RunAsAny
              fsGroup:
                rule: RunAsAny
    
    runtime_protection:
      gvisor_integration: |
        # gVisor运行时配置
        apiVersion: node.k8s.io/v1
        kind: RuntimeClass
        metadata:
          name: gvisor
        handler: runsc
        overhead:
          podFixed:
            memory: "20Mi"
            cpu: "10m"
        scheduling:
          nodeClassForScheduling: "gvisor-nodes"
        ---
        apiVersion: v1
        kind: Pod
        metadata:
          name: secure-pod
        spec:
          runtimeClassName: gvisor
          containers:
          - name: app
            image: myapp:v1.0
      
      kata_containers: |
        # Kata Containers配置
        apiVersion: node.k8s.io/v1
        kind: RuntimeClass
        metadata:
          name: kata
        handler: kata
        overhead:
          podFixed:
            memory: "130Mi"
            cpu: "250m"
        ---
        # 使用Kata运行时的Pod
        apiVersion: v1
        kind: Pod
        metadata:
          name: isolated-pod
        spec:
          runtimeClassName: kata
          containers:
          - name: app
            image: untrusted-app:latest
yaml
threat_response:
  automated_response:
    policy_enforcement: |
      # OPA Gatekeeper自动响应
      apiVersion: templates.gatekeeper.sh/v1beta1
      kind: ConstraintTemplate
      metadata:
        name: k8srequiredsecuritycontext
      spec:
        crd:
          spec:
            names:
              kind: K8sRequiredSecurityContext
            validation:
              properties:
                runAsNonRoot:
                  type: boolean
        targets:
          - target: admission.k8s.gatekeeper.sh
            rego: |
              package k8srequiredsecuritycontext
              
              violation[{"msg": msg}] {
                container := input.review.object.spec.containers[_]
                not container.securityContext.runAsNonRoot
                msg := "Container must run as non-root user"
              }
              
              violation[{"msg": msg}] {
                container := input.review.object.spec.containers[_]
                container.securityContext.privileged
                msg := "Container must not run in privileged mode"
              }
    
    incident_response: |
      # 事件响应自动化
      apiVersion: batch/v1
      kind: Job
      metadata:
        name: security-incident-response
      spec:
        template:
          spec:
            containers:
            - name: responder
              image: security-tools:latest
              command:
              - /bin/bash
              - -c
              - |
                # 检测到安全事件时的响应动作
                
                # 1. 隔离受影响的Pod
                kubectl delete pod $COMPROMISED_POD --grace-period=0
                
                # 2. 阻止网络访问
                kubectl apply -f - <<EOF
                apiVersion: networking.k8s.io/v1
                kind: NetworkPolicy
                metadata:
                  name: quarantine-${INCIDENT_ID}
                  namespace: ${NAMESPACE}
                spec:
                  podSelector:
                    matchLabels:
                      incident-id: ${INCIDENT_ID}
                  policyTypes:
                  - Ingress
                  - Egress
                EOF
                
                # 3. 收集证据
                kubectl logs $COMPROMISED_POD --previous > /evidence/pod-logs.txt
                kubectl describe pod $COMPROMISED_POD > /evidence/pod-details.txt
                
                # 4. 通知安全团队
                curl -X POST -H 'Content-type: application/json' \
                  --data '{"text":"Security incident detected: '"$INCIDENT_DESCRIPTION"'"}' \
                  $SLACK_WEBHOOK_URL
            restartPolicy: Never
  
  forensic_analysis:
    evidence_collection: |
      # 容器取证工具
      #!/bin/bash
      
      CONTAINER_ID=$1
      EVIDENCE_DIR="/tmp/evidence-$(date +%Y%m%d-%H%M%S)"
      mkdir -p $EVIDENCE_DIR
      
      # 收集容器信息
      docker inspect $CONTAINER_ID > $EVIDENCE_DIR/container-info.json
      docker logs $CONTAINER_ID > $EVIDENCE_DIR/container-logs.txt
      
      # 收集进程信息
      docker exec $CONTAINER_ID ps aux > $EVIDENCE_DIR/processes.txt
      
      # 收集网络连接
      docker exec $CONTAINER_ID netstat -tuln > $EVIDENCE_DIR/network-connections.txt
      
      # 收集文件系统变更
      docker diff $CONTAINER_ID > $EVIDENCE_DIR/filesystem-changes.txt
      
      # 内存转储 (如果可能)
      if command -v gcore >/dev/null 2>&1; then
        PID=$(docker inspect -f '{{.State.Pid}}' $CONTAINER_ID)
        gcore -o $EVIDENCE_DIR/memory-dump $PID
      fi
      
      # 创建证据包
      tar -czf evidence-$CONTAINER_ID.tar.gz $EVIDENCE_DIR
      
      echo "Evidence collected in evidence-$CONTAINER_ID.tar.gz"
    
    timeline_reconstruction: |
      # 时间线重建脚本
      #!/usr/bin/env python3
      
      import json
      import subprocess
      from datetime import datetime
      
      def collect_timeline_events(container_id):
          events = []
          
          # Docker事件
          result = subprocess.run(['docker', 'events', '--since', '1h', '--filter', f'container={container_id}', '--format', '{{.Time}} {{.Action}} {{.Actor.Attributes.name}}'], 
                                capture_output=True, text=True)
          
          for line in result.stdout.split('\n'):
              if line.strip():
                  parts = line.split(' ', 2)
                  events.append({
                      'timestamp': parts[0],
                      'event_type': 'docker',
                      'action': parts[1],
                      'details': parts[2] if len(parts) > 2 else ''
                  })
          
          # 系统调用日志 (如果有sysdig)
          try:
              result = subprocess.run(['sysdig', '-r', f'/tmp/{container_id}.scap', '-c', 'topprocs_cpu'], 
                                    capture_output=True, text=True)
              # 解析sysdig输出...
          except FileNotFoundError:
              pass
          
          # 按时间排序
          events.sort(key=lambda x: x['timestamp'])
          
          return events
      
      def generate_report(events, output_file):
          with open(output_file, 'w') as f:
              f.write("Security Incident Timeline Report\n")
              f.write("=" * 40 + "\n\n")
              
              for event in events:
                  f.write(f"[{event['timestamp']}] {event['event_type']}: {event['action']}\n")
                  if event['details']:
                      f.write(f"  Details: {event['details']}\n")
                  f.write("\n")
      
      if __name__ == "__main__":
          import sys
          if len(sys.argv) != 2:
              print("Usage: timeline_reconstruction.py <container_id>")
              sys.exit(1)
          
          container_id = sys.argv[1]
          events = collect_timeline_events(container_id)
          generate_report(events, f"timeline-{container_id}.txt")

📋 容器安全面试重点

基础概念类

  1. 容器与传统虚拟化的安全差异?

    • 共享内核的安全风险
    • 容器逃逸攻击向量
    • 隔离机制对比
    • 攻击面分析
  2. 容器安全生命周期的关键阶段?

    • 开发阶段安全左移
    • 构建阶段供应链安全
    • 运行时威胁检测
    • 事件响应和取证
  3. Docker安全的最佳实践?

    • 最小化基础镜像
    • 非root用户运行
    • 只读文件系统
    • 安全上下文配置

威胁检测类

  1. 如何检测容器逃逸攻击?

    • 行为异常监控
    • 系统调用分析
    • 进程树异常
    • 文件系统监控
  2. 容器运行时安全监控工具?

    • Falco规则引擎
    • Sysdig监控分析
    • Aqua运行时保护
    • Twistlock安全扫描
  3. 供应链攻击的防护策略?

    • 镜像签名验证
    • SBOM软件清单
    • 依赖漏洞扫描
    • 可信构建环境

技术实现类

  1. Kubernetes Pod安全配置?

    • SecurityContext设置
    • Pod Security Standards
    • 网络策略配置
    • 资源限制设置
  2. 容器镜像安全扫描实现?

    • 静态漏洞扫描
    • 动态行为分析
    • 恶意软件检测
    • 配置错误检查
  3. 容器隔离技术对比?

    • gVisor用户空间内核
    • Kata Containers虚拟化
    • Firecracker微虚拟机
    • 传统Linux容器

🔗 相关内容


容器安全是云原生安全的基石,需要从开发、构建、部署到运行的全生命周期进行安全防护。通过实施分层防御策略、持续监控和自动化响应,可以有效保护容器化应用免受各种安全威胁。

正在精进