# The alerts. Operation names come from Microsoft's audit activity reference # and are matched case-insensitively. locals { # Each audit query reads the rows that arrived in the last five minutes, out # of a one-hour window, so a late row is rarely missed or alerted twice. The # empty table keeps a query valid before AuditLogs exists; Azure disables a # rule whose query fails for a week. expected = jsonencode([for a in var.expected_actors : lower(a)]) audit = "union isfuzzy=true (datatable(TimeGenerated: datetime, OperationName: string, InitiatedBy: dynamic, TargetResources: dynamic, Result: string)[]), AuditLogs | where ingestion_time() > ago(5m)" shown = "extend Actor = coalesce(tostring(InitiatedBy.user.userPrincipalName), tostring(InitiatedBy.app.displayName)), ActorAppId = tostring(InitiatedBy.app.appId), Target = coalesce(tostring(TargetResources[0].userPrincipalName), tostring(TargetResources[0].displayName))" skip = "where not(tolower(Actor) in (dynamic(${local.expected}))) and not(tolower(ActorAppId) in (dynamic(${local.expected})))" operations = { role-granted = { list = [ "Add member to role", "Add eligible member to role", "Add member to role outside of PIM (permanent)", "Add member to role in PIM completed (permanent)", "Add member to role in PIM completed (timebound)", "Add eligible member to role in PIM completed (permanent)", "Add eligible member to role in PIM completed (timebound)", "Add member to role scoped over Restricted Management Administrative Unit", ] doc = "Someone was given a directory role, or made eligible for one." } # Microsoft's own Sentinel rules match the app secret operation by # substring, so this one does too. app-credentials = { list = [ "Add service principal credentials", "Update application - Certificates and secrets management", "Consent to application", "Add delegated permission grant", "Add app role assignment to service principal", ] doc = "An app or service principal was given a secret or certificate, or was granted consent or permissions." } sign-in-changed = { list = [ "Add Conditional Access policy", "Update Conditional Access policy", "Delete Conditional Access policy", "Add named location", "Update named location", "Delete named location", "Update security defaults", "Set domain authentication", "Set federation settings on domain", "Update authorization policy", "Add a partner to cross-tenant access setting", "Update a partner cross-tenant access setting", "Update the company default cross-tenant access setting", ] doc = "A Conditional Access policy, named location, domain federation, authorization policy, or cross-tenant setting changed." } mfa-changed-by-admin = { list = ["Admin registered security info", "Admin updated security info", "Admin deleted security info"] doc = "An admin added, changed, or removed a user's MFA methods." } } audit_detections = { for k, o in local.operations : k => { query = "${local.audit} | where OperationName in~ (${join(", ", [for x in o.list : jsonencode(x)])})${k == "app-credentials" ? " or OperationName has \"Certificates and secrets management\"" : ""} | ${local.shown} | ${local.skip}" doc = o.doc } } sign_ins = "union isfuzzy=true (datatable(TimeGenerated: datetime, UserId: string, UserPrincipalName: string, IPAddress: string, ResultType: string, AppDisplayName: string, RiskLevelDuringSignIn: string)[]), SigninLogs, AADNonInteractiveUserSignInLogs | where ingestion_time() > ago(5m)" sign_in_detections = merge( length(var.break_glass_object_ids) == 0 ? {} : { break-glass-sign-in = { query = "${local.sign_ins} | where tolower(UserId) in (${join(", ", [for id in var.break_glass_object_ids : jsonencode(lower(id))])})" doc = "An emergency access account signed in or tried to." } }, var.risky_sign_in_alerts ? { risky-sign-in = { query = "${local.sign_ins} | where RiskLevelDuringSignIn =~ \"high\"" doc = "Entra ID rated a sign-in high risk." } } : {}, ) detections = merge(local.audit_detections, local.sign_in_detections) # One row when no interactive sign-ins arrived in the silence window. silence = "union isfuzzy=true (datatable(TimeGenerated: datetime)[]), (SigninLogs | where TimeGenerated > ago(${var.silence_minutes}m)) | summarize Rows = count() | where Rows == 0" } # 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. resource "azurerm_monitor_scheduled_query_rules_alert_v2" "detection" { for_each = local.detections name = "entra-${each.key}" resource_group_name = data.azurerm_resource_group.security.name location = data.azurerm_resource_group.security.location scopes = [azurerm_log_analytics_workspace.entra.id] description = "${each.value.doc} The saved query entra-${each.key} in the workspace shows who, on what, and from where." 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.entra.id] } } resource "azurerm_monitor_scheduled_query_rules_alert_v2" "silence" { name = "entra-signals-silent" resource_group_name = data.azurerm_resource_group.security.name location = data.azurerm_resource_group.security.location scopes = [azurerm_log_analytics_workspace.entra.id] description = "No Entra ID sign-ins reached the workspace for ${var.silence_minutes} minutes. Check the tenant diagnostic setting entra-signals in Entra ID > Monitoring > Diagnostic settings." severity = 2 evaluation_frequency = "PT15M" window_duration = "P1D" skip_query_validation = true tags = local.tags identity { type = "SystemAssigned" } criteria { query = local.silence time_aggregation_method = "Count" operator = "GreaterThan" threshold = 0 } action { action_groups = [azurerm_monitor_action_group.entra.id] } } resource "azurerm_role_assignment" "rule_reads_workspace" { for_each = merge(azurerm_monitor_scheduled_query_rules_alert_v2.detection, { silence = azurerm_monitor_scheduled_query_rules_alert_v2.silence }) scope = azurerm_log_analytics_workspace.entra.id role_definition_name = "Log Analytics Reader" principal_id = each.value.identity[0].principal_id principal_type = "ServicePrincipal" }