Skip to content

Commit

Permalink
fix: url handle (#247)
Browse files Browse the repository at this point in the history
  • Loading branch information
climba03003 authored Oct 12, 2021
1 parent f324f8b commit d871592
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
15 changes: 12 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,8 @@ async function fastifyStatic (fastify, opts) {
try {
reply.redirect(301, getRedirectUrl(request.raw.url))
} catch (error) {
// the try-catch here is actually unreachable, but we keep it for safety and prevent DoS attack
/* istanbul ignore next */
reply.send(error)
}
} else {
Expand Down Expand Up @@ -447,16 +449,23 @@ function getEncodingExtension (encoding) {
}

function getRedirectUrl (url) {
if (url.startsWith('//') || url.startsWith('/\\')) {
// malicous redirect
return '/'
let i = 0
// we detech how many slash before a valid path
for (i; i < url.length; i++) {
if (url[i] !== '/' && url[i] !== '\\') break
}
// turns all leading / or \ into a single /
url = '/' + url.substr(i)
try {
const parsed = new URL(url, 'http://localhost.com/')
return parsed.pathname + (parsed.pathname[parsed.pathname.length - 1] !== '/' ? '/' : '') + (parsed.search || '')
} catch (error) {
// the try-catch here is actually unreachable, but we keep it for safety and prevent DoS attack
/* istanbul ignore next */
const err = new Error(`Invalid redirect URL: ${url}`)
/* istanbul ignore next */
err.statusCode = 400
/* istanbul ignore next */
throw err
}
}
Expand Down
7 changes: 4 additions & 3 deletions test/static.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3288,12 +3288,13 @@ t.test('should not redirect to protocol-relative locations', (t) => {
['//^/..', '/', 301],
['//^/.', null, 404], // it is NOT recognized as a directory by pillarjs/send
['//:/..', '/', 301],
['/\\\\a//google.com/%2e%2e%2f%2e%2e', '/', 301],
['//a//youtube.com/%2e%2e%2f%2e%2e', '/', 301],
['/\\\\a//google.com/%2e%2e%2f%2e%2e', '/a//google.com/%2e%2e%2f%2e%2e/', 301],
['//a//youtube.com/%2e%2e%2f%2e%2e', '/a//youtube.com/%2e%2e%2f%2e%2e/', 301],
['/^', null, 404], // it is NOT recognized as a directory by pillarjs/send
['//google.com/%2e%2e', '/', 301],
['//users/%2e%2e', '/', 301],
['//users', null, 404]
['//users', null, 404],
['///deep/path//for//test//index.html', null, 200]
]

t.plan(1 + urls.length * 2)
Expand Down

0 comments on commit d871592

Please sign in to comment.