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

# Privileged Mode Should Be Enabled CodeBuild Project Environment

### More Info:

This rule verifies whether privileged mode is enabled for the environment of an AWS CodeBuild project. Enabling privileged mode allows the build container to access resources that are not accessible to non-privileged containers. Its important to carefully evaluate the need for privileged mode to prevent potential security vulnerabilities.

### Risk Level

Medium

### 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 enable privileged mode for an AWS CodeBuild project using the AWS Management Console:

        1. **Sign in to the AWS Console**
           * Go to: [https://console.aws.amazon.com/](https://console.aws.amazon.com/)
           * Make sure you are in the correct **Region** where the CodeBuild project exists.

        2. **Open CodeBuild**
           * In the top search bar, type **CodeBuild** and select **CodeBuild** from the results.

        3. **Select the Project**
           * In the left menu, click **Build projects**.
           * Find your project in the list and click the **project name**.

        4. **Edit the Project**
           * On the project details page, in the top right, click **Edit**.

        5. **Go to Environment Settings**
           * Scroll to the **Environment** section.
           * Look for the **Additional configuration** or directly visible environment options (AWS occasionally shifts the layout).

        6. **Enable Privileged Mode**
           * Find the checkbox **Privileged** (sometimes labeled “Enable this flag if you want to build Docker images or use the Docker daemon”).
           * Check **Privileged** to enable privileged mode.

        7. **Save Changes**
           * Scroll to the bottom of the page.
           * Click **Update build project** (or **Save changes**, depending on UI).

        8. **Verify**
           * After saving, reopen the project’s details page.
           * Confirm under **Environment** that **Privileged mode** is shown as **Enabled**.

        You can now run builds that require Docker-in-Docker or access to the Docker daemon inside the build container.
      </Accordion>

      <Accordion title="Using CLI">
        To enable privileged mode on an existing AWS CodeBuild project via AWS CLI, you must update the project’s environment configuration and set `privilegedMode` to `true`.

        ### 1. Get the existing project configuration

        ```bash theme={null}
        PROJECT_NAME="my-codebuild-project"

        aws codebuild batch-get-projects \
          --names "$PROJECT_NAME" \
          > project.json
        ```

        The file `project.json` will contain all current settings.

        ### 2. Extract the current environment block

        ```bash theme={null}
        ENVIRONMENT_JSON=$(jq -r '.projects[0].environment' project.json)
        echo "$ENVIRONMENT_JSON" | jq
        ```

        You’ll see fields like `type`, `image`, `computeType`, `environmentVariables`, etc.

        ### 3. Modify environment to enable privilegedMode

        Use `jq` to add/set `"privilegedMode": true`:

        ```bash theme={null}
        UPDATED_ENVIRONMENT=$(echo "$ENVIRONMENT_JSON" \
          | jq '.privilegedMode = true')
        ```

        ### 4. Update the project with the modified environment

        You must pass all required environment fields back, not just `privilegedMode`.

        ```bash theme={null}
        aws codebuild update-project \
          --name "$PROJECT_NAME" \
          --environment "$UPDATED_ENVIRONMENT"
        ```

        If you also need to preserve/update other fields (e.g., `serviceRole`, `source`, `artifacts`, etc.), you can supply them too, for example:

        ```bash theme={null}
        SERVICE_ROLE=$(jq -r '.projects[0].serviceRole' project.json)
        DESCRIPTION=$(jq -r '.projects[0].description // empty' project.json)
        SOURCE=$(jq -r '.projects[0].source' project.json)
        ARTIFACTS=$(jq -r '.projects[0].artifacts' project.json)
        CACHE=$(jq -r '.projects[0].cache' project.json)
        TAGS=$(jq -r '.projects[0].tags' project.json)
        VPC_CONFIG=$(jq -r '.projects[0].vpcConfig' project.json)

        aws codebuild update-project \
          --name "$PROJECT_NAME" \
          --description "$DESCRIPTION" \
          --service-role "$SERVICE_ROLE" \
          --source "$SOURCE" \
          --artifacts "$ARTIFACTS" \
          --cache "$CACHE" \
          --environment "$UPDATED_ENVIRONMENT" \
          --vpc-config "$VPC_CONFIG" \
          --tags "$TAGS"
        ```

        (Include only the parameters relevant to your project; some optional fields may be omitted if not in use.)

        ### 5. Verify privileged mode is enabled

        ```bash theme={null}
        aws codebuild batch-get-projects \
          --names "$PROJECT_NAME" \
          | jq '.projects[0].environment.privilegedMode'
        ```

        The output should be `true`.
      </Accordion>

      <Accordion title="Using Python">
        To remediate this, you need to update each affected CodeBuild project and set `environment.privilegedMode = True` using the CodeBuild API (via `boto3` in Python).

        Below is a minimal, complete example.

        ***

        ### 1. Install and configure `boto3` (if not already)

        ```bash theme={null}
        pip install boto3
        aws configure   # configure credentials & region
        ```

        ***

        ### 2. Python script to enable privileged mode on one project

        ```python theme={null}
        import boto3

        codebuild = boto3.client("codebuild")

        PROJECT_NAME = "your-project-name"  # <-- change this

        def enable_privileged_mode(project_name: str):
            # 1. Get existing project configuration
            resp = codebuild.batch_get_projects(names=[project_name])
            if not resp["projects"]:
                raise ValueError(f"Project '{project_name}' not found")

            project = resp["projects"][0]

            # 2. Prepare updated fields
            # Most fields are required when calling update_project,
            # so we copy the existing config and modify environment.privilegedMode.
            updated_environment = project["environment"].copy()
            updated_environment["privilegedMode"] = True

            # 3. Call update_project with all required parameters
            codebuild.update_project(
                name=project["name"],
                description=project.get("description"),
                source=project["source"],
                secondarySources=project.get("secondarySources", []),
                artifacts=project["artifacts"],
                secondaryArtifacts=project.get("secondaryArtifacts", []),
                cache=project.get("cache"),
                environment=updated_environment,
                serviceRole=project["serviceRole"],
                timeoutInMinutes=project.get("timeoutInMinutes"),
                queuedTimeoutInMinutes=project.get("queuedTimeoutInMinutes"),
                encryptionKey=project.get("encryptionKey"),
                tags=project.get("tags", []),
                vpcConfig=project.get("vpcConfig"),
                badgeEnabled=project.get("badge"]["badgeEnabled"] if "badge" in project else None,
                logsConfig=project.get("logsConfig"),
                fileSystemLocations=project.get("fileSystemLocations", []),
                buildBatchConfig=project.get("buildBatchConfig"),
                concurrentBuildLimit=project.get("concurrentBuildLimit"),
                visibility=project.get("visibility"),
                resourceAccessRole=project.get("resourceAccessRole"),
                buildTimeoutInMinutes=project.get("buildTimeoutInMinutes"),
                queuedTimeoutInMinutesOverride=project.get("queuedTimeoutInMinutesOverride")
            )

            print(f"Privileged mode enabled for project: {project_name}")

        if __name__ == "__main__":
            enable_privileged_mode(PROJECT_NAME)
        ```

        > Note: Some optional parameters vary by SDK version; if any key is invalid in your environment, remove it from `update_project`. At minimum, you must pass `name`, `source`, `artifacts`, `environment`, and `serviceRole`.

        ***

        ### 3. Script to enable privileged mode for all projects that don’t have it

        ```python theme={null}
        import boto3

        codebuild = boto3.client("codebuild")

        def list_all_projects():
            names = []
            token = None
            while True:
                kwargs = {}
                if token:
                    kwargs["nextToken"] = token
                resp = codebuild.list_projects(**kwargs)
                names.extend(resp.get("projects", []))
                token = resp.get("nextToken")
                if not token:
                    break
            return names

        def enable_privileged_on_all():
            project_names = list_all_projects()
            for chunk_start in range(0, len(project_names), 100):
                chunk = project_names[chunk_start:chunk_start + 100]
                projects_resp = codebuild.batch_get_projects(names=chunk)
                for project in projects_resp["projects"]:
                    env = project["environment"]
                    if env.get("privilegedMode"):
                        continue  # already enabled

                    env_updated = env.copy()
                    env_updated["privilegedMode"] = True

                    codebuild.update_project(
                        name=project["name"],
                        source=project["source"],
                        artifacts=project["artifacts"],
                        environment=env_updated,
                        serviceRole=project["serviceRole"],
                    )
                    print(f"Enabled privilegedMode for {project['name']}")

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

        (Here we only use the minimum required fields to keep the example simple; add other fields as needed, following the first script.)

        ***

        This will remediate the “Privileged Mode Should Be Enabled” finding by programmatically turning on `privilegedMode` for the CodeBuild project environment via Python.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        resource "aws_codebuild_project" "THIS_PROJECT" {
          name         = "CODEBUILD_PROJECT_NAME" # replace with your project name
          service_role = "CODEBUILD_SERVICE_ROLE_ARN" # replace with an IAM role ARN

          environment {
            compute_type                = "BUILD_GENERAL1_SMALL"
            image                       = "aws/codebuild/standard:7.0"
            type                        = "LINUX_CONTAINER"
            privileged_mode             = true          # enable privileged mode
            image_pull_credentials_type = "CODEBUILD"
          }

          source {
            type            = "GITHUB"
            location        = "REPO_CLONE_URL" # replace with your repo
            git_clone_depth = 1
          }

          artifacts {
            type = "NO_ARTIFACTS"
          }

          # ...any other arguments you already use...
        }
        ```

        This change updates the existing CodeBuild project in place; it does not force resource replacement. After editing, `terraform plan` should show an in-place update with `privileged_mode` changing from `false` (or omitted) to `true` for the `environment` block of `aws_codebuild_project.THIS_PROJECT`.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>

### Additional Reading:

* [https://docs.aws.amazon.com/config/latest/developerguide/codebuild-project-environment-privileged-check.html](https://docs.aws.amazon.com/config/latest/developerguide/codebuild-project-environment-privileged-check.html)
