云安全与自建机房最大的区别在于责任共担模型(Shared Responsibility Model):云厂商负责"云的安全"(物理设施、虚拟化、托管服务),客户负责"云中的安全"(数据、身份、访问控制、应用配置)。现实中大部分云安全事故并非厂商漏洞,而是客户侧的错误配置——公开的 S3 桶、过度授权的 IAM 策略、开放的 Security Group。本指南以三朵云为主线,系统覆盖 IAM 最小权限、网络隔离、数据加密、威胁检测与合规基线,并给出跨云的统一安全策略。
一、云安全的责任共担与共同陷阱
1.1 责任共担模型
┌────────────────────────────────────────────┐
│ 客户负责(Customer Responsibility) │
│ · 数据分类与加密 │
│ · IAM 身份与访问策略 │
│ · 应用配置(OS、运行时、代码) │
│ · 网络配置(VPC/安全组/防火墙规则) │
│ · 合规与数据治理 │
├────────────────────────────────────────────┤
│ 云厂商负责(Provider Responsibility) │
│ · 物理设施、机房、硬件 │
│ · 虚拟化层、宿主机 OS │
│ · 托管服务(RDS/S3/等)底层 │
│ · 全球网络基础设施 │
└────────────────────────────────────────────┘
ℹ️ 核心洞察:责任共担模型的边界在云厂商服务文档中逐服务定义。SaaS 场景(如 S3)客户只负责配置与访问;IaaS 场景(如 EC2)客户还要负责 OS 与应用。事故后辩论"谁的责任"是徒劳——先把客户侧责任全部做到。
1.2 云安全事故 TOP 根因
| 根因 | 占比 | 典型场景 |
|---|---|---|
| IAM 过度授权 | 高 | 管理员角色绑到服务账号、通配符策略 |
| 网络配置错误 | 高 | Security Group 0.0.0.0/0 对 3306 开放 |
| 存储公开暴露 | 中 | S3/GCS/Azure Blob 公开读 |
| 密钥泄露 | 中 | 密钥提交进 Git、环境变量外泄 |
| 托管服务错误配置 | 中 | RDS 公网 + 弱口令 |
| 缺少检测 | 低 | 无 CloudTrail/Sentinel 审计告警 |
二、AWS 安全架构
2.1 IAM:最小权限的落地
// 反模式:通配符 + 管理权限
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "*",
"Resource": "*"
}]
}
// 正模式:最小权限 + 条件约束
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetObject"],
"Resource": ["arn:aws:s3:::prod-bucket/*"],
"Condition": {
"StringEquals": {"aws:PrincipalTag/team": "data"},
"IpAddress": {"aws:SourceIp": "10.0.0.0/8"}
}
}
]
}
# IAM Access Analyzer:检测过度授权策略
aws accessanalyzer create-analyzer --type ACCOUNT --name security-analyzer
aws accessanalyzer list-findings --analyzer-arn <arn>
# 最小权限工具:IAM Policy Simulator 验证效果
aws iam simulate-principal-policy \
--principal-arn arn:aws:iam::123456789012:user/deploy \
--action-names s3:PutObject --resource-arns arn:aws:s3:::prod/*
2.2 网络隔离:VPC 与 Security Group
# VPC 分段:生产/测试/数据三网隔离
aws ec2 create-vpc --cidr-block 10.0.0.0/16 --tag-specifications \
'ResourceType=vpc,Tags=[{Key=env,Value=prod}]'
# Security Group 最小开放(示例:仅 443 且限源)
aws ec2 authorize-security-group-ingress \
--group-id sg-0123456789abcdef0 \
--protocol tcp --port 443 --cidr 203.0.113.0/24
# 核心建议:
# · 数据库 SG 只接受来自应用 SG 的流量(SG 引用而非 CIDR)
# · 禁止 0.0.0.0/0 对管理端口(22/3389/3306/6379)开放
# SG 引用安全组:数据库只允许应用访问
aws ec2 authorize-security-group-ingress \
--group-id sg-0db1sgdata \
--protocol tcp --port 3306 \
--source-group sg-0appgroup # 引用应用安全组而非 IP
2.3 数据加密与密钥管理(KMS)
# boto3 KMS 加密实践
import boto3
kms = boto3.client("kms")
def encrypt_secret(plaintext: str, key_id: str) -> bytes:
"""用 KMS 主密钥加密,数据密钥不落盘。"""
resp = kms.encrypt(KeyId=key_id, Plaintext=plaintext.encode())
return resp["CiphertextBlob"]
def decrypt_secret(ciphertext: bytes) -> str:
resp = kms.decrypt(CiphertextBlob=ciphertext)
return resp["Plaintext"].decode()
# S3 默认加密 + 存储桶策略强制
import boto3
s3 = boto3.client("s3")
s3.put_bucket_encryption(
Bucket="prod-data-bucket",
ServerSideEncryptionConfiguration={
"Rules": [{"ApplyServerSideEncryptionByDefault":
{"SSEAlgorithm": "aws:kms"}}]})
# 强制所有对象加密(Deny 策略)
{
"Statement": [{
"Effect": "Deny",
"Action": ["s3:PutObject"],
"Resource": "arn:aws:s3:::prod-data-bucket/*",
"Condition": {
"StringNotEquals": {"s3:x-amz-server-side-encryption": "aws:kms"}
}
}]
}
2.4 威胁检测与审计
AWS 安全栈:
CloudTrail → 记录所有 API 调用(控制面审计)
GuardDuty → 威胁检测(异常行为、恶意 IP、Crypto 挖矿)
Config → 资源配置合规(CSPM)
Security Hub → 聚合告警与合规基线
CloudWatch → 指标与日志告警
# 强制开启 CloudTrail(所有区域、所有读写事件)
aws cloudtrail create-trail --name org-audit \
--s3-bucket-name security-logs-bucket \
--is-multi-region-trail \
--enable-log-file-validation
# 关键告警:根账号登录(Root MFA 必须)
# CloudWatch Event → 根账号 ConsoleLogin → SNS → 告警
三、Azure 安全架构
3.1 身份与条件访问(Entra ID)
Azure 的安全核心是 Entra ID(原 Azure AD) 与条件访问(Conditional Access):
# 强制 MFA:条件访问策略要求所有管理员 MFA
# az cli 创建条件访问策略(简化示意)
az rest --method POST --url "https://graph.microsoft.com/v1.0/identity/conditionalAccess/policies" \
--body '{
"displayName": "Require MFA for Admins",
"state": "enabled",
"conditions": {"applications": {"includeApplications": ["all"]}},
"grantControls": {"operator": "AND", "builtInControls": ["mfa"]}
}'
# 用 Azure SDK 校验订阅中的高风险访问
from azure.identity import DefaultAzureCredential
from azure.mgmt.security import SecurityCenter
def list_high_severity_alerts(subscription_id):
client = SecurityCenter(DefaultAzureCredential(), subscription_id)
alerts = client.alerts.list()
return [a for a in alerts if a.severity in ("High", "Critical")]
3.2 网络隔离:VNet 与 NSG / 防火墙
# NSG 规则:拒绝公网访问管理端口(示例)
az network nsg rule create \
--resource-group rg-prod \
--nsg-name prod-nsg \
--name deny-mgmt-internet \
--access Deny --direction Inbound \
--protocol Tcp --source-address-prefixes Internet \
--destination-port-ranges 22 3389
# 用 Azure Firewall 做 DMZ 与 FQDN 过滤
# 关键:数据库/存储应放私有端点(Private Endpoint)而非公网
az network private-endpoint create \
--resource-group rg-prod \
--name pe-sql \
--private-connection-resource-id <sql-server-id> \
--group-id sqlServer
3.3 数据保护:Key Vault 与 BYOK
# Azure Key Vault 密钥管理
from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient
def store_secret(vault_url, name, value):
client = SecretClient(vault_url, DefaultAzureCredential())
client.set_secret(name, value)
def get_secret(vault_url, name):
client = SecretClient(vault_url, DefaultAzureCredential())
return client.get_secret(name).value # 应用从 KV 取,不硬编码
Azure 加密分层:
· 存储账号 SSE(服务端加密,默认开启)
· Key Vault 管理密钥(含 HSM-backed key)
· BYOK(Bring Your Own Key):客户自持根密钥
· Disk Encryption:VM 磁盘加密(BitLocker / dm-crypt)
3.4 威胁检测:Microsoft Sentinel
Azure 安全栈:
Entra ID → 身份与条件访问
Microsoft Defender for Cloud → CSPM + 威胁防护
Sentinel → SIEM/SOAR(日志聚合、威胁狩猎、自动化响应)
Azure Monitor→ 指标与日志
Sentinel 分析规则示例(检测暴力破解):
· 聚合 SignInLogs 中连续失败的账号登录
· 阈值:1 分钟内失败 > 5 次
· 响应:自动禁用账号 + 创建工单
四、GCP 安全架构
4.1 IAM 与组织策略
GCP 采用资源层级(Org → Folder → Project → 资源)+ IAM 角色继承:
# 组织级策略:拒绝将服务账号密钥下载到外部
gcloud resource-manager org-policies deny \
iam.disableServiceAccountKeyCreation --organization=123456789012
# 绑定最小权限角色(示例:只读日志)
gcloud projects add-iam-policy-binding my-project \
--member="user:analyst@example.com" \
--role="roles/logging.viewer"
# 用 Asset Inventory 审计 IAM 过度授权
from google.cloud import asset_v1
def list_bindings(project):
client = asset_v1.AssetServiceClient()
# 搜索 role=owner/admin 的绑定,标记高风险
return find_high_privilege_bindings(client, project)
4.2 网络:VPC 与防火墙规则
# 零信任 VPC:默认拒绝,仅显式放行
gcloud compute firewall-rules create deny-all \
--network prod-vpc --direction INGRESS \
--action DENY --rules all --priority 65535 # 默认拒绝
gcloud compute firewall-rules create allow-https-from-alb \
--network prod-vpc --direction INGRESS \
--action ALLOW --rules tcp:443 \
--source-ranges 130.211.0.0/22,35.191.0.0/16 # 仅 Google 负载均衡 IP
4.3 数据加密:Cloud KMS 与 CMEK
# 客户管理加密密钥(CMEK):客户掌控密钥生命周期
gcloud kms keyrings create prod-ring --location global
gcloud kms keys create data-key \
--location global --keyring prod-ring \
--purpose encryption
# GCS 桶启用 CMEK 加密
gcloud storage buckets update gs://prod-data \
--encryption-key=projects/my-proj/locations/global/keyRings/prod-ring/cryptoKeys/data-key
4.4 威胁检测:Security Command Center
GCP 安全栈:
Cloud IAM → 身份与访问
VPC Service Controls → 服务边界隔离
Security Command Center → 风险发现 + 威胁检测
Cloud Audit Logs → 审计日志(Admin/Data Access)
Chronicle → SIEM(检测与狩猎)
# 强制开启数据访问日志(谁读了哪些数据)
gcloud projects set-iam-policy ... # 配置 audit config
# 关键检测:公网 GCS 桶、未加密资源、异常公钥登录
五、跨云统一安全基线(CSPM 思路)
5.1 统一基线清单(三云对齐)
| 基线项 | AWS | Azure | GCP |
|---|---|---|---|
| 根/超级管理员 MFA | Root MFA 必开 | Global Admin MFA | Super Admin MFA |
| IAM 最小权限 | IAM Access Analyzer | PIM + 角色 | IAM 条件 + 组织策略 |
| 管理端口不公开 | SG 禁 22/3389 | NSG 禁 | 防火墙规则禁 |
| 存储私有 | S3 私密 + 加密 | Blob 私密 + SSE | GCS 私密 + CMEK |
| 密钥托管 | KMS | Key Vault | Cloud KMS |
| 审计开启 | CloudTrail | Azure Activity Log | Cloud Audit Logs |
| 威胁检测 | GuardDuty | Defender/Sentinel | SCC/Chronicle |
| 配置合规 | AWS Config | Defender for Cloud | SCC 基线 |
5.2 IaC 安全:在部署前发现问题
# Terraform 安全基线示例(tfsec / checkov 扫描)
resource "aws_security_group" "db" {
# 反模式(会被 tfsec 拦截):
ingress {
from_port = 3306
to_port = 3306
cidr_blocks = ["0.0.0.0/0"] # ❌ 数据库公开
}
}
# 用 checkov 在 CI 扫描 Terraform / CloudFormation / k8s 配置
# checkov 集成 GitHub Actions
name: IaC Security Scan
on: [push]
jobs:
checkov:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: pip install checkov
- run: checkov -d . --framework terraform --hard-fail-on HIGH
5.3 云配置的持续监控
# multi_cloud_cspm.py — 统一云配置监控
def scan_all_clouds(clouds: list[str]) -> list[Finding]:
findings = []
for cloud in clouds:
if cloud == "aws":
findings += scan_aws(s3_public, sg_open, iam_overgrant)
elif cloud == "azure":
findings += scan_azure(storage_public, nsg_open)
elif cloud == "gcp":
findings += scan_gcp(gcs_public, firewall_open)
return [f for f in findings if f.severity in ("high", "critical")]
六、容器与 Kubernetes 的云安全
6.1 托管 K8s 的安全基线
# EKS / AKS / GKE 通用基线
# 1. 私有集群(Control Plane 不对公网)
# 2. RBAC 最小权限
# 3. Network Policy 命名空间隔离
# 4. 镜像扫描(Amazon ECR Scan / 开源 Trivy)
# 5. Pod Security Standards(基线/受限)
# Trivy 镜像扫描示例
trivy image --severity HIGH,CRITICAL --no-progress nginx:1.25
# Kubernetes NetworkPolicy:只允许同命名空间内服务互访
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: deny-except-app
namespace: backend
spec:
podSelector: {}
policyTypes: ["Ingress"]
ingress:
- from:
- namespaceSelector:
matchLabels: {name: backend}
6.2 密钥与凭证安全
云环境密钥管理黄金法则:
· 不使用环境变量明文密钥(会进日志/CI artifact)
· 使用云 KMS + Secrets Manager(AWS Secrets Manager / Azure KV / GCP Secret Manager)
· 服务身份而非密钥(AWS IAM Role / GCP Workload Identity / Azure Managed Identity)
· 密钥轮换自动化 + 使用历史追踪
# 服务身份替代静态密钥
# GCP Workload Identity:Pod 以工作负载身份访问,无需 API key
# 反模式:把 SA key 挂到 pod 里
# 正模式:Workload Identity Federation
def call_gcs_with_workload_identity():
from google.cloud import storage
# 无需密钥,用元数据服务自动获取身份
client = storage.Client() # 基于 workload identity
七、云安全运营:检测、响应与合规
7.1 安全运营中心的云侧建设
云 SOC 架构:
数据采集:CloudTrail / Audit Logs / 指标
聚合分析:SIEM(Sentinel / Chronicle / 自建)
检测规则:攻击模式、异常登录、数据外泄
响应:SOAR 剧本(隔离主机、吊销凭证、禁用账号)
复盘:Postmortem + 基线改进
7.2 合规基线的自动化
| 合规框架 | 覆盖 | 自动化工具 |
|---|---|---|
| CIS Benchmarks | 云配置基线 | AWS Security Hub CIS / Azure Policy / GCP SCC |
| SOC 2 | 安全运营 | 审计日志、访问控制、监控 |
| ISO 27001 | 信息安全管理 | 云侧控制项映射 |
| 等保 2.0(国内) | 合规 | 云安全评估工具 |
| GDPR / 个保法 | 数据保护 | DLP、加密、访问审计 |
# 示例:AWS Security Hub 启用 CIS AWS 基线
aws securityhub enable-security-hub \
--controls 'arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.4.0'
7.3 云安全事故的应急响应
云侧事件响应六步(示例:检测到异常 IAM 操作):
1. 检测:GuardDuty/Sentinel 告警
2. 遏制:吊销访问密钥 + 隔离主机(SG 移除公网)
3. 调查:CloudTrail 回溯 API 调用、分析 IAM 行为
4. 根因:确认过度授权策略 / 泄露密钥
5. 恢复:轮换所有受影响凭证、收紧策略
6. 复盘:更新基线 + 加检测规则
八、云安全评测与持续改进
8.1 安全评估演练
# cloud_security_testset.py — 云配置安全检查用例
def run_cloud_security_audit(provider_apis):
checks = [
check_root_account_no_mfa(),
check_storage_public(),
check_security_group_open_management(),
check_iam_overgranted(),
check_encryption_enabled(),
check_audit_trail_enabled(),
]
return {c["name"]: c["result"] for c in checks}
8.2 攻防演练(云红队)
云侧演练场景:
· 攻击者拿到泄露的 IAM 密钥 → 横向移动
· 恶意 pod 逃逸 → 访问元数据服务(169.254.169.254)
· 数据从私有桶外泄到攻击者控制的账号
· 公共 API 滥用 → 资源耗尽(云账单炸弹)
防御重点:
· 元数据服务防护(IMDSv2 强制)
· 服务账号密钥最小化 + 轮换
· 预算告警(异常支出 = 被滥用信号)
# 强制 IMDSv2(防 SSRF 窃取元数据)
aws ec2 modify-instance-metadata-options \
--instance-id i-xxx \
--http-tokens required \
--http-endpoint enabled
8.3 云安全的持续改进闭环
| 阶段 | 动作 |
|---|---|
| 发现 | CSPM 扫描 + 红队演练 + 基线审计 |
| 修复 | 策略收紧 + IaC 修复 + 配置加固 |
| 验证 | 复扫 + 渗透测试验证 |
| 预防 | 策略即代码 + CI 门禁 + 开发者安全培训 |
| 监测 | 威胁检测规则持续优化 |
总结:云安全的核心矩阵
| 领域 | 三云统一要点 |
|---|---|
| 身份 | MFA 必开、最小权限、服务身份优先 |
| 网络 | 默认拒绝、管理端口不公开、微隔离 |
| 数据 | 存储私密、加密默认、密钥托管 |
| 检测 | 审计全开、威胁检测、配置基线 |
| 治理 | 策略即代码、CI 扫描、持续改进 |
云安全与自建机房最大的差异,是**“配置即攻击面”**——S3 桶策略、安全组规则、IAM 角色这些一行配置就能决定系统生死。成熟的云安全实践可以归纳为三句话:身份最小化(没有凭证就没有攻击面)、网络默认拒绝(看不见就攻不进)、检测全开(攻进来也要立刻发现)。把这三点落到 IaC 扫描、CSPM 监控与应急剧本里,三朵云就能成为可治理的安全基础设施,而非默认暴露的攻击面。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。