Secret Management and Rotation: Automating KMS Key Rotation for Asymmetric Keys

In today's digital landscape, secrets such as encryption keys, API keys, credentials, SSH keys, and passwords are the backbone of application security. These secrets are crucial for authentication, authorization, and data encryption/decryption. However, managing these secrets manually can be cumbersome and error-prone, leading to potential security vulnerabilities.

To raise the security bar, it's essential to implement automated secret rotation and expiry. In this blog, we'll explore how to automate key rotation for asymmetric keys using AWS Secrets Manager, with insights from ZippyOPS, a trusted microservice consulting provider.

Why Secret Rotation Matters

Secret rotation is the process of periodically replacing secrets to minimize the risk of compromise. A compromised key can lead to data breaches, system compromises, and other security incidents. Automated key rotation ensures that secrets are updated regularly without manual intervention, enhancing overall security.

Types of Secrets

  1. Encryption/Decryption Keys: Used to encrypt/decrypt data at various levels, such as REST APIs and databases.

  2. API Keys: Provide access to exposed APIs.

  3. Credentials: Include database connection strings and other authentication details.

  4. SSH Keys: Facilitate secure communication with servers.

  5. Passwords: Store sensitive login information.

Key Rotation in AWS Secrets Manager

AWS Secrets Manager offers automated rotation for symmetric keys, with a default rotation period of 365 days. However, for asymmetric KMS keys, HMAC KMS keys, and KMS keys in custom key stores, automated rotation is not natively supported. This can be achieved through manual rotation or by developing an automated key rotation solution using AWS Lambda.

Implementing Automated Key Rotation for Asymmetric Keys

Here’s a step-by-step guide to automating key rotation for asymmetric keys using AWS Lambda:

  1. Create a KMS Key

    const asymmetricKey = new Key(this, 'AsymmetricKeyInScope', {
    keySpec: KeySpec.RSA_2048,
    keyUsage: KeyUsage.SIGN_VERIFY,
    });

    This code creates an asymmetric key using AWS CDK.

  2. Create a KMS Key Alias

    const asymmetricKeyAlias = new Alias(this, AsymmetricKeyAlias, {
    aliasName: 'AsymmetricKeyAliasTest',
    targetKey: this.asymmetricKey,
    });

    This code creates an alias for the asymmetric key.

  3. Create a Lambda Function for Key Rotation

    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: ['
    '],
    }));*

    This Lambda function will handle the key rotation process.

  4. Create a Schedule for Key Rotation

    const rule = new events.Rule(this, 'MyScheduleRule', {
    schedule: events.Schedule.cron({ minute: '0', hour: '0', day: '1', month: '
    ', weekDay: '?' }),
    });*

    rule.addTarget(new targets.LambdaFunction(rotationLambda));

    This code sets up a schedule to trigger the Lambda function every month.

  5. Implement Lambda Logic for Key Rotation

    *export class KmsKeyRotationHandler {
    private readonly kms: KMS;


    public constructor(kms: KMS) {  
        this.kms = kms;  
    }  
    
    public async handleRotation(event: any): Promise<void> {  
        try {  
            const alias = event.alias;  
            const describeKeyParams = {  
                KeyId: alias,  
            };  
            const {KeyMetadata} = await this.kms.describeKey(describeKeyParams).promise();  
            const {Description, KeyUsage, KeyId, KeySpec} = KeyMetadata!;  
    
            const keyPolicyParams = {  
                KeyId: KeyId,  
                PolicyName: 'default',  
            };  
            const {Policy} = await this.kms.getKeyPolicy(keyPolicyParams).promise();  
    
            const createKeyParams = {  
                KeySpec: KeySpec,  
                Description: Description,  
                KeyUsage: KeyUsage,  
                Policy: Policy,  
            };  
    
            const createKeyResult = await this.kms.createKey(createKeyParams).promise();  
    
            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);  
        }  
    }  

    }*

    This handler fetches the key, creates a new key with the same specifications, and replaces the old key, automating the rotation process.

How ZippyOPS Can Help

At ZippyOPS, we provide comprehensive consulting, implementation, and management services for DevOps, DevSecOps, DataOps, Cloud, Automated Ops, AI Ops, ML Ops, Microservices, Infrastructure, and Security. Our expertise ensures that your systems are secure, efficient, and scalable.

If you're interested in learning more about how we can help you implement automated key rotation or other security measures, please email us at [email protected] for a consultation.


By automating key rotation, you can significantly enhance your application's security posture. With ZippyOPS as your microservice consulting partner, you can ensure that your systems are not only secure but also optimized for performance and scalability.

Recent Comments

No comments

Leave a Comment