# siem-ingest / aws / t0 "Quick start"
#
# Sends one CloudWatch log group, such as the trail the audit log template
# writes, to Splunk through its HTTP Event Collector. Firehose unpacks
# CloudWatch's compressed batches itself, so there is no function to maintain.
# Anything Splunk refuses lands in a bucket, to resend.
#
# In Splunk, create an HTTP Event Collector token with indexer acknowledgement
# turned on and the source type your add-on expects, such as aws:cloudtrail.
# Firehose will not deliver without acknowledgement.
#
# Change the two values below, then:
#   export TF_VAR_hec_token=<the token>
#   terraform init && terraform apply
#
# Verify: do one recognisable thing, such as creating a bucket named
# siem-drill-<today>. Search Splunk for eventName=CreateBucket and find it.

locals {
  log_group    = "your-trail-log-group"                              # change me
  hec_endpoint = "https://http-inputs-yourstack.splunkcloud.com:443" # change me
}

variable "hec_token" {
  description = "Splunk HTTP Event Collector token. Set it with TF_VAR_hec_token so it stays out of files. It is still stored in state."
  type        = string
  sensitive   = true
}

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

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

data "aws_caller_identity" "current" {}
data "aws_region" "current" {}

locals {
  account = data.aws_caller_identity.current.account_id
  region  = data.aws_region.current.region
}

# Events Splunk refused, kept for a month so they can be resent.
resource "aws_s3_bucket" "failed" {
  bucket_prefix = "siem-failed-"
  force_destroy = true
}

resource "aws_s3_bucket_public_access_block" "failed" {
  bucket                  = aws_s3_bucket.failed.id
  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}

resource "aws_s3_bucket_lifecycle_configuration" "failed" {
  bucket = aws_s3_bucket.failed.id
  rule {
    id     = "expire"
    status = "Enabled"
    filter {}
    expiration {
      days = 30
    }
    abort_incomplete_multipart_upload {
      days_after_initiation = 1
    }
  }
}

data "aws_iam_policy_document" "firehose_trust" {
  statement {
    actions = ["sts:AssumeRole"]
    principals {
      type        = "Service"
      identifiers = ["firehose.amazonaws.com"]
    }
    condition {
      test     = "StringEquals"
      variable = "sts:ExternalId"
      values   = [local.account]
    }
  }
}

resource "aws_iam_role" "firehose" {
  name_prefix        = "siem-firehose-"
  assume_role_policy = data.aws_iam_policy_document.firehose_trust.json
}

resource "aws_iam_role_policy" "firehose" {
  name = "write-failed-events"
  role = aws_iam_role.firehose.id
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect   = "Allow"
      Action   = ["s3:PutObject", "s3:AbortMultipartUpload", "s3:GetBucketLocation", "s3:ListBucket"]
      Resource = [aws_s3_bucket.failed.arn, "${aws_s3_bucket.failed.arn}/*"]
    }]
  })
}

resource "aws_kinesis_firehose_delivery_stream" "splunk" {
  name        = "siem-splunk"
  destination = "splunk"

  server_side_encryption {
    enabled = true
  }

  splunk_configuration {
    hec_endpoint               = local.hec_endpoint
    hec_token                  = var.hec_token
    hec_endpoint_type          = "Raw"
    hec_acknowledgment_timeout = 300
    retry_duration             = 300
    s3_backup_mode             = "FailedEventsOnly"

    s3_configuration {
      role_arn           = aws_iam_role.firehose.arn
      bucket_arn         = aws_s3_bucket.failed.arn
      compression_format = "GZIP"
    }

    # CloudWatch Logs sends gzipped batches of many events. These two steps
    # unpack them so each log line reaches Splunk as its own event.
    processing_configuration {
      enabled = true
      processors {
        type = "Decompression"
        parameters {
          parameter_name  = "CompressionFormat"
          parameter_value = "GZIP"
        }
      }
      processors {
        type = "CloudWatchLogProcessing"
        parameters {
          parameter_name  = "DataMessageExtraction"
          parameter_value = "true"
        }
      }
    }
  }
}

# CloudWatch Logs writes into the stream with its own role.
data "aws_iam_policy_document" "logs_trust" {
  statement {
    actions = ["sts:AssumeRole"]
    principals {
      type        = "Service"
      identifiers = ["logs.${local.region}.amazonaws.com"]
    }
    condition {
      test     = "StringEquals"
      variable = "aws:SourceAccount"
      values   = [local.account]
    }
  }
}

resource "aws_iam_role" "logs" {
  name_prefix        = "siem-logs-"
  assume_role_policy = data.aws_iam_policy_document.logs_trust.json
}

resource "aws_iam_role_policy" "logs" {
  name = "put-to-firehose"
  role = aws_iam_role.logs.id
  policy = jsonencode({
    Version   = "2012-10-17"
    Statement = [{ Effect = "Allow", Action = ["firehose:PutRecord", "firehose:PutRecordBatch"], Resource = aws_kinesis_firehose_delivery_stream.splunk.arn }]
  })
}

resource "aws_cloudwatch_log_subscription_filter" "to_splunk" {
  name            = "to-splunk"
  log_group_name  = local.log_group
  filter_pattern  = ""
  destination_arn = aws_kinesis_firehose_delivery_stream.splunk.arn
  role_arn        = aws_iam_role.logs.arn
}

output "firehose_arn" {
  description = "Other log groups can send here too, such as the EKS audit log."
  value       = aws_kinesis_firehose_delivery_stream.splunk.arn
}

output "failed_events_bucket" {
  description = "Where refused events land. Empty means everything arrived."
  value       = aws_s3_bucket.failed.bucket
}
