2

I have created a bare-bones HTTP proxy that performs HTTP tunnelling using HTTP CONNECT method.

const http = require('http');
const https = require('https');
const pem = require('pem');
const net = require('net');
const util = require('util');

const createHttpsServer = (callback) => {
  pem.createCertificate({
    days: 365,
    selfSigned: true
  }, (error, {serviceKey, certificate, csr}) => {
    const httpsOptions = {
      ca: csr,
      cert: certificate,
      key: serviceKey
    };

    const server = https.createServer(httpsOptions, (req, res) => {
      // How do I know I here whats the target server port?

      res.writeHead(200);
      res.end('OK');
    });

    server.listen((error) => {
      if (error) {
        console.error(error);
      } else {
        callback(null, server.address().port);
      }
    });
  });
};

const createProxy = (httpsServerPort) => {
  const proxy = http.createServer();

  proxy.on('connect', (request, requestSocket, head) => {
    // Here I know whats the target server PORT.
    const targetServerPort = Number(request.url.split(':')[1]);

    console.log('target server port', targetServerPort);

    const serverSocket = net.connect(httpsServerPort, 'localhost', () => {
      requestSocket.write(
        'HTTP/1.1 200 Connection established\r\n\r\n'
      );

      serverSocket.write(head);
      serverSocket.pipe(requestSocket);
      requestSocket.pipe(serverSocket);
    });
  });

  proxy.listen(9000);
};

const main = () => {
  createHttpsServer((error, httpsServerPort) => {
    if (error) {
      console.error(error);
    } else {
      createProxy(httpsServerPort);
    }
  });
};

main();

The server accepts a HTTPS connection and responds with "OK" message without forwarding the request further.

As you can see in the code (see // Here I know whats the target server PORT.), I can obtain the target server's port within the HTTP CONNECT event handler. However, I am unable to figure out how to pass this information to the createHttpsServer HTTP server router (see // How do I know I here whats the target server port?).

When tunnelling a TLS connection, how to pass additional information?

The above code can be tested by running:

$ node proxy.js &
$ curl --proxy http://localhost:9000 https://localhost:59194/foo.html -k

The objective is to respond with "OK localhost:59194".

1

1 Answer 1

2

You can't add anything to a TLS stream (thankfully), short of tunneling it inside another protocol⁠—which is what the Connect method already does. But, since you have the HTTP proxy and the HTTPS server in the same codebase, you don't need to fling the TLS stream over the network another time. Instead, you want to parse the TLS stream, and then you can pass any variables to the code that handles it.

However, after parsing TLS you'll still have a raw HTTP stream, and you'll need an HTTP server to turn it into requests and to handle responses.

The quick and rather dirty way to go about it is to use Node's HTTPS server to both decode TLS and parse HTTP. But the server's API doesn't provide for dealing with sockets that are already connected, and server's code isn't cleanly separated from connection code. So you need to hijack the server's internal connection-handling logic—this is of course susceptible to breakage in case of future changes:

const http = require('http');
const https = require('https');
const pem = require('pem');

const createProxy = (httpsOptions) => {
    const proxy = http.createServer();

    proxy.on('connect', (request, requestSocket, head) => {
        const server = https.createServer(httpsOptions, (req, res) => {
            res.writeHead(200);
            res.end('OK');
        });
        server.emit('connection', requestSocket);
        requestSocket.write('HTTP/1.1 200 Connection established\r\n\r\n');
    });

    proxy.listen(9000);
};

const main = () => {
    pem.createCertificate({
        days: 365,
        selfSigned: true
    }, (error, {serviceKey, certificate, csr}) => {
        createProxy({
            ca: csr,
            cert: certificate,
            key: serviceKey
        });
    });
};

main();

To avoid creating an HTTPS server instance on every request, you can move the instance out and tack you data onto the socket object instead:

const server = https.createServer(httpsOptions, (req, res) => {
    res.writeHead(200);
    // here we reach to the net.Socket instance saved on the tls.TLSSocket object,
    // for extra dirtiness
    res.end('OK ' + req.socket._parent.marker + '\n');
});

proxy.on('connect', (request, requestSocket, head) => {
    requestSocket.marker = Math.random();
    server.emit('connection', requestSocket);
    requestSocket.write('HTTP/1.1 200 Connection established\r\n\r\n');
});

With the above code, if you do several successive requests:

curl --proxy http://localhost:9000 https://localhost:59194/foo.html \
     https://localhost:59194/foo.html https://localhost:59194/foo.html \
     https://localhost:59194/foo.html https://localhost:59194/foo.html -k

then you'll also notice that they're processed on a single connection, which is nice:

OK 0.6113572936982015
OK 0.6113572936982015
OK 0.6113572936982015
OK 0.6113572936982015
OK 0.6113572936982015

I can't quite vouch that nothing will be broken by handing the socket to the HTTPS server while the proxy server already manages it. [The server has the presence of mind to not overwrite another instance on the socket object](https://github.com/nodejs/node/blob/v10.9.0/lib/_http_server.js#L331), but otherwise seems to be rather closely involved with the socket. You'll want to test it with longer-running connections.
As for the `head` argument, [which can indeed contain initial data](https://www.rfc-editor.org/rfc/rfc2817#section-5.2):
  • you might be able to put it back on the stream with requestSocket.unshift(head), but I'm not sure that it won't be immediately consumed by the proxy server.
  • Or, you might be able to chuck it over to the HTTPS server with requestSocket.emit('data', head) since the HTTP server seems to use the stream events, however TLS socket source calls read() for whatever reason, and that's mutually exclusive with the events, so I'm not sure how they even work with each other.
  • One solution would be to make your own wrapper for stream.Duplex that will forward all calls and events, except for read() in the case when this initial buffer exists—and then use this wrapper in place of requestSocket. But you'll then need to replicate the 'data' event also, in accordance with the logic of Node's readable streams.
  • Finally, you can try creating a new duplex stream, write head and pipe the socket to it, like you did initially, and use the stream in place of the socket for the HTTPS server—not sure that it will be compatible with HTTP server's rather overbearing management of the socket.




An cleaner approach is to decode the TLS stream and use a standalone parser for the resultant HTTP stream. Thankfully, Node has a tls module that is nicely isolated and turns TLS sockets into regular sockets:

proxy.on('connect', (request, requestSocket, head) => {
    const httpSocket = new tls.TLSSocket(requestSocket, {
        isServer: true,
        // this var can be reused for all requests,
        // as it's normally saved on an HTTPS server instance
        secureContext: tls.createSecureContext(httpsOptions)
    });

    ...
});

See caveats on tls.createSecureContext regarding replicating the behavior of the HTTPS server.

Alas, Node's HTTP parser isn't so usable: it's a C library, which necessitates quite a bit of legwork between the socket and the parser calls. And the API can (and does) change between versions, without warnings, with a larger surface for incompatibilities compared to the HTTP server internals used above.

There are NPM modules for parsing HTTP: e.g. one, two, but none seem too mature and maintained.

I also have doubts about the feasibility of a custom HTTP server because network sockets tend to require plenty of nurture over time due to edge cases, with hard-to-debug timeout issues and such—which should all be already accounted for in the Node's HTTP server.




P.S. One possible area of investigation is how the Cluster module handles connections: afaik the parent process in a cluster hands connection sockets over to the children, but it doesn't fork on every request—which suggests that the child processes somehow deal with connected sockets, in code that's outside of an HTTP server instance. However, since the Cluster module is now in the core, it may exploit non-public APIs.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.