CVE-2023-26480 (published 2023-03-02T18:15Z)

XWiki Platform is a generic wiki platform. Starting in version 12.10, a user without script rights can introduce a stored cross-site scripting by using the Live Data macro. This has been patched in XWiki 14.9, 14.4.7, and 13.10.10. There are no known workarounds.\n

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.
         
         

Fix information:
repo_url: https://github.com/xwiki/xwiki-platform
commit_details: repo_url: https://github.com/xwiki/xwiki-platform
author: Manuel Leduc
author_date: 2022-10-20 11:18:19+02:00
msg: XWIKI-20143: Improved Live Data escaping
repository: repo_url: https://github.com/xwiki/xwiki-platform
repo_name: xwiki/xwiki-platform
description: The XWiki platform
repo_language: Java
owner: xwiki
file_changes: filename: pom.xml
change_type: ModificationType.MODIFY
diff: @@ -58,6 +58,11 @@
       <artifactId>xwiki-platform-skin-api</artifactId>
       <version>${project.version}</version>
     </dependency>
+    <dependency>
+      <groupId>org.xwiki.platform</groupId>
+      <artifactId>xwiki-platform-bridge</artifactId>
+      <version>${project.version}</version>
+    </dependency>
     <!-- Test dependencies -->
     <dependency>
       <groupId>org.xwiki.rendering</groupId>

programming_language: HTML
filename: LiveDataMacro.java
change_type: ModificationType.MODIFY
diff: @@ -19,17 +19,9 @@
  */
 package org.xwiki.livedata.internal.macro;
 
-import java.net.URL;
-import java.net.URLDecoder;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
 
 import javax.inject.Inject;
 import javax.inject.Named;
@@ -39,15 +31,6 @@
 import org.xwiki.component.annotation.Component;
 import org.xwiki.livedata.LiveDataConfiguration;
 import org.xwiki.livedata.LiveDataConfigurationResolver;
-import org.xwiki.livedata.LiveDataLayoutDescriptor;
-import org.xwiki.livedata.LiveDataMeta;
-import org.xwiki.livedata.LiveDataPaginationConfiguration;
-import org.xwiki.livedata.LiveDataQuery;
-import org.xwiki.livedata.LiveDataQuery.Constraint;
-import org.xwiki.livedata.LiveDataQuery.Filter;
-import org.xwiki.livedata.LiveDataQuery.SortEntry;
-import org.xwiki.livedata.LiveDataQuery.Source;
-import org.xwiki.livedata.internal.JSONMerge;
 import org.xwiki.livedata.macro.LiveDataMacroParameters;
 import org.xwiki.rendering.block.Block;
 import org.xwiki.rendering.block.GroupBlock;
@@ -59,6 +42,9 @@
 
 import com.fasterxml.jackson.databind.ObjectMapper;
 
+import static java.util.Collections.singletonList;
+import static java.util.Collections.singletonMap;
+
 /**
  * Display dynamic lists of data.
  * 
@@ -70,27 +56,17 @@
 @Singleton
 public class LiveDataMacro extends AbstractMacro<LiveDataMacroParameters>
 {
-    private static final Pattern PATTERN_COMMA = Pattern.compile("\\s*,\\s*");
-
-    private static final String UTF8 = "UTF-8";
-
     /**
      * Used to add default Live Data configuration values.
      */
     @Inject
     private LiveDataConfigurationResolver<LiveDataConfiguration> defaultLiveDataConfigResolver;
 
-    /**
-     * Used to read the Live Data configuration from the macro content.
-     */
     @Inject
-    private LiveDataConfigurationResolver<String> stringLiveDataConfigResolver;
+    private LiveDataMacroConfiguration liveDataMacroConfiguration;
 
