MediaWiki master
UploadVerification.php
Go to the documentation of this file.
1<?php
9
10namespace MediaWiki\Upload;
11
12use MediaWiki\Config\ConfigException;
13use MediaWiki\Config\ServiceOptions;
14use MediaWiki\MainConfigNames;
15use MediaWiki\Media\MediaHandler;
16use MediaWiki\Parser\Sanitizer;
17use MediaWiki\Shell\Shell;
18use Psr\Log\LoggerInterface;
19use Wikimedia\Mime\MimeAnalyzer;
20use Wikimedia\Mime\XmlTypeCheck;
21
35
36 private const SAFE_XML_ENCODINGS = [
37 'UTF-8',
38 'US-ASCII',
39 'ISO-8859-1',
40 'ISO-8859-2',
41 'UTF-16',
42 'UTF-32',
43 'WINDOWS-1250',
44 'WINDOWS-1251',
45 'WINDOWS-1252',
46 'WINDOWS-1253',
47 'WINDOWS-1254',
48 'WINDOWS-1255',
49 'WINDOWS-1256',
50 'WINDOWS-1257',
51 'WINDOWS-1258',
52 ];
53
54 public const CONSTRUCTOR_OPTIONS = [
61 ];
62
63 private SvgCssChecker $svgCssChecker;
64
65 public function __construct(
66 private ServiceOptions $config,
67 private MimeAnalyzer $mimeAnalyzer,
68 private LoggerInterface $logger,
69 ) {
70 $config->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
71 $this->svgCssChecker = new SvgCssChecker;
72 }
73
82 private function verifyMimeType( $mime ) {
83 $verifyMimeType = $this->config->get( MainConfigNames::VerifyMimeType );
84 if ( $verifyMimeType ) {
85 $mimeTypeExclusions = $this->config
87 if ( in_array( strtolower( $mime ), $mimeTypeExclusions, true ) ) {
88 return [ 'filetype-badmime', $mime ];
89 }
90 }
91
92 return true;
93 }
94
108 public function verifyFile( string $path, string $ext, array $fileProps ) {
109 $config = $this->config;
110 $verifyMimeType = $config->get( MainConfigNames::VerifyMimeType );
111 $disableUploadScriptChecks = $config->get( MainConfigNames::DisableUploadScriptChecks );
112 $status = $this->verifyPartialFile( $path, $ext, $fileProps );
113 if ( $status !== true ) {
114 return $status;
115 }
116
117 $mime = $fileProps['mime'];
118
119 if ( $verifyMimeType ) {
120 // XXX: Missing extension will be caught by validateName() via getTitle()
121 if ( $ext !== '' &&
122 !$this->verifyExtension( $mime, $ext )
123 ) {
124 return [ 'filetype-mime-mismatch', $ext, $mime ];
125 }
126 }
127
128 // Check for htmlish code and JavaScript
129 if ( !$disableUploadScriptChecks ) {
130 if ( $ext === 'svg' || $mime === 'image/svg+xml' ) {
131 $svgStatus = $this->detectScriptInSvg( $path, false );
132 if ( $svgStatus !== false ) {
133 return $svgStatus;
134 }
135 }
136 }
137
138 $handler = $mime !== null ? MediaHandler::getHandler( $mime ) : null;
139 if ( $handler ) {
140 $handlerStatus = $handler->verifyUpload( $path );
141 if ( !$handlerStatus->isOK() ) {
142 $errors = $handlerStatus->getErrorsArray();
143
144 return reset( $errors );
145 }
146 }
147
148 // TODO: Perhaps we should have a hook here akin to UploadVerifyFile
149 // except that it doesn't pass an UploadBase, and it would run
150 // even when someone is verifying a file not going through UploadBase.
151
152 $this->logger->debug( 'verifyFile: all clear; passing.' );
153
154 return true;
155 }
156
172 public function verifyPartialFile( string $path, string $ext, array $fileProps ) {
173 $config = $this->config;
174 $disableUploadScriptChecks = $config->get( MainConfigNames::DisableUploadScriptChecks );
175
176 // Check MIME type, if desired
177 $mime = $fileProps['file-mime'];
178 $status = $this->verifyMimeType( $mime );
179 $this->logger->debug( 'verifyMimeType: {mime} {status}',
180 [ 'mime' => $mime, 'status' => $status === true ? 'OK' : 'bad' ] );
181 if ( $status !== true ) {
182 return $status;
183 }
184
185 // Check for htmlish code and JavaScript
186 if ( !$disableUploadScriptChecks ) {
187 if ( $this->detectScript( $path, $mime, $ext ) ) {
188 return [ 'uploadscripted' ];
189 }
190 if ( $ext === 'svg' || $mime === 'image/svg+xml' ) {
191 $svgStatus = $this->detectScriptInSvg( $path, true );
192 if ( $svgStatus !== false ) {
193 return $svgStatus;
194 }
195 }
196 }
197
198 // Scan the uploaded file for viruses
199 $virus = $this->detectVirus( $path );
200 if ( $virus ) {
201 return [ 'uploadvirus', $virus ];
202 }
203
204 return true;
205 }
206
215 public function verifyExtension( $mime, $extension ) {
216 $magic = $this->mimeAnalyzer;
217 $logContext = [ 'mime' => $mime, 'extension' => $extension ];
218
219 if ( !$mime || $mime === 'unknown' || $mime === 'unknown/unknown' ) {
220 if ( !$magic->isRecognizableExtension( $extension ) ) {
221 $this->logger->debug(
222 'verifyExtension: passing file with unknown detected MIME type; ' .
223 "unrecognized extension '{extension}', can't verify",
224 $logContext
225 );
226
227 return true;
228 }
229
230 $this->logger->debug(
231 'verifyExtension: rejecting file with unknown detected MIME type; ' .
232 'recognized extension "{extension}", so probably invalid file',
233 $logContext
234 );
235 return false;
236 }
237
238 $match = $magic->isMatchingExtension( $extension, $mime );
239
240 if ( $match === null ) {
241 if ( $magic->getMimeTypesFromExtension( $extension ) !== [] ) {
242 $this->logger->debug(
243 'verifyExtension: No extension known for {mime}, but we ' .
244 'know a MIME for {extension}',
245 $logContext
246 );
247 return false;
248 }
249
250 $this->logger->debug(
251 'verifyExtension: no file extension known for MIME type {mime}, passing file',
252 $logContext
253 );
254 return true;
255 }
256
257 if ( $match ) {
258 $this->logger->debug(
259 'verifyExtension: MIME type {mime} matches extension {extension}, passing file',
260 $logContext
261 );
262 return true;
263 }
264
265 $this->logger->debug(
266 'verifyExtension: MIME type {mime} mismatches file extension {extension}, ' .
267 'rejecting file',
268 $logContext
269 );
270
271 return false;
272 }
273
289 public function detectScript( $file, $mime, $extension ) {
290 // Ugly hack: for text files, always look at the entire file.
291 // For binary field, just check the first K.
292
293 if ( str_starts_with( $mime ?? '', 'text/' ) ) {
294 $chunk = file_get_contents( $file );
295 } else {
296 $fp = fopen( $file, 'rb' );
297 if ( !$fp ) {
298 return false;
299 }
300 $chunk = fread( $fp, 1024 );
301 fclose( $fp );
302 }
303
304 $chunk = strtolower( $chunk );
305
306 if ( !$chunk ) {
307 return false;
308 }
309
310 // Decode from UTF-16 if needed (could be used for obfuscation).
311 if ( str_starts_with( $chunk, "\xfe\xff" ) ) {
312 $enc = 'UTF-16BE';
313 } elseif ( str_starts_with( $chunk, "\xff\xfe" ) ) {
314 $enc = 'UTF-16LE';
315 } else {
316 $enc = null;
317 }
318
319 if ( $enc !== null ) {
320 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
321 $chunk = @iconv( $enc, "ASCII//IGNORE", $chunk );
322 }
323
324 $chunk = trim( $chunk );
325
326 // Check for HTML doctype
327 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
328 $this->logger->debug( 'detectScript: found doctype html' );
329 return true;
330 }
331
332 // Some browsers will interpret obscure xml encodings as UTF-8, while
333 // PHP/expat will interpret the given encoding in the xml declaration (T49304)
334 if ( $extension === 'svg' || str_starts_with( $mime ?? '', 'image/svg' ) ) {
335 if ( $this->checkXMLEncodingMismatch( $file ) ) {
336 $this->logger->debug( 'detectScript: found SVG encoding mismatch' );
337 return true;
338 }
339 }
340
341 // Quick check for HTML heuristics in old IE and Safari.
342 //
343 // Check for `<script` and such still to forbid script tags and embedded HTML in SVG:
344 $tags = [
345 '<body',
346 '<head',
347 '<html', // also in safari
348 '<script', // also in safari
349 ];
350
351 foreach ( $tags as $tag ) {
352 if ( str_contains( $chunk, $tag ) ) {
353 $this->logger->debug( 'detectScript: found HTML tag "{tag}"', [ 'tag' => $tag ] );
354 return true;
355 }
356 }
357
358 // Look for JavaScript
359
360 // Resolve entity-refs to look at attributes.
361 $chunk = Sanitizer::decodeCharReferences( $chunk );
362
363 // Look for script-types
364 if ( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!im', $chunk ) ) {
365 $this->logger->debug( 'detectScript: found script types' );
366 return true;
367 }
368
369 // Look for HTML-style script-URLs
370 if ( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!im', $chunk ) ) {
371 $this->logger->debug( 'detectScript: found HTML-style script URLs' );
372 return true;
373 }
374
375 // Look for CSS-style script-URLs
376 if ( preg_match( '!url\s*\‍(\s*[\'"]?\s*(?:ecma|java)script:!im', $chunk ) ) {
377 $this->logger->debug( 'detectScript: found CSS-style script URLs' );
378 return true;
379 }
380
381 $this->logger->debug( 'detectScript: no scripts found' );
382 return false;
383 }
384
392 private function checkXMLEncodingMismatch( $file ) {
393 // https://mimesniff.spec.whatwg.org/#resource-header says browsers
394 // should read the first 1445 bytes. Do 4096 bytes for good measure.
395 // XML Spec says XML declaration if present must be first thing in file
396 // other than BOM
397 $contents = file_get_contents( $file, false, null, 0, 4096 );
398 $encodingRegex = '!encoding[ \t\n\r]*=[ \t\n\r]*[\'"](.*?)[\'"]!si';
399
400 if ( preg_match( "!<\?xml\b(.*?)\?>!si", $contents, $matches ) ) {
401 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
402 && !in_array( strtoupper( $encMatch[1] ), self::SAFE_XML_ENCODINGS )
403 ) {
404 $this->logger->debug(
405 'checkXMLEncodingMismatch: Found unsafe XML encoding "{encoding}"',
406 [ 'encoding' => $encMatch[1] ]
407 );
408 return true;
409 }
410 } elseif ( preg_match( "!<\?xml\b!i", $contents ) ) {
411 // Start of XML declaration without an end in the first 4096 bytes
412 // bytes. There shouldn't be a legitimate reason for this to happen.
413 $this->logger->debug( 'checkXMLEncodingMismatch: Unmatched XML declaration start' );
414 return true;
415 } elseif ( str_starts_with( $contents, "\x4C\x6F\xA7\x94" ) ) {
416 // EBCDIC encoded XML
417 $this->logger->debug( 'checkXMLEncodingMismatch: EBCDIC Encoded XML' );
418 return true;
419 }
420
421 // It's possible the file is encoded with multibyte encoding, so re-encode attempt to
422 // detect the encoding in case it specifies an encoding not allowed in
423 // self::SAFE_XML_ENCODINGS
424 $attemptEncodings = [ 'UTF-16', 'UTF-16BE', 'UTF-32', 'UTF-32BE' ];
425 foreach ( $attemptEncodings as $encoding ) {
426 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
427 $str = @iconv( $encoding, 'UTF-8', $contents );
428 if ( $str != '' && preg_match( "!<\?xml\b(.*?)\?>!si", $str, $matches ) ) {
429 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
430 && !in_array( strtoupper( $encMatch[1] ), self::SAFE_XML_ENCODINGS )
431 ) {
432 $this->logger->debug(
433 'checkXMLEncodingMismatch: Found unsafe XML encoding "{encoding}"',
434 [ 'encoding' => $encMatch[1] ]
435 );
436 return true;
437 }
438 } elseif ( $str != '' && preg_match( "!<\?xml\b!i", $str ) ) {
439 // Start of XML declaration without an end in the first 4096 bytes
440 // bytes. There shouldn't be a legitimate reason for this to happen.
441 $this->logger->debug( 'checkXMLEncodingMismatch: Unmatched XML declaration start' );
442
443 return true;
444 }
445 }
446
447 return false;
448 }
449
458 private function detectScriptInSvg( $filename, $partial ) {
459 $check = new XmlTypeCheck(
460 $filename,
461 $this->checkSvgScriptCallback( ... ),
462 true,
463 [
464 'processing_instruction_handler' => $this->checkSvgPICallback( ... ),
465 'external_dtd_handler' => $this->checkSvgExternalDTD( ... ),
466 ]
467 );
468 if ( $check->wellFormed !== true ) {
469 // Invalid XML (T60553)
470 // But only when non-partial (T67724)
471 return $partial ? false : [ 'uploadinvalidxml' ];
472 }
473
474 if ( $check->filterMatch ) {
475 return $check->filterMatchType;
476 }
477
478 return false;
479 }
480
487 private function checkSvgPICallback( $target ) {
488 // Don't allow external stylesheets (T59550)
489 if ( preg_match( '/xml-stylesheet/i', $target ) ) {
490 return [ 'upload-scripted-pi-callback' ];
491 }
492
493 return false;
494 }
495
508 private function checkSvgExternalDTD( $type, $publicId, $systemId ) {
509 // This doesn't include the XHTML+MathML+SVG doctype since we don't
510 // allow XHTML anyway.
511 static $allowedDTDs = [
512 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd',
513 'http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd',
514 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-basic.dtd',
515 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd',
516 // https://phabricator.wikimedia.org/T168856
517 'http://www.w3.org/TR/2001/PR-SVG-20010719/DTD/svg10.dtd',
518 ];
519 if ( $type !== 'PUBLIC'
520 || !in_array( $systemId, $allowedDTDs )
521 || !str_starts_with( $publicId, "-//W3C//" )
522 ) {
523 return [ 'upload-scripted-dtd' ];
524 }
525 return false;
526 }
527
537 private function checkSvgScriptCallback( $element, $attribs, $data = null ) {
538 [ $namespace, $strippedElement ] = self::splitXmlNamespace( $element );
539
540 $logContext = [
541 'element' => $element,
542 'namespace' => $namespace,
543 'localPart' => $strippedElement
544 ];
545
546 // We specifically don't include:
547 // http://www.w3.org/1999/xhtml (T62771)
548 static $validNamespaces = [
549 '',
550 'adobe:ns:meta/',
551 'http://c2pa.org/',
552 'http://c2pa.org/manifest',
553 'http://cipa.jp/exif/1.0/',
554 'http://creativecommons.org/ns#',
555 'http://developer.sonyericsson.com/cell/1.0/',
556 'http://inkscape.sourceforge.net/dtd/sodipodi-0.dtd',
557 'http://iptc.org/std/iptc4xmpcore/1.0/xmlns/',
558 'http://iptc.org/std/iptc4xmpext/2008-02-29/',
559 'http://leica-camera.com/digital-shift-assistant/1.0/',
560 'http://ns.acdsee.com/iptc/1.0/',
561 'http://ns.acdsee.com/regions/',
562 'http://ns.adobe.com/adobeillustrator/10.0/',
563 'http://ns.adobe.com/adobesvgviewerextensions/3.0/',
564 'http://ns.adobe.com/album/1.0/',
565 'http://ns.adobe.com/camera-raw-defaults/1.0/',
566 'http://ns.adobe.com/camera-raw-embedded-lens-profile/1.0/',
567 'http://ns.adobe.com/camera-raw-saved-settings/1.0/',
568 'http://ns.adobe.com/camera-raw-settings/1.0/',
569 'http://ns.adobe.com/creatoratom/1.0/',
570 'http://ns.adobe.com/dicom/',
571 'http://ns.adobe.com/exif/1.0/',
572 'http://ns.adobe.com/exif/1.0/aux/',
573 'http://ns.adobe.com/extensibility/1.0/',
574 'http://ns.adobe.com/flows/1.0/',
575 'http://ns.adobe.com/hdr-gain-map/1.0/',
576 'http://ns.adobe.com/hdr-metadata/1.0/',
577 'http://ns.adobe.com/ix/1.0/',
578 'http://ns.adobe.com/lightroom/1.0/',
579 'http://ns.adobe.com/illustrator/1.0/',
580 'http://ns.adobe.com/imagereplacement/1.0/',
581 'http://ns.adobe.com/pdf/1.3/',
582 'http://ns.adobe.com/pdfx/1.3/',
583 'http://ns.adobe.com/photoshop/1.0/',
584 'http://ns.adobe.com/photoshop/1.0/camera-profile',
585 'http://ns.adobe.com/photoshop/1.0/panorama-profile',
586 'http://ns.adobe.com/raw/1.0/',
587 'http://ns.adobe.com/swf/1.0/',
588 'http://ns.adobe.com/saveforweb/1.0/',
589 'http://ns.adobe.com/tiff/1.0/',
590 'http://ns.adobe.com/variables/1.0/',
591 'http://ns.adobe.com/xap/1.0/',
592 'http://ns.adobe.com/xap/1.0/bj/',
593 'http://ns.adobe.com/xap/1.0/g/',
594 'http://ns.adobe.com/xap/1.0/g/img/',
595 'http://ns.adobe.com/xap/1.0/mm/',
596 'http://ns.adobe.com/xap/1.0/plus/',
597 'http://ns.adobe.com/xap/1.0/rights/',
598 'http://ns.adobe.com/xap/1.0/stype/dimensions#',
599 'http://ns.adobe.com/xap/1.0/stype/font#',
600 'http://ns.adobe.com/xap/1.0/stype/manifestitem#',
601 'http://ns.adobe.com/xap/1.0/stype/resourceevent#',
602 'http://ns.adobe.com/xap/1.0/stype/resourceref#',
603 'http://ns.adobe.com/xap/1.0/stype/version#',
604 'http://ns.adobe.com/xap/1.0/t/pg/',
605 'http://ns.adobe.com/xmp/1.0/dynamicmedia/',
606 'http://ns.adobe.com/xmp/identifier/qual/1.0/',
607 'http://ns.adobe.com/xmp/note/',
608 'http://ns.adobe.com/xmp/stype/area#',
609 'http://ns.apple.com/adjustment-settings/1.0/',
610 'http://ns.apple.com/faceinfo/1.0/',
611 'http://ns.apple.com/hdrgainmap/1.0/',
612 'http://ns.apple.com/pixeldatainfo/1.0/',
613 'http://ns.exiftool.org/1.0/',
614 'http://ns.extensis.com/extensis/1.0/',
615 'http://ns.fastpictureviewer.com/fpv/1.0/',
616 'http://ns.google.com/photos/1.0/audio/',
617 'http://ns.google.com/photos/1.0/camera/',
618 'http://ns.google.com/photos/1.0/container/',
619 'http://ns.google.com/photos/1.0/creations/',
620 'http://ns.google.com/photos/1.0/depthmap/',
621 'http://ns.google.com/photos/1.0/focus/',
622 'http://ns.google.com/photos/1.0/image/',
623 'http://ns.google.com/photos/1.0/panorama/',
624 'http://ns.google.com/photos/dd/1.0/profile/',
625 'http://ns.google.com/videos/1.0/spherical/',
626 'http://ns.idimager.com/ics/1.0/',
627 'http://ns.iview-multimedia.com/mediapro/1.0/',
628 'http://ns.leiainc.com/photos/1.0/image/',
629 'http://ns.microsoft.com/expressionmedia/1.0/',
630 'http://ns.microsoft.com/photo/1.0',
631 'http://ns.microsoft.com/photo/1.1',
632 'http://ns.microsoft.com/photo/1.2/',
633 'http://ns.microsoft.com/photo/1.2/t/region#',
634 'http://ns.microsoft.com/photo/1.2/t/regioninfo#',
635 'http://ns.nikon.com/asteroid/1.0/',
636 'http://ns.nikon.com/nine/1.0/',
637 'http://ns.nikon.com/sdc/1.0/',
638 'http://ns.optimasc.com/dex/1.0/',
639 'http://ns.seal/2024/1.0/',
640 'http://ns.useplus.org/ldf/xmp/1.0/',
641 'http://prismstandard.org/namespaces/basic/2.0/',
642 'http://prismstandard.org/namespaces/pmi/2.2/',
643 'http://prismstandard.org/namespaces/prismusagerights/2.1/',
644 'http://prismstandard.org/namespaces/prl/2.1/',
645 'http://prismstandard.org/namespaces/prm/3.0/',
646 'http://purl.org/dc/elements/1.1/',
647 'http://purl.org/dc/elements/1.1',
648 'http://rs.tdwg.org/dwc/index.htm',
649 'http://schemas.microsoft.com/visio/2003/svgextensions/',
650 'http://sodipodi.sourceforge.net/dtd/sodipodi-0.dtd',
651 'http://taptrix.com/inkpad/svg_extensions',
652 'http://www.digikam.org/ns/1.0/',
653 'http://www.dji.com/drone-dji/1.0/',
654 'http://www.metadataworkinggroup.com/schemas/collections/',
655 'http://www.metadataworkinggroup.com/schemas/keywords/',
656 'http://www.metadataworkinggroup.com/schemas/regions/',
657 'http://web.resource.org/cc/',
658 'http://www.freesoftware.fsf.org/bkchem/cdml',
659 'http://www.inkscape.org/namespaces/inkscape',
660 'http://www.opengis.net/gml',
661 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
662 'http://www.w3.org/2000/01/rdf-schema#',
663 'http://www.w3.org/2000/svg',
664 'http://www.w3.org/2000/02/svg/testsuite/description/', // T278044
665 'http://www.w3.org/tr/rec-rdf-syntax/',
666 'http://xmp.gettyimages.com/gift/1.0/',
667 ];
668
669 // Inkscape mangles namespace definitions created by Adobe Illustrator.
670 // This is nasty but harmless. (T144827)
671 $isBuggyInkscape = preg_match( '/^&(#38;)*ns_[a-z_]+;$/', $namespace );
672
673 if ( !( $isBuggyInkscape || in_array( $namespace, $validNamespaces ) ) ) {
674 $this->logger->debug(
675 'detectScriptInSvg: Non-SVG namespace "{namespace}" in uploaded file.',
676 $logContext
677 );
678 return [ 'uploadscriptednamespace', $namespace ];
679 }
680
681 // Check for elements that can contain JavaScript
682 if ( $strippedElement === 'script' ) {
683 $this->logger->debug(
684 'detectScriptInSvg: Found script element "{element}" in uploaded file.',
685 $logContext
686 );
687 return [ 'uploaded-script-svg', $strippedElement ];
688 }
689
690 // e.g. <handler xmlns:ev="http://www.w3.org/2001/xml-events" ev:event="load"
691 // >alert(1)</handler>
692 if ( $strippedElement === 'handler' ) {
693 $this->logger->debug(
694 'detectScriptInSvg: Found scriptable element "{element}" in uploaded file.',
695 $logContext
696 );
697 return [ 'uploaded-script-svg', $strippedElement ];
698 }
699
700 // SVG reported in Feb '12 that used xml:stylesheet to generate JavaScript block
701 if ( $strippedElement === 'stylesheet' ) {
702 $this->logger->debug(
703 'detectScriptInSvg: Found scriptable element "{element}" in uploaded file.',
704 $logContext
705 );
706 return [ 'uploaded-script-svg', $strippedElement ];
707 }
708
709 // Block iframes, in case they pass the namespace check
710 if ( $strippedElement === 'iframe' ) {
711 $this->logger->debug( "detectScriptInSvg: iframe in uploaded file.", $logContext );
712 return [ 'uploaded-script-svg', $strippedElement ];
713 }
714
715 // Check <style> CSS
716 if ( $strippedElement === 'style' ) {
717 $cssCheck = $this->svgCssChecker->checkStyleTag( $data );
718 if ( $cssCheck !== true ) {
719 $this->logger->debug(
720 "detectScriptInSvg: hostile CSS in style element. {tag}",
721 [ 'tag' => $cssCheck[0] ]
722 );
723 return [ 'uploaded-hostile-svg', $cssCheck[0], $cssCheck[1], $cssCheck[2] ];
724 }
725 }
726
727 static $cssAttrs = [ 'font', 'clip-path', 'fill', 'filter', 'marker',
728 'marker-end', 'marker-mid', 'marker-start', 'mask', 'stroke', 'cursor' ];
729
730 foreach ( $attribs as $attrib => $value ) {
731 // If attributeNamespace is '', it is relative to its element's namespace
732 [ $attributeNamespace, $stripped ] = self::splitXmlNamespace( $attrib );
733 $value = strtolower( $value );
734 $attribLogContext = [ 'attrib' => $attrib, 'value' => $value ] + $logContext;
735
736 if ( !(
737 // Inkscape element's have valid attribs that start with on
738 // and are safe. Fail all others. We are assuming here that
739 // the SVG will be interpreted under XML serialization. This
740 // is not safe for SVGs embedded directly in HTML.
741 $namespace === 'http://www.inkscape.org/namespaces/inkscape' &&
742 $attributeNamespace === ''
743 ) && str_starts_with( $stripped, 'on' )
744 ) {
745 $this->logger->debug(
746 'detectScriptInSvg: Found event-handler attribute ' .
747 '{attrib}="{value}" in uploaded file.',
748 $attribLogContext
749 );
750 return [ 'uploaded-event-handler-on-svg', $attrib, $value ];
751 }
752
753 // Do not allow relative links, or unsafe url schemas.
754 // For <a> tags, only data:, http: and https: and same-document
755 // fragment links are allowed.
756 // For all other tags, only 'data:' and fragments (#) are allowed.
757 if (
758 $stripped === 'href'
759 && $value !== ''
760 && !str_starts_with( $value, 'data:' )
761 && !str_starts_with( $value, '#' )
762 && !( $strippedElement === 'a' && preg_match( '!^https?://!i', $value ) )
763 ) {
764 $this->logger->debug(
765 'detectScriptInSvg: Found href attribute <{localPart} {attrib}="{value}"> ' .
766 'in uploaded file.',
767 $attribLogContext
768 );
769 return [ 'uploaded-href-attribute-svg', $strippedElement, $attrib, $value ];
770 }
771
772 // Only allow 'data:\' targets that should be safe.
773 // This prevents vectors like image/svg, text/xml, application/xml,
774 // and text/html, which can contain scripts
775 if ( $stripped === 'href' && strncasecmp( 'data:', $value, 5 ) === 0 ) {
776 // See RFC 2397 section 3
777 $dataUriRegex = <<<'REGEX'
778!^data: \s*
779image / (gif|jpeg|jpg|a?png|webp|avif)
780# mediatype parameters (once-only subpattern)
781(?>
782 ;
783 # Parameter name
784 [a-zA-Z0-9\!#$&'*+.^_`{|}~-]+
785 =
786 # Value
787 (?>
788 # token
789 [a-zA-Z0-9\!#$&'*+.^_`{|}~-]+ |
790 # quoted-string (discouraged by RFC 2045)
791 "(?>
792 [\0-\x0c\x0e-\x21\x23-\x5b\x5d-\x7f]+ |
793 \\[\0-\x7f]
794 )*"
795 )
796)*
797# data URI parameter (non-capturing)
798(?: ; base64 )?
799!ix
800REGEX;
801
802 if ( !preg_match( $dataUriRegex, $value ) ) {
803 $this->logger->debug(
804 'detectScriptInSvg: Found href with data URI with MIME type that is not ' .
805 'allowed: <{localPart} {attrib}="{value}"> in uploaded file.',
806 $attribLogContext
807 );
808 return [ 'uploaded-href-unsafe-target-svg', $strippedElement, $attrib, $value ];
809 }
810 }
811
812 // Change href with animate from (http://html5sec.org/#137).
813 if ( $stripped === 'attributename'
814 && $strippedElement === 'animate'
815 && $this->stripXmlNamespace( $value ) === 'href'
816 ) {
817 $this->logger->debug(
818 'detectScriptInSvg: Found animate that might be changing href using "from": ' .
819 '<{localPart} {attrib}="{value}"> in uploaded file.',
820 $attribLogContext
821 );
822 return [ 'uploaded-animate-svg', $strippedElement, $attrib, $value ];
823 }
824
825 // Use set/animate to add event-handler attribute to parent.
826 if ( ( $strippedElement === 'set' || $strippedElement === 'animate' )
827 && $stripped === 'attributename'
828 && str_starts_with( $value, 'on' )
829 ) {
830 $this->logger->debug(
831 'detectScriptInSvg: Found SVG setting event-handler attribute with ' .
832 '<{localPart} {attrib}="{value}"> in uploaded file.',
833 $attribLogContext
834 );
835 return [ 'uploaded-setting-event-handler-svg',
836 $strippedElement, $stripped, $value ];
837 }
838
839 // Use set to add href attribute to parent element.
840 if ( $strippedElement === 'set'
841 && $stripped === 'attributename'
842 && str_contains( $value, 'href' )
843 ) {
844 $this->logger->debug(
845 'detectScriptInSvg: Found SVG setting href attribute "{value}" ' .
846 'in uploaded file.',
847 $attribLogContext
848 );
849 return [ 'uploaded-setting-href-svg' ];
850 }
851
852 // Use set to add a remote / data / script target to an element.
853 if ( $strippedElement === 'set'
854 && $stripped === 'to'
855 && preg_match( '!(http|https|data|script):!im', $value )
856 ) {
857 $this->logger->debug(
858 'detectScriptInSvg: Found SVG setting attribute to "{value}" in uploaded file.',
859 $attribLogContext
860 );
861 return [ 'uploaded-wrong-setting-svg', $value ];
862 }
863
864 // Use handler attribute with remote / data / script.
865 if ( $stripped === 'handler'
866 && preg_match( '!(http|https|data|script):!im', $value )
867 ) {
868 $this->logger->debug(
869 'detectScriptInSvg: Found SVG setting handler with remote/data/script ' .
870 '{attrib}="value" in uploaded file.',
871 $attribLogContext
872 );
873 return [ 'uploaded-setting-handler-svg', $attrib, $value ];
874 }
875
876 // use CSS styles to bring in remote code.
877 if ( $stripped === 'style'
878 && $this->svgCssChecker->checkStyleAttribute( $value ) !== true
879 ) {
880 $this->logger->debug(
881 'detectScriptInSvg: Found SVG setting a style with remote url ' .
882 '{attrib}="{value}" in uploaded file.',
883 $attribLogContext
884 );
885 return [ 'uploaded-remote-url-svg', $attrib, $value ];
886 }
887
888 // Several attributes can include CSS. CSS character escaping isn't allowed.
889 if ( in_array( $stripped, $cssAttrs, true )
890 && $this->svgCssChecker->checkPresentationalAttribute( $value ) !== true
891 ) {
892 $this->logger->debug(
893 'detectScriptInSvg: Found SVG setting a style with ' .
894 '{attrib}="{value}" in uploaded file.',
895 $attribLogContext
896 );
897 return [ 'uploaded-remote-url-svg', $attrib, $value ];
898 }
899
900 // Image filters can pull in URL, which could be SVG that executes scripts.
901 // Only allow url( "#foo" ).
902 // Do not allow url( http://example.com )
903 // TODO: It seems like the line above already does this check.
904 if ( $strippedElement === 'image'
905 && $stripped === 'filter'
906 && preg_match( '!url\s*\‍(\s*["\']?[^#]!im', $value )
907 ) {
908 $this->logger->debug(
909 'detectScriptInSvg: Found image filter with URL: ' .
910 '<{localPart} {attrib}="{value}"> in uploaded file.',
911 $attribLogContext
912 );
913 return [ 'uploaded-image-filter-svg', $strippedElement, $stripped, $value ];
914 }
915 }
916
917 return false; // No scripts detected
918 }
919
926 private function splitXmlNamespace( $element ) {
927 // 'http://www.w3.org/2000/svg:script' -> [ 'http://www.w3.org/2000/svg', 'script' ]
928 $parts = explode( ':', strtolower( $element ) );
929 $name = array_pop( $parts );
930 $ns = implode( ':', $parts );
931
932 return [ $ns, $name ];
933 }
934
939 private function stripXmlNamespace( $element ) {
940 // 'http://www.w3.org/2000/svg:script' -> 'script'
941 return self::splitXmlNamespace( $element )[1];
942 }
943
956 public function detectVirus( $file ) {
957 $mainConfig = $this->config;
958 $antivirus = $mainConfig->get( MainConfigNames::Antivirus );
959 $antivirusSetup = $mainConfig->get( MainConfigNames::AntivirusSetup );
960 $antivirusRequired = $mainConfig->get( MainConfigNames::AntivirusRequired );
961 if ( !$antivirus ) {
962 $this->logger->debug( 'detectVirus: virus scanner disabled' );
963 return null;
964 }
965
966 if ( !( $antivirusSetup[$antivirus] ?? false ) ) {
967 throw new ConfigException( "Unknown virus scanner: $antivirus" );
968 }
969
970 // Look up scanner configuration
971 $command = $antivirusSetup[$antivirus]['command'];
972 $exitCodeMap = $antivirusSetup[$antivirus]['codemap'];
973 $msgPattern = $antivirusSetup[$antivirus]['messagepattern'] ?? null;
974
975 if ( !str_contains( $command, "%f" ) ) {
976 // Simple pattern: append file to scan
977 $command .= " " . Shell::escape( $file );
978 } else {
979 // Complex pattern: replace "%f" with file to scan
980 $command = str_replace( "%f", Shell::escape( $file ), $command );
981 }
982
983 $this->logger->debug( 'detectVirus: running virus scan: {command}',
984 [ 'command' => $command ] );
985
986 // Execute virus scanner
987
988 $output = Shell::command()->unsafeCommand( $command )->includeStderr()->execute();
989 $exitCode = $output->getExitCode();
990
991 // map exit code to AV_xxx constants.
992 $mappedCode = $exitCode;
993 if ( $exitCodeMap ) {
994 if ( isset( $exitCodeMap[$exitCode] ) ) {
995 $mappedCode = $exitCodeMap[$exitCode];
996 } elseif ( isset( $exitCodeMap["*"] ) ) {
997 $mappedCode = $exitCodeMap["*"];
998 }
999 }
1000
1001 // NB: AV_NO_VIRUS is 0, but AV_SCAN_FAILED is false,
1002 // so we need the strict equalities === and thus can't use a switch here
1003 if ( $mappedCode === AV_SCAN_FAILED ) {
1004 // Scan failed (code was mapped to false by $exitCodeMap)
1005 $this->logger->debug( 'detectVirus: failed to scan {file} (code {exitCode}).',
1006 [ 'file' => $file, 'exitCode' => $exitCode ] );
1007
1008 $output = $antivirusRequired
1009 ? wfMessage( 'virus-scanfailed', [ $exitCode ] )->text()
1010 : null;
1011 } elseif ( $mappedCode === AV_SCAN_ABORTED ) {
1012 // Scan failed because file type is unknown (probably immune)
1013 $this->logger->debug( 'detectVirus: unsupported file type {file} (code {exitCode}).',
1014 [ 'file' => $file, 'exitCode' => $exitCode ] );
1015 $output = null;
1016 } elseif ( $mappedCode === AV_NO_VIRUS ) {
1017 // No virus found
1018 $this->logger->debug( 'detectVirus: file passed virus scan.' );
1019 $output = false;
1020 } else {
1021 $output = trim( $output->getStdout() );
1022
1023 if ( !$output ) {
1024 $output = true; // If there's no output, return true
1025 } elseif ( $msgPattern ) {
1026 $groups = [];
1027 if ( preg_match( $msgPattern, $output, $groups ) && $groups[1] ) {
1028 $output = $groups[1];
1029 }
1030 }
1031
1032 $this->logger->debug( 'detectVirus: FOUND VIRUS! scanner feedback: {output}',
1033 [ 'output' => $output ] );
1034 }
1035
1036 return $output;
1037 }
1038}
const AV_SCAN_FAILED
Definition Defines.php:86
const AV_SCAN_ABORTED
Definition Defines.php:85
const AV_NO_VIRUS
Definition Defines.php:83
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Exceptions for config failures.
A class for passing options to services.
assertRequiredOptions(array $expectedKeys)
Assert that the list of options provided in this instance exactly match $expectedKeys,...
const MimeTypeExclusions
Name constant for the MimeTypeExclusions setting, for use with Config\get().
const AntivirusSetup
Name constant for the AntivirusSetup setting, for use with Config\get().
const VerifyMimeType
Name constant for the VerifyMimeType setting, for use with Config\get().
const DisableUploadScriptChecks
Name constant for the DisableUploadScriptChecks setting, for use with Config\get().
const Antivirus
Name constant for the Antivirus setting, for use with Config\get().
const AntivirusRequired
Name constant for the AntivirusRequired setting, for use with Config\get().
Ensure SVG files cannot load external resources via URLs in CSS.
Service to verify file uploads are safe.
detectVirus( $file)
Generic wrapper function for a virus scanner program.
verifyFile(string $path, string $ext, array $fileProps)
Verifies that the upload file is safe.
verifyExtension( $mime, $extension)
Checks if the MIME type of the uploaded file matches the file extension.
verifyPartialFile(string $path, string $ext, array $fileProps)
A verification routine suitable for partial files.
__construct(private ServiceOptions $config, private MimeAnalyzer $mimeAnalyzer, private LoggerInterface $logger,)
detectScript( $file, $mime, $extension)
Heuristic for detecting files that could contain JavaScript instructions or things that may look like...