目录
2、安全架构全景图
7、内核级安全隔离:Seccomp/AppArmor/SELinux
9、文末三件套
10、总结
开篇:安全左移,从源头开始
你是否遇到过镜像漏洞被黑客利用、运行时异常行为没发现、安全策略靠人工检查的被动局面?云原生安全需要"左移"——在构建时就发现问题。本文将给出生产级安全扫描方案。
💡 效率技巧:安全左移(Shift Left Security)的核心思想是:问题发现得越早,修复成本越低。根据IBM的研究,生产环境发现的安全问题修复成本是开发阶段的100倍!
想象一下:你辛辛苦苦搭建的Kubernetes集群,就像一座精心设计的城堡。但如果你的"砖块"(容器镜像)本身就藏着定时炸弹,再厚的城墙也没用。这就是为什么我们需要一套从构建到运行的全方位安全方案。
安全架构全景图
在深入各个工具之前,让我们先看看整体架构:
┌─────────────────────────────────────────────────────────────────────────────┐
│ 云原生安全防线全景图 │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ 【构建阶段】 【镜像仓库】 【部署阶段】 【运行阶段】 │
│ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ 代码提交 │─────▶│ 镜像扫描 │──────▶│ 策略检查 │─────▶│ 实时监控 │ │
│ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ │
│ │ │ │ │ │
│ ▼ ▼ ▼ ▼ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ Trivy │ │ Notary │ │ OPA │ │ Falco │ │
│ │ 漏洞扫描 │ │ 镜像签名 │ │ 准入控制 │ │ 异常检测 │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
│ │ │ │ │ │
│ ▼ ▼ ▼ ▼ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ Clair │ │ Cosign │ │ Kyverno │ │ Seccomp │ │
│ │ 漏洞分析 │ │ 密钥签名 │ │ 策略引擎 │ │ AppArmor │ │
│ └──────────┘ └──────────┘ └──────────┘ │ SELinux │ │
│ └──────────┘ │
│ │
│ ═══════════════════════════════════════════════════════════════════════ │
│ │
│ 【安全数据流】 │
│ │
│ Developer ──git push──▶ CI Pipeline ──scan──▶ Registry ──sign──▶ K8s │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌────────┐ ┌────────┐ ┌────────┐ │
│ │ 阻断 │ │ 验证 │ │ 监控 │ │
│ └────────┘ └────────┘ └────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
⚠️ 避坑警告:很多团队只关注运行时的安全防护,却忽视了构建阶段的安全扫描。这就像在漏水的船上拼命往外舀水——治标不治本。
Trivy:CI阶段的"漏洞猎手"
为什么选Trivy?
Trivy是Aqua Security开源的容器镜像漏洞扫描工具,它就像一位不知疲倦的"漏洞猎手",能在几秒钟内找出镜像里的安全隐患。
核心优势:
- 🚀 极速扫描:< 5秒/镜像(实测比Clair快10倍以上)
- 📦 开箱即用:无需数据库初始化,自动更新漏洞库
- 🔍 全面覆盖:支持OS包、语言依赖、配置文件扫描
- 💰 完全免费:Apache 2.0协议,商用无忧
💡 效率技巧:Trivy的扫描速度之所以快,是因为它采用了轻量级的漏洞数据库,并且支持本地缓存。第一次扫描后,后续扫描会更快!
快速上手
# 安装Trivy(以Linux为例)
curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin
# 扫描单个镜像
trivy image nginx:latest
# 只显示高危和严重漏洞
trivy image --severity HIGH,CRITICAL nginx:latest
# 输出JSON格式(适合CI集成)
trivy image --format json --output report.json nginx:latest
# 扫描本地Dockerfile
trivy config ./Dockerfile
# 扫描文件系统
trivy filesystem /path/to/project
GitHub Actions集成
# .github/workflows/security-scan.yml
name: Security Scan
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main ]
jobs:
trivy-scan:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Build Docker image
run: docker build -t myapp:${{ github.sha }} .
- name: Run Trivy vulnerability scanner
uses: aquasecurity/trivy-action@master
with:
image-ref: 'myapp:${{ github.sha }}'
format: 'sarif'
output: 'trivy-results.sarif'
severity: 'CRITICAL,HIGH'
exit-code: '1' # 发现高危漏洞时阻断构建
- name: Upload scan results
uses: github/codeql-action/upload-sarif@v2
if: always()
with:
sarif_file: 'trivy-results.sarif'
⚠️ 避坑警告:默认情况下Trivy会扫描所有漏洞,包括低危的。建议在CI中设置
--severity HIGH,CRITICAL,否则会被海量低危漏洞淹没。
实战:扫描结果分析
$ trivy image --severity HIGH,CRITICAL python:3.9-slim
python:3.9-slim (debian 11.7)
==============================
Total: 45 (HIGH: 32, CRITICAL: 13)
┌──────────────────┬────────────────┬──────────┬─────────────────────┬─────────────────────┬─────────────────────────────────────────────┐
│ Library │ Vulnerability │ Severity │ Installed Version │ Fixed Version │ Title │
├──────────────────┼────────────────┼──────────┼─────────────────────┼─────────────────────┼─────────────────────────────────────────────┤
│ libssl1.1 │ CVE-2023-0286 │ CRITICAL │ 1.1.1n-0+deb11u4 │ 1.1.1n-0+deb11u5 │ openssl: X.400 address type confusion in │
│ │ │ │ │ │ X.509 GeneralName │
├──────────────────┼────────────────┼──────────┼─────────────────────┼─────────────────────┼─────────────────────────────────────────────┤
│ zlib1g │ CVE-2022-37434 │ CRITICAL │ 1:1.2.11.dfsg-2+... │ 1:1.2.11.dfsg-2+... │ zlib: heap-based buffer over-read │
└──────────────────┴────────────────┴──────────┴─────────────────────┴─────────────────────┴─────────────────────────────────────────────┘
看到这一堆CVE编号,是不是有点头大?别担心,重点关注Fixed Version列——只要升级到指定版本,漏洞就消失了。
Clair:Red Hat的"安全老将"
Clair vs Trivy
如果说Trivy是"小鲜肉",那Clair就是"老江湖"。作为CoreOS(后被Red Hat收购)开发的项目,Clair已经在生产环境摸爬滚打多年。
| 特性 | Clair | Trivy |
|---|---|---|
| 扫描速度 | 较慢(需拉取数据库) | < 5秒/镜像 |
| 数据库管理 | 需自建/维护 | 自动更新 |
| Notary集成 | ✅ 原生支持 | ❌ 需额外配置 |
| 镜像签名验证 | ✅ 内置 | ❌ 第三方工具 |
| 企业支持 | Red Hat背书 | Aqua Security |
💡 效率技巧:如果你的团队已经在使用Red Hat生态(OpenShift、Quay等),Clair是更自然的选择,因为它与这些工具深度集成。
Clair架构解析
┌─────────────────────────────────────────────────────────────────┐
│ Clair 架构图 │
├─────────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Indexer │───▶│ Matcher │───▶│ Notifier │ │
│ │ (索引服务) │ │ (匹配服务) │ │ (通知服务) │ │
│ └──────┬───────┘ └──────┬───────┘ └──────────────┘ │
│ │ │ │
│ ▼ ▼ │
│ ┌──────────────┐ ┌──────────────┐ │
│ │ Layer Blob │ │ Vuln DB │ │
│ │ (镜像层) │ │ (漏洞库) │ │
│ └──────────────┘ └──────────────┘ │
│ │
│ 工作流程: │
│ 1. Indexer分析镜像层,提取包信息 │
│ 2. Matcher将包信息与漏洞库匹配 │
│ 3. Notifier发送漏洞报告 │
│ │
└─────────────────────────────────────────────────────────────────┘
部署Clair(Docker Compose方式)
# docker-compose.yml
version: '3.8'
services:
clair-db:
image: postgres:15-alpine
environment:
POSTGRES_PASSWORD: clairpassword
POSTGRES_DB: clair
volumes:
- clair-db-data:/var/lib/postgresql/data
clair:
image: quay.io/projectquay/clair:4.7.0
depends_on:
- clair-db
environment:
CLAIR_CONF: |
indexer:
connstring: host=clair-db port=5432 user=postgres password=clairpassword dbname=clair sslmode=disable
matcher:
connstring: host=clair-db port=5432 user=postgres password=clairpassword dbname=clair sslmode=disable
notifiers:
connstring: host=clair-db port=5432 user=postgres password=clairpassword dbname=clair sslmode=disable
command: ["-conf", "/etc/clair/config.yaml"]
ports:
- "6060:6060"
volumes:
clair-db-data:
Notary签名验证
Clair的一大特色是原生支持Docker Content Trust(Notary)签名验证:
# 启用Docker Content Trust
export DOCKER_CONTENT_TRUST=1
# 拉取签名镜像
docker pull myregistry.com/myapp:v1.0
# 使用clairctl扫描并验证签名
clairctl report --host http://localhost:6060 myregistry.com/myapp:v1.0
⚠️ 避坑警告:Clair的数据库初始化时间较长,首次启动可能需要几分钟。建议在生产环境使用预先填充数据的数据库镜像。
OPA:策略即代码的"守门员"
什么是OPA?
Open Policy Agent(OPA)是CNCF毕业项目,它把安全策略从"人治"变成"法治"。想象一下:以前靠人工审核的部署请求,现在用代码自动判断——这就是策略即代码(Policy as Code)的魅力。
OPA能做什么?
- 🔐 Kubernetes准入控制(Admission Control)
- 🌐 API网关授权
- 📊 微服务间访问控制
- 🏗️ Terraform计划审查
💡 效率技巧:OPA使用声明式语言Rego编写策略,学习曲线有点陡,但一旦掌握,你会发现它比传统RBAC灵活得多。
OPA在Kubernetes中的位置
┌─────────────────────────────────────────────────────────────────┐
│ Kubernetes + OPA 架构 │
├─────────────────────────────────────────────────────────────────┤
│ │
│ User ──kubectl apply──▶ API Server ──Webhook──▶ OPA/Gatekeeper │
│ │ │
│ ▼ │
│ ┌─────────────┴─┐
│ │ 策略评估引擎 │
│ │ │
│ │ rego策略文件 │
│ │ - 禁止特权容器 │
│ │ - 强制资源限制 │
│ │ - 要求标签 │
│ └───────┬───────┘
│ │
│ ▼
│ ┌───────────────┐
│ │ Allow / Deny │
│ └───────────────┘
│ │
│ 工作流程: │
│ 1. 用户提交资源定义(Pod/Deployment等) │
│ 2. API Server调用OPA Webhook │
│ 3. OPA评估策略,返回允许/拒绝 │
│ 4. 只有符合策略的资源才能创建 │
│ │
└─────────────────────────────────────────────────────────────────┘
实战:禁止特权容器
# policy/restrict-privileged.rego
package kubernetes.admission
import rego.v1
# 默认拒绝
default allow := false
# 允许非特权容器
allow if {
input.request.kind.kind == "Pod"
not is_privileged
}
# 检测特权容器
is_privileged if {
container := input.request.object.spec.containers[_]
container.securityContext.privileged == true
}
# 拒绝信息
deny contains msg if {
is_privileged
msg := "特权容器被禁止!请移除securityContext.privileged"
}
Gatekeeper安装与使用
Gatekeeper是OPA的Kubernetes集成项目,提供了更友好的CRD方式管理策略:
# 安装Gatekeeper
kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/master/deploy/gatekeeper.yaml
# 等待部署完成
kubectl wait --for=condition=Ready pod -l control-plane=controller-manager -n gatekeeper-system --timeout=120s
# 创建约束模板(ConstraintTemplate)
cat <<EOF | kubectl apply -f -
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8srequiredlabels
spec:
crd:
spec:
names:
kind: K8sRequiredLabels
validation:
type: object
properties:
labels:
type: array
items:
type: string
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8srequiredlabels
violation[{"msg": msg}] {
provided := {label | input.review.object.metadata.labels[label]}
required := {label | label := input.parameters.labels[_]}
missing := required - provided
count(missing) > 0
msg := sprintf("必须包含标签: %v", [missing])
}
EOF
# 创建约束(要求所有Namespace必须有team标签)
cat <<EOF | kubectl apply -f -
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
name: ns-must-have-team
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Namespace"]
parameters:
labels: ["team"]
EOF
# 测试:创建没有team标签的Namespace会被拒绝
kubectl create namespace test-ns
# Error from server (Forbidden): admission webhook "validation.gatekeeper.sh" denied the request: [ns-must-have-team] 必须包含标签: {"team"}
# 创建带标签的Namespace成功
kubectl create namespace test-ns --label team=platform
⚠️ 避坑警告:Gatekeeper的策略是异步生效的,刚创建约束后立即测试可能会"漏网"。建议等待几秒再验证。
Falco:运行时的"安全摄像头"
Falco是什么?
Falco由Sysdig捐赠给CNCF,是云原生领域的"安全摄像头"。它在运行时监控系统调用,检测异常行为,就像给服务器装了一个24小时不间断的监控探头。
核心能力:
- 🎯 系统调用监控:基于eBPF或内核模块
- ⚡ 低延迟检测:规则命中延迟 < 100ms
- 📜 丰富规则库:内置100+检测规则
- 🔗 多平台输出:支持Slack、PagerDuty、Webhook等
💡 效率技巧:Falco的规则文件使用YAML格式,支持宏(Macros)和列表(Lists),可以像搭积木一样组合复杂的检测逻辑。
Falco架构图
┌─────────────────────────────────────────────────────────────────┐
│ Falco 架构图 │
├─────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ Linux Kernel │ │
│ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────────┐ │ │
│ │ │ eBPF Probe │ │Kernel Module│ │ Userspace Probe │ │ │
│ │ │ (推荐) │ │ (传统) │ │ (gVisor等) │ │ │
│ │ └──────┬──────┘ └──────┬──────┘ └────────┬────────┘ │ │
│ │ └─────────────────┴──────────────────┘ │ │
│ │ │ │ │
│ │ ▼ │ │
│ │ ┌─────────────────┐ │ │
│ │ │ System Calls │ │ │
│ │ │ (系统调用流) │ │ │
│ │ └────────┬────────┘ │ │
│ └───────────────────────────┼───────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ Falco Daemon │ │
│ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────────┐ │ │
│ │ │ Event Engine│──▶ Rule Engine │──▶ Output Manager │ │ │
│ │ │ (事件处理) │ │ (规则匹配) │ │ (告警输出) │ │ │
│ │ └─────────────┘ └─────────────┘ └─────────────────┘ │ │
│ │ │ │ │ │ │
│ │ ▼ ▼ ▼ │ │
│ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │
│ │ │ Raw Events │ │ YAML Rules │ │ Slack │ │ │
│ │ │ (原始事件) │ │ (检测规则) │ │ PagerDuty │ │ │
│ │ │ │ │ - 异常进程 │ │ Webhook │ │ │
│ │ │ │ │ - 文件篡改 │ │ stdout │ │ │
│ │ │ │ │ - 网络连接 │ │ File │ │ │
│ │ └─────────────┘ └─────────────┘ └─────────────┘ │ │
│ └─────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────┘
安装Falco
# 添加Falco Helm仓库
helm repo add falcosecurity https://falcosecurity.github.io/charts
helm repo update
# 安装Falco(使用eBPF驱动)
helm install falco falcosecurity/falco \
--namespace falco \
--create-namespace \
--set driver.kind=ebpf \
--set tty=true
# 查看Falco日志
kubectl logs -n falco -l app.kubernetes.io/name=falco -f
实战:检测反向Shell
反向Shell是黑客常用的攻击手段,Falco可以轻易检测:
# 自定义规则:检测反向Shell
- rule: Reverse Shell
desc: "检测到可能的反向Shell活动"
condition: >
spawned_process and
(
(proc.name = "bash" or proc.name = "sh") and
(fd.name contains "/dev/tcp/" or fd.name contains "/dev/udp/")
) or
(
proc.name = "nc" and
(proc.args contains "-e" or proc.args contains "-c")
) or
(
proc.name = "python" and
(proc.args contains "socket" or proc.args contains "subprocess")
)
output: >
反向Shell检测:
用户=%user.name
命令=%proc.cmdline
容器=%container.name
命名空间=%k8s.ns.name
priority: CRITICAL
实战:检测敏感文件访问
# 检测/etc/shadow等敏感文件被读取
- rule: Read Sensitive File
desc: "检测到敏感文件被读取"
condition: >
open_read and
(fd.name contains "/etc/shadow" or
fd.name contains "/etc/passwd" or
fd.name contains "/etc/kubernetes/admin.conf" or
fd.name contains "/root/.ssh/")
and not proc.name in ("cat", "less", "more", "vim")
output: >
敏感文件访问:
用户=%user.name
进程=%proc.name
文件=%fd.name
容器=%container.name
priority: WARNING
与Alertmanager集成
# falcosidekick配置,发送告警到Alertmanager
helm upgrade falco falcosecurity/falco \
--namespace falco \
--set falcosidekick.enabled=true \
--set falcosidekick.config.alertmanager.hostport=http://alertmanager:9093
⚠️ 避坑警告:Falco的eBPF驱动在某些内核版本上可能不兼容。如果遇到问题,可以尝试切换到内核模块驱动(
--set driver.kind=kmod)。
内核级安全隔离:Seccomp/AppArmor/SELinux
如果把容器比作公寓,Seccomp/AppArmor/SELinux就是门锁、监控和保安——它们在内核层面限制容器能做什么。
三种机制对比
| 特性 | Seccomp | AppArmor | SELinux |
|---|---|---|---|
| 层级 | 系统调用过滤 | 文件/网络访问控制 | 强制访问控制(MAC) |
| 复杂度 | 中等 | 较低 | 较高 |
| 默认发行版 | 通用 | Ubuntu/Debian | RHEL/CentOS/Fedora |
| 学习曲线 | 中等 | 平缓 | 陡峭 |
| 灵活性 | 高 | 中 | 高 |
💡 效率技巧:Kubernetes默认启用了RuntimeDefault Seccomp策略,但大多数镜像还是以Unconfined模式运行。建议显式指定Seccomp配置文件。
Seccomp实战
Seccomp(Secure Computing Mode)通过过滤系统调用限制容器权限:
# seccomp-profile.json - 自定义Seccomp配置
{
"defaultAction": "SCMP_ACT_ERRNO",
"architectures": ["SCMP_ARCH_X86_64", "SCMP_ARCH_X86"],
"syscalls": [
{
"names": [
"accept", "accept4", "access", "adjtimex", "alarm", "bind",
"brk", "capget", "capset", "chdir", "chmod", "chown", "clock_gettime",
"clone", "close", "connect", "copy_file_range", "creat"
],
"action": "SCMP_ACT_ALLOW"
},
{
"names": ["execve", "execveat"],
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"names": ["mount", "umount2", "pivot_root"],
"action": "SCMP_ACT_ERRNO"
}
]
}
# Pod中使用自定义Seccomp配置
apiVersion: v1
kind: Pod
metadata:
name: secure-pod
spec:
securityContext:
seccompProfile:
type: Localhost
localhostProfile: my-custom-profile.json
containers:
- name: app
image: myapp:v1.0
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
runAsNonRoot: true
runAsUser: 1000
capabilities:
drop:
- ALL
AppArmor实战
AppArmor使用路径-based的配置,更容易上手:
# /etc/apparmor.d/docker-nginx
#include <tunables/global>
profile docker-nginx flags=(attach_disconnected,mediate_deleted) {
#include <abstractions/base>
network inet tcp,
network inet udp,
network inet icmp,
deny network raw,
deny network packet,
file,
deny /etc/passwd r,
deny /etc/shadow r,
deny /root/** r,
deny /proc/sys/** w,
deny /sys/** w,
capability chown,
capability dac_override,
capability setuid,
capability setgid,
capability net_bind_service,
deny capability sys_admin,
deny capability sys_ptrace,
deny capability sys_module,
}
# Kubernetes中使用AppArmor
apiVersion: v1
kind: Pod
metadata:
name: nginx-apparmor
annotations:
container.apparmor.security.beta.kubernetes.io/nginx: localhost/docker-nginx
spec:
containers:
- name: nginx
image: nginx:alpine
SELinux实战
SELinux使用标签(Label)系统控制访问:
# 查看容器的SELinux标签
kubectl get pod mypod -o yaml | grep seLinuxOptions
# 在Pod中指定SELinux选项
apiVersion: v1
kind: Pod
metadata:
name: selinux-pod
spec:
securityContext:
seLinuxOptions:
level: "s0:c123,c456"
role: "system_r"
type: "spc_t"
user: "system_u"
containers:
- name: app
image: myapp:v1.0
securityContext:
seLinuxOptions:
level: "s0:c123,c456"
⚠️ 避坑警告:SELinux的调试非常困难,建议先用
setenforce 0临时关闭,确认问题确实由SELinux引起后再调整策略。
完整CI/CD安全流水线实战
架构图
┌─────────────────────────────────────────────────────────────────────────────┐
│ 完整CI/CD安全流水线架构 │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ Developer │
│ │ │
│ │ git push │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ GitHub Actions │ │
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │
│ │ │ 代码扫描 │─▶│ 单元测试 │─▶│ 构建镜像 │─▶│ Trivy扫描 │ │ │
│ │ │ CodeQL │ │ │ │ │ │ 漏洞检测 │ │ │
│ │ └──────────┘ └──────────┘ └──────────┘ └────┬─────┘ │ │
│ │ │ │ │
│ │ ┌───────────────────────────────────────────────┘ │ │
│ │ │ │ │
│ │ ▼ │ │
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │
│ │ │ 扫描通过? │─▶│ 镜像签名 │─▶│ 推送仓库 │ │ │
│ │ │ │ │ Cosign │ │ │ │ │
│ │ └──────────┘ └──────────┘ └────┬─────┘ │ │
│ │ │ │ │
│ └───────────────────────────────────┼─────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ Harbor Registry │ │
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │
│ │ │ 镜像存储 │ │ 漏洞扫描 │ │ 签名验证 │ │ │
│ │ │ │ │ (Clair) │ │ (Notary) │ │ │
│ │ └──────────┘ └──────────┘ └──────────┘ │ │
│ └───────────────────────────────────┬─────────────────────────────────┘ │
│ │ │
│ │ webhook │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ Kubernetes Cluster │ │
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │
│ │ │ OPA/Gate │─▶│ 准入控制 │─▶│ Pod创建 │─▶│ Falco监控 │ │ │
│ │ │ -keeper │ │ │ │ │ │ │ │ │
│ │ └──────────┘ └──────────┘ └──────────┘ └────┬─────┘ │ │
│ │ │ │ │
│ │ ┌───────────────────────────────────────────────┘ │ │
│ │ │ │ │
│ │ ▼ │ │
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │
│ │ │ Seccomp │ │AppArmor │ │ 运行时 │ │ │
│ │ │ 限制 │ │ 限制 │ │ 保护 │ │ │
│ │ └──────────┘ └──────────┘ └──────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │
│ ═══════════════════════════════════════════════════════════════════════ │
│ │
│ 【告警与响应】 │
│ │
│ Falco ──▶ Alertmanager ──▶ PagerDuty/Slack/邮件 │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
完整GitHub Actions工作流
# .github/workflows/complete-security-pipeline.yml
name: Complete Security Pipeline
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
jobs:
# 阶段1:代码安全扫描
code-scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: go, javascript
- name: Autobuild
uses: github/codeql-action/autobuild@v3
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
# 阶段2:构建与镜像扫描
build-and-scan:
runs-on: ubuntu-latest
needs: code-scan
permissions:
contents: read
packages: write
security-events: write
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Build image
run: |
docker build -t test-image:${{ github.sha }} .
- name: Run Trivy vulnerability scanner
uses: aquasecurity/trivy-action@master
with:
image-ref: 'test-image:${{ github.sha }}'
format: 'sarif'
output: 'trivy-results.sarif'
severity: 'CRITICAL,HIGH'
exit-code: '1'
- name: Upload Trivy scan results
uses: github/codeql-action/upload-sarif@v2
if: always()
with:
sarif_file: 'trivy-results.sarif'
# 阶段3:镜像签名与推送
sign-and-push:
runs-on: ubuntu-latest
needs: build-and-scan
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
permissions:
contents: read
packages: write
id-token: write
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to Container Registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}
- name: Install Cosign
uses: sigstore/cosign-installer@v3
- name: Sign image with Cosign
run: |
cosign sign --yes \
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}
Kubernetes安全策略配置
# security-policies.yaml
---
# 强制使用非root用户运行
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sPSPForbiddenRootUser
metadata:
name: forbid-root
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
excludedNamespaces: ["kube-system"]
---
# 强制资源限制
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredResources
metadata:
name: require-resources
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
parameters:
limits:
- cpu
- memory
---
# 禁止特权容器
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sPSPPrivilegedContainer
metadata:
name: deny-privileged
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
---
# 默认安全上下文
apiVersion: v1
kind: LimitRange
metadata:
name: default-security
namespace: default
spec:
limits:
- default:
cpu: "500m"
memory: "512Mi"
defaultRequest:
cpu: "100m"
memory: "128Mi"
type: Container
文末三件套
1. 【源码获取】
关注此系列获取后续更新,后台回复’安全’获取完整源码和配置文件!
2. 【思考题】
你们的安全扫描是在哪个阶段做的?
- A. 构建阶段(CI中扫描)
- B. 部署阶段(镜像仓库扫描)
- C. 运行阶段(实时监控)
- D. 以上都有
欢迎在评论区分享你的安全实践!
3. 【系列预告】
云原生进阶之路:
- 可观测性 → Prometheus + Grafana + Jaeger 构建可观测体系
- 高可用 → 多集群、灾备、自动故障转移
- 服务网格 → Istio深度实践,流量治理与安全防护
总结
云原生安全不是单一工具能解决的,需要构建从"构建-部署-运行"的全链路防护:
| 阶段 | 工具 | 作用 |
|---|---|---|
| 构建 | Trivy/Clair | 漏洞扫描 |
| 签名 | Cosign/Notary | 镜像签名验证 |
| 部署 | OPA/Gatekeeper | 策略准入控制 |
| 运行 | Falco | 异常行为检测 |
| 内核 | Seccomp/AppArmor/SELinux | 系统调用限制 |
记住:安全左移,从源头开始。在构建阶段发现问题,比在生产环境救火成本低100倍!
标签: Trivy Clair OPA Falco 安全扫描 容器安全 云原生安全
1538




被折叠的 条评论
为什么被折叠?



