# insider-data-theft / azure / t0 "Quick start"
#
# Three alerts for the moves someone makes on the way out with data. The
# first is handing out a storage key or a SAS that works without an
# identity. The second is changing who can use a key vault. The third is
# turning down the logging that would show either.
#
# Everything here reads the subscription's activity log, which Azure writes
# for every change to a resource and does not let anyone turn off. The
# activity log is copied into a Log Analytics workspace, where ingesting it
# costs nothing, and the alerts query it there. Three more alerts read the
# activity log without the workspace.
#
# Change the three values below, then:
#   az login
#   terraform init && terraform apply
#
# Verify: an export can take up to 90 minutes to start, so wait that long
# after the first apply. Then, on a test storage account, open Access keys in
# the portal and show a key, or run az storage account keys list. The email
# follows once the entry reaches the workspace; activity log entries usually
# take three to 20 minutes.

locals {
  subscription_id     = "00000000-0000-0000-0000-000000000000" # change me
  resource_group_name = "rg-security"                          # change me: an existing group for the workspace and alerts
  alert_email         = "security-alerts@example.com"          # change me

  # Each query keeps the rows that arrived in the last five minutes of a
  # one-hour window, so a late row is rarely missed or alerted twice.
  # Operation names are matched case-insensitively, because the activity log
  # mixes cases.
  recent    = "AzureActivity | where ingestion_time() > ago(5m)"
  succeeded = "ActivityStatusValue in~ (\"Success\", \"Succeeded\")"

  # The Key Vault roles that reach keys, secrets, or certificates, or can
  # grant themselves access, by the IDs Azure gives them: Administrator,
  # Crypto Officer, Crypto User, Crypto Service Encryption User, Crypto
  # Service Release User, Secrets Officer, Secrets User, Certificate User,
  # Certificates Officer, Data Access Administrator, and Contributor.
  vault_roles = "\"00482a5a-887f-4fb3-b363-3b7fe8e74483\", \"14b46e9e-c2b7-41b4-b07b-48a6ebf60603\", \"12338af0-0e69-4776-bea7-57ae8d297424\", \"e147488a-f6f5-4113-8e2d-b22465e65bf6\", \"08bbd89e-9f13-488c-ac41-acfcb10c90ab\", \"b86a8fe4-44ce-4948-aee5-eccb2c155cd7\", \"4633458b-17de-408a-b874-0445c86b69e6\", \"db79e9a7-68ee-4b58-9aeb-b90e7c24fcba\", \"a4417e6f-fecd-4de8-b567-7b0420556985\", \"8b54135c-b56d-4d72-a534-26097cfdc8d8\", \"f25e0fa2-a7c8-4377-a976-54943a77a395\""

  detections = {
    # A storage key or an account or service SAS works for whoever has it,
    # with no identity behind it and nothing the account can revoke short of
    # rotating the key.
    keys-or-sas = {
      query = "${local.recent} and ${local.succeeded} | where OperationNameValue in~ (\"Microsoft.Storage/storageAccounts/listKeys/action\", \"Microsoft.Storage/storageAccounts/listAccountSas/action\", \"Microsoft.Storage/storageAccounts/listServiceSas/action\", \"Microsoft.Storage/storageAccounts/regenerateKey/action\")"
      doc   = "Someone fetched a storage account key, made a SAS through Azure Resource Manager, or regenerated a key."
    }
    # A vault's access policy, or a role assignment at a vault or naming one
    # of the Key Vault data roles. A role assignment's request body is on its
    # Start event, which is where Microsoft's own alerting guide reads it.
    decrypt-rights = {
      query = "${local.recent} | extend Body = tostring(todynamic(Properties).requestbody) | where (OperationNameValue in~ (\"Microsoft.KeyVault/vaults/accessPolicies/write\", \"Microsoft.KeyVault/vaults/write\") and ${local.succeeded}) or (OperationNameValue =~ \"Microsoft.Authorization/roleAssignments/write\" and ActivityStatusValue in~ (\"Start\", \"Started\") and (Body has \"/providers/Microsoft.KeyVault/vaults/\" or Body has_any (${local.vault_roles})))"
      doc   = "Someone changed a key vault, its access policies, or who has a role that reaches its keys, secrets, or certificates."
    }
    # Diagnostic settings route logs, workspaces keep them, and alert rules
    # and action groups are what anyone hears.
    logging-weakened = {
      query = "${local.recent} and ${local.succeeded} | where OperationNameValue in~ (\"Microsoft.Insights/diagnosticSettings/delete\", \"Microsoft.Insights/diagnosticSettings/write\", \"Microsoft.OperationalInsights/workspaces/delete\", \"Microsoft.OperationalInsights/workspaces/write\", \"Microsoft.OperationalInsights/workspaces/purge/action\", \"Microsoft.OperationalInsights/workspaces/tables/write\", \"Microsoft.Insights/scheduledQueryRules/delete\", \"Microsoft.Insights/scheduledQueryRules/write\", \"Microsoft.Insights/activityLogAlerts/delete\", \"Microsoft.Insights/activityLogAlerts/write\", \"Microsoft.Insights/actionGroups/delete\", \"Microsoft.Insights/actionGroups/write\", \"Microsoft.AlertsManagement/actionRules/write\", \"Microsoft.Authorization/locks/delete\", \"Microsoft.Resources/subscriptions/resourceGroups/delete\")"
      doc   = "A diagnostic setting, workspace, alert rule, or action group was changed or deleted. Or a workspace was purged, table retention changed, a lock or resource group deleted, or an alert processing rule written."
    }
  }

  # Changes the workspace might never hear of. A deleted or rewritten export
  # stops the record of its own change, and a disabled rule does not run.
  native = {
    diagnostic-setting-deleted = {
      operation = "Microsoft.Insights/diagnosticSettings/delete"
      doc       = "A diagnostic setting was deleted in the subscription, possibly the one that feeds the insider alerts."
    }
    # Policy remediation and other teams' monitoring write diagnostic
    # settings too, so expect some of these.
    diagnostic-setting-written = {
      operation = "Microsoft.Insights/diagnosticSettings/write"
      doc       = "A diagnostic setting was created or changed in the subscription. A rewrite can drop a category or send the logs somewhere else."
    }
    # Azure writes this when a log search rule's query has failed for a week.
    rule-disabled = {
      operation = "Microsoft.Insights/ScheduledQueryRules/disable/action"
      doc       = "Azure disabled a log search alert rule in the subscription because its query kept failing."
    }
  }
}

