CVE-2023-42458 (published 2023-09-21T17:15Z)

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.

CVSS v3 base score: 5.4, MEDIUM (CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N)

Weakness information:
cwe_id: CWE-79
cwe_name: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
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.
extended_description: 
            Cross-site scripting (XSS) vulnerabilities occur when:
            
               Untrusted data enters a web application, typically from a web request.
               The web application dynamically generates a web page that contains this untrusted data.
               During page generation, the application does not prevent the data from containing content that is executable by a web browser, such as JavaScript, HTML tags, HTML attributes, mouse events, Flash, ActiveX, etc.
               A victim visits the generated web page through a web browser, which contains malicious script that was injected using the untrusted data.
               Since the script comes from a web page that was sent by the web server, the victim's web browser executes the malicious script in the context of the web server's domain.
               This effectively violates the intention of the web browser's same-origin policy, which states that scripts in one domain should not be able to access resources or run code in a different domain.
            
            There are three main kinds of XSS:
            
               
                  Type 1: Reflected XSS (or Non-Persistent) - 
         			The server reads data directly from the HTTP request and reflects it back in the HTTP response. Reflected XSS exploits occur when an attacker causes a victim to supply dangerous content to a vulnerable web application, which is then reflected back to the victim and executed by the web browser. The most common mechanism for delivering malicious content is to include it as a parameter in a URL that is posted publicly or e-mailed directly to the victim. URLs constructed in this manner constitute the core of many phishing schemes, whereby an attacker convinces a victim to visit a URL that refers to a vulnerable site. After the site reflects the attacker's content back to the victim, the content is executed by the victim's browser.
               
                  Type 2: Stored XSS (or Persistent) - 
               The application stores dangerous data in a database, message forum, visitor log, or other trusted data store. At a later time, the dangerous data is subsequently read back into the application and included in dynamic content. From an attacker's perspective, the optimal place to inject malicious content is in an area that is displayed to either many users or particularly interesting users. Interesting users typically have elevated privileges in the application or interact with sensitive data that is valuable to the attacker. If one of these users executes malicious content, the attacker may be able to perform privileged operations on behalf of the user or gain access to sensitive data belonging to the user. For example, the attacker might inject XSS into a log message, which might not be handled properly when an administrator views the logs.
            
               
                  Type 0: DOM-Based XSS - 
               In DOM-based XSS, the client performs the injection of XSS into the page; in the other types, the server performs the injection. DOM-based XSS generally involves server-controlled, trusted script that is sent to the client, such as Javascript that performs sanity checks on a form before the user submits it. If the server-supplied script processes user-supplied data and then injects it back into the web page (such as with dynamic HTML), then DOM-based XSS is possible.
            
            
            Once the malicious script is injected, the attacker can perform a variety of malicious activities. The attacker could transfer private information, such as cookies that may include session information, from the victim's machine to the attacker. The attacker could send malicious requests to a web site on behalf of the victim, which could be especially dangerous to the site if the victim has administrator privileges to manage that site. Phishing attacks could be used to emulate trusted web sites and trick the victim into entering a password, allowing the attacker to compromise the victim's account on that web site. Finally, the script could exploit a vulnerability in the web browser itself possibly taking over the victim's machine, sometimes referred to as "drive-by hacking."
            In many cases, the attack can be launched without the victim even being aware of it. Even with careful users, attackers frequently use a variety of methods to encode the malicious portion of the attack, such as URL encoding or Unicode, so the request looks less suspicious.
         
         
cwe_id: CWE-80
cwe_name: Improper Neutralization of Script-Related HTML Tags in a Web Page (Basic XSS)
description: The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special characters such as "<", ">", and "&" that could be interpreted as web-scripting elements when they are sent to a downstream component that processes web pages.
extended_description: This may allow such characters to be treated as control characters, which are executed client-side in the context of the user's session. Although this can be classified as an injection problem, the more pertinent issue is the improper conversion of such special characters to respective context-appropriate entities before displaying them to the user.
         

Fix information:
repo_url: https://github.com/zopefoundation/Zope
commit_details: repo_url: https://github.com/zopefoundation/Zope
author: Maurits van Rees
author_date: 2023-09-21 10:01:18+02:00
msg: 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>
repository: repo_url: https://github.com/zopefoundation/Zope
repo_name: zopefoundation/Zope
description: Zope is an open-source web application server.
repo_language: Python
owner: zopefoundation
file_changes: filename: CHANGES.rst
change_type: ModificationType.MODIFY
diff: @@ -11,6 +11,16 @@ 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.
 

programming_language: Markdown
filename: Image.py
change_type: ModificationType.MODIFY
diff: @@ -14,9 +14,12 @@
 """
 
 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
@@ -48,6 +51,64 @@ 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(),
@@ -107,6 +168,13 @@ class File(
     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'
@@ -403,6 +471,19 @@ class File(
                         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):
         """
@@ -441,6 +522,22 @@ class File(
         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:

programming_language: Python
filename: testFileAndImage.py
change_type: ModificationType.MODIFY
diff: @@ -373,6 +373,7 @@ class ImageTests(FileTests):
         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
@@ -387,6 +388,61 @@ class ImageTests(FileTests):
                          ' 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"""
 

programming_language: Python