forked from coolaj86/goldilocks.js
		
	
		
			
				
	
	
		
			318 lines
		
	
	
		
			10 KiB
		
	
	
	
		
			JavaScript
		
	
	
	
	
	
			
		
		
	
	
			318 lines
		
	
	
		
			10 KiB
		
	
	
	
		
			JavaScript
		
	
	
	
	
	
'use strict';
 | 
						|
 | 
						|
module.exports.create = function (deps, config, netHandler) {
 | 
						|
  var tls = require('tls');
 | 
						|
  var parseSni = require('sni');
 | 
						|
  var greenlock = require('greenlock');
 | 
						|
  var localhostCerts = require('localhost.daplie.me-certificates');
 | 
						|
  var domainMatches = require('../domain-utils').match;
 | 
						|
 | 
						|
  function extractSocketProp(socket, propName) {
 | 
						|
    // remoteAddress, remotePort... ugh... https://github.com/nodejs/node/issues/8854
 | 
						|
    var value = socket[propName] || socket['_' + propName];
 | 
						|
    try {
 | 
						|
      value = value || socket._handle._parent.owner.stream[propName];
 | 
						|
    } catch (e) {}
 | 
						|
 | 
						|
    try {
 | 
						|
      value = value || socket._handle._parentWrap[propName];
 | 
						|
      value = value || socket._handle._parentWrap._handle.owner.stream[propName];
 | 
						|
    } catch (e) {}
 | 
						|
 | 
						|
    return value || '';
 | 
						|
  }
 | 
						|
 | 
						|
  function nameMatchesDomains(name, domains) {
 | 
						|
    return domains.some(function (pattern) {
 | 
						|
      return domainMatches(pattern, name);
 | 
						|
    });
 | 
						|
  }
 | 
						|
 | 
						|
  var addressNames = [
 | 
						|
    'remoteAddress'
 | 
						|
  , 'remotePort'
 | 
						|
  , 'remoteFamily'
 | 
						|
  , 'localAddress'
 | 
						|
  , 'localPort'
 | 
						|
  ];
 | 
						|
  function wrapSocket(socket, opts) {
 | 
						|
    if (!opts.hyperPeek) {
 | 
						|
      process.nextTick(function () {
 | 
						|
        socket.unshift(opts.firstChunk);
 | 
						|
      });
 | 
						|
    }
 | 
						|
 | 
						|
    var wrapped = require('tunnel-packer').wrapSocket(socket);
 | 
						|
    addressNames.forEach(function (name) {
 | 
						|
      wrapped[name] = opts[name] || wrapped[name];
 | 
						|
    });
 | 
						|
    return wrapped;
 | 
						|
  }
 | 
						|
 | 
						|
  var le = greenlock.create({
 | 
						|
    server: 'https://acme-v01.api.letsencrypt.org/directory'
 | 
						|
 | 
						|
  , challenges: {
 | 
						|
      'http-01': require('le-challenge-fs').create({ debug: config.debug })
 | 
						|
    , 'tls-sni-01': require('le-challenge-sni').create({ debug: config.debug })
 | 
						|
      // TODO dns-01
 | 
						|
      //, 'dns-01': require('le-challenge-ddns').create({ debug: config.debug })
 | 
						|
    }
 | 
						|
  , challengeType: 'http-01'
 | 
						|
 | 
						|
  , store: require('le-store-certbot').create({ debug: config.debug })
 | 
						|
 | 
						|
  , approveDomains: function (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
 | 
						|
      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;
 | 
						|
      }
 | 
						|
 | 
						|
      function complete(optsOverride, domains) {
 | 
						|
        if (!cb) {
 | 
						|
          console.warn('tried to complete domain approval multiple times');
 | 
						|
          return;
 | 
						|
        }
 | 
						|
 | 
						|
        // // We can't request certificates for wildcard domains, so filter any of those
 | 
						|
        // // out of this list and put the domain that triggered this in the list if needed.
 | 
						|
        // domains = (domains || []).filter(function (dom) { return dom[0] !== '*'; });
 | 
						|
        // if (domains.indexOf(opts.domain) < 0) {
 | 
						|
        //   domains.push(opts.domain);
 | 
						|
        // }
 | 
						|
        domains = [ opts.domain ];
 | 
						|
        // TODO: allow user to specify options for challenges or storage.
 | 
						|
 | 
						|
        Object.assign(opts, optsOverride, { domains: domains, agreeTos: true });
 | 
						|
        cb(null, { options: opts, certs: certs });
 | 
						|
        cb = null;
 | 
						|
      }
 | 
						|
 | 
						|
      var handled = false;
 | 
						|
      if (Array.isArray(config.tls.domains)) {
 | 
						|
        handled = config.tls.domains.some(function (dom) {
 | 
						|
          if (!nameMatchesDomains(opts.domain, dom.names)) {
 | 
						|
            return false;
 | 
						|
          }
 | 
						|
 | 
						|
          return dom.modules.some(function (mod) {
 | 
						|
            if (mod.name !== 'acme') {
 | 
						|
              return false;
 | 
						|
            }
 | 
						|
            complete(mod, dom.names);
 | 
						|
            return true;
 | 
						|
          });
 | 
						|
        });
 | 
						|
      }
 | 
						|
      if (handled) {
 | 
						|
        return;
 | 
						|
      }
 | 
						|
 | 
						|
      if (Array.isArray(config.tls.modules)) {
 | 
						|
        handled = config.tls.modules.some(function (mod) {
 | 
						|
          if (mod.name !== 'acme') {
 | 
						|
            return false;
 | 
						|
          }
 | 
						|
          if (!nameMatchesDomains(opts.domain, mod.domains)) {
 | 
						|
            return false;
 | 
						|
          }
 | 
						|
 | 
						|
          complete(mod, mod.domains);
 | 
						|
          return true;
 | 
						|
        });
 | 
						|
      }
 | 
						|
      if (handled) {
 | 
						|
        return;
 | 
						|
      }
 | 
						|
 | 
						|
      var defAcmeConf;
 | 
						|
      if (config.tls.acme) {
 | 
						|
        defAcmeConf = config.tls.acme;
 | 
						|
      } else {
 | 
						|
        defAcmeConf = {
 | 
						|
          email: config.tls.email
 | 
						|
        , server: config.tls.acmeDirectoryUrl || le.server
 | 
						|
        , challengeType: config.tls.challengeType || le.challengeType
 | 
						|
        , approvedDomains: config.tls.servernames
 | 
						|
        };
 | 
						|
      }
 | 
						|
 | 
						|
      // Check config for domain name
 | 
						|
      // TODO: if `approvedDomains` isn't defined check all other modules to see if they can
 | 
						|
      // handle this domain (and what other domains it's grouped with).
 | 
						|
      if (-1 !== (defAcmeConf.approvedDomains || []).indexOf(opts.domain)) {
 | 
						|
        complete(defAcmeConf, defAcmeConf.approvedDomains);
 | 
						|
        return;
 | 
						|
      }
 | 
						|
 | 
						|
      cb(new Error('domain is not allowed'));
 | 
						|
    }
 | 
						|
  });
 | 
						|
  le.tlsOptions = le.tlsOptions || le.httpsOptions;
 | 
						|
 | 
						|
  var secureContexts = {};
 | 
						|
  var terminatorOpts = require('localhost.daplie.me-certificates').merge({});
 | 
						|
  terminatorOpts.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 = localhostCerts.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;
 | 
						|
      }
 | 
						|
    }
 | 
						|
 | 
						|
    le.tlsOptions.SNICallback(sni, cb);
 | 
						|
  };
 | 
						|
 | 
						|
  var terminateServer = tls.createServer(terminatorOpts, function (socket) {
 | 
						|
    console.log('(post-terminated) tls connection, addr:', extractSocketProp(socket, 'remoteAddress'));
 | 
						|
 | 
						|
    netHandler(socket, {
 | 
						|
      servername: socket.servername
 | 
						|
    , encrypted: true
 | 
						|
      // remoteAddress... ugh... https://github.com/nodejs/node/issues/8854
 | 
						|
    , remoteAddress: extractSocketProp(socket, 'remoteAddress')
 | 
						|
    , remotePort:    extractSocketProp(socket, 'remotePort')
 | 
						|
    , remoteFamily:  extractSocketProp(socket, 'remoteFamily')
 | 
						|
    });
 | 
						|
  });
 | 
						|
  terminateServer.on('error', function (err) {
 | 
						|
    console.log('[error] TLS termination server', err);
 | 
						|
  });
 | 
						|
 | 
						|
  function proxy(socket, opts, mod) {
 | 
						|
    var newConnOpts = require('../domain-utils').separatePort(mod.address || '');
 | 
						|
    newConnOpts.port = newConnOpts.port || mod.port;
 | 
						|
    newConnOpts.host = newConnOpts.host || mod.host || 'localhost';
 | 
						|
    newConnOpts.servername = opts.servername;
 | 
						|
    newConnOpts.data = opts.firstChunk;
 | 
						|
 | 
						|
    newConnOpts.remoteFamily  = opts.family  || extractSocketProp(socket, 'remoteFamily');
 | 
						|
    newConnOpts.remoteAddress = opts.address || extractSocketProp(socket, 'remoteAddress');
 | 
						|
    newConnOpts.remotePort    = opts.port    || extractSocketProp(socket, 'remotePort');
 | 
						|
 | 
						|
    deps.proxy(socket, newConnOpts, opts.firstChunk, function () {
 | 
						|
      // This function is called in the event of a connection error and should decrypt
 | 
						|
      // the socket so the proxy module can send a 502 HTTP response.
 | 
						|
      var tlsOpts = localhostCerts.mergeTlsOptions('localhost.daplie.me', {isServer: true});
 | 
						|
      if (opts.hyperPeek) {
 | 
						|
        return new tls.TLSSocket(socket, tlsOpts);
 | 
						|
      } else {
 | 
						|
        return new tls.TLSSocket(wrapSocket(socket, opts), tlsOpts);
 | 
						|
      }
 | 
						|
    });
 | 
						|
    return true;
 | 
						|
  }
 | 
						|
 | 
						|
  function terminate(socket, opts) {
 | 
						|
    console.log(
 | 
						|
      '[tls-terminate]'
 | 
						|
    , opts.localAddress || socket.localAddress +':'+ opts.localPort || socket.localPort
 | 
						|
    , 'servername=' + opts.servername
 | 
						|
    , opts.remoteAddress || socket.remoteAddress
 | 
						|
    );
 | 
						|
 | 
						|
    if (opts.hyperPeek) {
 | 
						|
      // This connection was peeked at using a method that doesn't interferre with the TLS
 | 
						|
      // server's ability to handle it properly. Currently the only way this happens is
 | 
						|
      // with tunnel connections where we have the first chunk of data before creating the
 | 
						|
      // new connection (thus removing need to get data off the new connection).
 | 
						|
      terminateServer.emit('connection', socket);
 | 
						|
    }
 | 
						|
    else {
 | 
						|
      // The hyperPeek flag wasn't set, so we had to read data off of this connection, which
 | 
						|
      // means we can no longer use it directly in the TLS server.
 | 
						|
      // See https://github.com/nodejs/node/issues/8752 (node's internal networking layer == 💩 sometimes)
 | 
						|
      terminateServer.emit('connection', wrapSocket(socket, opts));
 | 
						|
    }
 | 
						|
  }
 | 
						|
 | 
						|
  function handleConn(socket, opts) {
 | 
						|
    opts.servername = (parseSni(opts.firstChunk)||'').toLowerCase() || 'localhost.invalid';
 | 
						|
    // needs to wind up in one of 2 states:
 | 
						|
    // 1. SNI-based Proxy / Tunnel (we don't even need to put it through the tlsSocket)
 | 
						|
    // 2. Terminated (goes on to a particular module or route, including the admin interface)
 | 
						|
    // 3. Closed (we don't recognize the SNI servername as something we actually want to handle)
 | 
						|
 | 
						|
    // We always want to terminate is the SNI matches the challenge pattern, unless a client
 | 
						|
    // on the south side has temporarily claimed a particular challenge. For the time being
 | 
						|
    // we don't have a way for the south-side to communicate with us, so that part isn't done.
 | 
						|
    if (domainMatches('*.acme-challenge.invalid', opts.servername)) {
 | 
						|
      terminate(socket, opts);
 | 
						|
      return;
 | 
						|
    }
 | 
						|
 | 
						|
    if (deps.tunnelServer.isClientDomain(opts.servername)) {
 | 
						|
      deps.tunnelServer.handleClientConn(socket);
 | 
						|
      if (!opts.hyperPeek) {
 | 
						|
        process.nextTick(function () {
 | 
						|
          socket.unshift(opts.firstChunk);
 | 
						|
        });
 | 
						|
      }
 | 
						|
      return;
 | 
						|
    }
 | 
						|
 | 
						|
    function checkModule(mod) {
 | 
						|
      if (mod.name === 'proxy') {
 | 
						|
        return proxy(socket, opts, mod);
 | 
						|
      }
 | 
						|
      if (mod.name !== 'acme') {
 | 
						|
        console.error('saw unknown TLS module', mod);
 | 
						|
      }
 | 
						|
    }
 | 
						|
 | 
						|
    var handled = (config.tls.domains || []).some(function (dom) {
 | 
						|
      if (!nameMatchesDomains(opts.servername, dom.names)) {
 | 
						|
        return false;
 | 
						|
      }
 | 
						|
 | 
						|
      return dom.modules.some(checkModule);
 | 
						|
    });
 | 
						|
    if (handled) {
 | 
						|
      return;
 | 
						|
    }
 | 
						|
 | 
						|
    handled = (config.tls.modules || []).some(function (mod) {
 | 
						|
      if (!nameMatchesDomains(opts.servername, mod.domains)) {
 | 
						|
        return false;
 | 
						|
      }
 | 
						|
      return checkModule(mod);
 | 
						|
    });
 | 
						|
    if (handled) {
 | 
						|
      return;
 | 
						|
    }
 | 
						|
 | 
						|
    // TODO: figure out all of the domains that the other modules intend to handle, and only
 | 
						|
    // terminate those ones, closing connections for all others.
 | 
						|
    terminate(socket, opts);
 | 
						|
  }
 | 
						|
 | 
						|
  return {
 | 
						|
    emit: function (type, socket) {
 | 
						|
      if (type === 'connection') {
 | 
						|
        handleConn(socket, socket.__opts);
 | 
						|
      }
 | 
						|
    }
 | 
						|
  , middleware: le.middleware()
 | 
						|
  };
 | 
						|
};
 |