diff --git a/composer.json b/composer.json index 1ede6393..1fa9d30b 100644 --- a/composer.json +++ b/composer.json @@ -39,6 +39,7 @@ "ext-date": "*", "ext-dom": "*", "ext-libxml": "*", + "ext-mbstring": "*", "ext-pcre": "*", "ext-spl": "*", "ext-uri": "*", @@ -48,8 +49,6 @@ "simplesamlphp/composer-xmlprovider-installer": "~1.3" }, "require-dev": { - "ext-mbstring": "*", - "phpunit/phpunit": "^13.3", "simplesamlphp/simplesamlphp-test-framework": "dev-release-2.x" }, diff --git a/src/XML/DOMDocumentFactory.php b/src/XML/DOMDocumentFactory.php index 94da6ff5..dbf6be87 100644 --- a/src/XML/DOMDocumentFactory.php +++ b/src/XML/DOMDocumentFactory.php @@ -13,9 +13,14 @@ use SimpleSAML\XPath\XPath; use function file_get_contents; +use function mb_convert_encoding; +use function preg_match; use function restore_error_handler; use function set_error_handler; use function sprintf; +use function str_starts_with; +use function strlen; +use function substr; /** * @package simplesamlphp/xml-common @@ -31,6 +36,10 @@ final class DOMDocumentFactory */ public const int DEFAULT_OPTIONS_BASE = \LIBXML_COMPACT | \LIBXML_NONET | \LIBXML_NSCLEAN; + /** + */ + public const int DOCTYPE_CHECK_PREFIX_LENGTH = 1024; + /** * @return non-negative-int @@ -69,16 +78,19 @@ public static function fromString( ?int $options = null, ): Dom\XMLDocument { Assert::notWhitespaceOnly($xml); - Assert::notRegex( - $xml, - '/<(\s*)!(\s*)DOCTYPE/', - 'Dangerous XML detected, DOCTYPE nodes are not allowed in the XML body', - RuntimeException::class, - ); + self::assertNoDoctype($xml); $options = $options ?? self::getDefaultOptions(); + $prefix = substr($xml, 0, self::DOCTYPE_CHECK_PREFIX_LENGTH); + $family = self::detectXmlEncodingFamily($prefix); - $domDocument = self::create(); + if ($family !== 'utf-8' && $family !== 'ascii') { + $converted = @mb_convert_encoding($xml, 'UTF-8', $family); + if ($converted === false) { + throw new RuntimeException('Unable to convert XML encoding to UTF-8'); + } + $xml = $converted; + } // Convert parser warnings/notices into DOMException to avoid PHP warnings leaking into test output set_error_handler( @@ -91,7 +103,9 @@ static function (int $severity, string $message): never { ); try { - $loaded = $domDocument->createFromString($xml, $options, $domDocument->characterSet); + // Now always parse as UTF-8 + $domDocument = self::create(); + $loaded = $domDocument->createFromString($xml, $options, 'UTF-8'); } finally { restore_error_handler(); } @@ -250,4 +264,99 @@ public static function lookupNamespaceURI(Dom\Element $elt, ?string $prefix): ?s return null; } + + + /** + * @throws \SimpleSAML\XML\Exception\RuntimeException + */ + public static function assertNoDoctype(string $xml): void + { + // Fast path – UTF-8 / ASCII-compatible + if (preg_match('/<\s*!\s*DOCTYPE\b/i', $xml) === 1) { + throw new RuntimeException( + 'Dangerous XML detected, DOCTYPE nodes are not allowed in the XML body', + ); + } + + $prefix = substr($xml, 0, self::DOCTYPE_CHECK_PREFIX_LENGTH); + $family = self::detectXmlEncodingFamily($prefix); + + if ($family === 'utf-8' || $family === 'ascii') { + return; + } + + $decoded = @mb_convert_encoding($prefix, 'UTF-8', $family); + if ($decoded === false) { + return; // or throw if you prefer a stricter posture + } + + if (preg_match('/<\s*!\s*DOCTYPE\b/i', $decoded) === 1) { + throw new RuntimeException( + 'Dangerous XML detected, DOCTYPE nodes are not allowed in the XML body', + ); + } + } + + + /** + * Detect the encoding family from the first bytes of an XML document + * according to the rules in the XML 1.0 specification (Appendix F – Autodetection of Character Encodings). + * + * @return string One of: 'utf-8', 'utf-16be', 'utf-16le', 'ucs-4be', 'ucs-4le', 'ascii' + */ + public static function detectXmlEncodingFamily(string $bytes): string + { + $len = strlen($bytes); + if ($len < 2) { + return 'utf-8'; + } + + // BOMs (most specific first) + if (str_starts_with($bytes, "\xEF\xBB\xBF")) { + return 'utf-8'; + } + + if (str_starts_with($bytes, "\xFE\xFF")) { + return 'utf-16be'; + } + + if (str_starts_with($bytes, "\xFF\xFE\x00\x00")) { + return 'ucs-4le'; + } + + if (str_starts_with($bytes, "\xFF\xFE")) { + return 'utf-16le'; + } + + if (str_starts_with($bytes, "\x00\x00\xFE\xFF")) { + return 'ucs-4be'; + } + + // No BOM – look at the start of a possible XML declaration + // = 4) { + if (str_starts_with($bytes, "\x3C\x3F\x78\x6D")) { // + */ + public static function safeDocumentsProvider(): array + { + return [ + 'utf8-simple' => [ + '', + ], + 'utf8-with-declaration' => [ + 'text', + ], + 'utf8-bom' => [ + "\xEF\xBB\xBF", + ], + 'utf8-long-prolog-no-doctype' => [ + '' . + str_repeat('', 30) . + '', + ], + 'utf16le-simple' => [ + self::utf16le(''), + ], + 'utf16be-simple' => [ + self::utf16be(''), + ], + 'utf16le-bom' => [ + "\xFF\xFE" . self::utf16le(''), + ], + 'utf16be-bom' => [ + "\xFE\xFF" . self::utf16be(''), + ], + ]; + } + + + /** + * @param non-empty-string $xml + */ + #[DataProvider('safeDocumentsProvider')] + public function testSafeDocumentsAreAccepted(string $xml): void + { + $doc = DOMDocumentFactory::fromString($xml); + $this->assertNotNull($doc->documentElement); + } + + // ------------------------------------------------------------------ + // Documents that MUST be rejected + // ------------------------------------------------------------------ + + /** + * @return array + */ + public static function dangerousDocumentsProvider(): array + { + $doctype = ']>'; + + return [ + // UTF-8 variants + 'utf8-doctype' => [ + '' . $doctype . '', + ], + 'utf8-doctype-whitespace' => [ + '', + ], + 'utf8-doctype-bom' => [ + "\xEF\xBB\xBF" . $doctype . '', + ], + 'utf8-doctype-after-comments' => [ + '' . + str_repeat('', 20) . + $doctype . + '', + ], + + // UTF-16LE + 'utf16le-doctype' => [ + self::utf16le('' . $doctype . ''), + ], + 'utf16le-doctype-bom' => [ + "\xFF\xFE" . self::utf16le('' . $doctype . ''), + ], + + // UTF-16BE + 'utf16be-doctype' => [ + self::utf16be('' . $doctype . ''), + ], + 'utf16be-doctype-bom' => [ + "\xFE\xFF" . self::utf16be('' . $doctype . ''), + ], + ]; + } + + + /** + * @param non-empty-string $xml + */ + #[DataProvider('dangerousDocumentsProvider')] + public function testDangerousDocumentsAreRejected(string $xml): void + { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('DOCTYPE nodes are not allowed'); + + DOMDocumentFactory::fromString($xml); + } + + // ------------------------------------------------------------------ + // Edge / robustness cases + // ------------------------------------------------------------------ + + public function testPrefixLengthIsSufficient(): void + { + // Build a prolog that is deliberately close to the 1 KB limit + // but still contains a DOCTYPE near the end of the prefix. + $padding = str_repeat('', 80); // ~800 bytes + $xml = '' . $padding . ''; + + $this->expectException(RuntimeException::class); + DOMDocumentFactory::fromString($xml); + } + + + public function testVeryShortDocumentWithoutDoctype(): void + { + $doc = DOMDocumentFactory::fromString(''); + /** @var \Dom\Element $elt */ + $elt = $doc->documentElement; + $this->assertSame('root', $elt->localName); + } +} diff --git a/tests/XML/DOMDocumentFactoryTest.php b/tests/XML/DOMDocumentFactoryTest.php index 8b02fb7b..4a8a2c51 100644 --- a/tests/XML/DOMDocumentFactoryTest.php +++ b/tests/XML/DOMDocumentFactoryTest.php @@ -8,7 +8,6 @@ use DOMException; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\Group; -use PHPUnit\Framework\Attributes\RequiresOperatingSystemFamily; use PHPUnit\Framework\TestCase; use RuntimeException; use SimpleSAML\Assert\AssertionFailedException; @@ -55,7 +54,6 @@ protected function tearDown(): void * Classic external-entity payload aimed at a file we control. * The factory must reject the document; the marker must never appear. */ - #[RequiresOperatingSystemFamily('Linux')] public function testExternalEntityCannotReadLocalFileUsingDefaultOptions(): void { // file:// URI pointing at our temporary secret @@ -68,14 +66,10 @@ public function testExternalEntityCannotReadLocalFileUsingDefaultOptions(): void &xxe; XML; - $doc = Dom\XMLDocument::createFromString($payload, DOMDocumentFactory::getDefaultOptions()); + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Dangerous XML detected, DOCTYPE nodes are not allowed in the XML body'); + DOMDocumentFactory::fromString($payload, DOMDocumentFactory::getDefaultOptions()); // If we reach here the protection failed – check that the secret did not leak into the document. - $xml = $doc->saveXml(); - $this->assertStringNotContainsString( - $this->marker, - (string)$xml, - 'XXE succeeded: local file content was expanded into the document', - ); } @@ -83,7 +77,6 @@ public function testExternalEntityCannotReadLocalFileUsingDefaultOptions(): void * Classic external-entity payload aimed at a file we control. * The factory must reject the document; the marker must never appear. */ - #[RequiresOperatingSystemFamily('Linux')] public function testExternalEntityCannotReadLocalFileUsingNonDefaultOptions(): void { // file:// URI pointing at our temporary secret @@ -101,21 +94,16 @@ public function testExternalEntityCannotReadLocalFileUsingNonDefaultOptions(): v $options &= ~\LIBXML_NO_XXE; } - $doc = Dom\XMLDocument::createFromString($payload, $options | \LIBXML_NOENT); - // Check that the secret did leak into the document. - $xml = $doc->saveXml(); - $this->assertStringContainsString( - $this->marker, - (string)$xml, - 'XXE succeeded: local file content was expanded into the document', - ); + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Dangerous XML detected, DOCTYPE nodes are not allowed in the XML body'); + DOMDocumentFactory::fromString($payload, $options | \LIBXML_NOENT); + // If we reach here the protection failed – check that the secret did not leak into the document. } /** * Same idea with a UTF-16LE encoded payload. */ - #[RequiresOperatingSystemFamily('Linux')] public function testUtf16ExternalEntityCannotReadLocalFileUsingDefaultOptions(): void { $uri = 'file://' . $this->secretFile; @@ -130,21 +118,16 @@ public function testUtf16ExternalEntityCannotReadLocalFileUsingDefaultOptions(): $payload = "\xFF\xFE" . mb_convert_encoding($utf8, 'UTF-16LE', 'UTF-8'); - $doc = Dom\XMLDocument::createFromString($payload, DOMDocumentFactory::getDefaultOptions()); + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Dangerous XML detected, DOCTYPE nodes are not allowed in the XML body'); + DOMDocumentFactory::fromString($payload, DOMDocumentFactory::getDefaultOptions()); // If we reach here the protection failed – check that the secret did not leak into the document. - $xml = $doc->saveXml(); - $this->assertStringNotContainsString( - $this->marker, - (string)$xml, - 'XXE succeeded: local file content was expanded into the document', - ); } /** * Same idea with a UTF-16LE encoded payload. */ - #[RequiresOperatingSystemFamily('Linux')] public function testUtf16ExternalEntityCannotReadLocalFileUsingNonDefaultOptions(): void { $uri = 'file://' . $this->secretFile; @@ -164,14 +147,10 @@ public function testUtf16ExternalEntityCannotReadLocalFileUsingNonDefaultOptions $options &= ~\LIBXML_NO_XXE; } - $doc = Dom\XMLDocument::createFromString($payload, $options | \LIBXML_NOENT); - // Check that the secret did leak into the document. - $xml = mb_convert_encoding((string)$doc->saveXml(), 'UTF-8', 'UTF-16LE'); - $this->assertStringContainsString( - $this->marker, - (string)$xml, - 'XXE succeeded: local file content was expanded into the document', - ); + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Dangerous XML detected, DOCTYPE nodes are not allowed in the XML body'); + DOMDocumentFactory::fromString($payload, $options | \LIBXML_NOENT); + // If we reach here the protection failed – check that the secret did not leak into the document. }