Browse Source

Make safe_join able to safely join multiple paths

pull/1730/head
Giampaolo Eusebi 9 years ago
parent
commit
03ea11fe76
  1. 2
      CHANGES
  2. 32
      flask/helpers.py

2
CHANGES

@ -9,6 +9,8 @@ Version 0.12
- the cli command now responds to `--version`. - the cli command now responds to `--version`.
- Mimetype guessing for ``send_file`` has been removed, as per issue ``#104``. - Mimetype guessing for ``send_file`` has been removed, as per issue ``#104``.
See pull request ``#1849``. See pull request ``#1849``.
- Make ``flask.safe_join`` able to join multiple paths like ``os.path.join``
(pull request ``#1730``).
Version 0.11.1 Version 0.11.1
-------------- --------------

32
flask/helpers.py

@ -563,8 +563,9 @@ def send_file(filename_or_fp, mimetype=None, as_attachment=False,
return rv return rv
def safe_join(directory, filename): def safe_join(directory, *pathnames):
"""Safely join `directory` and `filename`. """Safely join `directory` and zero or more untrusted `pathnames`
components.
Example usage:: Example usage::
@ -574,20 +575,23 @@ def safe_join(directory, filename):
with open(filename, 'rb') as fd: with open(filename, 'rb') as fd:
content = fd.read() # Read and process the file content... content = fd.read() # Read and process the file content...
:param directory: the base directory. :param directory: the trusted base directory.
:param filename: the untrusted filename relative to that directory. :param pathnames: the untrusted pathnames relative to that directory.
:raises: :class:`~werkzeug.exceptions.NotFound` if the resulting path :raises: :class:`~werkzeug.exceptions.NotFound` if one or more passed
would fall out of `directory`. paths fall out of its boundaries.
""" """
filename = posixpath.normpath(filename) for filename in pathnames:
for sep in _os_alt_seps: if filename != '':
if sep in filename: filename = posixpath.normpath(filename)
for sep in _os_alt_seps:
if sep in filename:
raise NotFound()
if os.path.isabs(filename) or \
filename == '..' or \
filename.startswith('../'):
raise NotFound() raise NotFound()
if os.path.isabs(filename) or \ directory = os.path.join(directory, filename)
filename == '..' or \ return directory
filename.startswith('../'):
raise NotFound()
return os.path.join(directory, filename)
def send_from_directory(directory, filename, **options): def send_from_directory(directory, filename, **options):

Loading…
Cancel
Save