深色模式
云账号与权限
摘要:云上大多数安全事故都源于权限失控。本文教你用「主账号只付款、子账号干所有活、策略最小授权」的思路搭建云账号体系,并配上 MFA 与密钥轮换。
适用环境
bash
# 已安装并配置好云厂商 CLI(以下以 AWS CLI 为例,其它厂商概念相同)
aws --version
aws sts get-caller-identity # 确认当前使用的是哪个身份
python3 -c "print('ok')"1
2
3
4
2
3
4
操作步骤
一、确认当前身份,别用错了账号
bash
aws sts get-caller-identity
# 输出中的 Arn 若包含 :root,说明你正在用主账号 —— 立刻停用1
2
2
二、按职能创建子账号(用户)
bash
# 创建只读审计用户
aws iam create-user --user-name auditor
# 创建部署用户
aws iam create-user --user-name deployer1
2
3
4
2
3
4
危险
不要给子账号开启控制台密码登录并共享给多人。人是会流动的,共享账号无法追责;每人一个账号,离职即禁用。
三、授予最小权限
优先使用厂商预置策略,避免图省事直接给 AdministratorAccess:
bash
# 只读策略
aws iam attach-user-policy --user-name auditor \
--policy-arn arn:aws:iam::aws:policy/ReadOnlyAccess
# 部署用户只授予某台机器的重启权限(自定义策略示例)
cat > restart-one.json <<'EOF'
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": ["ec2:RebootInstances"],
"Resource": "arn:aws:ec2:ap-east-1:123456789012:instance/i-0abcdef1234567890",
"Condition": {"StringEquals": {"aws:ResourceTag/env": "prod"}}
}]
}
EOF
aws iam create-policy --policy-name RebootOneInstance \
--policy-document file://restart-one.json1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
四、开启 MFA 并强制生效
bash
# 为子账号绑定虚拟 MFA 设备(控制台操作更直观:IAM → 用户 → 安全凭证 → 分配 MFA)
aws iam create-virtual-mfa-device --virtual-mfa-device-name auditor-mfa \
--outfile /tmp/qr.png --bootstrap-method QRCodePNG
# 用手机 Authenticator 扫码后,回填连续两段 6 位码
aws iam enable-mfa-device --user-name auditor \
--serial-number arn:aws:iam::123456789012:mfa/auditor-mfa \
--authentication-code1 111111 --authentication-code2 2222221
2
3
4
5
6
7
2
3
4
5
6
7
五、用角色代替长期密钥(给机器授权)
跑在云服务器上的程序不要存 AccessKey,应该绑定实例角色:
bash
# 1) 创建可信实体为 EC2 的角色
aws iam create-role --role-name app-oss-role \
--assume-role-policy-document file://trust-ec2.json
# 2) 挂上最小策略后,把角色绑定到实例
aws ec2 associate-iam-instance-profile \
--instance-id i-0abcdef1234567890 --iam-instance-profile Name=app-oss-role
# 3) 机器内直接拿临时凭证,无需配置 AK
curl -s http://169.254.169.254/latest/meta-data/iam/security-credentials/app-oss-role | head -201
2
3
4
5
6
7
8
2
3
4
5
6
7
8
六、密钥轮换
bash
# 列出某账号所有 AccessKey 及创建时间
aws iam list-access-keys --user-name deployer
# 创建新密钥 → 替换到应用 → 验证 → 禁用旧密钥 → 观察 7 天 → 删除
aws iam create-access-key --user-name deployer
aws iam update-access-key --user-name deployer --access-key-id AKIA... --status Inactive
aws iam delete-access-key --user-name deployer --access-key-id AKIA...1
2
3
4
5
6
2
3
4
5
6
验证
- [ ]
aws sts get-caller-identity返回的身份不是主账号 - [ ] 每个子账号都绑定了 MFA
- [ ] 生产操作账号的策略里没有
*的 Action 或 Resource - [ ] 云主机内的程序通过实例角色获取凭证,磁盘上搜不到明文 AK:
bash
sudo grep -rIn "AKIA" /etc /opt /home 2>/dev/null | head1
常见坑
- 图方便给管理员权限:最小权限一开始麻烦,但它能把一次误操作的影响从「全账号瘫痪」降到「重启一台机器」。
- 把 AK 写进代码仓库:一旦提交到 Git,即使后续删除也视为已泄露,必须立刻轮换。
- 只禁用不删除密钥:禁用只是临时止损,长期不删会积累大量无人认领的凭证。
- 忘记清理离职人员账号:应把「账号回收」写进离职流程清单。