> ## Documentation Index
> Fetch the complete documentation index at: https://cloudanix.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# ECS Tasks With Network Mode Host Should Have Limited Permissions

### More Info:

This rule verifies that ECS Task Definitions do not specify a user when using the host network mode. In host network mode, containers share the network namespace with the host, potentially exposing sensitive network configurations or services. Not specifying a user for containers in host mode enhances security by preventing potential privilege escalation or unauthorized access to host resources.

### Risk Level

High

### Address

Security

### Compliance Standards

* APRA CPS 234 (Australia)
* BSI C5 (Germany)
* Brazil LGPD
* CCPA / CPRA (California)
* CIS Critical Security Controls v8
* CMMC 2.0
* CSA Cloud Controls Matrix v4
* Cloudanix Best Practice
* DPDPA
* Digital Operational Resilience Act (EU)
* Essential 8
* ISO/IEC 27017
* ISO/IEC 27018
* ISO/IEC 27701
* KSA PDPL
* MAS Technology Risk Management (Singapore)
* MITRE ATT\&CK (Cloud)
* NIST SP 800-171
* NYDFS 23 NYCRR 500
* SWIFT Customer Security Controls Framework
* Sarbanes-Oxley IT General Controls
* UK NCSC Cyber Assessment Framework

### Triage and Remediation

