-
Notifications
You must be signed in to change notification settings - Fork 163
/
kmsCrypto.js
265 lines (245 loc) · 7.77 KB
/
kmsCrypto.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
/*
Copyright 2014-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Amazon Software License (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/asl/
or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
var useRegion = undefined;
var aws = require('aws-sdk');
var async = require('async');
var kms = undefined;
var debug = (process.env['DEBUG'] === 'true');
var log_level = process.env['LOG_LEVEL'] || 'info';
const winston = require('winston');
const logger = winston.createLogger({
level : debug === true ? 'debug' : log_level,
transports : [ new winston.transports.Console({
format : winston.format.simple()
}) ]
});
var authContext = {
module : "AWSLambdaRedshiftLoader",
region : null
};
// module key alias to be used for this application
var moduleKeyName = "alias/LambdaRedshiftLoaderKey";
function setRegion(region) {
if (!region) {
useRegion = process.env['AWS_REGION'];
if (!useRegion) {
useRegion = 'us-east-1';
logger.info("AWS KMS using default region " + useRegion);
}
} else {
useRegion = region;
}
aws.config.update({
region : useRegion
});
kms = new aws.KMS({
apiVersion : '2014-11-01',
region : useRegion
});
authContext.region = useRegion;
};
exports.setRegion = setRegion;
/**
* Retrieves or creates the master key metadata for this module <br>
* Parameters:
* <li>callback(err,KeyMetadata) err - errors generated while getting or
* creating the key</li>
* <li>KeyMetadata - KMS Key Metadata including ID and ARN for this module's
* master key</li>
*/
function getOrCreateMasterKey(callback) {
kms.describeKey({
KeyId : moduleKeyName
}, function(err, data) {
if (err) {
if (err.code === 'InvalidArnException' || err.code === 'NotFoundException') {
// master key for the module doesn't exist, so
// create it
var createKeyParams = {
Description : "Lambda Redshift Loader Master Encryption Key",
KeyUsage : 'ENCRYPT_DECRYPT'
};
// create the master key for this module and
// bind an alias to it
kms.createKey(createKeyParams, function(err, createKeyData) {
if (err) {
logger.error("Error during Master Key creation");
return callback(err);
} else {
// create an alias for
// the master key
var createAliasParams = {
AliasName : moduleKeyName,
TargetKeyId : createKeyData.KeyMetadata.KeyId
};
kms.createAlias(createAliasParams, function(err, createAliasData) {
if (err) {
logger.error("Error during creation of Alias " + moduleKeyName + " for Master Key "
+ createKeyData.KeyMetadata.Arn);
return callback(err);
} else {
// invoke
// the
// callback
return callback(undefined, createKeyData.KeyMetadata);
}
});
}
});
} else {
// got an unknown error while describing the key
logger.info("Unknown Error during Customer Master Key describe");
return callback(err);
}
} else {
// ok - we got the previously generated key, so
// callback
return callback(undefined, data.KeyMetadata);
}
});
};
exports.getOrCreateMasterKey = getOrCreateMasterKey;
/**
* Function which encrypts a value using the module's master key <br>
* Parameters:
* <li>toEncrypt - value to be encrypted</li>
* <li>callback(err, encrypted) - function invoked once encryption is completed</li>
*/
function encrypt(toEncrypt, callback) {
// get the master key
getOrCreateMasterKey(function(err, keyMetadata) {
if (err) {
console.log("Error during resolution of Customer Master Key");
return callback(err);
} else {
// encrypt the data
var params = {
KeyId : keyMetadata.KeyId,
Plaintext : Buffer.from(toEncrypt),
EncryptionContext : authContext
};
kms.encrypt(params, function(err, encryptData) {
if (err) {
logger.error("Error during Encryption");
return callback(err);
} else {
return callback(undefined, encryptData.CiphertextBlob);
}
});
}
});
};
exports.encrypt = encrypt;
/**
* Function which does a blocking encryption of the array of values. Invokes the
* afterEncryption callback after all values in the input array have been
* encrypted<br>
* Parameters:
* <li>plaintextArray - Array of plaintext input values</li>
* <li>afterDecryptionCallback - function invoked once encryption has been
* completed</li>
*/
function encryptAll(plaintextArray, afterEncryptionCallback) {
async.map(plaintextArray, function(item, callback) {
// decrypt the value using internal decrypt
encrypt(item, function(err, ciphertext) {
return callback(err, ciphertext);
});
}, function(err, results) {
// call the after encryption callback with the result array
return afterEncryptionCallback(err, results);
});
};
exports.encryptAll = encryptAll;
function encryptMap(valueMap, afterEncryptionCallback) {
var encryptedValueMap = {};
async.each(Object.keys(valueMap), function(key, callback) {
encrypt(valueMap[key], function(err, ciphertext) {
if (err) {
callback(err);
} else {
encryptedValueMap[key] = ciphertext;
callback();
}
});
}, function(err) {
// call the after decryption callback with the result data
return afterEncryptionCallback(err, encryptedValueMap);
});
};
exports.encryptMap = encryptMap;
/**
* Function to decrypt a value using the module's master key<br>
* Parameters:
* <li>toDecrypt - value to be decrypted</li>
* <li>callback(err, decrypted) - Callback to be invoked after decryption which
* receives the decrypted value, and errors that were generated</li>
*/
function decrypt(encryptedCiphertext, callback) {
var params = {
CiphertextBlob : encryptedCiphertext,
EncryptionContext : authContext
};
kms.decrypt(params, function(err, decryptData) {
if (err) {
logger.error("Error during Decryption");
return callback(err);
} else {
if (!decryptData) {
logger.error("Failed to decrypt ciphertext");
return callback(undefined);
} else {
return callback(undefined, decryptData.Plaintext);
}
}
});
};
exports.decrypt = decrypt;
/**
* Function which does a blocking decryption of the array of values. Invokes the
* afterDecryption callback after all values in the input array have been
* decrypted<br>
* Parameters:
* <li>encryptedArray - Array of encrypted input values</li>
* <li>afterDecryptionCallback - function invoked once decryption has been
* completed</li>
*/
function decryptAll(encryptedArray, afterDecryptionCallback) {
async.map(encryptedArray, function(item, callback) {
// decrypt the value using internal decrypt
decrypt(item, function(err, plaintext) {
return callback(err, plaintext);
});
}, function(err, results) {
// call the after decryption callback with the result array
return afterDecryptionCallback(err, results);
});
};
exports.decryptAll = decryptAll;
function decryptMap(encryptedValueMap, afterDecryptionCallback) {
var decryptedValueMap = {};
async.each(Object.keys(encryptedValueMap), function(key, callback) {
// decrypt the value using internal decrypt
decrypt(encryptedValueMap[key], function(err, plaintext) {
if (err) {
logger.error(JSON.stringify(err));
callback(err);
} else {
decryptedValueMap[key] = plaintext;
callback();
}
});
}, function(err) {
// call the after decryption callback with the result data
return afterDecryptionCallback(err, decryptedValueMap);
});
};
exports.decryptMap = decryptMap;
function toLambdaStringFormat(buffer) {
return buffer.toString('base64');
};
exports.toLambdaStringFormat = toLambdaStringFormat;