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

# Azure audit keyvault keys need rotation remediation

### Triage and Remediation

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To remediate the issue of keys about to expire and need rotation in Azure using the Azure console, you can follow the below steps:

        1. Login to the Azure portal using your credentials.
        2. Navigate to the resource group where the key is stored.
        3. Select the key that needs to be rotated.
        4. Click on the "Rotate" button at the top of the page.
        5. Follow the on-screen instructions to complete the key rotation process.
        6. Once the key rotation process is complete, update the application or service that uses the key with the new key.

        It's important to note that you should regularly rotate your keys to prevent unauthorized access and protect your resources. Azure provides different options for key rotation, such as automatic key rotation or manual key rotation, based on your requirements.

        #
      </Accordion>

      <Accordion title="Using CLI">
        To remediate the misconfiguration of expiring keys in Azure using Azure CLI, follow the below steps:

        1. Open the Azure CLI in your terminal or command prompt.
        2. Log in to your Azure account using the command "az login".
        3. Once you are logged in, run the command "az account list" to see the list of all your Azure subscriptions.
        4. Select the subscription that has the expiring keys using the command `az account set --subscription <subscription_id>`.
        5. Check the current status of the keys using the command `az ad sp credential list --id <service_principal_id>`.
        6. Create a new key using the command `az ad sp credential reset --name <service_principal_id>`.
        7. The above command will return a JSON object that contains the new key. Copy the value of the "value" field.
        8. Update the key value in your application or service that is using the service principal.
        9. Verify that the new key is working by running a test on your application or service.

        By following the above steps, you can remediate the misconfiguration of expiring keys in Azure using Azure CLI.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the issue of key expiration and rotation for Azure using Python, you can follow the below steps:

        1. Install the Azure SDK for Python using the following command:

        ```python theme={null}
        pip install azure-mgmt-resource
        ```

        2. Authenticate with Azure using Azure Active Directory credentials. You can use the following code snippet to authenticate:

        ```python theme={null}
        from azure.common.credentials import UserPassCredentials
        from azure.mgmt.resource import ResourceManagementClient

        subscription_id = 'your-subscription-id'
        username = 'your-username'
        password = 'your-password'
        tenant_id = 'your-tenant-id'

        credentials = UserPassCredentials(username, password, tenant_id)
        resource_client = ResourceManagementClient(credentials, subscription_id)
        ```

        3. Retrieve the list of expired keys using the following code snippet:

        ```python theme={null}
        from datetime import datetime, timedelta

        expiry_date = datetime.now() - timedelta(days=30) # Change the number of days as per your requirement

        expired_keys = []
        for key in resource_client.providers.get('Microsoft.Storage').resource_types.get('storageAccounts').api_versions[0].locations[0].properties.supported_operations[5].description.split('\n')[1:]:
            if datetime.strptime(key.split(':')[-1], '%Y-%m-%dT%H:%M:%S.%fZ') < expiry_date:
                expired_keys.append(key.split(':')[0])
        ```

        4. Rotate the expired keys using the following code snippet:

        ```python theme={null}
        for key in expired_keys:
            resource_client.providers.get('Microsoft.Storage').resource_types.get('storageAccounts').api_versions[0].locations[0].properties.supported_operations[6].invoke(
                resource_group_name='your-resource-group-name',
                account_name='your-storage-account-name',
                parameters={
                    'keyName': key
                }
            )
        ```

        Replace the placeholders in the code with the appropriate values for your Azure subscription, resource group, and storage account.

        These steps will help you remediate the issue of key expiration and rotation for Azure using Python.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        # Configure a rotation policy so the Key Vault key is automatically rotated
        # 15 days before it expires (P15D = period of 15 days).
        #
        # NOTE: Terraform cannot itself "rotate now if < 15 days to expiry";
        # that immediate rotation must be done with Azure CLI/Portal.
        # This policy prevents the issue from recurring.

        resource "azurerm_key_vault_key" "KEY_TO_PROTECT" {
          name         = "KEY_NAME"                    # replace with your key name
          key_vault_id = azurerm_key_vault.VAULT.id    # replace with your Key Vault resource
          key_type     = "RSA"
          key_size     = 2048

          # Optionally set explicit expiry for the key
          expiration_date = "2030-12-31T23:59:59Z"     # replace with desired RFC3339 timestamp
        }

        resource "azurerm_key_vault_key_rotation_policy" "KEY_ROTATION_POLICY" {
          key_vault_id = azurerm_key_vault.VAULT.id    # same vault as above
          key_name     = azurerm_key_vault_key.KEY_TO_PROTECT.name

          lifetime_actions {
            action {
              type = "Rotate"
            }

            trigger {
              # Rotate 15 days before expiry to honor minDays = 15
              time_before_expiry = "P15D"
            }
          }

          # Optional: ensure there is always a fresh version at most every N days
          # lifetime_actions {
          #   action {
          #     type = "Rotate"
          #   }
          #
          #   trigger {
          #     time_after_create = "P180D"  # rotate every 180 days; adjust as needed
          #   }
          # }
        }
        ```

        Terraform cannot conditionally create a new key version based on “days until expiry” at apply time; to immediately rotate keys that are already within 15 days of expiry you must run an operational command such as:

        ```bash theme={null}
        az keyvault key rotate --vault-name VAULT_NAME --name KEY_NAME
        ```

        After adding the Terraform rotation policy and running `terraform plan`, you should see a new `azurerm_key_vault_key_rotation_policy.KEY_ROTATION_POLICY` to be created, with `lifetime_actions.trigger.time_before_expiry` set to `"P15D"` and no replacement of the existing key resource.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
