From 4006554a493f81e2303f63c1bf803915828e125c Mon Sep 17 00:00:00 2001 From: Jonas Wielicki Date: Thu, 2 Feb 2017 20:38:42 +0100 Subject: [PATCH] Prevent to write outside the output directory This is crude and simply raises RuntimeError. We would generally want to have earlier checks which log a warning and do not call write at all. --- pelican/writers.py | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/pelican/writers.py b/pelican/writers.py index d1c8069a..88a2bcfd 100644 --- a/pelican/writers.py +++ b/pelican/writers.py @@ -21,6 +21,18 @@ if not six.PY3: logger = logging.getLogger(__name__) +def _sanitised_join(base_directory, *parts): + joined = os.path.abspath(os.path.join(base_directory, *parts)) + if not joined.startswith(base_directory): + raise RuntimeError( + "attempt to break out of output directory to {}".format( + joined + ) + ) + + return joined + + class Writer(object): def __init__(self, output_path, settings=None): @@ -123,7 +135,8 @@ class Writer(object): self._add_item_to_the_feed(feed, elements[i]) if path: - complete_path = os.path.join(self.output_path, path) + complete_path = _sanitised_join(self.output_path, path) + try: os.makedirs(os.path.dirname(complete_path)) except Exception: @@ -169,7 +182,8 @@ class Writer(object): if localcontext['localsiteurl']: context['localsiteurl'] = localcontext['localsiteurl'] output = template.render(localcontext) - path = os.path.join(output_path, name) + path = _sanitised_join(output_path, name) + try: os.makedirs(os.path.dirname(path)) except Exception: