Skip to content
Open
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
4 changes: 4 additions & 0 deletions src/XML/Assert/Assert.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
* @package simplesamlphp/xml-common
*
* @phpcs:ignore Generic.Files.LineLength.TooLong
* @method static void assertSafeXML(\Dom\Element $value, string $message = '', string $exception = '');
* @method static void validAllowedXPathFilter(mixed $value, string[] $allowed_axes, string[] $allowed_functions, string $message = '', string $exception = '')
* @method static void validAnyURI(mixed $value, string $message = '', string $exception = '')
* @method static void validBase64Binary(mixed $value, string $message = '', string $exception = '')
Expand Down Expand Up @@ -54,6 +55,7 @@
* @method static void validYear(mixed $value, string $message = '', string $exception = '')
* @method static void validYearMonth(mixed $value, string $message = '', string $exception = '')
* @phpcs:ignore Generic.Files.LineLength.TooLong
* @method static void nullOrAssertSafeXML(mixed $value, string $message = '', string $exception = '');
* @method static void nullOrValidAllowedXPathFilter(mixed $value, string[] $allowed_axes, string[] $allowed_functions, string $message = '', string $exception = '')
* @method static void nullOrValidAnyURI(mixed $value, string $message = '', string $exception = '')
* @method static void nullOrValidBase64Binary(mixed $value, string $message = '', string $exception = '')
Expand Down Expand Up @@ -98,6 +100,7 @@
* @method static void nullOrValidYear(mixed $value, string $message = '', string $exception = '')
* @method static void nullOrValidYearMonth(mixed $value, string $message = '', string $exception = '')
* @phpcs:ignore Generic.Files.LineLength.TooLong
* @method static void allAssertSafeXML(\Dom\Element[] $value, string $message = '', string $exception = '');
* @method static void allValidAllowedXPathFilter(mixed $value, string[] $allowed_axes, string[] $allowed_functions, string $message = '', string $exception = '')
* @method static void allValidAnyURI(mixed $value, string $message = '', string $exception = '')
* @method static void allValidBase64Binary(mixed $value, string $message = '', string $exception = '')
Expand Down Expand Up @@ -176,6 +179,7 @@ class Assert extends BaseAssert
use NormalizedStringTrait;
use PositiveIntegerTrait;
use QNameTrait;
use SafeXMLTrait;
use ShortTrait;
use StringTrait;
use TimeTrait;
Expand Down
31 changes: 31 additions & 0 deletions src/XML/Assert/SafeXMLTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

declare(strict_types=1);

namespace SimpleSAML\XML\Assert;

use Dom;
use InvalidArgumentException;
use SimpleSAML\XML\Exception\StructuralLimitException;
use SimpleSAML\XML\Limit\XMLLimit;

/**
* @package simplesamlphp/xml-common
*/
trait SafeXMLTrait
{
/**
* @param \Dom\Element $value
* @param string $message
*/
protected static function assertSafeXML(Dom\Element $value, string $message = ''): void
{
$config = XMLLimit::getDefault();

try {
XMLLimit::assertSafeXML($value, $config);
} catch (StructuralLimitException $e) {
throw new InvalidArgumentException($e->getMessage());
}
}
}
2 changes: 2 additions & 0 deletions src/XML/Constants.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ class Constants
/**
* The maximum amount of child nodes this library is willing to handle.
* By specification, this limit is 150K, but that opens up for denial of service.
*
* @deprecated Use limits defined in XMLLimit instead. Will be removed in a future release
*/
public const int UNBOUNDED_LIMIT = 10000;
}
17 changes: 17 additions & 0 deletions src/XML/Exception/StructuralLimitException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

declare(strict_types=1);

namespace SimpleSAML\XML\Exception;

