I have a program that serves pages via http (without ssl). I want to make that secure. So I'm writing a nodejs program to use as a proxy server.
The nodejs program (proxy) will accept all the requests from the clients, repeat the requests to the server, receive the response and serve it back to the client.
Everything works except websocets!
I can see that the initial request and response behaves as expected:
request:
GET /wstest HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: qszv9wJR+ldyUuHgwOZOsv/2rQw=
Date: Sat, 17 Aug 2019 14
response:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: qszv9wJR+ldyUuHgwOZOsv/2rQw=
Date: Sat, 17 Aug 2019 14:17:13 GMT
Then the connection stays open and periodically I get some messages from the clients: 8A 00 (in hex)
Also Chrome 76.0.3809.100, Chrome Canary 78.0.3886.0 and FireFox have different behavior, and I not sure how to handle those messages.
Canary gets the message response from server, but Chrome doesn't. And in all browsers the ws connection status is always pending.
const fs = require("fs");
const https = require("https");
const net = require('net');
const source_hostname = "127.0.0.1";
const source_port = 80;
const destin_hostname = "127.0.0.1";
const destin_port = 8443;
const proxy_opt = {
pfx: fs.readFileSync("ssl/cert.pfx"),
passphrase: "###################"
};
const proxy = https.createServer(proxy_opt, (req, res) => { serve(req, res); });
proxy.listen(destin_port, destin_hostname, () => {
console.log(`Listening on: https://${destin_hostname}:${destin_port}/`);
});
const serve = (req, res) => {
let socket = new net.Socket();
let isFirst = true;
socket.on("data", data => {
let neck = findNeck(data);
let chunk_stop = data.length - 1;
let resArrayHead = data.subarray(0, neck).toString().trim().split("\r\n");
let statusCode = parseInt(resArrayHead[0].split(" ")[1]) || 400;
let headers = {};
//headers["Connection"] = "close";
for (let i = 1; i < resArrayHead.length; i++) {
let s = resArrayHead[i].split(":");
if (s.length == 1) continue;
headers[s[0].trim()] = s[1].trim();
}
if (headers["Transfer-Encoding"] == "chunked") { //handle chunked data
let precrop = neck;
for (let i=neck+1; i<Math.min(data.length, neck+8); i++)
if (data[i - 1] == 13 && data[i] == 10) {
neck = i + 1;
break;
}
let chunk_size=parseInt(data.subarray(precrop,neck).toString().trim(), 16);
chunk_stop = neck + chunk_size;
if (data[chunk_stop-4] == 48 &&
data[chunk_stop-3] == 13 &&
data[chunk_stop-2] == 10 &&
data[chunk_stop-1] == 13 &&
data[chunk_stop] == 10)
chunk_stop -= 5;
}
if (req.url == "/wstest") {
console.log(data[0], data[1], data[2], data[3]);
//console.log(" > ", headers);
//console.log(" < ", data);
}
if (isFirst) {
res.writeHead(statusCode, headers);
res.write(data.subarray(neck, chunk_stop));
} else
res.write(data);
isFirst = false;
});
socket.on("error", err => console.log("err: ", req.url, err));
socket.on("end", () => res.end());
req.on("data", chunk => {
socket.write(chunk);
});
req.on("end", () => socket.end());
let reqStringHead = "";
for (let key in req.headers)
reqStringHead += key + ": " + req.headers[key] + "\r\n";
reqStringHead += "X-Forwarded-For: " + source_hostname + "\r\n";
socket.connect(source_port, source_hostname);
socket.write(`${req.method} ${req.url} HTTP/1.1\r\n${reqStringHead}\r\n`);
};
const findNeck = (data) => { //Finds the point where head and body separates.
if (data == null && (data.length || 0) < 4) return 0;
let neck = 0;
for (neck = 3; neck < Math.min(data.length, 768); neck++)
if (data[neck - 3] == 13 &&
data[neck - 2] == 10 &&
data[neck - 1] == 13 &&
data[neck] == 10)
return neck;
return 0;
};