Node.js based forum software built for the modern web
fix: restrict x-return-to to internal paths
Sebastian Albrecht67555b4b5f50
diff --git a/src/controllers/helpers.js b/src/controllers/helpers.jsindex e7b3c3605e..398c7dee75 100644--- a/src/controllers/helpers.js+++ b/src/controllers/helpers.js@@ -185,6 +185,79 @@ helpers.redirect = function (res, url, permanent) {}};+helpers.normalizeReturnToPath = function (pathCandidate, { allowApi = true } = {}) {+ if (typeof pathCandidate !== 'string') {+ return '';+ }++ const raw = pathCandidate.trim();+ let decoded;+ let configuredUrl;+ try {+ decoded = decodeURIComponent(raw);+ configuredUrl = new URL(nconf.get('url'));+ } catch {+ return '';+ }++ const rawIsAbsolute = /^[a-z][a-z\d+.-]*:/i.test(raw);+ const decodedIsAbsolute = /^[a-z][a-z\d+.-]*:/i.test(decoded);+ const rawPathCandidate = raw.split(/[?#]/, 1)[0];+ const decodedPathCandidate = decoded.split(/[?#]/, 1)[0];+ const hasControlCharacter = Array.from(decoded).some((character) => {+ const codePoint = character.codePointAt(0);+ return codePoint < 32 || codePoint === 127;+ });+ if (+ !raw || raw.startsWith('//') || decoded.startsWith('//') ||+ hasControlCharacter ||+ rawPathCandidate.includes('\\') || decodedPathCandidate.includes('\\') ||+ (!raw.startsWith('/') && !rawIsAbsolute) ||+ (!decoded.startsWith('/') && !decodedIsAbsolute)+ ) {+ return '';+ }++ let parsed;+ let decodedParsed;+ try {+ parsed = new URL(raw, configuredUrl.origin);+ decodedParsed = new URL(decoded, configuredUrl.origin);+ } catch {+ return '';+ }++ if (+ parsed.origin !== configuredUrl.origin || decodedParsed.origin !== configuredUrl.origin ||+ parsed.username || parsed.password || decodedParsed.username || decodedParsed.password+ ) {+ return '';+ }++ const relativePath = nconf.get('relative_path') || '';+ const isWithinRelativePath = pathname => !relativePath ||+ pathname === relativePath || pathname.startsWith(`${relativePath}/`);+ if (rawIsAbsolute && !isWithinRelativePath(parsed.pathname)) {+ return '';+ }+ if (decodedIsAbsolute && !isWithinRelativePath(decodedParsed.pathname)) {+ return '';+ }++ const stripRelativePath = pathname => relativePath && isWithinRelativePath(pathname) ?+ (pathname.slice(relativePath.length) || '/') : pathname;+ const pathname = stripRelativePath(parsed.pathname);+ const decodedPathname = stripRelativePath(decodedParsed.pathname);+ if (pathname.startsWith('//') || decodedPathname.startsWith('//')) {+ return '';+ }+ if (!allowApi && (/^\/api(?:\/|$)/i.test(pathname) || /^\/api(?:\/|$)/i.test(decodedPathname))) {+ return '';+ }++ return `${pathname}${parsed.search}${parsed.hash}`;+};+function prependRelativePath(url) {return url.startsWith('http://') || url.startsWith('https://') ?url : relative_path + url;diff --git a/src/controllers/index.js b/src/controllers/index.jsindex 55465fa89f..05071df683 100644--- a/src/controllers/index.js+++ b/src/controllers/index.js@@ -111,12 +111,14 @@ Controllers.login = async function (req, res) {}if (req.headers['x-return-to']) {- req.session.returnTo = req.headers['x-return-to'];+ req.session.returnTo = helpers.normalizeReturnToPath(req.headers['x-return-to']) || '/';+ } else if (req.session.returnTo) {+ const normalizedReturnTo = helpers.normalizeReturnToPath(req.session.returnTo);+ if (normalizedReturnTo) {+ req.session.returnTo = normalizedReturnTo;+ }}- // Occasionally, x-return-to is passed a full url.- req.session.returnTo = req.session.returnTo && req.session.returnTo.replace(nconf.get('base_url'), '').replace(nconf.get('relative_path'), '');-data.alternate_logins = loginStrategies.length > 0;data.osw_logins = !!meta.config.activitypubEnabled;data.authentication = loginStrategies;@@ -154,7 +156,6 @@ Controllers.register = async function (req, res, next) {}let errorText;- const returnTo = (req.headers['x-return-to'] || '').replace(nconf.get('base_url') + nconf.get('relative_path'), '');if (req.query.error === 'csrf-invalid') {errorText = '[[error:csrf-invalid]]';}@@ -169,8 +170,8 @@ Controllers.register = async function (req, res, next) {}}- if (returnTo) {- req.session.returnTo = returnTo;+ if (req.headers['x-return-to']) {+ req.session.returnTo = helpers.normalizeReturnToPath(req.headers['x-return-to']) || '/';}const loginStrategies = require('../routes/authentication').getLoginStrategies();diff --git a/src/middleware/index.js b/src/middleware/index.jsindex 99ede28307..c6ea486393 100644--- a/src/middleware/index.js+++ b/src/middleware/index.js@@ -353,7 +353,9 @@ middleware.requireAPIReAuth = function ({ reauthWindowMinutes = 2 } = {}) {return next();}- req.session.returnTo = normalizeReturnToPath(req, req.headers['x-return-to']) || '/';+ req.session.returnTo = controllers.helpers.normalizeReturnToPath(+ req.headers['x-return-to'], { allowApi: false }+ ) || '/';if (await triggerReLoginHook(req, res)) {return;@@ -374,32 +376,3 @@ async function triggerReLoginHook(req, res) {await plugins.hooks.fire('response:auth.relogin', { req, res });return res.headersSent;}--function normalizeReturnToPath(req, pathCandidate) {- if (typeof pathCandidate !== 'string') {- return '';- }-- let p;- try {- p = decodeURIComponent(pathCandidate.trim());- } catch {- return '';- }-- if (!p.startsWith('/') || p.startsWith('//')) {- return '';- }- p = path.posix.normalize(p);-- if (relative_path && p.startsWith(relative_path)) {- p = p.slice(relative_path.length) || '/';- }-- // Never redirect to API routes after a browser login- if (/^\/api(?:\/|$)/.test(p)) {- return '';- }-- return p;-}\ No newline at end of filediff --git a/test/authentication.js b/test/authentication.jsindex 40c5aedb36..0f47ba8723 100644--- a/test/authentication.js+++ b/test/authentication.js@@ -13,6 +13,7 @@ const meta = require('../src/meta');const plugins = require('../src/plugins');const privileges = require('../src/privileges');const api = require('../src/api');+const controllerHelpers = require('../src/controllers/helpers');const helpers = require('./helpers');describe('authentication', () => {@@ -39,6 +40,212 @@ describe('authentication', () => {plugins.hooks.unregister('authentication-test', 'static:email.send');});+ describe('x-return-to', () => {+ it('should normalize URLs safely on a root installation', () => {+ const configuredUrl = nconf.get('url');+ const relativePath = nconf.get('relative_path');+ try {+ nconf.set('url', nconf.get('base_url'));+ nconf.set('relative_path', '');+ assert.strictEqual(controllerHelpers.normalizeReturnToPath('/topic/1?sort=newest#post-2'), '/topic/1?sort=newest#post-2');+ assert.strictEqual(controllerHelpers.normalizeReturnToPath(`${nconf.get('base_url')}/topic/1`), '/topic/1');+ assert.strictEqual(controllerHelpers.normalizeReturnToPath(`${nconf.get('base_url')}//attacker.example`), '');+ assert.strictEqual(controllerHelpers.normalizeReturnToPath('//attacker.example'), '');+ assert.strictEqual(controllerHelpers.normalizeReturnToPath('/api/v3/users'), '/api/v3/users');+ assert.strictEqual(controllerHelpers.normalizeReturnToPath('/api/v3/users', { allowApi: false }), '');+ } finally {+ nconf.set('url', configuredUrl);+ nconf.set('relative_path', relativePath);+ }+ });++ async function getLoginDestination(page, returnTo) {+ const requestJar = request.jar();+ const { response: pageResponse } = await request.get(`${nconf.get('url')}/api/${page}`, {+ jar: requestJar,+ headers: {+ 'x-return-to': returnTo,+ },+ });+ assert.strictEqual(pageResponse.statusCode, 200);++ const csrf_token = await helpers.getCsrfToken(requestJar);+ const { response, body } = await request.post(`${nconf.get('url')}/login`, {+ jar: requestJar,+ body: {+ username: 'regular',+ password: 'regularpwd',+ },+ headers: {+ 'x-csrf-token': csrf_token,+ },+ });+ assert.strictEqual(response.statusCode, 200);+ return body.next;+ }++ const home = `${nconf.get('relative_path')}/`;+ const invalidTargets = [+ { name: 'an external absolute URL', value: 'https://attacker.example/topic/1' },+ { name: 'a scheme-relative URL', value: '//attacker.example/topic/1' },+ { name: 'an encoded scheme-relative URL', value: '%2F%2Fattacker.example/topic/1' },+ { name: 'an encoded external absolute URL', value: 'https%3A%2F%2Fattacker.example%2Ftopic%2F1' },+ { name: 'a backslash authority URL', value: '/\\attacker.example/topic/1' },+ { name: 'an encoded backslash authority URL', value: '/%5Cattacker.example/topic/1' },+ { name: 'an encoded control character', value: '/topic/1%0D%0AX-Test%3Avalue' },+ { name: 'a malformed encoded URL', value: '/topic/%' },+ { name: 'a same-origin URL outside the configured subfolder', value: `${nconf.get('base_url')}/outside` },+ { name: 'a same-origin URL traversing outside the configured subfolder', value: `${nconf.get('url')}/../outside` },+ { name: 'a same-origin URL that becomes scheme-relative after subfolder stripping', value: `${nconf.get('url')}//attacker.example/topic/1` },+ { name: 'an encoded path that becomes scheme-relative after subfolder stripping', value: `${nconf.get('relative_path')}/%2F%2Fattacker.example/topic/1` },+ ];++ ['login', 'register'].forEach((page) => {+ invalidTargets.forEach((target) => {+ it(`should reject ${target.name} from the ${page} page`, async () => {+ assert.strictEqual(await getLoginDestination(page, target.value), home);+ });+ });++ it(`should preserve an internal URL with query and hash from the ${page} page`, async () => {+ const target = '/topic/1?next=%2Fcategory%2F1#post-2';+ assert.strictEqual(+ await getLoginDestination(page, target),+ `${nconf.get('relative_path')}${target}`+ );+ });++ it(`should strip the configured subfolder from a same-origin URL on the ${page} page`, async () => {+ const path = '/topic/1?sort=newest#post-2';+ assert.strictEqual(await getLoginDestination(page, `${nconf.get('url')}${path}`), `${nconf.get('relative_path')}${path}`);+ });++ it(`should not confuse a subfolder-prefix lookalike on the ${page} page`, async () => {+ assert.strictEqual(+ await getLoginDestination(page, `${nconf.get('relative_path')}ish/topic/1`),+ `${nconf.get('relative_path')}${nconf.get('relative_path')}ish/topic/1`+ );+ });+ });++ async function getApiReauthDestination(returnTo, expectedSessionReturnTo) {+ const { jar: reauthJar } = await helpers.loginUser('regular', 'regularpwd');+ let hookReturnTo;+ const hookName = `x-return-to-reauth-${utils.generateUUID()}`;+ plugins.hooks.register(hookName, {+ hook: 'response:auth.relogin',+ method: async ({ req }) => {+ hookReturnTo = req.session.returnTo;+ },+ });++ try {+ const { response } = await helpers.request('post', '/api/v3/users/reauth/verify', {+ jar: reauthJar,+ body: {},+ headers: {+ 'x-return-to': returnTo,+ },+ });+ assert.strictEqual(response.statusCode, 401);+ assert.strictEqual(hookReturnTo, expectedSessionReturnTo);+ } finally {+ plugins.hooks.unregister(hookName, 'response:auth.relogin');+ }++ const csrf_token = await helpers.getCsrfToken(reauthJar);+ const { body } = await request.post(`${nconf.get('url')}/login`, {+ jar: reauthJar,+ body: {+ username: 'regular',+ password: 'regularpwd',+ },+ headers: {+ 'x-csrf-token': csrf_token,+ },+ });+ return body.next;+ }++ it('should normalize the return path before firing the API reauthentication hook', async () => {+ const target = '/topic/1?sort=newest#post-2';+ assert.strictEqual(+ await getApiReauthDestination(`${nconf.get('url')}${target}`, target),+ `${nconf.get('relative_path')}${target}`+ );+ });++ it('should reject an external API reauthentication return URL', async () => {+ assert.strictEqual(+ await getApiReauthDestination('https://attacker.example/topic/1', '/'),+ home+ );+ });++ it('should not redirect a browser login back to an API route', async () => {+ assert.strictEqual(+ await getApiReauthDestination('/api/v3/admin/tokens', '/'),+ home+ );+ });++ it('should reject case and encoded variants of the API route', async () => {+ assert.strictEqual(+ await getApiReauthDestination('/API/v3/admin/tokens', '/'),+ home+ );+ assert.strictEqual(+ await getApiReauthDestination('/a%70i/v3/admin/tokens', '/'),+ home+ );+ });++ it('should let the registration-complete hook override a normalized internal target', async () => {+ const requestJar = request.jar();+ const target = '/topic/1?sort=newest#post-2';+ const pluginTarget = 'https://plugin.example/return';+ let hookNext;+ const hookName = `x-return-to-register-${utils.generateUUID()}`;+ plugins.hooks.register(hookName, {+ hook: 'filter:register.complete',+ method: async (data) => {+ hookNext = data.next;+ data.next = pluginTarget;+ return data;+ },+ });++ try {+ await request.get(`${nconf.get('url')}/api/register`, {+ jar: requestJar,+ headers: {+ 'x-return-to': `${nconf.get('url')}${target}`,+ },+ });+ const csrf_token = await helpers.getCsrfToken(requestJar);+ const username = `returnto${utils.generateUUID().slice(0, 8)}`;+ const { response, body } = await request.post(`${nconf.get('url')}/register`, {+ jar: requestJar,+ body: {+ username,+ email: `${username}@example.org`,+ password: 'register-password',+ 'password-confirm': 'register-password',+ gdpr_consent: true,+ },+ headers: {+ 'x-csrf-token': csrf_token,+ },+ });+ assert.strictEqual(response.statusCode, 200);+ assert.strictEqual(hookNext, target);+ assert.strictEqual(body.next, pluginTarget);+ } finally {+ plugins.hooks.unregister(hookName, 'filter:register.complete');+ }+ });+ });+it('should allow login with email for uid 1', async () => {const oldValue = meta.config.allowLoginWith;meta.config.allowLoginWith = 'username-email';