内容简介:本文风哥教程参考Linux官方文档、Red Hat Enterprise Linux官方文档、Ansible Automation Platform官方文档、Docker官方文档、Kubernetes官方文档和Podman官方文档等内容,详细介绍了相关技术的配置和使用方法。
本文
风哥提示:
档介绍Kubernetes安全审计实战案例。
Part01-审计日志配置
1.1 启用API审计
[root@k8s-master ~]# cat > /etc/kubernetes/audit-policy.yaml << 'EOF' apiVersion: audit.k8s.io/v1 kind: Policy rules: # 记录所有请求 - level: Metadata # 忽略系统请求 - level: None users: ["system:kube-proxy", "system:node", "system:apiserver"] verbs: ["watch", "get", "list"] # 忽略健康检查 - level: None users: ["system:apiserver"] verbs: ["get"] resources: - group: "" resources: ["namespaces", "nodes", "nodes/status", "services", "services/status", "endpoints"] # 记录Secret访问 - level: RequestResponse resources: - group: "" resources: ["secrets"] # 记录认证失败 - level: Metadata omitStages: - "RequestReceived" # 记录配置变更 - level: RequestResponse resources: - group: "" resources: ["configmaps", "secrets"] - group: "apps" resources: ["deployments", "daemonsets", "statefulsets"] - group: "rbac.authorization.k8s.io" resources: ["roles", "rolebindings", "clusterroles", "clusterrolebindings"] verbs: ["create", "update", "patch", "delete"] # 记录Pod操作 - level: Request resources: - group: "" resources: ["pods"] verbs: ["create", "delete", "update"] EOF # 配置API Server审计 [root@k8s-master ~]# cat >> /etc/kubernetes/manifests/kube-apiserver.yaml << 'EOF' - --audit-policy-file=/etc/kubernetes/audit-policy.yaml - --audit-log-path=/var/log/kubernetes/audit.log - --audit-log-maxage=30 - --audit-log-maxbackup=10 - --audit-log-maxsize=100 - --audit-log-format=json volumeMounts: - mountPath: /etc/kubernetes/audit-policy.yaml name: audit readOnly: true - mountPath: /var/log/kubernetes name: audit-log readOnly: false volumes: - hostPath: path: /etc/kubernetes/audit-policy.yaml type: File name: audit - hostPath: path: /var/log/kubernetes type: DirectoryOrCreate name: audit-log EOF # 重启API Server [root@k8s-master ~]# mv /etc/kubernetes/manifests/kube-apiserver.yaml /tmp/ [root@k8s-master ~]# sleep 10 [root@k8s-master ~]# mv /tmp/kube-apiserver.yaml /etc/kubernetes/manifests/ # 验证审计日志 [root@k8s-master ~]# tail -1 /var/log/kubernetes/audit.log | jq { "kind": "Event", "apiVersion": "audit.k8s.io/v1", "level": "Metadata", "auditID": "abc123-def456", "stage": "ResponseComplete", "requestURI": "/api/v1/namespaces/default/pods", "verb": "list", "user": { "username": "admin", "groups": ["system:masters"] }, "sourceIPs": ["192.168.1.100"], "responseStatus": { "metadata": {}, "code": 200 }, "requestReceivedTimestamp": "2026-04-04T23:00:00.000000Z", "stageTimestamp": "2026-04-04T23:00:00.100000Z" }
Part02-安全扫描
2.1 容器安全扫描
[root@k8s-master ~]# rpm -ivh https://github.com/aquasecurity/trivy/releases/download/v0.47.0/trivy_0.47.0_Linux-64bit.rpm
Preparing… ################################# [100%]
Updating / installing…
1:trivy-0.47.0-1 ################################# [100%]
# 扫描镜像
[root@k8s-master ~]# trivy image nginx:1.25
2026-04-04T23:00:00.000+0800 INFO Need to update DB
2026-04-04T23:00:00.000+080学习交流加群风哥QQ1132571740 INFO Downloading DB…
2026-04-04T23:00:10.000+0800 INFO Analyzing OS packages…
nginx:1.25 (debian 12.2)
=========================
Total: 5 (UNKNOWN: 0, LOW: 2, MEDIUM: 2, HIGH: 1, CRITICAL: 0)
┌──────────────┬────────────────┬──────────┬───────────────────┬───────────────┐
│ Library │ Vulnerability │ Severity │ Installed Version │ Fixed Version │
├──────────────┼────────────────┼──────────┼───────────────────┼───────────────┤
│ libexpat1 │ CVE-2023-52425 │ HIGH │ 2.5.0-1 │ 2.5.0-1+deb12 │
├──────────────┼────────────────┼──────────┼───────────────────┼───────────────┤
│ openssl │ CVE-2023-5678 │ MEDIUM │ 3.0.11-1 │ 3.0.12-1 │
└──────────────┴────────────────┴──────────┴───────────────────┴───────────────┘
# 扫描Kubernetes配置
[root@k8s-master ~]# trivy config /etc/kubernetes
2026-04-04T23:00:00.000+0800 INFO Detected config files: 10
/etc/kubernetes/admin.conf (secrets)
====================================
Tests: 1 (SUCCESSES: 0, FAILURES: 1, EXCEPTIONS: 0)
Fafrom PG视频:www.itpux.comilures: 1 (UNKNOWN: 0, LOW: 0, MEDIUM: 0, HIGH: 1, CRITICAL: 0)
HIGH: Secret ‘client-certificate-data’ found in config file.
════════════════════════════════════════════════════════════════════════════════
Kubernetes configuration file contains secrets.
# 安装Falco运行时安全
[root@k8s-master ~]# helm repo add falcosecurity https://falcosecurity.github.io/charts
“falcosecurity” has been added to your repositories
[root@k8s-master ~]# helm install falco falcosecurity/falco -n falco –create-namespace
NAME: falco
LAST DEPLOYED: Sat Apr 4 23:00:00 2026
NAMESPACE: falco
STATUS: deployed
# 查看Falco日志
[root@k8s-master ~]# kubectl logs -n falco -l app=falco | tail -5
23:00:00.000000000: Notice A shell was spawned in a container with an attached terminal (user=root user_loginuid=-1 shell=bash parent=dockerd cmdline=bash terminal=34816 container_id=abc123 container_name=fgedu-app)
Part03-RBAC审计
3.1 权限审计
[root@k8s-master ~]# kubectl get sa -A
NAMESPACE NAME SECRETS AGE
default default 0 100d
kube-system attachdetach-controller 0 100d
kube-system certificate-controller 0 100d
kube-system clusterrole-aggregation-controller 0 100d
# 检查过度权限
[root@k8s-master ~]# kubectl auth can-i –list
Resources Non-Resource URLs Resource Names Verbs
*.* [] [] [*]
# 创建RBAC审计脚本
[root@k8s-master ~]# cat > /usr/local/bin/rbac-audit.sh << 'EOF'
#!/bin/bash
# rbac-audit.sh
# from:www.itpux.com.qq113257174.wx:itpux-com
# web: http://www.fgedu.net.cn
echo "=== RBAC权限审计报告 ==="
echo "生成时间: $(date)"
echo ""
echo "1. ClusterRoleBindings with cluster-admin"
echo "----------------------------------------"
kubectl get clusterrolebindings -o json | jq -r '.items[] | select(.roleRef.name=="cluster-admin") | .metadata.name'
echo ""
echo "2. ServiceAccounts with secrets"
echo "----------------------------------------"
kubectl get sa -A -o json | jq -r '.items[] | select(.secrets !=学习交流加群风哥微信: itpux-com null) | "\(.metadata.namespace)/\(.metadata.name)"'
echo ""
echo "3. Roles with wildcard permissions"
echo "----------------------------------------"
kubectl get roles -A -o json | jq -r '.items[] | select(.rules[]?.resources[]? == "*") | "\(.metadata.namespace)/\(.metadata.name)"'
echo ""
echo "4. Users with create pods permission"
echo "----------------------------------------"
kubectl auth can-i create pods --all-namespaces --as=system:anonymous
echo ""
echo "5. External IP services"
echo "----------------------------------------"
kubectl get svc -A -o json | jq -r '.items[] | select(.spec.externalIPs != null) | "\(.metadata.namespace)/\(.metadata.name): \(.spec.externalIPs)"'
echo ""
echo "=== 审计完成 ==="
EOF
[root@k8s-master ~]# chmod +x /usr/local/bin/rbac-audit.sh
# 执行RBAC审计
[root@k8s-master ~]# /usr/local/bin/rbac-audi更多学习教程公众号风哥教程itpux_comt.sh
=== RBAC权限审计报告 ===
生成时间: Sat Apr 4 23:00:00 CST 2026
1. ClusterRoleBindings with cluster-admin
----------------------------------------
cluster-admin
2. ServiceAccounts with secrets
----------------------------------------
default/default
3. Roles with wildcard permissions
----------------------------------------
fgedu-prod/fgedu-admin
4. Users with create pods permission
----------------------------------------
no
5. External IP services
----------------------------------------
fgedu-prod/fgedu-lb: ["192.168.1.200"]
=== 审计完成 ===
Part04-安全合规检查
4.1 合规性检查
[root@k8s-master ~]# kube-bench run –targets master,node –benchmark cis-1.8
[INFO] 1 Control Plane Security Configuration
[INFO] 1.1 Control Plane Node Configuration Files
[PASS] 1.1.1 Ensure that the API server pod specification file permissions are set to 644 or more restrictive
[PASS] 1.1.2 Ensure that the API server pod specification file ownership is set to root:root
[FAIL] 1.1.3 Ensure that the controller manager pod specification file permissions are set to 644 or more restrictive
[INFO] 1.2 API Server
[PASS] 1.2.1 Ensure that the –anonymous-auth argument is set to false
[FAIL] 1.2.2 Ensure that the –token-auth-file parameter is not set
[PASS] 1.2.3 Ensure that the –DenyServiceExternalIPs is not set
== Summary ==
41 checks PASS
13 checks FAIL
12 checks WARN
# 创建合规检查脚本
[root@k8s-master ~]# cat > /usr/local/bin/compliance-check.sh << 'EOF'
#!/bin/bash
# compliance-check.sh
# from:www.itpux.com.qq113257174.wx:itpux-com
# web: http://www.fgedu.net.cn
REPORT_DIR="/var/log/compliance"
mkdir -p $REPORT_DIR
DATE=$(date +%Y%m%d-%H%M%S)
echo "=== Kubernetes合规性检查 ==="
echo "开始时间: $(date)"
# 1. CIS基准检查
echo "1. 执行CIS基准检查..."
kube-bench run --targets master,node --benchmark cis-1.8 > $REPORT_DIR/cis-$DATE.log 2>&1
# 2. 网络策略检查
echo “2. 检查网络策略…”
kubectl get networkpolicy -A -o yaml > $REPORT_DIR/networkpolicy-$DATE.yaml
# 3. RBAC检查
echo “3. 检查RBAC配置…”
kubectl get clusterrole,clusterrolebinding,role,rolebinding -A -o yaml > $REPORT_DIR/rbac-$DATE.yaml
# 4. Pod安全检查
echo “4. 检查Pod安全配置…”
kubectl get pods -A -o json | jq ‘.items[] | {name: .metadata.name, namespace: .metadata.namespace, securityContext: .spec.securityContext}’ > $REPORT_DIR/pod-security-$DATE.json
# 5. 镜像安全扫描
echo “5. 扫描镜像漏洞…”
kubectl get pods -A -o jsonpath=”{range .items[*]}{.metadata.namespace}{‘\t’}{.metadata.name}{‘\n’}{range .spec.containers[*]}{‘\t’}{.image}{‘\n’}{end}{end}” | sort -u > $REPORT_DIR/images-$DATE.txt
echo “=== 检查完成 ===”
echo “报告目录: $REPORT_DIR”
EOF
[root@k8s-master ~]# chmod +x /usr/local/bin/compliance-check.sh
# 执行合规检查
[root@k8s-master ~]# /usr/local/bin/compliance-check.sh
=== Kubernetes合规性检查 ===
开始时间: Sat Apr 4 23:00:00 CST 2026
1. 执行CIS基准检查…
2. 检查网络策略…
3. 检查RBAC配置…
4. 检查Pod安全配置…
5. 扫描镜像漏洞…
=== 检查完成 ===
报告目录: /var/log/compliance
- 启用API审计日志记录
- 定期运行安全扫描
- 审计RBAC权限配置
- 执行合规性检查
- 保留审计记录备查
本文由风哥教程整理发布,仅用于学习测试使用,转载注明出处:http://www.fgedu.net.cn/10327.html
