telebit-relay.js/wstunneld.js

372 lines
11 KiB
JavaScript
Raw Normal View History

2016-09-27 21:56:06 +00:00
'use strict';
var sni = require('sni');
var url = require('url');
var jwt = require('jsonwebtoken');
2016-09-28 05:26:16 +00:00
var packer = require('tunnel-packer');
2017-04-05 02:31:58 +00:00
var Devices = {};
Devices.replace = function (store, servername, newDevice) {
var devices = Devices.list(store, servername);
var oldDevice;
if (!devices.some(function (device, i) {
if ((device.deviceId && device.deviceId === newDevice.deviceId)
|| (device.servername && device.servername === newDevice.servername)) {
oldDevice = devices[i];
devices[i] = newDevice;
return true;
}
})) {
devices.push(newDevice);
store[servername] = devices;
}
return oldDevice;
};
Devices.remove = function (store, servername, newDevice) {
var devices = Devices.list(store, servername);
var oldDevice;
devices.some(function (device, i) {
if ((device.deviceId && device.deviceId === newDevice.deviceId)
|| (device.servername && device.servername === newDevice.servername)) {
oldDevice = devices.splice(i, 1);
return true;
}
});
return oldDevice;
};
Devices.list = function (store, servername) {
return store[servername] || [];
};
Devices.exist = function (store, servername) {
return (store[servername] || []).length;
};
Devices.next = function (store, servername) {
var devices = Devices.list(store, servername);
if (devices._index >= devices.length) {
devices._index = 0;
}
devices._index = (devices._index || 0) + 1;
return devices[devices._index];
};
module.exports.store = { Devices: Devices };
2016-10-13 00:16:14 +00:00
module.exports.create = function (copts) {
2017-04-05 02:31:58 +00:00
var deviceLists = {};
2016-09-27 21:56:06 +00:00
2016-10-01 05:52:37 +00:00
function onWsConnection(ws) {
2016-09-27 21:56:06 +00:00
var location = url.parse(ws.upgradeReq.url, true);
2017-04-05 02:31:58 +00:00
var authn = (ws.upgradeReq.headers.authorization||'').split(/\s+/);
var jwtoken;
2016-09-30 19:15:58 +00:00
var token;
2016-09-27 21:56:06 +00:00
2016-09-30 19:15:58 +00:00
try {
2017-04-05 02:31:58 +00:00
if (authn[0]) {
if ('basic' === authn[0].toLowerCase()) {
authn = new Buffer(authn[1], 'base64').toString('ascii').split(':');
}
/*
if (-1 !== [ 'bearer', 'jwk' ].indexOf(authn[0].toLowerCase())) {
jwtoken = authn[1];
}
*/
}
jwtoken = authn[1] || location.query.access_token;
} catch(e) {
jwtoken = null;
}
try {
token = jwt.verify(jwtoken, copts.secret);
2016-09-30 19:15:58 +00:00
} catch(e) {
token = null;
}
/*
2016-09-30 06:46:02 +00:00
if (!token || !token.name) {
console.log('location, token');
console.log(location.query.access_token);
console.log(token);
}
2016-09-30 19:15:58 +00:00
*/
2016-09-28 05:26:16 +00:00
2016-09-27 21:56:06 +00:00
if (!token) {
2016-09-30 19:15:58 +00:00
ws.send(JSON.stringify({ error: { message: "invalid access token", code: "E_INVALID_TOKEN" } }));
2016-09-27 21:56:06 +00:00
ws.close();
return;
}
2017-04-05 02:31:58 +00:00
//console.log('[wstunneld.js] DEBUG', token);
2016-10-11 23:00:03 +00:00
if (!Array.isArray(token.domains)) {
if ('string' === typeof token.name) {
token.domains = [ token.name ];
}
}
if (!Array.isArray(token.domains)) {
2016-09-30 19:15:58 +00:00
ws.send(JSON.stringify({ error: { message: "invalid server name", code: "E_INVALID_NAME" } }));
2016-09-27 21:56:06 +00:00
ws.close();
return;
}
2016-10-11 23:00:03 +00:00
var remote;
token.domains.some(function (domainname) {
2017-04-05 02:31:58 +00:00
remote = Devices.next(deviceLists, domainname);
2016-10-11 23:00:03 +00:00
return remote;
});
remote = remote || {};
token.domains.forEach(function (domainname) {
2016-10-15 06:18:30 +00:00
console.log('domainname', domainname);
2017-04-05 02:31:58 +00:00
Devices.replace(deviceLists, domainname, remote);
2016-10-11 23:00:03 +00:00
});
2016-09-30 06:46:02 +00:00
var handlers = {
onmessage: function (opts) {
// opts.data
2016-10-01 05:52:37 +00:00
var cid = packer.addrToId(opts);
2016-09-30 06:46:02 +00:00
var cstream = remote.clients[cid];
console.log("remote '" + remote.servername + " : " + remote.id + "' has data for '" + cid + "'", opts.data.byteLength);
if (!cstream) {
remote.ws.send(packer.pack(opts, null, 'error'));
return;
}
cstream.browser.write(opts.data);
}
, onend: function (opts) {
2016-10-01 05:52:37 +00:00
var cid = packer.addrToId(opts);
2016-09-30 06:46:02 +00:00
console.log('[TunnelEnd]', cid);
handlers._onend(cid);
}
, onerror: function (opts) {
2016-10-01 05:52:37 +00:00
var cid = packer.addrToId(opts);
2016-09-30 06:46:02 +00:00
console.log('[TunnelError]', cid);
handlers._onend(cid);
}
, _onend: function (cid) {
var c = remote.clients[cid];
delete remote.clients[cid];
try {
c.browser.end();
} catch(e) {
// ignore
}
try {
c.wrapped.end();
} catch(e) {
// ignore
}
}
};
2016-09-27 21:56:06 +00:00
// TODO allow more than one remote per servername
2016-09-28 05:26:16 +00:00
remote.ws = ws;
2017-04-05 02:31:58 +00:00
remote.servername = (token.device && token.device.hostname) || token.domains.join(',');
remote.deviceId = (token.device && token.device.id) || null;
2016-10-01 05:52:37 +00:00
remote.id = packer.socketToId(ws.upgradeReq.socket);
2016-09-30 02:20:38 +00:00
console.log("remote.id", remote.id);
2016-09-27 21:56:06 +00:00
// TODO allow tls to be decrypted by server if client is actually a browser
// and we haven't implemented tls in the browser yet
2016-09-28 05:26:16 +00:00
remote.decrypt = token.decrypt;
2016-09-27 21:56:06 +00:00
// TODO how to allow a child process to communicate with this one?
2016-09-28 05:26:16 +00:00
remote.clients = {};
remote.handle = { address: null, handle: null };
2016-09-30 06:46:02 +00:00
remote.unpacker = packer.create(handlers);
2017-04-05 02:31:58 +00:00
remote.domains = token.domains;
function forwardMessage(chunk) {
2016-09-30 02:20:38 +00:00
console.log('message from home cloud to tunneler to browser', chunk.byteLength);
2016-09-30 07:11:24 +00:00
//console.log(chunk.toString());
2016-09-30 02:20:38 +00:00
remote.unpacker.fns.addChunk(chunk);
2017-04-05 02:31:58 +00:00
}
function hangup() {
2016-09-30 06:46:02 +00:00
// the remote will handle closing its local connections
Object.keys(remote.clients).forEach(function (cid) {
try {
remote.clients[cid].browser.end();
} catch(e) {
// ignore
}
});
2017-04-05 02:31:58 +00:00
token.domains.forEach(function (domainname) {
Devices.remove(deviceLists, domainname, remote);
});
}
function die() {
hangup();
}
2016-09-28 05:26:16 +00:00
2017-04-05 02:31:58 +00:00
ws.on('message', forwardMessage);
ws.on('close', hangup);
ws.on('error', die);
2016-10-01 05:52:37 +00:00
}
2016-09-27 21:56:06 +00:00
2016-09-30 02:20:38 +00:00
function pipeWs(servername, service, browser, remote) {
console.log('pipeWs');
2017-04-05 02:31:58 +00:00
//var remote = deviceLists[servername];
2016-09-30 02:20:38 +00:00
var ws = remote.ws;
2016-10-01 05:52:37 +00:00
//var address = packer.socketToAddr(ws.upgradeReq.socket);
var baddress = packer.socketToAddr(browser);
var cid = packer.addrToId(baddress);
2016-09-30 02:20:38 +00:00
console.log('servername:', servername);
console.log('service:', service);
baddress.service = service;
2016-10-01 05:52:37 +00:00
var wrapForRemote = packer.Transform.create({
2016-09-30 02:20:38 +00:00
id: cid
//, remoteId: remote.id
, address: baddress
, servername: servername
, service: service
});
2016-10-01 06:54:22 +00:00
console.log('home-cloud is', packer.socketToId(remote.ws.upgradeReq.socket));
2016-09-30 02:20:38 +00:00
console.log('browser is', cid);
var bstream = remote.clients[cid] = {
wrapped: browser.pipe(wrapForRemote)
, browser: browser
2016-09-30 06:46:02 +00:00
, address: baddress
2016-09-30 02:20:38 +00:00
};
//var bstream = remote.clients[cid] = wrapForRemote.pipe(browser);
bstream.wrapped.on('data', function (pchunk) {
// var chunk = socket.read();
console.log('[bstream] data from browser to tunneler', pchunk.byteLength);
2016-09-30 07:11:24 +00:00
//console.log(JSON.stringify(pchunk.toString()));
2016-10-12 23:11:11 +00:00
try {
ws.send(pchunk, { binary: true });
} catch(e) {
try {
bstream.browser.end();
} catch(e) {
// ignore
}
}
2016-09-30 02:20:38 +00:00
});
2016-09-30 07:11:24 +00:00
bstream.wrapped.on('error', function (err) {
console.error('[error] bstream.wrapped.error');
console.error(err);
2016-09-30 06:46:02 +00:00
try {
ws.send(packer.pack(baddress, null, 'error'), { binary: true });
} catch(e) {
// ignore
}
try {
bstream.browser.end();
} catch(e) {
// ignore
}
2016-09-30 02:20:38 +00:00
delete remote.clients[cid];
});
bstream.wrapped.on('end', function () {
2016-09-30 06:46:02 +00:00
try {
ws.send(packer.pack(baddress, null, 'end'), { binary: true });
} catch(e) {
// ignore
}
try {
bstream.browser.end();
} catch(e) {
// ignore
}
2016-09-30 02:20:38 +00:00
delete remote.clients[cid];
});
}
2016-10-01 05:52:37 +00:00
function onTcpConnection(browser) {
2016-09-27 21:56:06 +00:00
// 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;
2016-09-30 02:20:38 +00:00
browser.once('data', function (firstChunk) {
2016-09-27 21:56:06 +00:00
// 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)
process.nextTick(function () {
2016-09-30 02:20:38 +00:00
browser.unshift(firstChunk);
2016-09-27 21:56:06 +00:00
});
var service = 'tcp';
var servername;
var str;
var m;
function tryTls() {
2017-04-05 02:31:58 +00:00
var nextDevice;
if (-1 !== copts.servernames.indexOf(servername)) {
copts.httpsTunnel(servername, browser);
return;
}
nextDevice = Devices.next(deviceLists, servername);
if (!servername || !nextDevice) {
2016-09-28 05:26:16 +00:00
console.log('this is a server or an unknown');
2017-04-05 02:31:58 +00:00
copts.httpsInvalid(servername, browser);
2016-09-27 21:56:06 +00:00
return;
}
2017-04-05 02:31:58 +00:00
console.log("pipeWs(servername, service, socket, deviceLists['" + servername + "'])");
pipeWs(servername, service, browser, nextDevice);
2016-09-27 21:56:06 +00:00
}
// https://github.com/mscdex/httpolyglot/issues/3#issuecomment-173680155
if (22 === firstChunk[0]) {
// TLS
service = 'https';
servername = (sni(firstChunk)||'').toLowerCase();
2016-09-30 02:20:38 +00:00
console.log("tls hello servername:", servername);
2016-09-27 21:56:06 +00:00
tryTls();
return;
}
if (firstChunk[0] > 32 && firstChunk[0] < 127) {
str = firstChunk.toString();
2016-09-30 02:20:38 +00:00
m = str.match(/(?:^|[\r\n])Host: ([^\r\n]+)[\r\n]*/im);
servername = (m && m[1].toLowerCase() || '').split(':')[0];
console.log('servername', servername);
2016-09-27 21:56:06 +00:00
if (/HTTP\//i.test(str)) {
service = 'http';
2017-04-05 02:31:58 +00:00
if (/well-known/.test(str)) {
2016-09-27 21:56:06 +00:00
// HTTP
2017-04-05 02:31:58 +00:00
if (Devices.exist(deviceLists, servername)) {
pipeWs(servername, service, browser, Devices.next(deviceLists, servername));
2016-09-28 05:26:16 +00:00
return;
}
2017-04-05 02:31:58 +00:00
copts.handleInsecureHttp(servername, browser);
2016-09-27 21:56:06 +00:00
}
else {
// redirect to https
2017-04-05 02:31:58 +00:00
copts.handleInsecureHttp(servername, browser);
2016-09-27 21:56:06 +00:00
}
return;
}
}
console.error("Got unexpected connection", str);
2016-09-30 02:20:38 +00:00
browser.write(JSON.stringify({ error: {
2016-09-27 21:56:06 +00:00
message: "not sure what you were trying to do there..."
, code: 'E_INVALID_PROTOCOL' }
}));
2016-09-30 02:20:38 +00:00
browser.end();
2016-09-27 21:56:06 +00:00
});
2016-09-30 07:11:24 +00:00
browser.on('error', function (err) {
console.error('[error] tcp socket raw TODO forward and close');
console.error(err);
});
2016-09-27 21:56:06 +00:00
2016-10-01 05:52:37 +00:00
}
2017-04-05 02:31:58 +00:00
return { tcp: onTcpConnection, ws: onWsConnection };
2016-10-01 05:52:37 +00:00
};