Skip to content
Myr

Improved fix for open redirect allow list bypass

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Wes Todd · committed by Wes Todd · parent 4f0f6cc · Browse files · 3 files+280 added−63 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Jon Church <me@jonchurch.com>
  • Co-authored-by: Blake Embrey <hello@blakeembrey.com>

Diff stats

3 files+280 added−63 removed

  • tests:+264 added−43 removed
  • other:+16 added−20 removed

3 files+280 added−63 removed

modified:lib/response.js+11 added-20 removed
32 unmodified lines
33var extname = path.extname;34var mime = send.mime;35var resolve = path.resolve;36var vary = require('vary');37var urlParse = require('url').parse;3738/**39 * Response prototype.40 * @public
13 unmodified lines
54 * @private55 */5657var charsetRegExp = /;\s*charset\s*=/;58var schemaAndHostRegExp = /^(?:[a-zA-Z][a-zA-Z0-9+.-]*:)?\/\/[^\\\/\?]+/;5960/**61 * Set status `code`.62 *
841 unmodified lines
904 * @public905 */906907res.location = function location(url) {908 var loc = String(url);908 var loc;909910 // "back" is an alias for the referrer911 if (url === 'back') {912 loc = this.req.get('Referrer') || '/';913 } else {914 loc = String(url);915 }916915 var lowerLoc = loc.toLowerCase();916 var encodedUrl = encodeUrl(loc);917 if (lowerLoc.indexOf('https://') === 0 || lowerLoc.indexOf('http://') === 0) {918 try {919 var parsedUrl = urlParse(loc);920 var parsedEncodedUrl = urlParse(encodedUrl);921 // Because this can encode the host, check that we did not change the host922 if (parsedUrl.host !== parsedEncodedUrl.host) {923 // If the host changes after encodeUrl, return the original url924 return this.set('Location', loc);925 }926 } catch (e) {927 // If parse fails, return the original url928 return this.set('Location', loc);929 }930 }917 var m = schemaAndHostRegExp.exec(loc);918 var pos = m ? m[0].length + 1 : 0;919932 // set location933 return this.set('Location', encodedUrl);920 // Only encode after host to avoid invalid encoding which can introduce921 // vulnerabilities (e.g. `\\` to `%5C`).922 loc = loc.slice(0, pos) + encodeUrl(loc.slice(pos));923924 return this.set('Location', loc);925};926927/**928 * Redirect to the given `url` with optional response `status`
250 unmodified lines
modified:test/res.location.js+264 added-43 removed
1'use strict'23var express = require('../')4 , request = require('supertest')5 , assert = require('assert')6 , url = require('url');78describe('res', function(){9 describe('.location(url)', function(){
35 unmodified lines
45 .expect('Location', 'https://google.com?q=%E2%98%83%20%C2%A710')46 .expect(200, done)47 })4848 it('should not encode bad "url"', function (done) {49 var app = express()5051 app.use(function (req, res) {52 // This is here to show a basic check one might do which53 // would pass but then the location header would still be bad54 if (url.parse(req.query.q).host !== 'google.com') {55 res.status(400).end('Bad url');56 }57 res.location(req.query.q).end();58 });5960 request(app)61 .get('/?q=http://google.com' + encodeURIComponent('\\@apple.com'))62 .expect(200)63 .expect('Location', 'http://google.com\\@apple.com')64 .end(function (err) {65 if (err) {66 throw err;67 }6869 // This ensures that our protocol check is case insensitive70 request(app)71 .get('/?q=HTTP://google.com' + encodeURIComponent('\\@apple.com'))72 .expect(200)73 .expect('Location', 'HTTP://google.com\\@apple.com')74 .end(done)75 });76 });7778 it('should not touch already-encoded sequences in "url"', function (done) {79 var app = express()8081 app.use(function (req, res) {82 res.location('https://google.com?q=%A710').end()83 })8485 request(app)86 .get('/')87 .expect('Location', 'https://google.com?q=%A710')88 .expect(200, done)89 })9049 describe('when url is "back"', function () {50 it('should set location from "Referer" header', function (done) {51 var app = express()52
50 unmodified lines
103 .expect(200, done)104 })105 })106107 it('should encode data uri', function (done) {108 var app = express()109 app.use(function (req, res) {110 res.location('data:text/javascript,export default () => { }').end();111 });112113 request(app)114 .get('/')115 .expect('Location', 'data:text/javascript,export%20default%20()%20=%3E%20%7B%20%7D')116 .expect(200, done)117 })118119 it('should encode data uri', function (done) {120 var app = express()121 app.use(function (req, res) {122 res.location('data:text/javascript,export default () => { }').end();123 });124125 request(app)126 .get('/')127 .expect('Location', 'data:text/javascript,export%20default%20()%20=%3E%20%7B%20%7D')128 .expect(200, done)129 })130131 it('should consistently handle non-string input: boolean', function (done) {132 var app = express()133 app.use(function (req, res) {134 res.location(true).end();135 });136137 request(app)138 .get('/')139 .expect('Location', 'true')140 .expect(200, done)141 });142143 it('should consistently handle non-string inputs: object', function (done) {144 var app = express()145 app.use(function (req, res) {146 res.location({}).end();147 });148149 request(app)150 .get('/')151 .expect('Location', '[object%20Object]')152 .expect(200, done)153 });154155 it('should consistently handle non-string inputs: array', function (done) {156 var app = express()157 app.use(function (req, res) {158 res.location([]).end();159 });160161 request(app)162 .get('/')163 .expect('Location', '')164 .expect(200, done)165 });166167 it('should consistently handle empty string input', function (done) {168 var app = express()169 app.use(function (req, res) {170 res.location('').end();171 });172173 request(app)174 .get('/')175 .expect('Location', '')176 .expect(200, done)177 });178179180 if (typeof URL !== 'undefined') {181 it('should accept an instance of URL', function (done) {182 var app = express();183
7 unmodified lines
191 .expect(200, done);192 });193 }194 })195196 describe('location header encoding', function() {197 function createRedirectServerForDomain (domain) {198 var app = express();199 app.use(function (req, res) {200 var host = url.parse(req.query.q, false, true).host;201 // This is here to show a basic check one might do which202 // would pass but then the location header would still be bad203 if (host !== domain) {204 res.status(400).end('Bad host: ' + host + ' !== ' + domain);205 }206 res.location(req.query.q).end();207 });208 return app;209 }210211 function testRequestedRedirect (app, inputUrl, expected, expectedHost, done) {212 return request(app)213 // Encode uri because old supertest does not and is required214 // to test older node versions. New supertest doesn't re-encode215 // so this works in both.216 .get('/?q=' + encodeURIComponent(inputUrl))217 .expect('') // No body.218 .expect(200)219 .expect('Location', expected)220 .end(function (err, res) {221 if (err) {222 console.log('headers:', res.headers)223 console.error('error', res.error, err);224 return done(err, res);225 }226227 // Parse the hosts from the input URL and the Location header228 var inputHost = url.parse(inputUrl, false, true).host;229 var locationHost = url.parse(res.headers['location'], false, true).host;230231 assert.strictEqual(locationHost, expectedHost);232233 // Assert that the hosts are the same234 if (inputHost !== locationHost) {235 return done(new Error('Hosts do not match: ' + inputHost + " !== " + locationHost));236 }237238 return done(null, res);239 });240 }241242 it('should not touch already-encoded sequences in "url"', function (done) {243 var app = createRedirectServerForDomain('google.com');244 testRequestedRedirect(245 app,246 'https://google.com?q=%A710',247 'https://google.com?q=%A710',248 'google.com',249 done250 );251 });252253 it('should consistently handle relative urls', function (done) {254 var app = createRedirectServerForDomain(null);255 testRequestedRedirect(256 app,257 '/foo/bar',258 '/foo/bar',259 null,260 done261 );262 });263264 it('should not encode urls in such a way that they can bypass redirect allow lists', function (done) {265 var app = createRedirectServerForDomain('google.com');266 testRequestedRedirect(267 app,268 'http://google.com\\@apple.com',269 'http://google.com\\@apple.com',270 'google.com',271 done272 );273 });274275 it('should not be case sensitive', function (done) {276 var app = createRedirectServerForDomain('google.com');277 testRequestedRedirect(278 app,279 'HTTP://google.com\\@apple.com',280 'HTTP://google.com\\@apple.com',281 'google.com',282 done283 );284 });285286 it('should work with https', function (done) {287 var app = createRedirectServerForDomain('google.com');288 testRequestedRedirect(289 app,290 'https://google.com\\@apple.com',291 'https://google.com\\@apple.com',292 'google.com',293 done294 );295 });296297 it('should correctly encode schemaless paths', function (done) {298 var app = createRedirectServerForDomain('google.com');299 testRequestedRedirect(300 app,301 '//google.com\\@apple.com/',302 '//google.com\\@apple.com/',303 'google.com',304 done305 );306 });307308 it('should percent encode backslashes in the path', function (done) {309 var app = createRedirectServerForDomain('google.com');310 testRequestedRedirect(311 app,312 'https://google.com/foo\\bar\\baz',313 'https://google.com/foo%5Cbar%5Cbaz',314 'google.com',315 done316 );317 });318319 it('should encode backslashes in the path after the first backslash that triggered path parsing', function (done) {320 var app = createRedirectServerForDomain('google.com');321 testRequestedRedirect(322 app,323 'https://google.com\\@app\\l\\e.com',324 'https://google.com\\@app%5Cl%5Ce.com',325 'google.com',326 done327 );328 });329330 it('should escape header splitting for old node versions', function (done) {331 var app = createRedirectServerForDomain('google.com');332 testRequestedRedirect(333 app,334 'http://google.com\\@apple.com/%0d%0afoo:%20bar',335 'http://google.com\\@apple.com/%0d%0afoo:%20bar',336 'google.com',337 done338 );339 });340341 it('should encode unicode correctly', function (done) {342 var app = createRedirectServerForDomain(null);343 testRequestedRedirect(344 app,345 '/%e2%98%83',346 '/%e2%98%83',347 null,348 done349 );350 });351352 it('should encode unicode correctly even with a bad host', function (done) {353 var app = createRedirectServerForDomain('google.com');354 testRequestedRedirect(355 app,356 'http://google.com\\@apple.com/%e2%98%83',357 'http://google.com\\@apple.com/%e2%98%83',358 'google.com',359 done360 );361 });362363 it('should work correctly despite using deprecated url.parse', function (done) {364 var app = createRedirectServerForDomain('google.com');365 testRequestedRedirect(366 app,367 'https://google.com\'.bb.com/1.html',368 'https://google.com\'.bb.com/1.html',369 'google.com',370 done371 );372 });373374 it('should encode file uri path', function (done) {375 var app = createRedirectServerForDomain('');376 testRequestedRedirect(377 app,378 'file:///etc\\passwd',379 'file:///etc%5Cpasswd',380 '',381 done382 );383 });384 });385})
modified:History.md+5 added
1unreleased2==========34 * Improved fix for open redirect allow list bypass564.19.1 / 2024-03-207==========89 * Allow passing non-strings to res.location with new encoding handling checks
3606 unmodified lines