Skip to content

Commit 528a3ce

Browse files
committed
tls: more session configuration options, methods
Introduce `ticketKeys` server option, `session` client option, `getSession()` and `getTLSTicket()` methods. fix nodejs#7032
1 parent 5ce4580 commit 528a3ce

5 files changed

Lines changed: 148 additions & 1 deletion

File tree

doc/api/tls.markdown

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,12 @@ automatically set as a listener for the [secureConnection][] event. The
205205
session identifiers and TLS session tickets created by the server are
206206
timed out. See [SSL_CTX_set_timeout] for more details.
207207

208+
- `ticketKeys`: A 48-byte `Buffer` instance consisting of 16-byte prefix,
209+
16-byte hmac key, 16-byte AES key. You could use it to accept tls session
210+
tickets on multiple instances of tls server.
211+
212+
NOTE: Automatically shared between `cluster` module workers.
213+
208214
- `sessionIdContext`: A string containing a opaque identifier for session
209215
resumption. If `requestCert` is `true`, the default is MD5 hash value
210216
generated from command-line. Otherwise, the default is not provided.
@@ -314,6 +320,8 @@ Creates a new client connection to the given `port` and `host` (old API) or
314320
SSL version 3. The possible values depend on your installation of
315321
OpenSSL and are defined in the constant [SSL_METHODS][].
316322

323+
- `session`: A `Buffer` instance, containing TLS session.
324+
317325
The `callback` parameter will be added as a listener for the
318326
['secureConnect'][] event.
319327

@@ -398,6 +406,8 @@ Construct a new TLSSocket object from existing TCP socket.
398406

399407
- `SNICallback`: Optional, see [tls.createServer][]
400408

409+
- `session`: Optional, a `Buffer` instance, containing TLS session
410+
401411
## tls.createSecurePair([credentials], [isServer], [requestCert], [rejectUnauthorized])
402412

403413
Stability: 0 - Deprecated. Use tls.TLSSocket instead.
@@ -646,6 +656,18 @@ and their processing can be delayed due to packet loss or reordering. However,
646656
smaller fragments add extra TLS framing bytes and CPU overhead, which may
647657
decrease overall server throughput.
648658

659+
### tlsSocket.getSession()
660+
661+
Return ASN.1 encoded TLS session or `undefined` if none was negotiated. Could
662+
be used to speed up handshake establishment when reconnecting to the server.
663+
664+
### tlsSocket.getTLSTicket()
665+
666+
NOTE: Works only with client TLS sockets. Useful only for debugging, for
667+
session reuse provide `session` option to `tls.connect`.
668+
669+
Return TLS session ticket or `undefined` if none was negotiated.
670+
649671
### tlsSocket.address()
650672

651673
Returns the bound address, the address family name and port of the

lib/_tls_wrap.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,9 @@ TLSSocket.prototype._init = function(socket) {
232232
} else {
233233
this.ssl.onhandshakestart = function() {};
234234
this.ssl.onhandshakedone = this._finishInit.bind(this);
235+
236+
if (options.session)
237+
this.ssl.setSession(options.session);
235238
}
236239