-    /**
-     * Used to merge the Live Data configuration built from the macro parameters with the live data configuration read
-     * from the macro content.
-     */
-    private JSONMerge jsonMerge = new JSONMerge();
+    @Inject
+    private LiveDataMacroRights liveDataMacroRights;
 
     /**
      * The component used to load the JavaScript code of the Live Data widget.
@@ -115,7 +91,7 @@ public List<Block> execute(LiveDataMacroParameters parameters, String content, M
         throws MacroExecutionException
     {
         // Load the JavaScript code of the Live Data widget.
-        Map<String, Object> skinExtensionParameters = Collections.singletonMap("forceSkinAction", Boolean.TRUE);
+        Map<String, Object> skinExtensionParameters = singletonMap("forceSkinAction", Boolean.TRUE);
         this.jsfx.use("uicomponents/widgets/liveData.js", skinExtensionParameters);
 
         GroupBlock output = new GroupBlock();
@@ -125,16 +101,23 @@ public List<Block> execute(LiveDataMacroParameters parameters, String content, M
         }
         try {
             // Compute the live data configuration based on the macro parameters.
-            LiveDataConfiguration liveDataConfig = getLiveDataConfiguration(content, parameters);
+            LiveDataConfiguration liveDataConfig = this.liveDataMacroConfiguration.getLiveDataConfiguration(content,
+                parameters);
             // Add the default values.
             liveDataConfig = this.defaultLiveDataConfigResolver.resolve(liveDataConfig);
             // Serialize as JSON.
             ObjectMapper objectMapper = new ObjectMapper();
             output.setParameter("data-config", objectMapper.writeValueAsString(liveDataConfig));
+            // The content is trusted if the author has script right, or if no advanced configuration is used (i.e., 
+            // no macro content), and we are running in a trusted context.
+            boolean trustedContent =
+                StringUtils.isBlank(content) || (this.liveDataMacroRights.authorHasScriptRight()
+                    && !context.getTransformationContext().isRestricted());
+            output.setParameter("data-config-content-trusted", Boolean.toString(trustedContent));
         } catch (Exception e) {
             throw new MacroExecutionException("Failed to generate live data configuration from macro parameters.", e);
         }
-        return Collections.singletonList(output);
+        return singletonList(output);
     }
 
     @Override
@@ -142,152 +125,4 @@ public boolean supportsInlineMode()
     {
         return false;
     }
-
-    private LiveDataConfiguration getLiveDataConfiguration(String content, LiveDataMacroParameters parameters)
-        throws Exception
-    {
-        String json = StringUtils.defaultIfBlank(content, "{}");
-        LiveDataConfiguration advancedConfig = this.stringLiveDataConfigResolver.resolve(json);
-        LiveDataConfiguration basicConfig = getLiveDataConfiguration(parameters);
-        // Make sure both configurations have the same id so that they are properly merged.
-        advancedConfig.setId(basicConfig.getId());
-        return this.jsonMerge.merge(advancedConfig, basicConfig);
-    }
-
-    private LiveDataConfiguration getLiveDataConfiguration(LiveDataMacroParameters parameters) throws Exception
-    {
-        LiveDataConfiguration liveDataConfig = new LiveDataConfiguration();
-        liveDataConfig.setId(parameters.getId());
-        liveDataConfig.setQuery(getQuery(parameters));
-        liveDataConfig.setMeta(getMeta(parameters));
-        return liveDataConfig;
-    }
-
-    private LiveDataQuery getQuery(LiveDataMacroParameters parameters) throws Exception
-    {
-        LiveDataQuery query = new LiveDataQuery();
-        query.setProperties(getProperties(parameters.getProperties()));
-        query.setSource(new Source(parameters.getSource()));
-        query.getSource().getParameters().putAll(getSourceParameters(parameters.getSourceParameters()));
-        query.setSort(getSortEntries(parameters.getSort()));
-        query.setFilters(getFilters(parameters.getFilters()));
-        query.setLimit(parameters.getLimit());
-        query.setOffset(parameters.getOffset());
-        return query;
-    }
-
-    private List<String> getProperties(String properties)
-    {
-        if (properties == null) {
-            return null;
-        } else {
-            return Stream.of(PATTERN_COMMA.split(properties)).collect(Collectors.toList());
-        }
-    }
-
-    private Map<String, Object> getSourceParameters(String sourceParametersString) throws Exception
-    {
-        if (StringUtils.isEmpty(sourceParametersString)) {
-            return Collections.emptyMap();
-        }
-
-        Map<String, List<String>> urlParams = getURLParameters('?' + sourceParametersString);
-        Map<String, Object> sourceParams = new HashMap<>();
-        for (Map.Entry<String, List<String>> entry : urlParams.entrySet()) {
-            if (entry.getValue().size() > 1) {
-                sourceParams.put(entry.getKey(), entry.getValue());
-            } else {
-                sourceParams.put(entry.getKey(), entry.getValue().get(0));
-            }
-        }
-        return sourceParams;
-    }
-
-    private List<SortEntry> getSortEntries(String sort)
-    {
-        if (sort == null) {
-            return null;
-        } else {
-            return Stream.of(PATTERN_COMMA.split(sort)).filter(StringUtils::isNotEmpty).map(this::getSortEntry)
-                .collect(Collectors.toList());
-        }
-    }
-
-    private SortEntry getSortEntry(String sortEntryString)
-    {
-        SortEntry sortEntry = new SortEntry();
-        sortEntry.setDescending(sortEntryString.endsWith(":desc"));
-        if (sortEntry.isDescending() || sortEntryString.endsWith(":asc")) {
-            sortEntry.setProperty(StringUtils.substringBeforeLast(sortEntryString, ":"));
-        } else {
-            sortEntry.setProperty(sortEntryString);
-        }
-        return sortEntry;
-    }
-
-    private List<Filter> getFilters(String filtersString) throws Exception
-    {
-        List<Filter> filters = getURLParameters('?' + StringUtils.defaultString(filtersString)).entrySet().stream()
-            .map(this::getFilter).collect(Collectors.toList());
-        return filters.isEmpty() ? null : filters;
-    }
-
-    private Filter getFilter(Map.Entry<String, List<String>> entry)
-    {
-        Filter filter = new Filter();
-        filter.setProperty(entry.getKey());
-        filter.getConstraints().addAll(entry.getValue().stream().map(Constraint::new).collect(Collectors.toList()));
-        return filter;
-    }
-
-    private LiveDataMeta getMeta(LiveDataMacroParameters parameters)
-    {
-        LiveDataMeta meta = new LiveDataMeta();
-        meta.setLayouts(getLayouts(parameters));
-        meta.setPagination(getPagination(parameters));
-        return meta;
-    }
-
-    private List<LiveDataLayoutDescriptor> getLayouts(LiveDataMacroParameters parameters)
-    {
-        if (parameters.getLayouts() == null) {
-            return null;
-        } else {
-            return Stream.of(PATTERN_COMMA.split(parameters.getLayouts())).map(LiveDataLayoutDescriptor::new)
-                .collect(Collectors.toList());
-        }
-    }
-
-    private LiveDataPaginationConfiguration getPagination(LiveDataMacroParameters parameters)
-    {
-        LiveDataPaginationConfiguration pagination = new LiveDataPaginationConfiguration();
-        pagination.setShowPageSizeDropdown(parameters.getShowPageSizeDropdown());
-        if (parameters.getPageSizes() != null) {
-            pagination.setPageSizes(Stream.of(PATTERN_COMMA.split(parameters.getPageSizes())).map(Integer::parseInt)
-                .collect(Collectors.toList()));
-        }
-        return pagination;
-    }
-
-    private Map<String, List<String>> getURLParameters(String url) throws Exception
-    {
-        URL baseURL = new URL("http://www.xwiki.org");
-        String queryString = new URL(baseURL, url).getQuery();
-        Map<String, List<String>> parameters = new HashMap<>();
-        for (String entry : queryString.split("&")) {
-            String[] parts = entry.split("=", 2);
-            String key = URLDecoder.decode(parts[0], UTF8);
-            if (key.isEmpty()) {
-                continue;
-            }
-            String value = parts.length == 2 ? URLDecoder.decode(parts[1], UTF8) : "";
-            List<String> values = parameters.get(key);
-            if (values == null) {
-                values = new ArrayList<>();
-                parameters.put(key, values);
-            }
-            values.add(value);
-        }
-        return parameters;
-    }
 }

programming_language: Java
filename: LiveDataMacroConfiguration.java
change_type: ModificationType.ADD
diff: @@ -0,0 +1,233 @@
+/*
+ * See the NOTICE file distributed with this work for additional
+ * information regarding copyright ownership.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.xwiki.livedata.internal.macro;
+
+import java.net.URL;
+import java.net.URLDecoder;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import org.apache.commons.lang3.StringUtils;
+import org.xwiki.component.annotation.Component;
+import org.xwiki.livedata.LiveDataConfiguration;
+import org.xwiki.livedata.LiveDataConfigurationResolver;
+import org.xwiki.livedata.LiveDataLayoutDescriptor;
+import org.xwiki.livedata.LiveDataMeta;
+import org.xwiki.livedata.LiveDataPaginationConfiguration;
+import org.xwiki.livedata.LiveDataQuery;
+import org.xwiki.livedata.internal.JSONMerge;
+import org.xwiki.livedata.macro.LiveDataMacroParameters;
+
+/**
+ * Provides services to manipulate configurations for the {@link LiveDataMacroConfiguration}.
+ *
+ * @version $Id$
+ * @since 14.9
+ * @since 14.4.7
+ * @since 13.10.10
+ */
+@Component(roles = LiveDataMacroConfiguration.class)
+@Singleton
+public class LiveDataMacroConfiguration
+{
+    private static final Pattern PATTERN_COMMA = Pattern.compile("\\s*,\\s*");
+
+    private static final String UTF8 = "UTF-8";
+
+    /**
+     * Used to read the Live Data configuration from the macro content.
+     */
+    @Inject
+    private LiveDataConfigurationResolver<String> stringLiveDataConfigResolver;
+
+    /**
+     * Used to merge the Live Data configuration built from the macro parameters with the live data configuration read
+     * from the macro content.
+     */
+    private JSONMerge jsonMerge = new JSONMerge();
+
+    /**
+     * Resolve a complete Live Data configuration from a json advanced configuration (the content) and a set of macro
+     * parameters.
+     *
+     * @param content the string representation of the json live data advanced configuration
+     * @param parameters the Live Data macro parameters
+     * @return the complete Live Data configuration
+     * @throws Exception in case of error when resolving the configuration
+     */
+    public LiveDataConfiguration getLiveDataConfiguration(String content, LiveDataMacroParameters parameters)
+        throws Exception
+    {
+        String json = StringUtils.defaultIfBlank(content, "{}");
+        LiveDataConfiguration advancedConfig = this.stringLiveDataConfigResolver.resolve(json);
+        LiveDataConfiguration basicConfig = getLiveDataConfiguration(parameters);
+        // Make sure both configurations have the same id so that they are properly merged.
+        advancedConfig.setId(basicConfig.getId());
+        return this.jsonMerge.merge(advancedConfig, basicConfig);
+    }
+
+    private LiveDataConfiguration getLiveDataConfiguration(LiveDataMacroParameters parameters) throws Exception
+    {
+        LiveDataConfiguration liveDataConfig = new LiveDataConfiguration();
+        liveDataConfig.setId(parameters.getId());
+        liveDataConfig.setQuery(getQuery(parameters));
+        liveDataConfig.setMeta(getMeta(parameters));
+        return liveDataConfig;
+    }
+
+    private LiveDataQuery getQuery(LiveDataMacroParameters parameters) throws Exception
+    {
+        LiveDataQuery query = new LiveDataQuery();
+        query.setProperties(getProperties(parameters.getProperties()));
+        query.setSource(new LiveDataQuery.Source(parameters.getSource()));
+        query.getSource().getParameters().putAll(getSourceParameters(parameters.getSourceParameters()));
+        query.setSort(getSortEntries(parameters.getSort()));
+        query.setFilters(getFilters(parameters.getFilters()));
+        query.setLimit(parameters.getLimit());
+        query.setOffset(parameters.getOffset());
+        return query;
+    }
+
+    private List<String> getProperties(String properties)
+    {
+        if (properties == null) {
+            return null;
+        } else {
+            return Stream.of(PATTERN_COMMA.split(properties)).collect(Collectors.toList());
+        }
+    }
+
+    private Map<String, Object> getSourceParameters(String sourceParametersString) throws Exception
+    {
+        if (StringUtils.isEmpty(sourceParametersString)) {
+            return Collections.emptyMap();
+        }
+
+        Map<String, List<String>> urlParams = getURLParameters('?' + sourceParametersString);
+        Map<String, Object> sourceParams = new HashMap<>();
+        for (Map.Entry<String, List<String>> entry : urlParams.entrySet()) {
+            if (entry.getValue().size() > 1) {
+                sourceParams.put(entry.getKey(), entry.getValue());
+            } else {
+                sourceParams.put(entry.getKey(), entry.getValue().get(0));
+            }
+        }
+        return sourceParams;
+    }
+
+    private List<LiveDataQuery.SortEntry> getSortEntries(String sort)
+    {
+        if (sort == null) {
+            return null;
+        } else {
+            return Stream.of(PATTERN_COMMA.split(sort)).filter(StringUtils::isNotEmpty).map(this::getSortEntry)
+                .collect(Collectors.toList());
+        }
+    }
+
+    private LiveDataQuery.SortEntry getSortEntry(String sortEntryString)
+    {
+        LiveDataQuery.SortEntry sortEntry = new LiveDataQuery.SortEntry();
+        sortEntry.setDescending(sortEntryString.endsWith(":desc"));
+        if (sortEntry.isDescending() || sortEntryString.endsWith(":asc")) {
+            sortEntry.setProperty(StringUtils.substringBeforeLast(sortEntryString, ":"));
+        } else {
+            sortEntry.setProperty(sortEntryString);
+        }
+        return sortEntry;
+    }
+
+    private List<LiveDataQuery.Filter> getFilters(String filtersString) throws Exception
+    {
+        List<LiveDataQuery.Filter> filters =
+            getURLParameters('?' + StringUtils.defaultString(filtersString)).entrySet().stream()
+                .map(this::getFilter).collect(Collectors.toList());
+        return filters.isEmpty() ? null : filters;
+    }
+
+    private LiveDataQuery.Filter getFilter(Map.Entry<String, List<String>> entry)
+    {
+        LiveDataQuery.Filter filter = new LiveDataQuery.Filter();
+        filter.setProperty(entry.getKey());
+        filter.getConstraints()
+            .addAll(entry.getValue().stream().map(LiveDataQuery.Constraint::new).collect(Collectors.toList()));
+        return filter;
+    }
+
+    private LiveDataMeta getMeta(LiveDataMacroParameters parameters)
+    {
+        LiveDataMeta meta = new LiveDataMeta();
+        meta.setLayouts(getLayouts(parameters));
+        meta.setPagination(getPagination(parameters));
+        return meta;
+    }
+
+    private List<LiveDataLayoutDescriptor> getLayouts(LiveDataMacroParameters parameters)
+    {
+        if (parameters.getLayouts() == null) {
+            return null;
+        } else {
+            return Stream.of(PATTERN_COMMA.split(parameters.getLayouts())).map(LiveDataLayoutDescriptor::new)
+                .collect(Collectors.toList());
+        }
+    }
+
+    private LiveDataPaginationConfiguration getPagination(LiveDataMacroParameters parameters)
+    {
+        LiveDataPaginationConfiguration pagination = new LiveDataPaginationConfiguration();
+        pagination.setShowPageSizeDropdown(parameters.getShowPageSizeDropdown());
+        if (parameters.getPageSizes() != null) {
+            pagination.setPageSizes(Stream.of(PATTERN_COMMA.split(parameters.getPageSizes())).map(Integer::parseInt)
+                .collect(Collectors.toList()));
+        }
+        return pagination;
+    }
+
+    private Map<String, List<String>> getURLParameters(String url) throws Exception
+    {
+        URL baseURL = new URL("http://www.xwiki.org");
+        String queryString = new URL(baseURL, url).getQuery();
+        Map<String, List<String>> parameters = new HashMap<>();
+        for (String entry : queryString.split("&")) {
+            String[] parts = entry.split("=", 2);
+            String key = URLDecoder.decode(parts[0], UTF8);
+            if (key.isEmpty()) {
+                continue;
+            }
+            String value = parts.length == 2 ? URLDecoder.decode(parts[1], UTF8) : "";
+            List<String> values = parameters.get(key);
+            if (values == null) {
+                values = new ArrayList<>();
+                parameters.put(key, values);
+            }
+            values.add(value);
+        }
+        return parameters;
+    }
+}

programming_language: Java
filename: LiveDataMacroRights.java
change_type: ModificationType.ADD
diff: @@ -0,0 +1,60 @@
+/*
+ * See the NOTICE file distributed with this work for additional
+ * information regarding copyright ownership.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.xwiki.livedata.internal.macro;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import org.xwiki.bridge.DocumentAccessBridge;
+import org.xwiki.component.annotation.Component;
+import org.xwiki.model.reference.DocumentReference;
+import org.xwiki.security.authorization.AuthorizationManager;
+
+import static org.xwiki.security.authorization.Right.SCRIPT;
+
+/**
+ * Provides the services related to rights for {@link LiveDataMacro}.
+ *
+ * @version $Id$
+ * @since 14.9
+ * @since 14.4.7
+ * @since 13.10.10
+ */
+@Component(roles = LiveDataMacroRights.class)
+@Singleton
+public class LiveDataMacroRights
+{
+    @Inject
+    private DocumentAccessBridge documentAccessBridge;
+
+    @Inject
+    private AuthorizationManager authorizationManager;
+
+    /**
+     * @return {@code true} if the last author of the document where the Live Data macro is executed has script rights
+     *     on said document, {@code false} otherwise
+     */
+    public boolean authorHasScriptRight()
+    {
+        DocumentReference currentDocumentReference = this.documentAccessBridge.getCurrentDocumentReference();
+        DocumentReference currentAuthorReference = this.documentAccessBridge.getCurrentAuthorReference();
+        return this.authorizationManager.hasAccess(SCRIPT, currentAuthorReference, currentDocumentReference);
+    }
+}

programming_language: Java
filename: ApplicationResources.properties
change_type: ModificationType.MODIFY
diff: @@ -106,7 +106,7 @@ livedata.panel.sort.direction.descending=Descending
 livedata.panel.sort.add=Add sort
 livedata.panel.sort.delete=Delete sort
 
-livedata.displayer.emptyValue=N/A<sup>*</sup>
+livedata.displayer.emptyValue=N/A
 
 livedata.displayer.link.noValue=(no value)
 

programming_language: R
filename: ApplicationResources_de.properties
change_type: ModificationType.MODIFY
diff: @@ -87,7 +87,7 @@ livedata.panel.sort.direction.ascending=Aufsteigend
 livedata.panel.sort.direction.descending=Absteigend
 livedata.panel.sort.add=Sortierung hinzuf\u00FCgen
 livedata.panel.sort.delete=Sortierung l\u00F6schen
-livedata.displayer.emptyValue=n.v.<sup>*</sup>
+livedata.displayer.emptyValue=n.v.
 livedata.displayer.link.noValue=(kein Wert)
 livedata.displayer.boolean.true=Wahr
 livedata.displayer.boolean.false=Falsch

programming_language: Batchfile
filename: ApplicationResources_fr.properties
change_type: ModificationType.MODIFY
diff: @@ -87,7 +87,7 @@ livedata.panel.sort.direction.ascending=Croissant
 livedata.panel.sort.direction.descending=D\u00E9croissant
 livedata.panel.sort.add=Ajouter un tri
 livedata.panel.sort.delete=Supprimer le tri
-livedata.displayer.emptyValue=SO<sup>*</sup>
+livedata.displayer.emptyValue=SO
 livedata.displayer.link.noValue=(aucune valeur)
 livedata.displayer.boolean.true=Vrai
 livedata.displayer.boolean.false=Faux

programming_language: R
filename: components.txt
change_type: ModificationType.MODIFY
diff: @@ -1 +1,3 @@
 org.xwiki.livedata.internal.macro.LiveDataMacro
+org.xwiki.livedata.internal.macro.LiveDataMacroConfiguration
+org.xwiki.livedata.internal.macro.LiveDataMacroRights

programming_language: SQL
filename: LiveDataMacroTest.java
change_type: ModificationType.MODIFY
diff: @@ -27,6 +27,7 @@
 import org.junit.jupiter.api.Test;
 import org.mockito.invocation.InvocationOnMock;
 import org.mockito.stubbing.Answer;
+import org.xwiki.bridge.DocumentAccessBridge;
 import org.xwiki.configuration.internal.RestrictedConfigurationSourceProvider;
 import org.xwiki.context.internal.DefaultExecution;
 import org.xwiki.livedata.LiveDataConfiguration;
@@ -43,6 +44,7 @@
 import org.xwiki.rendering.internal.renderer.xhtml.link.DefaultXHTMLLinkRenderer;
 import org.xwiki.rendering.internal.renderer.xhtml.link.DefaultXHTMLLinkTypeRenderer;
 import org.xwiki.rendering.renderer.PrintRendererFactory;
+import org.xwiki.security.authorization.AuthorizationManager;
 import org.xwiki.test.annotation.ComponentList;
 import org.xwiki.test.junit5.mockito.ComponentTest;
 import org.xwiki.test.junit5.mockito.InjectMockComponents;
