# evidence-capture / aws / t0 "Quick start"
#
# Tag an EC2 instance incident=<your incident id>, and within about a minute:
#   1. it is protected from termination and taken out of its Auto Scaling
#      group, so scaling cannot destroy the evidence
#   2. every attached volume is snapshotted, all at the same instant
#   3. it is moved into a security group with no inbound or outbound rules
#
# Tagging is the trigger because it works from the console, the CLI, a SOAR
# playbook, or another automation, and it leaves a record in CloudTrail of who
# pulled the lever.
#
# Run:
#   terraform init && terraform apply
#
# Verify, on a test instance you do not mind isolating:
#   terraform output verify
#
# Memory capture and a locked evidence bucket are in the Standard version.

terraform {
  required_version = ">= 1.6"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
    archive = {
      source  = "hashicorp/archive"
      version = "~> 2.7"
    }
  }
}

provider "aws" {
  default_tags {
    tags = {
      owner               = "security-engineering"
      environment         = "prod"
      data_classification = "restricted"
      managed_by          = "terraform"
    }
  }
}

locals {
  name = "evidence-capture"

  # The responder. Kept inline so this template stays one file. The Standard
  # version keeps it in its own responder.py.
  code = <<-PY
    import os, datetime, boto3

    ec2 = boto3.client("ec2")
    asg = boto3.client("autoscaling")
    QUARANTINE = "incident-quarantine"


    def handler(event, context):
        tags = event["detail"].get("tags", {})
        incident = tags.get("incident")
        if not incident:
            return {"skipped": "incident tag was removed, not added"}
        instance_id = event["resources"][0].split("/")[-1]
        inst = ec2.describe_instances(InstanceIds=[instance_id])["Reservations"][0]["Instances"][0]

        # 1. Keep it alive. Termination protection stops a person or a script.
        #    Detaching from the Auto Scaling group stops scaling, and the group
        #    launches a replacement so the service keeps running.
        ec2.modify_instance_attribute(InstanceId=instance_id, DisableApiTermination={"Value": True})
        groups = asg.describe_auto_scaling_instances(InstanceIds=[instance_id])["AutoScalingInstances"]
        for g in groups:
            asg.detach_instances(InstanceIds=[instance_id], AutoScalingGroupName=g["AutoScalingGroupName"],
                                 ShouldDecrementDesiredCapacity=False)

        # 2. Snapshot every volume at the same instant. A snapshot is fixed at
        #    the moment it is requested, so nothing after this line changes it.
        stamp = datetime.datetime.now(datetime.timezone.utc).isoformat()
        snaps = ec2.create_snapshots(
            InstanceSpecification={"InstanceId": instance_id, "ExcludeBootVolume": False},
            Description=f"incident {incident} {instance_id}",
            CopyTagsFromSource="volume",
            TagSpecifications=[{"ResourceType": "snapshot", "Tags": [
                {"Key": "incident", "Value": incident},
                {"Key": "source-instance", "Value": instance_id},
                {"Key": "captured-at", "Value": stamp},
            ]}],
        )["Snapshots"]

        # 3. Isolate. A new security group allows all outbound traffic until that
        #    rule is removed, so the rule is removed before the group is used.
        vpc = inst["VpcId"]
        found = ec2.describe_security_groups(Filters=[
            {"Name": "group-name", "Values": [QUARANTINE]}, {"Name": "vpc-id", "Values": [vpc]}])["SecurityGroups"]
        if found:
            sg = found[0]["GroupId"]
        else:
            sg = ec2.create_security_group(GroupName=QUARANTINE, VpcId=vpc,
                                           Description="No traffic in or out. Used to isolate instances under investigation.")["GroupId"]
            egress = ec2.describe_security_groups(GroupIds=[sg])["SecurityGroups"][0]["IpPermissionsEgress"]
            if egress:
                ec2.revoke_security_group_egress(GroupId=sg, IpPermissions=egress)
        for eni in inst["NetworkInterfaces"]:
            ec2.modify_network_interface_attribute(NetworkInterfaceId=eni["NetworkInterfaceId"], Groups=[sg])

        ec2.create_tags(Resources=[instance_id], Tags=[{"Key": "incident-status", "Value": "preserved-and-isolated"}])
        return {"instance": instance_id, "snapshots": [s["SnapshotId"] for s in snaps],
                "detached_from": [g["AutoScalingGroupName"] for g in groups], "quarantine_group": sg}
  PY
}

