allowedAttrs = array_map('strtolower', AllowedAttributes::getAttributes()); $this->allowedTags = array_map('strtolower', AllowedTags::getTags()); } /** * Set up the DOMDocument */ protected function resetInternal() { $this->xmlDocument = new \DOMDocument(); $this->xmlDocument->preserveWhiteSpace = false; $this->xmlDocument->strictErrorChecking = false; $this->xmlDocument->formatOutput = !$this->minifyXML; } /** * Set XML options to use when saving XML * See: DOMDocument::saveXML * * @param int $xmlOptions */ public function setXMLOptions($xmlOptions) { $this->xmlOptions = $xmlOptions; } /** * Get XML options to use when saving XML * See: DOMDocument::saveXML * * @return int */ public function getXMLOptions() { return $this->xmlOptions; } /** * Get the array of allowed tags * * @return array */ public function getAllowedTags() { return $this->allowedTags; } /** * Set custom allowed tags * * @param TagInterface $allowedTags */ public function setAllowedTags(TagInterface $allowedTags) { $this->allowedTags = array_map('strtolower', $allowedTags::getTags()); } /** * Get the array of allowed attributes * * @return array */ public function getAllowedAttrs() { return $this->allowedAttrs; } /** * Set custom allowed attributes * * @param AttributeInterface $allowedAttrs */ public function setAllowedAttrs(AttributeInterface $allowedAttrs) { $this->allowedAttrs = array_map('strtolower', $allowedAttrs::getAttributes()); } /** * Should we remove references to remote files? * * @param bool $removeRemoteRefs */ public function removeRemoteReferences($removeRemoteRefs = false) { $this->removeRemoteReferences = $removeRemoteRefs; } /** * Get XML issues. * * @return array */ public function getXmlIssues() { if ($this->omittedXmlIssues === 0) { return $this->xmlIssues; } $issues = $this->xmlIssues; $issues[] = array( 'message' => sprintf('%d more issues not listed', $this->omittedXmlIssues), 'line' => 0, ); return $issues; } /** * Record an issue, up to MAX_XML_ISSUES of them. Past that, issues are only * counted: an input can hold hundreds of thousands of removable nodes, and * keeping a record for each one could use more memory than the input itself. * * @param string $message * @param int $line */ protected function addXmlIssue($message, $line) { if (count($this->xmlIssues) < self::MAX_XML_ISSUES) { $this->xmlIssues[] = array( 'message' => $message, 'line' => $line, ); return; } $this->omittedXmlIssues++; } /** * Can we allow huge files? * * @return bool */ public function getAllowHugeFiles() { return $this->allowHugeFiles; } /** * Set whether we can allow huge files. * * @param bool $allowHugeFiles */ public function setAllowHugeFiles( $allowHugeFiles ) { $this->allowHugeFiles = $allowHugeFiles; } /** * Sanitize the passed string * * @param string $dirty * @return string|false */ public function sanitize($dirty) { // Every call starts with no issues, so getXmlIssues() never reports a // previous document's issues. $this->xmlIssues = array(); $this->omittedXmlIssues = 0; // Don't run on an empty string. Compare strictly: empty() is also true // for '0', which is not empty input but a document that fails to parse. if ($dirty === '' || $dirty === null || $dirty === false) { return ''; } $this->resetInternal(); $this->setUpBefore(); // Input we cannot process safely (a failed regex, a document the // reference graph rejects, or anything unexpected) fails closed with // false instead of throwing out of sanitize(). That includes the checks // before parsing. try { $dirty = $this->prepareForParsing($dirty); $clean = $dirty === false ? false : $this->sanitizeDocument($dirty); } catch (\Throwable $e) { $this->addXmlIssue($e->getMessage(), 0); $clean = false; } finally { $this->resetAfter(); } return $clean; } /** * Strip and check the raw input before it reaches libxml. * * @param string $dirty * @return string|false The input to parse, or false if it must be rejected */ protected function prepareForParsing($dirty) { /* * remove php tags, including ones hidden inside other tags * i.e. hp echo . ' danger! ';?> */ $dirty = $this->stripPhpTags($dirty); // Strip any DOCTYPE/DTD before parsing. This prevents custom entity // definitions (which can collide with HTML5 named character references) // and DTD-defaulted attributes from ever reaching libxml. $dirty = $this->removeDoctype($dirty); if ($dirty === false) { $this->addXmlIssue('Nested DOCTYPE declaration', 0); return false; } // Stripping can leave nothing behind (input that was only PHP tags or a // DOCTYPE). That is not a document, and loadXML('') would throw. if (trim($dirty) === '') { $this->addXmlIssue('Document is empty', 0); return false; } // Some input is unsafe to hand to libxml at all: libxml before 2.10 parses // one element's attributes in quadratic time, and an encoded DTD can be // expanded before it is rejected. $problem = $this->findProblemBeforeParsing($dirty); if ($problem !== null) { $this->addXmlIssue($problem, 0); return false; } return $dirty; } /** * Parse and clean the document. Expects setUpBefore() to have run. * * @param string $dirty * @return string|false */ protected function sanitizeDocument($dirty) { // LIBXML_NONET: never fetch anything over the network while parsing. // External entities are already not loaded; this states it outright. $options = LIBXML_NONET; if ($this->getAllowHugeFiles()) { $options |= LIBXML_PARSEHUGE; } $loaded = $this->xmlDocument->loadXML($dirty, $options); // If we couldn't parse the XML then we go no further. if (!$loaded) { foreach (self::getXmlErrors() as $error) { $this->addXmlIssue($error['message'], $error['line']); } return false; } // removeDoctype() works on raw bytes, so a DTD can still reach libxml in // an encoding it cannot read (UTF-16, for instance). By now libxml has // already applied the DTD's entities and attribute defaults, so the only // safe answer is to reject the document. A DOCTYPE without an internal // subset (e.g. PUBLIC only) is harmless and still allowed. $doctype = $this->xmlDocument->doctype; if ($doctype !== null && ( trim((string) $doctype->internalSubset) !== '' || $doctype->entities->length > 0 || $doctype->notations->length > 0 )) { $this->addXmlIssue('Internal DTD subset is not allowed', 0); return false; } // An `` root in some other namespace is not SVG to an XML reader, but // an HTML parser ignores `xmlns` and makes it live SVG when the output is // inlined. Accept the SVG namespace, or none. $rootNamespace = (string) $this->xmlDocument->documentElement->namespaceURI; if ($rootNamespace !== '' && $rootNamespace !== self::SVG_NAMESPACE_URI) { $this->addXmlIssue('Root element is not in the SVG namespace', 0); return false; } if ($this->minifyXML) { $this->collapseWhitespace(); } // Fails early (with a LogicException) unless the root is a single . $xPath = new XPath($this->xmlDocument); // Clean tags and attributes first. The `` limits must be measured on // the document a browser will render: before cleaning, a decoy the // cleaner removes, an unsafe href hiding a safe one, or an attribute the // cleaner renames would show the graph a different reference. $this->elementReferenceResolver = null; $this->startClean($this->xmlDocument->childNodes, array()); $this->removeDuplicateIds($xPath); // Then measure the `` references and remove any that break the limits. $this->elementReferenceResolver = new Resolver($xPath, $this->useNestingLimit); $this->elementReferenceResolver->collect(); $this->removeUnsafeUseElements($this->elementReferenceResolver->getElementsToRemove()); // Save cleaned XML to a variable if ($this->removeXMLTag) { $clean = $this->xmlDocument->saveXML($this->xmlDocument->documentElement, $this->xmlOptions); } else { $clean = $this->xmlDocument->saveXML($this->xmlDocument, $this->xmlOptions); } // Remove any extra whitespaces when minifying. Text and attribute values // were already collapsed before the security checks ran (see // collapseWhitespace()), so this only touches the serializer's own // line breaks and cannot change a value that was checked. if ($this->minifyXML) { $clean = $this->pregReplace('/\s+/', ' ', $clean); } return $clean; } /** * For minify(): collapse every run of whitespace in text, CDATA and * attribute values to one space, in the parsed document. * * This runs before cleaning so the security checks and the `` graph * see the values that will be output. Collapsing the serialized output * afterwards could change a checked value: in CSS a hex escape swallows one * following space, so `url(\2f /host)` would become `url(\2f /host)`, * which is `url(//host)`, and `id="a b"` would become `id="a b"`. */ protected function collapseWhitespace() { foreach ($this->walkNodes($this->xmlDocument) as $node) { $values = $node instanceof \DOMElement ? iterator_to_array($node->attributes, false) : array($node); foreach ($values as $valueNode) { if (!$valueNode instanceof \DOMAttr && !$valueNode instanceof \DOMText) { continue; } $value = $valueNode->nodeValue; $collapsed = $this->pregReplace('/\s+/', ' ', $value); if ($collapsed !== $value) { $valueNode->nodeValue = $collapsed; } } } } /** * Remove a node from the document. * * Before PHP 8.1, DOMNode::removeChild() searches the parent's child list * for the node first, so removing many children of one parent was * quadratic. Moving the node into a scratch fragment unlinks it directly, * and removing it from there is instant, because it is the fragment's only * child. * * @param \DOMNode $node */ protected function removeNode(\DOMNode $node) { if ($this->removedNodes === null || $this->removedNodes->ownerDocument !== $node->ownerDocument) { $this->removedNodes = $node->ownerDocument->createDocumentFragment(); } $this->removedNodes->appendChild($node); $this->removedNodes->removeChild($node); } /** * Every node under $node, in document order, one at a time. * * Before PHP 8.4, an XPath query or a node-list snapshot creates a PHP * object for every matching node at once, at about half a kilobyte each. * Following the sibling links instead keeps only the current path in memory. * The next sibling is read before a node is yielded, so the caller may * remove that node. The children of a removed node are skipped. * * @param \DOMNode $node * @return \Generator|\DOMNode[] */ protected function walkNodes(\DOMNode $node) { for ($child = $node->firstChild; $child !== null; $child = $next) { $next = $child->nextSibling; yield $child; if ($child->parentNode !== null && $child->hasChildNodes()) { yield from $this->walkNodes($child); } } } /** * Remove `` and `` blocks, including blocks that only * appear once an inner block has been removed (`hp b?>`). * * This matches what repeatedly applying `/<\?(=|php)(.+?)\?>/i` until nothing * changes would do (the leftmost opener up to the first closer on the same * line), but in a single linear pass. The regex loop needed a full pass per * nesting level, and the regex itself was quadratic on long lines without JIT. * * @param string $dirty * @return string */ protected function stripPhpTags($dirty) { // A tag can only be revealed by removing another one, so input without // any opener has nothing to strip. if (stripos($dirty, '') { // A closer needs at least one character of content before it. if ($openAt >= 0 && $size - 2 > $contentAt && $buffer[$size - 2] === '?') { $size = $openAt; $openAt = -1; } } elseif ($openAt < 0) { if (($char === 'p' || $char === 'P') && $size >= 5 && strtolower(substr($buffer, $size - 5, 5)) === '= 3 && $buffer[$size - 3] === '<' && $buffer[$size - 2] === '?') { $openAt = $size - 3; $contentAt = $size; } } } return substr($buffer, 0, $size); } /** * Check the raw input for anything that is unsafe to hand to libxml. * * @param string $dirty * @return string|null The reason to reject the input, or null if it is fine */ protected function findProblemBeforeParsing($dirty) { $markup = $this->readMarkupBeforeParsing($dirty); if ($markup === null) { return 'Unsupported document encoding'; } // removeDoctype() has already removed every DOCTYPE from input it can // read as bytes. In UTF-16 and UTF-32 it cannot, so look here. if ($markup['decoded'] && $this->hasInternalDtdSubset($markup['text'])) { return 'Internal DTD subset is not allowed'; } if ($this->hasElementWithTooManyAttributes($markup['text'])) { return 'Too many attributes on one element'; } return null; } /** * Read the input's markup the way libxml will, as ASCII. * * UTF-16 and UTF-32 input is decoded one code unit at a time: ASCII stays, * and anything else becomes `x`, so a byte inside a non-ASCII character can * never pass for markup. ASCII-compatible encodings are read as they are. * Anything else returns null: EBCDIC, UTF-7, an encoding that is not known * to be ASCII-compatible, or a declaration that does not match the bytes. * * @param string $dirty * @return array{text: string, decoded: bool}|null */ protected function readMarkupBeforeParsing($dirty) { // Byte order marks, then the patterns libxml uses to spot `findDeclaredEncoding($dirty); if ($declared !== null && !$this->isAsciiCompatibleEncoding($declared)) { return null; } return array('text' => $dirty, 'decoded' => false); } $length = strlen($dirty); $units = (int) (($length - $start) / $unitSize); $text = str_repeat('x', $units); for ($i = 0, $offset = $start; $i < $units; $i++, $offset += $unitSize) { $unit = 0; for ($byte = 0; $byte < $unitSize; $byte++) { $value = ord($dirty[$offset + ($bigEndian ? $byte : $unitSize - 1 - $byte)]); $unit = ($unit << 8) | $value; } if ($unit < 0x80) { $text[$i] = chr($unit); } } $declared = $this->findDeclaredEncoding($text); if ($declared !== null && !preg_match('/^(?:utf-?(?:16|32)(?:[bl]e)?|ucs-?[24]|iso-10646-ucs-[24])$/i', $declared)) { return null; } return array('text' => $text, 'decoded' => true); } /** * The encoding named in the XML declaration, if there is one. * * @param string $markup * @return string|null */ protected function findDeclaredEncoding($markup) { if (strncmp(ltrim($markup, "\xEF\xBB\xBF"), ''); $declaration = substr($markup, 0, $end === false ? 200 : $end); // This runs before parsing, outside the try block in sanitize(), so use // preg_match() directly. The subject is one short declaration. if (preg_match('/\bencoding\s*=\s*(["\'])([^"\']*)\1/', $declaration, $matches) !== 1) { return null; } return $matches[2]; } /** * Is this an encoding whose markup characters are plain ASCII bytes? * * @param string $encoding * @return bool */ protected function isAsciiCompatibleEncoding($encoding) { return (bool) preg_match( '/^(?:utf-?8|(?:us-)?ascii|iso[-_]?8859[-_]?\d+|iso[-_]?646[-_\w]*|latin-?\d+|l\d' . '|(?:windows|cp)-?(?:125\d|874|932|936|949|950)|koi8-?[ru]|shift[-_]?jis|sjis|windows-31j' . '|euc-?(?:jp|kr|cn|tw)|gb2312|gbk|gb18030|big5(?:-hkscs)?|tis-?620)$/i', $encoding ); } /** * Does a DOCTYPE in this markup carry an internal subset (`[...]`)? * * @param string $markup * @return bool */ protected function hasInternalDtdSubset($markup) { $lowerMarkup = strtolower($markup); $length = strlen($markup); $offset = 0; while (($start = strpos($lowerMarkup, '", $i); if ($i >= $length) { break; } if ($markup[$i] === '[') { return true; } if ($markup[$i] === '>') { break; } $close = strpos($markup, $markup[$i], $i + 1); if ($close === false) { return false; } $i = $close; } if ($i >= $length) { return false; } $offset = $i + 1; } return false; } /** * Does any element carry more than MAX_ATTRIBUTES_PER_ELEMENT attributes? * * Counts each `=` in a start tag outside quoted values, and skips comments, * CDATA sections, processing instructions, end tags and declarations. Text * is never scanned, because `<` cannot appear in it unescaped. Linear in the * input. * * @param string $markup * @return bool */ protected function hasElementWithTooManyAttributes($markup) { $length = strlen($markup); $offset = 0; while (($start = strpos($markup, '<', $offset)) !== false) { $next = $start + 1; $skipTo = null; if (substr($markup, $next, 3) === '!--') { $skipTo = '-->'; } elseif (substr($markup, $next, 8) === '![CDATA[') { $skipTo = ']]>'; } elseif ($next < $length && $markup[$next] === '?') { $skipTo = '?>'; } elseif ($next < $length && ($markup[$next] === '!' || $markup[$next] === '/')) { $skipTo = '>'; } if ($skipTo !== null) { $end = strpos($markup, $skipTo, $next); if ($end === false) { return false; } $offset = $end + strlen($skipTo); continue; } $attributes = 0; for ($i = $next; $i < $length; $i++) { $i += strcspn($markup, "\"'=>", $i); if ($i >= $length || $markup[$i] === '>') { break; } if ($markup[$i] === '=') { if (++$attributes > self::MAX_ATTRIBUTES_PER_ELEMENT) { return true; } continue; } $close = strpos($markup, $markup[$i], $i + 1); if ($close === false) { return false; } $i = $close; } if ($i >= $length) { return false; } $offset = $i + 1; } return false; } /** * Remove any DOCTYPE declaration (and its internal subset) from the input * string before it reaches the XML parser. * * The internal subset is scanned with balanced brackets so that a `>` * appearing inside an entity value cannot prematurely terminate the match. * * Removing one DOCTYPE can join the text around it into a new one * (`DOCTYPE svg [...]>`). Rather than rescanning, which would * be quadratic on deep nesting, any DOCTYPE left in the output means the * input is rejected. * * @param string $dirty * @return string|false */ protected function removeDoctype($dirty) { // Lower-case once and search with strpos(). stripos() lower-cases its // whole haystack on every call, which is quadratic over many matches. $lowerDirty = strtolower($dirty); if (strpos($lowerDirty, '' inside a DTD comment is not a real internal-subset // delimiter and must not affect the bracket depth. if ($char === '<' && substr($dirty, $i, 4) === '', $i + 4); if ($commentEnd === false) { $i = $length; break; } $i = $commentEnd + 2; continue; } // Likewise for a '[', ']' or '>' inside a quoted string. if ($char === '"' || $char === "'") { $stringEnd = strpos($dirty, $char, $i + 1); if ($stringEnd === false) { $i = $length; break; } $i = $stringEnd; continue; } if ($char === '[') { $depth++; } elseif ($char === ']') { if ($depth > 0) { $depth--; } } elseif ($char === '>' && $depth === 0) { $i++; break; } } $offset = $i; } $output .= substr($dirty, $offset); if (stripos($output, 'xmlLoaderValue = libxml_disable_entity_loader(true); } // Suppress the errors because we don't really have to worry about formation before cleansing. // See reset in resetAfter(). $this->xmlErrorHandlerPreviousValue = libxml_use_internal_errors(true); // Reset array of altered XML $this->xmlIssues = array(); } /** * Reset the class after use */ protected function resetAfter() { // This function has been deprecated in PHP 8.0 because in libxml 2.9.0, external entity loading is // disabled by default, so this function is no longer needed to protect against XXE attacks. if (\LIBXML_VERSION < 20900 && \function_exists('libxml_disable_entity_loader')) { // Reset the entity loader libxml_disable_entity_loader($this->xmlLoaderValue); } libxml_clear_errors(); libxml_use_internal_errors($this->xmlErrorHandlerPreviousValue); } /** * Start the cleaning with tags, then we move onto attributes and hrefs later * * @param \DOMNodeList $elements * @param array $elementsToRemove */ protected function startClean(\DOMNodeList $elements, array $elementsToRemove) { if ($elements->length === 0) { return; } // Walk the children from the last one back through their sibling links. // Calling item($i) on a live \DOMNodeList while stepping backwards // re-walks the list from the start every time, which is O(n²). A // snapshot of the whole list (iterator_to_array) avoids that, but holds // a PHP object for every child at once, which before PHP 8.4 costs about // half a kilobyte per node. Reading the previous sibling before handling // a node also means removing that node never skips a sibling. $parent = $elements->item(0)->parentNode; for ($currentElement = $parent->lastChild; $currentElement !== null; $currentElement = $previousSibling) { $previousSibling = $currentElement->previousSibling; /** * If the element has exceeded the nesting limit, we should remove it. * * As it's only elements that cause us issues with nesting DOS attacks * we should check what the element is before removing it. For now we'll only * remove elements. */ if ('use' === $currentElement->nodeName && in_array($currentElement, $elementsToRemove)) { $this->addXmlIssue('Invalid \'' . $currentElement->tagName . '\'', $currentElement->getLineNo()); $this->removeNode($currentElement); continue; } if ($currentElement instanceof \DOMElement) { // If the tag isn't in the whitelist, remove it and continue with next iteration if (!in_array(strtolower($currentElement->tagName), $this->allowedTags)) { $this->addXmlIssue('Suspicious tag \'' . $currentElement->tagName . '\'', $currentElement->getLineNo()); $this->removeNode($currentElement); continue; } // The `` limits only measure `` in the root's namespace. // ``, or a `` in another namespace (`xmlns=""`), means // nothing in XML, but an HTML parser turns it into a live SVG // `` when the output is inlined in a page. if (strtolower($currentElement->localName) === 'use' && ($currentElement->tagName !== 'use' || $currentElement->namespaceURI !== $this->xmlDocument->documentElement->namespaceURI) ) { $this->addXmlIssue('Suspicious tag \'' . $currentElement->tagName . '\'', $currentElement->getLineNo()); $this->removeNode($currentElement); continue; } // Strip remote @import / url() references from inline