Created
November 22, 2016 14:42
-
-
Save rnhurt/67a32139ca03030741876be5d009fb9a to your computer and use it in GitHub Desktop.
Decrypting CloudFormation secrets using a Lamba function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const https = require('https'); | |
const url = require('url'); | |
function sendResponse(event, callback, logStreamName, responseStatus, responseData) { | |
const responseBody = JSON.stringify({ | |
Status: responseStatus, | |
Reason: `See the details in CloudWatch Log Stream: ${logStreamName}`, | |
PhysicalResourceId: logStreamName, | |
StackId: event.StackId, | |
RequestId: event.RequestId, | |
LogicalResourceId: event.LogicalResourceId, | |
Data: responseData, | |
}); | |
const parsedUrl = url.parse(event.ResponseURL); | |
const options = { | |
hostname: parsedUrl.hostname, | |
port: 443, | |
path: parsedUrl.path, | |
method: 'PUT', | |
headers: { | |
'Content-Type': '', | |
'Content-Length': responseBody.length, | |
}, | |
}; | |
const req = https.request(options, (res) => { | |
console.log('STATUS:', res.statusCode); | |
console.log('HEADERS:', JSON.stringify(res.headers)); | |
callback(null, 'Successfully sent stack response!'); | |
}); | |
req.on('error', (err) => { | |
console.log('sendResponse Error:\n', err); | |
callback(err); | |
}); | |
req.write(responseBody); | |
req.end(); | |
} | |
exports.handler = (event, context, callback) => { | |
console.log('Received event:', JSON.stringify(event, null, 2)); | |
if (event.RequestType === 'Delete') { | |
sendResponse(event, callback, context.logStreamName, 'SUCCESS'); | |
return; | |
} | |
let responseStatus = 'FAILED'; | |
let responseData = {}; | |
var AWS = require('aws-sdk'); | |
var KMS = new AWS.KMS({apiVersion:'2014-11-01', region:event.ResourceProperties.Region}); | |
var params = { | |
CiphertextBlob: Buffer(event.ResourceProperties.CiphertextBlob, 'base64'), | |
EncryptionContext: event.ResourceProperties.EncryptionContext | |
}; | |
KMS.decrypt(params, function(err,data){ | |
if(err){ | |
responseData = { Error: 'Unable to decrypt blob: '+err}; | |
console.log(`${responseData.Error}:\n`, err); | |
} else { | |
responseStatus = 'SUCCESS'; | |
responseData = {Plaintext: data.Plaintext.toString()}; | |
} | |
sendResponse(event, callback, context.logStreamName, responseStatus, responseData); | |
} | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment