atlas_scoffed
atlas_scoffed

Reputation: 4127

How to decrypt AWS Lambda Environment Variables

I'm using the example code provided on the Lambda console when I 'encrypt' the environment variables.

I've created a key, and given the Role "kms:Decrypt" permission.

My function times out when trying to "decrypt" the variable, but runs fine when not encrypted. The logs do not provide any errors.

Here is the code used to decrypt:

private String decryptKey(String keyName) {
    byte[] encryptedKey = Base64.decode(keyName);
    AWSKMS client = AWSKMSClientBuilder.defaultClient();
    DecryptRequest request = new DecryptRequest()
     .withCiphertextBlob(ByteBuffer.wrap(encryptedKey));
    ByteBuffer plainTextKey = client.decrypt(request).getPlaintext();
    return new String(plainTextKey.array(), Charset.forName("UTF-8"));
}

And it's called like this...

return decryptKey(System.getenv(variableName));

I took this code as is, assuming that, as it runs from within Lambda, the 'defaultClient' knows the region, account, etc.

Edit:

These are the log lines:

START RequestId: 92419f62-fa84-11e6-876d-99aa85e9b481 Version: $LATEST END RequestId: 92419f62-fa84-11e6-876d-99aa85e9b481 REPORT RequestId: 92419f62-fa84-11e6-876d-99aa85e9b481 Duration: 15001.41 ms > Billed Duration: 15000 ms Memory Size: 512 MB Max Memory Used: 64 MB
2017-02-24T11:30:13.908Z 92419f62-fa84-11e6-876d-99aa85e9b481 Task timed out after 15.00 seconds

If I run without EncryptionHelpers, but still try and unencrypt the variables I get this, which is as expected:

{ "errorMessage": "Input is expected to be encoded in multiple of 4 bytes but found: 13", "errorType": "java.lang.IllegalArgumentException", "stackTrace": [ "com.amazonaws.util.Base64Codec.decode(Base64Codec.java:198)", "com.amazonaws.util.Base64.decode(Base64.java:89)", "scripts.Environment.decryptKey(Environment.java:56)", "scripts.Environment.getEnvVariable(Environment.java:38)", "scripts.Environment.(Environment.java:30)", "scripts.CreateNewDatabase.createNewConfigDatabase(CreateNewDatabase.java:33)", "sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)", "sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)", "sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)", "java.lang.reflect.Method.invoke(Method.java:498)" ] }

Upvotes: 4

Views: 4803

Answers (1)

DaMaill
DaMaill

Reputation: 925

kms.decrypt() are api calls which need internet and your issue seems to be a problem of connection to internet of your lambda.

To be sure, you should look into the logs. In this case, you'll find something like

Starting new HTTPS connection (1): kms.eu-west-1.amazonaws.com

To resolve this issue, you should associate the lambda to a subnet that has access to internet -
a private subnet with a NAT gateway.

You'll find more information in the part "Internet Access for Lambda Functions" of this document

Upvotes: 3

Related Questions