Sub topic 2
Encrypting Values with KMS Keys
Assume you know AWS accounts, Regions, IAM roles, the AWS CLI, JSON, and basic Python. This chapter focuses on how encryption and access control work together.
Encrypting values with KMS
AWS Key Management Service (KMS) creates and controls encryption keys. A SecureString parameter in Parameter Store is encrypted with KMS. Secrets Manager also encrypts secret values, using the AWS managed key aws/secretsmanager by default or a customer managed KMS key that you select.
Encryption alone does not grant access. An application needs permission to read the value and, for a customer managed key, permission to call kms:Decrypt.
Granting least-privilege access with IAM
IAM policies should name only the paths and secrets an application needs. Limit KMS access to the key that encrypts those values.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "ssm:GetParameter",
"Resource": "arn:aws:ssm:us-east-1:111122223333:parameter/myapp/prod/*"
},
{
"Effect": "Allow",
"Action": "secretsmanager:GetSecretValue",
"Resource": "arn:aws:secretsmanager:us-east-1:111122223333:secret:myapp/prod/db-*"
},
{
"Effect": "Allow",
"Action": "kms:Decrypt",
"Resource": "arn:aws:kms:us-east-1:111122223333:key/EXAMPLE-KEY-ID"
}
]
}Avoid Resource: "*" when a specific ARN is available. Do not log decrypted values.
Retrieving values
The CLI can decrypt a parameter during retrieval:
aws ssm get-parameter \
--name /myapp/prod/db/password \
--with-decryption
aws secretsmanager get-secret-value \
--secret-id myapp/prod/dbIn Python, request the values and keep the secret in memory:
import json
import boto3
ssm = boto3.client("ssm")
password = ssm.get_parameter(
Name="/myapp/prod/db/password",
WithDecryption=True,
)["Parameter"]["Value"]
secrets = boto3.client("secretsmanager")
secret = secrets.get_secret_value(SecretId="myapp/prod/db")
credentials = json.loads(secret["SecretString"])
username = credentials["username"]Versions and staging labels
Secrets Manager creates a new version when a secret changes. Staging labels identify its role:
AWSCURRENTidentifies the version applications should use.AWSPREVIOUSidentifies the prior working version.AWSPENDINGidentifies a candidate during rotation.
Parameter Store instead assigns an increasing integer version to each update.
Rotating secrets automatically
Secrets Manager rotation uses a Lambda function and usually follows four steps: create a pending credential, test it, change the service to use it, and move AWSCURRENT to the new version. Rotation reduces the lifetime of passwords, but the application must retrieve the current value and tolerate a brief transition.
Exercise
Why can an application receive an AccessDenied error even when it has permission to read a SecureString parameter?
Show answer
It may lack kms:Decrypt permission for the KMS key that encrypts the parameter.