IAM策略中使用${credentials-iot:ThingName}触发AccessDeniedException问题
问题:AWS IoT凭证策略中${credentials-iot:ThingName}变量不生效
问题现象
配置IoT凭证提供商关联IAM角色后,当角色策略使用${credentials-iot:ThingName}变量匹配DynamoDB表时,调用dynamodb:DescribeTable返回AccessDeniedException;将变量替换为具体表名则可正常调用。同时,即使不携带z-amzn-iot-thingname请求头,仍能通过curl获取临时凭证。
已配置资源回顾
- DynamoDB表:
H42318K04D - IAM角色:
IoTCertificateExchangedRole(内联策略使用${credentials-iot:ThingName}变量,信任策略允许credentials.iot.amazonaws.com执行sts:AssumeRole) - IoT Thing:
H42318K04D(已绑定激活状态的IoT证书) - IoT证书策略:允许执行
iot:AssumeRoleWithCertificate,目标为角色别名IoTCertificateExchangedRoleAlias - IoT角色别名:
IoTCertificateExchangedRoleAlias(关联上述IAM角色)
问题根源
- 变量未注入会话:
${credentials-iot:ThingName}变量需要同时满足两个条件才会被注入临时凭证会话:请求携带z-amzn-iot-thingname请求头,且该Thing与用于认证的IoT证书绑定;同时IAM角色的信任策略需验证该关联关系,否则变量不会被填充。 - 无请求头仍能获取凭证:当前IAM角色的信任策略仅限制了服务主体,未添加Thing关联的条件验证,导致任意有效IoT证书都能获取临时凭证,但此时会话中不存在ThingName变量,策略中的资源匹配规则失效。
修复方案
1. 更新IAM角色信任策略,强制验证Thing关联
修改IoTCertificateExchangedRole的信任策略,添加条件确保只有绑定指定Thing的证书才能AssumeRole,同时触发ThingName变量的注入:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "credentials.iot.amazonaws.com" }, "Action": "sts:AssumeRole", "Condition": { "StringEquals": { "credentials-iot:ThingName": "${aws:PrincipalTag:ThingName}" } } } ] }
2. 确认证书与Thing的绑定关系
使用AWS CLI验证目标证书已绑定到H42318K04D:
aws iot list-thing-principals --thing-name H42318K04D
输出结果中应包含你的IoT证书ARN。
3. 重新获取临时凭证并验证
必须携带z-amzn-iot-thingname请求头获取凭证:
curl --cert device.crt --key device.key -H "z-amzn-iot-thingname: H42318K04D" https://<IoT credential provider endpoint>/role-aliases/IoTCertificateExchangedRoleAlias/credentials
此时获取的临时凭证会话中会注入ThingName变量,IAM策略中的${credentials-iot:ThingName}会被自动替换为H42318K04D,DynamoDB的DescribeTable调用即可正常通过。
4. 验证变量生效状态
可通过CloudTrail查看AssumeRole事件,确认会话属性中包含credentials-iot:ThingName标签;或使用临时凭证执行以下命令查看会话信息:
aws sts get-caller-identity --region us-west-2
额外说明
- 修复完成后,不携带
z-amzn-iot-thingname请求头将无法获取临时凭证,符合最小权限安全原则。 ${credentials-iot:ThingName}是AWS IoT凭证提供商专属的会话变量,仅在满足Thing与证书绑定、请求携带指定头两个条件时才会被注入。
内容的提问来源于stack exchange,提问作者hencrice
相关产品推荐
相关产品推荐