237240
this.ssl.onerror = function(err) {
@@ -321,6 +324,10 @@ TLSSocket.prototype.setMaxSendFragment = function setMaxSendFragment(size) {
321324
return this.ssl.setMaxSendFragment(size) == 1;
322325
};
323326

327+
TLSSocket.prototype.getTLSTicket = function getTLSTicket() {
328+
return this.ssl.getTLSTicket();
329+
};
330+
324331
TLSSocket.prototype._handleTimeout = function() {
325332
this._tlsError(new Error('TLS handshake timeout'));
326333
};
@@ -620,6 +627,7 @@ Server.prototype.setOptions = function(options) {
620627
if (!util.isUndefined(options.ecdhCurve))
621628
this.ecdhCurve = options.ecdhCurve;
622629
if (options.sessionTimeout) this.sessionTimeout = options.sessionTimeout;
630+
if (options.ticketKeys) this.ticketKeys = options.ticketKeys;
623631
var secureOptions = options.secureOptions || 0;
624632
if (options.honorCipherOrder) {
625633
secureOptions |= constants.SSL_OP_CIPHER_SERVER_PREFERENCE;
@@ -747,6 +755,7 @@ exports.connect = function(/* [port, host], options, cb */) {
747755
isServer: false,
748756
requestCert: true,
749757
rejectUnauthorized: options.rejectUnauthorized,
758+
session: options.session,
750759
NPNProtocols: NPN.NPNProtocols
751760
});
752761
result = socket;

src/node_crypto.cc

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -856,6 +856,7 @@ void SSLWrap<Base>::AddMethods(Handle<FunctionTemplate> t) {
856856
NODE_SET_PROTOTYPE_METHOD(t, "endParser", EndParser);
857857
NODE_SET_PROTOTYPE_METHOD(t, "renegotiate", Renegotiate);
858858
NODE_SET_PROTOTYPE_METHOD(t, "shutdown", Shutdown);
859+
NODE_SET_PROTOTYPE_METHOD(t, "getTLSTicket", GetTLSTicket);
859860

860861
#ifdef SSL_set_max_send_fragment
861862
NODE_SET_PROTOTYPE_METHOD(t, "setMaxSendFragment", SetMaxSendFragment);
@@ -1129,7 +1130,7 @@ void SSLWrap<Base>::GetSession(const FunctionCallbackInfo<Value>& args) {
11291130
unsigned char* sbuf = new unsigned char[slen];
11301131
unsigned char* p = sbuf;
11311132
i2d_SSL_SESSION(sess, &p);
1132-
args.GetReturnValue().Set(Encode(sbuf, slen, BINARY));
1133+
args.GetReturnValue().Set(Encode(sbuf, slen, BUFFER));
11331134
delete[] sbuf;
11341135
}
11351136

@@ -1247,6 +1248,25 @@ void SSLWrap<Base>::Shutdown(const FunctionCallbackInfo<Value>& args) {
12471248
}
12481249

12491250

1251+
template <class Base>
1252+
void SSLWrap<Base>::GetTLSTicket(const FunctionCallbackInfo<Value>& args) {
1253+
HandleScope scope(args.GetIsolate());
1254+
1255+
Base* w = Unwrap<Base>(args.This());
1256+
Environment* env = w->ssl_env();
1257+
1258+
SSL_SESSION* sess = SSL_get_session(w->ssl_);
1259+
if (sess == NULL || sess->tlsext_tick == NULL)
1260+
return;
1261+
1262+
Local<Object> buf = Buffer::New(env,
1263+
reinterpret_cast<char*>(sess->tlsext_tick),
1264+
sess->tlsext_ticklen);
1265+
1266+
args.GetReturnValue().Set(buf);
1267+
}
1268+
1269+
12501270
#ifdef SSL_set_max_send_fragment
12511271
template <class Base>
12521272
void SSLWrap<Base>::SetMaxSendFragment(

src/node_crypto.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,7 @@ class SSLWrap {
187187
static void EndParser(const v8::FunctionCallbackInfo<v8::Value>& args);
188188
static void Renegotiate(const v8::FunctionCallbackInfo<v8::Value>& args);
189189
static void Shutdown(const v8::FunctionCallbackInfo<v8::Value>& args);
190+
static void GetTLSTicket(const v8::FunctionCallbackInfo<v8::Value>& args);
190191

191192
#ifdef SSL_set_max_send_fragment
192193
static void SetMaxSendFragment(

test/simple/test-tls-ticket.js

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
// Copyright Joyent, Inc. and other Node contributors.
2+
//
3+
// Permission is hereby granted, free of charge, to any person obtaining a
4+
// copy of this software and associated documentation files (the
5+
// "Software"), to deal in the Software without restriction, including
6+
// without limitation the rights to use, copy, modify, merge, publish,
7+
// distribute, sublicense, and/or sell copies of the Software, and to permit
8+
// persons to whom the Software is furnished to do so, subject to the
9+
// following conditions:
10+
//
11+
// The above copyright notice and this permission notice shall be included
12+
// in all copies or substantial portions of the Software.
13+
//
14+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15+
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16+
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17+
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18+
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19+
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20+
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21+
22+
if (!process.versions.openssl) {
23+
console.error('Skipping because node compiled without OpenSSL.');
24+
process.exit(0);
25+
}
26+
27+
var assert = require('assert');
28+
var fs = require('fs');
29+
var net = require('net');
30+
var tls = require('tls');
31+
var crypto = require('crypto');
32+
33+
var common = require('../common');
34+
35+
var keys = crypto.randomBytes(48);
36+
var serverLog = [];
37+
var ticketLog = [];
38+
39+
var serverCount = 0;
40+
function createServer() {
41+
var id = serverCount++;
42+
43+
var server = tls.createServer({
44+
key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'),
45+
cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'),
46+
ticketKeys: keys
47+
}, function(c) {
48+
serverLog.push(id);
49+
c.end();
50+
});
51+
52+
return server;
53+
}
54+
55+
var servers = [ createServer(), createServer(), createServer(), createServer(), createServer(), createServer() ];
56+
57+
// Create one TCP server and balance sockets to multiple TLS server instances
58+
var shared = net.createServer(function(c) {
59+
servers.shift().emit('connection', c);
60+
}).listen(common.PORT, function() {
61+
start(function() {
62+
shared.close();
63+
});
64+
});
65+
66+
function start(callback) {
67+
var sess = null;
68+
var left = servers.length;
69+
70+
function connect() {
71+
var s = tls.connect(common.PORT, {
72+
session: sess,
73+
rejectUnauthorized: false
74+
}, function() {
75+
sess = s.getSession() || sess;
76+
ticketLog.push(s.getTLSTicket().toString('hex'));
77+
});
78+
s.on('close', function() {
79+
if (--left === 0)
80+
callback();
81+
else
82+
connect();
83+
});
84+
}
85+
86+
connect();
87+
}
88+
89+
process.on('exit', function() {
90+
assert.equal(ticketLog.length, serverLog.length);
91+
for (var i = 0; i < serverLog.length - 1; i++) {
92+
assert.notEqual(serverLog[i], serverLog[i + 1]);
93+
assert.equal(ticketLog[i], ticketLog[i + 1]);
94+
}
95+
});

0 commit comments

Comments
 (0)