CVE-2023-32309: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') (CWE-22)
value: PyMdown Extensions is a set of extensions for the `Python-Markdown` markdown project. In affected versions an arbitrary file read is possible when using include file syntax. By using the syntax `--8<--"/etc/passwd"` or `--8<--"/proc/self/environ"` the content of these files will be rendered in the generated documentation. Additionally, a path relative to a specified, allowed base path can also be used to render the content of a file outside the specified base paths: `--8<-- "../../../../etc/passwd"`. Within the Snippets extension, there exists a `base_path` option but the implementation is vulnerable to Directory Traversal. The vulnerable section exists in `get_snippet_path(self, path)` lines 155 to 174 in snippets.py. Any readable file on the host where the plugin is executing may have its content exposed. This can impact any use of Snippets that exposes the use of Snippets to external users. It is never recommended to use Snippets to process user-facing, dynamic content. It is designed to process known content on the backend under the control of the host, but if someone were to accidentally enable it for user-facing content, undesired information could be exposed. This issue has been addressed in version 10.0. Users are advised to upgrade. Users unable to upgrade may restrict relative paths by filtering input.
CWE description: The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
CVSS v3 base score: 7.5
Published: 2023-05-15T21:15Z
Repository: https://github.com/facelessuser/pymdown-extensions
Language: Python
Files changed: docs/src/markdown/about/changelog.md, docs/src/markdown/extensions/snippets.md, pymdownx/__meta__.py, pymdownx/snippets.py, tests/test_extensions/_snippets/nested/nested.txt, tests/test_extensions/test_snippets.py
Commit date: 2023-05-14 11:55:18 -0600
Commit message: Merge pull request from GHSA-jh85-wwv9-24hv

* Add `restrict_base_path` and make it the default

New option to restrict snippets to be actual children of the base path
for a more sane default.

* Update grammar
Diff: diff --git a/docs/src/markdown/about/changelog.md b/docs/src/markdown/about/changelog.md
index c53e033..fdf31a3 100644
--- a/docs/src/markdown/about/changelog.md
+++ b/docs/src/markdown/about/changelog.md
@@ -1,7 +1,13 @@
 # Changelog
 
+## 10.0
+
+- **Break**: Snippets: snippets will restrict snippets to ensure they are under the `base_path` preventing snippets
+  relative to the `base_path` but not explicitly under it. `restrict_base_path` can be set to `False` for legacy
+  behavior.
+
 ## 9.11
 
 - **NEW**: Emoji: Update to new CDN and use Twemoji 14.1.2.
 - **NEW**: Snippets: Ignore nested snippet section syntax when including a section.
 
diff --git a/docs/src/markdown/extensions/snippets.md b/docs/src/markdown/extensions/snippets.md
index 8c3e813..e64a9f0 100644
--- a/docs/src/markdown/extensions/snippets.md
+++ b/docs/src/markdown/extensions/snippets.md
@@ -2,10 +2,15 @@
 
 # Snippets
 
 ## Overview
 
+/// warning | Not Meant for User Facing Sites
+Snippets is meant to make including snippets in documentation easier, but it should not be used for user facing sites
+that take and parse user content dynamically.
+///
+
 Snippets is an extension to insert markdown or HTML snippets into another markdown file.  Snippets is great for
 situations where you have content you need to insert into multiple documents.  For instance, this document keeps all its
 hyperlinks in a separate file and then includes those hyperlinks at the bottom of a document via Snippets. If a link
 needs to be updated, it can be updated in one location instead of updating them in multiple files.
 
@@ -258,5 +263,6 @@ Option                 | Type            | Default          | Description
 `url_download`         | bool            | `#!py3 False`    | Allows URLs to be specified as file snippets. URLs will be downloaded and inserted accordingly.
 `url_max_size`         | int             | `#!py3 33554432` | Sets an arbitrary max content size. If content length is reported to be larger, and exception will be thrown. Default is ~32 MiB.
 `url_timeout`          | float           | `#!py3 10.0`     | Passes an arbitrary timeout in seconds to URL requestor. By default this is set to 10 seconds.
 `url_request_headers`  | {string:string} | `#!py3 {}`       | Passes arbitrary headers to URL requestor. By default this is set to empty map.
 `dedent_subsections`   | bool            | `#!py3 False`    | Remove any common leading whitespace from every line in text of a subsection that is inserted via "sections" or by "lines".
