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

# KMS Key Should Be Associated With Minimum Users

### More Info:

KMS keys should be monitored to ensure that they are not overexposed i.e. there is at most a certain number of users associated with a key.

### 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)
* NIS2 Directive
* 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 "KMS Key Should Be Associated With Minimum Users" for GCP using GCP console, you can follow these steps:

        1. Go to the Google Cloud Console and select the project where the KMS key is located.
        2. In the navigation menu, select "Security" and then "Key Management".
        3. Find the KMS key that needs to be updated and click on its name.
        4. In the "Permissions" tab, review the current users and service accounts that have access to the key.
        5. Remove any unnecessary users and service accounts from the key's permissions list.
        6. Click on the "Add Member" button to add new users or service accounts to the key's permissions list.
        7. Select the appropriate role for each user or service account, such as "Cloud KMS CryptoKey Encrypter/Decrypter" or "Cloud KMS CryptoKey Decrypter".
        8. Click "Save" to apply the changes to the key's permissions.

        By following these steps, you can ensure that the KMS key is associated with the minimum number of users necessary, reducing the risk of unauthorized access to the key.

        #
      </Accordion>

      <Accordion title="Using CLI">
        To remediate the misconfiguration "KMS Key Should Be Associated With Minimum Users" in GCP using GCP CLI, you can follow these steps:

        1. Open the GCP Cloud Shell and ensure that you have the necessary permissions to create and manage KMS keys.

        2. Identify the KMS key that is associated with more users than required. You can use the following command to list all the KMS keys in your project:

           ```
           gcloud kms keyrings list --location [LOCATION]
           ```

           Replace `[LOCATION]` with the location of your keyring.

        3. Once you have identified the KMS key, you can check the IAM policy associated with it using the following command:

           ```
           gcloud kms keys get-iam-policy [KEY-NAME] --location [LOCATION] --keyring [KEYRING-NAME]
           ```

           Replace `[KEY-NAME]`, `[LOCATION]`, and `[KEYRING-NAME]` with the name of your KMS key, the location of your keyring, and the name of your keyring, respectively.

        4. Review the IAM policy and identify the users who have access to the KMS key. Remove the unnecessary users from the IAM policy using the following command:

           ```
           gcloud kms keys remove-iam-policy-binding [KEY-NAME] --location [LOCATION] --keyring [KEYRING-NAME] --member [MEMBER] --role [ROLE]
           ```

           Replace `[KEY-NAME]`, `[LOCATION]`, and `[KEYRING-NAME]` with the name of your KMS key, the location of your keyring, and the name of your keyring, respectively. Replace `[MEMBER]` with the email address of the user that you want to remove from the IAM policy. Replace `[ROLE]` with the role that the user has in the IAM policy.

        5. Verify that the user has been removed from the IAM policy using the following command:

           ```
           gcloud kms keys get-iam-policy [KEY-NAME] --location [LOCATION] --keyring [KEYRING-NAME]
           ```

           Replace `[KEY-NAME]`, `[LOCATION]`, and `[KEYRING-NAME]` with the name of your KMS key, the location of your keyring, and the name of your keyring, respectively.

        6. Repeat steps 4-5 for all the unnecessary users who have access to the KMS key.

        7. Once you have removed all the unnecessary users from the IAM policy, verify that the KMS key is associated with the minimum required users.

        By following these steps, you can remediate the misconfiguration "KMS Key Should Be Associated With Minimum Users" in GCP using GCP CLI.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the KMS Key Should Be Associated With Minimum Users misconfiguration in GCP using Python, you can follow these steps:

        1. First, you need to identify the KMS key that has more than the minimum required number of users associated with it. You can use the Google Cloud KMS API to list all the keys and their associated users.

        ```python theme={null}
        from google.oauth2 import service_account
        from googleapiclient.discovery import build

        # Set the credentials
        creds = service_account.Credentials.from_service_account_file('path/to/key.json')

        # Create the Cloud KMS API client
        kms_client = build('cloudkms', 'v1', credentials=creds)

        # List all the keys
        keys = kms_client.projects().locations().keyRings().cryptoKeys().list(parent='projects/<project_id>/locations/<location>/keyRings/<key_ring_id>').execute()

        # Iterate over all the keys
        for key in keys['cryptoKeys']:
            # Get the number of users associated with the key
            num_users = len(key['iamPolicy']['bindings'])
            # Check if the number of users is greater than the minimum required
            if num_users > 1:
                # Print the key and the number of users
                print(f"Key {key['name']} has {num_users} users.")
        ```

        2. Once you have identified the keys that have more than the minimum required number of users, you need to remove the excess users from the key. You can use the same API to update the IAM policy of the key and remove the excess users.

        ```python theme={null}
        # Set the key name
        key_name = 'projects/<project_id>/locations/<location>/keyRings/<key_ring_id>/cryptoKeys/<key_id>'

        # Set the minimum required number of users
        min_users = 1

        # Get the IAM policy for the key
        iam_policy = kms_client.projects().locations().keyRings().cryptoKeys().getIamPolicy(resource=key_name).execute()

        # Get the list of bindings for the key
        bindings = iam_policy.get('bindings', [])

        # Iterate over the bindings and remove the excess users
        for binding in bindings:
            if binding['role'] == 'roles/cloudkms.cryptoKeyEncrypterDecrypter' and len(binding['members']) > min_users:
                excess_users = binding['members'][min_users:]
                for user in excess_users:
                    binding['members'].remove(user)

        # Update the IAM policy for the key
        updated_policy = kms_client.projects().locations().keyRings().cryptoKeys().setIamPolicy(resource=key_name, body={'policy': iam_policy}).execute()
        ```

        3. Finally, you can verify that the excess users have been removed from the key by listing the keys and their associated users again.

        ```python theme={null}
        # List all the keys
        keys = kms_client.projects().locations().keyRings().cryptoKeys().list(parent='projects/<project_id>/locations/<location>/keyRings/<key_ring_id>').execute()

        # Iterate over all the keys
        for key in keys['cryptoKeys']:
            # Get the number of users associated with the key
            num_users = len(key['iamPolicy']['bindings'])
            # Check if the number of users is greater than the minimum required
            if num_users > 1:
                # Print the key and the number of users
                print(f"Key {key['name']} has {num_users} users.")
        ```

        This should remediate the KMS Key Should Be Associated With Minimum Users misconfiguration in GCP.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        resource "google_kms_key_ring" "example" {
          name     = "KEY_RING_NAME"        # Replace with your key ring name
          location = "KMS_LOCATION"         # Replace, e.g. "us-central1"
          project  = "PROJECT_ID"           # Replace with your project ID
        }

        resource "google_kms_crypto_key" "example" {
          name            = "CRYPTO_KEY_NAME"  # Replace with your crypto key name
          key_ring        = google_kms_key_ring.example.id
          rotation_period = "2592000s"         # Example: 30 days
        }

        # IAM binding for the crypto key with at most 10 members, per policy
        resource "google_kms_crypto_key_iam_binding" "crypto_key_users" {
          crypto_key_id = google_kms_crypto_key.example.id
          role          = "roles/cloudkms.cryptoKeyEncrypterDecrypter"

          members = [
            "user:USER_1@example.com",
            "user:USER_2@example.com",
            # ...
            # Add up to 10 total members here to satisfy max_users = 10
          ]
        }
        ```

        This Terraform limits the number of principals directly associated with the KMS crypto key role by explicitly listing at most 10 `members` for the key’s IAM binding; do not add more than 10 entries or the check will fail. No resource replacement is forced; Terraform will update the IAM binding in place.

        For verification, `terraform plan` should show updates only to the `google_kms_crypto_key_iam_binding.crypto_key_users` resource, reducing or capping the `members` list so that it contains no more than 10 entries.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
