forked from haraka/Haraka
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tls_socket.js
756 lines (615 loc) · 22.2 KB
/
tls_socket.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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
'use strict';
/*--------------------------------------------------------------------------*/
/* Obtained and modified from http://js.5sh.net/starttls.js on 8/18/2011. */
/*--------------------------------------------------------------------------*/
// node.js built-ins
const cluster = require('cluster');
const net = require('net');
const path = require('path');
const spawn = require('child_process').spawn;
const stream = require('stream');
const tls = require('tls');
const util = require('util');
// npm packages
const async = require('async');
const openssl = require('openssl-wrapper').exec;
exports.config = require('haraka-config'); // exported for tests
const log = require('./logger');
const certsByHost = {};
const ctxByHost = {};
let ocsp;
let ocspCache;
// provides a common socket for attaching
// and detaching from either main socket, or crypto socket
class pluggableStream extends stream.Stream {
constructor (socket) {
super();
this.readable = this.writable = true;
this._timeout = 0;
this._keepalive = false;
this._writeState = true;
this._pending = [];
this._pendingCallbacks = [];
if (socket) this.attach(socket);
}
pause () {
if (this.targetsocket.pause) {
this.targetsocket.pause();
this.readable = false;
}
}
resume () {
if (this.targetsocket.resume) {
this.readable = true;
this.targetsocket.resume();
}
}
attach (socket) {
const self = this;
self.targetsocket = socket;
self.targetsocket.on('data', data => {
self.emit('data', data);
});
self.targetsocket.on('connect', (a, b) => {
self.emit('connect', a, b);
});
self.targetsocket.on('secureConnect', (a, b) => {
self.emit('secureConnect', a, b);
self.emit('secure', a, b);
});
self.targetsocket.on('secureConnection', (a, b) => {
// investigate this for removal, see #2743
self.emit('secureConnection', a, b);
self.emit('secure', a, b);
});
self.targetsocket.on('secure', (a, b) => {
self.emit('secureConnection', a, b);
self.emit('secure', a, b);
});
self.targetsocket.on('end', () => {
self.writable = self.targetsocket.writable;
self.emit('end');
});
self.targetsocket.on('close', had_error => {
self.writable = self.targetsocket.writable;
self.emit('close', had_error);
});
self.targetsocket.on('drain', () => {
self.emit('drain');
});
self.targetsocket.once('error', exception => {
self.writable = self.targetsocket.writable;
exception.source = 'tls';
self.emit('error', exception);
});
self.targetsocket.on('timeout', () => {
self.emit('timeout');
});
if (self.targetsocket.remotePort) {
self.remotePort = self.targetsocket.remotePort;
}
if (self.targetsocket.remoteAddress) {
self.remoteAddress = self.targetsocket.remoteAddress;
}
}
clean (data) {
if (this.targetsocket && this.targetsocket.removeAllListeners) {
[ 'data', 'secure', 'secureConnect', 'secureConnection',
'end', 'close', 'error', 'drain'
].forEach((name) => {
this.targetsocket.removeAllListeners(name);
})
}
this.targetsocket = {};
this.targetsocket.write = () => {};
}
write (data, encoding, callback) {
if (this.targetsocket.write) {
return this.targetsocket.write(data, encoding, callback);
}
return false;
}
end (data, encoding) {
if (this.targetsocket.end) {
return this.targetsocket.end(data, encoding);
}
}
destroySoon () {
if (this.targetsocket.destroySoon) {
return this.targetsocket.destroySoon();
}
}
destroy () {
if (this.targetsocket.destroy) {
return this.targetsocket.destroy();
}
}
setKeepAlive (bool) {
this._keepalive = bool;
return this.targetsocket.setKeepAlive(bool);
}
setNoDelay (/* true||false */) {
}
unref () {
return this.targetsocket.unref();
}
setTimeout (timeout) {
this._timeout = timeout;
return this.targetsocket.setTimeout(timeout);
}
}
exports.parse_x509_names = string => {
// receives the text value of a x509 certificate and returns an array of
// of names extracted from the Subject CN and the v3 Subject Alternate Names
const names_found = [];
// log.loginfo(string);
let match = /Subject:.*?CN=([^/\s]+)/.exec(string);
if (match) {
// log.loginfo(match[0]);
if (match[1]) {
// log.loginfo(match[1]);
names_found.push(match[1]);
}
}
match = /X509v3 Subject Alternative Name:[^]*X509/.exec(string);
if (match) {
let dns_name;
const re = /DNS:([^,]+)[,\n]/g;
while ((dns_name = re.exec(match[0])) !== null) {
// log.loginfo(dns_name);
if (names_found.includes(dns_name[1])) continue; // ignore dupes
names_found.push(dns_name[1]);
}
}
return names_found;
}
exports.parse_x509_expire = (file, string) => {
const dateMatch = /Not After : (.*)/.exec(string);
if (!dateMatch) return;
// log.loginfo(dateMatch[1]);
return new Date(dateMatch[1]);
}
exports.parse_x509 = string => {
const res = {};
const match = /^([^-]*)?([-]+BEGIN (?:\w+\s)?PRIVATE KEY[-]+[^-]+[-]+END (?:\w+\s)?PRIVATE KEY[-]+\n)([^]*)$/.exec(string);
if (!match) return res;
if (match[1] && match[1].length) {
log.logerror('leading garbage');
log.logerror(match[1]);
}
if (!match[2] || !match[2].length) return res;
res.key = Buffer.from(match[2]);
if (!match[3] || !match[3].length) return res;
res.cert = Buffer.from(match[3]);
return res;
}
exports.load_tls_ini = (opts) => {
const tlss = this;
log.loginfo(`loading tls.ini`); // from ${this.config.root_path}`);
const cfg = exports.config.get('tls.ini', {
booleans: [
'-redis.disable_for_failed_hosts',
// wildcards match in any section and are not initialized
'*.requestCert',
'*.rejectUnauthorized',
'*.honorCipherOrder' ,
'*.enableOCSPStapling',
'*.requestOCSP',
// explicitely declared booleans are initialized
'+main.requestCert',
'-main.rejectUnauthorized',
'+main.honorCipherOrder',
'-main.requestOCSP',
]
}, () => {
tlss.load_tls_ini();
});
if (!cfg.no_tls_hosts) cfg.no_tls_hosts = {};
if (cfg.main.enableOCSPStapling !== undefined) {
log.logerror('deprecated setting enableOCSPStapling in tls.ini');
cfg.main.requestOCSP = cfg.main.enableOCSPStapling;
}
if (ocsp === undefined && cfg.main.requestOCSP) {
try {
ocsp = require('ocsp');
log.logdebug('ocsp loaded');
ocspCache = new ocsp.Cache();
}
catch (ignore) {
log.lognotice("OCSP Stapling not available.");
}
}
if (cfg.main.requireAuthorized === undefined) {
cfg.main.requireAuthorized = [];
}
else if (!Array.isArray(cfg.main.requireAuthorized)) {
cfg.main.requireAuthorized = [cfg.main.requireAuthorized];
}
tlss.cfg = cfg;
if (!opts || opts.role === 'server') {
tlss.applySocketOpts('*');
tlss.load_default_opts();
}
return cfg;
}
exports.saveOpt = (name, opt, val) => {
if (certsByHost[name] === undefined) certsByHost[name] = {};
certsByHost[name][opt] = val;
}
exports.applySocketOpts = name => {
const tlss = this;
if (!certsByHost[name]) certsByHost[name] = {};
// https://nodejs.org/api/tls.html#tls_new_tls_tlssocket_socket_options
const TLSSocketOptions = [
// 'server' // manually added
'isServer', 'requestCert', 'rejectUnauthorized',
'NPNProtocols', 'ALPNProtocols', 'session',
'requestOCSP', 'secureContext', 'SNICallback'
];
// https://nodejs.org/api/tls.html#tls_tls_createsecurecontext_options
const createSecureContextOptions = [
'key', 'cert', 'dhparam',
'pfx', 'passphrase', 'ca', 'crl', 'ciphers', 'minVersion', 'honorCipherOrder',
'ecdhCurve', 'secureProtocol', 'secureOptions', 'sessionIdContext'
];
const allOpts = TLSSocketOptions.concat(createSecureContextOptions);
allOpts.forEach(opt => {
if (tlss.cfg[name] && tlss.cfg[name][opt] !== undefined) {
// if the setting exists in tls.ini [name]
tlss.saveOpt(name, opt, tlss.cfg[name][opt]);
return;
}
if (tlss.cfg.main[opt] !== undefined) {
// if the setting exists in tls.ini [main]
// then save it to the certsByHost options
tlss.saveOpt(name, opt, tlss.cfg.main[opt]);
return;
}
// defaults
switch (opt) {
case 'sessionIdContext':
tlss.saveOpt(name, opt, 'haraka');
break;
case 'isServer':
tlss.saveOpt(name, opt, true);
break;
case 'key':
tlss.saveOpt(name, opt, 'tls_key.pem');
break;
case 'cert':
tlss.saveOpt(name, opt, 'tls_cert.pem');
break;
case 'dhparam':
tlss.saveOpt(name, opt, 'dhparams.pem');
break;
case 'SNICallback':
tlss.saveOpt(name, opt, SNICallback);
break;
}
})
}
exports.load_default_opts = () => {
const tlss = this;
const cfg = certsByHost['*'];
if (cfg.dhparam && typeof cfg.dhparam === 'string') {
log.logdebug(`loading dhparams from ${cfg.dhparam}`);
tlss.saveOpt('*', 'dhparam', tlss.config.get(cfg.dhparam, 'binary'));
}
if (cfg.ca && typeof cfg.ca === 'string') {
log.loginfo(`loading CA certs from ${cfg.ca}`);
tlss.saveOpt('*', 'ca', tlss.config.get(cfg.ca, 'binary'));
}
// make non-array key/cert option into Arrays with one entry
if (!(Array.isArray(cfg.key ))) cfg.key = [cfg.key];
if (!(Array.isArray(cfg.cert))) cfg.cert = [cfg.cert];
if (cfg.key.length != cfg.cert.length) {
log.logerror(`number of keys (${cfg.key.length}) not equal to certs (${cfg.cert.length}).`);
}
// if key file has already been loaded, it'll be a Buffer.
if (typeof cfg.key[0] === 'string') {
// turn key/cert file names into actual key/cert binary data
const asArray = cfg.key.map(keyFileName => {
if (!keyFileName) return;
const key = tlss.config.get(keyFileName, 'binary');
if (!key) {
log.logerror(`tls key ${path.join(tlss.config.root_path, keyFileName)} could not be loaded.`);
}
return key;
})
tlss.saveOpt('*', 'key', asArray);
}
if (typeof cfg.cert[0] === 'string') {
const asArray = cfg.cert.map(certFileName => {
if (!certFileName) return;
const cert = tlss.config.get(certFileName, 'binary');
if (!cert) {
log.logerror(`tls cert ${path.join(tlss.config.root_path, certFileName)} could not be loaded.`);
}
return cert;
})
tlss.saveOpt('*', 'cert', asArray);
}
if (cfg.cert[0] && cfg.key[0]) {
tlss.tls_valid = true;
// now that all opts are applied, generate TLS context
tlss.ensureDhparams(() => {
ctxByHost['*'] = tls.createSecureContext(cfg);
})
}
}
function SNICallback (servername, sniDone) {
log.logdebug(`SNI servername: ${servername}`);
if (ctxByHost[servername] === undefined) servername = '*';
sniDone(null, ctxByHost[servername]);
}
exports.get_certs_dir = (tlsDir, done) => {
const tlss = this;
tlss.config.getDir(tlsDir, {}, (iterErr, files) => {
if (iterErr) return done(iterErr);
async.map(files, (file, iter_done) => {
const parsed = exports.parse_x509(file.data.toString());
if (!parsed.key) {
return iter_done(null, {
err: new Error(`no PRIVATE key in ${file.path}`),
file
});
}
if (!parsed.cert) {
return iter_done(null, {
err: new Error(`no CERT in ${file.path}`),
file
});
}
const x509args = { noout: true, text: true };
openssl('x509', parsed.cert, x509args, (e, as_str) => {
if (e) {
log.logerror(`BAD TLS in ${file.path}`);
log.logerror(e);
}
const expire = tlss.parse_x509_expire(file, as_str);
if (expire && expire < new Date()) {
log.logerror(`${file.path} expired on ${expire}`);
}
iter_done(null, {
err: e,
file: path.basename(file.path),
key: parsed.key,
cert: parsed.cert,
names: tlss.parse_x509_names(as_str),
expires: expire,
})
})
},
(finalErr, certs) => {
if (finalErr) log.logerror(finalErr);
if (!certs || !certs.length) {
log.loginfo('found 0 TLS certs in config/tls');
return done(null, certs);
}
log.loginfo(`found ${certs.length} TLS certs in config/tls`);
certs.forEach(cert => {
if (undefined === cert) return;
if (cert.err) {
log.logerror(`${cert.file} had error: ${cert.err.message}`);
return;
}
log.logdebug(cert);
cert.names.forEach(name => {
tlss.applySocketOpts(name);
tlss.saveOpt(name, 'cert', cert.cert);
tlss.saveOpt(name, 'key', cert.key);
if (certsByHost['*'] !== undefined && certsByHost['*'].dhparam) {
// copy in dhparam from default '*' TLS config
tlss.saveOpt(name, 'dhparam', certsByHost['*'].dhparam);
}
// now that all opts are applied, generate TLS context
ctxByHost[name] = tls.createSecureContext(certsByHost[name]);
})
})
// log.loginfo(exports.certsByHost);
done(null, exports.certsByHost);
})
})
}
exports.getSocketOpts = (name, done) => {
const tlss = this;
// startup time, load the config/tls dir
if (!certsByHost['*']) tlss.load_tls_ini();
tlss.get_certs_dir('tls', () => {
if (certsByHost[name]) {
// log.logdebug(certsByHost[name]);
return done(certsByHost[name]);
}
// log.logdebug(certsByHost['*']);
done(certsByHost['*']);
});
}
function pipe (cleartext, socket) {
cleartext.socket = socket;
function onError (e) {
}
function onClose () {
socket.removeListener('error', onError);
socket.removeListener('close', onClose);
}
socket.on('error', onError);
socket.on('close', onClose);
}
exports.ensureDhparams = done => {
const tlss = this;
// empty/missing dhparams file
if (certsByHost['*'].dhparam) {
return done(null, certsByHost['*'].dhparam);
}
if (cluster.isWorker) return; // only once, on the master process
const filePath = tlss.cfg.main.dhparam || 'dhparams.pem';
const fpResolved = path.resolve(exports.config.root_path, filePath);
log.loginfo(`Generating a 2048 bit dhparams file at ${fpResolved}`);
const o = spawn('openssl', ['dhparam', '-out', `${fpResolved}`, '2048']);
o.stdout.on('data', data => {
// normally empty output
log.logdebug(data);
})
o.stderr.on('data', data => {
// this is the status gibberish `openssl dhparam` spews as it works
})
o.on('close', code => {
if (code !== 0) {
return done(`Error code: ${code}`);
}
log.loginfo(`Saved to ${fpResolved}`);
const content = tlss.config.get(filePath, 'binary');
tlss.saveOpt('*', 'dhparam', content);
done(null, certsByHost['*'].dhparam);
});
}
exports.addOCSP = server => {
if (!ocsp) {
log.logdebug('addOCSP: not available');
return;
}
if (server.listenerCount('OCSPRequest') > 0) {
log.logdebug('OCSPRequest already listening');
return;
}
log.logdebug('adding OCSPRequest listener');
server.on('OCSPRequest', (cert, issuer, ocr_cb) => {
log.logdebug(`OCSPRequest: ${cert}`);
ocsp.getOCSPURI(cert, (err, uri) => {
log.logdebug(`OCSP Request, URI: ${uri }, err=${ err}`);
if (err) return ocr_cb(err);
if (uri === null) return ocr_cb(); // not working OCSP server
const req = ocsp.request.generate(cert, issuer);
// look for a cached value first
ocspCache.probe(req.id, (err2, cached) => {
if (err2) return ocr_cb(err2);
if (cached) {
log.logdebug(`OCSP cache: ${util.inspect(cached)}`);
return ocr_cb(err2, cached.response);
}
const options = {
url: uri,
ocsp: req.data
};
log.logdebug(`OCSP req:${util.inspect(req)}`);
ocspCache.request(req.id, options, ocr_cb);
})
})
})
}
exports.shutdown = () => {
if (ocsp) cleanOcspCache();
}
function cleanOcspCache () {
log.logdebug(`Cleaning ocspCache. How many keys? ${Object.keys(ocspCache.cache).length}`);
Object.keys(ocspCache.cache).forEach((key) => {
clearTimeout(ocspCache.cache[key].timer);
});
}
exports.certsByHost = certsByHost;
exports.ocsp = ocsp;
exports.get_rejectUnauthorized = (rejectUnauthorized, port, port_list) => {
// console.log(`rejectUnauthorized: ${rejectUnauthorized}, port ${port}, list: ${port_list}`)
if (rejectUnauthorized) {
// console.log('true for all ports');
return true;
}
if (port_list.includes(port)) {
// console.log('port matched true');
return true;
}
// console.log('returning default false');
return false;
}
function createServer (cb) {
const server = net.createServer(cryptoSocket => {
const socket = new pluggableStream(cryptoSocket);
exports.addOCSP(server);
socket.upgrade = cb2 => {
log.logdebug('Upgrading to TLS');
socket.clean();
cryptoSocket.removeAllListeners('data');
const options = Object.assign({}, certsByHost['*']);
options.server = server; // TLSSocket needs server for SNI to work
options.rejectUnauthorized = exports.get_rejectUnauthorized(options.rejectUnauthorized, cryptoSocket.localPort, exports.cfg.main.requireAuthorized);
const cleartext = new tls.TLSSocket(cryptoSocket, options);
pipe(cleartext, cryptoSocket);
cleartext
.on('error', exception => {
exception.source = 'tls';
socket.emit('error', exception);
})
.on('secure', () => {
log.logdebug('TLS secured.');
socket.emit('secure');
const cipher = cleartext.getCipher();
cipher.version = cleartext.getProtocol();
if (cb2) cb2(
cleartext.authorized,
cleartext.authorizationError,
cleartext.getPeerCertificate(),
cipher
);
})
socket.cleartext = cleartext;
if (socket._timeout) {
cleartext.setTimeout(socket._timeout);
}
cleartext.setKeepAlive(socket._keepalive);
socket.attach(socket.cleartext);
};
cb(socket);
});
return server;
}
function connect (port, host, cb) {
let conn_options = {};
if (typeof port === 'object') {
conn_options = port;
cb = host;
}
else {
conn_options.port = port;
conn_options.host = host;
}
const cryptoSocket = net.connect(conn_options);
const socket = new pluggableStream(cryptoSocket);
socket.upgrade = (options, cb2) => {
socket.clean();
cryptoSocket.removeAllListeners('data');
if (exports.tls_valid) {
options = Object.assign(options, certsByHost['*']);
}
options.socket = cryptoSocket;
const cleartext = new tls.connect(options);
pipe(cleartext, cryptoSocket);
cleartext.on('error', err => {
if (err.reason) {
log.logerror(`client TLS error: ${err}`);
}
})
cleartext.once('secureConnect', () => {
log.logdebug('client TLS secured.');
const cipher = cleartext.getCipher();
cipher.version = cleartext.getProtocol();
if (cb2) cb2(
cleartext.authorized,
cleartext.authorizationError,
cleartext.getPeerCertificate(),
cipher
);
});
socket.cleartext = cleartext;
if (socket._timeout) {
cleartext.setTimeout(socket._timeout);
}
cleartext.setKeepAlive(socket._keepalive);
socket.attach(socket.cleartext);
log.logdebug('client TLS upgrade in progress, awaiting secured.');
}
return socket;
}
exports.connect = connect;
exports.createConnection = connect;
exports.Server = createServer;
exports.createServer = createServer;