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

# Ensure Activity Log Alert exists for Create or Update Network Security Group

### More Info:

Monitoring for Create or Update Network Security Group events gives insight into network access changes and may reduce the time it takes to detect suspicious activity.

### Risk Level

Low

### Address

Operational Maturity, Security

### Compliance Standards

* CIS AZURE
* Cloudanix Best Practice
* HIPAA
* HITRUST CSF
* ISO 27001
* NIST CSF
* SOC2

### Triage and Remediation

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To remediate the misconfiguration "Ensure Activity Log Alert exists for Create or Update Network Security Group" for AZURE using AZURE console, please follow the below steps:

        1. Log in to the Azure portal ([https://portal.azure.com/](https://portal.azure.com/)).
        2. Click on the "Activity log" option in the left-hand side menu.
        3. Click on the "Alerts" option in the left-hand side menu.
        4. Click on the "New alert rule" button.
        5. In the "Create alert rule" page, under the "Scope" section, select the subscription, resource group, or resource for which you want to create an alert.
        6. Under the "Condition" section, click on the "Add condition" button.
        7. In the "Add condition" page, select "Activity log" as the signal type.
        8. Under the "Filter" section, select "Resource provider" as the field and "Microsoft.Network" as the value.
        9. Under the "Operation" section, select "Create or Update Network Security Group" as the value.
        10. Under the "Threshold" section, set the frequency and threshold values according to your requirements.
        11. Under the "Actions" section, select the action you want to perform when the alert is triggered. You can send an email, a text message, or a webhook notification.
        12. Click on the "Create alert rule" button to create the alert.

        Once the alert is created, you will receive a notification whenever a network security group is created or updated in the selected scope.

        #
      </Accordion>

      <Accordion title="Using CLI">
        To remediate the misconfiguration "Ensure Activity Log Alert exists for Create or Update Network Security Group" in Azure using Azure CLI, you can follow these step-by-step instructions:

        1. Open the Azure CLI on your local machine or in the Azure portal.

        2. Run the following command to create an activity log alert for network security group creation or update:

           ```
           az monitor activity-log alert create --name <alert_name> --description <alert_description> --condition category=Administrative and resourceType=Microsoft.Network/networkSecurityGroups write --action-group <action_group_name> --enabled true
           ```

           Replace `<alert_name>` with a name for your alert and `<alert_description>` with a description of the alert. Replace `<action_group_name>` with the name of an existing action group that will receive notifications when the alert is triggered.

        3. Verify that the alert was created successfully by running the following command:

           ```
           az monitor activity-log alert show --name <alert_name>
           ```

           This command should display the details of the alert you just created.

        4. Repeat these steps for each network security group in your Azure environment to ensure that an activity log alert exists for all network security group creation or updates.

        By following these steps, you can remediate the misconfiguration "Ensure Activity Log Alert exists for Create or Update Network Security Group" in Azure using Azure CLI.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the misconfiguration "Ensure Activity Log Alert exists for Create or Update Network Security Group" in Azure using Python, you can use the Azure SDK for Python. Here are the steps to remediate the misconfiguration:

        Step 1: Install the Azure SDK for Python by running the following command in your terminal:

        ```
        pip install azure-mgmt-monitor
        ```

        Step 2: Authenticate to Azure by creating a Service Principal and obtaining the credentials. You can follow the steps mentioned in the Azure documentation to create a Service Principal.

        Step 3: Use the following Python code to create an Activity Log Alert for Create or Update Network Security Group:

        ```python theme={null}
        from azure.common.credentials import ServicePrincipalCredentials
        from azure.mgmt.monitor import MonitorManagementClient
        from azure.mgmt.monitor.models import AlertRuleResource, \
            AlertRuleAllOfCondition, AlertRuleLeafCondition, \
            AlertRuleActionGroup, AlertRuleActionList, \
            AlertRuleEmailAction, AlertRuleWebhookAction

        # Replace the values with your own
        subscription_id = '<your-subscription-id>'
        resource_group_name = '<your-resource-group-name>'
        network_security_group_name = '<your-network-security-group-name>'
        alert_rule_name = '<your-alert-rule-name>'
        action_group_name = '<your-action-group-name>'
        webhook_receiver_url = '<your-webhook-receiver-url>'
        email_receiver_address = '<your-email-receiver-address>'

        # Authenticate to Azure
        credentials = ServicePrincipalCredentials(
            client_id='<your-client-id>',
            secret='<your-client-secret>',
            tenant='<your-tenant-id>'
        )

        # Create the Monitor Management Client
        monitor_client = MonitorManagementClient(
            credentials=credentials,
            subscription_id=subscription_id
        )

        # Create the Alert Rule
        alert_rule = AlertRuleResource(
            location='global',
            tags={},
            name=alert_rule_name,
            description='Alert for Create or Update Network Security Group',
            is_enabled=True,
            condition=AlertRuleAllOfCondition(
                all_of=[
                    AlertRuleLeafCondition(
                        field='category',
                        equals='Administrative'
                    ),
                    AlertRuleLeafCondition(
                        field='resourceId',
                        contains=network_security_group_name
                    ),
                    AlertRuleLeafCondition(
                        field='operationName',
                        equals='Microsoft.Network/networkSecurityGroups/write'
                    ),
                    AlertRuleLeafCondition(
                        field='status',
                        equals='Succeeded'
                    )
                ]
            ),
            actions=AlertRuleActionList(
                action_groups=[
                    AlertRuleActionGroup(
                        action_group_id=action_group_name
                    )
                ],
                emails=[
                    AlertRuleEmailAction(
                        send_to_service_owners=False,
                        custom_emails=[email_receiver_address]
                    )
                ],
                webhooks=[
                    AlertRuleWebhookAction(
                        service_uri=webhook_receiver_url
                    )
                ]
            )
        )

        # Create the Alert Rule
        monitor_client.alert_rules.create_or_update(
            resource_group_name=resource_group_name,
            rule_name=alert_rule_name,
            parameters=alert_rule
        )
        ```

        In the above code, replace the values for `subscription_id`, `resource_group_name`, `network_security_group_name`, `alert_rule_name`, `action_group_name`, `webhook_receiver_url`, and `email_receiver_address` with your own values.

        This code creates an Activity Log Alert for the Create or Update operation on the specified Network Security Group. The Alert Rule sends notifications to the specified email address and webhook receiver URL, and also adds the specified Action Group to the Alert Rule.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        resource "azurerm_monitor_action_group" "NSG_ACTIVITY_LOG_ALERT_ACTION_GROUP" {
          name                = "NSG-ActivityLog-Alert-ActionGroup"
          resource_group_name = "RESOURCE_GROUP_FOR_ACTION_GROUP" # replace with the resource group that should contain the action group
          short_name          = "nsglogag"

          email_receiver {
            name          = "SECOPS_EMAIL_RECEIVER"
            email_address = "SECOPS_EMAIL@example.com" # replace with security/ops email or remove/change to your desired receivers
          }
        }

        resource "azurerm_monitor_activity_log_alert" "NSG_CREATE_UPDATE_ACTIVITY_LOG_ALERT" {
          name                = "NSG-CreateOrUpdate-ActivityLog-Alert"
          resource_group_name = "RESOURCE_GROUP_FOR_ALERT" # replace with the resource group that should contain the alert
          scopes              = ["/subscriptions/SUBSCRIPTION_ID"] # replace with the subscription ID whose activity log you want to monitor

          description = "Alert on Create or Update of any Network Security Group"

          enabled = true

          criteria {
            category       = "Administrative"
            operation_name = "Microsoft.Network/networkSecurityGroups/write"
          }

          action {
            action_group_id = azurerm_monitor_action_group.NSG_ACTIVITY_LOG_ALERT_ACTION_GROUP.id
          }
        }
        ```

        This does not force replacement of any existing Network Security Group; it only adds a new Activity Log Alert and an Action Group.

        Verification: `terraform plan` should show `+ create` for `azurerm_monitor_activity_log_alert.NSG_CREATE_UPDATE_ACTIVITY_LOG_ALERT` (and `azurerm_monitor_action_group.NSG_ACTIVITY_LOG_ALERT_ACTION_GROUP` if it is new), with `criteria.category = "Administrative"` and `criteria.operation_name = "Microsoft.Network/networkSecurityGroups/write"`.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>

### Additional Reading:

* [https://docs.microsoft.com/en-in/azure/azure-monitor/platform/alerts-activity-log](https://docs.microsoft.com/en-in/azure/azure-monitor/platform/alerts-activity-log)
