forked from joegoldbeck/mongoose-encryption
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
603 lines (493 loc) · 18.9 KB
/
index.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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
'use strict';
(function () {
var crypto = require('crypto');
var _ = require('underscore');
var mongoose = require('mongoose');
var semver = require('semver')
var ObjectId = mongoose.Types.ObjectId;
var stableStringify = require('json-stable-stringify');
var async = require('async');
var dotty = require('dotty');
var bufferEqual = require('buffer-equal-constant-time');
var mpath = require('mpath');
// Constants //
var ENCRYPTION_ALGORITHM = 'aes-256-cbc';
var IV_LENGTH = 16;
var AAC_LENGTH = 32;
var VERSION_LENGTH = 1;
var VERSION = 'a';
var VERSION_BUF = new Buffer(VERSION);
// Utility Functions //
var isEmbeddedDocument = function (doc) {
return doc.constructor.name === 'EmbeddedDocument';
};
var isSingleNestedDocument = function(doc) {
return doc.$isSingleNested;
};
var getParentModelName = function(doc) {
return isSingleNestedDocument(doc) && doc.$parent.constructor.modelName || '';
};
var getDocumentModelName = function(doc) {
return doc.constructor.modelName || getParentModelName(doc);
};
var deriveKey = function (master, type) {
var hmac = crypto.createHmac('sha512', master);
hmac.update(type);
return new Buffer(hmac.digest());
};
var clearBuffer = function (buf) {
for (var i = 0; i < buf.length; i++) {
buf[i] = 0;
}
};
var drop256 = function (buf) {
var buf256 = new Buffer(32);
buf.copy(buf256, 0, 0, 32);
clearBuffer(buf);
return buf256;
};
var decryptEmbeddedDocs = function(doc) {
_.keys(doc.schema.paths).forEach(function(path) {
if (path === '_id' || path === '__v') {
return;
}
var nestedDoc = dotty.get(doc, path);
if (nestedDoc && nestedDoc[0] && isEmbeddedDocument(nestedDoc[0])) {
nestedDoc.forEach(function(subDoc) {
if (_.isFunction(subDoc.decryptSync)){
subDoc.decryptSync();
}
});
}
});
};
if(semver.gt(process.version, '4.0.0')){
if(semver.lt(mongoose.version, '4.2.4')){
throw new Error('Mongoose version 4.2.4 or greater is required for Node version 4.0.0 or greater');
}
}
// using mpath.set() for this would be nice
// but it does not create new objects as it traverses the path
var setFieldValue = function(obj, field, val) {
var parts = field.split('.');
var partsLen = parts.length;
var partRef = obj || {};
var i, part;
for (i = 0; i < partsLen; i++) {
part = parts[i];
if (i === partsLen - 1) {
partRef[part] = val;
} else {
partRef[part] = partRef[part] || {};
partRef = partRef[part];
}
}
return obj;
};
var pickFieldsFromObject = function(obj, fields, options) {
var result = {};
var val;
var options = options || {};
_.defaults(options, {
excludeUndefinedValues: false
});
fields.forEach(function(field) {
val = mpath.get(field, obj);
if (!options.excludeUndefinedValues || val !== undefined) {
setFieldValue(result, field, val);
}
});
return result;
};
// Exported Plugin //
var mongoosePlugin = module.exports = function(schema, options) {
var details, encryptedFields, excludedFields, authenticatedFields, encryptionKey, signingKey, path;
_.defaults(options, {
middleware: true, // allow for skipping middleware with false
requireAuthenticationCode: true, // allow for no authentication code on docs (not recommended),
decryptPostSave: true // allow for skipping the decryption after save for improved performance
});
// Encryption Keys //
if (options.secret) {
if (options.encryptionKey || options.signingKey) {
throw new Error('if options.secret is used, then options.encryptionKey and options.signingKey must not be included');
} else {
encryptionKey = drop256(deriveKey(options.secret, 'enc'));
signingKey = deriveKey(options.secret, 'sig');
}
} else {
if (!options.encryptionKey || !options.signingKey) {
throw new Error('must provide either options.secret or both options.encryptionKey and options.signingKey');
} else {
encryptionKey = new Buffer(options.encryptionKey, 'base64');
if (encryptionKey.length !== 32) {
throw new Error('options.encryptionKey must be a a 32 byte base64 string');
}
signingKey = new Buffer(options.signingKey, 'base64');
if (signingKey.length !== 64) {
throw new Error('options.signingKey must be a a 64 byte base64 string');
}
}
}
// Deprecated options
if (options.fields) {
options.encryptedFields = options.fields;
console.warn('options.fields has been deprecated. please use options.encryptedFields');
}
if (options.exclude) {
options.excludeFromEncryption = options.exclude;
console.warn('options.fields has been deprecated. please use options.excludeFromEncryption');
}
// Encryption Options //
if (options.encryptedFields) {
encryptedFields = _.difference(options.encryptedFields, ['_ct']);
} else {
excludedFields = _.union(['_id', '_ct'], options.excludeFromEncryption);
encryptedFields = _.chain(schema.paths)
.filter(function(pathDetails) { // exclude indexed fields
return !pathDetails._index
})
.pluck('path') // get path name
.difference(excludedFields) // exclude excluded fields
.uniq()
.value();
}
// Authentication Options //
var baselineAuthenticateFields = ['_id', '_ct'];
if (options.additionalAuthenticatedFields) {
authenticatedFields = _.union(options.additionalAuthenticatedFields, baselineAuthenticateFields);
} else {
authenticatedFields = baselineAuthenticateFields;
}
// Augment Schema //
if (!schema.paths._ct) { // ciphertext
schema.add({
_ct: {
type: Buffer
}
});
}
if (!schema.paths._ac) { // authentication code
schema.add({
_ac: {
type: Buffer
}
});
}
// Authentication Helper Functions //
var computeAC = function(doc, fields, version, modelName) {
// HMAC-SHA512-drop-256
var hmac = crypto.createHmac('sha512', signingKey);
if (!(fields instanceof Array)){
throw new Error('fields must be an array');
}
if (fields.indexOf('_id') === -1) {
throw new Error('_id must be in array of fields to authenticate');
}
if (fields.indexOf('_ac') !== -1) {
throw new Error('_ac cannot be in array of fields to authenticate');
}
var collectionId = options.collectionId || modelName || getDocumentModelName(doc);
if (!collectionId) {
throw new Error('For authentication, each collection must have a unique id. This is normally the model name when there is one, but can be overridden or added by options.collectionId');
}
// convert to regular object if possible in order to convert to the eventual mongo form which may be different than mongoose form
// and only pick fields that will be authenticated
var objectToAuthenticate = pickFieldsFromObject((doc.toObject ? doc.toObject() : doc), fields);
var stringToAuthenticate = stableStringify(objectToAuthenticate);
hmac.update(collectionId);
hmac.update(version);
hmac.update(stringToAuthenticate);
hmac.update(JSON.stringify(fields));
var fullAuthenticationBuffer = new Buffer(hmac.digest());
return drop256(fullAuthenticationBuffer);
};
// Functions To Check If Authenticated Fields Were Selected By Query //
var authenticationFieldsToCheck = _.chain(authenticatedFields).union(['_ac']).without('_id').value(); // _id is implicitly selected
var authenticatedFieldsIsSelected = function(doc){
return _.map(authenticationFieldsToCheck, function(field) {
return doc.isSelected(field);
});
};
var allAuthenticationFieldsSelected = function(doc){
var isSelected = authenticatedFieldsIsSelected(doc);
if (_.uniq(isSelected).length === 1){
return isSelected[0];
} else {
return false;
}
};
var noAuthenticationFieldsSelected = function(doc){
var isSelected = authenticatedFieldsIsSelected(doc);
if (_.uniq(isSelected).length === 1){
return isSelected[0] === false;
} else {
return false;
}
};
// Middleware //
if (options.middleware) { // defaults to true
schema.pre('init', function(next, data) {
var err = null;
try { // this hook must be synchronous for embedded docs, so everything is synchronous for code simplicity
if (!isEmbeddedDocument(this)){ // don't authenticate embedded docs because there's no way to handle the error appropriately
if (allAuthenticationFieldsSelected(this)) {
this.authenticateSync.call(data, getDocumentModelName(this));
} else {
if (!noAuthenticationFieldsSelected(this)){
throw new Error("Authentication failed: Only some authenticated fields were selected by the query. Either all or none of the authenticated fields (" + authenticationFieldsToCheck + ") should be selected for proper authentication.");
}
}
}
if (this.isSelected('_ct')){
this.decryptSync.call(data);
}
} catch (e) {
err = e;
}
if (isSingleNestedDocument(this) || isEmbeddedDocument(this)) {
if (err) {
console.error(err);
throw err; // note: this won't actually get thrown until save, because errors in subdoc init fns are CastErrors and aren't thrown by validate()
}
this._doc = data;
next();
return this;
} else {
return next(err);
}
});
schema.pre('save', function(next) {
var that = this;
if (this.isNew || this.isSelected('_ct') ){
that.encrypt(function(err){
if (err) {
next(err);
} else {
if ((that.isNew || allAuthenticationFieldsSelected(that)) && !isEmbeddedDocument(that)) {
_.forEach(authenticatedFields, function(authenticatedField){
that.markModified(authenticatedField)
});
that.sign(next);
} else {
next();
}
}
});
} else if (allAuthenticationFieldsSelected(this) && !isEmbeddedDocument(this)) { // _ct is not selected but all authenticated fields are. cannot get hit in current version.
_.forEach(authenticatedFields, function(authenticatedField){
that.markModified(authenticatedField)
});
this.sign(next);
} else {
next();
}
});
if (options.decryptPostSave) { // true by default
schema.post('save', function(doc) {
if (_.isFunction(doc.decryptSync)) {
doc.decryptSync();
}
// Until 3.8.6, Mongoose didn't trigger post save hook on EmbeddedDocuments,
// instead had to call decrypt on all subDocs.
// ref https://github.com/LearnBoost/mongoose/issues/915
decryptEmbeddedDocs(doc);
return doc;
});
}
}
// Encryption Instance Methods //
schema.methods.encrypt = function(cb) {
var that = this;
// generate random iv
crypto.randomBytes(IV_LENGTH, function(err, iv) {
var cipher, field, jsonToEncrypt, objectToEncrypt;
if (err) {
return cb(err);
}
cipher = crypto.createCipheriv(ENCRYPTION_ALGORITHM, encryptionKey, iv);
objectToEncrypt = pickFieldsFromObject(that, encryptedFields, {excludeUndefinedValues: true});
jsonToEncrypt = JSON.stringify(objectToEncrypt);
cipher.end(jsonToEncrypt, 'utf-8', function() {
// add ciphertext to document
that._ct = Buffer.concat([VERSION_BUF, iv, cipher.read()]);
// remove encrypted fields from cleartext
encryptedFields.forEach(function(field){
setFieldValue(that, field, undefined);
});
cb(null);
});
});
};
schema.methods.decrypt = function(cb) { // callback style but actually synchronous to allow for decryptSync without copypasta or complication
try {
schema.methods.decryptSync.call(this);
} catch(e){
return cb(e);
}
cb();
};
schema.methods.decryptSync = function() {
var that = this;
var ct, ctWithIV, decipher, iv, idString, decryptedObject, decryptedObjectJSON, decipheredVal;
if (this._ct) {
ctWithIV = this._ct.hasOwnProperty('buffer') ? this._ct.buffer : this._ct;
iv = ctWithIV.slice(VERSION_LENGTH, VERSION_LENGTH + IV_LENGTH);
ct = ctWithIV.slice(VERSION_LENGTH + IV_LENGTH, ctWithIV.length);
decipher = crypto.createDecipheriv(ENCRYPTION_ALGORITHM, encryptionKey, iv);
try {
decryptedObjectJSON = decipher.update(ct, undefined, 'utf8') + decipher.final('utf8');
decryptedObject = JSON.parse(decryptedObjectJSON);
} catch (err) {
if (this._id) {
idString = this._id.toString();
} else {
idString = 'unknown';
}
throw new Error('Error parsing JSON during decrypt of ' + idString + ': ' + err);
}
encryptedFields.forEach(function(field) {
decipheredVal = mpath.get(field, decryptedObject);
//JSON.parse returns {type: "Buffer", data: Buffer} for Buffers
//https://nodejs.org/api/buffer.html#buffer_buf_tojson
if(_.isObject(decipheredVal) && decipheredVal.type === "Buffer"){
setFieldValue(that, field, decipheredVal.data);
}else {
setFieldValue(that, field, decipheredVal);
}
});
this._ct = undefined;
this._ac = undefined;
}
};
// Authentication Instance Methods //
schema.methods.sign = function(cb) {
var basicAC = computeAC(this, authenticatedFields, VERSION);
var authenticatedFieldsBuf = new Buffer(JSON.stringify(authenticatedFields));
this._ac = Buffer.concat([VERSION_BUF, basicAC, authenticatedFieldsBuf]);
cb();
};
schema.methods.authenticate = function(cb) { // callback style but actually synchronous to allow for decryptSync without copypasta or complication
try {
schema.methods.authenticateSync.call(this);
} catch(e){
return cb(e);
}
cb();
};
schema.methods.authenticateSync = function() {
if (!this._ac) {
if (options.requireAuthenticationCode) {
throw new Error('Authentication code missing');
} else {
return null;
}
}
var acBuf = this._ac.hasOwnProperty('buffer') ? this._ac.buffer : this._ac;
if (acBuf.length < VERSION_LENGTH + AAC_LENGTH + 2) {
throw new Error('_ac is too short and has likely been cut off or modified');
}
var versionUsed = acBuf.slice(0, VERSION_LENGTH).toString();
var basicAC = acBuf.slice(VERSION_LENGTH, VERSION_LENGTH + AAC_LENGTH);
var authenticatedFieldsUsed = JSON.parse(acBuf.slice(VERSION_LENGTH + AAC_LENGTH, acBuf.length).toString());
var expectedHMAC = computeAC(this, authenticatedFieldsUsed, versionUsed, arguments[0]); // pass in modelName as argument in init hook
var authentic = bufferEqual(basicAC, expectedHMAC);
if (!authentic){
throw new Error('Authentication failed');
}
};
};
// Exports For Schemas That Contain Encrypted Embedded Documents
// this ensures that if parent has a validation error, children don't come out encrypted,
// which could otherwise cause data loss if validation error fixed and a resave was attempted
// For use in conjunction with the main encryption plugin
module.exports.encryptedChildren = function(schema, options) {
if (mongoose.version > '4.1.0') {
console.warn('encryptedChildren plugin is not needed for mongoose versions above 4.1.1, continuing without plugin.');
return;
}
schema.post('validate', function(doc) {
if (doc.errors) {
decryptEmbeddedDocs(doc);
}
});
};
module.exports.migrations = function(schema, options) {
options.middleware = false; // don't run middleware during the migration
mongoosePlugin(schema, options); // get all instance methods
schema.statics.migrateToA = function(cb) {
this.find({}, function(err, docs){ // find all docs in collection
if (err) {
return cb(err);
}
async.each(docs, function(doc, errCb){ // for each doc
if (doc._ac) { // don't migrate if already migrated
return errCb();
}
if (doc._ct) { // if previously encrypted
doc._ct = Buffer.concat([VERSION_BUF, doc._ct]); // append version to ciphertext
doc.sign(function(err){ // sign
if (err) {
return errCb(err);
}
return doc.save(errCb); // save
});
} else { // if not previously encrypted
doc.encrypt(function(err){ // encrypt
if (err) {
return errCb(err);
}
doc.sign(function(err){ // sign
if (err) {
return errCb(err);
}
return doc.save(errCb); // save
});
});
}
}, cb);
});
};
schema.statics.migrateSubDocsToA = function(subDocField, cb) {
if (typeof subDocField !== 'string'){
cb(new Error('First argument must be the name of a field in which subdocuments are stored'));
}
this.find({}, function(err, docs){ // find all docs in collection
if (err) {
return cb(err);
}
async.each(docs, function(doc, errCb){ // for each doc
if (doc[subDocField]) {
_.each(doc[subDocField], function(subDoc){ // for each subdoc
if (subDoc._ct) { // if previously encrypted
subDoc._ct = Buffer.concat([VERSION_BUF, subDoc._ct]); // append version to ciphertext
}
});
return doc.save(errCb); // save
} else {
errCb()
}
}, cb);
});
};
// sign all the documents in a collection
schema.statics.signAll = function(cb) {
this.find({}, function(err, docs){ // find all docs in collection
if (err) {
return cb(err);
}
async.each(docs, function(doc, errCb){ // for each doc
doc.sign(function(err){ // sign
if (err) {
return errCb(err);
}
doc.save(errCb); // save
});
}, cb);
});
};
};
// Exports For Tests //
module.exports.AAC_LENGTH = AAC_LENGTH;
module.exports.VERSION_LENGTH = VERSION_LENGTH;
}).call(this);