> ## 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 Policy Change Alarm Configured

### More Info:

Monitor IamPolicyChange events. Unauthorized modifications to IAM policies can silently elevate privileges, allowing attackers to establish persistence or exfiltrate data.

### 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)
* Essential 8
* 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 CSF
* NIST SP 800-171
* NYDFS 23 NYCRR 500
* PCI
* 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 a **policy‑change alert** in OCI using the **Console**, leveraging **Events + Notifications (email/SNS)**, which is the standard way to get alerted on configuration changes like IAM policy updates.

        ***

        ## 1. Prerequisites

        1. You must have permissions to manage:
           * `events-rules` in the target compartment
           * `ons-topics` and `ons-subscriptions` (Notifications)
        2. Audit is on by default in OCI; no extra action needed for that.

        ***

        ## 2. Create a Notification Topic (for email/other alerts)

        1. In the OCI Console, open the **Navigation menu**.
        2. Go to **Developer Services → Notifications** (or **Application Integration → Notifications**, depending on UI version).
        3. Make sure you’re in the **correct compartment**.
        4. Click **Create Topic**.
           * Name: e.g. `policy-change-alerts-topic`
           * Description: `Alerts for IAM policy changes`
        5. Click **Create**.

        ### Add an Email Subscription

        1. In the same topic page, click on the topic you just created.
        2. Under **Subscriptions**, click **Create Subscription**.
        3. Choose **Protocol** = `Email`.
        4. Enter the **email address** to receive the alerts.
        5. Click **Create**.
        6. Go to your email inbox and **confirm** the subscription via the confirmation link.

        (Repeat with other protocols if needed: PagerDuty, Slack (via HTTPS), etc.)

        ***

        ## 3. Create an Event Rule for Policy Changes

        You’ll now create an **Events rule** that listens for IAM policy change events and forwards them to the Notifications topic.

        1. In the OCI Console, open **Navigation menu → Observability & Management → Events Service** (or **Events**).
        2. Ensure you’re in the **desired compartment**.
        3. Click **Create Rule**.

        Fill in the rule details:

        1. **Name**: `policy-change-events-rule`
        2. **Description**: `Trigger notifications when IAM policies are created, updated, or deleted`.
        3. **Rule Status**: Ensure it is **Enabled**.
        4. **Condition (Rule Type)**: Select **Event Type** or **Service Connector–style condition** depending on the UI; you want an **event pattern** that matches IAM policy changes.

        ### 3.1. Define the Event Pattern for Policy Changes

        Use the JSON editor (or the UI equivalent) to match IAM policy changes. Example event pattern:

        ```json theme={null}
        {
          "eventType": [
            "com.oraclecloud.identitycontrolplane.createpolicy",
            "com.oraclecloud.identitycontrolplane.updatepolicy",
            "com.oraclecloud.identitycontrolplane.deletepolicy"
          ]
        }
        ```

        If the console offers dropdowns instead of raw JSON:

        * **Service Name**: `Identity` (or “Identity and Access Management” / “iam”)
        * **Event Types**: select the ones matching:
          * `CreatePolicy`
          * `UpdatePolicy`
          * `DeletePolicy`

        (The exact wording can differ slightly by region/UI, but look for “policy” in the Identity event types.)

        ### 3.2. Set the Action to Your Notification Topic

        Still in the rule creation:

        1. Under **Actions**, choose **Notifications**.

        2. Select the **Topic** you created earlier: `policy-change-alerts-topic`.

        3. (Optional) Add multiple actions if you want messages to multiple topics or Functions.

        4. Click **Create Rule**.

        The rule should now be **Enabled** and pointing to your Notifications topic.

        ***

        ## 4. (Optional) Test the Policy Change Alert

        1. In the OCI Console, go to **Identity & Security → Policies**.
        2. In a test compartment or tenancy (be careful in production), do one of:
           * Create a temporary test policy.
           * Edit (update) an existing test policy.
           * Delete a test policy (if appropriate).
        3. Wait a few minutes.
        4. Check the email (or other channel) subscribed to the notification topic for an alert.

        You should receive a message containing the event details (who changed the policy, what was changed, timestamp, etc.).

        ***

        ## 5. (Optional) Refine or Scope the Rule

        To reduce noise, you can further refine the event pattern to specific compartments or policies by using conditions on attributes like:

        * `data.resourceName`
        * `data.compartmentId`
        * `data.additionalDetails.compartmentName`

        For example (conceptual):

        ```json theme={null}
        {
          "eventType": [
            "com.oraclecloud.identitycontrolplane.updatepolicy"
          ],
          "data": {
            "compartmentName": [
              "Prod-Compartment"
            ]
          }
        }
        ```

        Adjust depending on what the Events UI accepts.

        ***

        This configuration ensures that any **IAM policy creation, update, or deletion** in OCI will trigger a notification, satisfying the requirement that “Monitoring should have policy change alarm configured,” using **OCI’s native Events + Notifications** via the Console.
      </Accordion>

      <Accordion title="Using CLI">
        Below is a CLI-based way to configure an OCI Monitoring alarm that fires on IAM policy changes (create/update/delete) using the Audit metrics.

        Assumptions:

        * You already have `oci` CLI configured.
        * You know your `COMPARTMENT_OCID` (typically your root compartment for IAM policies).
        * You have permission to create Notifications resources and Alarms.

        ***

        ## 1. Create a Notifications Topic

        ```bash theme={null}
        oci ons topic create \
          --compartment-id "<COMPARTMENT_OCID>" \
          --name "policy-change-alerts" \
          --description "Alerts for IAM policy changes"
        ```

        Note the returned `"id"` as `TOPIC_OCID`.

        ***

        ## 2. (Optional) Add a Subscription to the Topic

        Example: email subscription.

        ```bash theme={null}
        oci ons subscription create \
          --topic-id "<TOPIC_OCID>" \
          --protocol "EMAIL" \
          --endpoint "security-team@example.com"
        ```

        Confirm the subscription from the email if required.

        ***

        ## 3. Build the Alarm Query for Policy Changes

        Audit metrics namespace is `oci_audit`.\
        We’ll alarm when any policy is created/updated/deleted.

        Example query:

        ```text theme={null}
        sum(AuditEventCount[1m]{resourceType = "policy" && (eventName = "CreatePolicy" || eventName = "UpdatePolicy" || eventName = "DeletePolicy")}) > 0
        ```

        You can also constrain by compartment if desired with `compartmentId`.

        ***

        ## 4. Create the Alarm via CLI

        ```bash theme={null}
        oci monitoring alarm create \
          --compartment-id "<COMPARTMENT_OCID>" \
          --display-name "OCI Policy Change Alarm" \
          --metric-compartment-id "<COMPARTMENT_OCID>" \
          --namespace "oci_audit" \
          --query 'sum(AuditEventCount[1m]{resourceType = "policy" && (eventName = "CreatePolicy" || eventName = "UpdatePolicy" || eventName = "DeletePolicy")}) > 0' \
          --severity "CRITICAL" \
          --destinations '["<TOPIC_OCID>"]' \
          --is-enabled true \
          --pending-duration "PT1M" \
          --resolution "1m" \
          --body "IAM policy change detected. Check Audit logs immediately." \
          --message-format "ONS_OPTIMIZED"
        ```

        Key options:

        * `--metric-compartment-id` is where the Audit metrics are emitted (often the same root compartment).
        * `--pending-duration` = how long the condition must be true before firing.
        * `--resolution` = evaluation interval.

        ***

        ## 5. Verify the Alarm

        List alarms:

        ```bash theme={null}
        oci monitoring alarm list \
          --compartment-id "<COMPARTMENT_OCID>"
        ```

        Get details:

        ```bash theme={null}
        oci monitoring alarm get \
          --alarm-id "<ALARM_OCID>"
        ```

        ***

        If you share your specific compartment layout (root vs subcompartments) I can refine the exact `query` and compartment filters.
      </Accordion>

      <Accordion title="Using Python">
        In OCI, “policy change alerts” are usually implemented with **Events + Notifications**, not with a classic Monitoring metric alarm, because IAM policy changes are emitted as **events**, not metrics. You can still treat this as “alerting/monitoring,” but you wire it through:

        1. **Events** – detect IAM policy changes
        2. **Notifications** – send email/Slack/HTTPS, etc.
        3. (Optional) **Monitoring Alarm** – only if you have a custom metric for policy changes

        Below is a minimal end‑to‑end Python approach using the OCI SDK.

        ***

        ## 1. Prerequisites

        * Python 3 + `oci` SDK installed:
          ```bash theme={null}
          pip install oci
          ```
        * A configured OCI CLI profile (e.g. `DEFAULT`) at `~/.oci/config` with:
          * tenancy OCID
          * user OCID
          * region
          * API key
        * The **compartment OCID** where you want to create the Events rule and topic.

        ***

        ## 2. Create a Notifications Topic + Subscription (email) via Python

        ```python theme={null}
        import oci

        config = oci.config.from_file("~/.oci/config", "DEFAULT")
        identity = oci.identity.IdentityClient(config)
        notification_client = oci.ons.NotificationControlPlaneClient(config)

        compartment_id = "<YOUR_COMPARTMENT_OCID>"
        email_address = "you@example.com"

        # 1) Create topic
        topic_details = oci.ons.models.CreateTopicDetails(
            name="policy-change-alerts-topic",
            compartment_id=compartment_id,
            description="Topic for OCI IAM policy change alerts"
        )

        topic = notification_client.create_topic(topic_details).data
        topic_id = topic.topic_id
        print("Created topic:", topic_id)

        # 2) Create email subscription
        subscription_details = oci.ons.models.CreateSubscriptionDetails(
            compartment_id=compartment_id,
            topic_id=topic_id,
            protocol="EMAIL",
            endpoint=email_address
        )

        subscription = notification_client.create_subscription(subscription_details).data
        print("Created subscription:", subscription.id)
        print("Check your email and confirm the subscription.")
        ```

        After running this:

        * Confirm the subscription from the confirmation email.

        ***

        ## 3. Create an Events Rule for IAM Policy Changes via Python

        OCI emits specific event types for IAM policy operations, e.g.:

        * `com.oraclecloud.identitycontrolplane.CreatePolicy`
        * `com.oraclecloud.identitycontrolplane.UpdatePolicy`
        * `com.oraclecloud.identitycontrolplane.DeletePolicy`

        The following creates a rule that triggers on those for your tenancy (or a compartment):

        ```python theme={null}
        events_client = oci.events.EventsClient(config)

        rule_compartment_id = compartment_id  # can be tenancy or specific compartment

        # Event pattern to catch create/update/delete policy operations
        event_pattern = """
        {
          "eventType": [
            "com.oraclecloud.identitycontrolplane.CreatePolicy",
            "com.oraclecloud.identitycontrolplane.UpdatePolicy",
            "com.oraclecloud.identitycontrolplane.DeletePolicy"
          ],
          "data": {
            "compartmentId": [
              "%s"
            ]
          }
        }
        """ % rule_compartment_id

        rule_details = oci.events.models.CreateRuleDetails(
            display_name="policy-change-rule",
            compartment_id=rule_compartment_id,
            description="Rule to detect IAM policy changes and send notifications",
            is_enabled=True,
            condition=event_pattern,
            actions=oci.events.models.ActionDetailsList(
                actions=[
                    oci.events.models.NotificationActionDetails(
                        action_type="ONS",
                        topic_id=topic_id
                    )
                ]
            )
        )

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

        Now, any Create/Update/Delete of an IAM Policy in that compartment will trigger:

        * Events rule → Notifications topic → email to you.

        ***

        ## 4. (Optional) Create a Monitoring Alarm on a Custom “PolicyChange” Metric

        If you already push a custom metric (e.g. `policy_changes_count`) to OCI Monitoring (via Logging or custom code), you can add a classic Monitoring alarm:

        ```python theme={null}
        from oci.monitoring import MonitoringClient
        from oci.monitoring.models import (
            CreateAlarmDetails,
            NotificationDetails
        )

        monitoring_client = MonitoringClient(config)

        # Example metric query (adjust for your metric namespace/name)
        query = "policy_changes[1m].count() > 0"

        alarm_details = CreateAlarmDetails(
            display_name="policy-change-metric-alarm",
            compartment_id=compartment_id,
            namespace="custom_metrics_namespace",
            query=query,
            severity="CRITICAL",
            destinations=[topic_id],  # Send alarm to same Notifications topic
            is_enabled=True,
            metric_compartment_id=compartment_id,
            message_format="ONS_OPTIMIZED"
        )

        alarm = monitoring_client.create_alarm(alarm_details).data
        print("Created Monitoring alarm:", alarm.id)
        ```

        If you don’t already have such a metric, you can rely **solely on the Events rule** (step 3) for policy-change alerting, which is the standard remediation.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        resource "oci_monitoring_alarm" "iam_policy_change_alarm" {
          # Create an alarm that fires whenever at least one IAM policy change event is recorded.
          compartment_id         = "COMPARTMENT_OCID"          # Replace with the OCID of the compartment whose IAM policy changes you want to monitor
          display_name           = "IAM Policy Change Alarm"
          is_enabled             = true
          severity               = "CRITICAL"
          namespace              = "oci_audit"                 # Audit events metric namespace
          metric_compartment_id  = "COMPARTMENT_OCID"          # Typically the same as compartment_id
          metric_compartment_id_in_subtree = true              # Optional: include subcompartments, set to false if not desired

          # Alarm query: count IAM policy change events over the last 5 minutes and fire if at least one occurs.
          # Adjust the window [5m] if your standard is different; the threshold here is ">= 1 event".
          query = "IamPolicyChange[5m].count() >= 1"

          # Where to send notifications when the alarm triggers
          destinations = [
            "NOTIFICATION_TOPIC_OCID",                         # Replace with an oci ons topic OCID (e.g., for email, PagerDuty, etc.)
          ]

          # Optional: fine-tune behavior
          resolution           = "1m"
          pending_duration     = "PT0M"
          message_format       = "TEXT"
          repeat_notification_duration = "PT60M"
        }
        ```

        Changing `query`, `namespace`, or `severity` on an existing `oci_monitoring_alarm` updates the alarm in place and does not force replacement; `terraform plan` should show an in-place update (`~ update in-place`) to the existing alarm, or a `+ create` for a new one if it does not yet exist.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