data "archive_file" "responder" {
  type        = "zip"
  output_path = "${path.module}/.build/responder.zip"
  source {
    content  = local.code
    filename = "index.py"
  }
}

data "aws_iam_policy_document" "assume" {
  statement {
    actions = ["sts:AssumeRole"]
    principals {
      type        = "Service"
      identifiers = ["lambda.amazonaws.com"]
    }
  }
}

resource "aws_iam_role" "responder" {
  name               = "${local.name}-responder"
  assume_role_policy = data.aws_iam_policy_document.assume.json
}

# Only what the three steps need. The responder can snapshot, protect, and
# isolate. It cannot delete, stop, or terminate anything.
data "aws_iam_policy_document" "responder" {
  statement {
    sid = "PreserveAndIsolate"
    actions = [
      "ec2:DescribeInstances", "ec2:DescribeSecurityGroups",
      "ec2:ModifyInstanceAttribute", "ec2:CreateSnapshots", "ec2:CreateTags",
      "ec2:CreateSecurityGroup", "ec2:RevokeSecurityGroupEgress",
      "ec2:ModifyNetworkInterfaceAttribute",
      "autoscaling:DescribeAutoScalingInstances", "autoscaling:DetachInstances",
    ]
    resources = ["*"]
  }
  statement {
    sid       = "OwnLogs"
    actions   = ["logs:CreateLogStream", "logs:PutLogEvents"]
    resources = ["${aws_cloudwatch_log_group.responder.arn}:*"]
  }
}

resource "aws_iam_role_policy" "responder" {
  name   = "preserve-and-isolate"
  role   = aws_iam_role.responder.id
  policy = data.aws_iam_policy_document.responder.json
}

resource "aws_cloudwatch_log_group" "responder" {
  name              = "/aws/lambda/${local.name}-responder"
  retention_in_days = 365
}

resource "aws_lambda_function" "responder" {
  function_name    = "${local.name}-responder"
  role             = aws_iam_role.responder.arn
  runtime          = "python3.13"
  handler          = "index.handler"
  filename         = data.archive_file.responder.output_path
  source_code_hash = data.archive_file.responder.output_base64sha256
  timeout          = 120
  depends_on       = [aws_cloudwatch_log_group.responder]
}

# Fires when the incident tag is added to an instance, and not for any other tag,
# so the responder's own tags never trigger it again.
resource "aws_cloudwatch_event_rule" "incident_tag" {
  name        = "${local.name}-incident-tag"
  description = "An EC2 instance was tagged incident=<id>."
  event_pattern = jsonencode({
    source        = ["aws.tag"]
    "detail-type" = ["Tag Change on Resource"]
    detail = {
      service            = ["ec2"]
      "resource-type"    = ["instance"]
      "changed-tag-keys" = ["incident"]
    }
  })
}

resource "aws_cloudwatch_event_target" "responder" {
  rule = aws_cloudwatch_event_rule.incident_tag.name
  arn  = aws_lambda_function.responder.arn
}

resource "aws_lambda_permission" "events" {
  statement_id  = "AllowEventBridge"
  action        = "lambda:InvokeFunction"
  function_name = aws_lambda_function.responder.function_name
  principal     = "events.amazonaws.com"
  source_arn    = aws_cloudwatch_event_rule.incident_tag.arn
}

output "verify" {
  description = "Tag a test instance, then confirm the snapshots, the isolation, and that it cannot be terminated."
  value       = <<-EOT
    aws ec2 create-tags --resources <test-instance-id> --tags Key=incident,Value=drill-1
    aws ec2 describe-snapshots --owner-ids self --filters Name=tag:incident,Values=drill-1 --query 'Snapshots[].[SnapshotId,VolumeId,State]'
    aws ec2 describe-instances --instance-ids <test-instance-id> --query 'Reservations[].Instances[].SecurityGroups'
    aws ec2 terminate-instances --instance-ids <test-instance-id>      # must be refused: termination protection is on
  EOT
}
