DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Beyond Secrets Manager: Designing Zero-Retention Secrets in AWS With Ephemeral Access Patterns
  • Processing Cloud Data With DuckDB And AWS S3
  • 12 Expert Tips for Secure Cloud Deployments
  • The Critical Role of Data at Rest Encryption in Cybersecurity

Trending

  • Dear Micromanager: Your Distrust Has a Job; It’s Just Not the One You’re Doing
  • AI Agents in Java: Architecting Intelligent Health Data Systems
  • Understanding MCP Architecture: LLM + API vs Model Context Protocol
  • Invisible Failures in S/4HANA Conversions (And Why Teams Miss Them)
  1. DZone
  2. Software Design and Architecture
  3. Security
  4. Secret Management and Rotation

Secret Management and Rotation

Learn about automating KMS key rotation for asymmetric keys to raise the security bar by replacing keys at an interval.

By 
Pranav Kumar Chaudhary user avatar
Pranav Kumar Chaudhary
·
Oct. 08, 24 · Code Snippet
Likes (2)
Comment
Save
Tweet
Share
4.8K Views

Join the DZone community and get the full member experience.

Join For Free

Secrets 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:

  1. Encryption/Decryption keys: Keys to encrypt/decrypt data at various levels; e.g., REST, database, etc.
  2. API keys: Keys to provide access to an exposed API
  3. Credentials: Keys to provide credentials; e.g., database connection strings
  4. SSH keys: Keys to provide SSH communication to server
  5. 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:

  1. To create or get arn of KMS Key (asymmetric) in scope
  2. To create a key alias for the given key
  3. Create an lambda to facilitate the rotation
  4. Create a schedule to rotate the key
  5. Create Lambda logic to rotate the key
  6. Test

1. Create KMS Key

TypeScript
 
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

TypeScript
 
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

TypeScript
 
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

TypeScript
 
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

TypeScript
 
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.

AWS Data (computing) security Key management secrets management

Opinions expressed by DZone contributors are their own.

Related

  • Beyond Secrets Manager: Designing Zero-Retention Secrets in AWS With Ephemeral Access Patterns
  • Processing Cloud Data With DuckDB And AWS S3
  • 12 Expert Tips for Secure Cloud Deployments
  • The Critical Role of Data at Rest Encryption in Cybersecurity

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook