Reverse proxy detection in socket.io
authorDarren <darren@darrenwhitlen.com>
Fri, 19 Oct 2012 17:49:10 +0000 (18:49 +0100)
committerDarren <darren@darrenwhitlen.com>
Fri, 19 Oct 2012 17:49:10 +0000 (18:49 +0100)
server/app.js

index f3b15488e0673b6fbd279676ef173041c257edee..7668bfcc723a1ccb144685688e921fc17fff3378 100644 (file)
@@ -721,6 +721,23 @@ this.websocketListen = function (servers, handler) {
 
         io.of('/kiwi').authorization(function (handshakeData, callback) {
             var address = handshakeData.address.address;
+
+            // If a forwarded-for header is found, switch the source address
+            if (handshakeData.headers['x-forwarded-for']) {
+                // Check we're connecting from a whitelisted proxy
+                if (!kiwi.config.http_proxies
+                    || kiwi.config.http_proxies.indexOf(address) < 0)
+                {
+                    console.log('Unlisted proxy:', address);
+                    websocket.disconnect();
+                    return;
+                }
+
+                // We're sent from a whitelisted proxy, replace the hosts
+                address = handshakeData.headers['x-forwarded-for'];
+            }
+
+    
             if (typeof kiwi.connections[address] === 'undefined') {
                 kiwi.connections[address] = {count: 0, sockets: []};
             }
@@ -736,9 +753,28 @@ this.websocketListen = function (servers, handler) {
 
 
 this.websocketConnection = function (websocket) {
-    var con;
-    kiwi.log("New connection!");
-    websocket.kiwi = {address: websocket.handshake.address.address, buffer: {list: []}};
+    var con, address;
+
+    address = websocket.handshake.address.address;
+
+    // If a forwarded-for header is found, switch the source address
+    if (websocket.handshake.headers['x-forwarded-for']) {
+        // Check we're connecting from a whitelisted proxy
+        if (!kiwi.config.http_proxies
+            || kiwi.config.http_proxies.indexOf(address) < 0)
+        {
+            console.log('Unlisted proxy:', address);
+            websocket.disconnect();
+            return;
+        }
+
+        // We're sent from a whitelisted proxy, replace the hosts
+        address = websocket.handshake.headers['x-forwarded-for'];
+    }
+
+    kiwi.log('New connection! ' + address);
+
+    websocket.kiwi = {address: address, buffer: {list: []}};
     con = kiwi.connections[websocket.kiwi.address];
 
     if (con.count >= kiwi.config.max_client_conns) {
@@ -811,7 +847,6 @@ this.IRCConnection = function (websocket, nick, host, port, ssl, password, callb
 
             websocket.sendServerLine('CAP LS');
             websocket.sendServerLine('NICK ' + nick);
-            console.log('SENDING ', 'USER kiwi_' + nick.replace(/[^0-9a-zA-Z\-_.]/, '') + ' 0 0 :' + realname);
             websocket.sendServerLine('USER kiwi_' + nick.replace(/[^0-9a-zA-Z\-_.]/, '') + ' 0 0 :' + realname);
 
             that.connected = true;