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

# Disable Automatic IAM Role Grants for Default Service Accounts

### More Info:

Ensure that Disable Automatic IAM Grants for Default Service Accounts policy is enforced for your Google Cloud Platform (GCP) organizations in order to deactivate the automatic IAM role grant for default service accounts.

### Risk Level

Medium

### Address

Operational Maturity, Security

### Compliance Standards

* Cloudanix Best Practice

### Triage and Remediation

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To remediate the misconfiguration "Disable Automatic IAM Role Grants for Default Service Accounts" in GCP using GCP console, please follow the below steps:

        1. Login to your GCP console.
        2. Navigate to the "IAM & Admin" section from the left-hand side menu.
        3. Click on the "Settings" tab.
        4. Scroll down to the "Service Accounts" section.
        5. In the "Service Accounts" section, you will find the option "Enable automatic role grants for default service accounts". Make sure this option is unchecked. If it is checked, click on the edit button (pencil icon) and uncheck the option.
        6. Once you have unchecked the option, click on the "Save" button to save the changes.

        By following the above steps, you have successfully remediated the misconfiguration "Disable Automatic IAM Role Grants for Default Service Accounts" in GCP using GCP console.

        #
      </Accordion>

      <Accordion title="Using CLI">
        To remediate the misconfiguration of "Disable Automatic IAM Role Grants for Default Service Accounts" in GCP, you can follow the below steps using GCP CLI:

        1. Open the GCP Cloud Shell or any terminal with GCP CLI installed.

        2. Run the following command to list the existing default service accounts in your project:

        ```
        gcloud iam service-accounts list
        ```

        3. Select the default service account for which you want to disable the automatic IAM role grant. For example, if you want to disable it for the Compute Engine default service account, run the following command:

        ```
        gcloud iam service-accounts describe <COMPUTE_ENGINE_DEFAULT_SERVICE_ACCOUNT_EMAIL>
        ```

        Replace `<COMPUTE_ENGINE_DEFAULT_SERVICE_ACCOUNT_EMAIL>` with the email address of the Compute Engine default service account.

        4. Once you have identified the default service account, run the following command to disable the automatic IAM role grant:

        ```
        gcloud projects add-iam-policy-binding <PROJECT_ID> --member serviceAccount:<DEFAULT_SERVICE_ACCOUNT_EMAIL> --role roles/iam.serviceAccountUser --condition=None
        ```

        Replace `<PROJECT_ID>` with your GCP project ID and `<DEFAULT_SERVICE_ACCOUNT_EMAIL>` with the email address of the default service account that you want to modify.

        5. Verify that the automatic IAM role grant has been disabled for the default service account by running the following command:

        ```
        gcloud iam service-accounts get-iam-policy <DEFAULT_SERVICE_ACCOUNT_EMAIL>
        ```

        This should return an empty policy for the default service account, indicating that no roles are automatically granted.

        That's it! You have successfully remediated the misconfiguration of "Disable Automatic IAM Role Grants for Default Service Accounts" in GCP using GCP CLI.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the misconfiguration "Disable Automatic IAM Role Grants for Default Service Accounts" for GCP using Python, follow the below steps:

        1. First, you need to create a service account for your project using the GCP console. Give it the necessary permissions to manage IAM roles.

        2. Install the necessary Python libraries for GCP authentication and authorization. You can use the following command to install these libraries:

        ```
        !pip install google-auth google-auth-oauthlib google-auth-httplib2 google-cloud-iam google-cloud-resource-manager
        ```

        3. Authenticate and authorize your Python script to access your GCP project. You can use the following code snippet to do this:

        ```
        from google.oauth2 import service_account
        from google.cloud import iam

        credentials = service_account.Credentials.from_service_account_file(
            'path/to/your/service_account.json')
        client = iam.IAMClient(credentials=credentials)
        ```

        4. List all the default service accounts in your GCP project. You can use the following code snippet to do this:

        ```
        from google.cloud import resource_manager

        project_id = 'your-project-id'
        client = resource_manager.Client()
        project = client.project(project_id)
        service_accounts = client.list_service_accounts(project)
        for account in service_accounts:
            if account.email.startswith('default'):
                print(account.email)
        ```

        5. Disable automatic IAM role grants for each default service account. You can use the following code snippet to do this:

        ```
        from google.api_core.exceptions import NotFound

        project_id = 'your-project-id'
        policy = client.get_policy(project_id)
        for binding in policy.bindings:
            if binding.role == 'roles/editor':
                for member in binding.members:
                    if member.startswith('serviceAccount:'):
                        try:
                            client.test_iam_permissions(
                                member, ['iam.roles.delete'])
                            client.set_iam_policy(
                                member, {'bindings': []})
                        except NotFound:
                            pass
        ```

        This code snippet will remove all the IAM role grants for the default service accounts in the specified project. You can modify the code to suit your specific requirements.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        resource "google_org_policy_policy" "disable_default_sa_auto_grants" {
          # Replace with your organization numeric ID, e.g. "organizations/123456789012"
          parent   = "organizations/ORG_ID"
          name     = "organizations/ORG_ID/policies/constraints/iam.automaticIamGrantsForDefaultServiceAccounts"

          spec {
            rules {
              enforce = true
            }
          }
        }
        ```

        Replace `ORG_ID` with your GCP organization ID. This change does not force replacement of any existing project resources, but it enforces the org policy across the organization.

        To verify, `terraform plan` should show creation or update of a `google_org_policy_policy.disable_default_sa_auto_grants` resource with `spec.rules[0].enforce = true` and no other unrelated changes.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
