> ## 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 roles assumable by database services remediation

### Triage and Remediation

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To remediate the issue of roles assumable by database services in Azure IAM, follow these step-by-step instructions using the Azure console:

        1. Sign in to the Azure portal ([https://portal.azure.com](https://portal.azure.com)) using your Azure account credentials.

        2. In the Azure portal, navigate to the Azure Active Directory (AAD) service by selecting "Azure Active Directory" from the left-hand menu.

        3. In the Azure AD overview page, click on "Enterprise applications" in the left-hand menu.

        4. In the Enterprise applications page, search for "Azure Database for PostgreSQL" or "Azure Database for MySQL" based on the database service you are using.

        5. Click on the appropriate database service application.

        6. In the application's overview page, click on "Properties" in the left-hand menu.

        7. Under the "Managed application" section, click on the "Users and groups" option.

        8. In the "Users and groups" page, review the list of users and groups that have access to assume the role of the database service.

        9. Identify any users or groups that should not have this role assumption privilege and should be remediated.

        10. To remove a user or group's role assumption privilege, click on the respective user or group.

        11. In the user or group's overview page, click on the "Roles and administrators" option in the left-hand menu.

        12. In the "Roles and administrators" page, review the list of roles assigned to the user or group.

        13. Identify the role that grants the privilege to assume the role of the database service and should be removed.

        14. To remove the role, click on the role and then click on the "Remove assignment" button.

        15. Confirm the removal of the role assignment when prompted.

        16. Repeat steps 10-15 for any other users or groups that need to have their role assumption privilege remediated.

        17. Once all necessary role assumption privileges have been removed, you have successfully remediated the issue of roles assumable by database services in Azure IAM.

        Ensure to regularly review and manage the roles and permissions assigned to users and groups in Azure IAM to maintain a secure and compliant environment.

        #
      </Accordion>

      <Accordion title="Using CLI">
        To remediate the misconfiguration "Roles Assumable By Database Services" in Azure using Azure CLI, follow these step-by-step instructions:

        1. Install Azure CLI: If you haven't already, install Azure CLI on your local machine by following the instructions provided by Microsoft.

        2. Log in to Azure: Open the command prompt or terminal and log in to your Azure account using the following command:
           ```
           az login
           ```

        3. Set the Azure subscription: If you have multiple Azure subscriptions, set the appropriate subscription using the following command:
           ```
           az account set --subscription <subscription_id>
           ```

        4. List existing roles: Run the following command to list all the existing roles in your Azure subscription:
           ```
           az role definition list
           ```

        5. Identify the roles assigned to database services: Review the list of roles and identify the roles assigned to database services. These roles typically have names like "Contributor", "Owner", or "Reader".

        6. Create a custom role: If the existing roles assigned to database services do not meet your requirements, you can create a custom role with limited permissions. Create a JSON file (e.g., `custom-role.json`) with the necessary permissions for database services. Here's an example of a custom role JSON file that allows read access to databases and denies write access:

           ```json theme={null}
           {
             "Name": "Custom Database Reader",
             "IsCustom": true,
             "Description": "Read-only access to databases",
             "Actions": [
               "Microsoft.Sql/servers/databases/read",
               "Microsoft.Sql/servers/databases/list"
             ],
             "NotActions": [
               "Microsoft.Sql/servers/databases/write"
             ],
             "AssignableScopes": [
               "/subscriptions/<subscription_id>"
             ]
           }
           ```

           Modify the `AssignableScopes` field with the appropriate subscription ID.

        7. Create the custom role: Run the following command to create the custom role:
           ```
           az role definition create --role-definition custom-role.json
           ```

        8. Assign the custom role to database services: Now, assign the newly created custom role to the appropriate database services. Replace `<custom_role_name>` with the name you provided in the custom role JSON file and `<database_service_name>` with the name of the database service you want to assign the role to. Run the following command:

           ```
           az role assignment create --assignee <database_service_name> --role <custom_role_name> --scope /subscriptions/<subscription_id>
           ```

           Repeat this step for each database service that needs the custom role assigned.

        9. Verify the role assignment: To verify that the custom role has been successfully assigned to the database services, run the following command:

           ```
           az role assignment list --assignee <database_service_name>
           ```

           This command will list all the role assignments for the specified database service.

        By following these steps, you will be able to remediate the misconfiguration "Roles Assumable By Database Services" in Azure using Azure CLI.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the misconfiguration "Roles Assumable By Database Services" in Azure using Python, follow these steps:

        1. Install the necessary dependencies:
           ```python theme={null}
           pip install azure-identity azure-mgmt-resource azure-mgmt-authorization
           ```

        2. Import the required modules:
           ```python theme={null}
           from azure.identity import DefaultAzureCredential
           from azure.mgmt.authorization import AuthorizationManagementClient
           from azure.mgmt.resource import ResourceManagementClient
           ```

        3. Authenticate with Azure using the DefaultAzureCredential:
           ```python theme={null}
           credential = DefaultAzureCredential()
           authorization_client = AuthorizationManagementClient(credential, <subscription_id>)
           resource_client = ResourceManagementClient(credential, <subscription_id>)
           ```

        4. Get the list of all the role assignments for the database services:
           ```python theme={null}
           role_assignments = authorization_client.role_assignments.list(
               filter="atScope() and (roleDefinitionName eq 'Contributor' or roleDefinitionName eq 'Owner') and (principalType eq 'ServicePrincipal' or principalType eq 'User') and (scope='/providers/Microsoft.DBforPostgreSQL/servers' or scope='/providers/Microsoft.DBforMySQL/servers' or scope='/providers/Microsoft.DBforMariaDB/servers')"
           )
           ```

        5. Iterate over the role assignments and remove any inappropriate assignments:
           ```python theme={null}
           for assignment in role_assignments:
               authorization_client.role_assignments.delete_by_id(assignment.id)
           ```

        6. Verify the remediation by rechecking the role assignments:
           ```python theme={null}
           role_assignments = authorization_client.role_assignments.list(
               filter="atScope() and (roleDefinitionName eq 'Contributor' or roleDefinitionName eq 'Owner') and (principalType eq 'ServicePrincipal' or principalType eq 'User') and (scope='/providers/Microsoft.DBforPostgreSQL/servers' or scope='/providers/Microsoft.DBforMySQL/servers' or scope='/providers/Microsoft.DBforMariaDB/servers')"
           )
           if not any(role_assignments):
               print("All inappropriate role assignments have been successfully removed.")
           else:
               print("Some inappropriate role assignments still exist.")
           ```

        Make sure to replace `<subscription_id>` with your Azure subscription ID in the code above. This code will remove any role assignments for the database services in Azure that have the 'Contributor' or 'Owner' role and are assigned to Service Principals or Users.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        # Principle: restrict the role assigned to the database service's managed identity
        # so it only has the minimum permissions it needs, and scope it to the database
        # (or resource group) instead of the whole subscription.

        # Custom least-privilege role definition for the database service
        resource "azurerm_role_definition" "DB_SERVICE_MINIMAL_ROLE" {
          name        = "DB-SERVICE-MINIMAL-ROLE"
          scope       = "/subscriptions/${var.SUBSCRIPTION_ID}" # substitute your subscription ID or narrower scope
          description = "Least-privilege role for the managed identity of the database service."

          permissions {
            actions = [
              # SUBSTITUTE: list only the specific actions the database service needs,
              # for example read access to secrets/keys it must use:
              "Microsoft.KeyVault/vaults/secrets/read",
              "Microsoft.KeyVault/vaults/keys/read",
            ]

            not_actions = []
          }

          assignable_scopes = [
            # Keep this as narrow as possible, e.g. the resource group or specific resource
            "/subscriptions/${var.SUBSCRIPTION_ID}/resourceGroups/${var.DB_RESOURCE_GROUP_NAME}"
          ]
        }

        # Role assignment for the database service's managed identity
        resource "azurerm_role_assignment" "DB_SERVICE_IDENTITY_ROLE" {
          scope                = "/subscriptions/${var.SUBSCRIPTION_ID}/resourceGroups/${var.DB_RESOURCE_GROUP_NAME}"
          role_definition_id   = azurerm_role_definition.DB_SERVICE_MINIMAL_ROLE.role_definition_resource_id
          principal_id         = azurerm_mssql_server.DB_SERVER.identity[0].principal_id

          # SUBSTITUTE:
          # - var.SUBSCRIPTION_ID with your subscription ID
          # - var.DB_RESOURCE_GROUP_NAME with the resource group that hosts the DB
          # - azurerm_mssql_server.DB_SERVER with your actual database resource that exposes the managed identity
        }

        # Example managed identity on a database server (for context only)
        resource "azurerm_mssql_server" "DB_SERVER" {
          name                         = "DB_SERVER_NAME"          # substitute
          resource_group_name          = "DB_RESOURCE_GROUP_NAME"  # substitute or use variable
          location                     = "DB_REGION"               # substitute
          version                      = "12.0"
          administrator_login          = "DB_ADMIN_LOGIN"          # substitute
          administrator_login_password = "DB_ADMIN_PASSWORD"       # substitute with a sensitive variable

          identity {
            type = "SystemAssigned"
          }
        }
        ```

        Changing the `role_definition_id` or `scope` on `azurerm_role_assignment.DB_SERVICE_IDENTITY_ROLE` will replace the role assignment (revoke the old permissions and grant the new, narrower ones), but it will not recreate the database resource itself.

        Verification: `terraform plan` should show the existing `azurerm_role_assignment` being updated (often as `-/+` destroy/create) to use the new minimal custom role and/or reduced scope, with no other resources changing.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
