# secrets-backend / azure / t1 "Standard" # # A Key Vault reachable only from named networks, with readers and officers # named by identity, every operation logged for two years, alerts on refused # access and on changes, and an optional encryption key that rotates itself. # Four native alerts read the subscription's activity log without the # workspace, and locks stop the workspace, the action group, and every alert # being deleted. locals { tags = merge({ owner = var.owner environment = var.environment data_classification = "restricted" managed_by = "terraform" }, var.extra_tags) queries = { refused = { severity = 2 description = "Someone was refused access to the vault. A burst is someone testing what a stolen identity can read." kql = <<-KQL AzureDiagnostics | where ingestion_time() > ago(5m) | where ResourceProvider == "MICROSOFT.KEYVAULT" and ResultSignature == "Forbidden" KQL } changed = { severity = 3 description = "A secret was set, deleted, restored, or purged, or the vault's settings changed." kql = <<-KQL AzureDiagnostics | where ingestion_time() > ago(5m) | where ResourceProvider == "MICROSOFT.KEYVAULT" | where OperationName in ("SecretSet", "SecretDelete", "SecretRestore", "SecretPurge", "VaultPatch", "VaultPut", "VaultDelete") KQL } } # Changes the workspace might never hear of. A deleted or rewritten setting # stops the record of its own change, and a disabled rule does not run. # Deleting a lock is the step before deleting anything it covers. native = { diagnostic-setting-deleted = { operation = "Microsoft.Insights/diagnosticSettings/delete" doc = "A diagnostic setting was deleted in the subscription, possibly the one that records the vault's reads and changes." } # 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 AuditEvent or send the record 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." } lock-deleted = { operation = "Microsoft.Authorization/locks/delete" doc = "A management lock was deleted in the subscription, possibly one that keeps the vault's alerts from being deleted." } } } data "azurerm_client_config" "current" {} resource "random_string" "suffix" { length = 6 special = false upper = false } resource "azurerm_resource_group" "secrets" { name = "rg-${var.name}" location = var.location tags = local.tags } resource "azurerm_key_vault" "secrets" { name = "kv-${var.name}-${random_string.suffix.result}" location = azurerm_resource_group.secrets.location resource_group_name = azurerm_resource_group.secrets.name tenant_id = data.azurerm_client_config.current.tenant_id sku_name = "premium" rbac_authorization_enabled = true purge_protection_enabled = true soft_delete_retention_days = 90 tags = local.tags network_acls { default_action = "Deny" bypass = "AzureServices" ip_rules = var.allowed_ip_ranges } } resource "azurerm_role_assignment" "readers" { for_each = var.readers scope = azurerm_key_vault.secrets.id role_definition_name = "Key Vault Secrets User" principal_id = each.value description = "Reader: ${each.key}" } resource "azurerm_role_assignment" "officers" { for_each = var.officers scope = azurerm_key_vault.secrets.id role_definition_name = "Key Vault Secrets Officer" principal_id = each.value description = "Officer: ${each.key}" } # Creating the key needs whoever runs apply to have Key Vault Crypto Officer # on the vault, so it is granted here. Azure can take a few minutes to honour # a new role; if the key fails with 403 on the first apply, run apply again. resource "azurerm_role_assignment" "apply_crypto_officer" { count = var.encryption_key ? 1 : 0 scope = azurerm_key_vault.secrets.id role_definition_name = "Key Vault Crypto Officer" principal_id = data.azurerm_client_config.current.object_id description = "Whoever runs Terraform, to create and rotate the key." } resource "azurerm_key_vault_key" "rotating" { count = var.encryption_key ? 1 : 0 depends_on = [azurerm_role_assignment.apply_crypto_officer] name = "cmk" key_vault_id = azurerm_key_vault.secrets.id key_type = "RSA-HSM" key_size = 3072 key_opts = ["wrapKey", "unwrapKey"] tags = local.tags rotation_policy { expire_after = "P1Y" notify_before_expiry = "P30D" automatic { time_after_creation = "P90D" } } } # --------------------------------------------------------------------------- # Every operation, kept, with alerts # --------------------------------------------------------------------------- resource "azurerm_log_analytics_workspace" "secrets" { name = "law-${var.name}-${random_string.suffix.result}" location = azurerm_resource_group.secrets.location resource_group_name = azurerm_resource_group.secrets.name sku = "PerGB2018" retention_in_days = var.log_retention_days tags = local.tags } resource "azurerm_monitor_diagnostic_setting" "vault" { name = "audit" target_resource_id = azurerm_key_vault.secrets.id log_analytics_workspace_id = azurerm_log_analytics_workspace.secrets.id log_analytics_destination_type = "AzureDiagnostics" enabled_log { category = "AuditEvent" } } resource "azurerm_monitor_action_group" "security" { name = "${var.name}-alerts" resource_group_name = azurerm_resource_group.secrets.name short_name = "secrets" tags = local.tags # Receiver names are numbered, because names must differ regardless of # case. 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 = "${var.name}-${each.key}" resource_group_name = azurerm_resource_group.secrets.name location = "global" scopes = ["/subscriptions/${var.subscription_id}"] description = each.value.doc tags = local.tags criteria { category = "Administrative" operation_name = each.value.operation } action { action_group_id = azurerm_monitor_action_group.security.id } } # The rules are made after the setting, though a setting can still take up # to 90 minutes to start sending. resource "azurerm_monitor_scheduled_query_rules_alert_v2" "detection" { for_each = local.queries name = "${var.name}-${each.key}" resource_group_name = azurerm_resource_group.secrets.name location = azurerm_resource_group.secrets.location scopes = [azurerm_log_analytics_workspace.secrets.id] description = each.value.description severity = each.value.severity # Look back an hour, keep rows that arrived in the last five minutes: a # late row is neither missed nor alerted twice. evaluation_frequency = "PT5M" window_duration = "PT1H" skip_query_validation = true tags = local.tags criteria { query = each.value.kql time_aggregation_method = "Count" operator = "GreaterThan" threshold = 0 } action { action_groups = [azurerm_monitor_action_group.security.id] } depends_on = [azurerm_monitor_diagnostic_setting.vault] } # The locks go on the alert path alone: the workspace, the action group, and # every alert. A lock on the vault or its resource group would also stop its # role assignments being deleted, and taking a reader away must stay one # line. Any locked resource still stops the resource group being deleted. # Deleting a lock first fires the lock-deleted alert. A cannot-delete lock # does not stop a workspace purge, or an edit such as disabling the action # group. # # The locks are made last and removed first, so terraform destroy can run. # Any change that replaces or removes a locked resource fails while its lock # is on. resource "azurerm_management_lock" "alert_path" { for_each = merge( { workspace = azurerm_log_analytics_workspace.secrets.id action-group = azurerm_monitor_action_group.security.id }, { for k, r in azurerm_monitor_scheduled_query_rules_alert_v2.detection : "rule-${k}" => r.id }, { for k, a in azurerm_monitor_activity_log_alert.native : "native-${k}" => a.id }, ) name = "secrets-backend" scope = each.value lock_level = "CanNotDelete" notes = "Keeps the vault's record and its alerts from being deleted. Managed by Terraform." }