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

# OCI Monitoring Should Have NSG Change Alarm Configured

### More Info:

NetworkSecurityGroupChange events should be monitored. NSGs govern granular instance-level access, and unapproved modifications can compromise micro-segmentation boundaries.

### Risk Level

Medium

### Address

Compliance, Security

### Compliance Standards

* APRA CPS 234 (Australia)
* AWS Well Architected Framework
* BSI C5 (Germany)
* Brazil LGPD
* CCPA / CPRA (California)
* CIS AWS
* CIS Critical Security Controls v8
* CMMC 2.0
* CSA Cloud Controls Matrix v4
* Cloudanix Best Practice
* DPDPA
* Digital Operational Resilience Act (EU)
* HIPAA
* HITRUST CSF
* ISO 27001
* ISO/IEC 27017
* ISO/IEC 27018
* ISO/IEC 27701
* KSA PDPL
* MAS Technology Risk Management (Singapore)
* MITRE ATT\&CK (Cloud)
* NIS2 Directive
* NIST
* NIST CSF
* NIST SP 800-171
* NYDFS 23 NYCRR 500
* SOC2
* 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">
        Below are concise, step‑by‑step instructions to configure an alarm/alert for NSG (Network Security Group) changes in OCI using the console. In OCI, this is done with **Events + Notifications** (which is still “alerting/monitoring,” but event‑driven rather than metric‑driven).

        ***

        ## 1. Create a Notifications Topic

        1. In the OCI Console, open the **Navigation menu** (☰).
        2. Go to **Developer Services** → **Application Integration** → **Notifications**.
        3. Make sure you’re in the correct **compartment**.
        4. Click **Create Topic**.
        5. Enter:
           * **Name**: e.g. `nsg-change-alerts-topic`
           * **Description**: e.g. `Alerts for OCI NSG configuration changes`
        6. Click **Create**.

        ***

        ## 2. Add a Subscription (Email or Other)

        1. After the topic is created, click the topic name (`nsg-change-alerts-topic`).
        2. Under **Subscriptions**, click **Create Subscription**.
        3. Choose **Protocol** (e.g. `Email`).
        4. Enter **Endpoint** (e.g. your email address).
        5. Click **Create**.
        6. Check your email and **confirm** the subscription via the confirmation link.

        ***

        ## 3. Create an Event Rule for NSG Changes

        You want to fire an alert whenever a Network Security Group is created, updated, or deleted.

        1. In the console, go to **Observability & Management** → **Events Service** → **Rules**.
        2. Ensure you are in the **compartment** where NSGs exist (or a higher-level compartment if you want broader scope).
        3. Click **Create Rule**.
        4. Fill in:
           * **Name**: `nsg-change-event-rule`
           * **Description**: `Trigger notification on NSG create, update, or delete`
           * **Status**: leave as **Enabled**.
        5. Under **Rule Conditions**:
           * Choose **Event Type:**
             * Click **Edit** or **+ Another Condition** as needed.
             * In **Service Name**, select **Virtual Cloud Network (VCN)** (sometimes labeled just Virtual Networking).
             * In **Event Type**, select events related to NSG:
               * `CreateNetworkSecurityGroup`
               * `UpdateNetworkSecurityGroup`
               * `DeleteNetworkSecurityGroup`
               * `UpdateNetworkSecurityGroupSecurityRules` (very important for rule changes)
             * If you cannot choose multiple explicitly, create multiple event type conditions combined with “Any” (OR) or create multiple rules (one per event type).
        6. Under **Actions**, choose:
           * **Action Type**: **Notifications**
           * **Topic**: select `nsg-change-alerts-topic`.
        7. Click **Create Rule**.

        ***

        ## 4. (Optional) Narrow Down with Additional Filters

        If you only want events for certain compartments or tags:

        1. Edit the rule you just created.
        2. Under **Condition**, add a **Custom Event Filter** using Event JSON (Advanced) or UI filters such as:
           * Compartment OCID
           * Defined tags / freeform tags
        3. Save the rule.

        ***

        ## 5. Test the Configuration

        1. Go to **Networking** → **Virtual Cloud Networks** → **Network Security Groups**.
        2. In the target compartment, pick an NSG.
        3. Perform a change, for example:
           * Add or remove an NSG security rule, or
           * Create a new NSG.
        4. Within a few minutes, you should receive an email (or selected protocol) indicating an NSG change event.

        ***

        This setup ensures OCI monitoring/alerting is in place for **any NSG configuration changes** via the Events service integrated with Notifications.
      </Accordion>

      <Accordion title="Using CLI">
        In OCI, configuration-change “alarms” for NSGs are implemented with **Events + Notifications**, not Monitoring metrics. Below are the exact steps using the OCI CLI.

        ***

        ### 1. Prerequisites

        Make sure your CLI is configured and you have:

        ```bash theme={null}
        export COMPARTMENT_OCID="<your_compartment_ocid>"
        export EMAIL_ADDRESS="<your_email_for_alerts>"
        ```

        ***

        ### 2. Create a Notifications Topic

        ```bash theme={null}
        oci ons topic create \
          --name "nsg-change-topic" \
          --compartment-id "$COMPARTMENT_OCID" \
          --description "Alerts when NSG configuration changes"

        # Capture the topic OCID
        export TOPIC_OCID=$(oci ons topic list \
          --compartment-id "$COMPARTMENT_OCID" \
          --name "nsg-change-topic" \
          --all \
          --query "data[0].\"id\"" \
          --raw-output)
        ```

        ***

        ### 3. Create a Subscription (e.g., Email)

        ```bash theme={null}
        oci ons subscription create \
          --topic-id "$TOPIC_OCID" \
          --protocol "EMAIL" \
          --endpoint "$EMAIL_ADDRESS"
        ```

        Then **confirm the subscription** from the email you receive.

        ***

        ### 4. Create an Events Rule for NSG Changes

        This rule triggers when NSGs are created/updated/deleted or when rules change.

        Prepare the condition JSON (you can inline it or put it in a file `nsg-change-condition.json`):

        ```json theme={null}
        {
          "eventType": [
            "com.oraclecloud.virtualnetwork.createNetworkSecurityGroup",
            "com.oraclecloud.virtualnetwork.updateNetworkSecurityGroup",
            "com.oraclecloud.virtualnetwork.deleteNetworkSecurityGroup",
            "com.oraclecloud.virtualnetwork.addNetworkSecurityGroupSecurityRules",
            "com.oraclecloud.virtualnetwork.removeNetworkSecurityGroupSecurityRules"
          ],
          "data": {
            "response": {
              "headers": {
              }
            },
            "additionalDetails": {
              "compartmentId": [
                "$COMPARTMENT_OCID"
              ]
            }
          }
        }
        ```

        If in a file, create the rule:

        ```bash theme={null}
        oci events rule create \
          --display-name "NSG-Change-Alert-Rule" \
          --description "Send notification when NSG configuration changes" \
          --compartment-id "$COMPARTMENT_OCID" \
          --is-enabled true \
          --condition file://nsg-change-condition.json \
          --actions '{
            "actions": [
              {
                "actionType": "ONS",
                "isEnabled": true,
                "description": "Send NSG change alert to Notifications topic",
                "topicId": "'"$TOPIC_OCID"'"
              }
            ]
          }'
        ```

        (If you want a global rule, you can omit the `compartmentId` filter from `additionalDetails`.)

        ***

        ### 5. Test the Alert

        Perform any NSG change in the compartment (e.g., add a security rule) and verify that you receive an email notification.

        If you specifically need this expressed as a “Monitoring alarm,” you would still rely on this Events + Notifications pattern, since NSG configuration changes are not exposed as a standard Monitoring metric.
      </Accordion>

      <Accordion title="Using Python">
        In OCI, configuration changes (including NSG changes) are exposed via **Events**, not Monitoring metrics.\
        To “alarm” on NSG changes you create:

        1. A **Notifications topic**
        2. An **Events rule** that matches Network Security Group change events and sends them to the topic
        3. (Optionally) subscribe email/Slack/etc. to the topic

        Below are step‑by‑step instructions and a Python example using the OCI SDK.

        ***

        ## 1. Prerequisites

        1. **Install OCI Python SDK**

        ```bash theme={null}
        pip install oci
        ```

        2. **Configure OCI CLI profile (used by SDK)**

        `~/.oci/config`:

        ```ini theme={null}
        [DEFAULT]
        user=ocid1.user.oc1..aaaaaaaa...
        fingerprint=...
        key_file=/path/to/oci_api_key.pem
        tenancy=ocid1.tenancy.oc1..aaaaaaaa...
        region=us-ashburn-1
        ```

        3. **IAM Policies**

        In the compartment (or tenancy) where you’ll create the rule and topic, add policies like:

        ```text theme={null}
        Allow group <your-admin-group> to manage ons-topic in compartment <compartment-name>
        Allow group <your-admin-group> to manage ons-subscription in compartment <compartment-name>
        Allow group <your-admin-group> to manage events-rule in compartment <compartment-name>

        Allow service events to use ons-topic in compartment <compartment-name>
        ```

        ***

        ## 2. Create Notifications Topic and Subscription (Python)

        ```python theme={null}
        import oci

        config = oci.config.from_file()  # uses DEFAULT profile
        compartment_id = "<COMPARTMENT_OCID>"
        notification_endpoint_email = "you@example.com"

        ons_client = oci.ons.NotificationControlPlaneClient(config)

        # 1) Create topic
        create_topic_details = oci.ons.models.CreateTopicDetails(
            name="nsg-change-alerts-topic",
            compartment_id=compartment_id,
            description="Alerts when NSGs are created/updated/deleted",
        )
        topic = ons_client.create_topic(create_topic_details).data
        print("Created topic:", topic.topic_id)

        # 2) Create email subscription
        create_sub_details = oci.ons.models.CreateSubscriptionDetails(
            topic_id=topic.topic_id,
            protocol="EMAIL",  # or HTTPS, ORACLE_FUNCTIONS, etc.
            endpoint=notification_endpoint_email,
        )
        subscription = ons_client.create_subscription(create_sub_details).data
        print("Created subscription:", subscription.id)
        ```

        You must confirm the subscription from the email that OCI sends.

        ***

        ## 3. Create Events Rule for NSG Changes (Python)

        NSG (Network Security Group) change events come from the **Virtual Network** service.\
        We match event types like:

        * `com.oraclecloud.virtualnetwork.createNetworkSecurityGroup`
        * `com.oraclecloud.virtualnetwork.updateNetworkSecurityGroup`
        * `com.oraclecloud.virtualnetwork.deleteNetworkSecurityGroup`

        You can use a condition that matches all three:

        ```python theme={null}
        import oci
        import json

        config = oci.config.from_file()
        compartment_id = "<COMPARTMENT_OCID>"
        topic_ocid = "<TOPIC_OCID_FROM_PREVIOUS_STEP>"

        events_client = oci.events.EventsClient(config)

        # Condition to match NSG create/update/delete in this compartment (or tenant-wide if you omit compartment condition)
        condition = {
            "eventType": [
                "com.oraclecloud.virtualnetwork.createNetworkSecurityGroup",
                "com.oraclecloud.virtualnetwork.updateNetworkSecurityGroup",
                "com.oraclecloud.virtualnetwork.deleteNetworkSecurityGroup"
            ],
            # Optional: restrict to this compartment where NSGs live
            "data": {
                "compartmentId": [compartment_id]
            }
        }

        create_rule_details = oci.events.models.CreateRuleDetails(
            display_name="NSG Change Alarm Rule",
            description="Triggers when Network Security Groups are created, updated, or deleted",
            compartment_id=compartment_id,
            is_enabled=True,
            condition=json.dumps(condition),
            actions=oci.events.models.ActionList(
                actions=[
                    oci.events.models.ONSAction(
                        action_type="ONS",
                        is_enabled=True,
                        topic_id=topic_ocid,
                        description="Send NSG change alerts"
                    )
                ]
            )
        )

        rule = events_client.create_rule(create_rule_details).data
        print("Created Events rule:", rule.id)
        ```

        ***

        ## 4. Validate

        1. Create or modify an NSG in the same compartment:
           * e.g., add/remove a security rule.
        2. Wait a few minutes.
        3. You should receive an email notification from the topic you created.

        ***

        ## 5. Key Points

        * NSG change “alarms” are implemented via **Events + Notifications**, not standard Monitoring metrics.
        * The Python SDK uses:
          * `oci.ons.NotificationControlPlaneClient` for topics/subscriptions.
          * `oci.events.EventsClient` for rules.
        * Make sure the **service events** is allowed to use the **ONS topic** via IAM policy.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        resource "oci_monitoring_alarm" "nsg_change_alarm" {
          # Compartment where the alarm itself lives
          compartment_id = "COMPARTMENT_OCID"

          # Compartment where NSG change events/metrics are emitted
          metric_compartment_id = "NETWORK_SECURITY_GROUP_COMPARTMENT_OCID"

          display_name = "NSG Change Alarm"
          is_enabled   = true
          severity     = "CRITICAL"

          # Namespace and query define “NetworkSecurityGroupChange” monitoring.
          # Replace NAMESPACE and QUERY_EXPRESSION with the correct Monitoring namespace
          # for Events in your tenancy and a query that:
          #  - filters for NSG change events
          #  - applies your desired threshold (for example: > 0 over 1 minute)
          namespace = "EVENTS_METRIC_NAMESPACE" # e.g. "oci_events" (confirm in Console → Monitoring → Metrics)

          # Example (replace with your exact eventType and threshold):
          # query = "Events[1m]{eventType = \"NETWORK_SECURITY_GROUP_CHANGE_EVENTTYPE\"}.count() > 0"
          query = "NSG_CHANGE_QUERY_EXPRESSION"

          # Where to send the alarm (Notification Service topic OCIDs)
          destinations = [
            "ONS_TOPIC_OCID_1",
            # "ONS_TOPIC_OCID_2",
          ]

          # Optional: free-form description / tags
          body = "Alert when any Network Security Group configuration change is detected."

          message_format = "PRETTY_JSON"
        }
        ```

        This change does not force replacement of any existing Network Security Groups; it only creates or updates an alarm resource.

        To verify, `terraform plan` should show either:

        * `+ oci_monitoring_alarm.nsg_change_alarm` (if new), or
        * `~ oci_monitoring_alarm.nsg_change_alarm` with updates only to fields like `namespace`, `query`, `destinations`, `is_enabled`, or `severity`.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
