-
Notifications
You must be signed in to change notification settings - Fork 51
/
forge.js
445 lines (373 loc) · 11.7 KB
/
forge.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
/**
* node-forge crypto engine
*
* @namespace forge
*/
const net = require('net');
const Promise = require('bluebird');
const forge = require('node-forge');
const generateKeyPair = Promise.promisify(forge.pki.rsa.generateKeyPair);
/**
* Attempt to parse forge object from PEM encoded string
*
* @private
* @param {string} input PEM string
* @return {object}
*/
function forgeObjectFromPem(input) {
const msg = forge.pem.decode(input)[0];
let result;
switch (msg.type) {
case 'PRIVATE KEY':
case 'RSA PRIVATE KEY':
result = forge.pki.privateKeyFromPem(input);
break;
case 'PUBLIC KEY':
case 'RSA PUBLIC KEY':
result = forge.pki.publicKeyFromPem(input);
break;
case 'CERTIFICATE':
case 'X509 CERTIFICATE':
case 'TRUSTED CERTIFICATE':
result = forge.pki.certificateFromPem(input).publicKey;
break;
case 'CERTIFICATE REQUEST':
result = forge.pki.certificationRequestFromPem(input).publicKey;
break;
default:
throw new Error('Unable to detect forge message type');
}
return result;
}
/**
* Parse domain names from a certificate or CSR
*
* @private
* @param {object} obj Forge certificate or CSR
* @returns {object} {commonName, altNames}
*/
function parseDomains(obj) {
let commonName = null;
let altNames = [];
let altNamesDict = [];
const commonNameObject = (obj.subject.attributes || []).find((a) => a.name === 'commonName');
const rootAltNames = (obj.extensions || []).find((e) => 'altNames' in e);
const rootExtensions = (obj.attributes || []).find((a) => 'extensions' in a);
if (rootAltNames && rootAltNames.altNames && rootAltNames.altNames.length) {
altNamesDict = rootAltNames.altNames;
}
else if (rootExtensions && rootExtensions.extensions && rootExtensions.extensions.length) {
const extAltNames = rootExtensions.extensions.find((e) => 'altNames' in e);
if (extAltNames && extAltNames.altNames && extAltNames.altNames.length) {
altNamesDict = extAltNames.altNames;
}
}
if (commonNameObject) {
commonName = commonNameObject.value;
}
if (altNamesDict) {
altNames = altNamesDict.map((a) => a.value);
}
return {
commonName,
altNames
};
}
/**
* Generate a private RSA key
*
* @param {number} [size] Size of the key, default: `2048`
* @returns {Promise<buffer>} PEM encoded private RSA key
*
* @example Generate private RSA key
* ```js
* const privateKey = await acme.forge.createPrivateKey();
* ```
*
* @example Private RSA key with defined size
* ```js
* const privateKey = await acme.forge.createPrivateKey(4096);
* ```
*/
async function createPrivateKey(size = 2048) {
const keyPair = await generateKeyPair({ bits: size });
const pemKey = forge.pki.privateKeyToPem(keyPair.privateKey);
return Buffer.from(pemKey);
}
exports.createPrivateKey = createPrivateKey;
/**
* Create public key from a private RSA key
*
* @param {buffer|string} key PEM encoded private RSA key
* @returns {Promise<buffer>} PEM encoded public RSA key
*
* @example Create public key
* ```js
* const publicKey = await acme.forge.createPublicKey(privateKey);
* ```
*/
exports.createPublicKey = async function(key) {
const privateKey = forge.pki.privateKeyFromPem(key);
const publicKey = forge.pki.rsa.setPublicKey(privateKey.n, privateKey.e);
const pemKey = forge.pki.publicKeyToPem(publicKey);
return Buffer.from(pemKey);
};
/**
* Parse body of PEM encoded object form buffer or string
* If multiple objects are chained, the first body will be returned
*
* @param {buffer|string} str PEM encoded buffer or string
* @returns {string} PEM body
*/
exports.getPemBody = (str) => {
const msg = forge.pem.decode(str)[0];
return forge.util.encode64(msg.body);
};
/**
* Split chain of PEM encoded objects from buffer or string into array
*
* @param {buffer|string} str PEM encoded buffer or string
* @returns {string[]} Array of PEM bodies
*/
exports.splitPemChain = (str) => forge.pem.decode(str).map(forge.pem.encode);
/**
* Get modulus
*
* @param {buffer|string} input PEM encoded private key, certificate or CSR
* @returns {Promise<buffer>} Modulus
*
* @example Get modulus
* ```js
* const m1 = await acme.forge.getModulus(privateKey);
* const m2 = await acme.forge.getModulus(certificate);
* const m3 = await acme.forge.getModulus(certificateRequest);
* ```
*/
exports.getModulus = async function(input) {
if (!Buffer.isBuffer(input)) {
input = Buffer.from(input);
}
const obj = forgeObjectFromPem(input);
return Buffer.from(forge.util.hexToBytes(obj.n.toString(16)), 'binary');
};
/**
* Get public exponent
*
* @param {buffer|string} input PEM encoded private key, certificate or CSR
* @returns {Promise<buffer>} Exponent
*
* @example Get public exponent
* ```js
* const e1 = await acme.forge.getPublicExponent(privateKey);
* const e2 = await acme.forge.getPublicExponent(certificate);
* const e3 = await acme.forge.getPublicExponent(certificateRequest);
* ```
*/
exports.getPublicExponent = async function(input) {
if (!Buffer.isBuffer(input)) {
input = Buffer.from(input);
}
const obj = forgeObjectFromPem(input);
return Buffer.from(forge.util.hexToBytes(obj.e.toString(16)), 'binary');
};
/**
* Read domains from a Certificate Signing Request
*
* @param {buffer|string} csr PEM encoded Certificate Signing Request
* @returns {Promise<object>} {commonName, altNames}
*
* @example Read Certificate Signing Request domains
* ```js
* const { commonName, altNames } = await acme.forge.readCsrDomains(certificateRequest);
*
* console.log(`Common name: ${commonName}`);
* console.log(`Alt names: ${altNames.join(', ')}`);
* ```
*/
exports.readCsrDomains = async function(csr) {
if (!Buffer.isBuffer(csr)) {
csr = Buffer.from(csr);
}
const obj = forge.pki.certificationRequestFromPem(csr);
return parseDomains(obj);
};
/**
* Read information from a certificate
*
* @param {buffer|string} cert PEM encoded certificate
* @returns {Promise<object>} Certificate info
*
* @example Read certificate information
* ```js
* const info = await acme.forge.readCertificateInfo(certificate);
* const { commonName, altNames } = info.domains;
*
* console.log(`Not after: ${info.notAfter}`);
* console.log(`Not before: ${info.notBefore}`);
*
* console.log(`Common name: ${commonName}`);
* console.log(`Alt names: ${altNames.join(', ')}`);
* ```
*/
exports.readCertificateInfo = async function(cert) {
if (!Buffer.isBuffer(cert)) {
cert = Buffer.from(cert);
}
const obj = forge.pki.certificateFromPem(cert);
const issuerCn = (obj.issuer.attributes || []).find((a) => a.name === 'commonName');
return {
issuer: {
commonName: issuerCn ? issuerCn.value : null
},
domains: parseDomains(obj),
notAfter: obj.validity.notAfter,
notBefore: obj.validity.notBefore
};
};
/**
* Determine ASN.1 type for CSR subject short name
* Note: https://tools.ietf.org/html/rfc5280
*
* @private
* @param {string} shortName CSR subject short name
* @returns {forge.asn1.Type} ASN.1 type
*/
function getCsrValueTagClass(shortName) {
switch (shortName) {
case 'C':
return forge.asn1.Type.PRINTABLESTRING;
case 'E':
return forge.asn1.Type.IA5STRING;
default:
return forge.asn1.Type.UTF8;
}
}
/**
* Create array of short names and values for Certificate Signing Request subjects
*
* @private
* @param {object} subjectObj Key-value of short names and values
* @returns {object[]} Certificate Signing Request subject array
*/
function createCsrSubject(subjectObj) {
return Object.entries(subjectObj).reduce((result, [shortName, value]) => {
if (value) {
const valueTagClass = getCsrValueTagClass(shortName);
result.push({ shortName, value, valueTagClass });
}
return result;
}, []);
}
/**
* Create array of alt names for Certificate Signing Requests
* Note: https://github.com/digitalbazaar/forge/blob/dfdde475677a8a25c851e33e8f81dca60d90cfb9/lib/x509.js#L1444-L1454
*
* @private
* @param {string[]} altNames Alt names
* @returns {object[]} Certificate Signing Request alt names array
*/
function formatCsrAltNames(altNames) {
return altNames.map((value) => {
const type = net.isIP(value) ? 7 : 2;
return { type, value };
});
}
/**
* Create a Certificate Signing Request
*
* @param {object} data
* @param {number} [data.keySize] Size of newly created private key, default: `2048`
* @param {string} [data.commonName]
* @param {array} [data.altNames] default: `[]`
* @param {string} [data.country]
* @param {string} [data.state]
* @param {string} [data.locality]
* @param {string} [data.organization]
* @param {string} [data.organizationUnit]
* @param {string} [data.emailAddress]
* @param {buffer|string} [key] CSR private key
* @returns {Promise<buffer[]>} [privateKey, certificateSigningRequest]
*
* @example Create a Certificate Signing Request
* ```js
* const [certificateKey, certificateRequest] = await acme.forge.createCsr({
* commonName: 'test.example.com'
* });
* ```
*
* @example Certificate Signing Request with both common and alternative names
* ```js
* const [certificateKey, certificateRequest] = await acme.forge.createCsr({
* keySize: 4096,
* commonName: 'test.example.com',
* altNames: ['foo.example.com', 'bar.example.com']
* });
* ```
*
* @example Certificate Signing Request with additional information
* ```js
* const [certificateKey, certificateRequest] = await acme.forge.createCsr({
* commonName: 'test.example.com',
* country: 'US',
* state: 'California',
* locality: 'Los Angeles',
* organization: 'The Company Inc.',
* organizationUnit: 'IT Department',
* emailAddress: 'contact@example.com'
* });
* ```
*
* @example Certificate Signing Request with predefined private key
* ```js
* const certificateKey = await acme.forge.createPrivateKey();
*
* const [, certificateRequest] = await acme.forge.createCsr({
* commonName: 'test.example.com'
* }, certificateKey);
*/
exports.createCsr = async function(data, key = null) {
if (!key) {
key = await createPrivateKey(data.keySize);
}
else if (!Buffer.isBuffer(key)) {
key = Buffer.from(key);
}
if (typeof data.altNames === 'undefined') {
data.altNames = [];
}
const csr = forge.pki.createCertificationRequest();
/* Public key */
const privateKey = forge.pki.privateKeyFromPem(key);
const publicKey = forge.pki.rsa.setPublicKey(privateKey.n, privateKey.e);
csr.publicKey = publicKey;
/* Ensure subject common name is present in SAN - https://cabforum.org/wp-content/uploads/BRv1.2.3.pdf */
if (data.commonName && !data.altNames.includes(data.commonName)) {
data.altNames.unshift(data.commonName);
}
/* Subject */
const subject = createCsrSubject({
CN: data.commonName,
C: data.country,
ST: data.state,
L: data.locality,
O: data.organization,
OU: data.organizationUnit,
E: data.emailAddress
});
csr.setSubject(subject);
/* SAN extension */
if (data.altNames.length) {
csr.setAttributes([{
name: 'extensionRequest',
extensions: [{
name: 'subjectAltName',
altNames: formatCsrAltNames(data.altNames)
}]
}]);
}
/* Sign CSR */
csr.sign(privateKey);
/* Done */
const pemCsr = forge.pki.certificationRequestToPem(csr);
return [key, Buffer.from(pemCsr)];
};