Handle excessively long paths

This commit is contained in:
Ben Sturmfels 2024-06-06 18:06:44 +10:00
parent 52d72eb554
commit 31fa3694ea
Signed by: bsturmfels
GPG key ID: 023C05E2C9C068F0
2 changed files with 14 additions and 4 deletions

View file

@ -55,3 +55,9 @@ def test_path_traversal_404s(rf):
request = rf.get('/about/../../../conservancy-website.sqlite3') request = rf.get('/about/../../../conservancy-website.sqlite3')
with pytest.raises(Http404): with pytest.raises(Http404):
views.content(request) views.content(request)
def test_long_path_404s(rf):
request = rf.get('x' * 1000)
with pytest.raises(Http404):
views.content(request)

View file

@ -52,10 +52,14 @@ def content(request, *args, **kwargs):
path += 'index.html' path += 'index.html'
full_path = (base_path / path).resolve() full_path = (base_path / path).resolve()
safe_from_path_traversal = full_path.is_relative_to(base_path) safe_from_path_traversal = full_path.is_relative_to(base_path)
if full_path.is_dir(): try:
# Should have been accessed with a trailing slash. if full_path.is_dir():
return HttpResponseRedirect(request.path + '/') # Should have been accessed with a trailing slash.
elif not full_path.exists() or not safe_from_path_traversal: return HttpResponseRedirect(request.path + '/')
elif not full_path.exists() or not safe_from_path_traversal:
raise Http404()
except OSError:
# eg. path is too long
raise Http404() raise Http404()
is_template = mimetypes.guess_type(full_path)[0] == 'text/html' is_template = mimetypes.guess_type(full_path)[0] == 'text/html'
if not is_template: if not is_template: