Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
"ext-date": "*",
"ext-dom": "*",
"ext-libxml": "*",
"ext-mbstring": "*",
"ext-pcre": "*",
"ext-spl": "*",
"ext-uri": "*",
Expand All @@ -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"
},
Expand Down
125 changes: 117 additions & 8 deletions src/XML/DOMDocumentFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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(
Expand All @@ -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();
}
Expand Down Expand Up @@ -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
// <?xml in different encodings
if ($len >= 4) {
if (str_starts_with($bytes, "\x3C\x3F\x78\x6D")) { // <?xm (UTF-8 / ASCII)
return 'utf-8';
}

if (str_starts_with($bytes, "\x00\x3C\x00\x3F")) { // UTF-16BE
return 'utf-16be';
}

if (str_starts_with($bytes, "\x3C\x00\x3F\x00")) { // UTF-16LE
return 'utf-16le';
}

if (str_starts_with($bytes, "\x00\x00\x00\x3C")) { // UCS-4BE
return 'ucs-4be';
}

if (str_starts_with($bytes, "\x3C\x00\x00\x00")) { // UCS-4LE
return 'ucs-4le';
}
}

// Fallback
return 'utf-8';
}
}
162 changes: 162 additions & 0 deletions tests/XML/DOMDocumentFactoryDoctypeTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
<?php

declare(strict_types=1);

namespace SimpleSAML\Test\XML;

use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use SimpleSAML\XML\DOMDocumentFactory;
use SimpleSAML\XML\Exception\RuntimeException;

final class DOMDocumentFactoryDoctypeTest extends TestCase
{
// ------------------------------------------------------------------
// Helpers
// ------------------------------------------------------------------

private static function utf16be(string $s): string
{
return mb_convert_encoding($s, 'UTF-16BE', 'UTF-8');
}


private static function utf16le(string $s): string
{
return mb_convert_encoding($s, 'UTF-16LE', 'UTF-8');
}

// ------------------------------------------------------------------
// Documents that MUST be accepted
// ------------------------------------------------------------------

/**
* @return array<string, string[]>
*/
public static function safeDocumentsProvider(): array
{
return [
'utf8-simple' => [
'<?xml version="1.0"?><root/>',
],
'utf8-with-declaration' => [
'<?xml version="1.0" encoding="UTF-8"?><root attr="value">text</root>',
],
'utf8-bom' => [
"\xEF\xBB\xBF<?xml version=\"1.0\"?><root/>",
],
'utf8-long-prolog-no-doctype' => [
'<?xml version="1.0" encoding="UTF-8"?>' .
str_repeat('<!-- comment -->', 30) .
'<root/>',
],
'utf16le-simple' => [
self::utf16le('<?xml version="1.0"?><root/>'),
],
'utf16be-simple' => [
self::utf16be('<?xml version="1.0"?><root/>'),
],
'utf16le-bom' => [
"\xFF\xFE" . self::utf16le('<?xml version="1.0"?><root/>'),
],
'utf16be-bom' => [
"\xFE\xFF" . self::utf16be('<?xml version="1.0"?><root/>'),
],
];
}


/**
* @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<string, string[]>
*/
public static function dangerousDocumentsProvider(): array
{
$doctype = '<!DOCTYPE root [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>';

return [
// UTF-8 variants
'utf8-doctype' => [
'<?xml version="1.0"?>' . $doctype . '<root/>',
],
'utf8-doctype-whitespace' => [
'<?xml version="1.0"?><! DOCTYPE root []><root/>',
],
'utf8-doctype-bom' => [
"\xEF\xBB\xBF<?xml version=\"1.0\"?>" . $doctype . '<root/>',
],
'utf8-doctype-after-comments' => [
'<?xml version="1.0"?>' .
str_repeat('<!-- safe comment -->', 20) .
$doctype .
'<root/>',
],

// UTF-16LE
'utf16le-doctype' => [
self::utf16le('<?xml version="1.0"?>' . $doctype . '<root/>'),
],
'utf16le-doctype-bom' => [
"\xFF\xFE" . self::utf16le('<?xml version="1.0"?>' . $doctype . '<root/>'),
],

// UTF-16BE
'utf16be-doctype' => [
self::utf16be('<?xml version="1.0"?>' . $doctype . '<root/>'),
],
'utf16be-doctype-bom' => [
"\xFE\xFF" . self::utf16be('<?xml version="1.0"?>' . $doctype . '<root/>'),
],
];
}


/**
* @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('<!-- x -->', 80); // ~800 bytes
$xml = '<?xml version="1.0"?>' . $padding . '<!DOCTYPE root []><root/>';

$this->expectException(RuntimeException::class);
DOMDocumentFactory::fromString($xml);
}


public function testVeryShortDocumentWithoutDoctype(): void
{
$doc = DOMDocumentFactory::fromString('<root/>');
/** @var \Dom\Element $elt */
$elt = $doc->documentElement;
$this->assertSame('root', $elt->localName);
}
}
Loading
Loading