Skip to content

Instantly share code, notes, and snippets.

@tg-x
Created February 20, 2011 02:48
Show Gist options
  • Save tg-x/835636 to your computer and use it in GitHub Desktop.
Save tg-x/835636 to your computer and use it in GitHub Desktop.
TLS detection for node.js
/*
* Autodetect if SSL/TLS is used by having a look at the first incoming bytes
* This technique is from http://webview.jabberd.org/cgi-bin/viewvc.cgi/trunk/jadc2s/clients.cc?view=markup
*
* used heuristic:
* - an incoming connection using SSLv3/TLSv1 records should start with 0x16
* - an incoming connection using SSLv2 records should start with the record size
* and as the first record should not be very big we can expect 0x80 or 0x00 (the MSB is a flag)
* - everything else is considered to be unencrypted
*/
var net = require('net');
var tls = require('tls');
var fs = require('fs');
var cfg = {
port: process.argv[2] || 1234,
address: process.argv[3] || '::',
tls: process.argv[4] == 'notls' ? false : true,
crypto: {
cert: fs.readFileSync(process.argv[5] || 'cert.pem', 'ascii'),
key: fs.readFileSync(process.argv[6] || 'key.pem', 'ascii'),
}
};
var onConnection = function (stream) {
var socket = stream.socket ? stream.socket : stream;
var id = socket.remoteAddress+':'+socket.remotePort;
console.log('>> new connection: '+ id);
stream.on('data', function (data) {
console.log('>> got data from: '+ id);
process.stdout.write(data.toString());
stream.write(data);
});
stream.on('close', function () {
console.log('>> connection closed: '+ id);
});
};
var srv, tlsSrv;
if (cfg.tls) {
tlsSrv = tls.createServer(cfg.crypto, onConnection);
srv = net.createServer(function(socket) {
socket.once('data', function(data) {
if (data[0] == 0x16 || data[0] == 0x80 || data[0] == 0x00) {
console.log('>> TLS detected');
tlsSrv.emit('connection', socket);
} else {
console.log('>> no TLS detected');
onConnection(socket);
}
socket.emit('data', data);
});
});
} else {
srv = net.createServer(onConnection);
}
srv.listen(cfg.port, cfg.address);
console.log('>> listening on '+ cfg.address +' port '+ cfg.port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment