File tree 2 files changed +24
-4
lines changed
2 files changed +24
-4
lines changed Original file line number Diff line number Diff line change @@ -152,7 +152,11 @@ async function fastifyStatic (fastify, opts) {
152
152
}
153
153
154
154
if ( opts . redirect === true ) {
155
- reply . redirect ( 301 , getRedirectUrl ( request . raw . url ) )
155
+ try {
156
+ reply . redirect ( 301 , getRedirectUrl ( request . raw . url ) )
157
+ } catch ( error ) {
158
+ reply . send ( error )
159
+ }
156
160
} else {
157
161
reply . callNotFound ( )
158
162
}
@@ -443,8 +447,18 @@ function getEncodingExtension (encoding) {
443
447
}
444
448
445
449
function getRedirectUrl ( url ) {
446
- const parsed = new URL ( url , 'http://localhost.com/' )
447
- return parsed . pathname + ( parsed . pathname [ parsed . pathname . length - 1 ] !== '/' ? '/' : '' ) + ( parsed . search || '' )
450
+ if ( url . startsWith ( '//' ) || url . startsWith ( '/\\' ) ) {
451
+ // malicous redirect
452
+ return '/'
453
+ }
454
+ try {
455
+ const parsed = new URL ( url , 'http://localhost.com/' )
456
+ return parsed . pathname + ( parsed . pathname [ parsed . pathname . length - 1 ] !== '/' ? '/' : '' ) + ( parsed . search || '' )
457
+ } catch ( error ) {
458
+ const err = new Error ( `Invalid redirect URL: ${ url } ` )
459
+ err . statusCode = 400
460
+ throw err
461
+ }
448
462
}
449
463
450
464
module . exports = fp ( fastifyStatic , {
Original file line number Diff line number Diff line change @@ -3283,8 +3283,14 @@ t.test(
3283
3283
}
3284
3284
)
3285
3285
3286
- t . test ( 'should not redirect to protocol-relative locations' , { only : 1 } , ( t ) => {
3286
+ t . test ( 'should not redirect to protocol-relative locations' , ( t ) => {
3287
3287
const urls = [
3288
+ [ '//^/..' , '/' , 301 ] ,
3289
+ [ '//^/.' , null , 404 ] , // it is NOT recognized as a directory by pillarjs/send
3290
+ [ '//:/..' , '/' , 301 ] ,
3291
+ [ '/\\\\a//google.com/%2e%2e%2f%2e%2e' , '/' , 301 ] ,
3292
+ [ '//a//youtube.com/%2e%2e%2f%2e%2e' , '/' , 301 ] ,
3293
+ [ '/^' , null , 404 ] , // it is NOT recognized as a directory by pillarjs/send
3288
3294
[ '//google.com/%2e%2e' , '/' , 301 ] ,
3289
3295
[ '//users/%2e%2e' , '/' , 301 ] ,
3290
3296
[ '//users' , null , 404 ]
You can’t perform that action at this time.
0 commit comments