CVE-2023-29512 (Other, published 2023-04-19T00:15Z)
Description: value: XWiki Platform is a generic wiki platform offering runtime services for applications built on top of it. Any user with edit rights on a page (e.g., it's own user page), can execute arbitrary Groovy, Python or Velocity code in XWiki leading to full access to the XWiki installation. The root cause is improper escaping of the information loaded from attachments in `imported.vm`, `importinline.vm`, and `packagelist.vm`. This page is installed by default. This vulnerability has been patched in XWiki 15.0-rc-1, 14.10.1, 14.4.8, and 13.10.11. Users are advised to upgrade. There are no known workarounds for this vulnerability.
Severity: nan (CVSS v3 base score: 8.8)
Weakness: CWE-74 \u2014 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
The product constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.
Repository: https://github.com/xwiki/xwiki-platform
Files changed:
xwiki-platform-core/xwiki-platform-web/xwiki-platform-web-templates/pom.xml
xwiki-platform-core/xwiki-platform-web/xwiki-platform-web-templates/src/main/resources/templates/imported.vm
xwiki-platform-core/xwiki-platform-web/xwiki-platform-web-templates/src/main/resources/templates/importinline.vm
xwiki-platform-core/xwiki-platform-web/xwiki-platform-web-templates/src/main/resources/templates/packagelist.vm
xwiki-platform-core/xwiki-platform-web/xwiki-platform-web-templates/src/test/java/org/xwiki/web/ImportInlinePageTest.java
Commit message: XWIKI-20267: Improved escaping in importinline.vm


Vulnerable code:
    <h4 class="legend">$services.localization.render("import_listof${text}files")</h4>
  #set($status = $services.localization.render("import_install_${xwiki.package.status}"))
  #info("$services.localization.render('importing') $!escapetool.xml($request.name): $status")
    <li>$xwiki.package.installed.size() $services.localization.render('import_documentinstalled')</li>
    <li>$xwiki.package.skipped.size() $services.localization.render('import_documentskipped')</li>
    <li>$xwiki.package.errors.size() $services.localization.render('import_documenterrors')</li>
<p class="legend">$services.localization.render('import') #if("$!{request.withversions}" == '1')$services.localization.render('export_addhistory')#end</p>
      <div class="legend">$services.localization.render('core.importer.uploadPackage')</div>
          <input type="hidden" name="form_token" value="$!{services.csrf.getToken()}" />
               <label for="xwikiuploadfile" class="hidden">$services.localization.render('core.viewers.attachments.upload.file')</label>
               <input id="xwikiuploadfile" type="file" name="filepath" class="uploadFileInput noitems" data-max-file-size="$!escapetool.xml($xwiki.getSpacePreference('upload_maxsize'))" />
               <span class="buttonwrapper">
                 <input type="submit" value="Upload" class="button" />
               </span>
    <div class="legend">$services.localization.render('core.importer.availablePackages')</div>
          <div class="legend">$services.localization.render('core.importer.availableDocuments')</div>
                <span class="label">$services.localization.render('core.importer.package')</span>
                <span class="filename">$attach.filename</span>
                <span class="label">$services.localization.render('core.importer.package.description')</span>
                <span class="name">$package.packageName</span>
                <span class="label">$services.localization.render('core.importer.package.version')</span>
                <span class="version">$package.packageVersion</span>
                <span class="label">$services.localization.render('core.importer.package.author')</span>
                <span class="author">$package.packageAuthor</span>
                <span class="label">$services.localization.render('core.importer.package.licence')</span>
                <span class="licence">$package.packageLicense</span>
            <form action="$!{importaction}" method="post" class="static-importer">
                <input type="hidden" name="form_token" value="$!{services.csrf.getToken()}" />
                            $document #if("$!locale.locale" != '') - $locale.locale #end
                        <div class="spacename">$space</div>
                    #foreach($node in $services.model.toTree($package.entries).children)
                  <em>$services.localization.render('core.importer.whenDocumentAlreadyExists')</em>
                     <input type="radio" name="historyStrategy" value="add" checked="checked" />
                     $services.localization.render('core.importer.addNewVersion')
                     <input type="radio" name="historyStrategy" value="replace" />
                     $services.localization.render('core.importer.replaceDocumentHistory')
                     <input type="radio" name="historyStrategy" value="reset" />
                     $services.localization.render('core.importer.resetHistory')
                  $services.localization.render('core.importer.importAsBackup')
                  <input class="button" type="submit" value="$services.localization.render('core.importer.import')" />
            #packName($attach.filename)
          <span class="version">$attach.version</span>
          $services.localization.render('core.importer.packageInformationExtract', [
          ]) - <span class="size">(#dynamicsize($attach.longSize))</span>
  <span class="noitems">$services.localization.render('core.importer.noPackageAvailable')</span>

Fixed code:
    <!-- Required to use the xar script service in the tests. -->
    <dependency>
      <groupId>org.xwiki.platform</groupId>
      <artifactId>xwiki-platform-xar-script</artifactId>
      <version>${project.version}</version>
      <scope>test</scope>
    </dependency>
    <h4 class="legend">
      $escapetool.xml($services.localization.render("import_listof${text}files"))
    </h4>
  #set($status = $escapetool.xml($services.localization.render("import_install_${xwiki.package.status}")))
  #info("$escapetool.xml($services.localization.render('importing')) $!escapetool.xml($request.name): $status")
    <li>$xwiki.package.installed.size() $escapetool.xml($services.localization.render('import_documentinstalled'))</li>
    <li>$xwiki.package.skipped.size() $escapetool.xml($services.localization.render('import_documentskipped'))</li>
    <li>$xwiki.package.errors.size() $escapetool.xml($services.localization.render('import_documenterrors'))</li>
<p class="legend">$escapetool.xml($services.localization.render('import')) #if("$!{request.withversions}" == '1')
  $escapetool.xml($services.localization.render('export_addhistory'))#end</p>
      <div class="legend">
        $escapetool.xml($services.localization.render('core.importer.uploadPackage'))
      </div>
          <input type="hidden" name="form_token" value="$!escapetool.xml($services.csrf.getToken())" />
              <label for="xwikiuploadfile" class="hidden">
                $escapetool.xml($services.localization.render('core.viewers.attachments.upload.file'))
              </label>
              <input id="xwikiuploadfile" type="file" name="filepath" class="uploadFileInput noitems"
                     data-max-file-size="$!escapetool.xml($xwiki.getSpacePreference('upload_maxsize'))"/>
              <span class="buttonwrapper">
                <input type="submit" value="Upload" class="button"/>
              </span>
    <div class="legend">
      $escapetool.xml($services.localization.render('core.importer.availablePackages'))
    </div>
          <div class="legend">
            $escapetool.xml($services.localization.render('core.importer.availableDocuments'))
          </div>
                <span class="label">
                  $escapetool.xml($services.localization.render('core.importer.package'))
                </span>
                <span class="filename">$escapetool.xml($attach.filename)</span>
                <span class="label">
                  $escapetool.xml($services.localization.render('core.importer.package.description'))
                </span>
                <span class="name">$escapetool.xml($package.packageName)</span>
                <span class="label">
                  $escapetool.xml($services.localization.render('core.importer.package.version'))
                </span>
                <span class="version">$escapetool.xml($package.packageVersion)</span>
                <span class="label">
                  $escapetool.xml($services.localization.render('core.importer.package.author'))
                </span>
                <span class="author">$escapetool.xml($package.packageAuthor)</span>
                <span class="label">
                  $escapetool.xml($services.localization.render('core.importer.package.licence'))
                </span>
                <span class="licence">$escapetool.xml($package.packageLicense)</span>
            <form action="$!escapetool.xml($importaction)" method="post" class="static-importer">
                <input type="hidden" name="form_token" value="$!escapetool.xml($services.csrf.token)" />
                            $escapetool.xml($document) #if("$!locale.locale" != '') - $locale.locale #end
                        <div class="spacename">$escapetool.xml($space)</div>
                    #set ($tree = $services.model.toTree($package.entries))
                    #foreach($node in $tree.children)
                  <em>
                    $escapetool.xml($services.localization.render('core.importer.whenDocumentAlreadyExists'))
                  </em>
                    <input type="radio" name="historyStrategy" value="add" checked="checked" />
                    $escapetool.xml($services.localization.render('core.importer.addNewVersion'))
                    <input type="radio" name="historyStrategy" value="replace" />
                    $escapetool.xml($services.localization.render('core.importer.replaceDocumentHistory'))
                    <input type="radio" name="historyStrategy" value="reset" />
                    $escapetool.xml($services.localization.render('core.importer.resetHistory'))
                  $escapetool.xml($services.localization.render('core.importer.importAsBackup'))
                  <input class="button" type="submit" 
                         value="$escapetool.xml($services.localization.render('core.importer.import'))" />
            #set ($packName = "#packName($attach.filename)")
            $escapetool.xml($packName)
          <span class="version">$escapetool.xml($attach.version)</span>
          $escapetool.xml($services.localization.render('core.importer.packageInformationExtract', [
          ])) - <span class="size">(#dynamicsize($attach.longSize))</span>
  <span class="noitems">$escapetool.xml($services.localization.render('core.importer.noPackageAvailable'))</span>
/*
 * 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.web;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.LocalDocumentReference;
import org.xwiki.model.script.ModelScriptService;
import org.xwiki.script.service.ScriptService;
import org.xwiki.skinx.internal.async.SkinExtensionAsync;
import org.xwiki.template.TemplateManager;
import org.xwiki.test.annotation.ComponentList;
import org.xwiki.test.page.PageTest;
import org.xwiki.xar.XarEntry;
import org.xwiki.xar.XarPackage;
import org.xwiki.xar.script.XarScriptService;

import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.plugin.XWikiPluginManager;
import com.xpn.xwiki.plugin.skinx.CssSkinFileExtensionPlugin;
import com.xpn.xwiki.plugin.skinx.JsSkinFileExtensionPlugin;

import static java.util.Collections.singletonList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.when;

/**
 * Test of template {@code importinline.vm}.
 *
 * @version $Id$
 * @since 15.0-rc-1
 * @since 14.10.1
 * @since 14.4.8
 * @since 13.10.11
 */
@ComponentList({
    SkinExtensionAsync.class,
    ModelScriptService.class
})
class ImportInlinePageTest extends PageTest
{
    private TemplateManager templateManager;

    @Mock
    private XarScriptService xarScriptService;

    @BeforeEach
    void setUp() throws Exception
    {
        this.templateManager = this.oldcore.getMocker().getInstance(TemplateManager.class);
        // Enable the ssfx/jsfx plugins.
        XWikiPluginManager pluginManager = this.oldcore.getSpyXWiki().getPluginManager();
        pluginManager.addPlugin("ssfx", CssSkinFileExtensionPlugin.class.getName(), this.context);
        pluginManager.addPlugin("jsfx", JsSkinFileExtensionPlugin.class.getName(), this.context);
        // Initialize XWiki.XWikiPreferences 
        XWikiDocument xWikiPreferencesDocument =
            this.xwiki.getDocument(new DocumentReference("xwiki", "XWiki", "XWikiPreferences"), this.context);
        this.xwiki.saveDocument(xWikiPreferencesDocument, this.context);
        // Initialize the current document
        XWikiDocument currentDocument = this.xwiki.getDocument(new DocumentReference("xwiki", "Doc", "Space"
            + "\"'/><script>console.log('docTitle'</script>{{html}}{{noscript/}}"), this.context);
        currentDocument.setAttachment("attachment.xar", new ByteArrayInputStream("xar content".getBytes()),
            this.context);
        currentDocument.setAttachment("\"'/><script>console.log('secondAttachment')</script>{{/html}}{{noscript/}}",
            new ByteArrayInputStream("file content".getBytes()), this.context);
        this.xwiki.saveDocument(currentDocument, this.context);
        this.context.setDoc(currentDocument);
        this.componentManager.registerComponent(ScriptService.class, "xar", this.xarScriptService);
    }

    @Test
    void escape() throws Exception
    {
        String packageAuthor = "\"'><script>console.log('package author');</script>{{/html}}{{noscript/}}";
        String packageName = "\"'><script>console.log('package name');</script>{{/html}}{{noscript/}}";
        String packageLicense = "\"'><script>console.log('package licence');</script>{{/html}}{{noscript/}}";
        String spaceName = "\"'><script>console.log('space name');</script>{{/html}}{{noscript/}}";
        String pageName = "\"'><script>console.log('page name');</script>{{/html}}{{noscript/}}";
        LocalDocumentReference reference = new LocalDocumentReference(spaceName, pageName, Locale.FRANCE);
        XarEntry xarEntry = new XarEntry(reference);

        XarPackage xarPackage = new XarPackage(singletonList(xarEntry));
        xarPackage.setPackageAuthor(packageAuthor);
        xarPackage.setPackageName(packageName);
        xarPackage.setPackageDescription("packageDescription");
        xarPackage.setPackageLicense(packageLicense);
        xarPackage.setPackageExtensionId("packageExtensionId");

        when(this.xarScriptService.getXarPackage(any(InputStream.class), anyBoolean())).thenReturn(xarPackage);
        this.request.put("file", "attachment.xar");
        Document document = Jsoup.parse(this.templateManager.render("importinline.vm"));

        assertEquals("/xwiki/bin/upload/Doc/Space%22%27%2F%3E%3Cscript%3Econsole.log%28%27docTitle"
                + "%27%3C%2Fscript%3E%7B%7Bhtml%7D%7D%7B%7Bnoscript%2F%7D%7D",
            document.selectFirst("form").attr("action"));
        Element packageinfos = document.selectFirst(".packageinfos");
        assertEquals(packageAuthor, packageinfos.selectFirst(".author").text());
        assertEquals(packageName, packageinfos.selectFirst(".name").text());
        assertEquals(packageLicense, packageinfos.selectFirst(".licence").text());
        Element packageDiv = document.getElementById("package");
        assertEquals(spaceName, packageDiv.selectFirst(".spacename").text());
        Element xitemLi = packageDiv.selectFirst(".xitem");
        assertEquals("\"'><script>console\\.log('space name');</script>{{/html}}{{noscript/}}.\"'>"
                + "<script>console\\.log('page name');</script>{{/html}}{{noscript/}}:fr_FR",
            xitemLi.selectFirst("input[type='hidden']").attr("name"));
        assertEquals("\"'><script>console.log('space name');</script>{{/html}}{{noscript/}} \"'>"
            + "<script>console.log('page name');</script>{{/html}}{{noscript/}} - fr_FR", xitemLi.text());
        List<String> attachmentLinksText =
            document.select("#packagelistcontainer .xitemcontainer.package .name>a")
                .stream()
                .map(Element::text)
                .collect(Collectors.toList());
        assertThat(attachmentLinksText,
            containsInAnyOrder("><script>console.log('secondAttachment')</script>{{/html}}{{noscript/}}",
                "attachment.xar"));
    }
}