Serverless, securing lambda secrets with AWS KMS (Key Management Service)

What is serverless?

Serverless is the open-source, application framework used to easily build serverless architectures on AWS Lambda & more. It allows us to deploy applications as independent functions that respond to events, charge only when they run, and scale automatically. To learn more about this framework, read the documentation here.

What is KMS?

AWS Key Management Service (KMS) is a managed service that makes it easy for you to create and control the encryption keys used to encrypt your data. To learn more about this service refer to the documentation here. 

Purpose

Sometimes in practices, when developing applications using this serverless framework, you may have a problem finding the best way to store your sensitive data. For example, data such as, database credentials, passwords, external API keys and so on. Of course, you can use environment variables, but using a KMS is a much better and more secure method. So where should we start?

Configuration

There is a nice serverless plugin called {serverless-crypt}, which will allow us to perform an encryption and decryption in our lambda function.
1. Install the plugin to your serverless application by adding it as a dependency of your app. You can find the installation guide readme file here.
2. Next, add the plugin to your serverless.yml file under the plugins section like this 

plugins:
serverless-crypt
1
2
plugins:
serverless-crypt

3. Add the KMS key variable under a custom section in your serverless.yml file, like this:

JavaScript

custom:
cryptKeyId: ${env:AWS_KMS_KEYID}
1
2
custom:
cryptKeyId: ${env:AWS_KMS_KEYID}

Next, create and attach an IAM policy to your serverless service role, log in to your AWS console, and search for a service called IAM (Identity and Access Management). From the left menu click on roles, then from the list provided search for a role of your lambda function.  NOTE: serverless creates a role for your function when you deploy it so you don’t have to. Basically the name consists of the name of your lambda function, plus the stage variable value, plus region, plus the wording “lambda Role,” so if you have a function with the name “foo,” the role name might be the following.

foo-dev-us-west-2-lambdaRole

Once found, click on it to navigate to the detail view, scroll to the bottom, and find a section called “Inline Policies.” Then under the actions, you should see an “edit policy” link. Click on it and add the KMS policy there. You can find the the policy sample in the readme file of the serverless-crypt repository.t. Once added, click apply policy. That’s all you need!

5. Go to the serverless-crypt readme file again if you want to see how to encrypt and decrypt your data in a lambda function.

  • Topics:
  • DevOps

Top Stories

High Five! You just read 2 awesome articles, in row. You may want to subscribe to our blog newsletter for new blog posts.