goldilocks.js/lib/goldilocks.js

310 lines
9.5 KiB
JavaScript

'use strict';
module.exports.create = function (deps, config) {
console.log('config', config);
//var PromiseA = global.Promise;
var PromiseA = require('bluebird');
var greenlock = require('greenlock');
var listeners = require('./servers').listeners;
var parseSni = require('sni');
var modules = { };
var program = {
tlsOptions: require('localhost.daplie.me-certificates').merge({})
, acmeDirectoryUrl: 'https://acme-v01.api.letsencrypt.org/directory'
, challengeType: 'tls-sni-01'
};
var secureContexts = {};
var tunnelAdminTlsOpts = {};
var tls = require('tls');
var tcpRouter = {
_map: { }
, _create: function (address, port) {
// port provides hinting for http, smtp, etc
return function (conn, firstChunk) {
console.log('[tcpRouter] ' + address + ':' + port + ' servername');
// At this point we cannot necessarily trace which port or address the socket came from
// (because node's netowrking layer == 💩 )
var m;
var str;
var servername;
// TODO test per-module
// Maybe HTTP
if (firstChunk[0] > 32 && firstChunk[0] < 127) {
str = firstChunk.toString();
m = str.match(/(?:^|[\r\n])Host: ([^\r\n]+)[\r\n]*/im);
servername = (m && m[1].toLowerCase() || '').split(':')[0];
//conn.__servername = servername;
console.log('[tcpRouter] hostname', servername);
if (/HTTP\//i.test(str)) {
//conn.__service = 'http';
}
}
console.log('1010');
if (!servername) {
// TODO allow tcp tunneling
// TODO we need some way of tagging tcp as either terminated tls or insecure
conn.write(
"HTTP/1.1 404 Not Found\r\n"
+ "Date: Fri, 31 Dec 1999 23:59:59 GMT\r\n"
+ "Content-Type: text/html\r\n"
+ "Content-Length: " + 9 + "\r\n"
+ "\r\n"
+ "Not Found"
);
conn.end();
return;
}
console.log('1020');
if (/\blocalhost\.admin\./.test(servername) || /\badmin\.localhost\./.test(servername)
|| /\blocalhost\.alpha\./.test(servername) || /\balpha\.localhost\./.test(servername)) {
console.log('1050');
if (!modules.admin) {
modules.admin = require('./modules/admin.js').create(deps, config);
}
console.log('1100');
modules.admin.emit('connection', conn);
console.log('1500');
return;
}
if (!modules.http) {
if (!modules.http) {
modules.http = require('./modules/http.js').create(deps, config);
}
modules.http.emit('connection', conn);
}
};
}
, get: function getTcpRouter(address, port) {
address = address || '0.0.0.0';
var id = address + ':' + port;
if (!tcpRouter._map[id]) {
tcpRouter._map[id] = tcpRouter._create(address, port);
}
return tcpRouter._map[id];
}
};
var tlsRouter = {
_map: { }
, _create: function (address, port) {
// port provides hinting for https, smtps, etc
return function (socket, servername) {
//program.tlsTunnelServer.emit('connection', socket);
//return;
console.log('[tlsRouter] ' + address + ':' + port + ' servername', servername);
var packerStream = require('tunnel-packer').Stream;
var myDuplex = packerStream.create(socket);
// needs to wind up in one of 3 states:
// 1. Proxied / Tunneled (we don't even need to put it through the tlsSocket)
// 2. Admin (skips normal processing)
// 3. Terminated (goes on to a particular module or route)
//myDuplex.__tlsTerminated = true;
program.tlsTunnelServer.emit('connection', myDuplex);
socket.on('data', function (chunk) {
console.log('[' + Date.now() + '] tls socket data', chunk.byteLength);
myDuplex.push(chunk);
});
socket.on('error', function (err) {
console.error('[error] httpsTunnel (Admin) TODO close');
console.error(err);
myDuplex.emit('error', err);
});
socket.on('close', function () {
myDuplex.close();
});
};
}
, get: function getTcpRouter(address, port) {
address = address || '0.0.0.0';
var id = address + ':' + port;
if (!tlsRouter._map[id]) {
tlsRouter._map[id] = tlsRouter._create(address, port);
}
return tlsRouter._map[id];
}
};
function handler(conn, opts) {
opts = opts || {};
console.log('[handler]', conn.localAddres, conn.localPort, opts.secure);
// TODO inspect SNI and HTTP Host
conn.once('data', function (firstChunk) {
var servername;
process.nextTick(function () {
conn.unshift(firstChunk);
});
// copying stuff over to firstChunk because the network abstraction goes too deep to find these again
//firstChunk.__port = conn.__port;
// TLS
if (22 === firstChunk[0]) {
servername = (parseSni(firstChunk)||'').toLowerCase() || 'localhost.invalid';
//conn.__servername = servername;
//conn.__tls = true;
//conn.__tlsTerminated = false;
//firstChunk.__servername = conn.__servername;
//firstChunk.__tls = true;
//firstChunk.__tlsTerminated = false;
console.log('tryTls');
tlsRouter.get(conn.localAddress, conn.localPort)(conn, servername);
}
else {
// TODO how to tag as insecure?
console.log('tryTcp');
tcpRouter.get(conn.localAddress, conn.localPort)(conn, firstChunk, { secure: opts.secure || false });
}
});
/*
if ('http' === config.tcp.default || !config.tcp.default) {
console.log('deal with as http');
}
*/
}
function approveDomains(opts, certs, cb) {
// This is where you check your database and associated
// email addresses with domains and agreements and such
// The domains being approved for the first time are listed in opts.domains
// Certs being renewed are listed in certs.altnames
function complete(err, stuff) {
opts.email = stuff.email;
opts.agreeTos = stuff.agreeTos;
opts.server = stuff.server;
opts.challengeType = stuff.challengeType;
cb(null, { options: opts, certs: certs });
}
if (certs) {
// TODO make sure the same options are used for renewal as for registration?
opts.domains = certs.altnames;
cb(null, { options: opts, certs: certs });
return;
}
// check config for domain name
if (-1 !== config.tls.servernames.indexOf(opts.domain)) {
// TODO how to handle SANs?
// TODO fetch domain-specific email
// TODO fetch domain-specific acmeDirectory
// NOTE: you can also change other options such as `challengeType` and `challenge`
// opts.challengeType = 'http-01';
// opts.challenge = require('le-challenge-fs').create({}); // TODO this doesn't actually work yet
complete(null, {
email: config.tls.email, agreeTos: true, server: program.acmeDirectoryUrl, challengeType: program.challengeType });
return;
}
// TODO ask http module about the default path (/srv/www/:hostname)
// (if it exists, we can allow and add to config)
if (!modules.http) {
modules.http = require('./modules/http.js').create(config);
}
modules.http.checkServername(opts.domain).then(function (stuff) {
if (!stuff.domains) {
// TODO once precheck is implemented we can just let it pass if it passes, yknow?
cb(new Error('domain is not allowed'));
return;
}
complete(null, {
domain: stuff.domain || stuff.domains[0]
, domains: stuff.domains
, email: program.email
, server: program.acmeDirectoryUrl
, challengeType: program.challengeType
});
return;
}, cb);
}
function getAcme() {
return greenlock.create({
//server: 'staging'
server: 'https://acme-v01.api.letsencrypt.org/directory'
, challenges: {
// TODO dns-01
'http-01': require('le-challenge-fs').create({ webrootPath: '/tmp/acme-challenges', debug: config.debug })
, 'tls-sni-01': require('le-challenge-sni').create({ debug: config.debug })
//, 'dns-01': require('le-challenge-ddns').create()
}
, store: require('le-store-certbot').create({ webrootPath: '/tmp/acme-challenges' })
//, email: program.email
//, agreeTos: program.agreeTos
, approveDomains: approveDomains
//, approvedDomains: program.servernames
});
}
Object.keys(program.tlsOptions).forEach(function (key) {
tunnelAdminTlsOpts[key] = program.tlsOptions[key];
});
tunnelAdminTlsOpts.SNICallback = function (sni, cb) {
console.log("[tlsOptions.SNICallback] SNI: '" + sni + "'");
var tlsOptions;
// Static Certs
if (/.*localhost.*\.daplie\.me/.test(sni.toLowerCase())) {
// TODO implement
if (!secureContexts[sni]) {
tlsOptions = require('localhost.daplie.me-certificates').mergeTlsOptions(sni, {});
}
if (tlsOptions) {
secureContexts[sni] = tls.createSecureContext(tlsOptions);
}
if (secureContexts[sni]) {
console.log('Got static secure context:', sni, secureContexts[sni]);
cb(null, secureContexts[sni]);
return;
}
}
if (!program.greenlock) {
program.greenlock = getAcme();
}
(program.greenlock.tlsOptions||program.greenlock.httpsOptions).SNICallback(servername, cb);
};
program.tlsTunnelServer = tls.createServer(tunnelAdminTlsOpts, function (tlsSocket) {
console.log('(pre-terminated) tls connection');
// things get a little messed up here
//tlsSocket.on('data', function (chunk) {
// console.log('terminated data:', chunk.toString());
//});
//(program.httpTunnelServer || program.httpServer).emit('connection', tlsSocket);
//tcpRouter.get(conn.localAddress, conn.localPort)(conn, firstChunk, { secure: false });
handler(tlsSocket, { secure: true });
});
PromiseA.all(config.tcp.ports.map(function (port) {
return listeners.tcp.add(port, handler);
}));
};