# The alerts, on the OfficeActivity table. Exchange admin actions are # recorded under the cmdlet's name, with its parameters in Parameters. locals { expected = jsonencode([for a in var.expected_admins : lower(a)]) # The empty table keeps a query valid before OfficeActivity exists; Azure # disables a rule whose query fails for a week. office = "union isfuzzy=true (datatable(TimeGenerated: datetime, OfficeWorkload: string, Operation: string, Parameters: string, UserId: string, ClientIP: string, OfficeObjectId: string, ResultStatus: string, EventSource: string, Members: dynamic, TeamName: string)[]), OfficeActivity" exchange = "${local.office} | where ingestion_time() > ago(5m) | where OfficeWorkload =~ \"Exchange\"" skip = "where not(tolower(UserId) in (dynamic(${local.expected})))" exchange_detections = { # Forwarding alerts for everyone, admins included, so an attacker who # takes an admin account is still seen forwarding its mail. # Clearing forwarding with Set-Mailbox names the same parameter, so it # alerts too. mail-forwarded = { query = "${local.exchange} | where Operation in~ (\"New-InboxRule\", \"Set-InboxRule\", \"Set-Mailbox\") | where Parameters has_any (\"ForwardTo\", \"RedirectTo\", \"ForwardAsAttachmentTo\", \"ForwardingSmtpAddress\", \"ForwardingAddress\")" doc = "An inbox rule or mailbox setting now forwards or redirects mail." } transport-rule-redirect = { query = "${local.exchange} | where Operation in~ (\"New-TransportRule\", \"Set-TransportRule\") | where Parameters has_any (\"BlindCopyTo\", \"RedirectMessageTo\", \"AddToRecipients\") | ${local.skip}" doc = "A mail flow rule now copies, redirects, or adds recipients to mail." } mailbox-access-granted = { query = "${local.exchange} | where Operation in~ (\"Add-MailboxPermission\", \"Add-RecipientPermission\", \"Add-MailboxFolderPermission\", \"New-ManagementRoleAssignment\") | ${local.skip}" doc = "Someone was given access to another mailbox or its folders, rights to send as it, or a new Exchange management role." } audit-weakened = { query = "${local.exchange} | where Operation in~ (\"Set-AdminAuditLogConfig\", \"Set-MailboxAuditBypassAssociation\") | ${local.skip}" doc = "The tenant's audit log settings changed, or a mailbox was set to skip auditing." } # Teams records added members with their UPN, and a guest's carries #EXT#. guest-added-to-team = { query = "${local.office} | where ingestion_time() > ago(5m) | where OfficeWorkload =~ \"MicrosoftTeams\" and Operation == \"MemberAdded\" and tostring(Members) has \"#EXT#\"" doc = "A guest from outside the tenant was added to a team." } } # Distinct files per user in the last hour. It runs every 15 minutes, so a # download that keeps going alerts again until it stops. bulk_download = "${local.office} | where TimeGenerated > ago(1h) | where Operation in (\"FileDownloaded\", \"FileSyncDownloadedFull\") | summarize Files = dcount(OfficeObjectId), Addresses = make_set(ClientIP, 10) by UserId | where Files > ${var.bulk_download_files}" silence = "union isfuzzy=true (datatable(TimeGenerated: datetime)[]), (OfficeActivity | where TimeGenerated > ago(${var.silence_hours}h)) | summarize Rows = count() | where Rows == 0" rules = merge( { for k, d in local.exchange_detections : k => merge(d, { frequency = "PT5M", window = "PT1H", severity = 1 }) }, { bulk-download = { query = local.bulk_download doc = "One user downloaded or synced more than ${var.bulk_download_files} distinct SharePoint or OneDrive files in an hour." frequency = "PT15M" window = "PT1H" severity = 2 } signals-silent = { query = local.silence doc = "No Microsoft 365 audit records reached the workspace for ${var.silence_hours} hours. Check the Microsoft 365 connector in Sentinel, and that UnifiedAuditLogIngestionEnabled is still True." frequency = "PT1H" window = "P2D" severity = 2 } }, ) } # 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.rules name = "m365-${each.key}" resource_group_name = data.azurerm_resource_group.security.name location = data.azurerm_resource_group.security.location scopes = [azurerm_log_analytics_workspace.m365.id] description = "${each.value.doc} The saved query m365-${each.key} in the workspace shows who, from where, and with what parameters." severity = each.value.severity evaluation_frequency = each.value.frequency window_duration = each.value.window 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.m365.id] } } resource "azurerm_role_assignment" "rule_reads_workspace" { for_each = azurerm_monitor_scheduled_query_rules_alert_v2.detection scope = azurerm_log_analytics_workspace.m365.id role_definition_name = "Log Analytics Reader" principal_id = each.value.identity[0].principal_id principal_type = "ServicePrincipal" }