CVE-2023-32309 (published 2023-05-15T21:15Z)

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.

CVSS v3 base score: 7.5, HIGH (CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N)

Weakness information:
cwe_id: CWE-22
cwe_name: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
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.
extended_description: 
            Many file operations are intended to take place within a restricted directory. By using special elements such as ".." and "/" separators, attackers can escape outside of the restricted location to access files or directories that are elsewhere on the system. One of the most common special elements is the "../" sequence, which in most modern operating systems is interpreted as the parent directory of the current location. This is referred to as relative path traversal. Path traversal also covers the use of absolute pathnames such as "/usr/local/bin" to access unexpected files. This is referred to as absolute path traversal.
         
         

Fix information:
repo_url: https://github.com/facelessuser/pymdown-extensions
commit_details: repo_url: https://github.com/facelessuser/pymdown-extensions
author: Isaac Muse
author_date: 2023-05-14 11:55:18-06:00
msg: 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
repository: repo_url: https://github.com/facelessuser/pymdown-extensions
repo_name: facelessuser/pymdown-extensions
description: Extensions for Python Markdown
repo_language: Python
owner: facelessuser
file_changes: filename: changelog.md
change_type: ModificationType.MODIFY
diff: @@ -1,5 +1,11 @@
 # 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.

programming_language: Markdown
filename: snippets.md
change_type: ModificationType.MODIFY
diff: @@ -4,6 +4,11 @@
 
 ## 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
@@ -260,3 +265,4 @@ Option                 | Type            | Default          | Description
 `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.

programming_language: Markdown
filename: __meta__.py
change_type: ModificationType.MODIFY
diff: @@ -185,5 +185,5 @@ def parse_version(ver, pre=False):
     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()

programming_language: Python
filename: snippets.py
change_type: ModificationType.MODIFY
diff: @@ -82,7 +82,8 @@ class SnippetPreprocessor(Preprocessor):
         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')
@@ -159,18 +160,22 @@ class SnippetPreprocessor(Preprocessor):
         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()
@@ -367,6 +372,10 @@ class SnippetExtension(Extension):
 
         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": [

programming_language: Python
filename: nested.txt
change_type: ModificationType.ADD
diff: @@ -0,0 +1 @@
+Snippet

programming_language: Batchfile
filename: test_snippets.py
change_type: ModificationType.MODIFY
diff: @@ -481,6 +481,63 @@ class TestSnippetsFile(util.MdCase):
         )
 
 
+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."""
 

programming_language: Python