CVE-2023-42458 (Python, published 2023-09-21T17:15Z)
Description: 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.
Severity: nan (CVSS v3 base score: 5.4)
Weakness: CWE-79 \u2014 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
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.
Repository: https://github.com/zopefoundation/Zope
Files changed:
CHANGES.rst
src/OFS/Image.py
src/OFS/tests/testFileAndImage.py
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>

Vulnerable code:

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"))