# identity-provider-signals / entra / t0 "Quick start"
#
# Four alerts for the moves that turn one stolen Entra ID account into the
# tenant: a directory role granted, credentials or consent given to an app,
# a change to who can sign in or how, and an admin changing a user's MFA
# methods. A fifth alert fires when no sign-ins have arrived for an hour.
#
# A tenant diagnostic setting copies the audit and sign-in logs into a Log
# Analytics workspace, and the alerts query them there. These logs are
# billed by the gigabyte.
#
# Before you start:
#   Microsoft's guide to these logs in Log Analytics lists Microsoft Entra
#   ID P1 or P2 as a prerequisite.
#   Whoever runs apply needs at least the Security Administrator role in
#   Entra ID, and Contributor on the resource group below.
#
# Change the three values below, then:
#   az login
#   terraform init && terraform apply
#
# The first rows can take a while to appear; Microsoft allows up to three
# days. The silence alert fires until they do.
#
# Verify: assign a test user the Reports Reader role, then remove
# it. The role-granted email arrives within about fifteen minutes.

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 AuditLogs exists; Azure disables
  # a rule whose query fails for a week.
  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)), Target = coalesce(tostring(TargetResources[0].userPrincipalName), tostring(TargetResources[0].displayName))"

  # Operation names from Microsoft's audit activity reference, matched
  # case-insensitively.
  detections = {
    role-granted = {
      operations = [
        "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."
    }
    # A secret on an app, or consent to one, is a way back in that survives
    # a password reset.
    app-credentials = {
      operations = [
        "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 = {
      operations = [
        "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."
    }
    # The help desk call that ends with "I lost my phone".
    mfa-changed-by-admin = {
      operations = ["Admin registered security info", "Admin updated security info", "Admin deleted security info"]
      doc        = "An admin added, changed, or removed a user's MFA methods."
    }
  }

  # A query that returns one row when no sign-ins arrived in the last hour.
  silence = "union isfuzzy=true (datatable(TimeGenerated: datetime)[]), (SigninLogs | where TimeGenerated > ago(1h)) | 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" "entra" {
  name                = "law-entra-signals"
  location            = data.azurerm_resource_group.security.location
  resource_group_name = data.azurerm_resource_group.security.name
  sku                 = "PerGB2018"
  retention_in_days   = 90
}

# Tenant-wide: one setting covers every user and app in the directory.
resource "azurerm_monitor_aad_diagnostic_setting" "entra" {
  name                       = "entra-signals"
  log_analytics_workspace_id = azurerm_log_analytics_workspace.entra.id

  enabled_log {
    category = "AuditLogs"
  }

  enabled_log {
    category = "SignInLogs"
  }
}

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

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

# The tables do not exist until the first rows arrive, 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                  = "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} In the workspace, run: AuditLogs | where OperationName in~ (...) | ${local.shown} | project TimeGenerated, OperationName, Actor, Target, Result"
  severity              = 1
  evaluation_frequency  = "PT5M"
  window_duration       = "PT1H"
  skip_query_validation = true

  criteria {
    query                   = "${local.audit} | where OperationName in~ (${join(", ", [for o in each.value.operations : jsonencode(o)])})${each.key == "app-credentials" ? " or OperationName has \"Certificates and secrets management\"" : ""} | ${local.shown}"
    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 an hour. Check the tenant diagnostic setting entra-signals in Entra ID > Monitoring > Diagnostic settings."
  severity              = 2
  evaluation_frequency  = "PT15M"
  window_duration       = "PT1H"
  skip_query_validation = true

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

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

output "verify" {
  description = "The drill."
  value       = <<-EOT
    Assign a test user the Reports Reader role, then remove it.
    The entra-role-granted email arrives within about fifteen minutes.
    Rows are flowing when this returns a recent time:
      az monitor log-analytics query -w ${azurerm_log_analytics_workspace.entra.workspace_id} --analytics-query "SigninLogs | summarize max(TimeGenerated)"
  EOT
}
