> ## 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 Malicious IP Password Reset Alarm Configured

### More Info:

Flag password reset requests originating from known threat-actor IP addresses or Tor exit nodes. This usually indicates an active account takeover sequence.

### Risk Level

Critical

### 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
* 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
* 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 practical, console-based steps to create an alarm/alert when a password reset occurs from a malicious IP in OCI. Because this specific condition comes from *security/audit events* rather than a native metric, you do it via **Cloud Guard + Notifications**, which is Oracle’s recommended way to alert on “malicious IP” identity activity.

        ***

        ## 1. Prerequisites

        1. **Permissions**
           * Your user/group must have IAM policies to:
             * Use Cloud Guard
             * Manage Notifications
             * Read tenancy audit logs (usually included in Cloud Guard permissions)

        2. **Region**
           * Do all steps in the *same region* where you want alerts, especially for Notifications topics.

        ***

        ## 2. Enable and Configure Cloud Guard

        1. In the OCI Console, open the menu (☰) → **Identity & Security** → **Cloud Guard**.

        2. If Cloud Guard is not enabled:
           * Click **Enable Cloud Guard**.
           * Choose:
             * **Reporting region**.
             * **Configuration**: usually `Default configuration` is fine, or choose your existing one.
           * Click **Enable**.

        3. Confirm the **Detector Recipe** that looks for malicious IP sign-ins is enabled:
           * Under Cloud Guard, go to **Detector Recipes**.
           * Locate the recipe you’re using (often `OCI Cloud Guard Managed – Activity Detector Recipe` or similar).
           * Click it → under **Detector Rules**, search for rules such as:
             * `Signin from Malicious IP Address`
             * Or any rule description mentioning *malicious IP* or *suspicious sign-in*.
           * For that rule:
             * Ensure its **Status** is `Enabled`.
             * Make sure the **Target** scope (compartments/tenancy) includes your IAM users.

        *(Cloud Guard will now create Problems when it detects sign-ins from malicious IPs, which includes password-related sign-in behavior.)*

        ***

        ## 3. Create a Notifications Topic and Subscription

        You’ll use **OCI Notifications** for alerts.

        1. Menu → **Application Integration** → **Notifications**.

        2. Click **Create Topic**.
           * Name: `malicious-ip-password-reset-topic`
           * Description: `Alerts for password reset / sign-in events from malicious IPs`
           * Choose the appropriate **compartment**.
           * Click **Create**.

        3. Add a **Subscription**:
           * Inside the topic, click **Create Subscription**.
           * Protocol: `Email` (or `Slack`, `PagerDuty`, `HTTPS`, etc., as needed).
           * Email: enter the address for security/ops.
           * Click **Create**.
           * Confirm the subscription via the email you receive.

        ***

        ## 4. Connect Cloud Guard Problems to Notifications

        You now tie Cloud Guard security problems (including malicious IP identity events) to that topic.

        1. Go back to **Cloud Guard** → **Configuration** (or **Targets**, depending on UI version).
        2. Open your **Target** (often `Root Compartment Target` or your specific compartment target).
        3. Under **Target Details**, locate the **Notifications** or **Responder Settings** section:
           * Look for “Notifications for Problems” or similar wording.
        4. Configure:
           * **Severity**: choose which severities to send (e.g., `High` and `Critical` or `All`).
           * **Notification Topic**: select the topic you created: `malicious-ip-password-reset-topic`.
        5. Save/Update the target configuration.

        Now, whenever the **malicious IP sign-in / password-related detector** fires and a Problem is created, a notification is sent to your topic and then to your email/endpoint.

        ***

        ## 5. (Optional) Narrow Notifications to Malicious IP Password Resets Only

        If you want only *malicious IP password reset*–type events, you can:

        1. In **Cloud Guard → Problems**, open a problem that corresponds to a malicious IP sign-in/password reset.
        2. Review:
           * **Detector Rule Name**
           * **Problem Type / Labels**
        3. Instead of globally notifying on all Problems, you can:
           * Use a SIEM or ticketing integration downstream (e.g., Splunk, QRadar) to filter only those with the specific **detector rule name** or **problem type**.
           * Or configure separate topics per severity / rule, and subscribe different teams accordingly.

        (Cloud Guard currently does problem-level alerting; password-reset-from-malicious-IP is captured as a specific type of Problem.)

        ***

        ## 6. Validate the Setup

        1. In Cloud Guard, use **Simulate** (if available) or temporarily trigger a test condition (e.g., from a test environment or using known-bad IP lists / IP reputation testing).
        2. Confirm:
           * A **Problem** appears in Cloud Guard.
           * An **email/notification** is sent to your configured subscription with the malicious IP and event details.

        ***

        If you need this strictly as a **Monitoring Alarms** object (under `Observability & Management → Alarms`) instead of Cloud Guard-driven Problems, say so and I’ll outline how to pipe Audit events to metrics via Service Connector + Logging, then build a metric-based alarm on those events.
      </Accordion>

      <Accordion title="Using CLI">
        Below is how you can configure a “Malicious IP Password Reset” alarm in OCI Monitoring using the OCI CLI. Since the exact metric name/dimensions can differ between tenants and setups, I’ll show you:

        * How to discover the metric
        * How to build the alarm query
        * How to create the alarm via CLI

        You can plug in the exact metric name/dimensions you find in your environment.

        ***

        ## 1. Prerequisites

        1. OCI CLI installed and configured:

        ```bash theme={null}
        oci setup config
        ```

        2. Identify:
           * **Compartment OCID**: `ocid1.compartment.oc1..xxxx`
           * **Notification Topic OCID** (for email/SMS/etc.): `ocid1.onstopic.oc1..xxxx`

        ***

        ## 2. Discover the Metric for “Malicious IP Password Reset”

        First, list metrics for the relevant namespace. Security- or IAM-related metrics are often in namespaces like `oci_audit`, `oci_identity`, or a custom namespace if you created custom metrics from logs.

        Example: list metrics in `oci_audit` for your compartment:

        ```bash theme={null}
        oci monitoring metric-list metric-data \
          --compartment-id <COMPARTMENT_OCID> \
          --namespace oci_audit \
          --limit 100 \
          --query-text ""
        ```

        If you know you are using a specific namespace (e.g., `security_events` or a custom namespace), list there:

        ```bash theme={null}
        oci monitoring metric-list metric-data \
          --compartment-id <COMPARTMENT_OCID> \
          --namespace <NAMESPACE_NAME> \
          --limit 100
        ```

        Look in the output for a metric whose name/dimensions clearly indicate password resets from malicious IPs. It might look something like:

        * Namespace: `security_events`
        * Metric name: `malicious_ip_password_reset`
        * Dimensions (examples): `eventType="PASSWORD_RESET"`, `threatType="MaliciousIP"`

        Write down:

        * `namespace`
        * `name` (metric name)
        * relevant `dimensions` (e.g. `threatType`, `eventType`, etc.)

        ***

        ## 3. Build the Alarm Query

        Assume you found:

        * Namespace: `security_events`
        * Metric name: `malicious_ip_password_reset`
        * Dimension: `threatType="MaliciousIP"`

        Example “count over 5 minutes and trigger if ≥ 1” query:

        ```text theme={null}
        malicious_ip_password_reset[5m]{threatType = "MaliciousIP"}.count() >= 1
        ```

        Adjust as needed for your real metric name/dimensions and threshold:

        * Time window: `[5m]`, `[15m]`, etc.
        * Aggregation: `.count()`, `.sum()`
        * Condition: `>= 1`, `>= 5`, etc.

        ***

        ## 4. Create the Alarm via OCI CLI

        Use `oci monitoring alarm create`. Example (replace placeholders):

        ```bash theme={null}
        oci monitoring alarm create \
          --compartment-id <COMPARTMENT_OCID> \
          --display-name "Malicious IP Password Reset Alarm" \
          --namespace "security_events" \
          --query "malicious_ip_password_reset[5m]{threatType = \"MaliciousIP\"}.count() >= 1" \
          --severity CRITICAL \
          --is-enabled true \
          --destinations '["<NOTIFICATION_TOPIC_OCID>"]' \
          --statistic SUM \
          --metric-compartment-id <COMPARTMENT_OCID> \
          --metric-compartment-id-in-subtree true \
          --resolution "1m" \
          --pending-duration "PT5M" \
          --message-format PRETTY_JSON \
          --body "Alert: Malicious IP-driven password reset detected." \
          --repeat-notification-interval "PT30M"
        ```

        Key flags:

        * `--namespace` must match the metric namespace.
        * `--query` must use your exact metric name and dimensions.
        * `--destinations`: list of Notification topic OCIDs.
        * `--pending-duration`: how long the condition must hold before firing.
        * `--repeat-notification-interval`: how often to re-notify while in alarm.

        ***

        ## 5. Verify the Alarm

        List alarms:

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

        Get full details:

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

        If needed, update:

        ```bash theme={null}
        oci monitoring alarm update \
          --alarm-id <ALARM_OCID> \
          --query "malicious_ip_password_reset[5m]{threatType = \"MaliciousIP\"}.count() >= 1"
        ```

        ***

        If you can share the exact metric name/namespace you see for malicious password resets in your tenancy, I can give you the exact `--query` line to use.
      </Accordion>

      <Accordion title="Using Python">
        Below is one way to implement this using OCI Monitoring + Python:

        **Goal:**\
        Raise an OCI Monitoring Alarm when a password reset occurs from a known malicious IP, using Python.

        ***

        ## 1. Prerequisites

        1. **OCI SDK for Python installed:**
           ```bash theme={null}
           pip install oci
           ```

        2. **Configured OCI credentials**, e.g. `~/.oci/config`:
           ```ini theme={null}
           [DEFAULT]
           user=ocid1.user.oc1..aaaa...
           fingerprint=...
           key_file=/path/to/key.pem
           tenancy=ocid1.tenancy.oc1..aaaa...
           region=us-ashburn-1
           ```

        3. **An OCI Notification topic** (for the alarm to publish to):
           * In Console: Developer Services → Notifications → Topics → Create Topic
           * Note its **OCID** (e.g. `ocid1.onstopic.oc1....`)

        4. **Your Malicious IP list**, e.g. a Python list or external file.

        ***

        ## 2. Overview of the Architecture

        1. **Poll Audit Logs** for password-reset events.
        2. **Filter by client IP** against your malicious IP list.
        3. For each malicious event, **push a custom metric** to OCI Monitoring.
        4. Create an **Alarm** on that custom metric that triggers a Notification.

        ***

        ## 3. Step 1 – Emit a Custom Metric When Malicious IP Detected

        Assume:

        * Namespace: `security_metrics`
        * Metric name: `malicious_password_reset`
        * Compartment OCID: `COMPARTMENT_OCID`
        * Region from config (`~/.oci/config`)

        ### 3.1. Sample script to scan Audit logs and push metrics

        This is a minimal example; in production you’d run this periodically (cron, OCI Functions, etc.).

        ```python theme={null}
        import oci
        from datetime import datetime, timedelta, timezone

        # -------- CONFIG --------
        PROFILE = "DEFAULT"
        COMPARTMENT_ID = "ocid1.compartment.oc1..xxxx"
        METRIC_NAMESPACE = "security_metrics"
        METRIC_NAME = "malicious_password_reset"
        MALICIOUS_IPS = {"1.2.3.4", "9.8.7.6"}  # replace with your list
        LOOKBACK_MINUTES = 5  # how far back to query audit logs
        # ------------------------

        config = oci.config.from_file("~/.oci/config", PROFILE)

        audit_client = oci.audit.AuditClient(config)
        monitoring_client = oci.monitoring.MonitoringClient(config)

        def get_recent_password_reset_events():
            end_time = datetime.now(timezone.utc)
            start_time = end_time - timedelta(minutes=LOOKBACK_MINUTES)

            # Get audit events in compartment for the last few minutes
            response = audit_client.list_events(
                compartment_id=COMPARTMENT_ID,
                start_time=start_time,
                end_time=end_time
            )

            events = []
            for e in response.data:
                # Filter for identity password-reset–type events.
                # Exact values depend on your tenant; inspect sample audit events in the Console.
                if (
                    e.event_type == "Identity" and
                    "password" in (e.operation or "").lower() and
                    "reset" in (e.operation or "").lower()
                ):
                    events.append(e)

            return events

        def extract_client_ip(audit_event):
            # IP often in data.request.client_ip or similar; inspect an example in your tenant.
            try:
                return audit_event.data.get("request", {}).get("clientIp", None)
            except Exception:
                return None

        def push_malicious_metric(count):
            if count == 0:
                return

            metric_data = oci.monitoring.models.MetricDataDetails(
                namespace=METRIC_NAMESPACE,
                resource_group=None,
                compartment_id=COMPARTMENT_ID,
                name=METRIC_NAME,
                dimensions={"source": "audit"},
                datapoints=[
                    oci.monitoring.models.Datapoint(
                        timestamp=datetime.now(timezone.utc),
                        value=float(count)
                    )
                ],
                metadata={}
            )

            post_metrics_details = oci.monitoring.models.PostMetricDataDetails(
                metric_data=[metric_data]
            )

            resp = monitoring_client.post_metric_data(post_metrics_details)
            print("Pushed metric, failed metrics count:", resp.data.failed_metrics_count)

        def main():
            events = get_recent_password_reset_events()
            malicious_count = 0

            for e in events:
                ip = extract_client_ip(e)
                if ip in MALICIOUS_IPS:
                    malicious_count += 1

            if malicious_count > 0:
                print(f"Detected {malicious_count} malicious password reset event(s)")
                push_malicious_metric(malicious_count)
            else:
                print("No malicious events found")

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

        Run this script every few minutes; it emits the metric `malicious_password_reset` whenever it detects password resets from IPs in `MALICIOUS_IPS`.

        ***

        ## 4. Step 2 – Create the Monitoring Alarm via Python

        This alarm fires when any malicious event metric is emitted in the last 5 minutes.

        ```python theme={null}
        import oci

        PROFILE = "DEFAULT"
        COMPARTMENT_ID = "ocid1.compartment.oc1..xxxx"
        TOPIC_ID = "ocid1.onstopic.oc1..xxxx"  # Your Notifications topic OCID
        METRIC_NAMESPACE = "security_metrics"
        METRIC_NAME = "malicious_password_reset"
        ALARM_DISPLAY_NAME = "Malicious IP Password Reset Alarm"
        ALARM_OCID_FILE = "created_alarm_ocid.txt"

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

        # Monitoring query: sum of metric over last 5 minutes > 0
        # See OCI Monitoring query language docs for details.
        query = f"{METRIC_NAMESPACE}.{METRIC_NAME}[5m].sum() > 0"

        alarm_details = oci.monitoring.models.CreateAlarmDetails(
            display_name=ALARM_DISPLAY_NAME,
            compartment_id=COMPARTMENT_ID,
            metric_compartment_id=COMPARTMENT_ID,
            namespace=METRIC_NAMESPACE,
            query=query,
            severity="CRITICAL",
            destinations=[TOPIC_ID],
            is_enabled=True,
            repeat_notification_duration="PT15M",  # repeat every 15 minutes while in ALARM
            suppression=None,
            message_format="ONS_OPTIMIZED",
            body="Malicious IP password reset detected.",
            is_notifications_per_metric_dimension_enabled=False
        )

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

        with open(ALARM_OCID_FILE, "w") as f:
            f.write(alarm.id + "\n")
        ```

        ***

        ## 5. Validate

        1. **Generate a test event**:\
           Temporarily add your own IP to `MALICIOUS_IPS`, perform a password reset, run the script, and confirm:
           * Metric appears in **Monitoring → Metrics → security\_metrics**.
           * Alarm transitions to **FIRING**.
           * Notification is received (email, Slack, etc., depending on your subscription).

        2. **Adjust thresholds** if you want alarms only on multiple events, e.g.:
           ```text theme={null}
           security_metrics.malicious_password_reset[5m].sum() > 3
           ```

        ***

        If you share how password-reset events and IPs appear in your Audit logs (a single example JSON), I can refine the filters and IP extraction to exactly match your tenancy.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        resource "oci_monitoring_alarm" "malicious_ip_password_reset" {
          # Compartment where the alarm is defined
          compartment_id = VAR_ALARM_COMPARTMENT_OCID  # substitute your alarm compartment OCID

          display_name = "Malicious IP Password Reset Alarm"
          is_enabled   = true
          severity     = "CRITICAL"

          # Namespace and metric must already exist (e.g., via Service Connector/Logging
          # that emits a metric for password resets from malicious IPs or Tor nodes)
          namespace = "custom_security"  # substitute your metric namespace

          # Example: alarm when there is at least 1 password reset from a malicious IP
          # over the last 5 minutes. Adjust metric name, dimensions, window, and threshold
          # to match how your pipeline publishes the metric.
          #
          # Replace:
          #   PasswordResetFromMaliciousIpCount  with your metric name
          #   sourceIpCategory                   with your dimension key
          #   "MALICIOUS"                        with your tag/category for bad IPs
          query = "PasswordResetFromMaliciousIpCount[5m]{sourceIpCategory = \"MALICIOUS\"}.sum() > 0"

          # Where the metric lives (often same as or a logging compartment)
          metric_compartment_id                 = VAR_METRIC_COMPARTMENT_OCID  # substitute metric compartment OCID
          metric_compartment_id_in_subtree      = false
          pending_duration                      = "PT5M"   # how long the condition must hold before firing
          resolution                            = "5m"     # evaluation interval
          repeat_notification_duration          = "PT30M"  # how often to re-notify while in alarm
          is_notifications_per_metric_dimension_enabled = false

          # ONS topics to receive the alarm (email, PagerDuty, webhook, etc.)
          destinations = [
            ONS_TOPIC_OCID_PASSWORD_SECURITY  # substitute your Notification Topic OCID
          ]

          # Optional: structured notifications for ONS
          message_format = "ONS"
        }
        ```

        OCI Monitoring alarms can only evaluate metrics, not inspect raw log fields like source IPs; to fully remediate this finding you must first ensure a Logging / Service Connector (or external pipeline) publishes a metric like `PasswordResetFromMaliciousIpCount` with a dimension indicating malicious/Tor IPs, then attach an `oci_monitoring_alarm` like the one above to that metric.

        This change does not force replacement of other resources; `terraform plan` should show either creation of a new `oci_monitoring_alarm.malicious_ip_password_reset` or an in‑place update of its `query` (and any other changed arguments) only.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
