telebit-relay.js/lib/unwrap-tls.js

225 lines
7.7 KiB
JavaScript
Raw Permalink Normal View History

'use strict';
var sni = require('sni');
2018-06-01 06:41:32 +00:00
var pipeWs = require('./pipe-ws.js');
2018-11-04 06:36:29 +00:00
var ago = require('./ago.js').AGO;
var up = Date.now();
function fromUptime(ms) {
if (ms) {
return ago(Date.now() - ms);
} else {
return "Not seen since relay restarted, " + ago(Date.now() - up);
}
}
2018-06-01 06:41:32 +00:00
module.exports.createTcpConnectionHandler = function (state) {
var Devices = state.Devices;
2018-05-31 06:12:37 +00:00
return function onTcpConnection(conn, serviceport) {
2018-05-31 06:18:02 +00:00
serviceport = serviceport || conn.localPort;
// this works when I put it here, but I don't know if it's tls yet here
// httpsServer.emit('connection', socket);
//tls3000.emit('connection', socket);
//var tlsSocket = new tls.TLSSocket(socket, { secureContext: tls.createSecureContext(tlsOpts) });
//tlsSocket.on('data', function (chunk) {
// console.log('dummy', chunk.byteLength);
//});
//return;
2018-08-21 02:58:04 +00:00
//conn.once('data', function (firstChunk) {
//});
conn.once('readable', function () {
var firstChunk = conn.read();
2018-06-19 23:43:28 +00:00
var service = 'tcp';
var servername;
var str;
var m;
if (!firstChunk) {
try {
conn.end();
} catch(e) {
console.error("[lib/unwrap-tls.js] Error:", e);
conn.destroy();
}
return;
}
2018-08-21 02:58:04 +00:00
//conn.pause();
2018-05-26 21:21:03 +00:00
conn.unshift(firstChunk);
// BUG XXX: this assumes that the packet won't be chunked smaller
// than the 'hello' or the point of the 'Host' header.
// This is fairly reasonable, but there are edge cases where
// it does not hold (such as manual debugging with telnet)
// and so it should be fixed at some point in the future
// defer after return (instead of being in many places)
2018-05-26 21:21:03 +00:00
function deferData(fn) {
2018-11-04 06:36:29 +00:00
if ('httpsInvalid' === fn) {
state[fn]({
servername: servername
, ago: fromUptime(Devices.lastSeen(state.deviceLists, servername))
}, conn);
} else if (fn) {
2018-06-19 23:43:28 +00:00
state[fn](servername, conn);
} else {
console.error("[SANITY ERROR] '" + fn + "' doesn't have a state handler");
2018-05-26 21:21:03 +00:00
}
2018-08-21 02:58:04 +00:00
/*
2018-05-26 21:21:03 +00:00
process.nextTick(function () {
conn.resume();
});
2018-08-21 02:58:04 +00:00
*/
2018-05-26 21:21:03 +00:00
}
var httpOutcomes = {
missingServername: function () {
console.log("[debug] [http] missing servername");
// TODO use a more specific error page
deferData('handleInsecureHttp');
}
, requiresSetup: function () {
console.log("[debug] [http] requires setup");
// TODO Insecure connections for setup will not work on secure domains (i.e. .app)
state.httpSetupServer.emit('connection', conn);
}
, isInternal: function () {
console.log("[debug] [http] is known internally (admin)");
if (/well-known/.test(str)) {
deferData('handleHttp');
} else {
deferData('handleInsecureHttp');
}
}
, isVhost: function () {
console.log("[debug] [http] is vhost (normal server)");
if (/well-known/.test(str)) {
deferData('handleHttp');
} else {
deferData('handleInsecureHttp');
}
}
, assumeExternal: function () {
console.log("[debug] [http] assume external");
var service = 'http';
if (!Devices.exist(state.deviceLists, servername)) {
// It would be better to just re-read the host header rather
// than creating a whole server object, but this is a "rare"
// case and I'm feeling lazy right now.
console.log("[debug] [http] no device connected");
2018-11-04 06:36:29 +00:00
state.createHttpInvalid({
servername: servername
, ago: fromUptime(Devices.lastSeen(state.deviceLists, servername))
}).emit('connection', conn);
return;
}
// TODO make https redirect configurable on a per-domain basis
// /^\/\.well-known\/acme-challenge\//.test(str)
if (/well-known/.test(str)) {
// HTTP
console.log("[debug] [http] passthru");
pipeWs(servername, service, Devices.next(state.deviceLists, servername), conn, serviceport);
return;
} else {
console.log("[debug] [http] redirect to https");
deferData('handleInsecureHttp');
}
}
};
var tlsOutcomes = {
missingServername: function () {
if (state.debug) { console.log("No SNI was given, so there's nothing we can do here"); }
deferData('httpsInvalid');
}
, requiresSetup: function () {
2018-06-01 06:41:32 +00:00
console.info("[Setup] https => admin => setup => (needs bogus tls certs to start?)");
2018-05-26 21:21:03 +00:00
deferData('httpsSetupServer');
2018-05-23 11:12:39 +00:00
}
, isInternal: function () {
2018-06-01 06:41:32 +00:00
if (state.debug) { console.log("[Admin]", servername); }
2018-05-26 21:21:03 +00:00
deferData('httpsTunnel');
}
, isVhost: function (vhost) {
if (state.debug) { console.log("[tcp] [vhost]", state.config.vhost, "=>", vhost); }
deferData('httpsVhost');
2018-06-14 09:59:19 +00:00
}
, assumeExternal: function () {
var nextDevice = Devices.next(state.deviceLists, servername);
if (!nextDevice) {
2018-06-01 06:41:32 +00:00
if (state.debug) { console.log("No devices match the given servername"); }
2018-05-26 21:21:03 +00:00
deferData('httpsInvalid');
return;
}
2018-06-19 23:43:28 +00:00
if (state.debug) { console.log("pipeWs(servername, service, deviceLists['" + servername + "'], socket)"); }
pipeWs(servername, service, nextDevice, conn, serviceport);
}
};
function handleConnection(outcomes) {
var vhost;
// No routing information available
if (!servername) { outcomes.missingServername(); return; }
// Server needs to be set up
if (!state.servernames.length) { outcomes.requiresSetup(); return; }
// This is one of the admin domains
if (-1 !== state.servernames.indexOf(servername)) { outcomes.isInternal(); return; }
2018-06-01 06:41:32 +00:00
// TODO don't run an fs check if we already know this is working elsewhere
//if (!state.validHosts) { state.validHosts = {}; }
if (state.config.vhost) {
vhost = state.config.vhost.replace(/:hostname/, servername);
require('fs').readdir(vhost, function (err, nodes) {
2018-06-01 06:41:32 +00:00
if (state.debug && err) { console.log("VHOST error", err); }
if (err || !nodes) { outcomes.assumeExternal(); return; }
outcomes.isVhost(vhost);
});
return;
}
outcomes.assumeExternal();
}
// https://github.com/mscdex/httpolyglot/issues/3#issuecomment-173680155
if (22 === firstChunk[0]) {
// TLS
service = 'https';
2018-06-14 09:59:19 +00:00
servername = (sni(firstChunk)||'').toLowerCase().trim();
2018-06-01 06:41:32 +00:00
if (state.debug) { console.log("[tcp] tls hello from '" + servername + "'"); }
handleConnection(tlsOutcomes);
return;
}
if (firstChunk[0] > 32 && firstChunk[0] < 127) {
// (probably) HTTP
str = firstChunk.toString();
m = str.match(/(?:^|[\r\n])Host: ([^\r\n]+)[\r\n]*/im);
servername = (m && m[1].toLowerCase() || '').split(':')[0];
2018-06-01 06:41:32 +00:00
if (state.debug) { console.log("[tcp] http hostname '" + servername + "'"); }
2018-05-23 11:12:39 +00:00
if (/HTTP\//i.test(str)) {
handleConnection(httpOutcomes);
return;
}
}
console.error("Got unexpected connection", str);
conn.write(JSON.stringify({ error: {
message: "not sure what you were trying to do there..."
, code: 'E_INVALID_PROTOCOL' }
}));
conn.end();
});
conn.on('error', function (err) {
console.error('[error] tcp socket raw TODO forward and close');
console.error(err);
});
};
};