Kubernetes安全认证
大约 5 分钟Kubernetes指南Kubernetes安全认证
Kubernetes安全认证
Kubernetes安全认证概述
Kubernetes安全认证是保护集群免受未授权访问的关键机制。Kubernetes提供了多层次的安全控制,包括认证(Authentication)、授权(Authorization)和准入控制(Admission Control),确保只有经过验证和授权的用户和应用才能访问集群资源。
认证机制
1. 认证方式
Kubernetes支持多种认证方式:
客户端证书认证
# 生成客户端证书
openssl genrsa -out client.key 2048
openssl req -new -key client.key -out client.csr -subj "/CN=myuser/O=mygroup"
openssl x509 -req -in client.csr -CA /etc/kubernetes/pki/ca.crt -CAkey /etc/kubernetes/pki/ca.key -CAcreateserial -out client.crt -days 365
Bearer Token认证
# 创建ServiceAccount
kubectl create serviceaccount myuser
# 获取Token
kubectl create token myuser
# 使用Token访问API
curl -H "Authorization: Bearer <token>" https://kubernetes-api-server/api/v1/namespaces
HTTP基本认证(已废弃)
# 创建密码文件
echo "user1:password1" > /etc/kubernetes/auth/basic_auth.csv
# 在API Server中配置
--basic-auth-file=/etc/kubernetes/auth/basic_auth.csv
OpenID Connect (OIDC)
# API Server配置
--oidc-issuer-url=https://accounts.google.com
--oidc-client-id=my-kubernetes-cluster
--oidc-username-claim=email
--oidc-groups-claim=groups
2. ServiceAccount
ServiceAccount为Pod提供身份认证。
# 创建ServiceAccount
apiVersion: v1
kind: ServiceAccount
metadata:
name: my-service-account
namespace: default
# 在Pod中使用ServiceAccount
apiVersion: v1
kind: Pod
metadata:
name: my-pod
spec:
serviceAccountName: my-service-account
containers:
- name: my-container
image: nginx
3. RBAC权限控制
RBAC(Role-Based Access Control)基于角色的访问控制。
Role和RoleBinding
# 创建Role
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
namespace: default
name: pod-reader
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "watch", "list"]
# 创建RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: read-pods
namespace: default
subjects:
- kind: User
name: myuser
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: Role
name: pod-reader
apiGroup: rbac.authorization.k8s.io
ClusterRole和ClusterRoleBinding
# 创建ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: secret-reader
rules:
- apiGroups: [""]
resources: ["secrets"]
verbs: ["get", "watch", "list"]
# 创建ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: read-secrets-global
subjects:
- kind: Group
name: manager
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: ClusterRole
name: secret-reader
apiGroup: rbac.authorization.k8s.io
授权机制
1. ABAC(基于属性的访问控制)
ABAC通过策略文件定义访问控制规则。
{
"apiVersion": "abac.authorization.kubernetes.io/v1beta1",
"kind": "Policy",
"spec": {
"user": "myuser",
"namespace": "default",
"resource": "pods",
"readonly": true
}
}
2. Webhook授权
Webhook授权通过外部服务进行授权决策。
# API Server配置
--authorization-webhook-config-file=/etc/kubernetes/auth/webhook-config.yaml
--authorization-mode=Webhook,RBAC
# Webhook配置文件
apiVersion: v1
kind: Config
clusters:
- name: webhook
cluster:
server: https://webhook-authz-server/authz
users:
- name: webhook
user:
token: "secret-token"
current-context: webhook
contexts:
- context:
cluster: webhook
user: webhook
name: webhook
网络安全
1. 网络策略
NetworkPolicy用于控制Pod之间的网络通信。
# 限制Pod网络访问
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny
spec:
podSelector: {}
policyTypes:
- Ingress
# 允许特定流量
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-nginx
spec:
podSelector:
matchLabels:
app: nginx
ingress:
- from:
- podSelector:
matchLabels:
app: web
ports:
- protocol: TCP
port: 80
2. Pod安全策略
PodSecurityPolicy用于控制Pod的安全相关配置。
# Pod安全策略示例
apiVersion: policy/v1beta1
kind: PodSecurityPolicy
metadata:
name: restricted
spec:
privileged: false
allowPrivilegeEscalation: false
requiredDropCapabilities:
- ALL
volumes:
- 'configMap'
- 'emptyDir'
- 'projected'
- 'secret'
- 'downwardAPI'
- 'persistentVolumeClaim'
hostNetwork: false
hostIPC: false
hostPID: false
runAsUser:
rule: 'MustRunAsNonRoot'
seLinux:
rule: 'RunAsAny'
supplementalGroups:
rule: 'MustRunAs'
ranges:
- min: 1
max: 65535
fsGroup:
rule: 'MustRunAs'
ranges:
- min: 1
max: 65535
readOnlyRootFilesystem: false
安全上下文
1. Pod安全上下文
# Pod安全上下文配置
apiVersion: v1
kind: Pod
metadata:
name: security-context-demo
spec:
securityContext:
runAsUser: 1000
runAsGroup: 3000
fsGroup: 2000
volumes:
- name: sec-ctx-vol
emptyDir: {}
containers:
- name: sec-ctx-demo
image: busybox
command: [ "sh", "-c", "sleep 1h" ]
volumeMounts:
- name: sec-ctx-vol
mountPath: /data/demo
securityContext:
allowPrivilegeEscalation: false
2. 容器安全上下文
# 容器安全上下文配置
apiVersion: v1
kind: Pod
metadata:
name: security-context-demo-2
spec:
containers:
- name: sec-ctx-demo-2
image: gcr.io/google-samples/node-hello:1.0
securityContext:
runAsUser: 2000
allowPrivilegeEscalation: false
capabilities:
drop: ["ALL"]
add: ["NET_BIND_SERVICE"]
密钥管理
1. Secret管理
# 创建Secret
apiVersion: v1
kind: Secret
metadata:
name: mysecret
type: Opaque
data:
username: YWRtaW4=
password: MWYyZDFlMmU2N2Rm
# 在Pod中使用Secret
apiVersion: v1
kind: Pod
metadata:
name: mypod
spec:
containers:
- name: mypod
image: redis
env:
- name: SECRET_USERNAME
valueFrom:
secretKeyRef:
name: mysecret
key: username
- name: SECRET_PASSWORD
valueFrom:
secretKeyRef:
name: mysecret
key: password
2. 外部密钥管理
# 使用外部密钥管理服务(如HashiCorp Vault)
apiVersion: secrets-store.csi.x-k8s.io/v1alpha1
kind: SecretProviderClass
metadata:
name: vault-database
spec:
provider: vault
parameters:
roleName: "database-role"
vaultAddress: "https://vault:8200"
vaultCACertPath: "/etc/kubernetes/certs/vault-ca.crt"
安全审计
1. 审计日志配置
# API Server审计配置
--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
# 审计策略示例
apiVersion: audit.k8s.io/v1
kind: Policy
rules:
- level: Metadata
resources:
- group: ""
resources: ["secrets", "configmaps"]
- level: Request
verbs: ["create", "update", "delete"]
resources:
- group: ""
resources: ["pods"]
- level: None
2. 审计日志分析
# 查看审计日志
kubectl get --raw /api/v1/namespaces/default/pods | jq .
# 使用审计日志分析工具
kubectl apply -f https://github.com/kubernetes-sigs/audit2rbac/releases/latest/download/audit2rbac.yaml
安全最佳实践
1. 访问控制最佳实践
# 最小权限原则
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
namespace: production
name: deployment-manager
rules:
- apiGroups: ["apps"]
resources: ["deployments"]
verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "list", "watch"]
2. 网络安全最佳实践
# 默认拒绝所有流量
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-all
namespace: secure-namespace
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress
3. 镜像安全最佳实践
# 使用特定版本的镜像
apiVersion: apps/v1
kind: Deployment
metadata:
name: secure-app
spec:
template:
spec:
containers:
- name: app
image: myregistry.example.com/myapp:v1.2.3
securityContext:
readOnlyRootFilesystem: true
runAsNonRoot: true
runAsUser: 10001
4. 资源限制最佳实践
# 设置资源请求和限制
apiVersion: v1
kind: Pod
metadata:
name: secure-pod
spec:
containers:
- name: app
image: nginx
resources:
requests:
memory: "64Mi"
cpu: "250m"
limits:
memory: "128Mi"
cpu: "500m"
安全工具和监控
1. 安全扫描工具
# 使用Trivy扫描镜像漏洞
trivy image nginx:latest
# 使用Clair扫描镜像
clair-scanner --ip YOUR_LOCAL_IP nginx:latest
2. 运行时安全监控
# 使用Falco进行运行时安全监控
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: falco
namespace: falco
spec:
selector:
matchLabels:
app: falco
template:
metadata:
labels:
app: falco
spec:
containers:
- name: falco
image: falcosecurity/falco:latest
securityContext:
privileged: true
3. 安全合规检查
# 使用kube-bench检查CIS基准
kube-bench master
# 使用kube-hunter发现安全问题
kube-hunter --pod
常用安全命令
命令 | 说明 |
---|---|
kubectl auth can-i | 检查权限 |
kubectl get roles | 查看角色 |
kubectl get rolebindings | 查看角色绑定 |
kubectl get clusterroles | 查看集群角色 |
kubectl get clusterrolebindings | 查看集群角色绑定 |
kubectl get secrets | 查看密钥 |
kubectl get networkpolicies | 查看网络策略 |
kubectl describe pod pod-name | 查看Pod安全配置 |
总结
Kubernetes安全认证是保护容器化应用的重要机制。通过合理的认证、授权和安全配置,可以有效防止未授权访问和安全威胁。在实际应用中,应该遵循安全最佳实践,定期进行安全审计和漏洞扫描,确保集群和应用的安全性。