I'm trying to tunnel traffic received by my node.js server to a TLS connection. I have some code like this:
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);
}
When I run it and test it, I see this in my terminal:
$ curl --insecure https://myhost:443
hello world
$ curl --insecure https://localhost:7000
# nothing... just hangs
In the server console, I see Data received from client
, but never the connect
callback.
Am I on the right track?
答案 0 :(得分:0)
Sockets passed to a server's connection
event handler (the callback you pass to createServer()
) are already connected, so there will never be a connect
event (that is for client sockets created with net.connect()
/tls.connect()
).
Here is what a proxy would look like that only accepts one connection:
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);
I should also point out that using rejectUnauthorized: false
is not secure. If you are using that because the upstream server is using a self-signed certificate, then you should instead set the ca
option to the self-signed CA. This will allow certificates signed by the CA and prevent MITM attacks.