# identity-provider-signals / m365 / t0 "Quick start"
#
# Four alerts for what an attacker does inside a Microsoft 365 mailbox after
# taking an account: forward its mail out, add a transport rule that copies
# or redirects mail, give someone else access to a mailbox, and turn down
# the audit log that would show any of it. A fifth alert fires when no
# Microsoft 365 records have arrived for 12 hours.
#
# Microsoft Sentinel's Microsoft 365 connector copies the unified audit log
# for Exchange, SharePoint, OneDrive, and Teams into the OfficeActivity table
# of a Log Analytics workspace. Turning on Sentinel puts every table in that
# workspace under Sentinel billing, so this one gets its own workspace.
#
# Before you start:
#   Auditing must be on in the tenant. In Exchange Online PowerShell,
#   Get-AdminAuditLogConfig | Format-List UnifiedAuditLogIngestionEnabled
#   should read True.
#   Whoever runs apply needs Global Administrator or Security Administrator
#   in the tenant, and read, write, and delete on the workspace.
#
# Change the three values below, then:
#   az login
#   terraform init && terraform apply
#
# Verify: in Outlook on the web, on a test mailbox, add an inbox rule that
# forwards to an outside address, then delete it. The mail-forwarded email
# follows once the record reaches the workspace.

locals {
  subscription_id     = "00000000-0000-0000-0000-000000000000" # change me: where the workspace goes
  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 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 OfficeActivity exists; Azure
  # disables a rule whose query fails for a week. Exchange admin actions are
  # recorded under the cmdlet's name, with its parameters in Parameters.
  exchange = "union isfuzzy=true (datatable(TimeGenerated: datetime, OfficeWorkload: string, Operation: string, Parameters: string, UserId: string, ClientIP: string, OfficeObjectId: string, ResultStatus: string)[]), OfficeActivity | where ingestion_time() > ago(5m) | where OfficeWorkload =~ \"Exchange\""

  detections = {
    # 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\")"
      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\")"
      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\")"
      doc   = "The tenant's audit log settings changed, or a mailbox was set to skip auditing."
    }
  }

  silence = "union isfuzzy=true (datatable(TimeGenerated: datetime)[]), (OfficeActivity | where TimeGenerated > ago(12h)) | summarize Rows = count() | where Rows == 0"
}

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" "m365" {
  name                = "law-m365-signals"
  location            = data.azurerm_resource_group.security.location
  resource_group_name = data.azurerm_resource_group.security.name
  sku                 = "PerGB2018"
  retention_in_days   = 90
}

resource "azurerm_sentinel_log_analytics_workspace_onboarding" "m365" {
  workspace_id = azurerm_log_analytics_workspace.m365.id
}

resource "azurerm_sentinel_data_connector_office_365" "m365" {
  name                       = "m365-audit"
  log_analytics_workspace_id = azurerm_sentinel_log_analytics_workspace_onboarding.m365.workspace_id
  exchange_enabled           = true
  sharepoint_enabled         = true
  teams_enabled              = true
}

resource "azurerm_monitor_action_group" "m365" {
  name                = "m365-signals"
  resource_group_name = data.azurerm_resource_group.security.name
  short_name          = "m365"

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

# OfficeActivity does not exist until the first record arrives, and a rule's
# query is checked when the rule is made. Skipping that check lets the rules
# exist first.
resource "azurerm_monitor_scheduled_query_rules_alert_v2" "detection" {
  for_each              = local.detections
  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} In the workspace, run the alert's query with ago(5m) widened, and read UserId, ClientIP, Operation, and Parameters."
  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.m365.id]
  }
}

resource "azurerm_monitor_scheduled_query_rules_alert_v2" "silence" {
  name                  = "m365-signals-silent"
  resource_group_name   = data.azurerm_resource_group.security.name
  location              = data.azurerm_resource_group.security.location
  scopes                = [azurerm_log_analytics_workspace.m365.id]
  description           = "No Microsoft 365 audit records reached the workspace for 12 hours. Check the Microsoft 365 connector in Sentinel, and that UnifiedAuditLogIngestionEnabled is still True."
  severity              = 2
  evaluation_frequency  = "PT1H"
  window_duration       = "P1D"
  skip_query_validation = true

  criteria {
    query                   = local.silence
    time_aggregation_method = "Count"
    operator                = "GreaterThan"
    threshold               = 0
  }

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

output "verify" {
  description = "The drill."
  value       = <<-EOT
    In Outlook on the web, on a test mailbox, add an inbox rule that forwards to an outside address, then delete it.
    The m365-mail-forwarded email follows once the record reaches the workspace.
    Records are flowing when this returns a recent time:
      az monitor log-analytics query -w ${azurerm_log_analytics_workspace.m365.workspace_id} --analytics-query "OfficeActivity | summarize max(TimeGenerated) by OfficeWorkload"
  EOT
}