+`restrict_base_path`   | bool            | `#!py True`      | Ensure that the specified snippets are children of the specified base path(s). This prevents a path relative to the base path, but not explicitly a child of the base path.
diff --git a/pymdownx/__meta__.py b/pymdownx/__meta__.py
index 4e7534c..b8400f7 100644
--- a/pymdownx/__meta__.py
+++ b/pymdownx/__meta__.py
@@ -183,7 +183,7 @@ def parse_version(ver, pre=False):
     post = int(m.group('post')) if m.group('post') else 0
 
     return Version(major, minor, micro, release, pre, post, dev)
 
 
-__version_info__ = Version(9, 11, 0, "final")
+__version_info__ = Version(10, 0, 0, "final")
 __version__ = __version_info__._get_canonical()
diff --git a/pymdownx/snippets.py b/pymdownx/snippets.py
index e7ae2e9..56b03de 100644
--- a/pymdownx/snippets.py
+++ b/pymdownx/snippets.py
@@ -80,11 +80,12 @@ class SnippetPreprocessor(Preprocessor):
         """Initialize."""
 
         base = config.get('base_path')
         if isinstance(base, str):
             base = [base]
-        self.base_path = base
+        self.base_path = [os.path.abspath(b) for b in base]
+        self.restrict_base_path = config['restrict_base_path']
         self.encoding = config.get('encoding')
         self.check_paths = config.get('check_paths')
         self.auto_append = config.get('auto_append')
         self.url_download = config['url_download']
         self.url_max_size = config['url_max_size']
@@ -157,22 +158,26 @@ class SnippetPreprocessor(Preprocessor):
 
         snippet = None
         for base in self.base_path:
             if os.path.exists(base):
                 if os.path.isdir(base):
-                    filename = os.path.join(base, path)
+                    if self.restrict_base_path:
+                        filename = os.path.abspath(os.path.join(base, path))
+                        # If the absolute path is no longer under the specified base path, reject the file
+                        if not os.path.samefile(base, os.path.dirname(filename)):
+                            continue
+                    else:
+                        filename = os.path.join(base, path)
                     if os.path.exists(filename):
                         snippet = filename
                         break
                 else:
-                    basename = os.path.basename(base)
                     dirname = os.path.dirname(base)
