Skip to content

Instantly share code, notes, and snippets.

@tlivings
Last active December 24, 2015 06:49
Show Gist options
  • Select an option

  • Save tlivings/6759319 to your computer and use it in GitHub Desktop.

Select an option

Save tlivings/6759319 to your computer and use it in GitHub Desktop.
Example of the undocumented reuse of an SSL session in Node.js. This is a very simplistic example, but demonstrates the undocumented option for 'session' on a client connection.
'use strict';
var assert = require('assert');
var https = require('https'),
fs = require('fs');
describe('SSL Connection', function () {
var server, server_options;
before(function (next) {
server_options = {
key : fs.readFileSync('./server.key'),
cert : fs.readFileSync('./server.crt')
};
server = https.createServer(server_options, function (req, res) {
res.writeHead(200);
res.end();
});
server.listen(3000, function () {
next();
});
});
after(function () {
server.close();
});
it('should reuse session', function (next) {
//Simplistic example, just saving the first connection's SSL session off.
var session;
var agent = new https.Agent({
maxSockets : 10,
rejectUnauthorized : false,
key : server_options.key,
cert : server_options.cert
});
var createConnection = agent.createConnection;
//Override createConnection on agent to inject session.
//This is better than passing session to options directly because this might use an async lookup, etc.
agent.createConnection = function (opts) {
if (session) {
opts.session = session;
}
return createConnection.call(agent, opts);
};
var client_options = {
scheme : 'https',
host : 'localhost',
method : 'GET',
port : 3000,
path : '/',
agent : agent
};
//First request, full handshake.
var req = https.request(client_options, function (res) {
//Different between 0.11.x and prior versions.
var ssl = req.socket.ssl || req.socket.pair.ssl;
//Save this session
session = ssl.getSession();
res.on('readable', function () {
while(res.read() !== null);
});
res.once('end', function () {
//Second request, session should be reused now.
var _req = https.request(client_options, function (_res) {
_res.on('readable', function () {
while(_res.read() !== null);
});
_res.on('end', function () {
//Is it reused?
assert(_req.socket.isSessionReused(), 'Expected session to be reused.');
next();
});
});
_req.end();
});
});
req.end();
});
});
@tlivings
Copy link
Copy Markdown
Author

Example of the undocumented reuse of an SSL session in Node.js. This is a very simplistic example, but demonstrates the undocumented option for 'session' on a client connection.

There are two ways to pass a session to a client connection:

  1. Passed directly on options.
  2. Added to options from wrapped createConnection.

The latter is used in the code above.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment