CVE-2023-37908 (published 2023-10-25T18:17Z)

XWiki Rendering is a generic Rendering system that converts textual input in a given syntax into another syntax. The cleaning of attributes during XHTML rendering, introduced in version 14.6-rc-1, allowed the injection of arbitrary HTML code and thus cross-site scripting via invalid attribute names. This can be exploited, e.g., via the link syntax in any content that supports XWiki syntax like comments in XWiki. When a user moves the mouse over a malicious link, the malicious JavaScript code is executed in the context of the user session. When this user is a privileged user who has programming rights, this allows server-side code execution with programming rights, impacting the confidentiality, integrity and availability of the XWiki instance. While this attribute was correctly recognized as not allowed, the attribute was still printed with a prefix `data-xwiki-translated-attribute-` without further cleaning or validation. This problem has been patched in XWiki 14.10.4 and 15.0 RC1 by removing characters not allowed in data attributes and then validating the cleaned attribute again. There are no known workarounds apart from upgrading to a version including the fix.

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

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.
         
         

Fix information:
repo_url: https://github.com/xwiki/xwiki-rendering
commit_details: repo_url: https://github.com/xwiki/xwiki-rendering
author: Michael Hamann
author_date: 2023-01-13 17:28:19+01:00
msg: XRENDERING-697: XHTMLWikiPrinter doesn't validate generated data attributes

* Strip invalid characters and make sure the data attribute is allowed.
* Add tests.
repository: repo_url: https://github.com/xwiki/xwiki-rendering
repo_name: xwiki/xwiki-rendering
description: The XWiki Rendering Engine
repo_language: Java
owner: xwiki
file_changes: filename: XHTMLWikiPrinter.java
change_type: ModificationType.MODIFY
diff: @@ -23,6 +23,8 @@
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
+import java.util.regex.Pattern;
 
 import org.apache.commons.lang3.StringUtils;
 import org.xml.sax.Attributes;
@@ -48,6 +50,17 @@ public class XHTMLWikiPrinter extends XMLWikiPrinter
     @Unstable
     public static final String TRANSLATED_ATTRIBUTE_PREFIX = "data-xwiki-translated-attribute-";
 
+    /**
+     * Pattern for matching characters not allowed in data attributes.
+     * <p>
+     * This is the inverse of the definition of a name being
+     * <a href="https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible>XML-compatible</a>,
+     * i.e., matching the <a href="https://www.w3.org/TR/xml/#NT-Name">Name production</a> without ":".
+     */
+    private static final Pattern DATA_REPLACEMENT_PATTERN = Pattern.compile("[^A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6"
+        + "\\u00F8-\\u02ff\\u0370-\\u037d\\u037f-\\u1fff\\u200c\\u200d\\u2070-\\u218f\\u2c00-\\u2fef\\u3001-\\ud7ff"
+        + "\\uf900-\\ufdcf\\ufdf0-\\ufffd\\x{10000}-\\x{EFFFF}\\-.0-9\\u00b7\\u0300-\\u036f\\u203f-\\u2040]");
+
     /**
      * The sanitizer used to restrict allowed elements and attributes, can be null (no restrictions).
      *
@@ -260,7 +273,13 @@ private Map<String, String> cleanAttributes(String elementName, Map<String, Stri
                 if (this.htmlElementSanitizer.isAttributeAllowed(elementName, e.getKey(), e.getValue())) {
                     cleanAttributes.put(e.getKey(), e.getValue());
                 } else {
-                    cleanAttributes.put(TRANSLATED_ATTRIBUTE_PREFIX + e.getKey(), e.getValue());
+                    // Keep but clean invalid attributes with a prefix (removed during parsing) to avoid loosing them
+                    // through WYSIWYG editing.
+                    String translatedName =
+                        TRANSLATED_ATTRIBUTE_PREFIX + removeInvalidDataAttributeCharacters(e.getKey());
+                    if (this.htmlElementSanitizer.isAttributeAllowed(elementName, translatedName, e.getValue())) {
+                        cleanAttributes.put(translatedName, e.getValue());
+                    }
                 }
             }
         }
@@ -279,9 +298,18 @@ private String[][] cleanAttributes(String elementName, String[][] attributes)
                     if (this.htmlElementSanitizer.isAttributeAllowed(elementName, entry[0], entry[1])) {
                         return entry;
                     } else {
-                        return new String[] { TRANSLATED_ATTRIBUTE_PREFIX + entry[0], entry[1] };
+                        // Keep but clean invalid attributes with a prefix (removed during parsing) to avoid loosing
+                        // them through WYSIWYG editing.
+                        String translatedName =
+                            TRANSLATED_ATTRIBUTE_PREFIX + removeInvalidDataAttributeCharacters(entry[0]);
+                        if (this.htmlElementSanitizer.isAttributeAllowed(elementName, translatedName, entry[1])) {
+                            return new String[] { translatedName, entry[1] };
+                        } else {
+                            return null;
+                        }
                     }
                 })
+                .filter(Objects::nonNull)
                 .toArray(String[][]::new);
         }
 
@@ -304,8 +332,16 @@ private Attributes cleanAttributes(String elementName, Attributes attributes)
                     ((AttributesImpl) allowedAttribute).addAttribute(null, null, attributes.getQName(i),
                         null, attributes.getValue(i));
                 } else {
-                    ((AttributesImpl) allowedAttribute).addAttribute(null, null,
-                        TRANSLATED_ATTRIBUTE_PREFIX + attributes.getQName(i), null, attributes.getValue(i));
+                    // Keep but clean invalid attributes with a prefix (removed during parsing) to avoid loosing them
+                    // through WYSIWYG editing.
+                    String translatedName =
+                        TRANSLATED_ATTRIBUTE_PREFIX + removeInvalidDataAttributeCharacters(attributes.getQName(i));
+                    if (this.htmlElementSanitizer.isAttributeAllowed(elementName, translatedName,
+                        attributes.getValue(i)))
+                    {
+                        ((AttributesImpl) allowedAttribute).addAttribute(null, null,
+                            translatedName, null, attributes.getValue(i));
+                    }
                 }
             }
         }
@@ -313,6 +349,17 @@ private Attributes cleanAttributes(String elementName, Attributes attributes)
         return allowedAttribute;
     }
 
+    /**
+     * Strips out invalid characters from names used for data attributes.
+     *
+     * @param name the data attribute name to clean
+     * @return valid name, to be prefixed with data-
+     */
+    public static String removeInvalidDataAttributeCharacters(String name)
+    {
+        return DATA_REPLACEMENT_PATTERN.matcher(name).replaceAll("");
+    }
+
     private void handleSpaceWhenStartElement()
     {
         // Use case: <tag1>something <tag2>...

programming_language: Java
filename: XHTMLWikiPrinterTest.java
change_type: ModificationType.MODIFY
diff: @@ -19,11 +19,21 @@
  */
 package org.xwiki.rendering.renderer.printer;
 
+import java.util.Map;
+
 import org.junit.jupiter.params.ParameterizedTest;
 import org.junit.jupiter.params.provider.CsvSource;
+import org.mockito.InOrder;
+import org.mockito.Mockito;
+import org.xml.sax.helpers.AttributesImpl;
+import org.xwiki.xml.html.HTMLElementSanitizer;
 
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.atLeast;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
 
 /**
  * Unit tests for {@link XHTMLWikiPrinter}.
@@ -46,4 +56,75 @@ void testRawEscaping(String input, String expected)
         xhtmlWikiPrinter.printRaw(input);
         verify(mockPrinter).print(expected);
     }
+
+    @ParameterizedTest
+    @CsvSource({
+        "invalid, value, data-xwiki-translated-attribute-invalid, value",
+        "valid, test&, valid, test&amp;",
+        "in/valid, value, data-xwiki-translated-attribute-invalid, value"
+    })
+    void testParameterCleaning(String parameterName, String parameterValue, String expectedName, String expectedValue)
+    {
+        HTMLElementSanitizer mockSanitizer = mock(HTMLElementSanitizer.class);
+        when(mockSanitizer.isElementAllowed(anyString())).thenReturn(true);
+        when(mockSanitizer.isAttributeAllowed(anyString(), anyString(), anyString())).then(invocation ->
+        {
+            String attributeName = invocation.getArgument(1, String.class);
+            return "valid".equals(attributeName) || attributeName.startsWith("data-");
+        });
+
+        // Test all possibilities of invoking the printer (with different kinds of arguments).
+        WikiPrinter mockPrinter = mock(WikiPrinter.class);
+        XHTMLWikiPrinter xhtmlWikiPrinter = new XHTMLWikiPrinter(mockPrinter, mockSanitizer);
+        Map<String, String> mapParameters = Map.of(parameterName, parameterValue);
+        xhtmlWikiPrinter.printXMLStartElement("div", mapParameters);
+        verify(mockSanitizer, atLeast(1)).isElementAllowed("div");
+        verify(mockSanitizer, atLeast(1)).isAttributeAllowed("div", parameterName, parameterValue);
+        verify(mockSanitizer, atLeast(1)).isAttributeAllowed("div", expectedName, parameterValue);
+        verifyPrinting(mockPrinter, expectedName, expectedValue, true);
+
+        mockPrinter = mock(WikiPrinter.class);
+        xhtmlWikiPrinter = new XHTMLWikiPrinter(mockPrinter, mockSanitizer);
+        xhtmlWikiPrinter.printXMLElement("div", mapParameters);
+        verifyPrinting(mockPrinter, expectedName, expectedValue, false);
+
+        mockPrinter = mock(WikiPrinter.class);
+        xhtmlWikiPrinter = new XHTMLWikiPrinter(mockPrinter, mockSanitizer);
+        String[][] arrayParameters = { { parameterName, parameterValue } };
+        xhtmlWikiPrinter.printXMLStartElement("div", arrayParameters);
+        verifyPrinting(mockPrinter, expectedName, expectedValue, true);
+
+        mockPrinter = mock(WikiPrinter.class);
+        xhtmlWikiPrinter = new XHTMLWikiPrinter(mockPrinter, mockSanitizer);
+        xhtmlWikiPrinter.printXMLElement("div", arrayParameters);
+        verifyPrinting(mockPrinter, expectedName, expectedValue, false);
+
+        mockPrinter = mock(WikiPrinter.class);
+        xhtmlWikiPrinter = new XHTMLWikiPrinter(mockPrinter, mockSanitizer);
+        AttributesImpl attributes = new AttributesImpl();
+        attributes.addAttribute(null, null, parameterName, null, parameterValue);
+        xhtmlWikiPrinter.printXMLStartElement("div", attributes);
+        verifyPrinting(mockPrinter, expectedName, expectedValue, true);
+    }
+
+    private void verifyPrinting(WikiPrinter mockPrinter, String attributeName,
+        String attributeValue, boolean isStart)
+    {
+        InOrder inOrder = Mockito.inOrder(mockPrinter);
+        inOrder.verify(mockPrinter).print("<");
+        inOrder.verify(mockPrinter).print("div");
+        inOrder.verify(mockPrinter).print(" ");
+        inOrder.verify(mockPrinter).print(attributeName);
+        inOrder.verify(mockPrinter).print("=");
+        inOrder.verify(mockPrinter).print("\"");
+        inOrder.verify(mockPrinter).print(attributeValue);
+        inOrder.verify(mockPrinter).print("\"");
+        if (isStart) {
+            inOrder.verify(mockPrinter).print(">");
+        } else {
+            inOrder.verify(mockPrinter).print("/>");
+        }
+        verifyNoMoreInteractions(mockPrinter);
+
+    }
 }

programming_language: Java