Skip to content

Node.js based forum software built for the modern web

fix: socket.io ip resolution

Barış Soner Uşaklıa95db1e9f2c7
diff --git a/install/package.json b/install/package.json
index f368319fad..8d5524f481 100644
--- a/install/package.json
+++ b/install/package.json
@@ -129,6 +129,7 @@
"pretty": "^2.0.0",
"progress-webpack-plugin": "1.0.16",
"prompt": "1.3.0",
+ "proxy-addr": "2.0.7",
"qs": "6.15.3",
"redis": "5.12.1",
"rimraf": "6.1.3",
diff --git a/src/meta/blacklist.js b/src/meta/blacklist.js
index 7a2cae5a73..6fd8811d9e 100644
--- a/src/meta/blacklist.js
+++ b/src/meta/blacklist.js
@@ -57,36 +57,46 @@ Blacklist.test = async function (clientIp) {
if (!clientIp) {
return;
}
- clientIp = clientIp.split(':').length === 2 ? clientIp.split(':')[0] : clientIp;
+ const parts = clientIp.split(':');
+ if (parts.length === 2) {
+ clientIp = parts[0];
+ }
if (!validator.isIP(clientIp)) {
throw new Error('[[error:invalid-ip]]');
}
+ let addr;
+ try {
+ addr = ipaddr.parse(clientIp);
+ // Normalize IPv4-mapped IPv6 addresses (::ffff:x.x.x.x) to plain IPv4
+ if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) {
+ addr = addr.toIPv4Address();
+ clientIp = addr.toString();
+ }
+ } catch (err) {
+ winston.error(`[meta/blacklist] Error parsing client IP : ${clientIp}`);
+ throw err;
+ }
+
const rules = Blacklist._rules;
- function checkCidrRange(clientIP) {
+ function checkCidrRange(address) {
if (!rules.cidr.length) {
return false;
}
- let addr;
- try {
- addr = ipaddr.parse(clientIP);
- } catch (err) {
- winston.error(`[meta/blacklist] Error parsing client IP : ${clientIp}`);
- throw err;
- }
+
return rules.cidr.some((subnet) => {
const cidr = ipaddr.parseCIDR(subnet);
- if (addr.kind() !== cidr[0].kind()) {
+ if (address.kind() !== cidr[0].kind()) {
return false;
}
- return addr.match(cidr);
+ return address.match(cidr);
});
}
if (rules.ipv4.includes(clientIp) ||
rules.ipv6.includes(clientIp) ||
- checkCidrRange(clientIp)) {
+ checkCidrRange(addr)) {
const err = new Error('[[error:blacklisted-ip]]');
err.code = 'blacklisted-ip';
diff --git a/src/socket.io/index.js b/src/socket.io/index.js
index e407524629..8173423082 100644
--- a/src/socket.io/index.js
+++ b/src/socket.io/index.js
@@ -14,6 +14,7 @@ const ratelimit = require('../middleware/ratelimit');
const blacklist = require('../meta/blacklist');
const als = require('../als');
const apiHelpers = require('../api/helpers');
+const socketIp = require('./utils/ip');
const Namespaces = Object.create(null);
@@ -85,10 +86,7 @@ Sockets.init = async function (server) {
function onConnection(socket) {
socket.uid = socket.request.uid;
socket.data.uid = String(socket.uid); // socket.data is shared between nodes via fetchSockets
- socket.ip = (
- socket.request.headers['x-forwarded-for'] ||
- socket.request.connection.remoteAddress || ''
- ).split(',')[0];
+ socket.ip = socketIp.getClientIp(socket.request);
socket.request.ip = socket.ip;
logger.io_one(socket, socket.uid);
diff --git a/src/socket.io/utils/ip.js b/src/socket.io/utils/ip.js
new file mode 100644
index 0000000000..9fe1e72fa2
--- /dev/null
+++ b/src/socket.io/utils/ip.js
@@ -0,0 +1,70 @@
+'use strict';
+
+const nconf = require('nconf');
+const proxyaddr = require('proxy-addr');
+const ipaddr = require('ipaddr.js');
+
+function getTrustFunction() {
+ const trustProxy = nconf.get('trust_proxy');
+
+ if (trustProxy === true) {
+ return () => true;
+ }
+
+ if (trustProxy === false || trustProxy == null) {
+ return () => false;
+ }
+
+ if (typeof trustProxy === 'number') {
+ return (_addr, i) => i < trustProxy;
+ }
+
+ try {
+ return proxyaddr.compile(trustProxy);
+ } catch (err) {
+ return () => false;
+ }
+}
+
+function getSocketRemoteAddress(request) {
+ return request?.socket?.remoteAddress || request?.connection?.remoteAddress || '';
+}
+
+function normalizeIp(ip) {
+ if (!ip) {
+ return '';
+ }
+
+ try {
+ const parsed = ipaddr.parse(String(ip).trim());
+ if (parsed.kind() === 'ipv6' && parsed.isIPv4MappedAddress()) {
+ return parsed.toIPv4Address().toString();
+ }
+ return parsed.toString();
+ } catch (err) {
+ return '';
+ }
+}
+
+exports.getClientIp = function (request) {
+ if (!request) {
+ return '';
+ }
+
+ const trustFn = getTrustFunction();
+ const remoteAddress = getSocketRemoteAddress(request);
+ const normalizedRemote = normalizeIp(remoteAddress);
+ const req = {
+ headers: request.headers || {},
+ connection: {
+ remoteAddress: remoteAddress,
+ },
+ };
+
+ try {
+ const resolved = proxyaddr(req, trustFn) || req.connection.remoteAddress || '';
+ return normalizeIp(resolved) || normalizedRemote;
+ } catch (err) {
+ return normalizedRemote;
+ }
+};
\ No newline at end of file
diff --git a/src/webserver.js b/src/webserver.js
index 774bbe5b7c..de141966de 100644
--- a/src/webserver.js
+++ b/src/webserver.js
@@ -317,7 +317,7 @@ async function listen() {
winston.warn("[startup] 'trust_proxy' is not configured, so Express proxy trust is disabled by default. Set 'trust_proxy' in config.json only when NodeBB is behind a reverse proxy that strips or overwrites X-Forwarded-For from untrusted clients.");
}
if (trust_proxy != null) {
- const trustProxyPrefix = trust_proxy === true ? '🤝' : '❌';
+ const trustProxyPrefix = trust_proxy ? '🤝' : '❌';
winston.info(`${trustProxyPrefix} Setting 'trust proxy' to ${JSON.stringify(trust_proxy)}`);
app.set('trust proxy', trust_proxy);
}
diff --git a/test/blacklist.js b/test/blacklist.js
index 068882b8c8..a59e7ffd27 100644
--- a/test/blacklist.js
+++ b/test/blacklist.js
@@ -66,6 +66,13 @@ describe('blacklist', () => {
});
});
+ it('should fail ip test against blacklist with ipv6-mapped ipv4', (done) => {
+ blacklist.test('::ffff:1.1.1.1', (err) => {
+ assert.equal(err.message, '[[error:blacklisted-ip]]');
+ done();
+ });
+ });
+
it('should pass ip test and not crash with ipv6 address', (done) => {
blacklist.test('2001:db8:85a3:0:0:8a2e:370:7334', (err) => {
assert.ifError(err);
diff --git a/test/helpers/index.js b/test/helpers/index.js
index 1a2a4a2bac..670128870e 100644
--- a/test/helpers/index.js
+++ b/test/helpers/index.js
@@ -59,7 +59,7 @@ helpers.logoutUser = async function (jar) {
return { response, body };
};
-helpers.connectSocketIO = function (res, csrf_token) {
+helpers.connectSocketIO = function (res, csrf_token, extraHeaders = {}) {
const io = require('socket.io-client');
const cookie = res.headers['set-cookie'];
const socket = io(nconf.get('base_url'), {
@@ -67,6 +67,7 @@ helpers.connectSocketIO = function (res, csrf_token) {
extraHeaders: {
Origin: nconf.get('url'),
Cookie: cookie,
+ ...extraHeaders,
},
query: {
_csrf: csrf_token,
diff --git a/test/socket.io.ip.js b/test/socket.io.ip.js
new file mode 100644
index 0000000000..50a9e8987a
--- /dev/null
+++ b/test/socket.io.ip.js
@@ -0,0 +1,82 @@
+'use strict';
+
+
+const assert = require('assert');
+const nconf = require('nconf');
+
+const db = require('./mocks/databasemock');
+
+const socketIp = require('../src/socket.io/utils/ip');
+
+describe('socket.io ip utils', () => {
+ let originalTrustProxy;
+
+ before(() => {
+ originalTrustProxy = nconf.get('trust_proxy');
+ });
+
+ after(() => {
+ nconf.set('trust_proxy', originalTrustProxy);
+ });
+
+ it('should use remoteAddress when trust_proxy is false', () => {
+ nconf.set('trust_proxy', false);
+ const ip = socketIp.getClientIp({
+ headers: {
+ 'x-forwarded-for': '203.0.113.1, 198.51.100.1',
+ },
+ socket: {
+ remoteAddress: '192.0.2.1',
+ },
+ });
+
+ assert.strictEqual(ip, '192.0.2.1');
+ });
+
+ it('should use forwarded client address when trust_proxy is true', () => {
+ nconf.set('trust_proxy', true);
+ const ip = socketIp.getClientIp({
+ headers: {
+ 'x-forwarded-for': '203.0.113.1, 198.51.100.1',
+ },
+ socket: {
+ remoteAddress: '192.0.2.1',
+ },
+ });
+
+ assert.strictEqual(ip, '203.0.113.1');
+ });
+
+ it('should honor numeric trust proxy hop counts', () => {
+ nconf.set('trust_proxy', 1);
+ const ip = socketIp.getClientIp({
+ headers: {
+ 'x-forwarded-for': '203.0.113.1, 198.51.100.1',
+ },
+ socket: {
+ remoteAddress: '192.0.2.1',
+ },
+ });
+
+ assert.strictEqual(ip, '198.51.100.1');
+ });
+
+ it('should fall back to remoteAddress when forwarded chain is invalid', () => {
+ nconf.set('trust_proxy', true);
+ const ip = socketIp.getClientIp({
+ headers: {
+ 'x-forwarded-for': '<script>alert("xss")</script>',
+ },
+ socket: {
+ remoteAddress: '192.0.2.1',
+ },
+ });
+
+ assert.strictEqual(ip, '192.0.2.1');
+ });
+
+ it('should return empty string without request', () => {
+ nconf.set('trust_proxy', false);
+ assert.strictEqual(socketIp.getClientIp(null), '');
+ });
+});
diff --git a/test/socket.io.js b/test/socket.io.js
index 434ff80418..78a923730b 100644
--- a/test/socket.io.js
+++ b/test/socket.io.js
@@ -239,6 +239,60 @@ describe('socket.io', () => {
});
});
+ it('should ignore forwarded IP when trust_proxy is false', async () => {
+ const blacklist = require('../src/meta/blacklist');
+ const oldTrustProxy = nconf.get('trust_proxy');
+ const oldRules = await blacklist.get();
+ let tempSocket;
+
+ try {
+ nconf.set('trust_proxy', false);
+ await blacklist.save('203.0.113.1');
+
+ const { response, csrf_token } = await helpers.loginUser('admin', 'adminpwd');
+ tempSocket = await helpers.connectSocketIO(response, csrf_token, {
+ 'x-forwarded-for': '203.0.113.1',
+ });
+
+ const err = await new Promise((resolve) => {
+ tempSocket.emit('meta.rooms.enter', null, resolve);
+ });
+
+ assert.strictEqual(err.message, '[[error:invalid-data]]');
+ } finally {
+ tempSocket?.close();
+ nconf.set('trust_proxy', oldTrustProxy);
+ await blacklist.save(oldRules || '');
+ }
+ });
+
+ it('should trust forwarded IP when trust_proxy is true', async () => {
+ const blacklist = require('../src/meta/blacklist');
+ const oldTrustProxy = nconf.get('trust_proxy');
+ const oldRules = await blacklist.get();
+ let tempSocket;
+
+ try {
+ nconf.set('trust_proxy', true);
+ await blacklist.save('203.0.113.1');
+
+ const { response, csrf_token } = await helpers.loginUser('admin', 'adminpwd');
+ tempSocket = await helpers.connectSocketIO(response, csrf_token, {
+ 'x-forwarded-for': '203.0.113.1',
+ });
+
+ const err = await new Promise((resolve) => {
+ tempSocket.emit('meta.rooms.enter', null, resolve);
+ });
+
+ assert.strictEqual(err.message, '[[error:blacklisted-ip]]');
+ } finally {
+ tempSocket?.close();
+ nconf.set('trust_proxy', oldTrustProxy);
+ await blacklist.save(oldRules || '');
+ }
+ });
+
it('should return if uid is 0', (done) => {
const socketMeta = require('../src/socket.io/meta');
socketMeta.rooms.enter({ uid: 0 }, null, (err) => {