Secret Management and Rotation
Learn about automating KMS key rotation for asymmetric keys to raise the security bar by replacing keys at an interval.
Join the DZone community and get the full member experience.
Join For FreeSecrets are the keys to manage and enhance the security of a software application. Secret keys play a pivotal role in the authentication, authorization, encryption/decryption, etc. of data flowing through the application. There are various types of secrets and few of them are:
- Encryption/Decryption keys: Keys to encrypt/decrypt data at various levels; e.g., REST, database, etc.
- API keys: Keys to provide access to an exposed API
- Credentials: Keys to provide credentials; e.g., database connection strings
- SSH keys: Keys to provide SSH communication to server
- Passwords: Keys to store passwords
It is very important to store these keys and ensure safety of the stored keys. A compromised key could lead to data leak, system compromise, etc., and to raise the security bar, it is required to ensure the secrets' rotation and expiry. A manual secret rotation is cumbersome and challenging problem to solve. In this post, I will discuss about implementing an automated key rotation for AWS Secrets Manager.
Key Rotation in AWS Secrets Manager
As outlined above, there are various types of secrets that is used and can be stored in a secrets manager. In this post, I will focus on symmetric and asymmetric keys. AWS provides an automated rotation for symmetric keys with a default value of 365 days; however, users have the option to update the rotation period to customized time frame to, let's say, 30 days.
For the asymmetric KMS keys, HMAC KMS keys, and KMS keys in custom key stores, an automated key rotation is not available. This can be achieved either via manual rotation or developing an automated key rotation using AWS Lambda.
This will require:
- To create or get arn of KMS Key (asymmetric) in scope
- To create a key alias for the given key
- Create an lambda to facilitate the rotation
- Create a schedule to rotate the key
- Create Lambda logic to rotate the key
- Test
1. Create KMS Key
const asymmetricKey = new Key(this, 'AsymmetricKeyInScope', {
keySpec: KeySpec.RSA_2048
keyUsage: KeyUsage.SIGN_VERIFY,
});
The above block with create an asymmetric key using CDK.
2. Create KMS Key Alias
const asymmetricKeyAlias = new Alias(this, `AsymmetricKeyAlias`,{
aliasName: 'AsymmetricKeyAliasTest',
targetKey: this.asymmetricKey
});
This will create an alias for the above key.
3. Create Lambda for Rotating the Key
const rotationLambda = new Function(this, "AsymmetricKeyRotationLambda", {
code: Code.fromAsset('assetname'),
runtime: SecureRuntime.NODEJS_14_X,
handler: "index.handler",
});
rotationLambda.grantInvoke(new ServicePrincipal("kms.amazonaws.com"));
rotationLambda.addToRolePolicy(new PolicyStatement({
effect: Effect.ALLOW,
actions: [
"kms:UpdateAlias",
"kms:ListAliases",
"kms:ListKeys",
"kms:DescribeKey",
"kms:CreateKey",
"kms:GetKeyPolicy",
"kms:PutKeyPolicy"
],
resources: ['*'],
}));
4. Create a Schedule to Rotate the Key
const rule = new events.Rule(this, 'MyScheduleRule', {
//Trigger every month
schedule: events.Schedule.cron({ minute: '0', hour: '0', day: '1', month: '*', weekDay: '?' }),
});
rule.addTarget(new targets.LambdaFunction(rotationLambda));
5. Create Lambda Logic to Rotate the Key
export class KmsKeyRotationHandler {
private readonly kms: KMS;
public constructor(kms: KMS) {
this.kms = kms;
}
public async handleRotation(event: any): Promise<void> {
try {
//get key alias
const alias = event.alias;
// Get key properties
const describeKeyParams = {
KeyId: alias
};
const {KeyMetadata} = await this.kms.describeKey(describeKeyParams).promise();
const {Description, KeyUsage, KeyId, KeySpec} = KeyMetadata!;
// Get key policy
const keyPolicyParams = {
KeyId: KeyId,
PolicyName: 'default'
};
const {Policy} = await this.kms.getKeyPolicy(keyPolicyParams).promise();
// Create new key using the same key properties
const createKeyParams = {
KeySpec: KeySpec,
Description: Description,
KeyUsage: KeyUsage,
Policy: Policy,
};
const createKeyResult = await this.kms.createKey(createKeyParams).promise();
// Update alias to map to new key
const newKeyId = createKeyResult?.KeyMetadata?.KeyId;
if (newKeyId) {
const updateAliasParams = {
AliasName: alias,
TargetKeyId: newKeyId
};
await this.kms.updateAlias(updateAliasParams).promise();
console.log(`Successfully rotated key for alias ${alias}`);
}
} catch (e) {
console.error(`Key rotation failed with error for event ${event}, `, e);
}
}
}
The above handler will fetch the key, create a new key with the same spec, and replace it with the old key. This way we can automate the key rotation for asymmetric keys as well.
Opinions expressed by DZone contributors are their own.
Comments