Skip to content

Commit 7cf4da9

Browse files
JeroenDeDauwclaude
andauthored
Sanitize the default text, inline labels, intro and outro of semantic maps (#952)
Special:Ask let anyone craft a link that runs JavaScript on the wiki through the semantic map formats (`map`, `leaflet`, `googlemaps3`): * When a query found no locations, the formats returned its `default` text as raw HTML, also in the raw output that Special:Ask serves as HTML * Static locations passed their inline label to the map unsanitized, and Google Maps renders it as HTML * On pages, the formats output `intro` and `outro` as raw HTML, which crafted Special:Ask links could also reach * On wikis that set `$wgRawHtml`, maps on Special:Ask rendered `<html>` sections in their texts as raw HTML The same input in an inline `#ask` let editors store the script in a page. `default` now follows Semantic MediaWiki's handling of a query without results: wikitext on pages, plain text elsewhere. Inline labels get the sanitizing `#display_map` applies, wikitext keeping only links and images, now also without event handlers and unsafe URLs. On pages, the map formats parse `intro` and `outro` themselves, in one parse around the map, so that they can still wrap it. Special:Ask parses without raw HTML. * `MapPrinter` returns `default` as wikitext only on pages, and parses `intro` and `outro` there with the new `WikitextParser::wikitextAroundHtmlToHtml()` * `ElementJsonSerializer::inlineLabel()` holds the inline label sanitizing, now through `HtmlSanitizer`, for `MapPrinter` and `DisplayMapRenderer` * `MapsFactory::newRequestParser()` disallows raw HTML * `TestFactory::renderOnSpecialAsk()` replaces the private copy in `SemanticMapPageParserTest` and takes the output mode Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 1d02d91 commit 7cf4da9

10 files changed

Lines changed: 263 additions & 29 deletions

File tree

‎RELEASE-NOTES.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@ different releases and which versions of PHP and MediaWiki they support, see the
77

88
Not yet released
99

10+
* Fixed an XSS vulnerability in semantic maps: when a query found no locations, its `default` text was output as raw HTML, so a crafted link to Special:Ask could run JavaScript. `default` now works as in other result formats: wikitext on pages, plain text on Special:Ask
11+
* Fixed an XSS vulnerability in semantic maps shown with Google Maps: the inline label of a location in `staticlocations` was used as raw HTML, so a crafted link to Special:Ask could run JavaScript. As in `{{#display_map:}}`, the label now takes wikitext and keeps only its links and images
12+
* Fixed an XSS vulnerability in semantic maps: on pages, their `intro` and `outro` were output as raw HTML, which let editors add scripts and, through Special:Ask, let a crafted link run JavaScript. They now take wikitext, as in other result formats
13+
* Fixed an XSS vulnerability on wikis that set `$wgRawHtml`: maps on Special:Ask rendered `<html>` sections in their texts as raw HTML, so a crafted link could run JavaScript
1014
* Fixed maps not updating when a template or GeoJSON page they use is edited
1115
* Fixed links in marker text and popups missing from "What links here"
1216
* Fixed `<nowiki>`, `<pre>` and similar tags in `{{#display_map:}}` marker text showing as strip markers such as `UNIQ--nowiki-00000000-QINU`. Under Parsoid on MediaWiki 1.44 and later, other tags still show as strip markers, and `<nowiki>` content is parsed as wikitext

‎src/Map/DisplayMap/DisplayMapRenderer.php‎

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
use Maps\Map\MapOutputBuilder;
1313
use Maps\MappingService;
1414
use Maps\Presentation\ElementJsonSerializer;
15-
use Maps\Presentation\WikitextParser;
1615
use Maps\WikitextParsers\LocationParser;
1716
use MediaWiki\Parser\Parser;
1817

@@ -28,7 +27,6 @@ class DisplayMapRenderer {
2827
public ?MappingService $service;
2928
private LocationParser $locationParser;
3029
private FileUrlFinder $fileUrlFinder;
31-
private WikitextParser $wikitextParser;
3230
private ElementJsonSerializer $elementSerializer;
3331

3432
public function __construct( ?MappingService $service = null ) {
@@ -50,8 +48,7 @@ final public function renderMap( MapData $mapData, Parser $parser ): MapOutput {
5048
$this->locationParser = $factory->newLocationParser();
5149
$this->fileUrlFinder = $factory->getFileUrlFinder();
5250

53-
$this->wikitextParser = $factory->newWikitextParser( $parser );
54-
$this->elementSerializer = new ElementJsonSerializer( $this->wikitextParser );
51+
$this->elementSerializer = new ElementJsonSerializer( $factory->newWikitextParser( $parser ) );
5552

5653
$mapData->setParameters( $this->handleMarkerData( $mapData->getParameters() ) );
5754

@@ -129,13 +126,7 @@ private function getLocationJsonObject( Location $location, array $params, $icon
129126
$jsonObj = $location->getJSONObject( $params['title'], $params['label'], $iconUrl, '', '', $visitedIconUrl );
130127

131128
$this->elementSerializer->titleAndText( $jsonObj );
132-
133-
if ( isset( $jsonObj['inlineLabel'] ) ) {
134-
$jsonObj['inlineLabel'] = strip_tags(
135-
$this->wikitextParser->wikitextToHtml( $jsonObj['inlineLabel'] ),
136-
'<a><img>'
137-
);
138-
}
129+
$this->elementSerializer->inlineLabel( $jsonObj );
139130

140131
return $jsonObj;
141132
}

‎src/Map/SemanticFormat/MapPrinter.php‎

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
use Maps\MappingService;
1414
use Maps\MapsFactory;
1515
use Maps\Presentation\ElementJsonSerializer;
16+
use Maps\Presentation\WikitextParser;
1617
use Maps\SemanticMW\QueryHandler;
1718
use Maps\WikitextParsers\LocationParser;
1819
use MediaWiki\Title\Title;
@@ -77,8 +78,6 @@ final public function getResultText( QueryResult $res, $outputMode ): string {
7778
return $this->fatalErrorMsg;
7879
}
7980

80-
$this->isHTML = true;
81-
8281
$factory = MapsFactory::globalInstance();
8382
$this->locationParser = $factory->newLocationParser();
8483
$this->fileUrlFinder = $factory->getFileUrlFinder();
@@ -116,9 +115,13 @@ final public function getResultText( QueryResult $res, $outputMode ): string {
116115
$params['ajaxquery'] = urlencode( $params['ajaxquery'] );
117116

118117
if ( $params['locations'] === [] ) {
119-
return $params['default'];
118+
// Only pages parse the text as wikitext: Special:Ask serves even raw output as HTML.
119+
$this->isHTML = $outputMode !== SMW_OUTPUT_WIKI;
120+
return $this->isHTML ? htmlspecialchars( $this->mDefault ) : $this->mDefault;
120121
}
121122

123+
$this->isHTML = true;
124+
122125
// We can only take care of the zoom defaulting here,
123126
// as not all locations are available in whats passed to Validator.
124127
if ( $this->fullParams['zoom']->wasSetToDefault() && count( $params['locations'] ) > 1 ) {
@@ -134,7 +137,7 @@ final public function getResultText( QueryResult $res, $outputMode ): string {
134137

135138
$this->outputResources( $mapOutput );
136139

137-
return $mapOutput->getHtml();
140+
return $this->withIntroAndOutro( $mapOutput->getHtml(), $wikitextParser, $outputMode );
138141
}
139142

140143
private function outputResources( MapOutput $mapOutput ) {
@@ -148,6 +151,22 @@ private function outputResources( MapOutput $mapOutput ) {
148151
}
149152
}
150153

154+
/**
155+
* On pages, Semantic MediaWiki adds the intro and outro to HTML results without parsing them, so the map parses
156+
* them itself and leaves Semantic MediaWiki none to add.
157+
*/
158+
private function withIntroAndOutro( string $html, WikitextParser $wikitextParser, int $outputMode ): string {
159+
if ( $outputMode !== SMW_OUTPUT_WIKI || ( $this->mIntro === '' && $this->mOutro === '' ) ) {
160+
return $html;
161+
}
162+
163+
$html = $wikitextParser->wikitextAroundHtmlToHtml( $this->mIntro, $html, $this->mOutro );
164+
$this->mIntro = '';
165+
$this->mOutro = '';
166+
167+
return $html;
168+
}
169+
151170
private function randomString(): string {
152171
return substr( str_shuffle( '0123456789abcdefghijklmnopqrstuvwxyz' ), 0, 10 );
153172
}
@@ -250,6 +269,8 @@ private function getJsonForStaticLocation( Location $location, array $params, $i
250269

251270
if ( $params['pagelabel'] ) {
252271
$jsonObj['inlineLabel'] = Linker::link( Title::newFromText( $jsonObj['title'] ) );
272+
} else {
273+
$this->elementSerializer->inlineLabel( $jsonObj );
253274
}
254275

255276
return $jsonObj;

‎src/MapsFactory.php‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -360,7 +360,11 @@ public function newWikitextParser( Parser $pageParser ): WikitextParser {
360360
* as nothing caches the result for other readers.
361361
*/
362362
public function newRequestParser(): Parser {
363-
return $this->newParser( ParserOptions::newFromContext( RequestContext::getMain() ) );
363+
$options = ParserOptions::newFromContext( RequestContext::getMain() );
364+
// The text comes from the request, so anyone can write it.
365+
$options->setAllowUnsafeRawHtml( false );
366+
367+
return $this->newParser( $options );
364368
}
365369

366370
public function smwIntegrationIsEnabled(): bool {

‎src/Presentation/ElementJsonSerializer.php‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,11 @@
99
class ElementJsonSerializer {
1010

1111
private WikitextParser $parser;
12+
private HtmlSanitizer $sanitizer;
1213

1314
public function __construct( WikitextParser $parser ) {
1415
$this->parser = $parser;
16+
$this->sanitizer = new HtmlSanitizer();
1517
}
1618

1719
public function elementToJson( BaseElement $element ): array {
@@ -31,4 +33,10 @@ public function titleAndText( array &$elementJson ): void {
3133
$elementJson['title'] = strip_tags( $elementJson['title'] );
3234
}
3335

36+
public function inlineLabel( array &$elementJson ): void {
37+
if ( isset( $elementJson['inlineLabel'] ) ) {
38+
$elementJson['inlineLabel'] = $this->sanitizer->sanitize( $this->parser->wikitextToHtml( $elementJson['inlineLabel'] ) );
39+
}
40+
}
41+
3442
}

‎src/Presentation/WikitextParser.php‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,20 @@ public function wikitextToHtml( string $text ): string {
5555
return '';
5656
}
5757

58+
return $this->parse( $text, $this->startTextParse() );
59+
}
60+
61+
/**
62+
* The HTML is not parsed as wikitext, while the wikitext around it can wrap it, as a tag opened before the HTML and
63+
* closed after it.
64+
*/
65+
public function wikitextAroundHtmlToHtml( string $wikitextBefore, string $html, string $wikitextAfter ): string {
5866
$textParser = $this->startTextParse();
67+
68+
return $this->parse( $wikitextBefore . $textParser->insertStripItem( $html ) . $wikitextAfter, $textParser );
69+
}
70+
71+
private function parse( string $text, Parser $textParser ): string {
5972
$html = $this->withWidgets(
6073
$textParser->recursiveTagParseFully( $this->handOverStripMarkers( $text, $textParser ) ),
6174
$textParser->getOutput()
Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
<?php
2+
3+
declare( strict_types = 1 );
4+
5+
namespace Maps\Tests\System;
6+
7+
use Maps\Tests\Util\PageCreator;
8+
use Maps\Tests\Util\TestFactory;
9+
use MediaWiki\Parser\ParserOptions;
10+
use PHPUnit\Framework\TestCase;
11+
12+
/**
13+
* Needs the database: the queries need a page in the Semantic MediaWiki store. They do not ask for its coordinates, so
14+
* they find the page but no locations other than those they give.
15+
*
16+
* @covers \Maps\Map\SemanticFormat\MapPrinter
17+
* @covers \Maps\Presentation\ElementJsonSerializer
18+
*/
19+
class MapQueryEscapingTest extends TestCase {
20+
21+
private const QUERY = '[[Coordinates::+]]';
22+
private const SCRIPT = '<script>alert(1)</script>';
23+
private const ESCAPED_SCRIPT = '&lt;script&gt;alert(1)&lt;/script&gt;';
24+
25+
public static function setUpBeforeClass(): void {
26+
parent::setUpBeforeClass();
27+
28+
if ( !defined( 'SMW_VERSION' ) ) {
29+
self::markTestSkipped( 'SMW is not available' );
30+
}
31+
32+
PageCreator::instance()->createPage(
33+
'Property:Coordinates',
34+
'[[Has type::Geographic coordinate|geographic coordinate]]'
35+
);
36+
37+
PageCreator::instance()->createPage(
38+
'MapQueryEscapingTest location',
39+
'[[Coordinates::52° 31\' 0", 13° 24\' 0"]]'
40+
);
41+
}
42+
43+
public function testPageShowsScriptInDefaultAsText(): void {
44+
$this->assertStringContainsString( self::ESCAPED_SCRIPT, $this->renderPage( 'format=leaflet|default=' . self::SCRIPT ) );
45+
}
46+
47+
private function renderPage( string $askParameters ): string {
48+
return TestFactory::newInstance()->renderPage(
49+
'{{#ask:' . self::QUERY . '|' . $askParameters . '}}',
50+
ParserOptions::newFromAnon()
51+
)->getContentHolderText();
52+
}
53+
54+
public function testSpecialAskShowsScriptInDefaultAsText(): void {
55+
$this->assertStringContainsString(
56+
self::ESCAPED_SCRIPT,
57+
$this->renderOnSpecialAsk( [ 'format=leaflet', 'default=' . self::SCRIPT ], SMW_OUTPUT_HTML )
58+
);
59+
}
60+
61+
/**
62+
* @param string[] $askParameters
63+
*/
64+
private function renderOnSpecialAsk( array $askParameters, int $outputMode ): string {
65+
return TestFactory::newInstance()->renderOnSpecialAsk( [ self::QUERY, ...$askParameters ], $outputMode );
66+
}
67+
68+
public function testPageRendersWikitextInDefault(): void {
69+
$this->assertStringContainsString( '<b>No locations</b>', $this->renderPage( "format=leaflet|default='''No locations'''" ) );
70+
}
71+
72+
public function testSpecialAskShowsWikitextInDefaultAsText(): void {
73+
$this->assertStringContainsString(
74+
'[[No locations]]',
75+
$this->renderOnSpecialAsk( [ 'format=leaflet', 'default=[[No locations]]' ], SMW_OUTPUT_HTML )
76+
);
77+
}
78+
79+
/**
80+
* Special:Ask serves the raw output of a query as HTML.
81+
*/
82+
public function testRawResultShowsScriptInDefaultAsText(): void {
83+
$this->assertStringContainsString(
84+
self::ESCAPED_SCRIPT,
85+
$this->renderOnSpecialAsk( [ 'format=leaflet', 'default=' . self::SCRIPT ], SMW_OUTPUT_RAW )
86+
);
87+
}
88+
89+
public function testSpecialAskShowsScriptInInlineLabelAsText(): void {
90+
$html = $this->renderOnSpecialAsk( [ 'format=googlemaps3', 'locations=1,1~Title~Text~~~' . self::SCRIPT ], SMW_OUTPUT_HTML );
91+
92+
$this->assertStringContainsString( self::ESCAPED_SCRIPT, $this->mapDataOf( $html )['locations'][0]['inlineLabel'] );
93+
}
94+
95+
private function mapDataOf( string $html ): array {
96+
$this->assertSame( 1, preg_match( '/data-mw-maps-mapdata="([^"]*)"/', $html, $matches ), 'The output holds no map' );
97+
98+
return json_decode( htmlspecialchars_decode( $matches[1] ), true );
99+
}
100+
101+
/**
102+
* @dataProvider introAndOutroProvider
103+
*/
104+
public function testPageShowsScriptInIntroOrOutroAsText( string $parameter ): void {
105+
$html = $this->renderPage( 'format=leaflet|locations=1,1|' . $parameter . '=' . self::SCRIPT );
106+
107+
$this->assertStringContainsString( self::ESCAPED_SCRIPT, $html );
108+
$this->assertStringNotContainsString( self::SCRIPT, $html );
109+
}
110+
111+
public static function introAndOutroProvider(): iterable {
112+
yield 'intro' => [ 'intro' ];
113+
yield 'outro' => [ 'outro' ];
114+
}
115+
116+
public function testPageRendersWikitextInIntro(): void {
117+
$this->assertStringContainsString(
118+
'<b>Some locations</b>',
119+
$this->renderPage( "format=leaflet|locations=1,1|intro='''Some locations'''" )
120+
);
121+
}
122+
123+
public function testPageWrapsTheMapInIntroAndOutro(): void {
124+
$this->assertMatchesRegularExpression(
125+
'/<div class="map-box">\s*<div id="map_leaflet_/',
126+
$this->renderPage( 'format=leaflet|locations=1,1|intro=<div class="map-box">|outro=</div>' )
127+
);
128+
}
129+
130+
}

‎tests/System/SemanticMapPageParserTest.php‎

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313
use MediaWiki\Parser\ParserOutput;
1414
use PHPUnit\Framework\TestCase;
1515
use SMW\ParserData;
16-
use SMWQueryProcessor;
1716

1817
/**
1918
* Needs the database: the queries need a page with coordinates in the Semantic MediaWiki store, and the maps use a
@@ -33,6 +32,7 @@ class SemanticMapPageParserTest extends TestCase {
3332
private const GEO_JSON_PAGE_NAME = 'SemanticMapPageParserTest';
3433
private const GEO_JSON_PAGE = 'GeoJson:' . self::GEO_JSON_PAGE_NAME;
3534
private const GEO_JSON_FEATURE = 'Feature of the SemanticMapPageParserTest GeoJSON page';
35+
private const LABEL_LINK_TARGET = 'SemanticMapPageParserTest label link target';
3636

3737
public static function setUpBeforeClass(): void {
3838
parent::setUpBeforeClass();
@@ -93,6 +93,14 @@ public function testLinkInStaticLocationTextIsRecordedOnThePage(): void {
9393
$this->assertContains( 'SemanticMapPageParserTest link target', RecordedLinks::linksOf( $output ) );
9494
}
9595

96+
public function testLinkInStaticLocationInlineLabelIsRecordedOnThePage(): void {
97+
$output = $this->render(
98+
'{{#ask:[[Coordinates::+]]|?Coordinates|format=map|locations=1,1~Title~Text~~~[[' . self::LABEL_LINK_TARGET . ']]}}'
99+
);
100+
101+
$this->assertContains( self::LABEL_LINK_TARGET, RecordedLinks::linksOf( $output ) );
102+
}
103+
96104
public function testLinkInShapeTextIsRecordedOnThePage(): void {
97105
$output = $this->render(
98106
'{{#ask:[[Coordinates::+]]|?Coordinates|format=map|lines=1,1:2,2~Line title~[[SemanticMapPageParserTest shape link target]]}}'
@@ -125,27 +133,26 @@ private function semanticPropertiesOf( ParserOutput $output ): array {
125133
);
126134
}
127135

136+
/**
137+
* Special:Ask renders text from the request, which must not become raw HTML, also where $wgRawHtml allows it in pages.
138+
*/
139+
public function testParserForSpecialAskAllowsNoRawHtml(): void {
140+
$this->assertFalse( MapsTestFactory::newTestInstance()->newRequestParser()->getOptions()->getAllowUnsafeRawHtml() );
141+
}
142+
128143
/**
129144
* Nothing caches a map on Special:Ask for other readers.
130145
*/
131146
public function testMapOnSpecialAskShowsWhatTheRequestingUserMayRead(): void {
132147
RefusingParserOptions::whileDefaultsRefuseAnonymousReaders( function (): void {
133148
$this->assertStringContainsString(
134149
self::GEO_JSON_FEATURE,
135-
$this->renderOnSpecialAsk( [ '[[Coordinates::+]]', '?Coordinates', 'format=leaflet', 'geojson=SemanticMapPageParserTest' ] )
150+
TestFactory::newInstance()->renderOnSpecialAsk(
151+
[ '[[Coordinates::+]]', '?Coordinates', 'format=leaflet', 'geojson=SemanticMapPageParserTest' ],
152+
SMW_OUTPUT_HTML
153+
)
136154
);
137155
} );
138156
}
139157

140-
private function renderOnSpecialAsk( array $queryParameters ): string {
141-
[ $query, $params ] = SMWQueryProcessor::getQueryAndParamsFromFunctionParams(
142-
$queryParameters,
143-
SMW_OUTPUT_HTML,
144-
SMWQueryProcessor::SPECIAL_PAGE,
145-
false
146-
);
147-
148-
return SMWQueryProcessor::getResultFromQuery( $query, $params, SMW_OUTPUT_HTML, SMWQueryProcessor::SPECIAL_PAGE );
149-
}
150-
151158
}

0 commit comments

Comments
 (0)