Better solution for isolating directory that handles relative links

This commit is contained in:
Michael Lazar 2019-08-06 10:35:03 -04:00
parent d8f6d0b0a1
commit ccee54b448
1 changed files with 5 additions and 4 deletions

View File

@ -3,6 +3,7 @@ import argparse
import asyncio import asyncio
import datetime import datetime
import mimetypes import mimetypes
import os
import pathlib import pathlib
import ssl import ssl
import subprocess import subprocess
@ -91,14 +92,14 @@ class StaticDirectoryApp:
def __iter__(self) -> typing.Iterator[bytes]: def __iter__(self) -> typing.Iterator[bytes]:
url_path = pathlib.Path(self.environ["PATH_INFO"].strip("/")) url_path = pathlib.Path(self.environ["PATH_INFO"].strip("/"))
filesystem_path = (self.root / url_path).resolve()
try: filename = pathlib.Path(os.path.normpath(str(url_path)))
filesystem_path.relative_to(self.root) if filename.is_absolute() or filename.parts[0] == "..":
except ValueError:
# Guard against breaking out of the directory # Guard against breaking out of the directory
self.send_status(STATUS_NOT_FOUND, "Not Found") self.send_status(STATUS_NOT_FOUND, "Not Found")
return return
else:
filesystem_path = self.root / filename
if filesystem_path.is_file(): if filesystem_path.is_file():
mimetype = self.guess_mimetype(filesystem_path.name) mimetype = self.guess_mimetype(filesystem_path.name)