如何在Node.js中创建TLS隧道

How to create a TLS tunnel in Node.js

本文关键字:创建 TLS 隧道 js Node      更新时间:2023-12-10

我正在尝试将node.js服务器接收到的流量隧道传输到TLS连接。我有一些这样的代码:

function tunnel() {
  var c = tls.connect(443, 'myhost', {rejectUnauthorized: false});
  var server = net.createServer(function (socket) {
    socket.addListener("connect", function () {
      console.log("Connection from " + socket.remoteAddress);
      //sync the file descriptors, so that the socket data structures are the same
      c.fd = socket.fd;
      //pipe the incoming data from the client directly onto the server
      c.pipe(socket);
      //and the response from the server back to the client
      socket.pipe(c);
    });
    socket.addListener("data", function (data) {
      console.log("Data received from client");
    });
    socket.addListener("close", function () {
      server.close();
    });
  });
  server.listen(7000);
}

当我运行并测试它时,我在我的终端中看到了这个:

$ curl --insecure https://myhost:443
hello world
$ curl --insecure https://localhost:7000
# nothing... just hangs

在服务器控制台中,我看到Data received from client,但从未看到connect回调。

我走对了吗?

传递给服务器的connection事件处理程序(传递给createServer()的回调)的套接字已连接,因此永远不会有connect事件(即使用net.connect()/tls.connect()创建的客户端套接字)。

以下是只接受一个连接的代理:

net.createServer(function(socket) {
  server.close(); // Stop listening for additional connections
  var upstream = tls.connect(443, 'myhost', {rejectUnauthorized: false});
  socket.pipe(upstream).pipe(socket);
}).listen(7000);

我还应该指出,使用rejectUnauthorized: false是不安全的。如果您使用它是因为上游服务器使用自签名证书,那么您应该将ca选项设置为自签名CA。这将允许CA签署证书,并防止MITM攻击。