> ## 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 Event Rule For NSG Changes

### More Info:

Ensure Event Rules track Network Security Group edits. Immediate event triggers on NSGs prevent attackers from silently opening SSH or RDP ports to compute instances.

### 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 step‑by‑step instructions to configure an **OCI Event Rule for NSG changes** and integrate it with **OCI Alerting (Notifications) using the OCI Console**.

        ***

        ## 1. Prerequisites

        1. You must have permissions (policies) to:
           * Use `events-rules` in the compartment
           * Use `notifications-topics` and `subscriptions`
        2. Identify the **compartment** where your Network Security Groups (NSGs) reside.

        ***

        ## 2. Create (or Reuse) a Notifications Topic

        1. In the OCI Console, open the navigation menu and go to\
           **Developer Services → Notifications**.
        2. Make sure the correct **Compartment** is selected.
        3. Click **Create Topic**.
        4. Enter:
           * **Name**: e.g. `nsg-change-alerts`
           * **Description**: e.g. `Alerts for NSG configuration changes`
        5. Click **Create**.

        ### Add a Subscription (Email / Pager / etc.)

        1. Open the topic you just created (e.g. `nsg-change-alerts`).
        2. Under **Subscriptions**, click **Create Subscription**.
        3. Choose **Protocol**: e.g. `Email`.
        4. Enter your **Email** address.
        5. Click **Create**.
        6. Confirm the subscription from your email (click the confirmation link).

        (Use HTTPS/Slack/PagerDuty/etc. instead if desired.)

        ***

        ## 3. Create the Event Rule for NSG Changes

        1. Open the navigation menu and go to\
           **Observability & Management → Events Service → Rules**.
        2. Make sure the **Compartment** is set to where you want the rule stored (often same as NSGs, or a central logging/ops compartment).
        3. Click **Create Rule**.

        ### 3.1. Basic Rule Details

        1. **Name**: e.g. `Detect-NSG-Changes`
        2. **Description**: e.g. `Triggers when NSG configuration is modified or deleted`
        3. **Rule State**: ensure it is **Enabled**.

        ### 3.2. Define the Event Pattern

        1. In **Rule Conditions**, choose:
           * **Rule Type**: `Event Type`
        2. Configure:
           * **Service**: `Virtual Cloud Network (VCN)` or `Networking` (name may vary slightly).
           * **Resource Type**: `NetworkSecurityGroup`.
        3. For **Event Type**, select the operations you care about (at minimum):
           * `Update Network Security Group`
           * `Change Security Rules` (if separately available)
           * `Delete Network Security Group`
           * Optionally also:
             * `Create Network Security Group` (to track creation)

        If the console uses a JSON pattern editor, the filter will conceptually look like:

        ```json theme={null}
        {
          "eventType": [
            "com.oraclecloud.nsg.updatenetworksecuritygroup",
            "com.oraclecloud.nsg.deletenetworksecuritygroup",
            "com.oraclecloud.nsg.changesecurityrules"
          ]
        }
        ```

        (Use the UI dropdowns rather than typing JSON if available.)

        4. If needed, restrict by **Compartment** of the NSGs (often you choose the same application compartment).

        ***

        ## 4. Attach an Action to Send Alerts

        1. In the **Actions** section of the rule, click **+ Add Action**.
        2. Choose **Action Type**: `Notifications`.
        3. Select the **Notifications Topic** you created earlier\
           (e.g. `nsg-change-alerts`).
        4. Optionally, add a **Message Format** or specify custom payload if offered; otherwise, leave defaults.
        5. Click **Create** (or **Create Rule**) to save the rule.

        ***

        ## 5. (Optional) Centralize or Enhance Monitoring

        If you want more advanced workflows (e.g. send events to Logging or custom processors):

        * Use **Service Connector Hub**:
          * Source: **Events Service**
          * Target: **Logging** or **Function** for richer analysis.

        OCI Monitoring Alarms are metric‑based, so NSG changes are generally alerted via **Events + Notifications** as configured above.

        ***

        ## 6. Test the Configuration

        1. Go to **Networking → Virtual Cloud Networks → Network Security Groups**.
        2. Pick an NSG in the monitored compartment.
        3. Perform one of the actions you configured:
           * Modify a security rule (e.g., change port or CIDR).
           * Add or remove a rule.
        4. Within a short time, verify you receive an email (or other protocol) from the **Notifications** topic indicating an NSG change event.

        Once this works, you have successfully remediated the misconfiguration: OCI now generates and sends alerts for NSG changes using OCI’s Event Rules and Notifications.
      </Accordion>

      <Accordion title="Using CLI">
        Below is a simple, CLI‑only way to get alerts when any Network Security Group (NSG) is changed, using OCI Events + Notifications (which is what OCI “alerting/monitoring” for config changes is built on).

        Replace all `<PLACEHOLDER>` values with your own OCIDs / data.

        ***

        ### 1. Prereqs

        * OCI CLI installed and configured (`oci setup config`)
        * You know:
          * Tenancy OCID: `<TENANCY_OCID>`
          * Target compartment OCID where NSGs live: `<COMPARTMENT_OCID>`
          * Region is set in your CLI config

        ***

        ### 2. Create a Notifications topic

        ```bash theme={null}
        oci ons topic create \
          --compartment-id <COMPARTMENT_OCID> \
          --name "nsg-change-topic" \
          --description "Topic for NSG change alerts"
        ```

        Capture the `id` from the output as `<TOPIC_OCID>`.

        ***

        ### 3. Create a subscription on the topic (e.g., email)

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

        Confirm the email subscription when you receive the confirmation email.

        ***

        ### 4. Create the Events rule for NSG changes

        Event types for NSGs include:

        * `com.oraclecloud.virtualnetwork.createnetworksecuritygroup`
        * `com.oraclecloud.virtualnetwork.updatenetworksecuritygroup`
        * `com.oraclecloud.virtualnetwork.deletenetworksecuritygroup`

        Create the rule:

        ```bash theme={null}
        oci events rule create \
          --compartment-id <TENANCY_OCID> \
          --display-name "NSG-Changes-Rule" \
          --is-enabled true \
          --condition '{
            "eventType": [
              "com.oraclecloud.virtualnetwork.createnetworksecuritygroup",
              "com.oraclecloud.virtualnetwork.updatenetworksecuritygroup",
              "com.oraclecloud.virtualnetwork.deletenetworksecuritygroup"
            ],
            "data": {
              "compartmentId": "<COMPARTMENT_OCID>"
            }
          }' \
          --actions '{
            "actions": [
              {
                "actionType": "ONS",
                "isEnabled": true,
                "topicId": "<TOPIC_OCID>"
              }
            ]
          }'
        ```

        Notes:

        * Use `<TENANCY_OCID>` for the rule compartment (best practice), and filter to `<COMPARTMENT_OCID>` in the `condition`.
        * If you want this to fire for all compartments, drop the `data.compartmentId` filter.

        ***

        ### 5. Test

        * Modify an NSG (e.g., add a rule) in `<COMPARTMENT_OCID>`.
        * Verify that you receive an email from the Notifications topic.

        This satisfies the requirement “OCI Monitoring Should Have Event Rule For NSG Changes” using OCI CLI.
      </Accordion>

      <Accordion title="Using Python">
        Below is a practical way to enforce **“OCI Monitoring Should Have Event Rule For NSG Changes”** and wire it into **alerting** using **OCI Events + Notifications** in Python.

        ***

        ## 1. What you will create

        In one Python run you will:

        1. Create an **ONS Topic** (Notifications).
        2. Create an **Email Subscription** to that topic.
        3. Create an **Events Rule** that listens for **NSG create / update / delete** events.
        4. Route matching events to the ONS topic (so you get alerts).

        ***

        ## 2. Prerequisites

        * OCI Python SDK installed:
          ```bash theme={null}
          pip install oci
          ```
        * OCI config file (`~/.oci/config`) with a profile, e.g. `DEFAULT`.
        * Your:
          * `compartment_ocid`
          * `region`
          * An email address for alerts.

        ***

        ## 3. Event Types for NSG Changes

        Use these event types for Network Security Groups (NSGs):

        ```json theme={null}
        "com.oraclecloud.virtualnetwork.create.networksecuritygroup"
        "com.oraclecloud.virtualnetwork.update.networksecuritygroup"
        "com.oraclecloud.virtualnetwork.delete.networksecuritygroup"
        ```

        Condition (rule) expression:

        ```json theme={null}
        {
          "eventType": [
            "com.oraclecloud.virtualnetwork.create.networksecuritygroup",
            "com.oraclecloud.virtualnetwork.update.networksecuritygroup",
            "com.oraclecloud.virtualnetwork.delete.networksecuritygroup"
          ]
        }
        ```

        ***

        ## 4. Full Python Example

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

        # ---------- CONFIG ----------
        PROFILE = "DEFAULT"  # OCI CLI profile
        COMPARTMENT_OCID = "<your_compartment_ocid>"
        ALERT_EMAIL = "<your_email@example.com>"
        TOPIC_NAME = "nsg-change-alerts-topic"
        TOPIC_DESC = "Alerts when NSGs are created, updated, or deleted"
        RULE_DISPLAY_NAME = "NSG Change Events Rule"
        RULE_DESCRIPTION = "Triggers on NSG create/update/delete and sends notification"
        REGION = "<your_region>"  # e.g. "us-ashburn-1"
        # ----------------------------

        config = oci.config.from_file("~/.oci/config", PROFILE)
        config["region"] = REGION

        ons_client = oci.ons.NotificationControlPlaneClient(config)
        events_client = oci.events.EventsClient(config)


        def create_topic_if_not_exists():
            topics = oci.pagination.list_call_get_all_results(
                ons_client.list_topics,
                compartment_id=COMPARTMENT_OCID
            ).data

            for t in topics:
                if t.name == TOPIC_NAME:
                    print(f"Topic already exists: {t.topic_id}")
                    return t

            create_details = oci.ons.models.CreateTopicDetails(
                compartment_id=COMPARTMENT_OCID,
                name=TOPIC_NAME,
                description=TOPIC_DESC
            )
            topic = ons_client.create_topic(create_details).data
            print(f"Created topic: {topic.topic_id}")
            return topic


        def create_email_subscription_if_not_exists(topic_ocid):
            subs = oci.pagination.list_call_get_all_results(
                ons_client.list_subscriptions,
                compartment_id=COMPARTMENT_OCID
            ).data

            for s in subs:
                if s.topic_id == topic_ocid and s.endpoint == ALERT_EMAIL and s.protocol == "EMAIL":
                    print(f"Subscription already exists: {s.id}")
                    return s

            create_sub_details = oci.ons.models.CreateSubscriptionDetails(
                topic_id=topic_ocid,
                protocol="EMAIL",
                endpoint=ALERT_EMAIL
            )
            sub = ons_client.create_subscription(create_sub_details).data
            print(f"Created subscription: {sub.id}")
            print("Check your email and CONFIRM the subscription link from OCI.")
            return sub


        def create_nsg_events_rule_if_not_exists(topic_ocid):
            rules = oci.pagination.list_call_get_all_results(
                events_client.list_rules,
                compartment_id=COMPARTMENT_OCID
            ).data

            for r in rules:
                if r.display_name == RULE_DISPLAY_NAME:
                    print(f"Events rule already exists: {r.id}")
                    return r

            condition = {
                "eventType": [
                    "com.oraclecloud.virtualnetwork.create.networksecuritygroup",
                    "com.oraclecloud.virtualnetwork.update.networksecuritygroup",
                    "com.oraclecloud.virtualnetwork.delete.networksecuritygroup"
                ]
            }

            # Define the action to send events to the topic
            ons_target = oci.events.models.CreateStreamingServiceActionDetails(
                # NOTE: For Notifications, use CreateNotificationServiceActionDetails in newer SDKs.
                # Some older SDKs may require a different class; adjust as per your oci version.
            )

            # Correct action for Notifications:
            ons_action = oci.events.models.CreateNotificationServiceActionDetails(
                action_type="ONS",
                is_enabled=True,
                topic_id=topic_ocid
            )

            create_rule_details = oci.events.models.CreateRuleDetails(
                display_name=RULE_DISPLAY_NAME,
                description=RULE_DESCRIPTION,
                is_enabled=True,
                compartment_id=COMPARTMENT_OCID,
                condition=condition,
                actions=oci.events.models.ActionDetailsList(
                    actions=[ons_action]
                )
            )

            rule = events_client.create_rule(create_rule_details).data
            print(f"Created NSG events rule: {rule.id}")
            return rule


        def main():
            topic = create_topic_if_not_exists()
            create_email_subscription_if_not_exists(topic.topic_id)
            # Wait a bit to avoid race conditions in very fresh tenancy setups
            time.sleep(5)
            create_nsg_events_rule_if_not_exists(topic.topic_id)


        if __name__ == "__main__":
            main()
        ```

        Notes:

        * Ensure your SDK version supports `CreateNotificationServiceActionDetails`. If not, update:
          ```bash theme={null}
          pip install --upgrade oci
          ```
        * After running the script, **confirm the email subscription** from your inbox.
        * From then on, any **NSG create/update/delete** in the compartment will trigger an email alert.

        ***

        If you want, I can adapt this to:

        * Use a specific dynamic group/policy setup,
        * Target a different protocol (Slack via HTTPS, PagerDuty, etc.),
        * Or wire an OCI Function instead of direct email.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        resource "oci_events_rule" "nsg_change_events" {
          # Substitute with your compartment OCID
          compartment_id = "OCID_OF_TARGET_COMPARTMENT"

          display_name = "nsg-change-events"
          description  = "Trigger notifications when Network Security Groups are created, updated, deleted, or moved."

          is_enabled = true

          # Event rule condition to match NSG changes
          # Adjust 'id' if you want to scope only to specific NSGs.
          condition = <<EOF
        {
          "eventType": [
            "com.oraclecloud.virtualnetwork.createnetworksecuritygroup",
            "com.oraclecloud.virtualnetwork.updatenetworksecuritygroup",
            "com.oraclecloud.virtualnetwork.deletenetworksecuritygroup",
            "com.oraclecloud.virtualnetwork.changenetworksecuritygroupcompartment"
          ],
          "data": {
            "resourceName": [
              "networksecuritygroups"
            ]
          }
        }
        EOF

          actions {
            actions {
              # Send an alert via OCI Notifications
              action_type = "ONS"
              is_enabled  = true

              # Substitute with your Notifications topic OCID
              topic_id = "OCID_OF_OCI_NOTIFICATIONS_TOPIC"

              description = "Notify on Network Security Group configuration changes"
            }
          }

          freeform_tags = {
            "OWNER" = "TEAM_NAME_OR_OWNER"
          }
        }
        ```

        This change is in-place for an existing `oci_events_rule` (no forced replacement unless you change `compartment_id` to a different compartment or switch to a new rule resource entirely).

        Verification: `terraform plan` should show either a new `oci_events_rule.nsg_change_events` being created or the existing rule updated so that:

        * `is_enabled` is `true`
        * `condition` matches the NSG event types
        * `actions[0].action_type` is `ONS` with the desired `topic_id`.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
