# insider-data-theft / gcp / t0 "Quick start"
#
# Three alerts across the organisation for the moves someone makes on the way
# out with data: making it public, changing who can use an encryption key,
# and turning down the logging that would show either.
#
# Everything here reads Admin Activity audit logs, which Google Cloud writes
# for every project and does not let anyone turn off.
#
# Change the three values below, then:
#   gcloud auth application-default login
#   terraform init && terraform apply
#
# Verify: in a test project, grant allUsers the Storage Object Viewer role on
# a test bucket, then remove it. The alert email arrives within minutes.

locals {
  org_id           = "123456789012"                # change me: gcloud organizations list
  security_project = "your-security-project"       # change me: where the alerts live
  alert_email      = "security-alerts@example.com" # change me

  public = "(\"allUsers\" OR \"allAuthenticatedUsers\")"

  detections = {
    # A grant to everyone. Most services record IAM changes in
    # serviceData.policyDelta; BigQuery records dataset access changes in
    # metadata.datasetChange.
    shared-publicly = {
      filter = "protoPayload.serviceData.policyDelta.bindingDeltas.member=${local.public} OR protoPayload.metadata.datasetChange.bindingDeltas.member=${local.public}"
      doc    = "Something was shared with allUsers or allAuthenticatedUsers."
    }
    decrypt-rights = {
      filter = "protoPayload.serviceName=\"cloudkms.googleapis.com\" AND protoPayload.methodName=\"SetIamPolicy\""
      doc    = "Someone changed who can use a Cloud KMS key or key ring."
    }
    # Sinks and buckets route and keep logs, and an exclusion drops them before
    # they are stored. Removing a Data Access audit setting stops the record at
    # the source.
    logging-weakened = {
      filter = join(" OR ", [
        "protoPayload.methodName=(\"google.logging.v2.ConfigServiceV2.DeleteSink\" OR \"google.logging.v2.ConfigServiceV2.UpdateSink\")",
        "protoPayload.methodName=(\"google.logging.v2.ConfigServiceV2.DeleteBucket\" OR \"google.logging.v2.ConfigServiceV2.UpdateBucket\")",
        "protoPayload.methodName=(\"google.logging.v2.ConfigServiceV2.CreateExclusion\" OR \"google.logging.v2.ConfigServiceV2.UpdateExclusion\")",
        "protoPayload.serviceData.policyDelta.auditConfigDeltas.action=\"REMOVE\"",
      ])
      doc = "A log sink, log bucket, or exclusion changed, or a Data Access audit setting was removed."
    }
  }
}

terraform {
  required_version = ">= 1.6"
  required_providers {
    google = {
      source  = "hashicorp/google"
      version = "~> 8.0"
    }
  }
}

provider "google" {
  project = local.security_project
}

# Log-based metrics only see their own project's logs, so an organisation sink
# copies the matching entries from every project into one bucket first.
resource "google_logging_project_bucket_config" "insider" {
  project        = local.security_project
  location       = "global"
  bucket_id      = "insider-data-theft"
  retention_days = 400
}

resource "google_logging_organization_sink" "insider" {
  org_id           = local.org_id
  name             = "insider-data-theft"
  destination      = "logging.googleapis.com/${google_logging_project_bucket_config.insider.id}"
  filter           = join(" OR ", [for d in local.detections : "(${d.filter})"])
  include_children = true
}

resource "google_project_iam_member" "sink_writes" {
  project = local.security_project
  role    = "roles/logging.bucketWriter"
  member  = google_logging_organization_sink.insider.writer_identity
}

resource "google_logging_metric" "detection" {
  for_each    = local.detections
  project     = local.security_project
  name        = "insider-${each.key}"
  bucket_name = google_logging_project_bucket_config.insider.id
  filter      = each.value.filter
  metric_descriptor {
    metric_kind = "DELTA"
    value_type  = "INT64"
  }
}

resource "google_monitoring_notification_channel" "email" {
  project      = local.security_project
  display_name = "Insider data theft alerts"
  type         = "email"
  labels = {
    email_address = local.alert_email
  }
}

resource "google_monitoring_alert_policy" "detection" {
  for_each              = local.detections
  project               = local.security_project
  display_name          = "Insider: ${each.key}"
  combiner              = "OR"
  notification_channels = [google_monitoring_notification_channel.email.id]
  conditions {
    display_name = each.value.doc
    condition_threshold {
      filter          = "metric.type=\"logging.googleapis.com/user/${google_logging_metric.detection[each.key].name}\""
      comparison      = "COMPARISON_GT"
      threshold_value = 0
      duration        = "0s"
      aggregations {
        alignment_period     = "60s"
        per_series_aligner   = "ALIGN_SUM"
        cross_series_reducer = "REDUCE_SUM"
      }
    }
  }
  documentation {
    content = "${each.value.doc} Open the insider-data-theft log bucket in ${local.security_project} to see who, what, and where."
  }
}
