# evidence-capture / azure / t0 "Quick start"
#
# Add the tag incident=<id> to a virtual machine, and a function:
#   1. locks it against deletion
#   2. snapshots every managed disk, into a resource group of its own
#   3. moves each of its network interfaces to a security group that allows
#      nothing in or out
#
# The tag is the trigger because anyone on the incident can add one from the
# portal or the command line, and the Activity Log records who did.
#
# Azure has no managed way to capture memory. Snapshot first, then use the
# manual route described on the template page.
#
# Change the two values below, then:
#   az login
#   export ARM_SUBSCRIPTION_ID=$(az account show --query id -o tsv)
#   terraform init && terraform apply
#
# Verify, on a test VM you do not mind isolating:
#   terraform output verify

locals {
  location  = "eastus2"          # change me: where your VMs run; the quarantine group must be in the same region
  responder = "sec-ir-responder" # change me: a name for the function and its group, letters and digits
  tags = {
    owner               = "security-operations"
    environment         = "prod"
    data_classification = "restricted"
    managed_by          = "terraform"
  }
}

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

provider "azurerm" {
  features {}
}

data "azurerm_subscription" "current" {}

resource "random_string" "suffix" {
  length  = 6
  special = false
  upper   = false
}

resource "azurerm_resource_group" "responder" {
  name     = "rg-${local.responder}"
  location = local.location
  tags     = local.tags
}

# Deny everything, in and out, ahead of the default rules that allow traffic
# inside the virtual network and out to the internet. 4096 is the lowest
# priority a custom rule may take, and every custom rule beats every default.
resource "azurerm_network_security_group" "quarantine" {
  name                = "nsg-incident-quarantine-${local.location}"
  location            = azurerm_resource_group.responder.location
  resource_group_name = azurerm_resource_group.responder.name
  tags                = local.tags
}

resource "azurerm_network_security_rule" "quarantine" {
  for_each = {
    in  = "Inbound"
    out = "Outbound"
  }
  name                        = "deny-all-${each.key}"
  network_security_group_name = azurerm_network_security_group.quarantine.name
  resource_group_name         = azurerm_resource_group.responder.name
  priority                    = 4096
  direction                   = each.value
  access                      = "Deny"
  protocol                    = "*"
  source_port_range           = "*"
  destination_port_range      = "*"
  source_address_prefix       = "*"
  destination_address_prefix  = "*"
}

# What the function may do, and nothing more: read a VM and its disks, lock
# it, snapshot into its own group, move its interfaces, and mark it done.
resource "azurerm_role_definition" "responder" {
  name              = "Incident responder function ${random_string.suffix.result}"
  scope             = data.azurerm_subscription.current.id
  assignable_scopes = [data.azurerm_subscription.current.id]
  description       = "Preserves and isolates VMs tagged incident=<id>. Cannot delete, stop, or run commands on them."

  permissions {
    actions = [
      "Microsoft.Compute/virtualMachines/read",
      "Microsoft.Compute/virtualMachines/instanceView/read",
      "Microsoft.Compute/disks/read",
      "Microsoft.Compute/snapshots/read",
      "Microsoft.Compute/snapshots/write",
      "Microsoft.Network/networkInterfaces/read",
      "Microsoft.Network/networkInterfaces/write",
      "Microsoft.Network/networkSecurityGroups/read",
      "Microsoft.Network/networkSecurityGroups/join/action",
      # Writing an interface re-links what it already has, and each link is
      # checked again.
      "Microsoft.Network/virtualNetworks/subnets/join/action",
      "Microsoft.Network/publicIPAddresses/join/action",
      "Microsoft.Network/loadBalancers/backendAddressPools/join/action",
      "Microsoft.Network/applicationSecurityGroups/joinIpConfiguration/action",
      "Microsoft.Authorization/locks/read",
      "Microsoft.Authorization/locks/write",
      "Microsoft.Resources/tags/read",
      "Microsoft.Resources/tags/write",
      "Microsoft.Resources/subscriptions/resourceGroups/read",
    ]
  }
}

