-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
480 lines (419 loc) · 12.6 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
'use strict';
function getChildExecArgv() {
// Fix for forked process debugging.
function amIUnderDebug() {
const argv = process.execArgv.join();
return argv.includes('--inspect') || argv.includes('--debug');
}
if (!amIUnderDebug()) {
return process.execArgv;
}
return process.execArgv.map((val) => {
if (val.startsWith('--inspect-brk=')) {
return '--inspect-brk=0';
}
if (val.startsWith('--inspect=')) {
return '--inspect=0';
}
// If --inspect, or --inspect-brk - let it remain in execArgv.
if (val.startsWith('--inspect-port=')) {
return '--inspect-port=0';
}
return val;
});
}
const assert = require('assert');
const forge = require('node-forge');
const { fork } = require('child_process');
const crypto = require('crypto');
const alg = 'aes192';
const cipherPwd = 'asbySdfhbne2347sbns&6329dsbnkhqp3nny39';
/**
* AES encryption.
* @param {String} data - utf8 encoded string to encrypt.
* @returns {String} - base64 encoded encrypted string.
*/
function encrypt(data) {
const cipher = crypto.createCipher(alg, cipherPwd);
const encrypted = cipher.update(data, 'utf8', 'base64');
return encrypted + cipher.final('base64');
}
/**
* AES decryption.
* @param {String} data - base64 encoded encrypted string.
* @returns {String} - utf8 encoded decrypted string.
*/
function decrypt(data) {
const decipher = crypto.createDecipher(alg, cipherPwd);
const decrypted = decipher.update(data, 'base64', 'utf8');
return decrypted + decipher.final('utf8');
}
/**
* Default certificate parameters. You can change them.
*/
exports.certCfg = {
serialNumber: 1, // Is incremented during new certificates generation.
defaultPassphrase: 'Dbsh4_e',
minusDays: 2,
plusDays: 366,
keySize: 2048,
};
function checkCn(cn) {
assert(cn && (typeof cn === 'string'), 'No Common Name for certificate');
}
/**
* Generates RSA key pair.
* @return {Object} - RSA keypair: { privateKey, publicKey }
*/
exports.genKeyPair = function genKeyPair() {
const keyPair = crypto.generateKeyPairSync('rsa', {
modulusLength: exports.certCfg.keySize,
publicKeyEncoding: {
type: 'spki',
format: 'pem',
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
},
});
const forgeKeyPair = {};
forgeKeyPair.privateKey = forge.pki.privateKeyFromPem(keyPair.privateKey);
forgeKeyPair.publicKey = forge.pki.publicKeyFromPem(keyPair.publicKey);
return forgeKeyPair;
};
/**
* Generates 2048 bit, RSA key pair for SSH.
* @param {String} comment - a comment for public key.
* @param {String} [passPhrase] - a passphrase for private key.
*/
exports.genSSHKeyPair = function genSSHKeyPair(comment, passPhrase) {
const keyPair = exports.genKeyPair();
keyPair.publicKey = forge.ssh.publicKeyToOpenSSH(keyPair.publicKey, comment);
keyPair.privateKey = forge.ssh.privateKeyToOpenSSH(keyPair.privateKey, passPhrase);
return keyPair;
};
/**
* Convert a PEM-formatted private key to a PEM/OpenSSH -formatted public key.
* @param {String} privateKey - a PEM-formatted private key.
* @param {String} [passPhrase] - a passphrase for private key.
* @param {Object} [options] - Options
* @param {Boolean} [options.openssh] - format public key to OpenSSH format, default to PEM format
* @param {String} [options.comment] - a comment for public key in OpenSSH format.
*/
exports.privateKeyToPublicKey = function privateKeyToPublicKey(privateKey, passPhrase = '', options = {}) {
const retOpenSshFormat = Boolean(options.openssh);
const comment = options.comment;
const pkey = typeof passPhrase === 'string' && passPhrase
? forge.pki.decryptRsaPrivateKey(privateKey, passPhrase)
: forge.pki.privateKeyFromPem(privateKey);
// in case of wrong passPhrase decryptRsaPrivateKey will return null
if (!pkey) {
return null;
}
const publicKey = forge.pki.setRsaPublicKey(pkey.n, pkey.e);
return retOpenSshFormat
? forge.ssh.publicKeyToOpenSSH(publicKey, comment)
: forge.pki.publicKeyToPem(publicKey);
};
// Default attributes for certificate creation.
function getDefaultAttrs() {
return [{
name: 'countryName',
value: 'CH',
}, {
name: 'localityName',
value: 'Geneva',
}, {
name: 'organizationName',
value: 'Unique Organization',
}];
}
/**
* Generates self-signed certificate by cn.
* @param {String} cn - common name
*
* @param {String} [passPhrase] - pass phrase.
* Some inner pass phrase is used as default,
* so certificates with default pass phrase can be used only by this module API.
*
* @param {Array<Object>} [attrs] - three certificate attributes, like following:
* ```
* [{
name: 'countryName',
value: 'CH',
}, {
name: 'localityName',
value: 'Geneva',
}, {
name: 'organizationName',
value: 'Unuque Organization',
}]
```
* @returns {{cert: String, pfx: Buffer}}
*/
exports.genSSCert = function genSSCert(
cn,
passPhrase = exports.certCfg.defaultPassphrase,
attrs = getDefaultAttrs()
) {
checkCn(cn);
attrs.push({
name: 'commonName',
value: cn,
});
const keyPair = exports.genKeyPair();
const cert = forge.pki.createCertificate();
cert.serialNumber = (exports.certCfg.serialNumber++).toString();
cert.validity.notBefore = new Date();
cert.validity.notBefore.setDate(cert.validity.notBefore.getDate() - exports.certCfg.minusDays);
cert.validity.notAfter = new Date();
cert.validity.notAfter.setDate(cert.validity.notAfter.getDate() + exports.certCfg.plusDays);
cert.setSubject(attrs);
cert.setIssuer(attrs);
cert.publicKey = keyPair.publicKey;
cert.sign(keyPair.privateKey, forge.md.sha256.create());
const p12Asn1 = forge.pkcs12.toPkcs12Asn1(
keyPair.privateKey, cert, passPhrase/* , {algorithm: '3des'} */);
const p12Der = forge.asn1.toDer(p12Asn1).getBytes();
const buf = Buffer.from(forge.util.encode64(p12Der), 'base64');
return {
cert: forge.pki.certificateToPem(cert),
pfx: buf,
};
};
/**
* Extracts CN from a certificate.
*
* @param {String} cert
* @returns {String} CN of certificate.
*/
exports.getCertificateCn = function getCertificateCn(cert) {
const forgeCert = forge.pki.certificateFromPem(cert);
return forgeCert.subject.getField('CN').value;
};
/**
* Extracts Serial number from a certificate.
*
* @param {String} cert
* @returns {String} Serial number of certificate.
*/
exports.getCertificateSerNum = function getCertificateSerNum(cert) {
const forgeCert = forge.pki.certificateFromPem(cert);
return forgeCert.serialNumber;
};
// Array with certificate properties. Can be used for testing also.
exports.dataCertProps = [
'subjectCn',
'issuerCn',
'serialNumber',
'notAfter',
'notBefore',
];
/**
* Extracts data from certificate string or PFX buffer.
*
* @param {String | Buffer} certOrPfx - Certificate string or PFX Buffer.
* @returns
* {subjectCn: String, issuerCn: String, serialNumber: String, notBefore: Date, notAfter: Date}
* }
*/
exports.extractCertData = function extractCertData(
certOrPfx,
passPhrase = exports.certCfg.defaultPassphrase
) {
let forgeCert;
if (Buffer.isBuffer(certOrPfx)) {
const p12Der = forge.util.decode64(certOrPfx.toString('base64'));
const p12Asn1 = forge.asn1.fromDer(p12Der);
const p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1, passPhrase);
const bags = p12.getBags({ bagType: forge.pki.oids.certBag });
forgeCert = bags[forge.pki.oids.certBag][0].cert;
} else {
forgeCert = forge.pki.certificateFromPem(certOrPfx);
}
const data = {
subjectCn: forgeCert.subject.getField('CN').value,
issuerCn: forgeCert.issuer.getField('CN').value,
countryName: forgeCert.issuer.getField('C').value,
organizationName: forgeCert.issuer.getField('O').value,
serialNumber: forgeCert.serialNumber,
notBefore: forgeCert.validity.notBefore,
notAfter: forgeCert.validity.notAfter,
};
return data;
};
/**
* Checks fields passed in options object, plus 'notBefore', 'notAfter' fields.
* @param cert
* @param {Object} [options]
* @param {String} [options.subjectCn]
* @param {String} [options.issuerCn]
* @param {String} [options.serialNumber]
* @param {Boolean} [options.throwIfWrong]
*
* @returns {Object} with boolean check results for each requested field
* and for 'notBefore', 'notAfter' fields.
* @throws {Error} if options.throwIfWrong is used and some checking is wrong.
*/
exports.checkCertificate = function checkCertificate(cert, options = {}) {
const certData = exports.extractCertData(cert);
const curDate = new Date();
let totalRes = true;
const res = {};
let propName;
function handleErr() {
if (!res[propName]) {
if (options.throwIfWrong) {
throw new Error(`Error at checking: ${propName}`);
}
totalRes = false;
}
}
for (let i = 0; i < 3; i++) {
propName = exports.dataCertProps[i];
if (options[propName]) {
res[propName] = certData[propName] === options[propName];
handleErr();
}
}
propName = 'notBefore';
res[propName] = curDate >= certData[propName];
handleErr();
propName = 'notAfter';
res[propName] = curDate <= certData[propName];
handleErr();
res.totalRes = totalRes;
return res;
};
function asyncHelper(params) {
if (params.passPhrase) {
params.passPhrase = encrypt(params.passPhrase); // eslint-disable-line no-param-reassign
}
return new Promise((resolve, reject) => {
const child = fork(__filename, [], { execArgv: getChildExecArgv() });
child.send(params);
child.on('message', (msg) => {
resolve(msg);
});
child.on('error', (err) => {
reject(err);
});
});
}
/**
* Generates self signed certificate asynchronously, in separate process.
* @param {String} cn - common name
*
* @param {String} [passPhrase] - pass phrase.
* Some inner pass phrase is used as default,
* so certificates with default pass phrase can be used only by this module API.
*
* @param {Array<Object>} [attrs] - three certificate attributes, like following:
* ```
* [{
name: 'countryName',
value: 'CH',
}, {
name: 'localityName',
value: 'Geneva',
}, {
name: 'organizationName',
value: 'Unuque Organization',
}]
* @returns {Promise} Promise which is resolved to object
* {cert (String), pfx (String in base64)}.
*/
exports.genSSCertAsync = function genSSCertAsync(cn, passPhrase, attrs) {
checkCn(cn);
const params = {
cn,
func: 'genSSCert',
};
if (attrs) {
params.attrs = attrs;
}
return asyncHelper(params);
};
/**
* Generates 2048 bit, RSA key pair in a separate process.
*/
exports.genKeyPairAsync = function genKeyPairAsync() {
const params = {
func: 'genKeyPair',
};
return asyncHelper(params);
};
/**
* Generates 2048 bit, RSA key pair for SSH in a separate process.
* @param {String} comment - a comment for public key.
* @param {String} [passPhrase] - a passphrase for private key.
*/
exports.genSSHKeyPairAsync = function genSSHKeyPairAsync(comment, passPhrase) {
const params = {
func: 'genSSHKeyPair',
comment,
passPhrase,
};
return asyncHelper(params);
};
/**
* Convert a PEM-formatted private key to a PEM/OpenSSH -formatted public key.
* @param {String} privateKey - a PEM-formatted private key.
* @param {String} [passPhrase] - a passphrase for private key.
* @param {Object} [options] - Options
* @param {Boolean} [options.openssh] - format public key to OpenSSH format, default to PEM format
* @param {String} [options.comment] - a comment for public key in OpenSSH format.
*/
exports.privateKeyToPublicKeyAsync = function privateKeyToPublicKeyAsync(privateKey, passPhrase, options) {
const params = {
func: 'privateKeyToPublicKey',
privateKey,
passPhrase,
};
if (options) {
params.options = options;
}
return asyncHelper(params);
};
if (process.send) { // Child process.
process.on('message', (msg) => {
if (typeof msg === 'string') {
return;
}
const {
attrs,
cn,
comment,
func,
options,
privateKey,
} = msg;
let { passPhrase } = msg;
if (passPhrase) {
passPhrase = decrypt(passPhrase);
}
let res;
switch (func) {
case 'genKeyPair':
res = exports[func]();
break;
case 'genSSHKeyPair':
res = exports[func](comment, passPhrase);
break;
case 'genSSCert':
res = exports[func](cn, passPhrase, attrs);
res.pfx = res.pfx.toString('base64');
break;
case 'privateKeyToPublicKey':
res = exports[func](privateKey, passPhrase, options);
break;
default:
throw new Error('Unknown function in async call.');
}
process.send(res, () => {
// https://github.com/nodejs/node-v0.x-archive/issues/2605
process.exit();
});
});
}