CVE-2023-42458: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') (CWE-79)
value: Zope is an open-source web application server. Prior to versions 4.8.10 and 5.8.5, there is a stored cross site scripting vulnerability for SVG images. Note that an image tag with an SVG image as source is never vulnerable, even when the SVG image contains malicious code. To exploit the vulnerability, an attacker would first need to upload an image, and then trick a user into following a specially crafted link. Patches are available in Zope 4.8.10 and 5.8.5. As a workaround, make sure the "Add Documents, Images, and Files" permission is only assigned to trusted roles. By default, only the Manager has this permission.
CWE description: The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
CVSS v3 base score: 5.4
Published: 2023-09-21T17:15Z
Repository: https://github.com/zopefoundation/Zope
Language: Python
Files changed: CHANGES.rst, src/OFS/Image.py, src/OFS/tests/testFileAndImage.py
Commit date: 2023-09-21 10:01:18 +0200
Commit message: Merge pull request from GHSA-wm8q-9975-xh5v

* Allow only some image types to be displayed inline.

Force download for others, especially SVG images.  By default we use a list of allowed types.
You can switch a to a list of denied types by setting OS environment variable
``OFS_IMAGE_USE_DENYLIST=1``.  This change only affects direct URL access.
``<img src="image.svg" />`` works the same as before.

See security advisory:
https://github.com/zopefoundation/Zope/security/advisories/GHSA-wm8q-9975-xh5v

* Use guess_extension as first guess for the extension of an image.

* Support overriding ALLOWED_INLINE_MIMETYPES and DISALLOWED_INLINE_MIMETYPES.

* Test that filename of attachment gets encoded correctly.

* Add CVE

---------

Co-authored-by: Michael Howitz <icemac@gmx.net>
Diff: diff --git a/CHANGES.rst b/CHANGES.rst
index b003ffbb67..7173687ffe 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -9,10 +9,20 @@ https://github.com/zopefoundation/Zope/blob/4.x/CHANGES.rst
 
 
 5.8.5 (unreleased)
 ------------------
 
+- Allow only some image types to be displayed inline. Force download for
+  others, especially SVG images.  By default we use a list of allowed types.
+  You can switch a to a list of denied types by setting OS environment variable
+  ``OFS_IMAGE_USE_DENYLIST=1``.  You can override the allowed list with
+  environment variable ``ALLOWED_INLINE_MIMETYPES`` and the disallowed list
+  with ``DISALLOWED_INLINE_MIMETYPES``.  Separate multiple entries by either
+  comma or space.  This change only affects direct URL access.
+  ``<img src="image.svg" />`` works the same as before. (CVE-2023-42458)
+  See `security advisory <https://github.com/zopefoundation/Zope/security/advisories/GHSA-wm8q-9975-xh5v>`_.
+
 - Tighten down the ZMI frame source logic to only allow site-local sources.
   Problem reported by Miguel Segovia Gil.
 
 - Update to newest compatible versions of dependencies.
 
diff --git a/src/OFS/Image.py b/src/OFS/Image.py
index 86e4b2c124..bb9c428967 100644
--- a/src/OFS/Image.py
+++ b/src/OFS/Image.py
@@ -12,13 +12,16 @@
 ##############################################################################
 """Image object
 """
 
 import html
+import os
 import struct
 from email.generator import _make_boundary
 from io import BytesIO
+from mimetypes import guess_extension
+from urllib.parse import quote
 from xml.dom import minidom
 
 import ZPublisher.HTTPRequest
 from AccessControl.class_init import InitializeClass
 from AccessControl.Permissions import change_images_and_files  # NOQA
@@ -46,10 +49,68 @@ from zope.lifecycleevent import ObjectCreatedEvent
 from zope.lifecycleevent import ObjectModifiedEvent
 from ZPublisher import HTTPRangeSupport
 from ZPublisher.HTTPRequest import FileUpload
 
 
