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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • 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
  • Securing the Cloud: Navigating the Frontier of Cloud Security

Trending

  • What’s Got Me Interested in OpenTelemetry—And Pursuing Certification
  • Monoliths, REST, and Spring Boot Sidecars: A Real Modernization Playbook
  • Creating a Web Project: Caching for Performance Optimization
  • Navigating Change Management: A Guide for Engineers
  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.1K 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

  • 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
  • Securing the Cloud: Navigating the Frontier of Cloud Security

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!