<Tabs>
  <Tab title="Remediation">
    ### Remediation

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To remediate the misconfiguration of ECS tasks with network mode host having limited permissions in AWS, follow these steps using the AWS Management Console:

        1. **Access the AWS Management Console**: Go to the AWS Management Console at [https://aws.amazon.com/](https://aws.amazon.com/) and log in with your credentials.

        2. **Navigate to ECS**: Click on the "Services" dropdown menu at the top of the console, then select "ECS" under the "Compute" section.

        3. **Select the Cluster**: From the ECS dashboard, select the cluster where the ECS tasks with network mode host are running.

        4. **Select the Task Definition**: In the cluster, click on the task definition that includes the ECS tasks with network mode host that need to have limited permissions.

        5. **Edit Task Definition**: In the task definition details page, click on the "Create new revision" button to create a new revision of the task definition.

        6. **Update Task Definition**: In the task definition editor, scroll down to the "Task execution IAM role" section. Here, you can update the task execution role to have limited permissions by attaching a custom IAM policy with restricted permissions.

        7. **Create a Custom IAM Policy**: If you don't have a custom IAM policy with limited permissions already created, you can create one by navigating to the IAM service in the AWS Management Console. Click on "Policies" in the left-hand menu, then click on "Create policy" and follow the steps to define the policy with the necessary limited permissions.

        8. **Attach Custom IAM Policy**: Once you have created the custom IAM policy with limited permissions, go back to the task definition editor in the ECS console. In the "Task execution IAM role" section, click on "Attach policies" and search for the custom IAM policy you created. Select the policy and attach it to the task execution role.

        9. **Review and Save**: Review the changes you have made to the task definition, ensuring that the task execution role now has limited permissions. Once you are satisfied with the changes, click on the "Create" button to save the new revision of the task definition.

        10. **Update ECS Service**: After saving the new revision of the task definition, go back to the ECS cluster dashboard and select the service that is running the ECS tasks with network mode host. Update the service to use the new revision of the task definition with the limited permissions for the task execution role.

        By following these steps, you can remediate the misconfiguration of ECS tasks with network mode host having limited permissions in AWS using the AWS Management Console.

        #
      </Accordion>

      <Accordion title="Using CLI">
        To remediate the misconfiguration of ECS tasks with network mode host having limited permissions in AWS Kubernetes using AWS CLI, follow these steps:

        1. **Identify the ECS tasks with network mode host**: Run the following AWS CLI command to list all ECS tasks with network mode host:
           ```
           aws ecs list-tasks --query 'taskArns[*]' --output text
           ```

        2. **Update the task definition**: For each ECS task identified in the previous step, you need to update the task definition to limit the permissions. Run the following AWS CLI command to describe the task definition:
           ```
           aws ecs describe-task-definition --task-definition <task-definition-arn>
           ```

        3. **Modify the task definition**: Edit the task definition JSON to remove any unnecessary or overly permissive permissions. Ensure that the task has the least privilege necessary to function properly. Here's an example of modifying the task definition JSON:
           ```json theme={null}
           {
               "executionRoleArn": "arn:aws:iam::123456789012:role/ecsTaskExecutionRole",
               "containerDefinitions": [
                   {
                       "name": "myContainer",
                       "image": "myImage",
                       "networkMode": "host",
                       "essential": true,
                       "portMappings": [
                           {
                               "containerPort": 80,
                               "hostPort": 80
                           }
                       ],
                       "logConfiguration": {
                           "logDriver": "awslogs",
                           "options": {
                               "awslogs-group": "/ecs/myApp",
                               "awslogs-region": "us-east-1",
                               "awslogs-stream-prefix": "myApp"
                           }
                       }
                   }
               ]
           }
           ```

        4. **Update the task definition**: Run the following AWS CLI command to update the task definition with the modified JSON:
           ```
           aws ecs register-task-definition --cli-input-json file://updated-task-definition.json
           ```

        5. **Verify the changes**: Run the following AWS CLI command to verify that the task definition has been updated successfully:
           ```
           aws ecs describe-task-definition --task-definition <updated-task-definition-arn>
           ```

        By following these steps, you can remediate the misconfiguration of ECS tasks with network mode host having limited permissions in AWS Kubernetes using AWS CLI.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the misconfiguration of ECS tasks with network mode host having limited permissions in AWS Kubernetes using Python, you can follow these steps:

        ```python theme={null}
        # Describe task definition
        response = ecs_client.describe_task_definition(taskDefinition=task_definition_arn)
        task_definition = response['taskDefinition']

        # Modify the task definition to ensure user is not "root" or not specified
        for container_definition in task_definition['containerDefinitions']:
            if container_definition['networkMode'] == 'host':
                if container_definition.get('user', '') == 'root' or not container_definition.get('user', ''):
                    container_definition['user'] = 'non-root-user'  # Specify a non-root user

        # Register the updated task definition
        response = ecs_client.register_task_definition(**task_definition)
        print(f"Task definition '{task_definition_arn}' remediated.")

        def main():
            # Specify the ARN of the ECS task definition to remediate
            task_definition_arn = 'your-task-definition-arn'

            # Remediate the ECS task definition
            remediate_ecs_task_definition(task_definition_arn)

        if __name__ == "__main__":
            main()
        ```

        Replace `'your-task-definition-arn'` with the ARN of the ECS task definition you want to remediate. This script retrieves the task definition, modifies it to ensure the user is not "root" or not specified for containers using the host network mode, and registers the updated task definition. Adjust the script to specify a non-root user as needed.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        resource "aws_ecs_task_definition" "HOST_MODE_TASK" {
          family                   = "FAMILY_NAME"            # replace with your ECS task definition family
          network_mode             = "host"
          requires_compatibilities = ["EC2"]
          cpu                      = "256"                    # adjust as needed
          memory                   = "512"                    # adjust as needed
          execution_role_arn       = "EXECUTION_ROLE_ARN"     # replace with your IAM role ARN
          task_role_arn            = "TASK_ROLE_ARN"          # replace with your IAM role ARN

          # IMPORTANT: do NOT include a "user" field in any container definition when network_mode = "host"
          container_definitions = jsonencode([
            {
              name         = "CONTAINER_NAME"                 # replace with your container name
              image        = "IMAGE_URI"                      # replace with your image
              essential    = true
              portMappings = [
                {
                  containerPort = 80
                  hostPort      = 80
                  protocol      = "tcp"
                }
              ]
              # "user" field REMOVED to match the verified CLI remediation
              # e.g., do NOT include: "user" = "1000" or "user" = "root"
            }
          ])
        }
        ```

        Changing `container_definitions` in `aws_ecs_task_definition` forces creation of a new task definition revision (replacement of this resource in Terraform terms); you must ensure any `aws_ecs_service` or schedulers are updated to reference the new revision if you manage them in Terraform.

        For verification, `terraform plan` should show the existing `aws_ecs_task_definition` being replaced with a new one whose JSON-encoded `container_definitions` no longer contain a `user` field for any container when `network_mode` is `"host"`.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>

### Additional Reading:

* [https://docs.aws.amazon.com/config/latest/developerguide/ecs-task-definition-user-for-host-mode-check.html](https://docs.aws.amazon.com/config/latest/developerguide/ecs-task-definition-user-for-host-mode-check.html)