@@ -80,7 +82,9 @@
     HTMLDefinitions.class,
     MathMLDefinitions.class,
     SVGDefinitions.class,
-    DefaultExecution.class
+    DefaultExecution.class,
+    LiveDataMacroConfiguration.class,
+    LiveDataMacroRights.class
 })
 class LiveDataMacroTest
 {
@@ -93,6 +97,12 @@
     @MockComponent
     private LiveDataConfigurationResolver<String> stringConfigResolver;
 
+    @MockComponent
+    private DocumentAccessBridge documentAccessBridge;
+
+    @MockComponent
+    private AuthorizationManager authorizationManager;
+
     private PrintRendererFactory rendererFactory;
 
     @BeforeEach
@@ -117,7 +127,8 @@ public LiveDataConfiguration answer(InvocationOnMock invocation) throws Throwabl
     void executeWithoutParams() throws Exception
     {
         String expectedConfig = json("{'query':{'source':{}},'meta':{'pagination':{}}}");
-        String expected = "<div class=\"liveData loading\" data-config=\"" + escapeXML(expectedConfig) + "\"></div>";
+        String expected = "<div class=\"liveData loading\" data-config=\"" + escapeXML(expectedConfig) + "\" "
+            + "data-config-content-trusted=\"true\"></div>";
 
         List<Block> blocks = this.liveDataMacro.execute(new LiveDataMacroParameters(), null, null);
         assertBlocks(expected, blocks, this.rendererFactory);
@@ -155,8 +166,8 @@ void execute() throws Exception
         expectedConfig.append("  }".trim());
         expectedConfig.append("}");
 
-        String expected = "<div class=\"liveData loading\" id=\"test\" data-config=\""
-            + escapeXML(json(expectedConfig.toString())) + "\"></div>";
+        String expected = String.format("<div class=\"liveData loading\" id=\"test\" data-config=\"%s\" "
+            + "data-config-content-trusted=\"true\"></div>", escapeXML(json(expectedConfig.toString())));
 
         LiveDataMacroParameters parameters = new LiveDataMacroParameters();
         parameters.setId("test");
@@ -214,8 +225,8 @@ void executeWithContent() throws Exception
         expectedConfig.append("  }".trim());
         expectedConfig.append("}");
 
-        String expected = "<div class=\"liveData loading\" id=\"test\" data-config=\""
-            + escapeXML(json(expectedConfig.toString())) + "\"></div>";
+        String expected = String.format("<div class=\"liveData loading\" id=\"test\" data-config=\"%s\" "
+            + "data-config-content-trusted=\"false\"></div>", escapeXML(json(expectedConfig.toString())));
 
         List<Block> blocks = this.liveDataMacro.execute(parameters, "{...}", null);
         assertBlocks(expected, blocks, this.rendererFactory);

programming_language: Java
filename: package-lock.json
change_type: ModificationType.MODIFY
diff: @@ -8,6 +8,7 @@
       "name": "xwiki-livedata-vue",
       "version": "1.0.0",
       "dependencies": {
+        "dompurify": "2.4.0",
         "lz-string": "1.4.4",
         "u-node": "0.0.2",
         "vue": "2.7.10",
@@ -6475,6 +6476,11 @@
         "url": "https://github.com/fb55/domhandler?sponsor=1"
       }
     },
+    "node_modules/dompurify": {
+      "version": "2.4.0",
+      "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-2.4.0.tgz",
+      "integrity": "sha512-Be9tbQMZds4a3C6xTmz68NlMfeONA//4dOavl/1rNw50E+/QO0KVpbcU0PcaW0nsQxurXls9ZocqFxk8R2mWEA=="
+    },
     "node_modules/domutils": {
       "version": "2.8.0",
       "resolved": "https://registry.npmjs.org/domutils/-/domutils-2.8.0.tgz",
@@ -21827,6 +21833,11 @@
         "domelementtype": "^2.2.0"
       }
     },
+    "dompurify": {
+      "version": "2.4.0",
+      "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-2.4.0.tgz",
+      "integrity": "sha512-Be9tbQMZds4a3C6xTmz68NlMfeONA//4dOavl/1rNw50E+/QO0KVpbcU0PcaW0nsQxurXls9ZocqFxk8R2mWEA=="
+    },
     "domutils": {
       "version": "2.8.0",
       "resolved": "https://registry.npmjs.org/domutils/-/domutils-2.8.0.tgz",

programming_language: JavaScript
filename: package.json
change_type: ModificationType.MODIFY
diff: @@ -19,7 +19,8 @@
     "u-node": "0.0.2",
     "vuedraggable": "2.24.3",
     "vue-tippy": "4.16.0",
-    "vue2-touch-events": "3.2.2"
+    "vue2-touch-events": "3.2.2",
+    "dompurify": "2.4.0"
   },
   "devDependencies": {
     "@vue/cli-plugin-babel": "5.0.8",

programming_language: JavaScript
filename: BaseDisplayer.spec.js
change_type: ModificationType.MODIFY
diff: @@ -81,7 +81,7 @@ describe('BaseDisplayer.vue', () => {
       }
     });
 
