# container-evidence / azure / t0 "Quick start"
#
# What a responder needs to preserve a compromised container on AKS: a blob
# container for the evidence that nobody can change or delete from for a day,
# the right to read a node and snapshot its disks and nothing more on the
# Azure side, and the commands to run, in order, printed with your names
# filled in.
#
# Kubernetes rights come from the incident-responder role in the Kubernetes
# evidence template (outcomes/evidence-capture/kubernetes). Apply it to the
# cluster. The cluster must use Microsoft Entra ID integration, and the
# binding's subject is your responder group's object ID:
#   subjects:
#     - apiGroup: rbac.authorization.k8s.io
#       kind: Group
#       name: <the same object ID as below>
#
# Change the three values below, then:
#   az login
#   export ARM_SUBSCRIPTION_ID=$(az account show --query id -o tsv)
#   terraform init && terraform apply
#   terraform output capture
#
# Verify: run the printed commands against a test pod. The pod's record,
# logs, and hashes land in the container, and the node's disks have snapshots
# tagged with the incident. As someone who can delete blobs, such as Storage
# Blob Data Owner, try to delete one: the immutability policy refuses it.

locals {
  cluster_name              = "your-cluster"                         # change me
  cluster_resource_group    = "your-cluster-rg"                      # change me: the cluster's own group; its MC_ node group is looked up
  responder_group_object_id = "00000000-0000-0000-0000-000000000000" # change me: a Microsoft Entra group
  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"
    }
    random = {
      source  = "hashicorp/random"
      version = "~> 3.6"
    }
  }
}

provider "azurerm" {
  features {}
  # Shared keys are off on the storage account, so the provider uses Entra ID.
  storage_use_azuread = true
}

data "azurerm_kubernetes_cluster" "this" {
  name                = local.cluster_name
  resource_group_name = local.cluster_resource_group
}

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

# Snapshots are created in this group, outside the cluster's node resource
# group. Deleting the cluster deletes its node group and anything in it, and
# AKS does not support changes made there. A snapshot must be in the same
# region as its disk, so the group follows the cluster.
resource "azurerm_resource_group" "evidence" {
  name     = "rg-container-evidence-${random_string.suffix.result}"
  location = data.azurerm_kubernetes_cluster.this.location
  tags     = local.tags
}

resource "azurerm_storage_account" "evidence" {
  name                            = "ctrevidence${random_string.suffix.result}"
  resource_group_name             = azurerm_resource_group.evidence.name
  location                        = azurerm_resource_group.evidence.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
  shared_access_key_enabled       = false
  tags                            = local.tags
}

resource "azurerm_storage_container" "evidence" {
  name                  = "evidence"
  storage_account_id    = azurerm_storage_account.evidence.id
  container_access_type = "private"
}

# One day, unlocked, so you can try this and clean it up tomorrow. The
# Standard version defaults to a year and can lock it. Appends stay off:
# evidence is written once.
resource "azurerm_storage_container_immutability_policy" "evidence" {
  storage_container_resource_manager_id = azurerm_storage_container.evidence.id
  immutability_period_in_days           = 1
}

# Read a node and its disks, in the cluster's node resource group. Nothing
# here can change, stop, or delete them.
resource "azurerm_role_definition" "node_reader" {
  name              = "Container evidence node reader ${random_string.suffix.result}"
  scope             = data.azurerm_kubernetes_cluster.this.node_resource_group_id
  assignable_scopes = [data.azurerm_kubernetes_cluster.this.node_resource_group_id]
  description       = "Reads AKS node VMs and their disks, so their disks can be snapshotted elsewhere."

  permissions {
    actions = [
      "Microsoft.Compute/virtualMachineScaleSets/read",
      "Microsoft.Compute/virtualMachineScaleSets/virtualMachines/read",
      "Microsoft.Compute/virtualMachines/read",
      "Microsoft.Compute/disks/read",
      "Microsoft.Compute/disks/beginGetAccess/action",
    ]
  }
}

# In the evidence group: create snapshots and add blobs. No read of blobs, no
# delete of anything.
resource "azurerm_role_definition" "responder" {
  name              = "Container evidence responder ${random_string.suffix.result}"
  scope             = azurerm_resource_group.evidence.id
  assignable_scopes = [azurerm_resource_group.evidence.id]
  description       = "Creates snapshots and adds evidence blobs. Cannot read, change, or delete evidence."

  permissions {
    actions = [
      "Microsoft.Resources/subscriptions/resourceGroups/read",
      "Microsoft.Compute/snapshots/read",
      "Microsoft.Compute/snapshots/write",
    ]
    data_actions = [
      "Microsoft.Storage/storageAccounts/blobServices/containers/blobs/write",
      "Microsoft.Storage/storageAccounts/blobServices/containers/blobs/add/action",
    ]
  }
}

