NodeJS TCP代理和TCP服务器

时间:2018-07-09 08:46:32

标签: node.js sockets tcp

我正在运行DebianNodeJS

我正在尝试同时构建TCP ProxyTCP Server,这就是IP packet流程:

clients (10.1.10.10/10) <-> TCP Proxy <-> TCP Server <-> internet

我的tcp-proxy.js如下:

var net = require("net");

process.on("uncaughtException", function(error) {
  console.error(error);
});

var localport = 4000;
var remotehost = '159.21.91.10';
var remoteport = 5000;

var server = net.createServer(function (localsocket) {

  var remotesocket = new net.Socket();
  remotesocket.connect(remoteport, remotehost);

  localsocket.on('connect', function (data) {
    console.log(">>> connection #%d from %s:%d", server.connections, localsocket.remoteAddress, localsocket.remotePort);
  });

  localsocket.on('data', function (data) {
    console.log("%s:%d - writing data to remote", localsocket.remoteAddress, localsocket.remotePort);

    var flushed = remotesocket.write(data);
    if (!flushed) {
      console.log("  remote not flushed; pausing local");
      localsocket.pause();
    }
  });

  remotesocket.on('data', function(data) {
    console.log("%s:%d - writing data to local", localsocket.remoteAddress, localsocket.remotePort);

    var flushed = localsocket.write(data);
    if (!flushed) {
      console.log("  local not flushed; pausing remote");
      remotesocket.pause();
    }
  });

  localsocket.on('drain', function() {
    console.log("%s:%d - resuming remote", localsocket.remoteAddress, localsocket.remotePort);

    remotesocket.resume();
  });

  remotesocket.on('drain', function() {
    console.log("%s:%d - resuming local", localsocket.remoteAddress, localsocket.remotePort);

    localsocket.resume();
  });

  localsocket.on('close', function(had_error) {
    console.log("%s:%d - closing remote", localsocket.remoteAddress, localsocket.remotePort);

    remotesocket.end();
  });

  remotesocket.on('close', function(had_error) {
    console.log("%s:%d - closing local", localsocket.remoteAddress, localsocket.remotePort);

    localsocket.end();
  });

});

server.listen(localport);

我的tcp-server.js如下:

var net = require('net');

var server = net.createServer(function (socket) {

  console.log(">>> connection #%d from %s:%d",
    server.connections,
    socket.remoteAddress,
    socket.remotePort
  );

  socket.pipe(socket);

});

server.listen(5000);

在客户端,我的TCP ProxyTCP Server之间似乎有数据流,但是在客户端上运行:

curl google.com

从不在客户端上返回HTTP数据包,并且在TCP Server上运行该HTTP数据包将永远不会显示10.1.10.10/10范围内的任何内部IP地址:

tshark -i any -Y "ip.addr == 10.1.10.10/10"

如果我收到任何具有该IP的数据包,我会NAT到公共IP地址以获取数据包。

在我的TCP Proxy上,我有以下东西要通过TCP来捕获iptables数据包:

iptables -t nat -A PREROUTING -s 10.1.10.10/10 -p tcp -j REDIRECT --to-port 4000

当我在客户端上执行curl google.com时,我从tcp-server.js得到以下输出:

::ffff:139.29.91.11:45346 - writing data to remote
GET / HTTP/1.1
User-Agent: curl/7.38.0
Host: google.com
Accept: */*

所以请求通过了,但是我希望tcp-server.js实际上向客户提供google.com HTTP数据包,并且我希望能够看到客户{{1} }地址,而不是我的IP地址。

0 个答案:

没有答案