> ## 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 MFA Violation Alarm Configured

### More Info:

An alarm must exist for MfaRequirementViolation. This ensures security administrators are immediately notified if a user attempts to bypass Multi-Factor Authentication constraints.

### Risk Level

Medium

### Address

Compliance, Security

### Compliance Standards

* APRA CPS 234 (Australia)
* 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
* Securities and Exchange Board of India (SEBI) - Cloud Security Adoption Framework
* UK NCSC Cyber Assessment Framework

### Triage and Remediation

<Tabs>
  <Tab title="Remediation">
    ### Remediation

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To remediate “OCI Monitoring Should Have MFA Violation Alarm Configured” using the OCI Console, you generally need to:

        1. Detect MFA violations in Audit logs
        2. Turn those log records into a custom metric
        3. Create a Monitoring alarm on that custom metric
        4. Wire the alarm to a Notification topic (email/Slack/etc.)

        Below are step‑by‑step console instructions.

        ***

        ## 1. Identify the MFA violation condition in Audit logs

        1. In the Console, go to **Observability & Management → Logging → Logs**.
        2. From the left side, select **Audit** as the log group/source (or the tenancy/compartment where Audit logs are enabled).
        3. Click **Search**.
        4. Build a query that identifies logins without MFA. This will vary by tenant, but typically you filter by:

           * `eventType` related to sign-in / authentication, and
           * a field that indicates MFA was not used (e.g., `additionalDetails.mfaUsed = "false"` or similar; inspect a few audit events to see the exact field names).

           Example (pseudo) query:

           ```text theme={null}
           data.eventName = "SignIn" 
           and data.additionalDetails.mfaUsed = "false"
           ```
        5. Run the search and confirm you see events that truly represent “MFA violation” for your environment.

        You must confirm your exact field names by inspecting real Audit log entries in your tenancy. They may differ slightly depending on Identity type (IDCS vs IAM Identity Domains, etc.).

        ***

        ## 2. Create a custom log-based metric for MFA violations

        1. Still in **Logging → Logs → Search**, with your working MFA-violation query loaded, click **Create Metric** (or **Save as Metric**, depending on UI).
        2. Fill in the metric definition:
           * **Metric Namespace**: e.g., `custom_security`
           * **Metric Name**: e.g., `mfa_violation_count`
           * **Resource Group**: optional or as per your standards.
           * **Metric Description**: “Number of sign-in events without MFA”.
           * **Unit**: `count`
           * **Dimension(s)**: You can add useful ones, e.g. `userName`, `region`, `compartmentId`, etc., if present in the log records.
        3. Ensure the **Filter** (query) is the same as the one you verified: it should only match *MFA violation* events.
        4. Save the metric.

        Once created, this metric will increment whenever new log entries match the filter.

        ***

        ## 3. Create an alarm on the custom MFA violation metric

        1. Go to **Observability & Management → Monitoring → Alarms**.
        2. Click **Create alarm**.
        3. Fill in **Alarm details**:
           * **Alarm name**: e.g., `MFA_Violation_Alarm`
           * **Alarm compartment**: your security/monitoring compartment.
        4. Define **Alarm query**:
           * **Metric namespace**: `custom_security` (or the one you defined).
           * **Metric name**: `mfa_violation_count`
           * Choose appropriate dimensions/filters (optional), e.g.:
             ```text theme={null}
             custom_security.mfa_violation_count[1m].sum() > 0
             ```
             This means: if any MFA violations occur (sum > 0) in the last 1 minute, trigger.
           * Adjust interval and window as desired (e.g., `[5m].sum() > 0`).
        5. **Trigger rule**:
           * Set **Severity**: usually `Critical` or `High`.
        6. Under **Notification channels**, select an existing **Topic** or create one (see next step).
        7. Choose **Repeat Notification Duration** (e.g., 60 minutes) if you don’t want continuous alerts for an ongoing violation.
        8. Save the alarm.

        ***

        ## 4. Configure Notifications for the alarm

        If you don’t already have a topic:

        1. Go to **Application Integration → Notifications → Topics**.
        2. Click **Create Topic**:
           * Name: e.g., `security-alerts-topic`
        3. After creating, open the topic and click **Create Subscription**:
           * Type: `Email` (or HTTPS/Slack integration, etc.)
           * Endpoint: your security team’s email or distribution list.
        4. Confirm the subscription via the email sent to that address.

        Return to the alarm configuration (if needed) and ensure this topic is selected under **Notifications**.

        ***

        ## 5. Test the setup

        1. Generate or simulate a login without MFA (in a controlled way) or temporarily adjust the metric filter/threshold so that it will trigger using existing events.
        2. Verify:
           * The **custom metric** shows data points in **Monitoring → Metrics Explorer** with namespace `custom_security`.
           * The **alarm** transitions from `OK` to `FIRING`.
           * A **notification email/message** is received by the configured recipient.

        ***

        You have now remediated the issue by configuring an OCI Monitoring alarm that alerts on MFA violation events, fully via the OCI Console.
      </Accordion>

      <Accordion title="Using CLI">
        Below is a minimal, CLI-focused way to meet the requirement “OCI Monitoring Should Have MFA Violation Alarm Configured” using OCI Monitoring + Alarms. Because IAM/MFA violations are not exposed as a native Monitoring metric, the usual pattern is:

        1. Get/derive an **MFA violation metric** (often via Logs + Service Connector → custom metric).
        2. Create an **alarm** on that metric with Notifications destinations.

        Below assumes:

        * You already have a custom metric like `mfa_violations` in namespace `security`, where value > 0 means an MFA violation.
        * You want an email notification when violations occur.
        * OCI CLI is already configured.

        ***

        ## 1. (If needed) Create a Notifications topic

        ```bash theme={null}
        TOPIC_OCID=$(oci ons topic create \
          --name "mfa-violations-topic" \
          --compartment-id "<COMPARTMENT_OCID>" \
          --description "Notify on MFA violations" \
          --query "data.id" \
          --raw-output)
        ```

        ## 2. (If needed) Create an email subscription

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

        The recipient must confirm the subscription from the email.

        ***

        ## 3. Create the MFA violation alarm via OCI CLI

        Example alarm: triggers if any MFA violations are observed in the last 1 minute, for at least 5 minutes.

        ```bash theme={null}
        oci monitoring alarm create \
          --display-name "MFA Violation Alarm" \
          --compartment-id "<COMPARTMENT_OCID>" \
          --metric-compartment-id "<COMPARTMENT_OCID>" \
          --namespace "security" \
          --query-text "mfa_violations[1m].sum() > 0" \
          --severity "CRITICAL" \
          --destinations "[\"$TOPIC_OCID\"]" \
          --is-enabled true \
          --resolution "1m" \
          --pending-duration "PT5M" \
          --message-format "PRETTY_JSON" \
          --body "Alarm when MFA violations are detected"
        ```

        Key fields to adapt:

        * `--namespace`: your custom metric namespace.
        * `--query-text`: your actual metric name and condition.
        * `--destinations`: one or more ONS topic OCIDs.

        ***

        ## 4. (Optional) Push a test MFA violation metric

        If you want to test the alarm and you’re using a custom metric:

        ```bash theme={null}
        oci monitoring metric-data post \
          --metric-data '[
            {
              "namespace": "security",
              "resourceGroup": "mfa-monitoring",
              "compartmentId": "<COMPARTMENT_OCID>",
              "name": "mfa_violations",
              "datapoints": [
                {
                  "timestamp": "'$(date -u +"%Y-%m-%dT%H:%M:%S.000Z")'",
                  "value": 1
                }
              ],
              "dimensions": {
                "eventType": "MFA_VIOLATION"
              }
            }
          ]'
        ```

        The alarm should fire once the condition `mfa_violations[1m].sum() > 0` is satisfied for the pending duration.

        ***

        If you share how your MFA violations are currently detected (logs, Cloud Guard, custom app), I can give an exact metric expression and any Service Connector steps needed.
      </Accordion>

      <Accordion title="Using Python">
        Below is one practical pattern to meet “MFA violation alarm” requirements in OCI using Python and the Monitoring service.

        Because MFA events are in **Audit logs**, not native metrics, the high‑level flow is:

        1. Get MFA‑related events into a metric (via Service Connector + Logging custom metrics).
        2. Create an **Alarm** in OCI Monitoring on that metric using Python.

        ***

        ## 1. Pre‑requisites

        * `oci` Python SDK installed:
          ```bash theme={null}
          pip install oci
          ```
        * A working OCI config file (`~/.oci/config`) with a profile that has permissions to:
          * Read compartments.
          * Manage alarms in Monitoring.
          * Manage/log metrics if you need to create the custom metric pipeline.

        ***

        ## 2. Set up the metric for MFA violations (one‑time)

        High‑level (usually done via Console, but can be automated via SDK as well):

        1. **Enable Audit logs** for the tenancy (usually already on).
        2. Create a **Service Connector**:
           * Source: `Audit Logs`.
           * Target: `Monitoring / Metrics` (custom metrics) or `Logging Analytics` → metric.
        3. In the Service Connector log filter or transformation, define which audit entries count as an “MFA violation”, for example:
           * `eventType = "com.oraclecloud.identitycontrolplane.authenticateuser"`
           * AND `responseCode = 401` or `errorCode = "MFA_REQUIRED"` / `MFA_FAILED` (use exact values you see in your Audit logs).
        4. Map each matching event to increment a custom metric, e.g.:
           * **Namespace**: `security_mfa`
           * **Metric name**: `mfa_violations`
           * **Dimensions**: `{"userName": "<from audit record>", "region": "<region>"}`

        Once this is in place, you’ll have a metric:

        * `security_mfa.mfa_violations`

        You can verify using the Console → Monitoring → Metrics.

        ***

        ## 3. Alarm design

        Example policy:

        * **Namespace**: `security_mfa`
        * **Query**: average of `mfa_violations` over 5 minutes
        * **Condition**: `> 0`
        * **Alarm**: triggers if at least one MFA violation happens in any 5‑minute window.

        Monitoring query expression:

        ```text theme={null}
        mfa_violations[5m].sum() > 0
        ```

        (or `mfa_violations[5m].rate() > 0` if you configured it as a cumulative counter; adapt to how your metric is defined).

        ***

        ## 4. Python code to create the MFA violation alarm

        Replace the placeholders with your values.

        ```python theme={null}
        import oci
        from oci.monitoring.models import Alarm, CreateAlarmDetails

        # ---------- CONFIG ----------
        # OCI config/profile
        CONFIG_FILE = "~/.oci/config"
        PROFILE = "DEFAULT"

        # Compartment and OCIDs
        COMPARTMENT_ID = "<compartment_ocid_for_alarm>"  # usually root or security compartment

        # Metric namespace
        NAMESPACE = "security_mfa"

        # Alarm details
        ALARM_DISPLAY_NAME = "MFA Violation Alarm"
        ALARM_DESCRIPTION = "Triggers when MFA violations are detected via custom metric."
        ALARM_SEVERITY = "CRITICAL"  # or INFO, WARNING, ERROR
        IS_ENABLED = True

        # Notification topic OCID (ONS)
        TOPIC_ID = "<notification_topic_ocid>"  # create a Notifications topic & subscriptions first

        # Monitoring query: adjust if your metric name or semantics differ
        QUERY = f"{NAMESPACE}.mfa_violations[5m].sum() > 0"

        # ---------- CREATE ALARM ----------
        def create_mfa_alarm():
            config = oci.config.from_file(CONFIG_FILE, PROFILE)
            monitoring_client = oci.monitoring.MonitoringClient(config)

            create_alarm_details = CreateAlarmDetails(
                display_name=ALARM_DISPLAY_NAME,
                compartment_id=COMPARTMENT_ID,
                description=ALARM_DESCRIPTION,
                # The Monitoring query expression
                query=QUERY,
                severity=ALARM_SEVERITY,
                is_enabled=IS_ENABLED,
                # Namespace of the metric
                namespace=NAMESPACE,
                # Notification topic (ONS)
                destinations=[TOPIC_ID],
                # Evaluate every 1 minute, use last 5 minutes of data
                pending_duration="PT0M",          # no extra delay; adjust as needed
                resolution="1m",                  # evaluation period
                repeat_notification_duration="PT1H",  # avoid spamming: once per hour if still firing
                is_notifications_per_metric_dimension_enabled=False
            )

            response = monitoring_client.create_alarm(create_alarm_details)
            print("Alarm created with OCID:", response.data.id)


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

        ***

        ## 5. Testing

        1. Generate a test MFA violation (e.g., failed login requiring MFA, depending on your policy).
        2. Check:
           * Metric `security_mfa.mfa_violations` shows non‑zero values.
           * Alarm moves to `FIRING` state in Monitoring.
           * Notification is delivered to the configured channel (email, Slack, etc.).

        ***

        If you share:

        * The exact format of the MFA violation in your Audit logs, or
        * The metric/namespace you already have for MFA,

        I can provide a more precise query expression and a tailored Python snippet.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        resource "oci_monitoring_alarm" "mfa_requirement_violation" {
          # REQUIRED: replace with your actual OCID of an existing Notifications topic
          destinations = [
            "OCID_OF_OCI_NOTIFICATIONS_TOPIC"
          ]

          # REQUIRED: replace with your compartment OCID where the metric is emitted
          compartment_id = "OCID_OF_COMPARTMENT_FOR_MFA_METRICS"

          display_name = "MFA Requirement Violation Alarm"
          is_enabled   = true
          severity     = "CRITICAL"

          # Adjust to match your tenancy's metric namespace/compartment if different.
          # This example fires when at least 1 MFA requirement violation is recorded
          # during the evaluation window.
          metric_compartment_id = "OCID_OF_COMPARTMENT_FOR_MFA_METRICS"
          namespace             = "identity"

          # Honouring the intent of the check: alarm on any MfaRequirementViolation > 0
          query = "MfaRequirementViolation[1m].sum() > 0"

          # How long the condition must be met before firing
          pending_duration = "PT1M"

          # Optional but recommended configuration
          resolution            = "1m"
          repeat_notification_duration = "PT15M"

          # Optional: narrow the metric to specific dimensions if required, for example:
          # query = "MfaRequirementViolation[1m]{resourceId = \"OCID_OF_IDENTITY_RESOURCE\"}.sum() > 0"

          message_format = "ONS_OPTIMIZED"
          body           = "MFA requirement violation detected. Investigate potential attempts to bypass MFA."

          # OPTIONAL: free-form or defined tags as per your standards
          # freeform_tags = {
          #   "Owner" = "SECURITY_TEAM"
          # }
        }
        ```

        This change only creates (or updates) an `oci_monitoring_alarm` and does not force replacement of other resources. After updating your Terraform, `terraform plan` should show a new `oci_monitoring_alarm.mfa_requirement_violation` resource to be created (or updated with the `query`/destinations shown above) and no unexpected changes elsewhere.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