resource "azurerm_role_assignment" "node_reader" {
  scope              = data.azurerm_kubernetes_cluster.this.node_resource_group_id
  role_definition_id = azurerm_role_definition.node_reader.role_definition_resource_id
  principal_id       = local.responder_group_object_id
  principal_type     = "Group"
}

resource "azurerm_role_assignment" "responder" {
  scope              = azurerm_resource_group.evidence.id
  role_definition_id = azurerm_role_definition.responder.role_definition_resource_id
  principal_id       = local.responder_group_object_id
  principal_type     = "Group"
}

# Enough to fetch a kubeconfig. What responders may do inside the cluster is
# set by the incident-responder role.
resource "azurerm_role_assignment" "cluster_user" {
  scope                = data.azurerm_kubernetes_cluster.this.id
  role_definition_name = "Azure Kubernetes Service Cluster User Role"
  principal_id         = local.responder_group_object_id
  principal_type       = "Group"
}

output "capture" {
  description = "The commands, in order. Set ID, NS, and POD first."
  value       = <<-EOT
    ID=inc-001 NS=<namespace> POD=<pod>
    az aks get-credentials -g ${local.cluster_resource_group} -n ${local.cluster_name} --file "$PWD/$ID.kubeconfig" && export KUBECONFIG="$PWD/$ID.kubeconfig"
    kubelogin convert-kubeconfig -l azurecli   # use your az login session
    NODE=$(kubectl get pod -n "$NS" "$POD" -o jsonpath='{.spec.nodeName}')
    mkdir -p "$ID" && cd "$ID"

    # 1. Keep the node. The cluster autoscaler and node auto-provisioning skip
    #    it, and nothing new lands on it. Do not cut the node off the network:
    #    a node that stops reporting for about 10 minutes is rebooted, then reimaged.
    kubectl annotate node "$NODE" cluster-autoscaler.kubernetes.io/scale-down-disabled=true karpenter.sh/do-not-disrupt=true
    kubectl annotate pod -n "$NS" "$POD" karpenter.sh/do-not-disrupt=true
    kubectl cordon "$NODE"

    # 2. Record the pod, its images by digest, its logs, and its node.
    kubectl get pod -n "$NS" "$POD" -o json > pod.json
    kubectl logs -n "$NS" "$POD" --all-containers --timestamps > logs.txt
    kubectl logs -n "$NS" "$POD" --all-containers --timestamps --previous > logs-previous.txt || true
    kubectl get events -n "$NS" --field-selector involvedObject.name="$POD" -o json > events.json
    kubectl get node "$NODE" -o json > node.json

    # 3. Snapshot the node's managed disks, persistent volumes included. An
    #    ephemeral OS disk lives on the host and cannot be snapshotted, so it
    #    is skipped. A snapshot is fixed when you ask for it.
    VM=$(kubectl get node "$NODE" -o jsonpath='{.spec.providerID}'); VM=$${VM#azure://}
    az resource show --ids "$VM" --api-version 2024-07-01 --query properties.storageProfile > storage-profile.json
    Q="[properties.storageProfile.osDisk.managedDisk.id, properties.storageProfile.dataDisks[].managedDisk.id][]"
    [ "$(az resource show --ids "$VM" --api-version 2024-07-01 --query properties.storageProfile.osDisk.diffDiskSettings.option -o tsv)" = "Local" ] && { echo "OS disk is ephemeral: not snapshotted"; Q="properties.storageProfile.dataDisks[].managedDisk.id"; }
    n=0; for disk in $(az resource show --ids "$VM" --api-version 2024-07-01 --query "$Q" -o tsv); do
      n=$((n+1)); az snapshot create -g ${azurerm_resource_group.evidence.name} -n "ir-$ID-$(date -u +%Y%m%d%H%M%S)-$n" --source "$disk" --incremental true --tags incident="$ID" source-disk="$${disk##*/}"
    done

    # 4. Cut it off. The quarantine network policy from the Kubernetes evidence template matches this label.
    kubectl label pod -n "$NS" "$POD" quarantine=true incident="$ID" --overwrite

    # 5. Hash every file, then store them with their hashes.
    for f in *; do sha256sum "$f" > "$f.sha256"; done
    DEST="$ID/$NS/$POD/$(date -u +%Y%m%dT%H%M%SZ)"
    for f in *; do az storage blob upload --auth-mode login --account-name ${azurerm_storage_account.evidence.name} -c evidence -n "$DEST/$f" -f "$f" --overwrite false; done
  EOT
}