-    expect(wrapper.find('div.view > div').html()).toBe('<div><span></span> <span>livedata.displayer.emptyValue</span></div>');
+    expect(wrapper.find('div.view > div').text()).toBe('livedata.displayer.emptyValue*');
   })
 
   it('Renders a viewable entry with an empty content', () => {

programming_language: TypeScript
filename: DisplayerDocTitle.spec.js
change_type: ModificationType.MODIFY
diff: @@ -37,7 +37,8 @@ describe('DisplayerDocTitle.vue', () => {
           return {
             propertyHref: 'colorHref'
           };
-        }
+        },
+        isContentTrusted: () => true
       }
     });
     expect(wrapper.find('a').html()).toBe('<a href="entryLink" class="">Test <sup>1</sup></a>');

programming_language: JavaScript
filename: DisplayerHtml.spec.js
change_type: ModificationType.MODIFY
diff: @@ -28,6 +28,24 @@ describe('DisplayerHtml.vue', () => {
         entry: {
           color: '<strong>some content</strong>'
         }
+      },
+      logic: {
+        isContentTrusted: () => true
+      }
+    })
+    expect(wrapper.find('.html-wrapper').html())
+      .toBe('<div class="html-wrapper"><strong>some content</strong></div>')
+  })
+
+  it('Renders an entry in view mode with untrusted content', () => {
+    const wrapper = initWrapper(DisplayerHtml, {
+      props: {
+        entry: {
+          color: '<strong>some content<script>console.log("hello world")</script></strong>'
+        }
+      },
+      logic: {
+        isContentTrusted: () => false
       }
     })
     expect(wrapper.find('.html-wrapper').html())

programming_language: JavaScript
filename: DisplayerLink.spec.js
change_type: ModificationType.MODIFY
diff: @@ -43,6 +43,41 @@ describe('DisplayerLink.vue', () => {
     expect(wrapper.find('a').element.href).toBe('http://localhost/entryLink');
   })
 
+  it('Renders an entry in view mode with untrusted content', () => {
+    const logic = {
+      getDisplayerDescriptor() {
+        return {
+          propertyHref: 'colorHref'
+        };
+      },
+      isContentTrusted: () => false
+    };
+    const wrapperHttpLink = initWrapper(DisplayerLink, {
+      props: {
+        entry: {
+          color: 'yellow<script>console.log("hello")</script>',
+          colorHref: 'http://test.com'
+        }
+      },
+      logic
+    });
+    expect(wrapperHttpLink.text()).toMatch('yellow')
+    expect(wrapperHttpLink.find('a').element.href).toBe('http://test.com/');
+
+    const wrapperJavascriptLink = initWrapper(DisplayerLink, {
+      props: {
+        entry: {
+          color: 'yellow<script>console.log("hello")</script>',
+          colorHref: 'javascript:console.log("world")'
+        }
+      },
+      logic
+    });
+
+    expect(wrapperJavascriptLink.text()).toMatch('yellow')
+    expect(wrapperJavascriptLink.find('a').element.href).toBe('http://localhost/#');
+  })
+
   it('Renders an entry in view mode with an empty content', () => {
     const wrapper = initWrapper(DisplayerLink, {
       props: {

programming_language: JavaScript
filename: displayerTestsHelper.js
change_type: ModificationType.MODIFY
diff: @@ -158,7 +158,8 @@ export function initWrapper(displayer, {props, logic, editBus, mocks})
           put() {},
           reset() {},
           list() { return []; }
-        }
+        },
+        isContentTrusted: () => true
       }, logic),
     },
     mocks: Object.assign({

programming_language: TypeScript
filename: BaseDisplayer.vue
change_type: ModificationType.MODIFY
diff: @@ -71,10 +71,9 @@
             -->
             <span>{{ value }}</span>
           </slot>
-          <span
-            v-if="!isViewable"
-            v-html="$t('livedata.displayer.emptyValue')"
-          ></span>
+          <span v-if="!isViewable">
+            {{ $t('livedata.displayer.emptyValue') }}<sup>*</sup>
+          </span>
         </div>
 
         <!-- The slot containing the displayer Editor widget -->
@@ -116,7 +115,7 @@
           :close-popover="closePopover"
         />
         <ActionFollowLink
-          :displayer="{ href }"
+          :displayer="{ href: sanitizeUrl(href) }"
           v-if="href"
           :close-popover="closePopover"
         />

programming_language: HTML
filename: DisplayerActions.vue
change_type: ModificationType.MODIFY
diff: @@ -46,7 +46,7 @@
           :key="action.id"
           :class="'action action_' + action.id"
           :title="action.description"
-          :href="entry[action.urlProperty] || '#'"
+          :href="sanitizeUrl(entry[action.urlProperty]) || '#'"
         >
           <XWikiIcon :iconDescriptor="action.icon" /><span class="action-name">{{ action.name }}</span>
         </a>

programming_language: HTML
filename: DisplayerHtml.vue
change_type: ModificationType.MODIFY
diff: @@ -33,7 +33,8 @@
     view-only>
     <!-- Provide the Html Viewer widget to the `viewer` slot -->
     <template #viewer>
-      <div class="html-wrapper" v-html="value"></div>
+      <div class="html-wrapper"
+           v-html="safeValue"/>
     </template>
   </BaseDisplayer>
 </template>

programming_language: HTML
filename: DisplayerLink.vue
change_type: ModificationType.MODIFY
diff: @@ -45,11 +45,11 @@
         so we create an explicit "no value" message in that case
       -->
       <a v-if="linkContent && hasViewRight"
-        :href="href"
+        :href="sanitizeUrl(href)"
         :class="{'explicit-empty-value': !html && !htmlValue}"
-        v-html="linkContent"
+        v-html="sanitizeHtml(linkContent)"
       ></a>
-      <span v-else v-html="linkContent"></span>
+      <span v-else v-html="sanitizeHtml(linkContent)"></span>
     </template>
 
 

programming_language: HTML
filename: DisplayerXObjectProperty.vue
change_type: ModificationType.MODIFY
diff: @@ -35,12 +35,15 @@
 
     <!-- Provide the Html Viewer widget to the `viewer` slot -->
     <template #viewer>
-      <div :class="['html-wrapper', isLoading ? 'disabled' : '']" v-html="value" ref="xObjectPropertyView"></div>
+      <div :class="['html-wrapper', isLoading ? 'disabled' : '']"
+           v-html="sanitizeHtml(value)"
+           ref="xObjectPropertyView"/>
     </template>
 
     <!-- Provide the Html Editor widget to the `editor` slot -->
     <template #editor>
-      <div v-html="editField" ref="xObjectPropertyEdit"></div>
+      <div v-html="sanitizeHtml(editField)"
+           ref="xObjectPropertyEdit"/>
     </template>
   </BaseDisplayer>
 </template>

programming_language: TypeScript
filename: displayerMixin.js
change_type: ModificationType.MODIFY
diff: @@ -18,6 +18,7 @@
  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  */
 
+import * as DOMPurify from 'dompurify';
 
 /**
  * The displayerMixin is a vue mixin containing all the needed
@@ -59,6 +60,9 @@ export default {
     value () {
       return this.entry[this.propertyId];
     },
+    safeValue() {
+      return this.sanitizeHtml(this.value)
+    },
     // The property descriptor of `this.propertyId`
     propertyDescriptor () {
       return this.logic.getPropertyDescriptor(this.propertyId);
@@ -106,6 +110,22 @@ export default {
     genericSave(value) {
       const savedValue =  value || this.editedValue;
       this.logic.getEditBus().save(this.entry, this.propertyId, {[this.propertyId]: savedValue})
+    },
+    sanitizeHtml(value) {
+      if (!this.logic.isContentTrusted()) {
+        // TODO: Take into account xml.htmlElementSanitizer properties when sanitizing (see XWIKI-20249).
+        return DOMPurify.sanitize(value);
+      } else {
+        return value;
+      }
+    },
+    sanitizeUrl(url, subtitute) {
+      // TODO: Take into account xml.htmlElementSanitizer properties when sanitizing (see XWIKI-20249).
+      if (this.logic.isContentTrusted() || DOMPurify.isValidAttribute('a', 'href', url)) {
+        return url;
+      } else {
+        return (subtitute || '#');
+      }
     }
   },
   

programming_language: JavaScript
filename: Logic.js
change_type: ModificationType.MODIFY
diff: @@ -105,6 +105,7 @@ define('xwiki-livedata', [
   const Logic = function (element) {
     this.element = element;
     this.data = JSON.parse(element.getAttribute("data-config") || "{}");
+    this.contentTrusted = element.getAttribute("data-config-content-trusted") === "true"; 
     this.data.entries = Object.freeze(this.data.entries);
 
     // Reactive properties must be initialized before Vue is instantiated.
@@ -1519,6 +1520,18 @@ define('xwiki-livedata', [
       } else {
         this.panels.splice(index, 0, panel);
       }
+    },
+
+    //
+    // Content status
+    //
+
+    /**
+     * @returns {boolean} when false, the content is not trusted will be sanitized whenever Vue integrated escaping
+     * is not enough. When true, the content is never sanitized
+     */
+    isContentTrusted() {
+      return this.contentTrusted;
     }
   };
 

programming_language: JavaScript
repo_url: https://github.com/xwiki/xwiki-platform
commit_details: repo_url: https://github.com/xwiki/xwiki-platform
author: Manuel Leduc
author_date: 2022-10-20 17:10:24+02:00
msg: XWIKI-20143: Improved Live Data escaping

Add missing components in LiveDataMacroComponentList.
repository: repo_url: https://github.com/xwiki/xwiki-platform
repo_name: xwiki/xwiki-platform
description: The XWiki platform
repo_language: Java
owner: xwiki
file_changes: filename: LiveDataMacroComponentList.java
change_type: ModificationType.MODIFY
diff: @@ -49,7 +49,9 @@
     LiveDataMacro.class,
     DefaultLiveDataConfigurationResolver.class,
     StringLiveDataConfigurationResolver.class,
-    JsFileSkinExtension.class
+    JsFileSkinExtension.class,
+    LiveDataMacroConfiguration.class,
+    LiveDataMacroRights.class
 })
 @Inherited
 public @interface LiveDataMacroComponentList

programming_language: Java