terraform {
  required_version = ">= 1.6"
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~> 5.0"
    }
  }
}

provider "azurerm" {
  features {}
  subscription_id = local.subscription_id
}

data "azurerm_resource_group" "security" {
  name = local.resource_group_name
}

resource "azurerm_log_analytics_workspace" "insider" {
  name                = "law-insider-data-theft"
  location            = data.azurerm_resource_group.security.location
  resource_group_name = data.azurerm_resource_group.security.name
  sku                 = "PerGB2018"
  retention_in_days   = 365
}

# The subscription's activity log, into the workspace.
resource "azurerm_monitor_diagnostic_setting" "activity" {
  name                       = "insider-data-theft"
  target_resource_id         = "/subscriptions/${local.subscription_id}"
  log_analytics_workspace_id = azurerm_log_analytics_workspace.insider.id

  enabled_log {
    category = "Administrative"
  }

  enabled_log {
    category = "Security"
  }

  enabled_log {
    category = "Policy"
  }
}

resource "azurerm_monitor_action_group" "insider" {
  name                = "insider-data-theft"
  resource_group_name = data.azurerm_resource_group.security.name
  short_name          = "insider"

  email_receiver {
    name          = "security"
    email_address = local.alert_email
  }
}

# Azure evaluates these alerts on the activity log itself, with no workspace
# in between, and they cost nothing. They still notify through the one action
# group, so deleting or disabling it, or deleting the resource group,
# silences every alert here. Standard locks the group against deletes.
resource "azurerm_monitor_activity_log_alert" "native" {
  for_each            = local.native
  name                = "insider-${each.key}"
  resource_group_name = data.azurerm_resource_group.security.name
  location            = "global"
  scopes              = ["/subscriptions/${local.subscription_id}"]
  description         = each.value.doc

  criteria {
    category       = "Administrative"
    operation_name = each.value.operation
  }

  action {
    action_group_id = azurerm_monitor_action_group.insider.id
  }
}

# The first alert, kept under its new address so it is not replaced.
moved {
  from = azurerm_monitor_activity_log_alert.export_deleted
  to   = azurerm_monitor_activity_log_alert.native["diagnostic-setting-deleted"]
}

# The AzureActivity table does not exist until the first event arrives, and a
# rule's query is checked when the rule is made. Skipping that check lets the
# rules exist first. They are made after the export, though an export can
# still take up to 90 minutes to start delivering.
resource "azurerm_monitor_scheduled_query_rules_alert_v2" "detection" {
  for_each              = local.detections
  name                  = "insider-${each.key}"
  resource_group_name   = data.azurerm_resource_group.security.name
  location              = data.azurerm_resource_group.security.location
  scopes                = [azurerm_log_analytics_workspace.insider.id]
  description           = "${each.value.doc} In the workspace, run: ${each.value.query} | project TimeGenerated, Caller, CallerIpAddress, OperationNameValue, _ResourceId"
  severity              = 1
  evaluation_frequency  = "PT5M"
  window_duration       = "PT1H"
  skip_query_validation = true

  criteria {
    query                   = each.value.query
    time_aggregation_method = "Count"
    operator                = "GreaterThan"
    threshold               = 0
  }

  action {
    action_groups = [azurerm_monitor_action_group.insider.id]
  }

  depends_on = [azurerm_monitor_diagnostic_setting.activity]
}
