# forensic-workstation / aws / t0 "Quick start"
#
# A workstation for examining evidence that has no route to anything live:
# its own VPC with no internet gateway, no NAT, and no peering. You reach it
# through Session Manager, over private endpoints. S3 is reachable only
# through an endpoint whose policy allows two buckets: your evidence bucket,
# read-only, and the Amazon Linux package repository.
#
# Change the evidence bucket below, then:
#   terraform init && terraform apply
#   aws ssm start-session --target $(terraform output -raw instance_id)
#
# Verify, inside the session:
#   curl -m 5 -sI https://aws.amazon.com         # times out: no route out
#   aws s3 ls s3://<evidence bucket>/            # lists the evidence
#   aws s3 ls s3://<any other bucket>/           # AccessDenied from the endpoint policy

locals {
  evidence_bucket = "your-evidence-bucket" # change me: such as the evidence capture template's bucket
  cidr            = "10.250.0.0/24"
}

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

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

data "aws_region" "current" {}
# A closed list, so a zone AWS adds later cannot change which one is picked
# and force the subnet, and the workstation with it, to be rebuilt.
data "aws_availability_zones" "available" {
  state = "available"
  filter {
    name   = "zone-name"
    values = ["${data.aws_region.current.region}a", "${data.aws_region.current.region}b", "${data.aws_region.current.region}c"]
  }
}

locals {
  region = data.aws_region.current.region
  az     = data.aws_availability_zones.available.names[0]
}

resource "aws_vpc" "forensics" {
  cidr_block           = local.cidr
  enable_dns_support   = true
  enable_dns_hostnames = true # private endpoint names only resolve with both on
  tags                 = { Name = "forensics-isolated" }
}

resource "aws_subnet" "forensics" {
  vpc_id            = aws_vpc.forensics.id
  cidr_block        = local.cidr
  availability_zone = local.az
  tags              = { Name = "forensics-isolated" }
}

# No aws_internet_gateway and no NAT gateway, anywhere in this file. The
# route table has the VPC's own range and the S3 endpoint, and nothing else.
resource "aws_route_table" "forensics" {
  vpc_id = aws_vpc.forensics.id
  tags   = { Name = "forensics-isolated" }
}

resource "aws_route_table_association" "forensics" {
  subnet_id      = aws_subnet.forensics.id
  route_table_id = aws_route_table.forensics.id
}

resource "aws_security_group" "endpoints" {
  name_prefix = "forensics-endpoints-"
  description = "HTTPS from the forensic workstation to the private endpoints"
  vpc_id      = aws_vpc.forensics.id
  ingress {
    description = "HTTPS from inside this VPC"
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = [local.cidr]
  }
}

# Session Manager needs these three. They are the only way in.
resource "aws_vpc_endpoint" "ssm" {
  for_each            = toset(["ssm", "ssmmessages", "ec2messages"])
  vpc_id              = aws_vpc.forensics.id
  service_name        = "com.amazonaws.${local.region}.${each.value}"
  vpc_endpoint_type   = "Interface"
  subnet_ids          = [aws_subnet.forensics.id]
  security_group_ids  = [aws_security_group.endpoints.id]
  private_dns_enabled = true
}

# The endpoint policy is what stops a tool on the workstation from copying
# evidence to a bucket somewhere else.
data "aws_iam_policy_document" "s3_endpoint" {
  statement {
    sid     = "ReadEvidence"
    actions = ["s3:GetObject", "s3:ListBucket", "s3:GetBucketLocation"]
    resources = [
      "arn:aws:s3:::${local.evidence_bucket}",
      "arn:aws:s3:::${local.evidence_bucket}/*",
    ]
    principals {
      type        = "*"
      identifiers = ["*"]
    }
  }
  # Amazon Linux 2023 installs packages from this bucket, so dnf still works.
  statement {
    sid       = "AmazonLinuxPackages"
    actions   = ["s3:GetObject"]
    resources = ["arn:aws:s3:::al2023-repos-${local.region}-de612dc2/*"]
    principals {
      type        = "*"
      identifiers = ["*"]
    }
  }
}

resource "aws_vpc_endpoint" "s3" {
  vpc_id            = aws_vpc.forensics.id
  service_name      = "com.amazonaws.${local.region}.s3"
  vpc_endpoint_type = "Gateway"
  route_table_ids   = [aws_route_table.forensics.id]
  policy            = data.aws_iam_policy_document.s3_endpoint.json
}

resource "aws_security_group" "workstation" {
  name_prefix = "forensics-workstation-"
  description = "No inbound. Out only to the endpoints and S3."
  vpc_id      = aws_vpc.forensics.id
  egress {
    description = "HTTPS to the private endpoints"
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = [local.cidr]
  }
  egress {
    description     = "HTTPS to S3 through the gateway endpoint"
    from_port       = 443
    to_port         = 443
    protocol        = "tcp"
    prefix_list_ids = [aws_vpc_endpoint.s3.prefix_list_id]
  }
}

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

resource "aws_iam_role" "workstation" {
  name_prefix        = "forensic-workstation-"
  assume_role_policy = data.aws_iam_policy_document.ec2_trust.json
}

resource "aws_iam_role_policy_attachment" "ssm" {
  role       = aws_iam_role.workstation.name
  policy_arn = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"
}

resource "aws_iam_role_policy" "read_evidence" {
  name = "read-evidence"
  role = aws_iam_role.workstation.id
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect   = "Allow"
      Action   = ["s3:GetObject", "s3:ListBucket"]
      Resource = ["arn:aws:s3:::${local.evidence_bucket}", "arn:aws:s3:::${local.evidence_bucket}/*"]
    }]
  })
}

resource "aws_iam_instance_profile" "workstation" {
  name_prefix = "forensic-workstation-"
  role        = aws_iam_role.workstation.name
}

data "aws_ssm_parameter" "al2023" {
  name = "/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64"
}

resource "aws_instance" "workstation" {
  ami                    = data.aws_ssm_parameter.al2023.value
  instance_type          = "m7i.xlarge"
  subnet_id              = aws_subnet.forensics.id
  vpc_security_group_ids = [aws_security_group.workstation.id]
  iam_instance_profile   = aws_iam_instance_profile.workstation.name
  ebs_optimized          = true
  monitoring             = true

  metadata_options {
    http_tokens                 = "required"
    http_put_response_hop_limit = 1
  }

  root_block_device {
    volume_size = 200
    volume_type = "gp3"
    encrypted   = true
  }

  tags = { Name = "forensic-workstation" }

  # The AMI parameter moves with every Amazon Linux release. Replace the
  # workstation on purpose, never because a plan noticed a new image.
  lifecycle {
    ignore_changes = [ami]
  }
}

output "instance_id" {
  description = "Open a session with aws ssm start-session --target <this>."
  value       = aws_instance.workstation.id
}

output "attach_snapshot" {
  description = "How to examine a disk snapshot here. Attach it read-only in practice: mount with -o ro,noload."
  value       = <<-EOT
    aws ec2 create-volume --snapshot-id <snap-id> --availability-zone ${local.az} --volume-type gp3
    aws ec2 attach-volume --volume-id <vol-id> --instance-id ${aws_instance.workstation.id} --device /dev/sdf
    Then, in the session: sudo mkdir -p /mnt/evidence && sudo mount -o ro,noload /dev/nvme1n1p1 /mnt/evidence
  EOT
}
