-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathssl.js
482 lines (411 loc) · 19.2 KB
/
ssl.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
// SSL binary wrapper in pure JS
// Copyright (c) 2012-present Tom Zhou<[email protected]>
//
'use strict';
var debug = require('debug')('ssl');
var _ = require('lodash');
var IPADDR = require('ipaddr.js');
var fs = require('fs');
var NET = require('net');
const { exec } = require('child_process');
// Debug level
var Debug = 0;
// Generate self-signed cert
// - openssl genrsa -out server-key.pem 2048
// - openssl req -new -key server-key.pem -out server-csr.pem
// - openssl x509 -req -in server-csr.pem -signkey server-key.pem -out server-cert.pem
//
// Or prefer in single line: http://www.madboa.com/geek/openssl/#cert-self
// openssl req -x509 -nodes -days 365 -subj '/C=CN/ST=SH/L=SH/CN=51dese.com' -newkey rsa:2048 -keyout server-key.pem -out server-cert.pem
// Or create self-signed wildcard ssl certificate
// - http://security.stackexchange.com/questions/10538/what-certificates-are-needed-for-multi-level-subdomains
// -
var genSslCert = exports.genSslCert = function(filename, info, fn){
// check parameter
if (typeof info === 'function') {
fn = info;
info = {};
info.cn = '51dese.com';
}
if (!info.cn) {
info.cn = '51dese.com';
}
filename += info.cn;
filename = filename.replace('*', 'x');
debug('genSslCert info: ' + JSON.stringify(info));
// SSL CA cert generate with retry
function genCert(filename, info, fn) {
// construct openssl CLI arguments
var clistr = '', cliarg = ['req', '-x509', '-nodes'];
// duration
if (info.days) {
cliarg.push('-days');
cliarg.push(info.days);
} else {
cliarg.push('-days');
cliarg.push('365');
}
// subject
cliarg.push('-subj');
cliarg.push('/C=CN/ST=SH/L=SH/CN='+info.cn);
// -newkey rsa:2048
cliarg.push('-newkey');
cliarg.push('rsa:2048');
// output
cliarg.push('-keyout');
cliarg.push(__dirname+'/certs-tmp/'+filename+'-key.pem');
cliarg.push('-out');
cliarg.push(__dirname+'/certs-tmp/'+filename+'-cert.pem');
// V3 extension, subject alternate name
// !!! count CN into altnames due to latest openssl not take CN field
info.altname = info.altname || []; info.altname.push(info.cn);
if (info.altname && info.altname.length) {
// remove duplicates
info.altname = _.uniq(info.altname, function(v) {if (6 === NET.isIP(v)) return IPADDR.parse(v).toString(); else return v;});
debug('client altnames: '+info.altname);
// -extensions v3_req
cliarg.push('-extensions');
cliarg.push('v3_req');
// create ssl.conf
var v3_conf = '[req] \n';
v3_conf += ' req_extensions = v3_req \n\n';
v3_conf += ' [ v3_req ] \n';
v3_conf += ' basicConstraints = CA:FALSE \n';
v3_conf += ' keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment \n';
v3_conf += ' subjectAltName = @alt_names \n\n';
// like
// [alt_names]
// DNS.1 = ns3.dns.com
// ...
// IP.1 = 192.168.1.84
// ...
var ips = [], dns = [];
v3_conf += ' [alt_names] \n';
for (var idx = 0; idx < info.altname.length; idx ++) {
var name = info.altname[idx];
if (NET.isIP(name)) {
ips.push(name);
} else {
dns.push(name);
}
}
for (var idx = 0; idx < ips.length; idx++) {
v3_conf += ' IP.' + idx + ' = ' + ips[idx] + '\n';
}
for (var idx = 0; idx < dns.length; idx ++) {
v3_conf += ' DNS.'+ idx + ' = '+dns[idx]+'\n';
}
v3_conf += '\n';
// create file
try {
fs.writeFileSync(__dirname+'/certs-tmp/'+filename+'-v3.conf', v3_conf);
} catch (e) {
console.error('Warning!s3 syncWrite V3 conf file failed ' + e);
fn('Warning!s3 syncWrite V3 conf file failed ' + e);
return;
}
// -extfile
cliarg.push('-extfile');
cliarg.push(__dirname+'/certs-tmp/'+filename+'-v3.conf');
}
clistr = 'openssl '+cliarg.join(' ');
debug('s1 cli: '+clistr);
var s1 = exec(clistr, {maxBuffer: 200*1024}, function(err, stdout, stderr){
if (err) {
console.error('Warning!s1 openssl process exited with error ' + err + stderr);
fn('Warning!s1 openssl process exited with error ' + err + stderr);
} else {
try {
fn(null, {
key: fs.readFileSync(__dirname+'/certs-tmp/'+filename+'-key.pem').toString(),
cert: fs.readFileSync(__dirname+'/certs-tmp/'+filename+'-cert.pem').toString()
});
// destroy certs
fs.unlinkSync(__dirname+'/certs-tmp/'+filename+'-key.pem');
fs.unlinkSync(__dirname+'/certs-tmp/'+filename+'-cert.pem');
} catch (e) {
console.error('Warning!open certs file failure:'+e);
fn('Warning!open certs file failure:'+e);
}
}
});
}
// retry 3 times
var retry = 0;
(function regenCert(){
genCert(filename, info, function(err, cert){
if (err) {
if (retry < 3) {
// delay regen
setTimeout(function(){
retry ++;
regenCert();
}, 1000); // 1s delay
} else {
// pass error
fn('ssl certgen failed');
}
} else {
// pass cert
fn(null, cert);
}
})
})();
};
// Generate CA-signed cert
// - openssl genrsa -out server-key.pem 2048
// - openssl req -new -key server-key.pem -subj '/C=CN/ST=SH/L=SH/CN=51dese.com' -out server-csr.pem
// - openssl x509 -req -days 730 -CA ca-cert.pem -CAkey ca-key.pem -CAcreateserial -in server-csr.pem -out server-cert.pem -extensions v3_req -extfile openssl.cnf
// -
// - http://blog.didierstevens.com/2008/12/30/howto-make-your-own-cert-with-openssl/
// -- CA root cert:
// --- openssl genrsa -out ca-key.pem 4096
// --- openssl req -new -x509 -days 1868 -subj '/C=CN/ST=SH/L=SH/CN=51dese.com' -key ca-key.pem -out ca-cert.pem
// --
// -- server cert:
// --- openssl genrsa -out ia.key 2048
// --- openssl req -new -key ia.key -subj '/C=CN/ST=SH/L=SH/CN=xxx.com' -out ia.csr
// --- openssl x509 -req -days 730 -in ia.csr -CA ca.crt -CAkey ca.key -set_serial 01 -out ia.crt
// --- To use this subordinate CA key for Authenticode signatures with Microsoft¡¯s signtool, you¡¯ll have to package the keys and certs in a PKCS12 file:
// ---- openssl pkcs12 -export -out ia.p12 -inkey ia.key -in ia.crt -chain -CAfile ca.crt
// --
// --- V3 extension
// ---- http://blog.csdn.net/marujunyy/article/details/8477854
// ---- http://apetec.com/support/GenerateSAN-CSR.htm
// ---- http://blog.endpoint.com/2013/10/ssl-certificate-sans-and-multi-level.html
// ---- like san.conf
/*
[req]
distinguished_name = req_distinguished_name
req_extensions = v3_req
[req_distinguished_name]
countryName = Country Name (2 letter code)
countryName_default = CN
stateOrProvinceName = State or Province Name (full name)
stateOrProvinceName_default = BeiJing
localityName = Locality Name (eg, city)
localityName_default = YaYunCun
organizationalUnitName = Organizational Unit Name (eg, section)
organizationalUnitName_default = Domain Control Validated
commonName = Internet Widgits Ltd
commonName_max = 64
[ v3_req ]
# Extensions to add to a certificate request
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = ns1.dns.com
DNS.2 = ns2.dns.com
DNS.3 = ns3.dns.com
IP.1 = 192.168.1.84
IP.2 = 127.0.0.1
IP.3 = 127.0.0.2
*/
var genSslCertCA = exports.genSslCertCA = function(filename, info, fn){
// check parameter
if (typeof info === 'function') {
fn = info;
info = {};
info.cn = '51dese.com';
}
if (!info.cn) {
info.cn = '51dese.com';
}
filename += info.cn;
filename = filename.replace('*', 'x');
debug('genSslCertCA info: '+JSON.stringify(info));
// SSL CA cert generate with retry
function genCert(filename, info, fn) {
// construct openssl CLI arguments
var clistr = '', cliarg = [];
var key_out = '', csr_out = '', cert_out = '';
// 1.
// - openssl genrsa -out server-key.pem 2048
cliarg.push('genrsa');
///cliarg.push('-out');
///cliarg.push(__dirname+'/certs-tmp/'+filename+'-key.pem');
cliarg.push('2048');
clistr = 'openssl '+cliarg.join(' ');
debug('s1 cli: '+clistr);
var s1 = exec(clistr, {maxBuffer: 200*1024}, function(err, stdout, stderr){
if (err) {
console.error('Warning!s1 openssl process exited with error ' + err + stderr);
fn('Warning!s1 openssl process exited with error ' + err + stderr);
} else {
debug('s1 stdout: '+stdout);
// 1.1
// syncWrite output to file
key_out = stdout;
try {
fs.writeFileSync(__dirname+'/certs-tmp/'+filename+'-key.pem', key_out);
} catch (e) {
console.error('Warning!s1 syncWrite key file failed ' + e);
fn('Warning!s1 syncWrite key file failed ' + e);
return;
}
// 2.
// - openssl req -new -key server-key.pem -subj '/C=CN/ST=SH/L=SH/CN=domain' -out server-csr.pem
cliarg = ['req', '-new', '-key', __dirname+'/certs-tmp/'+filename+'-key.pem'];
// subject
cliarg.push('-subj');
cliarg.push('/C=CN/ST=SH/L=SH/CN='+info.cn);
// csr output
///cliarg.push('-out');
///cliarg.push(__dirname+'/certs-tmp/'+filename+'-csr.pem');
clistr = 'openssl '+cliarg.join(' ');
debug('s2 cli: '+clistr);
var s2 = exec(clistr, function(err, stdout, stderr){
if (err) {
console.error('Warning!s2 openssl process exited with error ' + err + stderr);
fn('Warning!s2 openssl process exited with error ' + err + stderr);
} else {
debug('s2 stdout: '+stdout);
// 2.1
// syncWrite output to file
csr_out = stdout;
try {
fs.writeFileSync(__dirname+'/certs-tmp/'+filename+'-csr.pem', csr_out);
} catch (e) {
console.error('Warning!s2 syncWrite csr file failed ' + e);
fn('Warning!s2 syncWrite csr file failed ' + e);
return;
}
// 3.
// - openssl x509 -req -days 730 -CA ca-cert.pem -CAkey ca-key.pem -CAcreateserial -in server-csr.pem -out server-cert.pem
cliarg = ['x509', '-req', '-CA', info.ca_cert, '-CAkey', info.ca_key,
'-CAcreateserial', '-in', __dirname+'/certs-tmp/'+filename+'-csr.pem'];
// duration
if (info.days) {
cliarg.push('-days');
cliarg.push(info.days);
} else {
cliarg.push('-days');
cliarg.push('365');
}
// 3.1
// V3 extension, subject alternate name
// !!! count CN into altnames
info.altname = info.altname || []; info.altname.push(info.cn);
if (info.altname && info.altname.length) {
// remove duplicates
info.altname = _.uniq(info.altname, function(v) {if (6 === NET.isIP(v)) return IPADDR.parse(v).toString(); else return v;});
debug('client altnames: '+info.altname);
// -extensions v3_req
cliarg.push('-extensions');
cliarg.push('v3_req');
// create ssl.conf
var v3_conf = '[req] \n';
v3_conf += ' req_extensions = v3_req \n\n';
v3_conf += ' [ v3_req ] \n';
v3_conf += ' basicConstraints = CA:FALSE \n';
v3_conf += ' keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment \n';
v3_conf += ' subjectAltName = @alt_names \n\n';
// like
// [alt_names]
// DNS.1 = ns3.dns.com
// ...
// IP.1 = 192.168.1.84
// ...
var ips = [], dns = [];
v3_conf += ' [alt_names] \n';
for (var idx = 0; idx < info.altname.length; idx ++) {
var name = info.altname[idx];
if (NET.isIP(name)) {
ips.push(name);
} else {
dns.push(name);
}
}
for (var idx = 0; idx < ips.length; idx++) {
v3_conf += ' IP.' + idx + ' = ' + ips[idx] + '\n';
}
for (var idx = 0; idx < dns.length; idx ++) {
v3_conf += ' DNS.'+idx+' = '+dns[idx]+'\n';
}
v3_conf += '\n';
// create file
try {
fs.writeFileSync(__dirname+'/certs-tmp/'+filename+'-v3.conf', v3_conf);
} catch (e) {
console.error('Warning!s3 syncWrite V3 conf file failed ' + e);
fn('Warning!s3 syncWrite V3 conf file failed ' + e);
return;
}
// -extfile
cliarg.push('-extfile');
cliarg.push(__dirname+'/certs-tmp/'+filename+'-v3.conf');
}
clistr = 'openssl '+cliarg.join(' ');
debug('s3 cli: '+clistr);
var s3 = exec(clistr, {maxBuffer: 200*1024}, (err, stdout, stderr) => {
if (err) {
console.error('Warning!s3 openssl process exited with error ' + err + stderr);
fn('Warning!s3 openssl process exited with error ' + err + stderr);
} else {
debug('s3 stdout: '+stdout);
// 3.2
// caputre cert
cert_out = stdout;
try {
fn(null, {
key: key_out,
cert: cert_out
});
// destroy certs
fs.unlinkSync(__dirname+'/certs-tmp/'+filename+'-key.pem');
fs.unlinkSync(__dirname+'/certs-tmp/'+filename+'-csr.pem');
if (info.altname && info.altname.length)
fs.unlinkSync(__dirname+'/certs-tmp/'+filename+'-v3.conf');
} catch (e) {
console.error('Warning!s3 open certs file failure:'+e);
fn('Warning!s3 open certs file failure:'+e);
}
}
});
}
});
}
});
}
// retry 3 times
var retry = 0;
(function regenCert(){
genCert(filename, info, function(err, cert){
if (err) {
if (retry < 3) {
// delay regen
setTimeout(function(){
retry ++;
regenCert();
}, 1000); // 1s delay
} else {
// pass error
fn('ssl certgen failed');
}
} else {
// pass cert
fn(null, cert);
}
})
})();
};
// simple test
/*(function(){
genSslCertCA('browser-iwebpp', {
ca_cert: './ca-certs/ca-cert.pem',
ca_key: './ca-certs/ca-key.pem',
days: 666,
cn: '51dese.com',
altname: ['vurl.51dese.com', '*.vurl.51dese.com', '127.0.0.1']
},
function(err, certs){
if (err) {
console.error(err+' genSslCertCA failed');
} else {
console.log('genSslCertCA successfully: '+JSON.stringify(certs));
fs.writeFileSync('webrowser-cert.pem', certs.cert);
fs.writeFileSync('webrowser-key.pem', certs.key);
}
});
})();*/