# Customer-managed key. Two reasons over SSE-S3: rotation you control, and a # revocation lever that does not require deleting data. resource "aws_kms_key" "audit" { description = "${var.name} trail encryption" deletion_window_in_days = 30 enable_key_rotation = true policy = data.aws_iam_policy_document.key.json } resource "aws_kms_alias" "audit" { name = "alias/${var.name}" target_key_id = aws_kms_key.audit.key_id } data "aws_iam_policy_document" "key" { statement { sid = "AccountRootManagesKey" effect = "Allow" principals { type = "AWS" identifiers = ["arn:${data.aws_partition.current.partition}:iam::${local.account_id}:root"] } actions = ["kms:*"] resources = ["*"] } statement { sid = "CloudTrailEncrypt" effect = "Allow" principals { type = "Service" identifiers = ["cloudtrail.amazonaws.com"] } actions = ["kms:GenerateDataKey*"] resources = ["*"] condition { test = "StringLike" variable = "kms:EncryptionContext:aws:cloudtrail:arn" values = ["arn:${data.aws_partition.current.partition}:cloudtrail:*:${local.account_id}:trail/*"] } } # A DescribeKey call carries no encryption context, so it needs a statement # of its own. Behind the condition above it is refused, and CloudTrail # rejects the key when the trail is created or updated. statement { sid = "CloudTrailDescribeKey" effect = "Allow" principals { type = "Service" identifiers = ["cloudtrail.amazonaws.com"] } actions = ["kms:DescribeKey"] resources = ["*"] } # CloudWatch Logs encrypts the log group with this key, and it can only do that # if the key policy names it. Without this statement the log group fails to # create with a message about the key not existing. statement { sid = "CloudWatchLogsEncrypt" effect = "Allow" principals { type = "Service" identifiers = ["logs.${data.aws_region.current.region}.amazonaws.com"] } actions = [ "kms:Encrypt*", "kms:Decrypt*", "kms:ReEncrypt*", "kms:GenerateDataKey*", "kms:Describe*", ] resources = ["*"] condition { test = "ArnLike" variable = "kms:EncryptionContext:aws:logs:arn" values = ["arn:${data.aws_partition.current.partition}:logs:${data.aws_region.current.region}:${local.account_id}:log-group:/aws/cloudtrail/${var.name}"] } } statement { sid = "ReadersDecrypt" effect = "Allow" principals { type = "AWS" identifiers = ["arn:${data.aws_partition.current.partition}:iam::${local.account_id}:root"] } actions = ["kms:Decrypt", "kms:ReEncryptFrom"] resources = ["*"] condition { test = "StringEquals" variable = "kms:CallerAccount" values = [local.account_id] } } }