# key-baseline / aws / t1 "Standard" # # A KMS key with separation of duties: people who manage the key cannot use it, # people who use it cannot manage it, and only the named managers can switch it # off or schedule its deletion. Plus an alert whenever anyone tries. data "aws_caller_identity" "current" {} data "aws_partition" "current" {} locals { root = "arn:${data.aws_partition.current.partition}:iam::${data.aws_caller_identity.current.account_id}:root" tags = merge({ owner = var.owner environment = var.environment data_classification = "restricted" managed_by = "terraform" }, var.extra_tags) } resource "aws_kms_key" "this" { description = "${var.name} data key" is_enabled = var.enabled enable_key_rotation = true rotation_period_in_days = 365 deletion_window_in_days = var.deletion_window_days policy = data.aws_iam_policy_document.key.json } resource "aws_kms_alias" "this" { name = "alias/${var.name}" target_key_id = aws_kms_key.this.key_id } data "aws_iam_policy_document" "key" { # Kept so the key can always be recovered through IAM. Without it, a policy # naming the wrong role can leave a key that nobody can manage, and only AWS # support can help. statement { sid = "AccountManagesKeyThroughIAM" effect = "Allow" principals { type = "AWS" identifiers = [local.root] } actions = ["kms:*"] resources = ["*"] } dynamic "statement" { for_each = length(var.key_admin_arns) > 0 ? [1] : [] content { sid = "AdministratorsManageKey" effect = "Allow" principals { type = "AWS" identifiers = var.key_admin_arns } actions = [ "kms:Describe*", "kms:List*", "kms:Get*", "kms:Create*", "kms:Put*", "kms:Update*", "kms:Enable*", "kms:Disable*", "kms:Revoke*", "kms:TagResource", "kms:UntagResource", "kms:ScheduleKeyDeletion", "kms:CancelKeyDeletion", "kms:RotateKeyOnDemand", ] resources = ["*"] } } dynamic "statement" { for_each = length(var.key_user_arns) > 0 ? [1] : [] content { sid = "UsersEncryptAndDecrypt" effect = "Allow" principals { type = "AWS" identifiers = var.key_user_arns } actions = ["kms:Encrypt", "kms:Decrypt", "kms:ReEncrypt*", "kms:GenerateDataKey*", "kms:DescribeKey"] resources = ["*"] } } # The off switch and the delete button belong to the named administrators # alone. Everyone else is refused, whatever their IAM policies say. PutKeyPolicy # is deliberately left out, so a mistake in this list can still be fixed. dynamic "statement" { for_each = length(var.key_admin_arns) > 0 ? [1] : [] content { sid = "OnlyAdministratorsSwitchOffOrDelete" effect = "Deny" principals { type = "AWS" identifiers = ["*"] } actions = ["kms:DisableKey", "kms:ScheduleKeyDeletion"] resources = ["*"] condition { test = "ArnNotLike" variable = "aws:PrincipalArn" values = var.key_admin_arns } } } }