+def _get_list_from_env(name, default=None):
+    """Get list from environment variable.
+
+    Supports splitting on comma or white space.
+    Use the default as fallback only when the variable is not set.
+    So if the env variable is set to an empty string, this will ignore the
+    default and return an empty list.
+    """
+    value = os.environ.get(name)
+    if value is None:
+        return default or []
+    value = value.strip()
+    if "," in value:
+        return value.split(",")
+    return value.split()
+
+
+# We have one list for allowed, and one for disallowed inline mimetypes.
+# This is for security purposes.
+# By default we use the allowlist.  We give integrators the option to choose
+# the denylist via an environment variable.
+ALLOWED_INLINE_MIMETYPES = _get_list_from_env(
+    "ALLOWED_INLINE_MIMETYPES",
+    default=[
+        "image/gif",
+        # The mimetypes registry lists several for jpeg 2000:
+        "image/jp2",
+        "image/jpeg",
+        "image/jpeg2000-image",
+        "image/jpeg2000",
+        "image/jpx",
+        "image/png",
+        "image/webp",
+        "image/x-icon",
+        "image/x-jpeg2000-image",
+        "text/plain",
+        # By popular request we allow PDF:
+        "application/pdf",
+    ]
+)
+DISALLOWED_INLINE_MIMETYPES = _get_list_from_env(
+    "DISALLOWED_INLINE_MIMETYPES",
+    default=[
+        "application/javascript",
+        "application/x-javascript",
+        "text/javascript",
+        "text/html",
+        "image/svg+xml",
+        "image/svg+xml-compressed",
+    ]
+)
+try:
+    USE_DENYLIST = os.environ.get("OFS_IMAGE_USE_DENYLIST")
+    USE_DENYLIST = bool(int(USE_DENYLIST))
+except (ValueError, TypeError, AttributeError):
+    USE_DENYLIST = False
+
+
 manage_addFileForm = DTMLFile(
     'dtml/imageAdd',
     globals(),
     Kind='File',
     kind='file',
@@ -105,10 +166,17 @@ class File(
     RoleManager,
     Item_w__name__,
     Cacheable
 ):
     """A File object is a content object for arbitrary files."""
+    # You can control which mimetypes may be shown inline
+    # and which must always be downloaded, for security reasons.
+    # Make the configuration available on the class.
+    # Then subclasses can override this.
+    allowed_inline_mimetypes = ALLOWED_INLINE_MIMETYPES
+    disallowed_inline_mimetypes = DISALLOWED_INLINE_MIMETYPES
+    use_denylist = USE_DENYLIST
 
     meta_type = 'File'
     zmi_icon = 'far fa-file-archive'
 
     security = ClassSecurityInfo()
@@ -401,10 +469,23 @@ class File(
 
                     RESPONSE.write(
                         b'\r\n--' + boundary.encode('ascii') + b'--\r\n')
                     return True
 
+    def _should_force_download(self):
+        # If this returns True, the caller should set a
+        # Content-Disposition header with filename.
+        mimetype = self.content_type
+        if not mimetype:
+            return False
+        if self.use_denylist:
+            # We explicitly deny a few mimetypes, and allow the rest.
+            return mimetype in self.disallowed_inline_mimetypes
+        # Use the allowlist.
+        # We only explicitly allow a few mimetypes, and deny the rest.
+        return mimetype not in self.allowed_inline_mimetypes
+
     @security.protected(View)
     def index_html(self, REQUEST, RESPONSE):
         """
         The default view of the contents of a File or Image.
 
@@ -439,10 +520,26 @@ class File(
         RESPONSE.setHeader('Last-Modified', rfc1123_date(self._p_mtime))
         RESPONSE.setHeader('Content-Type', self.content_type)
         RESPONSE.setHeader('Content-Length', self.size)
         RESPONSE.setHeader('Accept-Ranges', 'bytes')
 
+        if self._should_force_download():
+            # We need a filename, even a dummy one if needed.
+            filename = self.getId()
+            if "." not in filename:
+                # This either returns None or ".some_extension"
+                ext = guess_extension(self.content_type, strict=False)
+                if not ext:
+                    # image/svg+xml -> svg
+                    ext = "." + self.content_type.split("/")[-1].split("+")[0]
+                filename += f"{ext}"
+            filename = quote(filename.encode("utf8"))
+            RESPONSE.setHeader(
+                "Content-Disposition",
+                f"attachment; filename*=UTF-8''{filename}",
+            )
+
         if self.ZCacheable_isCachingEnabled():
             result = self.ZCacheable_get(default=None)
             if result is not None:
                 # We will always get None from RAMCacheManager and HTTP
                 # Accelerated Cache Manager but we will get
diff --git a/src/OFS/tests/testFileAndImage.py b/src/OFS/tests/testFileAndImage.py
index 41afe9910b..17d65fd8f4 100644
--- a/src/OFS/tests/testFileAndImage.py
+++ b/src/OFS/tests/testFileAndImage.py
@@ -371,10 +371,11 @@ class ImageTests(FileTests):
     def testViewImageOrFile(self):
         request = self.app.REQUEST
         response = request.RESPONSE
         result = self.file.index_html(request, response)
         self.assertEqual(result, self.data)
+        self.assertIsNone(response.getHeader("Content-Disposition"))
 
     def test_interfaces(self):
         from OFS.Image import Image
         from OFS.interfaces import IWriteLock
         from zope.interface.verify import verifyClass
@@ -385,10 +386,65 @@ class ImageTests(FileTests):
         self.assertEqual(str(self.file),
                          '<img src="http://nohost/file"'
                          ' alt="" title="" height="16" width="16" />')
 
 
+class SVGTests(ImageTests):
+    content_type = 'image/svg+xml'
+
+    def testViewImageOrFile(self):
+        request = self.app.REQUEST
+        response = request.RESPONSE
+        result = self.file.index_html(request, response)
+        self.assertEqual(result, self.data)
+        self.assertEqual(
+            response.getHeader("Content-Disposition"),
+            "attachment; filename*=UTF-8''file.svg",
+        )
+
+    def testViewImageOrFileNonAscii(self):
+        try:
+            factory = getattr(self.app, self.factory)
+            factory('hällo',
+                    file=self.data, content_type=self.content_type)
+            transaction.commit()
+        except Exception:
+            transaction.abort()
+            self.connection.close()
+            raise
+        transaction.begin()
+        image = getattr(self.app, 'hällo')
+        request = self.app.REQUEST
+        response = request.RESPONSE
+        result = image.index_html(request, response)
+        self.assertEqual(result, self.data)
+        self.assertEqual(
+            response.getHeader("Content-Disposition"),
+            "attachment; filename*=UTF-8''h%C3%A4llo.svg",
+        )
+
+    def testViewImageOrFile_with_denylist(self):
+        request = self.app.REQUEST
+        response = request.RESPONSE
+        self.file.use_denylist = True
+        result = self.file.index_html(request, response)
+        self.assertEqual(result, self.data)
+        self.assertEqual(
+            response.getHeader("Content-Disposition"),
+            "attachment; filename*=UTF-8''file.svg",
+        )
+
+    def testViewImageOrFile_with_empty_denylist(self):
+        request = self.app.REQUEST
+        response = request.RESPONSE
+        self.file.use_denylist = True
+        self.file.disallowed_inline_mimetypes = []
+        result = self.file.index_html(request, response)
+        self.assertEqual(result, self.data)
+        self.assertIsNone(response.getHeader("Content-Disposition"))
+
+
 class FileEditTests(Testing.ZopeTestCase.FunctionalTestCase):
     """Browser testing ..Image.File"""
 
     def setUp(self):
         super().setUp()

Fixed code: - Allow only some image types to be displayed inline. Force download for
  others, especially SVG images.  By default we use a list of allowed types.
  You can switch a to a list of denied types by setting OS environment variable
  ``OFS_IMAGE_USE_DENYLIST=1``.  You can override the allowed list with
  environment variable ``ALLOWED_INLINE_MIMETYPES`` and the disallowed list
  with ``DISALLOWED_INLINE_MIMETYPES``.  Separate multiple entries by either
  comma or space.  This change only affects direct URL access.
  ``<img src="image.svg" />`` works the same as before. (CVE-2023-42458)
  See `security advisory <https://github.com/zopefoundation/Zope/security/advisories/GHSA-wm8q-9975-xh5v>`_.

import os
from mimetypes import guess_extension
from urllib.parse import quote
def _get_list_from_env(name, default=None):
    """Get list from environment variable.

    Supports splitting on comma or white space.
    Use the default as fallback only when the variable is not set.
    So if the env variable is set to an empty string, this will ignore the
    default and return an empty list.
    """
    value = os.environ.get(name)
    if value is None:
        return default or []
    value = value.strip()
    if "," in value:
        return value.split(",")
    return value.split()


# We have one list for allowed, and one for disallowed inline mimetypes.
# This is for security purposes.
# By default we use the allowlist.  We give integrators the option to choose
# the denylist via an environment variable.
ALLOWED_INLINE_MIMETYPES = _get_list_from_env(
    "ALLOWED_INLINE_MIMETYPES",
    default=[
        "image/gif",
        # The mimetypes registry lists several for jpeg 2000:
        "image/jp2",
        "image/jpeg",
        "image/jpeg2000-image",
        "image/jpeg2000",
        "image/jpx",
        "image/png",
        "image/webp",
        "image/x-icon",
        "image/x-jpeg2000-image",
        "text/plain",
        # By popular request we allow PDF:
        "application/pdf",
    ]
)
DISALLOWED_INLINE_MIMETYPES = _get_list_from_env(
    "DISALLOWED_INLINE_MIMETYPES",
    default=[
        "application/javascript",
        "application/x-javascript",
        "text/javascript",
        "text/html",
        "image/svg+xml",
        "image/svg+xml-compressed",
    ]
)
try:
    USE_DENYLIST = os.environ.get("OFS_IMAGE_USE_DENYLIST")
    USE_DENYLIST = bool(int(USE_DENYLIST))
except (ValueError, TypeError, AttributeError):
    USE_DENYLIST = False


    # You can control which mimetypes may be shown inline
    # and which must always be downloaded, for security reasons.
    # Make the configuration available on the class.
    # Then subclasses can override this.
    allowed_inline_mimetypes = ALLOWED_INLINE_MIMETYPES
    disallowed_inline_mimetypes = DISALLOWED_INLINE_MIMETYPES
    use_denylist = USE_DENYLIST
    def _should_force_download(self):
        # If this returns True, the caller should set a
        # Content-Disposition header with filename.
        mimetype = self.content_type
        if not mimetype:
            return False
        if self.use_denylist:
            # We explicitly deny a few mimetypes, and allow the rest.
            return mimetype in self.disallowed_inline_mimetypes
        # Use the allowlist.
        # We only explicitly allow a few mimetypes, and deny the rest.
        return mimetype not in self.allowed_inline_mimetypes

        if self._should_force_download():
            # We need a filename, even a dummy one if needed.
            filename = self.getId()
            if "." not in filename:
                # This either returns None or ".some_extension"
                ext = guess_extension(self.content_type, strict=False)
                if not ext:
                    # image/svg+xml -> svg
                    ext = "." + self.content_type.split("/")[-1].split("+")[0]
                filename += f"{ext}"
            filename = quote(filename.encode("utf8"))
            RESPONSE.setHeader(
                "Content-Disposition",
                f"attachment; filename*=UTF-8''{filename}",
            )

        self.assertIsNone(response.getHeader("Content-Disposition"))
class SVGTests(ImageTests):
    content_type = 'image/svg+xml'

    def testViewImageOrFile(self):
        request = self.app.REQUEST
        response = request.RESPONSE
        result = self.file.index_html(request, response)
        self.assertEqual(result, self.data)
        self.assertEqual(
            response.getHeader("Content-Disposition"),
            "attachment; filename*=UTF-8''file.svg",
        )

    def testViewImageOrFileNonAscii(self):
        try:
            factory = getattr(self.app, self.factory)
            factory('hällo',
                    file=self.data, content_type=self.content_type)
            transaction.commit()
        except Exception:
            transaction.abort()
            self.connection.close()
            raise
        transaction.begin()
        image = getattr(self.app, 'hällo')
        request = self.app.REQUEST
        response = request.RESPONSE
        result = image.index_html(request, response)
        self.assertEqual(result, self.data)
        self.assertEqual(
            response.getHeader("Content-Disposition"),
            "attachment; filename*=UTF-8''h%C3%A4llo.svg",
        )

    def testViewImageOrFile_with_denylist(self):
        request = self.app.REQUEST
        response = request.RESPONSE
        self.file.use_denylist = True
        result = self.file.index_html(request, response)
        self.assertEqual(result, self.data)
        self.assertEqual(
            response.getHeader("Content-Disposition"),
            "attachment; filename*=UTF-8''file.svg",
        )

    def testViewImageOrFile_with_empty_denylist(self):
        request = self.app.REQUEST
        response = request.RESPONSE
        self.file.use_denylist = True
        self.file.disallowed_inline_mimetypes = []
        result = self.file.index_html(request, response)
        self.assertEqual(result, self.data)
        self.assertIsNone(response.getHeader("Content-Disposition"))