-                    if basename.lower() == path.lower():
-                        filename = os.path.join(dirname, path)
-                        if os.path.exists(filename):
-                            snippet = filename
-                            break
+                    filename = os.path.join(dirname, path)
+                    if os.path.exists(filename) and os.path.samefile(filename, base):
+                        snippet = filename
+                        break
         return snippet
 
     @functools.lru_cache()
     def download(self, url):
         """
@@ -365,10 +370,14 @@ class SnippetExtension(Extension):
     def __init__(self, *args, **kwargs):
         """Initialize."""
 
         self.config = {
             'base_path': [["."], "Base path for snippet paths - Default: [\".\"]"],
+            'restrict_base_path': [
+                True,
+                "Restrict snippet paths such that they are under the base paths - Default: True"
+            ],
             'encoding': ["utf-8", "Encoding of snippets - Default: \"utf-8\""],
             'check_paths': [False, "Make the build fail if a snippet can't be found - Default: \"False\""],
             "auto_append": [
                 [],
                 "A list of snippets (relative to the 'base_path') to auto append to the Markdown content - Default: []"
diff --git a/tests/test_extensions/_snippets/nested/nested.txt b/tests/test_extensions/_snippets/nested/nested.txt
new file mode 100644
index 0000000..528c55e
--- /dev/null
+++ b/tests/test_extensions/_snippets/nested/nested.txt
@@ -0,0 +1 @@
+Snippet
diff --git a/tests/test_extensions/test_snippets.py b/tests/test_extensions/test_snippets.py
index e91a8c4..caa1a1b 100644
--- a/tests/test_extensions/test_snippets.py
+++ b/tests/test_extensions/test_snippets.py
@@ -479,10 +479,67 @@ class TestSnippetsFile(util.MdCase):
             ''',
             True
         )
 
 
+class TestSnippetsNested(util.MdCase):
+    """Test nested restriction."""
+
+    extension = [
+        'pymdownx.snippets',
+    ]
+
+    extension_configs = {
+        'pymdownx.snippets': {
+            'base_path': os.path.join(BASE, '_snippets', 'nested'),
+            'check_paths': True
+        }
+    }
+
+    def test_restricted(self):
+        """Test file restriction."""
+
+        with self.assertRaises(SnippetMissingError):
+            self.check_markdown(
+                R'''
+                --8<-- "../b.txt"
+                ''',
+                '''
+                <p>Snippet</p>
+                ''',
+                True
+            )
+
+
+class TestSnippetsNestedUnrestricted(util.MdCase):
+    """Test nested no bounds."""
+
+    extension = [
+        'pymdownx.snippets',
+    ]
+
+    extension_configs = {
+        'pymdownx.snippets': {
+            'base_path': os.path.join(BASE, '_snippets', 'nested'),
+            'restrict_base_path': False
+        }
+    }
+
+    def test_restricted(self):
+        """Test file restriction."""
+
+        self.check_markdown(
+            R'''
+            --8<-- "../b.txt"
+            ''',
+            '''
+            <p>Snippet</p>
+            ''',
+            True
+        )
+
+
 class TestSnippetsAutoAppend(util.MdCase):
     """Test snippet file case."""
 
     extension = [
         'pymdownx.snippets',

Vulnerable code: __version_info__ = Version(9, 11, 0, "final")
        self.base_path = base
                    filename = os.path.join(base, path)
                    basename = os.path.basename(base)
                    if basename.lower() == path.lower():
                        filename = os.path.join(dirname, path)
                        if os.path.exists(filename):
                            snippet = filename
                            break
Fixed code: ## 10.0

- **Break**: Snippets: snippets will restrict snippets to ensure they are under the `base_path` preventing snippets
  relative to the `base_path` but not explicitly under it. `restrict_base_path` can be set to `False` for legacy
  behavior.

/// warning | Not Meant for User Facing Sites
Snippets is meant to make including snippets in documentation easier, but it should not be used for user facing sites
that take and parse user content dynamically.
///

`restrict_base_path`   | bool            | `#!py True`      | Ensure that the specified snippets are children of the specified base path(s). This prevents a path relative to the base path, but not explicitly a child of the base path.
__version_info__ = Version(10, 0, 0, "final")
        self.base_path = [os.path.abspath(b) for b in base]
        self.restrict_base_path = config['restrict_base_path']
                    if self.restrict_base_path:
                        filename = os.path.abspath(os.path.join(base, path))
                        # If the absolute path is no longer under the specified base path, reject the file
                        if not os.path.samefile(base, os.path.dirname(filename)):
                            continue
                    else:
                        filename = os.path.join(base, path)
                    filename = os.path.join(dirname, path)
                    if os.path.exists(filename) and os.path.samefile(filename, base):
                        snippet = filename
                        break
            'restrict_base_path': [
                True,
                "Restrict snippet paths such that they are under the base paths - Default: True"
            ],
Snippet
class TestSnippetsNested(util.MdCase):
    """Test nested restriction."""

    extension = [
        'pymdownx.snippets',
    ]

    extension_configs = {
        'pymdownx.snippets': {
            'base_path': os.path.join(BASE, '_snippets', 'nested'),
            'check_paths': True
        }
    }

    def test_restricted(self):
        """Test file restriction."""

        with self.assertRaises(SnippetMissingError):
            self.check_markdown(
                R'''
                --8<-- "../b.txt"
                ''',
                '''
                <p>Snippet</p>
                ''',
                True
            )


class TestSnippetsNestedUnrestricted(util.MdCase):
    """Test nested no bounds."""

    extension = [
        'pymdownx.snippets',
    ]

    extension_configs = {
        'pymdownx.snippets': {
            'base_path': os.path.join(BASE, '_snippets', 'nested'),
            'restrict_base_path': False
        }
    }

    def test_restricted(self):
        """Test file restriction."""

        self.check_markdown(
            R'''
            --8<-- "../b.txt"
            ''',
            '''
            <p>Snippet</p>
            ''',
            True
        )