# insider-data-theft / aws / t1 "Standard" # # The three quick start alarms with named exceptions, plus an alarm on any one # principal reading more than a set number of objects from the buckets you # name, and saved Logs Insights queries for working the case. data "aws_caller_identity" "current" {} data "aws_partition" "current" {} data "aws_region" "current" {} locals { account = data.aws_caller_identity.current.account_id partition = data.aws_partition.current.partition region = data.aws_region.current.region reads_on = length(var.sensitive_bucket_arns) > 0 topic_arn = var.alert_topic_arn != "" ? var.alert_topic_arn : aws_sns_topic.alerts[0].arn tags = merge({ owner = var.owner environment = var.environment data_classification = "confidential" managed_by = "terraform" }, var.extra_tags) # Changes by these roles are expected and do not alarm. CloudTrail records a # role's calls under its session ARN, arn:aws:sts:::assumed-role/ # /, so each role ARN is turned into that form with a wildcard # for the session. expected_sessions = [for a in var.expected_principal_arns : "arn:${local.partition}:sts::${split(":", a)[4]}:assumed-role/${reverse(split("/", a))[0]}/*" ] not_expected = join("", [for a in local.expected_sessions : " && ($.userIdentity.arn != \"${a}\")"]) shared = join(" || ", [for e in [ "PutBucketPolicy", "PutBucketAcl", "DeleteBucketPublicAccessBlock", "DeleteAccountPublicAccessBlock", "PutBucketReplication", "ModifySnapshotAttribute", "ModifyImageAttribute", "ModifyDBSnapshotAttribute", "ModifyDBClusterSnapshotAttribute", ] : "($.eventName = \"${e}\")"]) weakened = join(" || ", [for e in [ "StopLogging", "DeleteTrail", "UpdateTrail", "PutEventSelectors", "DeleteFlowLogs", ] : "($.eventName = \"${e}\")"]) detections = { shared-outside = { pattern = "{ (${local.shared})${local.not_expected} }" description = "Data was shared outside the account, or a public access block was removed." } # AWS services create grants 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 = "{ ($.eventSource = \"kms.amazonaws.com\") && (($.eventName = \"PutKeyPolicy\") || (($.eventName = \"CreateGrant\") && ($.sourceIPAddress != \"*.amazonaws.com\") && ($.sourceIPAddress != \"AWS Internal\")))${local.not_expected} }" description = "Someone changed who can use a KMS key, by key policy or by a grant made directly." } logging-weakened = { pattern = "{ (${local.weakened})${local.not_expected} }" description = "A trail was stopped, deleted, or narrowed, or flow logs were deleted." } } } # --------------------------------------------------------------------------- # Alert topic, with a key CloudWatch alarms are allowed to use. The AWS # managed SNS key cannot be changed to allow them, and alarms publishing to a # topic encrypted with it fail without an error anyone sees. # --------------------------------------------------------------------------- data "aws_iam_policy_document" "key" { statement { sid = "AccountManagesKeyThroughIAM" actions = ["kms:*"] resources = ["*"] principals { type = "AWS" identifiers = ["arn:${local.partition}:iam::${local.account}:root"] } } statement { sid = "CloudWatchAlarmsPublish" actions = ["kms:Decrypt", "kms:GenerateDataKey*"] resources = ["*"] principals { type = "Service" identifiers = ["cloudwatch.amazonaws.com"] } } statement { sid = "CloudTrailWritesReadRecords" actions = ["kms:GenerateDataKey*"] resources = ["*"] principals { type = "Service" identifiers = ["cloudtrail.amazonaws.com"] } condition { test = "StringLike" variable = "kms:EncryptionContext:aws:cloudtrail:arn" values = ["arn:${local.partition}:cloudtrail:*:${local.account}:trail/${var.name}-reads"] } } # DescribeKey carries no encryption context, so it cannot sit behind the # condition above. CloudTrail calls it when the trail is created. statement { sid = "CloudTrailDescribesKey" actions = ["kms:DescribeKey"] resources = ["*"] principals { type = "Service" identifiers = ["cloudtrail.amazonaws.com"] } } statement { sid = "CloudWatchLogsEncryptsReadGroup" actions = ["kms:Encrypt*", "kms:Decrypt*", "kms:ReEncrypt*", "kms:GenerateDataKey*", "kms:Describe*"] resources = ["*"] principals { type = "Service" identifiers = ["logs.${local.region}.amazonaws.com"] } condition { test = "ArnLike" variable = "kms:EncryptionContext:aws:logs:arn" values = ["arn:${local.partition}:logs:${local.region}:${local.account}:log-group:/aws/cloudtrail/${var.name}-reads"] } } } resource "aws_kms_key" "insider" { description = "${var.name}: alert topic and object read records" enable_key_rotation = true deletion_window_in_days = 30 policy = data.aws_iam_policy_document.key.json } resource "aws_kms_alias" "insider" { name = "alias/${var.name}" target_key_id = aws_kms_key.insider.key_id } resource "aws_sns_topic" "alerts" { count = var.alert_topic_arn == "" ? 1 : 0 name = var.name kms_master_key_id = aws_kms_key.insider.arn } resource "aws_sns_topic_subscription" "email" { for_each = var.alert_topic_arn == "" ? toset(var.alert_emails) : toset([]) topic_arn = aws_sns_topic.alerts[0].arn protocol = "email" endpoint = each.value } # --------------------------------------------------------------------------- # Management event alarms, from the organisation's audit trail # --------------------------------------------------------------------------- resource "aws_cloudwatch_log_metric_filter" "detection" { for_each = local.detections name = "${var.name}-${each.key}" log_group_name = var.trail_log_group pattern = each.value.pattern metric_transformation { name = "Insider-${each.key}" namespace = "Security/Insider" value = "1" default_value = "0" } lifecycle { precondition { condition = length(each.value.pattern) <= 1024 error_message = "The ${each.key} filter pattern is over CloudWatch's 1,024 character limit. Shorten expected_principal_arns." } } } resource "aws_cloudwatch_metric_alarm" "detection" { for_each = local.detections alarm_name = "${var.name}-${each.key}" alarm_description = "${each.value.description} Run the saved query ${var.name}/changes-by-person in Logs Insights 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 = [local.topic_arn] depends_on = [aws_cloudwatch_log_metric_filter.detection] }