> ## 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 Root Activity Alarm Configured

### More Info:

Unauthorized API calls, especially by root or admin-level entities, must trigger alerts. This is a critical indicator of privilege escalation or internal reconnaissance by a threat actor.

### Risk Level

High

### Address

Compliance, Security

### Compliance Standards

* APRA CPS 234 (Australia)
* AWS Startup Security Baseline
* 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
* 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 concise, console-based steps to configure an alarm for root activity in OCI Monitoring. This uses:

        * Audit → Logs
        * Service Connector → Custom Metric in Monitoring
        * Alarm → Notification to email/Slack/etc.

        ***

        ## 1. Prerequisites

        1. Make sure:
           * **Audit** is enabled (it is on by default for all compartments).
           * You have permissions for:
             * `audit`, `logging`, `sch` (Service Connector Hub), `metrics`, and `ons` (Notifications).

        2. Decide:
           * Which **compartment** to monitor (often the root compartment/tenancy).
           * Where to put:
             * The **Service Connector**
             * The **Custom Metric compartment** (often same as tenancy or a central ops compartment)
             * The **Alarm** and **Notification topics**

        ***

        ## 2. Confirm Audit Logs Are Flowing to Logging

        1. In OCI Console, open the **navigation menu**.
        2. Go to **Observability & Management → Logging**.
        3. Under **Logs**, select the compartment where Audit logs should appear.
        4. Ensure there is a log group such as **`Default Audit Logs`** and that **Audit logs** exist (filter by `Service = Audit` or check for recent events).

        If Audit logs aren’t going to Logging, enable them:

        1. Go to **Identity & Security → Audit**.
        2. Choose your **compartment** (root / tenancy).
        3. Confirm events exist. By default, they are exported to the Logging service for 90 days; if not, configure a log as needed.

        ***

        ## 3. Create a Service Connector to Turn Root Activity into a Custom Metric

        You will create a Service Connector that:

        * **Source**: Audit Logs
        * **Target**: Monitoring custom metrics
        * **Filter**: Only events where the actor is the **tenancy’s root user** (OCID of root user) or equivalent high-privilege user.

        1. Find the root user OCID:
           * Go to **Identity & Security → Users**.
           * Locate the **tenancy root user** (often the first user or the user associated with the tenancy).
           * Copy the root **User OCID**.

        2. Go to **Observability & Management → Service Connector Hub**.

        3. Click **Create service connector**.

        4. **Basics**:
           * Name: e.g., `Root-Activity-to-Metrics`
           * Compartment: choose your central ops / security compartment.

        5. **Source**:
           * Select **Logging**.
           * Choose:
             * **Log group** containing your Audit logs (e.g., `Default Audit Logs`).
             * **Log**: the **Audit** log.

        6. **Filter** (important):
           * Under **Stream logs by specifying filters**, add a filter to match Audit events where:
             * `data.identity.principalId = "<ROOT_USER_OCID>"`\
               (replace with the OCID you copied)
           * Example filter (JSON filter expression, depending on UI version):
             ```json theme={null}
             {
               "operator": "EQUALS",
               "field": "data.identity.principalId",
               "value": "ocid1.user.oc1..aaaa...rootUserOCID"
             }
             ```
           * If `principalEmail` or `userName` is easier to filter on in your environment, adjust the field accordingly (e.g., `data.identity.userName`).

        7. **Target**:
           * Choose **Monitoring**.
           * Metric namespace: e.g., `security_root_activity`.
           * Metric name: e.g., `root_actions_count`.
           * Dimensions (recommended):
             * `compartmentId`, `eventName`, `requestAction`, `requestResource`, etc.
           * Value: typically `1` per event (the target UI usually defaults to counting occurrences).

        8. Save and **Activate** the service connector.

        Now each root activity event will push a custom metric point into Monitoring.

        ***

        ## 4. Verify the Custom Metric

        1. Go to **Observability & Management → Monitoring → Metrics Explorer**.
        2. In **Compartment**, pick the compartment where metrics are stored.
        3. Under **Namespace**, select `security_root_activity` (or the namespace you used).
        4. Under **Metric Name**, select `root_actions_count`.
        5. Adjust time range (e.g., last 1–24 hours).
        6. Confirm you see metric data when you know root has done an action (you can do a trivial root action to test, like listing resources).

        ***

        ## 5. Create a Notification Topic (If Not Already)

        1. Go to **Application Integration → Notifications**.
        2. Click **Create topic**:
           * Name: e.g., `Root-Activity-Alerts`.
           * Compartment: security / ops.
        3. Open the topic; click **Create subscription**.
        4. Choose **Protocol** (e.g., Email, HTTPS, Slack via webhook, PagerDuty, etc.).
        5. Enter the endpoint (email address, webhook URL).
        6. For email, confirm via the link sent to your email.

        ***

        ## 6. Create an Alarm on the Root Activity Metric

        1. Go to **Observability & Management → Monitoring → Alarms**.

        2. Click **Create alarm**.

        3. **Alarm basics**:
           * Name: `Root-Activity-Alarm`.
           * Compartment: same as your metrics (or your monitoring compartment).

        4. **Alarm query** (example):

           * **Namespace**: `security_root_activity`
           * **Metric**: `root_actions_count`
           * **Statistic**: `sum`
           * **Interval**: `1 minute` or `5 minutes`.
           * Use a Monitoring query like:
             ```text theme={null}
             sum(root_actions_count[5m]) > 0
             ```
           * This means: trigger if **any** root activity occurs in the last 5 minutes.

        5. **Severity**: choose **Critical** (recommended).

        6. **Destination**:
           * Select the **Notification topic** `Root-Activity-Alerts`.

        7. **Alarm trigger settings**:
           * Trigger rule: **Greater than** threshold (as defined above).
           * Specify how many consecutive periods should breach before triggering (e.g., `1` period for immediate alert).

        8. Optional: **Suppress** (to avoid alert storms) if needed, e.g., auto-resolve or cooldown period.

        9. Click **Create alarm**.

        ***

        ## 7. Test the Alarm

        1. Perform a **test action as root** (e.g., view or modify a resource).
        2. Wait for the monitoring interval (e.g., 5 minutes).
        3. Confirm:
           * The **metric** updated in **Metrics Explorer**.
           * The **alarm** enters **FIRING**.
           * You receive the **notification** via your configured channel.

        ***

        If you share exactly how you identify the “root account” in your tenancy (user OCID, group, or specific IAM conditions), I can give you a more precise filter expression for the Service Connector.
      </Accordion>

      <Accordion title="Using CLI">
        Below is a CLI-based way to configure an OCI Monitoring alarm for root activity. Because metric names and dimensions can differ between tenancies, the steps first discover the exact Audit metric and then create the alarm.

        ***

        ### 1. Set your common variables

        ```bash theme={null}
        # Root compartment (tenancy) OCID
        TENANCY_OCID="<your_tenancy_ocid>"

        # Compartment where you want the alarm resource itself to live
        ALARM_COMPARTMENT_OCID="<compartment_ocid_for_alarm>"

        # Notification Topic OCID (for email/SNS style notifications)
        TOPIC_OCID="<notification_topic_ocid>"

        # Region
        REGION="<your_region>"   # e.g. "us-ashburn-1"
        ```

        You can avoid repeating `--region` by exporting:

        ```bash theme={null}
        export OCI_CLI_REGION="$REGION"
        ```

        ***

        ### 2. Discover available Audit metrics (to locate root-activity metric)

        List metrics for the `oci_audit` namespace in the root compartment:

        ```bash theme={null}
        oci monitoring metric list \
          --compartment-id "$TENANCY_OCID" \
          --compartment-id-in-subtree true \
          --namespace "oci_audit" \
          --all
        ```

        Inspect the output for a metric that clearly represents root/tenant-level activity (for example, you may see metrics like `root_activity`, `audit_events`, etc., with dimensions such as `userName`, `principalId`, or flags indicating root usage).

        Identify:

        * `metricName` (e.g. `root_activity`)
        * Any dimension(s) that distinguish root user or root-compartment actions (e.g. `userName = "ocid1.tenancy.oc1..."` or `principalId = "<root-principal-id>"`)

        You will use these in the query.

        ***

        ### 3. Build the Monitoring query for “root activity”

        A typical query pattern:

        ```text theme={null}
        <metricName>{dimensionKey = "value"}[1m].count() > 0
        ```

        Example (you must adapt `metricName`, `dimensionKey`, and `value` based on step 2):

        ```text theme={null}
        root_activity[1m].count() > 0
        ```

        or, with a dimension (example only):

        ```text theme={null}
        audit_events{userName = "ocid1.tenancy.oc1..aaaa..."}[1m].count() > 0
        ```

        Test your query interactively in the OCI Console (Monitoring → Metrics Explorer) to confirm it returns data when you simulate or view historical root activity.

        ***

        ### 4. Create the alarm via OCI CLI

        Use the query from step 3 in `--query-text`.

        ```bash theme={null}
        oci monitoring alarm create \
          --compartment-id "$ALARM_COMPARTMENT_OCID" \
          --display-name "Root Activity Alarm" \
          --is-enabled true \
          --metric-compartment-id "$TENANCY_OCID" \
          --metric-compartment-id-in-subtree true \
          --namespace "oci_audit" \
          --query-text '<YOUR_QUERY_TEXT_HERE>' \
          --severity "CRITICAL" \
          --destinations '["'"$TOPIC_OCID"'"]' \
          --pending-duration "PT1M" \
          --repeat-notification-duration "PT30M" \
          --body "Root activity detected in tenancy" \
          --message-format "PRETTY_JSON" \
          --resolution "1m"
        ```

        Replace `<YOUR_QUERY_TEXT_HERE>` with your tested query, for example:

        ```bash theme={null}
        --query-text 'root_activity[1m].count() > 0'
        ```

        or:

        ```bash theme={null}
        --query-text 'audit_events{userName = "ocid1.tenancy.oc1..aaaa..."}[1m].count() > 0'
        ```

        ***

        ### 5. Verify the alarm

        1. List alarms:

           ```bash theme={null}
           oci monitoring alarm list \
             --compartment-id "$ALARM_COMPARTMENT_OCID" \
             --all
           ```

        2. Describe the alarm to confirm configuration:

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

        3. Trigger a controlled root action (if possible) and confirm a notification is sent to the topic.

        ***

        If you paste the output of step 2 (the relevant metric snippet), I can help you craft the exact `--query-text` for your tenancy.
      </Accordion>

      <Accordion title="Using Python">
        Below is a practical way to remediate this in **OCI using Python** by creating a **Monitoring Alarm** that fires whenever there is root user activity (using Audit metrics).

        ***

        ## 1. Prerequisites

        1. **Enable Audit** in the tenancy (it’s on by default).
        2. Install OCI Python SDK:
           ```bash theme={null}
           pip install oci
           ```
        3. Configure your `~/.oci/config` with appropriate `tenancy`, `user`, `fingerprint`, `key_file`, `region` and a profile (e.g. `DEFAULT`).
        4. Have:
           * **Compartment OCID** where you want the alarm created.
           * **Notification Topic OCID** (for OCI Notifications) to receive alerts.

        ***

        ## 2. Find / Confirm Root Activity Metric

        Oracle provides Audit-related metrics in namespace `oci_audit`. You should confirm what’s available in your tenancy:

        ```python theme={null}
        import oci

        config = oci.config.from_file("~/.oci/config", "DEFAULT")
        monitoring_client = oci.monitoring.MonitoringClient(config)

        compartment_id = "<COMPARTMENT_OCID>"

        list_metrics_details = oci.monitoring.models.ListMetricsDetails(
            namespace="oci_audit",
            query="*"
        )

        response = monitoring_client.list_metrics(
            compartment_id=compartment_id,
            list_metrics_details=list_metrics_details
        )

        for metric in response.data:
            print(metric.name, metric.namespace, metric.dimensions)
        ```

        Look for a metric that represents root activity (e.g., `auditrootactioncount` or similar) or a way to filter on `principalId` or `identity.domain.id`/`identity.user.name` indicating root or tenancy-level identity.

        Suppose you identified:

        * Namespace: `oci_audit`
        * Metric: `auditrootactioncount`
        * Dimension for root activity: `principalid = "ocid1.tenancy.oc1..root"` (example – adjust to what you actually see).

        ***

        ## 3. Define the Alarm Query

        A typical Monitoring query for “any root action in last minute” might look like:

        ```text theme={null}
        auditrootactioncount[1m]{principalid = "ocid1.tenancy.oc1..root"}.sum() > 0
        ```

        Adjust:

        * Metric name
        * Dimension key/value (whatever you confirmed in step 2)
        * Window `[1m]`, `[5m]`, etc.
        * Aggregation `.sum()` / `.rate()` as appropriate.

        ***

        ## 4. Create the Alarm with Python

        ```python theme={null}
        import oci

        # Load config
        config = oci.config.from_file("~/.oci/config", "DEFAULT")

        monitoring_client = oci.monitoring.MonitoringClient(config)

        compartment_id = "<COMPARTMENT_OCID>"      # where the alarm resource will live
        topic_id = "<NOTIFICATION_TOPIC_OCID>"     # OCI Notifications topic to notify

        # Monitoring query for root activity
        # Replace metric name, dimension and OCID values as per your environment
        alarm_query = (
            'auditrootactioncount[1m]{principalid = "ocid1.tenancy.oc1..root"}.sum() > 0'
        )

        alarm_details = oci.monitoring.models.CreateAlarmDetails(
            display_name="Root Activity Alarm",
            compartment_id=compartment_id,
            namespace="oci_audit",
            query=alarm_query,
            severity="CRITICAL",                # or "ERROR", etc.
            is_enabled=True,
            # Notify every evaluation when condition is met
            pending_duration="PT0M",            # 0 minutes pending; trigger immediately
            resolution="PT5M",                  # reset period; optional
            destinations=[topic_id],            # one or more topic OCIDs
            repeat_notification_duration="PT30M",  # re-notify if still firing
            body="Root user activity detected in tenancy.",
            metric_compartment_id_in_subtree=True,  # include all subcompartments if needed
            is_notifications_per_metric_dimension_enabled=False
        )

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

        ***

        ## 5. Validate

        1. In the OCI Console:\
           Monitoring → Alarms → locate “Root Activity Alarm”.
        2. Confirm:
           * Namespace: `oci_audit`.
           * Query matches what you tested.
           * Notification destination is correct.
        3. Trigger a test (if possible) or temporarily lower the threshold to confirm a notification is sent.

        ***

        ## 6. Summary of Remediation

        * **Identify / confirm** the metric(s) representing root activity in `oci_audit`.
        * **Craft a Monitoring query** that detects non-zero root activity in a small time window.
        * **Programmatically create** an Alarm using the OCI Python SDK with:
          * `namespace="oci_audit"`
          * The root-activity query
          * A Notifications topic as the destination.

        If you share the exact metric name and dimensions you see from `list_metrics`, I can give you a fully tailored query string.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        resource "oci_monitoring_alarm" "root_unauthorized_api_calls" {
          # OCI compartment where the alarm resource itself will live
          compartment_id = OCID_OF_ALARM_COMPARTMENT

          # Metric source (often same as compartment_id, but can differ if metrics are in another compartment)
          metric_compartment_id = OCID_OF_METRIC_COMPARTMENT

          display_name = "Root Unauthorized API Calls Alarm"

          # Destination(s) for notifications (Notifications topic OCIDs)
          destinations = [
            OCID_OF_OCI_NOTIFICATIONS_TOPIC,
          ]

          # Monitoring namespace and query for your root/admin unauthorized API metric
          # Replace CUSTOM_NAMESPACE and CUSTOM_METRIC with your actual metric source,
          # for example a custom metric emitted from Audit/Logging for root 4xx/5xx calls.
          namespace = "CUSTOM_NAMESPACE_FOR_ROOT_ACTIVITY_METRICS"

          # Example: trigger if there is any unauthorized root/admin API call in 5 minutes
          # Replace CUSTOM_METRIC_NAME and dimension filters with your real metric and labels.
          query = "CUSTOM_NAMESPACE_FOR_ROOT_ACTIVITY_METRICS.CUSTOM_METRIC_NAME{userType = \"root\", responseCode = \"4xx\"}.sum(5m) > 0"

          severity    = "CRITICAL"
          is_enabled  = true
          resolution  = "5m"

          # Optional: tighten alarm behavior as needed
          pending_duration  = "PT5M"   # how long condition must hold before firing
          repeat_notification_duration = "PT30M"

          # Optional freeform / defined tags
          # freeform_tags = {
          #   "ENV" = "PROD"
          # }

          # Optional: specify whether metric is from a cross-tenant source
          # is_cross_tenancy = false
        }
        ```

        Substitute:

        * `OCID_OF_ALARM_COMPARTMENT` with the compartment OCID where you manage alarms.
        * `OCID_OF_METRIC_COMPARTMENT` with the compartment OCID where the metric is emitted.
        * `OCID_OF_OCI_NOTIFICATIONS_TOPIC` with your Notifications topic OCID used for alerting.
        * `CUSTOM_NAMESPACE_FOR_ROOT_ACTIVITY_METRICS` and `CUSTOM_METRIC_NAME` with the actual namespace/metric you publish for unauthorized root/admin API calls, and adjust the dimension filters (`userType`, `responseCode`) to match your metric schema.

        This change does not force replacement of existing resources; it creates (or updates) a single `oci_monitoring_alarm` resource.

        Verification: `terraform plan` should show one `oci_monitoring_alarm.root_unauthorized_api_calls` to be created (or updated) with the `query` condition using your root-activity metric and a threshold of `> 0`.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
