2
votes

As far as I see on the net, I have to include a piece of code snippet to decrypt the environment variables encrypted with KMS keys but does anyone know the rationale for why this step has to be taken while the lambda function already has access to the key, can decrypt the values on the fly, and pass decrypted values to the underlying execution?

Copied from the code generated on the AWS console to include in my code:

using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Amazon.KeyManagementService;
using Amazon.KeyManagementService.Model;

namespace AWSLambda
{
    public class Function
    {
        private static string Key1Value;
        // Read values once, in the constructor
        public Function()
        {
            // Decrypt code should run once and variables stored outside of the
            // function handler so that these are decrypted once per container
            Key1Value = DecodeEnvVar("ConnString").Result;
        }
        private static async Task<string> DecodeEnvVar(string envVarName)
        {
            // Retrieve env var text
            var encryptedBase64Text = Environment.GetEnvironmentVariable(envVarName);
            // Convert base64-encoded text to bytes
            var encryptedBytes = Convert.FromBase64String(encryptedBase64Text);
            // Construct client
            using (var client = new AmazonKeyManagementServiceClient())
            {
                // Construct request
                var decryptRequest = new DecryptRequest
                {
                    CiphertextBlob = new MemoryStream(encryptedBytes),
                };
                // Call KMS to decrypt data
                var response = await client.DecryptAsync(decryptRequest);
                using (var plaintextStream = response.Plaintext)
                {
                    // Get decrypted bytes
                    var plaintextBytes = plaintextStream.ToArray();
                    // Convert decrypted bytes to ASCII text
                    var plaintext = Encoding.UTF8.GetString(plaintextBytes);
                    return plaintext;
                }
            }
        }
        public void FunctionHandler()
        {
            Console.WriteLine("Encrypted environment variable Key1 = " + Key1Value);
        }
    }
}
1

1 Answers

0
votes

I guess I found the answer. The encryption key does not stay on the lambda. It is a one off operation to encrypt the values on the console. Refreshed the page and the link to KMS is gone, or login with another user to only see encrypted values on the env var, with no encryption key attached.