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

# Customer Master Keys (CMKs) Should Be Used

### More Info:

Delete any disabled KMS Customer Master Keys (CMKs) and remove them in order to lower costs.

### Risk Level

Low

### Address

Reliability, 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
* DPDPA
* Digital Operational Resilience Act (EU)
* ISO/IEC 27017
* ISO/IEC 27018
* ISO/IEC 27701
* KSA PDPL
* MAS Technology Risk Management (Singapore)
* MITRE ATT\&CK (Cloud)
* NIS2 Directive
* NIST
* 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 "Customer Master Keys (CMKs) Should Be Used" for GCP using GCP console, follow the below steps:

        1. Log in to the Google Cloud Console.
        2. Navigate to the Cloud KMS page.
        3. Click on "Create Key Ring" to create a new key ring.
        4. Enter a name for the key ring and select the location where you want to create the key ring.
        5. Click on "Create".
        6. Navigate to the "Create Key" page.
        7. Select the key ring that you created in step 4.
        8. Enter a name for the key and select the key version.
        9. Select the key algorithm and protection level.
        10. Click on "Create".
        11. Navigate to the "IAM" page.
        12. Click on "Add Member" to add a new member to the project.
        13. Enter the email address of the member and select the role that you want to assign to the member.
        14. Click on "Save".

        By following these steps, you have now created a new key ring, created a new key, and assigned a role to a member. You can now use this key to encrypt and decrypt data in GCP.

        #
      </Accordion>

      <Accordion title="Using CLI">
        To remediate the misconfiguration "Customer Master Keys (CMKs) Should Be Used" for GCP using GCP CLI, follow these steps:

        1. Open the Google Cloud Console and navigate to the Cloud Key Management Service (KMS) page.

        2. Create a new key ring and key for your project if you haven't already done so.

        3. Use the following command to create a new symmetric key for your project:

           ```
           gcloud kms keys create <KEY-NAME> --location <LOCATION> --keyring <KEY-RING-NAME> --purpose encryption
           ```

           Replace `<KEY-NAME>`, `<LOCATION>`, and `<KEY-RING-NAME>` with the appropriate values for your project.

        4. Use the following command to encrypt your data using the new key:

           ```
           gcloud kms encrypt --plaintext-file=<PLAINTEXT-FILE> --ciphertext-file=<CIPHERTEXT-FILE> --location=<LOCATION> --keyring=<KEY-RING-NAME> --key=<KEY-NAME>
           ```

           Replace `<PLAINTEXT-FILE>`, `<CIPHERTEXT-FILE>`, `<LOCATION>`, `<KEY-RING-NAME>`, and `<KEY-NAME>` with the appropriate values for your project.

        5. Update your application or service to use the new encrypted data.

        6. Verify that the new key is being used to encrypt and decrypt your data by checking the Cloud KMS audit logs.

        By following these steps, you can remediate the misconfiguration "Customer Master Keys (CMKs) Should Be Used" for GCP using GCP CLI.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the misconfiguration "Customer Master Keys (CMKs) Should Be Used" in GCP using Python, you can follow the below steps:

        1. Import the necessary libraries:

        ```python theme={null}
        from googleapiclient import discovery
        from oauth2client.client import GoogleCredentials
        ```

        2. Authenticate and create a client object:

        ```python theme={null}
        credentials = GoogleCredentials.get_application_default()
        service = discovery.build('cloudkms', 'v1', credentials=credentials)
        ```

        3. List all the key rings:

        ```python theme={null}
        key_rings = service.projects().locations().keyRings().list(parent='projects/[PROJECT_ID]/locations/[LOCATION]').execute()
        ```

        Note: Replace \[PROJECT\_ID] and \[LOCATION] with your project ID and location respectively.

        4. Loop through each key ring and list all the crypto keys:

        ```python theme={null}
        for key_ring in key_rings['keyRings']:
            crypto_keys = service.projects().locations().keyRings().cryptoKeys().list(parent=key_ring['name']).execute()
        ```

        5. Check if the crypto key has a customer-managed encryption key:

        ```python theme={null}
        for crypto_key in crypto_keys['cryptoKeys']:
            if crypto_key['purpose'] == 'ENCRYPT_DECRYPT' and 'customerManagedEncryption' not in crypto_key:
                # Create a new customer-managed encryption key
                # Update the crypto key to use the new key
        ```

        6. If the crypto key does not have a customer-managed encryption key, create a new one:

        ```python theme={null}
        key_ring_name = key_ring['name'].split('/')[-1]
        location = key_ring['name'].split('/')[-3]
        key_name = 'new-customer-key'

        request_body = {
            'purpose': 'ENCRYPT_DECRYPT',
            'versionTemplate': {
                'algorithm': 'GOOGLE_SYMMETRIC_ENCRYPTION',
            },
            'encryptionAlgorithm': 'GOOGLE_SYMMETRIC_ENCRYPTION',
            'protectionLevel': 'SOFTWARE',
            'customerManagedEncryption': {
                'kmsKeyName': 'projects/[PROJECT_ID]/locations/[LOCATION]/keyRings/{}/cryptoKeys/{}'.format(key_ring_name, key_name)
            }
        }

        response = service.projects().locations().keyRings().cryptoKeys().create(parent='projects/[PROJECT_ID]/locations/{}'.format(location), body=request_body).execute()
        ```

        7. Update the crypto key to use the new customer-managed encryption key:

        ```python theme={null}
        update_body = {
            'cryptoKey': {
                'name': crypto_key['name'],
                'purpose': crypto_key['purpose'],
                'versionTemplate': crypto_key['versionTemplate'],
                'nextRotationTime': crypto_key['nextRotationTime'],
                'rotationPeriod': crypto_key['rotationPeriod'],
                'labels': crypto_key['labels'],
                'customerManagedEncryption': {
                    'kmsKeyName': 'projects/[PROJECT_ID]/locations/[LOCATION]/keyRings/{}/cryptoKeys/{}'.format(key_ring_name, key_name)
                }
            },
            'updateMask': 'customerManagedEncryption'
        }

        response = service.projects().locations().keyRings().cryptoKeys().patch(name=crypto_key['name'], body=update_body).execute()
        ```

        Note: Replace \[PROJECT\_ID] and \[LOCATION] with your project ID and location respectively.

        By following these steps, you can remediate the misconfiguration "Customer Master Keys (CMKs) Should Be Used" in GCP using Python.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        # This is the resource that must be *removed* from Terraform to delete the disabled CMK.
        # Update it only if you currently have prevent_destroy set, so it can be destroyed safely.

        resource "google_kms_crypto_key" "DISABLED_CMK_TO_REMOVE" {
          name            = "DISABLED_CMK_NAME"          # replace with the disabled CMK name
          key_ring        = google_kms_key_ring.KEYRING.id
          purpose         = "ENCRYPT_DECRYPT"

          # Ensure this is not blocking deletion; then remove this entire resource block
          # from your configuration and run `terraform apply` to destroy the key.
          lifecycle {
            prevent_destroy = false
          }
        }
        ```

        Deleting the disabled CMK is an irreversible destroy operation (you cannot recover data encrypted with that key if no other copies exist); confirm that the key is not needed before removing this resource block and applying.

        For verification, after you delete the `google_kms_crypto_key.DISABLED_CMK_TO_REMOVE` block from your Terraform code, `terraform plan` should show this resource with a `-` prefix, indicating it will be destroyed.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
