# insider-data-theft / aws / t0 "Quick start"
#
# Three alarms for the moves someone makes on the way out with data: sharing
# it outside the account, giving themselves a way to decrypt it, and turning
# down the logging that would show either.
#
# Needs a multi-region CloudTrail trail that delivers to CloudWatch Logs, such
# as the Standard audit log template builds. Apply in that log group's region.
#
# Change the two values below, then:
#   terraform init && terraform apply
#   Confirm the subscription in the email SNS sends.
#
# Verify: add a harmless statement to a test bucket's policy, then remove it.
# The shared-outside alarm emails within about ten minutes.

locals {
  trail_log_group = "your-cloudtrail-log-group"   # change me
  alert_email     = "security-alerts@example.com" # change me

  # CloudWatch filter patterns, one per detection, each under the 1,024
  # character limit. They read the trail's log group, which contains every
  # region's events.
  detections = {
    # Data made readable outside the account: bucket policies and ACLs, the
    # public access block removed, replication to another bucket, and
    # snapshots or images shared with other accounts.
    shared-outside = {
      pattern = join("", [
        "{ ($.eventName = \"PutBucketPolicy\") || ($.eventName = \"PutBucketAcl\") ",
        "|| ($.eventName = \"DeleteBucketPublicAccessBlock\") || ($.eventName = \"DeleteAccountPublicAccessBlock\") ",
        "|| ($.eventName = \"PutBucketReplication\") || ($.eventName = \"ModifySnapshotAttribute\") ",
        "|| ($.eventName = \"ModifyImageAttribute\") || ($.eventName = \"ModifyDBSnapshotAttribute\") ",
        "|| ($.eventName = \"ModifyDBClusterSnapshotAttribute\") }",
      ])
      description = "Data was shared outside the account, or a public access block was removed."
    }
    # A new key policy, or a grant made by a person. AWS services create
    # grants all day on a caller's behalf, and those calls carry the service's
    # name as the source address, so they are left out.
    decrypt-rights = {
      pattern = join("", [
        "{ ($.eventSource = \"kms.amazonaws.com\") && (($.eventName = \"PutKeyPolicy\") ",
        "|| (($.eventName = \"CreateGrant\") && ($.sourceIPAddress != \"*.amazonaws.com\") ",
        "&& ($.sourceIPAddress != \"AWS Internal\"))) }",
      ])
      description = "Someone changed who can use a KMS key, by key policy or by a grant made directly."
    }
    # The records that would show the other two.
    logging-weakened = {
      pattern = join("", [
        "{ ($.eventName = \"StopLogging\") || ($.eventName = \"DeleteTrail\") || ($.eventName = \"UpdateTrail\") ",
        "|| ($.eventName = \"PutEventSelectors\") || ($.eventName = \"DeleteFlowLogs\") }",
      ])
      description = "A trail was stopped, deleted, or narrowed, or flow logs were deleted."
    }
  }
}

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 = "internal"
      managed_by          = "terraform"
    }
  }
}

resource "aws_sns_topic" "alerts" {
  name = "insider-data-theft"
}

resource "aws_sns_topic_subscription" "email" {
  topic_arn = aws_sns_topic.alerts.arn
  protocol  = "email"
  endpoint  = local.alert_email
}

resource "aws_cloudwatch_log_metric_filter" "detection" {
  for_each       = local.detections
  name           = "insider-${each.key}"
  log_group_name = local.trail_log_group
  pattern        = each.value.pattern
  metric_transformation {
    name          = "Insider-${each.key}"
    namespace     = "Security/Insider"
    value         = "1"
    default_value = "0"
  }
}

resource "aws_cloudwatch_metric_alarm" "detection" {
  for_each            = local.detections
  alarm_name          = "insider-${each.key}"
  alarm_description   = "${each.value.description} In Logs Insights on ${local.trail_log_group}, filter on the event names in the insider-${each.key} metric filter to see who and what."
  namespace           = "Security/Insider"
  metric_name         = "Insider-${each.key}"
  statistic           = "Sum"
  period              = 300
  evaluation_periods  = 1
  threshold           = 1
  comparison_operator = "GreaterThanOrEqualToThreshold"
  treat_missing_data  = "notBreaching"
  alarm_actions       = [aws_sns_topic.alerts.arn]
  depends_on          = [aws_cloudwatch_log_metric_filter.detection]
}

output "verify" {
  description = "The drill."
  value       = <<-EOT
    aws s3api get-bucket-policy --bucket <test-bucket>          # save the current policy first
    Add and remove a statement on that test bucket's policy.
    The insider-shared-outside alarm goes to ALARM and the email arrives within about ten minutes.
    aws cloudwatch describe-alarms --alarm-name-prefix insider- --query 'MetricAlarms[].[AlarmName,StateValue]'
  EOT
}
