# breakglass-identity / azure / t0 "Quick start"
#
# Owner on a subscription for an emergency account, and an email every time
# that account signs in, is changed, or does anything in the subscription.
# Three more alerts read the activity log without the workspace, for the
# changes that would quiet the first one.
#
# First, in the Entra admin center, as a Global Administrator:
#   1. Create a cloud-only user, such as breakglass@<tenant>.onmicrosoft.com,
#      so it does not depend on federation or on-premises sync.
#   2. Register a FIDO2 security key for it, and seal the key and password
#      where your runbook says.
#   3. Exclude it from every Conditional Access policy, or from the ones
#      that could lock it out, and record that exclusion.
# Terraform cannot do those steps with this provider, and never sees the
# password.
#
# Change the three values below, then:
#   az login
#   export ARM_SUBSCRIPTION_ID=$(az account show --query id -o tsv)
#   terraform init && terraform apply
#
# Streaming Entra sign-in logs needs Global Administrator or Security
# Administrator for the person running apply.
#
# Verify: an export can take up to 90 minutes to start, so wait that long
# after the first apply. Then sign in as the account. The email follows once
# the sign-in reaches the workspace, usually a few minutes later.

locals {
  break_glass_upn       = "breakglass@example.onmicrosoft.com"   # change me
  break_glass_object_id = "00000000-0000-0000-0000-000000000000" # change me: az ad user show --id <upn> --query id
  alert_email           = "oncall@example.com"                   # change me
  location              = "eastus"
  tags = {
    owner               = "security-engineering"
    environment         = "prod"
    data_classification = "restricted"
    managed_by          = "terraform"
  }

  # Changes the workspace might never hear of. A deleted or rewritten export
  # stops the record of its own change, and a disabled rule does not run.
  native = {
    diagnostic-setting-deleted = {
      operation = "Microsoft.Insights/diagnosticSettings/delete"
      doc       = "A diagnostic setting was deleted in the subscription, possibly the one that feeds the break-glass alert."
    }
    # 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 a category or send the logs 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."
    }
  }
}

terraform {
  required_version = ">= 1.6"
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~> 5.0"
    }
  }
}

provider "azurerm" {
  features {}
}

data "azurerm_subscription" "current" {}

resource "azurerm_role_assignment" "owner" {
  scope                = data.azurerm_subscription.current.id
  role_definition_name = "Owner"
  principal_id         = local.break_glass_object_id
  description          = "Break-glass account. Every use alerts."
}

resource "azurerm_resource_group" "break_glass" {
  name     = "rg-break-glass-monitoring"
  location = local.location
  tags     = local.tags
}

resource "azurerm_log_analytics_workspace" "break_glass" {
  name                = "law-break-glass"
  location            = azurerm_resource_group.break_glass.location
  resource_group_name = azurerm_resource_group.break_glass.name
  sku                 = "PerGB2018"
  retention_in_days   = 365
  tags                = local.tags
}

# Sign-ins and directory changes come from Entra, actions in the
# subscription from its Activity Log. Both land in one workspace.
resource "azurerm_monitor_aad_diagnostic_setting" "entra" {
  name                       = "break-glass-watch"
  log_analytics_workspace_id = azurerm_log_analytics_workspace.break_glass.id
  enabled_log {
    category = "SignInLogs"
  }
  enabled_log {
    category = "AuditLogs"
  }
}

resource "azurerm_monitor_diagnostic_setting" "activity" {
  name                       = "break-glass-watch"
  target_resource_id         = data.azurerm_subscription.current.id
  log_analytics_workspace_id = azurerm_log_analytics_workspace.break_glass.id
  enabled_log {
    category = "Administrative"
  }
}

resource "azurerm_monitor_action_group" "oncall" {
  name                = "break-glass-alerts"
  resource_group_name = azurerm_resource_group.break_glass.name
  short_name          = "breakglass"
  tags                = local.tags
  email_receiver {
    name          = "oncall"
    email_address = local.alert_email
  }
}

# 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 deleting or disabling it, or deleting the resource group,
# silences every alert here. Standard locks the group against deletes. The
# Entra log stream is set at the tenant, outside the subscription's activity
# log, so none of them sees it change.
resource "azurerm_monitor_activity_log_alert" "native" {
  for_each            = local.native
  name                = "break-glass-${each.key}"
  resource_group_name = azurerm_resource_group.break_glass.name
  location            = "global"
  scopes              = [data.azurerm_subscription.current.id]
  description         = each.value.doc
  tags                = local.tags

  criteria {
    category       = "Administrative"
    operation_name = each.value.operation
  }

  action {
    action_group_id = azurerm_monitor_action_group.oncall.id
  }
}

# The tables appear only once data arrives, so the query is not validated
# at creation. The rule is made after the exports, though an export can
# still take up to 90 minutes to start delivering.
resource "azurerm_monitor_scheduled_query_rules_alert_v2" "used" {
  name                = "break-glass-used"
  resource_group_name = azurerm_resource_group.break_glass.name
  location            = azurerm_resource_group.break_glass.location
  scopes              = [azurerm_log_analytics_workspace.break_glass.id]
  description         = "The break-glass account signed in, was changed, or acted in the subscription."
  severity            = 0
  # 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                   = <<-KQL
      let upn = "${local.break_glass_upn}";
      union isfuzzy=true
        (SigninLogs | where ingestion_time() > ago(5m) | where UserPrincipalName =~ upn),
        (AuditLogs | where ingestion_time() > ago(5m) | where tostring(TargetResources) has upn or tostring(InitiatedBy) has upn),
        (AzureActivity | where ingestion_time() > ago(5m) | where Caller =~ upn)
    KQL
    time_aggregation_method = "Count"
    operator                = "GreaterThan"
    threshold               = 0
  }

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

  depends_on = [
    azurerm_monitor_aad_diagnostic_setting.entra,
    azurerm_monitor_diagnostic_setting.activity,
  ]
}