locals {
  code = <<-PY
    """Preserve, then isolate, a VM tagged incident=<id>."""
    import json
    import logging
    import os
    import re

    import azure.functions as func
    from azure.identity import DefaultAzureCredential
    from azure.mgmt.compute import ComputeManagementClient
    from azure.mgmt.compute.models import CreationData, Snapshot
    from azure.mgmt.network import NetworkManagementClient
    from azure.mgmt.network.models import NetworkSecurityGroup
    from azure.mgmt.resource.locks import ManagementLockClient
    from azure.mgmt.resource.locks.models import ManagementLockObject
    from azure.mgmt.resource.resources import ResourceManagementClient
    from azure.mgmt.resource.resources.models import Tags, TagsPatchResource

    NSGS = json.loads(os.environ["QUARANTINE_NSG_IDS"])   # region -> security group id
    SNAPSHOT_RG = os.environ["SNAPSHOT_RESOURCE_GROUP"]
    DONE = "preserved-and-isolated"
    # A write on the VM names the VM. A write through the tags API names the
    # VM's tags resource, which sits beneath it.
    VM = re.compile(r"^/subscriptions/([^/]+)/resourceGroups/([^/]+)/providers/Microsoft\.Compute/virtualMachines/([^/]+)(/providers/Microsoft\.Resources/tags/default)?$", re.I)

    app = func.FunctionApp()


    def safe(value, limit=40):
        return re.sub(r"[^A-Za-z0-9_-]", "-", value)[:limit].strip("-") or "incident"


    @app.function_name(name="preserve")
    @app.event_grid_trigger(arg_name="event")
    def preserve(event: func.EventGridEvent):
        m = VM.match(event.get_json().get("resourceUri", ""))
        if not m:
            return
        sub, rg, name = m.group(1), m.group(2), m.group(3)
        cred = DefaultAzureCredential()
        compute = ComputeManagementClient(cred, sub)
        vm = compute.virtual_machines.get(rg, name)
        tags = vm.tags or {}
        incident = tags.get("incident")
        # Marking the VM done changes its tags, which fires this again. Stop there.
        if not incident or tags.get("incident-status") == DONE:
            return
        incident = safe(incident)
        logging.info("incident %s: preserving %s", incident, vm.id)

        # 1. Keep it. Nothing can delete the VM while the lock is on.
        ManagementLockClient(cred, sub).management_locks.create_or_update_by_scope(
            vm.id, f"incident-{incident}", ManagementLockObject(level="CanNotDelete", notes=f"Incident {incident}: evidence"))

        # 2. Snapshot every managed disk. An ephemeral OS disk lives on the
        #    host and cannot be snapshotted, so it is skipped.
        sp = vm.storage_profile
        disks = [d.managed_disk.id for d in (sp.data_disks or []) if d.managed_disk]
        if sp.os_disk.managed_disk and not sp.os_disk.diff_disk_settings:
            disks.insert(0, sp.os_disk.managed_disk.id)
        for i, disk in enumerate(disks, 1):
            compute.snapshots.begin_create_or_update(SNAPSHOT_RG, safe(f"ir-{incident}-{name}-{i}", 80), Snapshot(
                location=vm.location, incremental=True,
                creation_data=CreationData(create_option="Copy", source_resource_id=disk),
                tags={"incident": incident, "source-vm": vm.id, "source-disk": disk.rsplit("/", 1)[-1]})).result()

        # 3. Cut it off: every interface into the quarantine group for its region.
        network = NetworkManagementClient(cred, sub)
        nsg = NSGS[vm.location.lower()]
        for ref in vm.network_profile.network_interfaces:
            nic_rg, nic_name = ref.id.split("/")[4], ref.id.split("/")[-1]
            nic = network.network_interfaces.get(nic_rg, nic_name)
            nic.network_security_group = NetworkSecurityGroup(id=nsg)
            network.network_interfaces.begin_create_or_update(nic_rg, nic_name, nic).result()

        ResourceManagementClient(cred, sub).tags.begin_update_at_scope(
            vm.id, TagsPatchResource(operation="Merge", properties=Tags(tags={"incident-status": DONE}))).result()
        logging.info("incident %s: %s preserved and isolated", incident, vm.id)
  PY
}

data "archive_file" "responder" {
  type        = "zip"
  output_path = "${path.module}/.build/responder.zip"
  source {
    content  = local.code
    filename = "function_app.py"
  }
  source {
    content  = "azure-functions\nazure-identity\nazure-mgmt-compute>=38\nazure-mgmt-network>=33\nazure-mgmt-resource>=26\nazure-mgmt-resource-locks>=1\n"
    filename = "requirements.txt"
  }
  source {
    content  = jsonencode({ version = "2.0", extensionBundle = { id = "Microsoft.Azure.Functions.ExtensionBundle", version = "[4.*, 5.0.0)" } })
    filename = "host.json"
  }
}

# The function's own storage: its deployment package and its runtime state.
resource "azurerm_storage_account" "responder" {
  name                            = "fn${random_string.suffix.result}"
  resource_group_name             = azurerm_resource_group.responder.name
  location                        = azurerm_resource_group.responder.location
  account_tier                    = "Standard"
  account_replication_type        = "LRS"
  min_tls_version                 = "TLS1_2"
  https_traffic_only_enabled      = true
  allow_nested_items_to_be_public = false
  tags                            = local.tags
}

resource "azurerm_storage_container" "deploy" {
  name                  = "deployments"
  storage_account_id    = azurerm_storage_account.responder.id
  container_access_type = "private"
}

