# insider-data-theft / azure / t1 "Standard" # # The quick start's three alerts and three native alerts, with named # callers left out, each rule reading under its own identity, and the # workspace kept for your own period. A fourth native alert reports a rule's # read access removed, and a lock stops anything in the security group being # deleted. reads.tf records blob reads on the accounts you name and alerts on # bulk downloads. queries.tf saves the queries behind every alert. locals { tags = merge({ owner = var.owner environment = var.environment data_classification = "confidential" managed_by = "terraform" }, var.extra_tags) # 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. expected = jsonencode([for c in var.expected_callers : lower(c)]) recent = "AzureActivity | where ingestion_time() > ago(5m) | where not(tolower(Caller) in (dynamic(${local.expected}))) and not(tolower(tostring(Claims_d.appid)) in (dynamic(${local.expected})))" 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. keys-or-sas = { query = "${local.recent} | where ${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 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." } # Deleting the lock is the step before deleting anything in the security # group. logging-weakened = { query = "${local.recent} | where ${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, a rule without its read access reads # nothing, 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." } # Only the rules' own assignments, named in the alert below. rule-access-removed = { operation = "Microsoft.Authorization/roleAssignments/delete" doc = "A role assignment that lets an insider alert rule read the workspace was deleted. That rule now reads nothing, and Azure disables it after a week." } } } data "azurerm_resource_group" "security" { name = var.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 = var.retention_days # No daily cap. A cap drops events once it is reached, with no alert. daily_quota_gb = -1 tags = local.tags } # The subscription's activity log, into the workspace. Ingesting it costs # nothing. resource "azurerm_monitor_diagnostic_setting" "activity" { name = "insider-data-theft" target_resource_id = "/subscriptions/${var.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" tags = local.tags # Receiver names are numbered, because names must differ regardless of # case and two addresses can reduce to the same name. dynamic "email_receiver" { for_each = var.alert_emails content { name = "email-${email_receiver.key}" email_address = email_receiver.value } } } # 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 someone who can edit it can disable it or change its addresses. 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/${var.subscription_id}"] tags = local.tags description = each.value.doc # Microsoft records a role assignment in the activity log under its full # ID, scope included, which is what resource_ids matches. The verify output # shows how to test it. criteria { category = "Administrative" operation_name = each.value.operation resource_ids = each.key == "rule-access-removed" ? concat([for r in azurerm_role_assignment.rule_reads_workspace : r.id], azurerm_role_assignment.bulk_read_reads_workspace[*].id) : null } 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"] } # Each rule reads the workspace as itself. Without an identity a rule reads # as whoever last saved it, and stops when that person's access does. The # rules 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} The saved query insider-${each.key} in the workspace shows who, from where, and on what." severity = 1 evaluation_frequency = "PT5M" window_duration = "PT1H" skip_query_validation = true tags = local.tags identity { type = "SystemAssigned" } 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] } resource "azurerm_role_assignment" "rule_reads_workspace" { for_each = azurerm_monitor_scheduled_query_rules_alert_v2.detection scope = azurerm_log_analytics_workspace.insider.id role_definition_name = "Log Analytics Reader" principal_id = each.value.identity[0].principal_id principal_type = "ServicePrincipal" } # Nothing in the security group can be deleted while this lock is on: the # workspace and its saved queries, the action group, the alerts, and the # rules' role assignments. Deleting the lock first is watched by # logging-weakened. A cannot-delete lock does not stop a workspace purge, # which is watched too, or an edit such as disabling the action group. # # The lock is made last and removed first, so terraform destroy can run. # Any change that replaces or removes a resource in the group fails while # it is on. resource "azurerm_management_lock" "security" { name = "insider-data-theft" scope = data.azurerm_resource_group.security.id lock_level = "CanNotDelete" notes = "Keeps the insider alerts and their record from being deleted. Managed by Terraform." depends_on = [ azurerm_log_analytics_workspace.insider, azurerm_log_analytics_saved_search.insider, azurerm_monitor_action_group.insider, azurerm_monitor_activity_log_alert.native, azurerm_monitor_scheduled_query_rules_alert_v2.detection, azurerm_monitor_scheduled_query_rules_alert_v2.bulk_read, azurerm_role_assignment.rule_reads_workspace, azurerm_role_assignment.bulk_read_reads_workspace, ] }