/**
* Class StructuralLimitException
*
* This exception is thrown when one of the configured structural limits
* have been reached during processing in the library.
*
* @package simplesamlphp/xml-common
*/
class StructuralLimitException extends RuntimeException
{
}
3 changes: 2 additions & 1 deletion src/XML/ExtendableAttributesTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use RuntimeException;
use SimpleSAML\XML\Assert\Assert;
use SimpleSAML\XML\Constants as C;
use SimpleSAML\XML\Limit\XMLLimit;
use SimpleSAML\XMLSchema\Exception\InvalidDOMAttributeException;
use SimpleSAML\XMLSchema\Exception\SchemaViolationException;
use SimpleSAML\XMLSchema\Type\StringValue;
Expand Down Expand Up @@ -180,7 +181,7 @@ protected static function getAttributesNSFromXML(
*/
protected function setAttributesNS(array $attributes): void
{
Assert::maxCount($attributes, C::UNBOUNDED_LIMIT);
Assert::maxCount($attributes, XMLLimit::getDefault()->maxAttribute);
Assert::allIsInstanceOf(
$attributes,
Attribute::class,
Expand Down
4 changes: 2 additions & 2 deletions src/XML/ExtendableElementTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
use RuntimeException;
use SimpleSAML\XML\Assert\Assert;
use SimpleSAML\XML\Chunk;
use SimpleSAML\XML\Constants as C;
use SimpleSAML\XML\Limit\XMLLimit;
use SimpleSAML\XML\Registry\ElementRegistry;
use SimpleSAML\XMLSchema\Exception\InvalidDOMElementException;
use SimpleSAML\XMLSchema\Exception\SchemaViolationException;
Expand Down Expand Up @@ -120,7 +120,7 @@ protected static function getChildElementsFromXML(
*/
protected function setElements(array $elements): void
{
Assert::maxCount($elements, C::UNBOUNDED_LIMIT);
Assert::maxCount($elements, XMLLimit::getDefault()->maxNode);
Assert::allIsInstanceOf($elements, SerializableElementInterface::class);

$namespace = $this->getElementNamespace();
Expand Down
132 changes: 132 additions & 0 deletions src/XML/Limit/XMLLimit.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
<?php

declare(strict_types=1);

namespace SimpleSAML\XML\Limit;

use Dom;
use SimpleSAML\XML\Constants as C;
use SimpleSAML\XML\Exception\StructuralLimitException;
use WeakMap;

use function count;
use function max;
use function sprintf;
use function str_starts_with;

final class XMLLimit
{
private static ?XMLLimitConfig $config = null;

/** @var \WeakMap<\Dom\Element, true> */
private static ?\WeakMap $checked = null;


public static function setDefault(?XMLLimitConfig $config): void
{
self::$config = $config;
}


public static function getDefault(): XMLLimitConfig
{
return self::$config ?? XMLLimitConfig::getHardDefaults();
}


public static function assertSafeXML(
Dom\Element $root,
?XMLLimitConfig $config = null,
): void {
self::$checked ??= new WeakMap();

$doc = $root->ownerDocument;
if (isset(self::$checked[$doc])) {
return; // already validated this document
}

$config ??= self::getDefault();

$nodeCount = 0;
$maxObservedDepth = 0;
$maxObservedNsInScope = 0;
$maxNodes = $config->maxNode;
$maxAttributes = $config->maxAttribute;
$maxNsDecls = $config->maxNsDecl;
$maxDepth = $config->maxDepth;
$maxNsInScope = $config->maxNsInScope;

$walker = function (
Dom\Node $node,
int $depth,
array $inScopeNs,
) use (
&$walker,
&$nodeCount,
&$maxObservedDepth,
&$maxObservedNsInScope,
$maxNodes,
$maxAttributes,
$maxNsDecls,
$maxDepth,
$maxNsInScope,
): void {
if (++$nodeCount > $maxNodes) {
throw new StructuralLimitException(
sprintf('XML structural limit exceeded: more than %d nodes', $maxNodes),
);
}
if ($depth > $maxDepth) {
throw new StructuralLimitException(
sprintf('XML structural limit exceeded: nesting depth > %d', $maxDepth),
);
}
$maxObservedDepth = max($maxObservedDepth, $depth);

if ($node->nodeType === XML_ELEMENT_NODE) {
/** @var \Dom\Element $node */
$attrCount = 0;
$nsDeclCount = 0;
$localNs = $inScopeNs;

foreach ($node->attributes ?? [] as $attr) {
$attrCount++;
if ($attrCount > $maxAttributes) {
throw new StructuralLimitException(
sprintf('XML structural limit exceeded: element has > %d attributes', $maxAttributes),
);
}
// xmlns or xmlns:prefix
if ($attr->namespaceURI === C::NS_XMLNS || str_starts_with($attr->name, 'xmlns')) {
$nsDeclCount++;
if ($nsDeclCount > $maxNsDecls) {
throw new StructuralLimitException(sprintf(
'XML structural limit exceeded: > %d namespace declarations on one element',
$maxNsDecls,
));
}
$prefix = $attr->prefix === 'xmlns' ? $attr->localName : '';
$localNs[$prefix] = $attr->value;
}
}

$nsInScope = count($localNs);
if ($nsInScope > $maxNsInScope) {
throw new StructuralLimitException(sprintf(
'XML structural limit exceeded: > %d namespaces in scope',
$maxNsInScope,
));
}
$maxObservedNsInScope = max($maxObservedNsInScope, $nsInScope);

foreach ($node->childNodes as $child) {
$walker($child, $depth + 1, $localNs);
}
}
};

$walker($root, 1, []);

self::$checked[$doc] = true;
}
}
101 changes: 101 additions & 0 deletions src/XML/Limit/XMLLimitConfig.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
<?php

declare(strict_types=1);

namespace SimpleSAML\XML\Limit;

final class XMLLimitConfig
{
// Hard defaults that must be enforced at all time
// while making the O(KN²) / O(N²) / O(D³W²) paths impractical.
public const int HARD_MAX_NODE = 100000; // total Element + Attribute + Text + ...

public const int HARD_MAX_ATTRIBUTE = 200; // per element

public const int HARD_MAX_NS_DECL = 64; // xmlns* attributes per element

public const int HARD_MAX_DEPTH = 128; // nesting depth

public const int HARD_MAX_NS_IN_SCOPE = 128; // distinct prefixes/namespaces visible at any point

// Conservative defaults that still allow every common legitimate XML-document
public const int DEFAULT_MAX_NODE = 25000; // total Element + Attribute + Text + ...

public const int DEFAULT_MAX_ATTRIBUTE = 100; // per element

public const int DEFAULT_MAX_NS_DECL = 40; // xmlns* attributes per element

public const int DEFAULT_MAX_DEPTH = 64; // nesting depth

public const int DEFAULT_MAX_NS_IN_SCOPE = 64; // distinct prefixes/namespaces visible at any point

// Even more conservative defaults that should still allow most XML-documents
// Think of relatively small XML-structures like SAML 2.0 responses or metadata
public const int STRICT_MAX_NODE = 5000; // total Element + Attribute + Text + ...

public const int STRICT_MAX_ATTRIBUTE = 60; // per element

public const int STRICT_MAX_NS_DECL = 20; // xmlns* attributes per element

public const int STRICT_MAX_DEPTH = 32; // nesting depth

public const int STRICT_MAX_NS_IN_SCOPE = 40; // distinct prefixes/namespaces visible at any point


/**
* Initialize an XMLLimit class
*/
public function __construct(
public int $maxNode = self::DEFAULT_MAX_NODE,
public int $maxAttribute = self::DEFAULT_MAX_ATTRIBUTE,
public int $maxNsDecl = self::DEFAULT_MAX_NS_DECL,
public int $maxDepth = self::DEFAULT_MAX_DEPTH,
public int $maxNsInScope = self::DEFAULT_MAX_NS_IN_SCOPE,
) {
}


/**
* Return the strict limits
*/
public static function getStrictDefaults(): static
{
return new static(
self::STRICT_MAX_NODE,
self::STRICT_MAX_ATTRIBUTE,
self::STRICT_MAX_NS_DECL,
self::STRICT_MAX_DEPTH,
self::STRICT_MAX_NS_IN_SCOPE,
);
}


/**
* Return the default limits
*/
public static function getDefaultXMLDefaults(): static
{
return new static(
self::DEFAULT_MAX_NODE,
self::DEFAULT_MAX_ATTRIBUTE,
self::DEFAULT_MAX_NS_DECL,
self::DEFAULT_MAX_DEPTH,
self::DEFAULT_MAX_NS_IN_SCOPE,
);
}


/**
* Return the hard limits
*/
public static function getHardDefaults(): static
{
return new static(
self::HARD_MAX_NODE,
self::HARD_MAX_ATTRIBUTE,
self::HARD_MAX_NS_DECL,
self::HARD_MAX_DEPTH,
self::HARD_MAX_NS_IN_SCOPE,
);
}
}
4 changes: 4 additions & 0 deletions tests/bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

use SimpleSAML\Test\Container\TestContainer;
use SimpleSAML\XML\Container\TestContainerSingleton;
use SimpleSAML\XML\Limit\XMLLimit;
use SimpleSAML\XML\Limit\XMLLimitConfig;
use SimpleSAML\XML\Registry\ElementRegistry;

$projectRoot = dirname(__DIR__);
Expand All @@ -14,3 +16,5 @@

$testContainer = new TestContainer();
TestContainerSingleton::setContainer($testContainer);

XMLLimit::setDefault(XMLLimitConfig::getHardDefaults());
Loading