diff --git a/addons/logging-alb/.header.md b/addons/logging-alb/.header.md index d7bf03e..4b09950 100644 --- a/addons/logging-alb/.header.md +++ b/addons/logging-alb/.header.md @@ -1,5 +1,5 @@ # ALB Logging Addon -This addon creates an S3 bucket for ALB access logs with in-place SSE-KMS re-encryption via Lambda. ALB access logging requires SSE-S3 (AES256), so objects are written with SSE-S3 and immediately re-encrypted to SSE-KMS using a customer-managed KMS key. +This addon creates an S3 bucket for ALB access logs with in-place SSE-KMS re-encryption via Lambda. ALB access logging requires SSE-S3 (AES256), so objects are written with SSE-S3 and immediately re-encrypted to SSE-KMS using a customer-managed KMS key. The same module-managed CMK also encrypts the Lambda functions and their CloudWatch log groups. ## How it works diff --git a/addons/logging-alb/README.md b/addons/logging-alb/README.md index 07b3f60..2b99ddd 100644 --- a/addons/logging-alb/README.md +++ b/addons/logging-alb/README.md @@ -1,5 +1,5 @@ # ALB Logging Addon -This addon creates an S3 bucket for ALB access logs with in-place SSE-KMS re-encryption via Lambda. ALB access logging requires SSE-S3 (AES256), so objects are written with SSE-S3 and immediately re-encrypted to SSE-KMS using a customer-managed KMS key. +This addon creates an S3 bucket for ALB access logs with in-place SSE-KMS re-encryption via Lambda. ALB access logging requires SSE-S3 (AES256), so objects are written with SSE-S3 and immediately re-encrypted to SSE-KMS using a customer-managed KMS key. The same module-managed CMK also encrypts the Lambda functions and their CloudWatch log groups. ## How it works @@ -84,7 +84,7 @@ No requirements. | Name | Version | |------|---------| | [archive](#provider\_archive) | 2.7.1 | -| [aws](#provider\_aws) | 6.34.0 | +| [aws](#provider\_aws) | 6.37.0 | ## Modules diff --git a/addons/logging-alb/main.tf b/addons/logging-alb/main.tf index 99a39ec..dc90a30 100644 --- a/addons/logging-alb/main.tf +++ b/addons/logging-alb/main.tf @@ -6,6 +6,10 @@ data "aws_region" "current" {} locals { landing_bucket_name = "${var.prefix}-alb-logs" + lambda_function_arns = [ + "arn:${data.aws_partition.current.partition}:lambda:${data.aws_region.current.id}:${data.aws_caller_identity.current.account_id}:function:${var.prefix}-alb-log-reencrypt", + "arn:${data.aws_partition.current.partition}:lambda:${data.aws_region.current.id}:${data.aws_caller_identity.current.account_id}:function:${var.prefix}-alb-log-sweep", + ] kms_base_policy_statements = var.kms_base_policy != null ? var.kms_base_policy : [ { @@ -54,6 +58,34 @@ locals { identifiers = [aws_iam_role.batch_reencrypt.arn] } conditions = [] + }, + { + sid = "AllowCloudWatchLogsUseOfTheKey" + effect = "Allow" + actions = ["kms:Encrypt*", "kms:Decrypt*", "kms:ReEncrypt*", "kms:GenerateDataKey*", "kms:Describe*"] + resources = ["*"] + principals = { + type = "Service" + identifiers = ["logs.${data.aws_region.current.id}.amazonaws.com"] + } + conditions = [] + }, + { + sid = "AllowLambdaServiceUseOfTheKey" + effect = "Allow" + actions = ["kms:GenerateDataKey", "kms:Decrypt"] + resources = ["*"] + principals = { + type = "Service" + identifiers = ["lambda.amazonaws.com"] + } + conditions = [ + { + test = "StringLike" + variable = "kms:EncryptionContext:aws:lambda:FunctionArn" + values = local.lambda_function_arns + } + ] } ] @@ -320,6 +352,7 @@ data "archive_file" "lambda_reencrypt" { resource "aws_cloudwatch_log_group" "lambda_reencrypt" { name = "/aws/lambda/${var.prefix}-alb-log-reencrypt" + kms_key_id = aws_kms_key.logs.arn retention_in_days = var.lambda_log_retention_in_days } @@ -327,6 +360,7 @@ resource "aws_lambda_function" "reencrypt" { function_name = "${var.prefix}-alb-log-reencrypt" role = aws_iam_role.lambda_reencrypt.arn handler = "reencrypt.handler" + kms_key_arn = aws_kms_key.logs.arn runtime = "python3.12" timeout = 60 filename = data.archive_file.lambda_reencrypt.output_path @@ -448,6 +482,7 @@ data "archive_file" "lambda_sweep" { resource "aws_cloudwatch_log_group" "lambda_sweep" { name = "/aws/lambda/${var.prefix}-alb-log-sweep" + kms_key_id = aws_kms_key.logs.arn retention_in_days = var.lambda_log_retention_in_days } @@ -455,6 +490,7 @@ resource "aws_lambda_function" "sweep_reencrypt" { function_name = "${var.prefix}-alb-log-sweep" role = aws_iam_role.lambda_sweep.arn handler = "sweep_reencrypt.handler" + kms_key_arn = aws_kms_key.logs.arn runtime = "python3.12" timeout = 900 filename = data.archive_file.lambda_sweep.output_path diff --git a/addons/mdm/.header.md b/addons/mdm/.header.md index 021a895..d926f0d 100644 --- a/addons/mdm/.header.md +++ b/addons/mdm/.header.md @@ -1,7 +1,7 @@ # MDM addon Notice: Previous versions of this module referred to `dep`, but to reduce confusion that has been replaces with `abm` -to mach the change to the newer Apple Busines Manager. For each key/value pair below, the key names have been changed +to match the change to the newer Apple Business Manager. For each key/value pair below, the key names have been changed from previous version to match the name of the env var for easier usability. Older unused env vars were also removed for simplification. This includes removing the need for `extra_environment_variables` completely. @@ -11,6 +11,10 @@ The following secrets are created: - scep - apn +To encrypt those secrets with a CMK, use `secrets_kms`. Supply `kms_key_arn` to use an existing key, or set `cmk_enabled = true` and leave `kms_key_arn = null` to have this module create a key using `kms_alias`. + +If you are creating the MDM secrets CMK and this module's `extra_execution_iam_policies` output is fed back into the Fleet ECS execution role in the same stack, pass `secrets_kms.fleet_execution_role_name` as the stable execution role name string instead of trying to read it from a Fleet module output. That avoids introducing a cycle while still letting this module add the execution role to the CMK policy. + Note: ABM is optional. If Apple Business Manager (ABM) is not used, set the abm variable to `null` and it will be omitted. Since this module cannot determine the value for the secrets at apply time, this module must be applied in 2 phases: @@ -18,6 +22,27 @@ Since this module cannot determine the value for the secrets at apply time, this 1. In the first phase, just add the module without passing additional config to the main Fleet module 1. In the second phase, after the secret values have been populated, apply while also passing the additional config to the main Fleet module. +Example KMS configuration: + +``` +module "mdm" { + source = "github.com/fleetdm/fleet-terraform/addons/mdm?depth=1&ref=tf-mod-addon-mdm-v2.0.0" + + apn_secret_name = null + scep_secret_name = "fleet-scep" + abm_secret_name = null + enable_apple_mdm = false + enable_windows_mdm = true + + secrets_kms = { + cmk_enabled = true + kms_alias = "fleet-mdm-secrets" + kms_base_policy = local.kms_base_policy_statements + fleet_execution_role_name = "fleet-execution-role" + } +} +``` + The secrets should have the following layouts, note that all values are strings. If a value is a JSON object, string escape it.: ## ABM ``` diff --git a/addons/mdm/README.md b/addons/mdm/README.md index 4acccf3..615ccef 100644 --- a/addons/mdm/README.md +++ b/addons/mdm/README.md @@ -1,7 +1,7 @@ # MDM addon Notice: Previous versions of this module referred to `dep`, but to reduce confusion that has been replaces with `abm` -to mach the change to the newer Apple Business Manager. For each key/value pair below, the key names have been changed +to match the change to the newer Apple Business Manager. For each key/value pair below, the key names have been changed from previous version to match the name of the env var for easier usability. Older unused env vars were also removed for simplification. This includes removing the need for `extra_environment_variables` completely. @@ -11,6 +11,10 @@ The following secrets are created: - scep - apn +To encrypt those secrets with a CMK, use `secrets_kms`. Supply `kms_key_arn` to use an existing key, or set `cmk_enabled = true` and leave `kms_key_arn = null` to have this module create a key using `kms_alias`. + +If you are creating the MDM secrets CMK and this module's `extra_execution_iam_policies` output is fed back into the Fleet ECS execution role in the same stack, pass `secrets_kms.fleet_execution_role_name` as the stable execution role name string instead of trying to read it from a Fleet module output. That avoids introducing a cycle while still letting this module add the execution role to the CMK policy. + Note: ABM is optional. If Apple Business Manager (ABM) is not used, set the abm variable to `null` and it will be omitted. Since this module cannot determine the value for the secrets at apply time, this module must be applied in 2 phases: @@ -18,6 +22,27 @@ Since this module cannot determine the value for the secrets at apply time, this 1. In the first phase, just add the module without passing additional config to the main Fleet module 1. In the second phase, after the secret values have been populated, apply while also passing the additional config to the main Fleet module. +Example KMS configuration: + +``` +module "mdm" { + source = "github.com/fleetdm/fleet-terraform/addons/mdm?depth=1&ref=tf-mod-addon-mdm-v2.0.0" + + apn_secret_name = null + scep_secret_name = "fleet-scep" + abm_secret_name = null + enable_apple_mdm = false + enable_windows_mdm = true + + secrets_kms = { + cmk_enabled = true + kms_alias = "fleet-mdm-secrets" + kms_base_policy = local.kms_base_policy_statements + fleet_execution_role_name = "fleet-execution-role" + } +} +``` + The secrets should have the following layouts, note that all values are strings. If a value is a JSON object, string escape it.: ## ABM ``` @@ -58,7 +83,7 @@ No requirements. | Name | Version | |------|---------| -| [aws](#provider\_aws) | 4.53.0 | +| [aws](#provider\_aws) | n/a | ## Modules @@ -69,10 +94,17 @@ No modules. | Name | Type | |------|------| | [aws_iam_policy.main](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_policy) | resource | +| [aws_kms_alias.secrets](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/kms_alias) | resource | +| [aws_kms_key.secrets](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/kms_key) | resource | | [aws_secretsmanager_secret.abm](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/secretsmanager_secret) | resource | | [aws_secretsmanager_secret.apn](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/secretsmanager_secret) | resource | | [aws_secretsmanager_secret.scep](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/secretsmanager_secret) | resource | +| [aws_caller_identity.current](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/caller_identity) | data source | | [aws_iam_policy_document.main](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.secrets_kms](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_role.fleet_execution](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_role) | data source | +| [aws_kms_key.provided](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/kms_key) | data source | +| [aws_partition.current](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/partition) | data source | | [aws_region.current](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/region) | data source | ## Inputs @@ -83,8 +115,8 @@ No modules. | [apn\_secret\_name](#input\_apn\_secret\_name) | n/a | `string` | `"fleet-apn"` | no | | [enable\_apple\_mdm](#input\_enable\_apple\_mdm) | n/a | `bool` | `true` | no | | [enable\_windows\_mdm](#input\_enable\_windows\_mdm) | n/a | `bool` | `false` | no | -| [public\_domain\_name](#input\_public\_domain\_name) | n/a | `string` | n/a | yes | | [scep\_secret\_name](#input\_scep\_secret\_name) | n/a | `string` | `"fleet-scep"` | no | +| [secrets\_kms](#input\_secrets\_kms) | Configuration for optional customer-managed KMS encryption of the MDM Secrets Manager secrets. |
object({
cmk_enabled = optional(bool, false)
kms_key_arn = optional(string, null)
kms_alias = optional(string, "fleet-mdm-secrets")
kms_base_policy = optional(list(object({
sid = string
effect = string
principals = object({
type = string
identifiers = list(string)
})
actions = list(string)
resources = list(string)
conditions = optional(list(object({
test = string
variable = string
values = list(string)
})), [])
})), null)
extra_kms_policies = optional(list(any), [])
fleet_execution_role_name = optional(string, null)
})
|
{
"cmk_enabled": false,
"extra_kms_policies": [],
"fleet_execution_role_name": null,
"kms_alias": "fleet-mdm-secrets",
"kms_base_policy": null,
"kms_key_arn": null
}
| no | ## Outputs diff --git a/addons/mdm/main.tf b/addons/mdm/main.tf index 845d9df..c135e16 100644 --- a/addons/mdm/main.tf +++ b/addons/mdm/main.tf @@ -1,8 +1,187 @@ data "aws_region" "current" {} +data "aws_caller_identity" "current" {} +data "aws_partition" "current" {} + +locals { + secrets_cmk_enabled = var.secrets_kms.cmk_enabled + secrets_provided_kms_key_id = var.secrets_kms.kms_key_arn + secrets_create_kms_key = local.secrets_cmk_enabled == true && local.secrets_provided_kms_key_id == null + secrets_kms_key_arn = local.secrets_cmk_enabled == true ? ( + local.secrets_provided_kms_key_id != null ? data.aws_kms_key.provided[0].arn : aws_kms_key.secrets[0].arn + ) : null + fleet_execution_role_name = ( + var.secrets_kms.fleet_execution_role_name != null && + trimspace(var.secrets_kms.fleet_execution_role_name) != "" + ) ? trimspace(var.secrets_kms.fleet_execution_role_name) : null + secrets_kms_base_policy_statements = var.secrets_kms.kms_base_policy != null ? var.secrets_kms.kms_base_policy : [ + { + sid = "EnableRootPermissions" + effect = "Allow" + actions = ["kms:*"] + resources = ["*"] + principals = { + type = "AWS" + identifiers = ["arn:${data.aws_partition.current.partition}:iam::${data.aws_caller_identity.current.account_id}:root"] + } + conditions = [] + } + ] + secrets_kms_service_statements = [ + { + sid = "AllowSecretsManagerUseOfTheKey" + effect = "Allow" + actions = ["kms:Encrypt", "kms:Decrypt", "kms:ReEncrypt*", "kms:GenerateDataKey*", "kms:CreateGrant", "kms:DescribeKey"] + resources = ["*"] + principals = { + type = "Service" + identifiers = ["secretsmanager.amazonaws.com"] + } + conditions = [] + } + ] + secrets_kms_execution_role_statements = local.fleet_execution_role_name != null ? [ + { + sid = "AllowFleetExecutionRoleDecrypt" + effect = "Allow" + actions = ["kms:Decrypt", "kms:DescribeKey"] + resources = ["*"] + principals = { + type = "AWS" + identifiers = [data.aws_iam_role.fleet_execution[0].arn] + } + conditions = [] + } + ] : [] +} + +check "kms_base_policy_requires_module_managed_cmk" { + assert { + condition = var.secrets_kms.kms_base_policy == null || ( + local.secrets_create_kms_key == true + ) + error_message = "secrets_kms.kms_base_policy is not used by mdm unless this module is creating the secrets CMK. When kms_key_arn is provided, external key policies remain caller-managed." + } +} + +data "aws_kms_key" "provided" { + count = local.secrets_provided_kms_key_id != null ? 1 : 0 + key_id = local.secrets_provided_kms_key_id +} + +data "aws_iam_role" "fleet_execution" { + count = local.secrets_create_kms_key == true && local.fleet_execution_role_name != null ? 1 : 0 + name = local.fleet_execution_role_name +} + +data "aws_iam_policy_document" "secrets_kms" { + count = local.secrets_create_kms_key == true ? 1 : 0 + + dynamic "statement" { + for_each = local.secrets_kms_base_policy_statements + content { + sid = try(statement.value.sid, "") + effect = try(statement.value.effect, null) + actions = try(statement.value.actions, []) + resources = try(statement.value.resources, []) + principals { + type = statement.value.principals.type + identifiers = statement.value.principals.identifiers + } + dynamic "condition" { + for_each = try(statement.value.conditions, []) + content { + test = condition.value.test + variable = condition.value.variable + values = condition.value.values + } + } + } + } + + dynamic "statement" { + for_each = var.secrets_kms.extra_kms_policies + content { + sid = try(statement.value.sid, "") + effect = try(statement.value.effect, null) + actions = try(statement.value.actions, []) + resources = try(statement.value.resources, []) + principals { + type = statement.value.principals.type + identifiers = statement.value.principals.identifiers + } + dynamic "condition" { + for_each = try(statement.value.conditions, []) + content { + test = condition.value.test + variable = condition.value.variable + values = condition.value.values + } + } + } + } + + dynamic "statement" { + for_each = local.secrets_kms_service_statements + content { + sid = try(statement.value.sid, "") + effect = try(statement.value.effect, null) + actions = try(statement.value.actions, []) + resources = try(statement.value.resources, []) + principals { + type = statement.value.principals.type + identifiers = statement.value.principals.identifiers + } + dynamic "condition" { + for_each = try(statement.value.conditions, []) + content { + test = condition.value.test + variable = condition.value.variable + values = condition.value.values + } + } + } + } + + dynamic "statement" { + for_each = local.secrets_kms_execution_role_statements + content { + sid = try(statement.value.sid, "") + effect = try(statement.value.effect, null) + actions = try(statement.value.actions, []) + resources = try(statement.value.resources, []) + principals { + type = statement.value.principals.type + identifiers = statement.value.principals.identifiers + } + dynamic "condition" { + for_each = try(statement.value.conditions, []) + content { + test = condition.value.test + variable = condition.value.variable + values = condition.value.values + } + } + } + } +} + +resource "aws_kms_key" "secrets" { + count = local.secrets_create_kms_key == true ? 1 : 0 + description = "CMK for Fleet MDM Secrets Manager secret encryption." + enable_key_rotation = true + policy = data.aws_iam_policy_document.secrets_kms[0].json +} + +resource "aws_kms_alias" "secrets" { + count = local.secrets_create_kms_key == true ? 1 : 0 + target_key_id = aws_kms_key.secrets[0].id + name = "alias/${var.secrets_kms.kms_alias}" +} resource "aws_secretsmanager_secret" "apn" { - count = var.apn_secret_name == null ? 0 : 1 - name = var.apn_secret_name + count = var.apn_secret_name == null ? 0 : 1 + name = var.apn_secret_name + kms_key_id = local.secrets_kms_key_arn recovery_window_in_days = "0" lifecycle { @@ -11,7 +190,8 @@ resource "aws_secretsmanager_secret" "apn" { } resource "aws_secretsmanager_secret" "scep" { - name = var.scep_secret_name + name = var.scep_secret_name + kms_key_id = local.secrets_kms_key_arn recovery_window_in_days = "0" lifecycle { @@ -20,8 +200,9 @@ resource "aws_secretsmanager_secret" "scep" { } resource "aws_secretsmanager_secret" "abm" { - count = var.abm_secret_name == null ? 0 : 1 - name = var.abm_secret_name + count = var.abm_secret_name == null ? 0 : 1 + name = var.abm_secret_name + kms_key_id = local.secrets_kms_key_arn recovery_window_in_days = "0" lifecycle { @@ -36,6 +217,15 @@ data "aws_iam_policy_document" "main" { [aws_secretsmanager_secret.scep.arn], var.abm_secret_name == null ? [] : [aws_secretsmanager_secret.abm[0].arn]) } + + dynamic "statement" { + for_each = local.secrets_kms_key_arn != null ? [local.secrets_kms_key_arn] : [] + content { + sid = "UseMDMSecretsKMSKey" + actions = ["kms:Decrypt", "kms:DescribeKey"] + resources = [statement.value] + } + } } resource "aws_iam_policy" "main" { diff --git a/addons/mdm/variables.tf b/addons/mdm/variables.tf index aeadae9..dcd5728 100644 --- a/addons/mdm/variables.tf +++ b/addons/mdm/variables.tf @@ -27,3 +27,79 @@ variable "enable_apple_mdm" { nullable = false type = bool } + +variable "secrets_kms" { + description = "Configuration for optional customer-managed KMS encryption of the MDM Secrets Manager secrets." + type = object({ + cmk_enabled = optional(bool, false) + kms_key_arn = optional(string, null) + kms_alias = optional(string, "fleet-mdm-secrets") + kms_base_policy = optional(list(object({ + sid = string + effect = string + principals = object({ + type = string + identifiers = list(string) + }) + actions = list(string) + resources = list(string) + conditions = optional(list(object({ + test = string + variable = string + values = list(string) + })), []) + })), null) + extra_kms_policies = optional(list(any), []) + fleet_execution_role_name = optional(string, null) + }) + default = { + cmk_enabled = false + kms_key_arn = null + kms_alias = "fleet-mdm-secrets" + kms_base_policy = null + extra_kms_policies = [] + fleet_execution_role_name = null + } + + validation { + condition = ( + var.secrets_kms.kms_key_arn == null || + var.secrets_kms.cmk_enabled == true + ) + error_message = "secrets_kms.kms_key_arn requires secrets_kms.cmk_enabled = true." + } + + validation { + condition = ( + length(var.secrets_kms.extra_kms_policies) == 0 || + ( + var.secrets_kms.cmk_enabled == true && + var.secrets_kms.kms_key_arn == null + ) + ) + error_message = "secrets_kms.extra_kms_policies can be set only when the mdm module is creating the secrets CMK." + } + + validation { + condition = ( + var.secrets_kms.kms_base_policy == null || + ( + var.secrets_kms.cmk_enabled == true && + var.secrets_kms.kms_key_arn == null + ) + ) + error_message = "secrets_kms.kms_base_policy can be set only when the mdm module is creating the secrets CMK." + } + + validation { + condition = ( + var.secrets_kms.fleet_execution_role_name == null || + trimspace(var.secrets_kms.fleet_execution_role_name) == "" || + ( + var.secrets_kms.cmk_enabled == true && + var.secrets_kms.kms_key_arn == null + ) + ) + error_message = "secrets_kms.fleet_execution_role_name can be set only when the mdm module is creating the secrets CMK." + } +} diff --git a/addons/monitoring/.header.md b/addons/monitoring/.header.md index e37a361..bd2db4b 100644 --- a/addons/monitoring/.header.md +++ b/addons/monitoring/.header.md @@ -31,7 +31,36 @@ https://github.com/fleetdm/fleet-terraform/blob/main/example/main.tf for details If the Fleet database password secret is encrypted with a CMK, also pass `mysql_password_secret_kms_key_arn` so the cron-monitoring Lambda can decrypt it. When using the `byo-vpc` module, wire this from `module..byo-vpc.rds_password_secret_kms_key_arn`. -**Important:** If you supply a custom `kms_base_policy` that does not grant `kms:*` to the account root (for example, a least-privilege policy that only allows specific principals), you must also add the cron-monitoring Lambda role to `rds_config.password_secret_kms.extra_kms_policies` in the `byo-vpc` module. AWS KMS requires both the key policy and the IAM policy to allow access. The Lambda role name is predictable (`-cron-monitoring-lambda`), so you can construct the ARN before the role exists. See the `byo-vpc` module README for a full example. +To encrypt the cron-monitoring Lambda and its CloudWatch log group with a CMK, use `cron_monitoring.lambda_kms`. Supply `kms_key_arn` to use an existing key, or set `cmk_enabled = true` and leave `kms_key_arn = null` to have this module create a key using `kms_alias`. If you need to customize the base key policy for that module-created CMK, set `cron_monitoring.lambda_kms.kms_base_policy`. + +**Important:** If the Fleet database password secret key is using a custom `kms_base_policy` that does not grant `kms:*` to the account root (for example, a least-privilege policy that only allows specific principals), you must also add the cron-monitoring Lambda role to `rds_config.password_secret_kms.extra_kms_policies` in the `byo-vpc` module. AWS KMS requires both the key policy and the IAM policy to allow access. The Lambda role name is predictable (`-cron-monitoring-lambda`), so you can construct the ARN before the role exists. See the `byo-vpc` module README for a full example. + +## Upgrading existing cron-monitoring log groups + +If you are upgrading from a version where the cron-monitoring Lambda log group was not managed with the Lambda's real function name, AWS may already have auto-created `/aws/lambda/_cron_monitoring` outside Terraform. When this module starts managing that real log group so KMS encryption can be applied, Terraform cannot create it if it already exists. + +There are two ways to handle that: + +1. **Delete the existing auto-created log group and let Terraform recreate it with the new KMS settings.** This avoids carrying forward older log events that were not encrypted with the new CMK. + +```bash +aws logs delete-log-group --log-group-name "/aws/lambda/_cron_monitoring" +terraform apply +``` + +2. **Import the existing auto-created log group into Terraform state.** Use this only if you need to preserve the existing log events as-is. + +```bash +terraform state rm 'module.monitoring.aws_cloudwatch_log_group.cron_monitoring_lambda[0]' +terraform import 'module.monitoring.aws_cloudwatch_log_group.cron_monitoring_lambda[0]' '/aws/lambda/_cron_monitoring' +terraform apply +``` + +If the older unused hyphenated log group still exists, you can remove it after the upgrade: + +```bash +aws logs delete-log-group --log-group-name "/aws/lambda/-cron-monitoring" +``` ``` module "monitoring" { @@ -85,6 +114,11 @@ module "monitoring" { log_retention_in_days = 365 # Cron List of Names to Ignore (see below for valid values) ignore_list = [] + lambda_kms = { + cmk_enabled = true + kms_alias = "fleet-cron-monitoring" + kms_base_policy = local.kms_base_policy_statements + } } log_monitoring = { invalid-secret = { diff --git a/addons/monitoring/README.md b/addons/monitoring/README.md index d93f345..9a99b5b 100644 --- a/addons/monitoring/README.md +++ b/addons/monitoring/README.md @@ -31,7 +31,36 @@ https://github.com/fleetdm/fleet-terraform/blob/main/example/main.tf for details If the Fleet database password secret is encrypted with a CMK, also pass `mysql_password_secret_kms_key_arn` so the cron-monitoring Lambda can decrypt it. When using the `byo-vpc` module, wire this from `module..byo-vpc.rds_password_secret_kms_key_arn`. -**Important:** If you supply a custom `kms_base_policy` that does not grant `kms:*` to the account root (for example, a least-privilege policy that only allows specific principals), you must also add the cron-monitoring Lambda role to `rds_config.password_secret_kms.extra_kms_policies` in the `byo-vpc` module. AWS KMS requires both the key policy and the IAM policy to allow access. The Lambda role name is predictable (`-cron-monitoring-lambda`), so you can construct the ARN before the role exists. See the `byo-vpc` module README for a full example. +To encrypt the cron-monitoring Lambda and its CloudWatch log group with a CMK, use `cron_monitoring.lambda_kms`. Supply `kms_key_arn` to use an existing key, or set `cmk_enabled = true` and leave `kms_key_arn = null` to have this module create a key using `kms_alias`. If you need to customize the base key policy for that module-created CMK, set `cron_monitoring.lambda_kms.kms_base_policy`. + +**Important:** If the Fleet database password secret key is using a custom `kms_base_policy` that does not grant `kms:*` to the account root (for example, a least-privilege policy that only allows specific principals), you must also add the cron-monitoring Lambda role to `rds_config.password_secret_kms.extra_kms_policies` in the `byo-vpc` module. AWS KMS requires both the key policy and the IAM policy to allow access. The Lambda role name is predictable (`-cron-monitoring-lambda`), so you can construct the ARN before the role exists. See the `byo-vpc` module README for a full example. + +## Upgrading existing cron-monitoring log groups + +If you are upgrading from a version where the cron-monitoring Lambda log group was not managed with the Lambda's real function name, AWS may already have auto-created `/aws/lambda/_cron_monitoring` outside Terraform. When this module starts managing that real log group so KMS encryption can be applied, Terraform cannot create it if it already exists. + +There are two ways to handle that: + +1. **Delete the existing auto-created log group and let Terraform recreate it with the new KMS settings.** This avoids carrying forward older log events that were not encrypted with the new CMK. + +```bash +aws logs delete-log-group --log-group-name "/aws/lambda/_cron_monitoring" +terraform apply +``` + +2. **Import the existing auto-created log group into Terraform state.** Use this only if you need to preserve the existing log events as-is. + +```bash +terraform state rm 'module.monitoring.aws_cloudwatch_log_group.cron_monitoring_lambda[0]' +terraform import 'module.monitoring.aws_cloudwatch_log_group.cron_monitoring_lambda[0]' '/aws/lambda/_cron_monitoring' +terraform apply +``` + +If the older unused hyphenated log group still exists, you can remove it after the upgrade: + +```bash +aws logs delete-log-group --log-group-name "/aws/lambda/-cron-monitoring" +``` ``` module "monitoring" { @@ -85,6 +114,11 @@ module "monitoring" { log_retention_in_days = 365 # Cron List of Names to Ignore (see below for valid values) ignore_list = [] + lambda_kms = { + cmk_enabled = true + kms_alias = "fleet-cron-monitoring" + kms_base_policy = local.kms_base_policy_statements + } } log_monitoring = { invalid-secret = { @@ -163,7 +197,7 @@ No requirements. | Name | Version | |------|---------| | [archive](#provider\_archive) | 2.7.1 | -| [aws](#provider\_aws) | 6.20.0 | +| [aws](#provider\_aws) | 6.37.0 | | [null](#provider\_null) | 3.2.4 | ## Modules @@ -194,6 +228,8 @@ No modules. | [aws_iam_role.cron_monitoring_lambda](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role) | resource | | [aws_iam_role_policy_attachment.cron_monitoring_lambda](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy_attachment) | resource | | [aws_iam_role_policy_attachment.cron_monitoring_lambda_managed](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy_attachment) | resource | +| [aws_kms_alias.cron_monitoring_lambda](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/kms_alias) | resource | +| [aws_kms_key.cron_monitoring_lambda](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/kms_key) | resource | | [aws_lambda_function.cron_monitoring](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lambda_function) | resource | | [aws_lambda_permission.cron_monitoring_cloudwatch](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lambda_permission) | resource | | [aws_security_group.cron_monitoring](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/security_group) | resource | @@ -203,6 +239,8 @@ No modules. | [aws_caller_identity.current](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/caller_identity) | data source | | [aws_iam_policy_document.cron_monitoring_lambda](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | | [aws_iam_policy_document.cron_monitoring_lambda_assume_role](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.cron_monitoring_lambda_kms](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_partition.current](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/partition) | data source | | [aws_region.current](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/region) | data source | | [aws_secretsmanager_secret.mysql_database_password](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/secretsmanager_secret) | data source | @@ -212,7 +250,7 @@ No modules. |------|-------------|------|---------|:--------:| | [acm\_certificate\_arn](#input\_acm\_certificate\_arn) | n/a | `string` | `null` | no | | [albs](#input\_albs) | n/a |
list(object({
name = string
arn_suffix = string
target_group_name = string
target_group_arn_suffix = string
min_containers = optional(string, 1)
ecs_service_name = string
alert_thresholds = optional(
object({
HTTPCode_ELB_5XX_Count = object({
period = number
threshold = number
})
HTTPCode_Target_5XX_Count = object({
period = number
threshold = number
})
}),
{
HTTPCode_ELB_5XX_Count = {
period = 120
threshold = 0
},
HTTPCode_Target_5XX_Count = {
period = 120
threshold = 0
}
}
)
}))
| `[]` | no | -| [cron\_monitoring](#input\_cron\_monitoring) | n/a |
object({
mysql_host = string
mysql_database = string
mysql_user = string
mysql_password_secret_name = string
mysql_password_secret_kms_key_arn = optional(string, null)
mysql_tls_config = optional(string, "true")
vpc_id = string
subnet_ids = list(string)
rds_security_group_id = string
delay_tolerance = string
run_interval = string
log_retention_in_days = optional(number, 7)
ignore_list = optional(list(string), [])
})
| `null` | no | +| [cron\_monitoring](#input\_cron\_monitoring) | n/a |
object({
mysql_host = string
mysql_database = string
mysql_user = string
mysql_password_secret_name = string
mysql_password_secret_kms_key_arn = optional(string, null)
mysql_tls_config = optional(string, "true")
vpc_id = string
subnet_ids = list(string)
rds_security_group_id = string
delay_tolerance = string
run_interval = string
log_retention_in_days = optional(number, 7)
ignore_list = optional(list(string), [])
lambda_kms = optional(object({
cmk_enabled = optional(bool, false)
kms_key_arn = optional(string, null)
kms_alias = optional(string, "fleet-cron-monitoring")
kms_base_policy = optional(list(object({
sid = string
effect = string
principals = object({
type = string
identifiers = list(string)
})
actions = list(string)
resources = list(string)
conditions = optional(list(object({
test = string
variable = string
values = list(string)
})), [])
})), null)
extra_kms_policies = optional(list(any), [])
}), {
cmk_enabled = false
kms_key_arn = null
kms_alias = "fleet-cron-monitoring"
kms_base_policy = null
extra_kms_policies = []
})
})
| `null` | no | | [customer\_prefix](#input\_customer\_prefix) | n/a | `string` | `"fleet"` | no | | [default\_sns\_topic\_arns](#input\_default\_sns\_topic\_arns) | n/a | `list(string)` | `[]` | no | | [fleet\_ecs\_service\_name](#input\_fleet\_ecs\_service\_name) | n/a | `string` | `null` | no | diff --git a/addons/monitoring/main.tf b/addons/monitoring/main.tf index b8dbfec..649d459 100644 --- a/addons/monitoring/main.tf +++ b/addons/monitoring/main.tf @@ -37,7 +37,84 @@ resource "aws_db_event_subscription" "default" { } locals { - alb_map = { for k, v in var.albs : k => v } + alb_map = { for k, v in var.albs : k => v } + cron_monitoring_lambda_function_name = var.cron_monitoring != null ? "${var.customer_prefix}_cron_monitoring" : null + cron_monitoring_lambda_log_group_name = var.cron_monitoring != null ? "/aws/lambda/${local.cron_monitoring_lambda_function_name}" : null + cron_monitoring_lambda_kms_cmk_enabled = var.cron_monitoring != null ? var.cron_monitoring.lambda_kms.cmk_enabled : false + cron_monitoring_lambda_create_kms_key = var.cron_monitoring != null && local.cron_monitoring_lambda_kms_cmk_enabled == true && var.cron_monitoring.lambda_kms.kms_key_arn == null + cron_monitoring_lambda_kms_key_arn = var.cron_monitoring != null && local.cron_monitoring_lambda_kms_cmk_enabled == true ? ( + var.cron_monitoring.lambda_kms.kms_key_arn != null ? var.cron_monitoring.lambda_kms.kms_key_arn : aws_kms_key.cron_monitoring_lambda[0].arn + ) : null + cron_monitoring_lambda_kms_base_policy_statements = var.cron_monitoring != null && var.cron_monitoring.lambda_kms.kms_base_policy != null ? var.cron_monitoring.lambda_kms.kms_base_policy : [ + { + sid = "EnableRootPermissions" + effect = "Allow" + principals = { + type = "AWS" + identifiers = ["arn:${data.aws_partition.current.partition}:iam::${data.aws_caller_identity.current.account_id}:root"] + } + actions = ["kms:*"] + resources = ["*"] + conditions = [] + } + ] + cron_monitoring_lambda_kms_policy_statements = var.cron_monitoring != null ? [ + { + sid = "AllowCloudWatchLogsUseOfTheKey" + effect = "Allow" + principals = { + type = "Service" + identifiers = ["logs.${data.aws_region.current.id}.amazonaws.com"] + } + actions = [ + "kms:Encrypt*", + "kms:Decrypt*", + "kms:ReEncrypt*", + "kms:GenerateDataKey*", + "kms:Describe*" + ] + resources = ["*"] + conditions = [] + }, + { + sid = "AllowLambdaServiceUseOfTheKey" + effect = "Allow" + principals = { + type = "Service" + identifiers = ["lambda.amazonaws.com"] + } + actions = [ + "kms:GenerateDataKey", + "kms:Decrypt" + ] + resources = ["*"] + conditions = [ + { + test = "StringLike" + variable = "kms:EncryptionContext:aws:lambda:FunctionArn" + values = [ + "arn:${data.aws_partition.current.partition}:lambda:${data.aws_region.current.id}:${data.aws_caller_identity.current.account_id}:function:${local.cron_monitoring_lambda_function_name}" + ] + } + ] + }, + { + sid = "AllowCronMonitoringLambdaRoleUseOfTheKey" + effect = "Allow" + principals = { + type = "AWS" + identifiers = [aws_iam_role.cron_monitoring_lambda[0].arn] + } + actions = [ + "kms:Encrypt", + "kms:Decrypt", + "kms:GenerateDataKey*", + "kms:DescribeKey" + ] + resources = ["*"] + conditions = [] + } + ] : [] } // Log-based monitoring @@ -380,7 +457,7 @@ resource "aws_lambda_function" "cron_monitoring" { data.archive_file.cron_monitoring_lambda[0] ] - function_name = "${var.customer_prefix}_cron_monitoring" + function_name = local.cron_monitoring_lambda_function_name runtime = "provided.al2" memory_size = 256 timeout = 300 @@ -388,6 +465,7 @@ resource "aws_lambda_function" "cron_monitoring" { filename = data.archive_file.cron_monitoring_lambda[0].output_path source_code_hash = data.archive_file.cron_monitoring_lambda[0].output_base64sha256 handler = "bootstrap" + kms_key_arn = local.cron_monitoring_lambda_kms_key_arn reserved_concurrent_executions = 1 description = "This function has the ability to log into a production database and validate that the Fleet crons are running properly" tracing_config { @@ -430,6 +508,15 @@ data "aws_iam_policy_document" "cron_monitoring_lambda_assume_role" { } } +check "kms_base_policy_requires_module_managed_cmk" { + assert { + condition = var.cron_monitoring == null || var.cron_monitoring.lambda_kms.kms_base_policy == null || ( + local.cron_monitoring_lambda_create_kms_key == true + ) + error_message = "cron_monitoring.lambda_kms.kms_base_policy is not used unless this module is creating the cron monitoring Lambda CMK. When kms_key_arn is provided, external key policies remain caller-managed." + } +} + resource "aws_iam_role_policy_attachment" "cron_monitoring_lambda" { count = var.cron_monitoring == null ? 0 : 1 role = aws_iam_role.cron_monitoring_lambda[0].id @@ -456,6 +543,90 @@ resource "aws_iam_role" "cron_monitoring_lambda" { data "aws_region" "current" {} data "aws_caller_identity" "current" {} +data "aws_partition" "current" {} + +data "aws_iam_policy_document" "cron_monitoring_lambda_kms" { + count = local.cron_monitoring_lambda_create_kms_key == true ? 1 : 0 + + dynamic "statement" { + for_each = local.cron_monitoring_lambda_kms_base_policy_statements + content { + sid = statement.value.sid + effect = statement.value.effect + actions = statement.value.actions + resources = statement.value.resources + principals { + type = statement.value.principals.type + identifiers = statement.value.principals.identifiers + } + dynamic "condition" { + for_each = try(statement.value.conditions, []) + content { + test = condition.value.test + variable = condition.value.variable + values = condition.value.values + } + } + } + } + + dynamic "statement" { + for_each = var.cron_monitoring != null ? var.cron_monitoring.lambda_kms.extra_kms_policies : [] + content { + sid = try(statement.value.sid, "") + effect = try(statement.value.effect, null) + actions = try(statement.value.actions, []) + resources = try(statement.value.resources, []) + principals { + type = statement.value.principals.type + identifiers = statement.value.principals.identifiers + } + dynamic "condition" { + for_each = try(statement.value.conditions, []) + content { + test = condition.value.test + variable = condition.value.variable + values = condition.value.values + } + } + } + } + + dynamic "statement" { + for_each = local.cron_monitoring_lambda_kms_policy_statements + content { + sid = statement.value.sid + effect = statement.value.effect + actions = statement.value.actions + resources = statement.value.resources + principals { + type = statement.value.principals.type + identifiers = statement.value.principals.identifiers + } + dynamic "condition" { + for_each = try(statement.value.conditions, []) + content { + test = condition.value.test + variable = condition.value.variable + values = condition.value.values + } + } + } + } +} + +resource "aws_kms_key" "cron_monitoring_lambda" { + count = local.cron_monitoring_lambda_create_kms_key == true ? 1 : 0 + description = "CMK for cron monitoring Lambda storage and CloudWatch Logs encryption." + enable_key_rotation = true + policy = data.aws_iam_policy_document.cron_monitoring_lambda_kms[0].json +} + +resource "aws_kms_alias" "cron_monitoring_lambda" { + count = local.cron_monitoring_lambda_create_kms_key == true ? 1 : 0 + target_key_id = aws_kms_key.cron_monitoring_lambda[0].id + name = "alias/${var.cron_monitoring != null ? var.cron_monitoring.lambda_kms.kms_alias : ""}" +} data "aws_iam_policy_document" "cron_monitoring_lambda" { statement { @@ -490,6 +661,24 @@ data "aws_iam_policy_document" "cron_monitoring_lambda" { } } + dynamic "statement" { + for_each = var.cron_monitoring != null && var.cron_monitoring.lambda_kms.kms_key_arn != null ? [local.cron_monitoring_lambda_kms_key_arn] : [] + content { + sid = "UseCronMonitoringLambdaKMSKey" + + actions = [ + "kms:Encrypt", + "kms:Decrypt", + "kms:GenerateDataKey*", + "kms:DescribeKey" + ] + + resources = [statement.value] + + effect = "Allow" + } + } + statement { sid = "SNSPublish" @@ -509,7 +698,8 @@ data "aws_iam_policy_document" "cron_monitoring_lambda" { resource "aws_cloudwatch_log_group" "cron_monitoring_lambda" { count = var.cron_monitoring == null ? 0 : 1 - name = "/aws/lambda/${var.customer_prefix}-cron-monitoring" + kms_key_id = local.cron_monitoring_lambda_kms_key_arn + name = local.cron_monitoring_lambda_log_group_name retention_in_days = var.cron_monitoring.log_retention_in_days } diff --git a/addons/monitoring/variables.tf b/addons/monitoring/variables.tf index ebd2031..26accde 100644 --- a/addons/monitoring/variables.tf +++ b/addons/monitoring/variables.tf @@ -82,19 +82,79 @@ variable "log_monitoring" { variable "cron_monitoring" { type = object({ - mysql_host = string - mysql_database = string - mysql_user = string - mysql_password_secret_name = string + mysql_host = string + mysql_database = string + mysql_user = string + mysql_password_secret_name = string mysql_password_secret_kms_key_arn = optional(string, null) - mysql_tls_config = optional(string, "true") - vpc_id = string - subnet_ids = list(string) - rds_security_group_id = string - delay_tolerance = string - run_interval = string - log_retention_in_days = optional(number, 7) - ignore_list = optional(list(string), []) + mysql_tls_config = optional(string, "true") + vpc_id = string + subnet_ids = list(string) + rds_security_group_id = string + delay_tolerance = string + run_interval = string + log_retention_in_days = optional(number, 7) + ignore_list = optional(list(string), []) + lambda_kms = optional(object({ + cmk_enabled = optional(bool, false) + kms_key_arn = optional(string, null) + kms_alias = optional(string, "fleet-cron-monitoring") + kms_base_policy = optional(list(object({ + sid = string + effect = string + principals = object({ + type = string + identifiers = list(string) + }) + actions = list(string) + resources = list(string) + conditions = optional(list(object({ + test = string + variable = string + values = list(string) + })), []) + })), null) + extra_kms_policies = optional(list(any), []) + }), { + cmk_enabled = false + kms_key_arn = null + kms_alias = "fleet-cron-monitoring" + kms_base_policy = null + extra_kms_policies = [] + }) }) default = null + + validation { + condition = ( + var.cron_monitoring == null || + var.cron_monitoring.lambda_kms.kms_key_arn == null || + var.cron_monitoring.lambda_kms.cmk_enabled == true + ) + error_message = "cron_monitoring.lambda_kms.kms_key_arn requires cron_monitoring.lambda_kms.cmk_enabled = true." + } + + validation { + condition = ( + var.cron_monitoring == null || + length(var.cron_monitoring.lambda_kms.extra_kms_policies) == 0 || + ( + var.cron_monitoring.lambda_kms.cmk_enabled == true && + var.cron_monitoring.lambda_kms.kms_key_arn == null + ) + ) + error_message = "cron_monitoring.lambda_kms.extra_kms_policies can be set only when the monitoring module is creating the cron monitoring Lambda CMK." + } + + validation { + condition = ( + var.cron_monitoring == null || + var.cron_monitoring.lambda_kms.kms_base_policy == null || + ( + var.cron_monitoring.lambda_kms.cmk_enabled == true && + var.cron_monitoring.lambda_kms.kms_key_arn == null + ) + ) + error_message = "cron_monitoring.lambda_kms.kms_base_policy can be set only when the monitoring module is creating the cron monitoring Lambda CMK." + } }