resource "azurerm_service_plan" "responder" {
  name                = "plan-${local.responder}"
  resource_group_name = azurerm_resource_group.responder.name
  location            = azurerm_resource_group.responder.location
  os_type             = "Linux"
  sku_name            = "FC1"
  tags                = local.tags
}

resource "azurerm_function_app_flex_consumption" "responder" {
  name                        = "${local.responder}-${random_string.suffix.result}"
  resource_group_name         = azurerm_resource_group.responder.name
  location                    = azurerm_resource_group.responder.location
  service_plan_id             = azurerm_service_plan.responder.id
  storage_container_type      = "blobContainer"
  storage_container_endpoint  = "${azurerm_storage_account.responder.primary_blob_endpoint}${azurerm_storage_container.deploy.name}"
  storage_authentication_type = "StorageAccountConnectionString"
  storage_access_key          = azurerm_storage_account.responder.primary_access_key
  runtime_name                = "python"
  runtime_version             = "3.12"
  maximum_instance_count      = 5
  instance_memory_in_mb       = 2048
  https_only                  = true
  tags                        = local.tags

  identity {
    type = "SystemAssigned"
  }

  site_config {
    minimum_tls_version = "1.2"
  }

  app_settings = {
    QUARANTINE_NSG_IDS      = jsonencode({ (lower(local.location)) = azurerm_network_security_group.quarantine.id })
    SNAPSHOT_RESOURCE_GROUP = azurerm_resource_group.responder.name
  }
}

# Flex Consumption takes code as a package built by the service, which the
# provider cannot send, so the Azure CLI deploys it during apply. A change to
# the code deploys again.
resource "terraform_data" "deploy" {
  triggers_replace = data.archive_file.responder.output_sha256

  provisioner "local-exec" {
    interpreter = ["bash", "-c"]
    environment = {
      GROUP = azurerm_resource_group.responder.name
      APP   = azurerm_function_app_flex_consumption.responder.name
      ZIP   = data.archive_file.responder.output_path
    }
    command = "az functionapp deployment source config-zip -g \"$GROUP\" -n \"$APP\" --src \"$ZIP\" --build-remote true --only-show-errors"
  }

  depends_on = [azurerm_role_assignment.responder]
}

resource "azurerm_role_assignment" "responder" {
  scope              = data.azurerm_subscription.current.id
  role_definition_id = azurerm_role_definition.responder.role_definition_resource_id
  principal_id       = azurerm_function_app_flex_consumption.responder.identity[0].principal_id
  principal_type     = "ServicePrincipal"
}

# Every successful write to a VM in the subscription reaches the function,
# which reads the VM's tags and returns at once when incident is not among
# them. A subscription-wide topic must be Global, and a subscription can have
# one: if yours already has one, use its name here.
resource "azurerm_eventgrid_system_topic" "subscription" {
  name                = "evgt-${local.responder}"
  resource_group_name = azurerm_resource_group.responder.name
  location            = "Global"
  source_resource_id  = data.azurerm_subscription.current.id
  topic_type          = "Microsoft.Resources.Subscriptions"
  tags                = local.tags
}

resource "azurerm_eventgrid_system_topic_event_subscription" "vm_writes" {
  name                 = "vm-writes-to-${local.responder}"
  system_topic         = azurerm_eventgrid_system_topic.subscription.name
  resource_group_name  = azurerm_resource_group.responder.name
  included_event_types = ["Microsoft.Resources.ResourceWriteSuccess"]

  advanced_filter {
    # A tag added on the VM itself, or through the tags API.
    string_in {
      key    = "data.operationName"
      values = ["Microsoft.Compute/virtualMachines/write", "Microsoft.Resources/tags/write"]
    }
    string_contains {
      key    = "data.resourceUri"
      values = ["/providers/Microsoft.Compute/virtualMachines/"]
    }
  }

  azure_function_endpoint {
    function_id = "${azurerm_function_app_flex_consumption.responder.id}/functions/preserve"
  }

  retry_policy {
    max_delivery_attempts = 10
    event_time_to_live    = 60
  }

  # Event Grid fetches the function's key when the subscription is created,
  # so the function must be deployed first.
  depends_on = [terraform_data.deploy]
}

output "verify" {
  description = "Tag a test VM, then confirm the lock, the snapshots, and the quarantine group."
  value       = <<-EOT
    az tag update --resource-id <test vm id> --operation Merge --tags incident=drill-1
    az lock list --resource <test vm id> -o table                                                                  # incident-drill-1, CanNotDelete
    az snapshot list -g ${azurerm_resource_group.responder.name} --query "[?tags.incident=='drill-1'].name" -o tsv
    az network nic show --ids <nic id> --query networkSecurityGroup.id -o tsv                                       # ${azurerm_network_security_group.quarantine.id}
    az vm delete --ids <test vm id> --yes                                                                          # must be refused: the lock
  EOT
}
