-
Notifications
You must be signed in to change notification settings - Fork 9
/
fipsrypto.js
502 lines (461 loc) · 15.3 KB
/
fipsrypto.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
"use strict";
const base32 = require('rfc4648').base32;
const base64url = require('rfc4648').base64url;
const Backend = require('../contract/backend');
const Constants = require('../constants');
const crypto = require('crypto');
const fs = require('fs-extra');
const SodiumPlus = require('sodium-plus').SodiumPlus;
const Util = require('../util');
const SymmetricKey = require('./key/symmetrickey');
const CryptoOperationException = require('../exception/cryptooperationexception');
let sodium;
const MAGIC_HEADER = "fips:";
const MAC_SIZE = 48;
const SALT_SIZE = 32;
const NONCE_SIZE = 16;
/**
* Class FIPSCrypto
*
* This only uses algorithms supported by FIPS-140-2.
*
* Please consult your FIPS compliance auditor before you claim that your use
* of this library is FIPS 140-2 compliant.
*
* @ref https://csrc.nist.gov/CSRC/media//Publications/fips/140/2/final/documents/fips1402annexa.pdf
* @ref https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38a.pdf
* @ref https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf
*
* @package CipherSweet.backend
* @author Paragon Initiative Enterprises
*/
module.exports = class FIPSCrypto extends Backend
{
/**
* AES-256-CTR encrypt
*
* @param {Buffer} plaintext
* @param {Buffer} key
* @param {Buffer} nonce
* @return {Buffer}
*/
async aes256ctr(plaintext, key, nonce)
{
let ciphertext;
let cipher = crypto.createCipheriv('aes-256-ctr', key, nonce);
ciphertext = cipher.update(plaintext);
cipher.final();
return ciphertext;
}
/**
*
* @param {string|Buffer} plaintext
* @param {SymmetricKey} key
* @param {string|Buffer} aad
*/
async encrypt(plaintext, key, aad = '')
{
if (!sodium) sodium = await SodiumPlus.auto();
if (!Buffer.isBuffer(plaintext)) {
plaintext = await Util.toBuffer(plaintext);
}
let hkdfSalt = await Util.randomBytes(SALT_SIZE);
let encKey = await Util.HKDF(key, hkdfSalt, 'AES-256-CTR');
let macKey = await Util.HKDF(key, hkdfSalt, 'HMAC-SHA-384');
let ctrNonce = await Util.randomBytes(NONCE_SIZE);
let ciphertext = await this.aes256ctr(plaintext, encKey, ctrNonce);
await sodium.sodium_memzero(encKey);
let mac;
if (aad.length > 0) {
mac = await Util.hmac(
'sha384',
Buffer.concat([
Util.pack([
Buffer.from(MAGIC_HEADER, 'binary'),
hkdfSalt,
ctrNonce,
ciphertext
]),
Buffer.from(aad)
]),
macKey,
true
);
} else {
mac = await Util.hmac(
'sha384',
Util.pack([
Buffer.from(MAGIC_HEADER, 'binary'),
hkdfSalt,
ctrNonce,
ciphertext
]),
macKey,
true
);
}
await sodium.sodium_memzero(macKey);
return MAGIC_HEADER + base64url.stringify(
Buffer.concat([
hkdfSalt,
ctrNonce,
mac,
ciphertext
])
);
}
/**
*
* @param {string|Buffer} ciphertext
* @param {SymmetricKey} key
* @param {string|Buffer} aad
* @return {string}
*/
async decrypt(ciphertext, key, aad = '')
{
if (!sodium) sodium = await SodiumPlus.auto();
let header = ciphertext.slice(0, 5);
if (!await Util.hashEquals(MAGIC_HEADER, header)) {
throw new CryptoOperationException('Invalid ciphertext header.');
}
let decoded = await Util.toBuffer(base64url.parse(ciphertext.slice(5)));
let hkdfSalt = decoded.slice(0, SALT_SIZE);
let ctrNonce = decoded.slice(
SALT_SIZE,
SALT_SIZE + NONCE_SIZE
);
let mac = decoded.slice(
SALT_SIZE + NONCE_SIZE,
SALT_SIZE + NONCE_SIZE + MAC_SIZE
);
let cipher = decoded.slice(SALT_SIZE + NONCE_SIZE + MAC_SIZE);
let macKey = await Util.HKDF(key, hkdfSalt, 'HMAC-SHA-384');
let recalc;
if (aad.length > 0) {
recalc = await Util.hmac(
'sha384',
Buffer.concat([
Util.pack([
Buffer.from(MAGIC_HEADER, 'binary'),
hkdfSalt,
ctrNonce,
cipher
]),
Buffer.from(aad)
]),
macKey,
true
);
} else {
recalc = await Util.hmac(
'sha384',
Util.pack([
Buffer.from(MAGIC_HEADER, 'binary'),
hkdfSalt,
ctrNonce,
cipher
]),
macKey,
true
);
}
if (!await Util.hashEquals(recalc, mac)) {
await sodium.sodium_memzero(macKey);
throw new CryptoOperationException('Invalid MAC');
}
let encKey = await Util.HKDF(key, hkdfSalt, 'AES-256-CTR');
let plaintext = await this.aes256ctr(cipher, encKey, ctrNonce);
await sodium.sodium_memzero(encKey);
return plaintext.toString('binary');
}
/**
* Perform a fast blind index. Ideal for high-entropy inputs.
* Algorithm: PBKDF2-SHA384 with only 1 iteration.
*
* @param {string|Buffer} plaintext
* @param {SymmetricKey} key
* @param {Number} length
* @param {object} config
* @return {Buffer}
*/
async blindIndexFast(plaintext, key, length = 256, config = [])
{
let ikm;
if (Buffer.isBuffer(key)) {
ikm = key;
} else if (SymmetricKey.isSymmetricKey(key)) {
ikm = key.getRawKey();
} else {
throw new TypeError('Argument 1 must be a SymmetricKey');
}
return Util.andMask(
crypto.pbkdf2Sync(plaintext, ikm, 1, length >>> 3, 'sha384'),
length
);
}
/**
* Perform a slower Blind Index calculation.
* Algorithm: PBKDF2-SHA384 with at least 50,000 iterations.
*
* @param {string|Buffer} plaintext
* @param {SymmetricKey} key
* @param {Number} length
* @param {object} config
* @return {Buffer}
*/
async blindIndexSlow(plaintext, key, length = 256, config = [])
{
let ikm;
if (Buffer.isBuffer(key)) {
ikm = key;
} else if (SymmetricKey.isSymmetricKey(key)) {
ikm = key.getRawKey();
} else {
throw new TypeError('Argument 1 must be a SymmetricKey');
}
let iterations = 50000;
if (typeof config['iterations'] !== 'undefined') {
if (config['iterations'] > 50000) {
iterations = config['iterations'];
}
}
plaintext = await Util.toBuffer(plaintext);
return await Util.pbkdf2(plaintext, ikm, iterations, length >>> 3, 'sha384')
.then((input) => {
return Util.andMask(input, length);
}
);
}
/**
*
* @param {string|Buffer} tableName
* @param {string|Buffer} fieldName
* @param {string|Buffer} indexName
* @return {string}
*/
async getIndexTypeColumn(tableName, fieldName, indexName)
{
let hash = await Util.hmac(
'sha384',
Util.pack([
await Util.toBuffer(fieldName),
await Util.toBuffer(indexName)
]),
tableName,
true
);
return base32.stringify(hash.slice(0, 8))
.toLowerCase()
.replace(/=+$/, '');
}
/**
* @returns {string}
*/
getPrefix()
{
return MAGIC_HEADER;
}
/**
* @param {string|Buffer} password
* @param {string|Buffer} salt
*/
async deriveKeyFromPassword(password, salt)
{
return new SymmetricKey(
await Util.pbkdf2(
password,
salt,
100000,
32,
'sha384'
)
);
}
/**
*
* @param {number} inputFP
* @param {number} outputFP
* @param {SymmetricKey} key
* @param {number} chunkSize
* @return {Promise<boolean>}
*/
async doStreamDecrypt(
inputFP,
outputFP,
key,
chunkSize = 8192
) {
if (!sodium) sodium = await SodiumPlus.auto();
let header = Buffer.alloc(5, 0);
let storedMAC = Buffer.alloc(48, 0);
let salt = Buffer.alloc(16, 0); // pbkdf2
let hkdfSalt = Buffer.alloc(32, 0); // HKDF
let ctrNonce = Buffer.alloc(16, 0);
let inputFileSize = (await fs.fstat(inputFP)).size;
if (inputFileSize < 5) {
throw new CryptoOperationException('Input file is empty');
}
await fs.read(inputFP, header, 0, 5);
if (!await Util.hashEquals(MAGIC_HEADER, header)) {
throw new CryptoOperationException('Invalid cipher backend for this file');
}
await fs.read(inputFP, storedMAC, 0, 48, 5);
await fs.read(inputFP, salt, 0, 16, 53);
await fs.read(inputFP, hkdfSalt, 0, 32, 69);
await fs.read(inputFP, ctrNonce, 0, 16, 101);
let encKey = await Util.HKDF(key, hkdfSalt, 'AES-256-CTR');
let macKey = await Util.HKDF(key, hkdfSalt, 'HMAC-SHA-384');
let hmac = crypto.createHmac('sha384', macKey);
hmac.update(MAGIC_HEADER);
hmac.update(salt);
hmac.update(hkdfSalt);
hmac.update(ctrNonce);
// Chunk HMAC
let cHmac = crypto.createHmac('sha384', macKey);
cHmac.update(MAGIC_HEADER);
cHmac.update(salt);
cHmac.update(hkdfSalt);
cHmac.update(ctrNonce);
let ctrIncrease = (chunkSize + 15) >>> 4;
let outPos = 0;
let inPos = 117;
let toRead = chunkSize;
let plaintext;
let ciphertext = Buffer.alloc(chunkSize, 0);
// First, validate the HMAC of the ciphertext. We're storing the MAC of each chunk
// in memory, as well.
let thisChunkMac;
let chunkMacs = [];
do {
toRead = (inPos + chunkSize > inputFileSize)
? (inputFileSize - inPos)
: chunkSize;
await fs.read(inputFP, ciphertext, 0, toRead, inPos);
hmac.update(ciphertext.slice(0, toRead));
// Append chunk MAC for TOCTOU protection
cHmac.update(ciphertext.slice(0, toRead));
thisChunkMac = cHmac.digest();
chunkMacs.push(thisChunkMac);
cHmac = crypto.createHmac('sha384', macKey);
cHmac.update(thisChunkMac);
outPos += toRead;
inPos += toRead;
} while (inPos < inputFileSize);
let calcMAC = hmac.digest();
if (!await Util.hashEquals(calcMAC, storedMAC)) {
throw new CryptoOperationException('Invalid authentication tag');
}
thisChunkMac = cHmac.digest();
chunkMacs.push(thisChunkMac);
cHmac = crypto.createHmac('sha384', macKey);
cHmac.update(MAGIC_HEADER);
cHmac.update(salt);
cHmac.update(hkdfSalt);
cHmac.update(ctrNonce);
outPos = 0;
inPos = 117;
toRead = chunkSize;
let shifted;
do {
toRead = (inPos + chunkSize > inputFileSize)
? (inputFileSize - inPos)
: chunkSize;
await fs.read(inputFP, ciphertext, 0, toRead, inPos);
cHmac.update(ciphertext.slice(0, toRead));
thisChunkMac = cHmac.digest();
shifted = chunkMacs.shift();
if (typeof (shifted) === 'undefined') {
throw new CryptoOperationException('TOCTOU + truncation attack');
}
if (!await Util.hashEquals(thisChunkMac, shifted)) {
throw new CryptoOperationException('TOCTOU + chosen ciphertext attack');
}
// Reinitialize
cHmac = crypto.createHmac('sha384', macKey);
cHmac.update(thisChunkMac);
plaintext = await this.aes256ctr(
ciphertext.slice(0, toRead),
encKey,
ctrNonce
);
await fs.write(outputFP, plaintext);
ctrNonce = await Util.increaseCtrNonce(ctrNonce, ctrIncrease);
outPos += toRead;
inPos += toRead;
} while (inPos < inputFileSize);
await sodium.sodium_memzero(macKey);
await sodium.sodium_memzero(encKey);
return true;
}
/**
*
* @param {number} inputFP
* @param {number} outputFP
* @param {SymmetricKey} key
* @param {number} chunkSize
* @param {Buffer} salt
* @return {Promise<boolean>}
*/
async doStreamEncrypt(
inputFP,
outputFP,
key,
chunkSize = 8192,
salt = Constants.DUMMY_SALT
) {
if (!sodium) sodium = await SodiumPlus.auto();
let hkdfSalt = await Util.randomBytes(SALT_SIZE);
let ctrNonce = await Util.randomBytes(NONCE_SIZE);
let encKey = await Util.HKDF(key, hkdfSalt, 'AES-256-CTR');
let macKey = await Util.HKDF(key, hkdfSalt, 'HMAC-SHA-384');
await fs.write(outputFP, await Util.toBuffer(MAGIC_HEADER), 0, 5);
// Empty space for MAC
await fs.write(outputFP, Buffer.alloc(48, 0), 0, 48, 5);
await fs.write(outputFP, salt, 0, 16, 53); // pwhash salt
await fs.write(outputFP, hkdfSalt, 0, 32, 69); // hkdf salt
await fs.write(outputFP, ctrNonce, 0, 16, 101);
// Init MAC state
let hmac = crypto.createHmac('sha384', macKey);
await sodium.sodium_memzero(macKey);
hmac.update(MAGIC_HEADER);
hmac.update(salt);
hmac.update(hkdfSalt);
hmac.update(ctrNonce);
// We want to increase our CTR value by the number of blocks we used previously
let ctrIncrease = (chunkSize + 15) >>> 4;
let inputFileSize = (await fs.fstat(inputFP)).size;
let outPos = 117;
let inPos = 0;
let toRead = chunkSize;
let plaintext = Buffer.alloc(chunkSize, 0);
let ciphertext;
do {
toRead = (inPos + chunkSize > inputFileSize)
? (inputFileSize - inPos)
: chunkSize;
await fs.read(inputFP, plaintext, 0, toRead, inPos);
ciphertext = await this.aes256ctr(
plaintext.slice(0, toRead),
encKey,
ctrNonce
);
hmac.update(ciphertext);
await fs.write(outputFP, ciphertext, 0, toRead, outPos);
ctrNonce = await Util.increaseCtrNonce(ctrNonce, ctrIncrease);
outPos += toRead;
inPos += toRead;
} while (inPos < inputFileSize);
await sodium.sodium_memzero(encKey);
let storedMAC = hmac.digest();
// Write the MAC at the beginning of the file.
await fs.write(outputFP, storedMAC, 0, 48, 5);
return true;
}
/**
* @return {number}
*/
getFileEncryptionSaltOffset()
{
return 53;
}
};