# insider-data-theft / oci / t0 "Quick start"
#
# Three alarms across the tenancy for the moves someone makes on the way out
# with data. The first is sharing it publicly, by link, or to another
# region. The second is changing who may use what. The third is turning
# down the logging that would show either.
#
# Everything here reads the Audit service, which records every call to an
# Oracle Cloud API in every compartment and keeps it 365 days, a period
# Oracle does not let you change. Alarms read metrics only, so each
# detection is a connector that counts matching audit events into a metric,
# with the caller as a dimension, and an alarm on that metric.
#
# Change the three values below. Credentials come from ~/.oci/config. Then:
#   terraform init && terraform apply
#
# Verify: confirm the subscription email first. Then, on a test bucket,
# create a pre-authenticated request, and delete it. The alarm email arrives
# within a few minutes.

locals {
  tenancy_ocid = "ocid1.tenancy.oc1..aaaaaaaa" # change me
  region       = "us-ashburn-1"                # change me: the home region
  alert_email  = "security-alerts@example.com" # change me

  namespace = "insider_data_theft"

  # The filter language has search, where, equality, and a wildcard inside a
  # value; parentheses are not documented. A detection that needs an "and" is its own
  # connector; several connectors may feed one metric. Audit event names are
  # the API operations' own names.
  connectors = {
    par-created = {
      metric    = "shared_outside"
      condition = "data.eventName='CreatePreauthenticatedRequest'"
    }
    bucket-made-public = {
      metric    = "shared_outside"
      condition = "data.eventName='UpdateBucket' and data.additionalDetails.publicAccessType='ObjectRead*'"
    }
    public-bucket-created = {
      metric    = "shared_outside"
      condition = "data.eventName='CreateBucket' and data.additionalDetails.publicAccessType='ObjectRead*'"
    }
    # Replication copies a bucket to another region, where other policies
    # may apply; a copy request does the same for one object.
    data-copied-out = {
      metric    = "shared_outside"
      condition = "data.eventName='CreateReplicationPolicy' or data.eventName='CopyObject'"
    }
    rights-changed = {
      metric    = "rights_changed"
      condition = join(" or ", [for e in ["CreatePolicy", "UpdatePolicy", "ChangeKeyCompartment", "AddUserToGroup", "CreateDynamicGroup", "UpdateDynamicGroup", "CreateCustomerSecretKey", "CreateAuthToken", "UploadApiKey"] : "data.eventName='${e}'"])
    }
    logging-weakened = {
      metric    = "logging_weakened"
      condition = join(" or ", [for e in ["DeleteLog", "UpdateLog", "DeleteLogGroup", "UpdateLogGroup", "DeleteServiceConnector", "DeactivateServiceConnector", "UpdateServiceConnector", "ChangeServiceConnectorCompartment", "DeleteAlarm", "UpdateAlarm", "CreateAlarmSuppression", "ChangeAlarmCompartment", "DeleteTopic", "UpdateTopic", "ChangeTopicCompartment", "DeleteSubscription", "UpdateSubscription", "DeleteRetentionRule"] : "data.eventName='${e}'"])
    }
  }

  alarms = {
    shared-outside   = { metric = "shared_outside", body = "A bucket was made public, a pre-authenticated request was made, or data was copied or replicated to another region." }
    rights-changed   = { metric = "rights_changed", body = "A policy, group membership, or dynamic group changed, a key moved compartment, or someone made a credential that works outside the console." }
    logging-weakened = { metric = "logging_weakened", body = "A log, log group, connector, alarm, alarm suppression, notification topic or subscription, or bucket retention rule was changed, moved, or deleted." }
  }
}

terraform {
  required_version = ">= 1.6"
  required_providers {
    oci = {
      source  = "oracle/oci"
      version = "~> 9.0"
    }
  }
}

provider "oci" {
  region = local.region
}

resource "oci_ons_notification_topic" "insider" {
  compartment_id = local.tenancy_ocid
  name           = "insider-data-theft"
  description    = "Alarms on sharing, rights, and logging changes"
}

resource "oci_ons_subscription" "email" {
  compartment_id = local.tenancy_ocid
  topic_id       = oci_ons_notification_topic.insider.id
  protocol       = "EMAIL"
  endpoint       = local.alert_email
}

# The connectors write the metrics as themselves, in this namespace only.
resource "oci_identity_policy" "connector" {
  compartment_id = local.tenancy_ocid
  name           = "insider-data-theft-connectors"
  description    = "Lets the insider connectors count audit events into the ${local.namespace} metrics"
  statements = [
    "Allow any-user to use metrics in tenancy where all {request.principal.type='serviceconnector', target.metrics.namespace='${local.namespace}', request.principal.compartment.id='${local.tenancy_ocid}'}",
  ]
}

resource "oci_sch_service_connector" "detection" {
  for_each       = local.connectors
  compartment_id = local.tenancy_ocid
  display_name   = "insider-${each.key}"
  description    = "Counts ${each.key} audit events, from every compartment, into a metric"
  # Set, so a connector switched off by hand shows in the daily drift plan.
  state = "ACTIVE"

  source {
    kind = "logging"
    log_sources {
      compartment_id = local.tenancy_ocid
      log_group_id   = "_Audit_Include_Subcompartment"
    }
  }

  tasks {
    kind      = "logRule"
    condition = each.value.condition
  }

  target {
    kind             = "monitoring"
    compartment_id   = local.tenancy_ocid
    metric_namespace = local.namespace
    metric           = each.value.metric
    dimensions {
      name = "principal"
      dimension_value {
        kind = "jmesPath"
        path = "logContent.data.identity.principalName"
      }
    }
  }

  depends_on = [oci_identity_policy.connector]
}

resource "oci_monitoring_alarm" "detection" {
  for_each              = local.alarms
  compartment_id        = local.tenancy_ocid
  metric_compartment_id = local.tenancy_ocid
  display_name          = "insider-${each.key}"
  namespace             = local.namespace
  query                 = "${each.value.metric}[1m].count() > 0"
  severity              = "CRITICAL"
  is_enabled            = true
  destinations          = [oci_ons_notification_topic.insider.id]
  message_format        = "ONS_OPTIMIZED"
  body                  = "${each.value.body} The caller is in the alarm's dimensions. In Logging Search, search the tenancy's _Audit_Include_Subcompartment for the event names in this alarm's connectors."
}
