CVE-2023-38500 (published 2023-07-25T21:15Z)

TYPO3 HTML Sanitizer is an HTML sanitizer, written in PHP, aiming to provide cross-site-scripting-safe markup based on explicitly allowed tags, attributes and values. Starting in version 1.0.0 and prior to versions 1.5.1 and 2.1.2, due to an encoding issue in the serialization layer, malicious markup nested in a `noscript` element was not encoded correctly. `noscript` is disabled in the default configuration, but might have been enabled in custom scenarios. This allows bypassing the cross-site scripting mechanism of TYPO3 HTML Sanitizer. Versions 1.5.1 and 2.1.2 fix the problem.

CVSS v3 base score: 6.1, MEDIUM (CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N)

Weakness information:
cwe_id: CWE-79
cwe_name: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
description: The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
extended_description: 
            Cross-site scripting (XSS) vulnerabilities occur when:
            
               Untrusted data enters a web application, typically from a web request.
               The web application dynamically generates a web page that contains this untrusted data.
               During page generation, the application does not prevent the data from containing content that is executable by a web browser, such as JavaScript, HTML tags, HTML attributes, mouse events, Flash, ActiveX, etc.
               A victim visits the generated web page through a web browser, which contains malicious script that was injected using the untrusted data.
               Since the script comes from a web page that was sent by the web server, the victim's web browser executes the malicious script in the context of the web server's domain.
               This effectively violates the intention of the web browser's same-origin policy, which states that scripts in one domain should not be able to access resources or run code in a different domain.
            
            There are three main kinds of XSS:
            
               
                  Type 1: Reflected XSS (or Non-Persistent) - 
         			The server reads data directly from the HTTP request and reflects it back in the HTTP response. Reflected XSS exploits occur when an attacker causes a victim to supply dangerous content to a vulnerable web application, which is then reflected back to the victim and executed by the web browser. The most common mechanism for delivering malicious content is to include it as a parameter in a URL that is posted publicly or e-mailed directly to the victim. URLs constructed in this manner constitute the core of many phishing schemes, whereby an attacker convinces a victim to visit a URL that refers to a vulnerable site. After the site reflects the attacker's content back to the victim, the content is executed by the victim's browser.
               
                  Type 2: Stored XSS (or Persistent) - 
               The application stores dangerous data in a database, message forum, visitor log, or other trusted data store. At a later time, the dangerous data is subsequently read back into the application and included in dynamic content. From an attacker's perspective, the optimal place to inject malicious content is in an area that is displayed to either many users or particularly interesting users. Interesting users typically have elevated privileges in the application or interact with sensitive data that is valuable to the attacker. If one of these users executes malicious content, the attacker may be able to perform privileged operations on behalf of the user or gain access to sensitive data belonging to the user. For example, the attacker might inject XSS into a log message, which might not be handled properly when an administrator views the logs.
            
               
                  Type 0: DOM-Based XSS - 
               In DOM-based XSS, the client performs the injection of XSS into the page; in the other types, the server performs the injection. DOM-based XSS generally involves server-controlled, trusted script that is sent to the client, such as Javascript that performs sanity checks on a form before the user submits it. If the server-supplied script processes user-supplied data and then injects it back into the web page (such as with dynamic HTML), then DOM-based XSS is possible.
            
            
            Once the malicious script is injected, the attacker can perform a variety of malicious activities. The attacker could transfer private information, such as cookies that may include session information, from the victim's machine to the attacker. The attacker could send malicious requests to a web site on behalf of the victim, which could be especially dangerous to the site if the victim has administrator privileges to manage that site. Phishing attacks could be used to emulate trusted web sites and trick the victim into entering a password, allowing the attacker to compromise the victim's account on that web site. Finally, the script could exploit a vulnerability in the web browser itself possibly taking over the victim's machine, sometimes referred to as "drive-by hacking."
            In many cases, the attack can be launched without the victim even being aware of it. Even with careful users, attackers frequently use a variety of methods to encode the malicious portion of the attack, such as URL encoding or Unicode, so the request looks less suspicious.
         
         

Fix information:
repo_url: https://github.com/TYPO3/html-sanitizer
commit_details: repo_url: https://github.com/TYPO3/html-sanitizer
author: Oliver Hader
author_date: 2023-07-25 09:14:55+02:00
msg: Merge pull request from GHSA-59jf-3q9v-rh6g

* [SECURITY] Properly encode noscript child nodes

The `<noscript>` element has a special behavior when
being evaluated in browsers, which depends on whether
script-parsing is enabled or disabled.

As a consequence this change will

* encode comment inner data, e.g. `<!-- <"comment"> -->`
  as `<!-- &lt;&quot;comment&quot;&gt -->`
* always encode tag attributes, e.g. `<p id="<value>">`
  as `<p id="&lt;value&gt;">`
* extend `Comment` and `CdataSection` to have a constructor
  (which triggers encoding per default) and to implement the
  `Behavior\HandlerInterface`
* add a new serializer option `encode_attributes`, which might
  basically be extracted to `Masterminds\HTML5`

* [TASK] Ensure attribute serialization preserves values as is

We don't want so called double-encoding – which is a valid
usecase when HTML describes how HTML is to be written – to
be automagically transformed to single encoded values,
as otherwise a valid input like

<a title="Insert &amp;amp; to write an &amp;"></a>
(Browser would show "Insert &amp; to write an &")

…would be changed to:

<a title="Insert &amp; to write an &amp;"></a>
(Browser would show "Insert & to write an &")

Also add tests for the attribute encoding we want:
 * Encode quotes, tags and stuff that might cause security issues
 * do not encode unnecessarily encode slashes or colons
   (like htmlentitites would do)

---------

Co-authored-by: Benjamin Franzke <ben@bnf.dev>
repository: repo_url: https://github.com/TYPO3/html-sanitizer
repo_name: TYPO3/html-sanitizer
description: HTML sanitizer, written in PHP, aiming to provide XSS-safe markup based on explicitly allowed tags, attributes and values.
repo_language: PHP
owner: TYPO3
file_changes: filename: Behavior.php
change_type: ModificationType.MODIFY
diff: @@ -15,6 +15,8 @@ declare(strict_types=1);
 namespace TYPO3\HtmlSanitizer;
 
 use LogicException;
+use TYPO3\HtmlSanitizer\Behavior\CdataSection;
+use TYPO3\HtmlSanitizer\Behavior\Comment;
 use TYPO3\HtmlSanitizer\Behavior\NodeInterface;
 use TYPO3\HtmlSanitizer\Behavior\Tag;
 
@@ -74,11 +76,16 @@ class Behavior
      * Node names as array index, e.g. `['strong' => new Tag('strong', '#comment' => new Comment()]`
      * @var array<string, ?NodeInterface>
      */
-    protected $nodes = [
+    protected $nodes = [];
+
+    public function __construct()
+    {
         // v2.1.0: adding `#comment` and `#cdata-section` hints for backward compatibility, will be removed with v3.0.0
-        '#comment' => null,
-        '#cdata-section' => null,
-    ];
+        $this->nodes = array_merge($this->nodes, [
+            '#comment' => new Comment(),
+            '#cdata-section' => new CdataSection(),
+        ]);
+    }
 
     public function withFlags(int $flags): self
     {
@@ -125,7 +132,6 @@ class Behavior
         if (!is_array($indexedNodes)) {
             return $this;
         }
-        $this->assertNodeUniqueness($indexedNodes);
         $target = clone $this;
         $target->nodes = array_merge($target->nodes, $indexedNodes);
         return $target;
@@ -136,9 +142,8 @@ class Behavior
         $names = array_map([$this, 'getNodeName'], $nodes);
         $filteredNodes = array_filter(
             $this->nodes,
-            static function (?NodeInterface $node, string $name) use ($nodes, $names) {
-                return $node === null && !in_array($name, $names, true)
-                    || $node !== null && !in_array($node, $nodes, true);
+            static function (NodeInterface $node, string $name) use ($nodes, $names) {
+                return !in_array($name, $names, true) && !in_array($node, $nodes, true);
             },
             ARRAY_FILTER_USE_BOTH
         );
@@ -247,23 +252,6 @@ class Behavior
         }
     }
 
-    /**
-     * @param array<string, NodeInterface> $nodes
-     */
-    protected function assertNodeUniqueness(array $nodes): void
-    {
-        $existingNodeNames = array_intersect_key(array_filter($this->nodes), $nodes);
-        if ($existingNodeNames !== []) {
-            throw new LogicException(
-                sprintf(
-                    'Cannot redeclare node names %s. Remove duplicates first',
-                    implode(', ', array_keys($existingNodeNames))
-                ),
-                1625391217
-            );
-        }
-    }
-
     protected function getNodeName(NodeInterface $node): string
     {
         return strtolower($node->getName());

programming_language: PHP
filename: CdataSection.php
change_type: ModificationType.MODIFY
diff: @@ -14,13 +14,36 @@ declare(strict_types=1);
 
 namespace TYPO3\HtmlSanitizer\Behavior;
 
+use DOMNode;
+use DOMText;
+use TYPO3\HtmlSanitizer\Behavior;
+use TYPO3\HtmlSanitizer\Context;
+
 /**
  * Model of CDATA node.
  */
-class CdataSection implements NodeInterface
+class CdataSection implements NodeInterface, HandlerInterface
 {
+    /**
+     * @var bool
+     */
+    protected $secure = true;
+
+    public function __construct(bool $secure = true)
+    {
+        $this->secure = $secure;
+    }
+
     public function getName(): string
     {
         return '#cdata-section';
     }
+
+    public function handle(NodeInterface $node, ?DOMNode $domNode, Context $context, Behavior $behavior = null): ?DOMNode
+    {
+        if (!$this->secure || $domNode === null) {
+            return $domNode;
+        }
+        return new DOMText(trim($domNode->nodeValue));
+    }
 }

programming_language: PHP
filename: Comment.php
change_type: ModificationType.MODIFY
diff: @@ -14,13 +14,36 @@ declare(strict_types=1);
 
 namespace TYPO3\HtmlSanitizer\Behavior;
 
+use DOMComment;
+use DOMNode;
+use TYPO3\HtmlSanitizer\Behavior;
+use TYPO3\HtmlSanitizer\Context;
+
 /**
  * Model of comment node.
  */
-class Comment implements NodeInterface
+class Comment implements NodeInterface, HandlerInterface
 {
+    /**
+     * @var bool
+     */
+    protected $secure = true;
+
+    public function __construct(bool $secure = true)
+    {
+        $this->secure = $secure;
+    }
+
     public function getName(): string
     {
         return '#comment';
     }
+
+    public function handle(NodeInterface $node, ?DOMNode $domNode, Context $context, Behavior $behavior = null): ?DOMNode
+    {
+        if (!$this->secure || $domNode === null) {
+            return $domNode;
+        }
+        return new DOMComment(htmlspecialchars($domNode->textContent, ENT_QUOTES, 'UTF-8', false));
+    }
 }

programming_language: PHP
filename: CommonBuilder.php
change_type: ModificationType.MODIFY
diff: @@ -14,11 +14,8 @@ declare(strict_types=1);
 
 namespace TYPO3\HtmlSanitizer\Builder;
 
-use DOMNode;
-use DOMText;
 use TYPO3\HtmlSanitizer\Behavior;
 use TYPO3\HtmlSanitizer\Behavior\Attr\UriAttrValueBuilder;
-use TYPO3\HtmlSanitizer\Behavior\NodeInterface;
 use TYPO3\HtmlSanitizer\Sanitizer;
 use TYPO3\HtmlSanitizer\Visitor\CommonVisitor;
 
@@ -83,8 +80,7 @@ class CommonBuilder implements BuilderInterface
             ->withName('common')
             ->withTags(...array_values($this->createBasicTags()))
             ->withTags(...array_values($this->createMediaTags()))
-            ->withTags(...array_values($this->createTableTags()))
-            ->withNodes(...array_values($this->createSpecialNodes()));
+            ->withTags(...array_values($this->createTableTags()));
     }
 
     protected function createBasicTags(): array
@@ -211,23 +207,6 @@ class CommonBuilder implements BuilderInterface
         return $tags;
     }
 
-    /**
-     * @return array<string, Behavior\NodeInterface>
-     */
-    protected function createSpecialNodes(): array
-    {
-        $nodes = [];
-        $nodes['#cdata-section'] = (new Behavior\NodeHandler(
-            new Behavior\CdataSection(),
-            new Behavior\Handler\ClosureHandler(
-                static function (NodeInterface $node, ?DOMNode $domNode) {
-                    return $domNode !== null ? new DOMText(trim($domNode->nodeValue)) : null;
-                }
-            )
-        ));
-        return $nodes;
-    }
-
     /**
      * @return Behavior\Attr[]
      */

programming_language: PHP
filename: Sanitizer.php
change_type: ModificationType.MODIFY
diff: @@ -41,6 +41,7 @@ class Sanitizer
     protected const mastermindsDefaultOptions = [
         // Whether the serializer should aggressively encode all characters as entities.
         'encode_entities' => false,
+        'encode_attributes' => true,
         // Prevents the parser from automatically assigning the HTML5 namespace to the DOM document.
         // (adjusted due to https://github.com/Masterminds/html5-php/issues/181#issuecomment-643767471)
         'disable_html_ns' => true,

programming_language: PHP
filename: Rules.php
change_type: ModificationType.MODIFY
diff: @@ -45,6 +45,11 @@ class Rules extends OutputRules implements RulesInterface
      */
     protected $initiator;
 
+    /**
+     * @var bool
+     */
+    protected $encodeAttributes;
+
     /**
      * @param Behavior $behavior
      * @param resource$output
@@ -66,6 +71,7 @@ class Rules extends OutputRules implements RulesInterface
     public function __construct($output, $options = [])
     {
         $this->options = (array)$options;
+        $this->encodeAttributes = !empty($options['encode_attributes']);
         parent::__construct($output, $this->options);
     }
 
@@ -158,6 +164,32 @@ class Rules extends OutputRules implements RulesInterface
         $this->wr($domNode->data);
     }
 
+    protected function enc($text, $attribute = false): string
+    {
+        if ($attribute && $this->encodeAttributes && !$this->encode) {
+            // In contrast to parent::enc() (when $this->encode is true),
+            // we are using htmlspecialchars() instead of htmlentities() as
+            // colons and slashes do not need to be aggressively escaped.
+            $value = htmlspecialchars(
+                $text,
+                ENT_HTML5 | ENT_SUBSTITUTE | ENT_QUOTES,
+                'UTF-8',
+                // $double_encode: true
+                // (name is misleading, it actually means: disable-automagic/always-encode)
+                // Our input is always entity decoded by the parser and we do not
+                // want to consider our input to possibly contain valid entities
+                // we rather want to treat it as pure text, that is *always* to be encoded.
+                true
+            );
+            // htmlspecialchars does escaping, but it doesn't match the requirements of
+            // HTML5 section 8.3 to ecape non breaking spaces
+            // https://www.w3.org/TR/2013/CR-html5-20130806/syntax.html#escapingString
+            $value = implode('&nbsp;', mb_split("\xc2\xa0", $value));
+            return $value;
+        }
+        return parent::enc($text, $attribute);
+    }
+
     /**
      * If the element has a declared namespace in the HTML, MathML or
      * SVG namespaces, we use the localName instead of the tagName.

programming_language: PHP
filename: CommonVisitor.php
change_type: ModificationType.MODIFY
diff: @@ -86,6 +86,9 @@ class CommonVisitor extends AbstractVisitor implements LoggerAwareInterface
             if (!$node->shallHandleFirst()) {
                 $domNode = $node->getHandler()->handle($node->getNode(), $domNode, $this->context, $this->behavior);
             }
+        } elseif ($node instanceof Behavior\HandlerInterface) {
+            $domNode = $node->handle($node, $domNode, $this->context, $this->behavior);
+            $domNode = $domNode instanceof DOMElement ? $this->enterDomElement($domNode, $node) : $domNode;
         } elseif ($domNode instanceof DOMElement) {
             $domNode = $this->enterDomElement($domNode, $node);
         }

programming_language: PHP
filename: BehaviorTest.php
change_type: ModificationType.MODIFY
diff: @@ -24,7 +24,6 @@ class BehaviorTest extends TestCase
     public function ambiguityIsDetectedDataProvider(): array
     {
         return [
-            [ ['same'], ['same'], 1625391217 ],
             [ ['same', 'same'], [], 1625591503 ],
             [ ['same', 'same'], ['same'], 1625591503 ],
             [ [], ['same', 'same'], 1625591503 ],

programming_language: PHP
filename: CommonBuilderTest.php
change_type: ModificationType.MODIFY
diff: @@ -256,13 +256,21 @@ class CommonBuilderTest extends TestCase
                 '<!-- #comment -->',
             ],
             '#910' => [
-                '<![CDATA[ #cdata ]]>',
-                '#cdata',
+                '<!-- <"comment"> -->',
+                '<!-- &lt;&quot;comment&quot;&gt; -->',
             ],
             '#911' => [
+                '<!-- &lt;&quot;comment&quot;&gt; -->',
+                '<!-- &lt;&quot;comment&quot;&gt; -->',
+            ],
+            '#915' => [
                 '#text',
                 '#text',
             ],
+            '#920' => [
+                '<![CDATA[ #cdata ]]>',
+                '#cdata',
+            ],
             '#921' => [
                 '<![CDATA[<any><span data-value="value"></any>*/]]>',
                 '&lt;any&gt;&lt;span data-value="value"&gt;&lt;/any&gt;*/',
@@ -287,6 +295,14 @@ class CommonBuilderTest extends TestCase
                 '<img src="/typo3.org/logo.svg"><any>value</any></img>',
                 '<img src="/typo3.org/logo.svg">&lt;any&gt;value&lt;/any&gt;',
             ],
+            '#935' => [
+                '<p class="</p><script>alert(1)">value</p>',
+                '<p class="&lt;/p&gt;&lt;script&gt;alert(1)">value</p>',
+            ],
+            '#936' => [
+                '<p class="{&quot;json&quot;:true}">value</p>',
+                '<p class="{&quot;json&quot;:true}">value</p>',
+            ],
         ];
     }
 

programming_language: PHP
filename: ScenarioTest.php
change_type: ModificationType.MODIFY
diff: @@ -231,23 +231,41 @@ class ScenarioTest extends TestCase
         return [
             'not allowed' => [
                 false,
+                null,
                 Behavior::BLUNT,
                 '<div><!-- before -->test<!-- after --></div>',
                 '<div>test</div>'
             ],
-            'allowed' => [
+            'allowed, insecure' => [
                 true,
+                false,
                 Behavior::BLUNT,
                 '<div><!-- before -->test<!-- after --></div>',
                 '<div><!-- before -->test<!-- after --></div>'
             ],
-            'not allowed, encoded' => [
+            'allowed, secure' => [
+                true,
+                true,
+                Behavior::BLUNT,
+                '<div><!-- before -->test<!-- after --></div>',
+                '<div><!-- before -->test<!-- after --></div>'
+            ],
+            'not allowed, encode invalid' => [
                 false,
+                null,
                 Behavior::ENCODE_INVALID_COMMENT,
                 '<div><!-- before -->test<!-- after --></div>',
                 '<div>&lt;!-- before --&gt;test&lt;!-- after --&gt;</div>',
             ],
-            'allowed, encoded' => [
+            'allowed, insecure, encode invalid' => [
+                true,
+                false,
+                Behavior::ENCODE_INVALID_COMMENT,
+                '<div><!-- before -->test<!-- after --></div>',
+                '<div><!-- before -->test<!-- after --></div>'
+            ],
+            'allowed, secure, encode invalid' => [
+                true,
                 true,
                 Behavior::ENCODE_INVALID_COMMENT,
                 '<div><!-- before -->test<!-- after --></div>',
@@ -260,13 +278,13 @@ class ScenarioTest extends TestCase
      * @test
      * @dataProvider commentsAreHandledDataProvider
      */
-    public function commentsAreHandled(bool $allowed, int $flags, string $payload, string $expectation): void
+    public function commentsAreHandled(bool $allowed, ?bool $secure, int $flags, string $payload, string $expectation): void
     {
         $behavior = (new Behavior())
             ->withFlags($flags)
             ->withName('scenario-test')
             ->withTags(new Behavior\Tag('div', Behavior\Tag::ALLOW_CHILDREN));
-        $comment = new Behavior\Comment();
+        $comment = new Behavior\Comment($secure ?? true);
         $behavior = $allowed ? $behavior->withNodes($comment) : $behavior->withoutNodes($comment);
         $sanitizer = new Sanitizer(
             $behavior,
@@ -280,27 +298,45 @@ class ScenarioTest extends TestCase
         return [
             'not allowed' => [
                 false,
+                null,
                 Behavior::BLUNT,
-                '<div><![CDATA[ before ]]>test<![CDATA[ after ]]></div>',
-                '<div>test</div>'
+                '<div><![CDATA[ before ]]>.test.<![CDATA[ after ]]></div>',
+                '<div>.test.</div>'
             ],
-            'allowed' => [
+            'allowed, insecure' => [
                 true,
+                false,
                 Behavior::BLUNT,
-                '<div><![CDATA[ before ]]>test<![CDATA[ after ]]></div>',
-                '<div><![CDATA[ before ]]>test<![CDATA[ after ]]></div>'
+                '<div><![CDATA[ before ]]>.test.<![CDATA[ after ]]></div>',
+                '<div><![CDATA[ before ]]>.test.<![CDATA[ after ]]></div>'
             ],
-            'not allowed, encoded' => [
+            'allowed, secure' => [
+                true,
+                true,
+                Behavior::BLUNT,
+                '<div><![CDATA[ before ]]>.test.<![CDATA[ after ]]></div>',
+                '<div>before.test.after</div>'
+            ],
+            'not allowed, encode invalid' => [
                 false,
+                null,
                 Behavior::ENCODE_INVALID_CDATA_SECTION,
-                '<div><![CDATA[ before ]]>test<![CDATA[ after ]]></div>',
-                '<div>&lt;![CDATA[ before ]]&gt;test&lt;![CDATA[ after ]]&gt;</div>',
+                '<div><![CDATA[ before ]]>.test.<![CDATA[ after ]]></div>',
+                '<div>&lt;![CDATA[ before ]]&gt;.test.&lt;![CDATA[ after ]]&gt;</div>',
             ],
-            'allowed, encoded' => [
+            'allowed, insecure, encode invalid' => [
                 true,
+                false,
                 Behavior::ENCODE_INVALID_CDATA_SECTION,
-                '<div><![CDATA[ before ]]>test<![CDATA[ after ]]></div>',
-                '<div><![CDATA[ before ]]>test<![CDATA[ after ]]></div>'
+                '<div><![CDATA[ before ]]>.test.<![CDATA[ after ]]></div>',
+                '<div><![CDATA[ before ]]>.test.<![CDATA[ after ]]></div>'
+            ],
+            'allowed, secure, encode invalid' => [
+                true,
+                true,
+                Behavior::ENCODE_INVALID_CDATA_SECTION,
+                '<div><![CDATA[ before ]]>.test.<![CDATA[ after ]]></div>',
+                '<div>before.test.after</div>'
             ],
         ];
     }
@@ -309,13 +345,13 @@ class ScenarioTest extends TestCase
      * @test
      * @dataProvider cdataSectionsAreHandledDataProvider
      */
-    public function cdataSectionsAreHandled(bool $allowed, int $flags, string $payload, string $expectation): void
+    public function cdataSectionsAreHandled(bool $allowed, ?bool $secure, int $flags, string $payload, string $expectation): void
     {
         $behavior = (new Behavior())
             ->withFlags($flags)
             ->withName('scenario-test')
             ->withTags(new Behavior\Tag('div', Behavior\Tag::ALLOW_CHILDREN));
-        $cdataSection = new Behavior\CdataSection();
+        $cdataSection = new Behavior\CdataSection($secure ?? true);
         $behavior = $allowed ? $behavior->withNodes($cdataSection) : $behavior->withoutNodes($cdataSection);
         $sanitizer = new Sanitizer(
             $behavior,
@@ -482,4 +518,136 @@ class ScenarioTest extends TestCase
         );
         self::assertSame($expectation, $sanitizer->sanitize($payload));
     }
+
+    public static function attributesAreEncodedDataProvider(): \Generator
+    {
+        yield 'preserve entities' => [
+	        '<a title="Insert &amp;"></a>',
+	        '<a title="Insert &amp;"></a>',
+        ];
+        yield 'encode single quotes' => [
+	        '<a title="\'"></a>',
+	        '<a title="&apos;"></a>',
+        ];
+        yield 'encode single quotes from entity' => [
+	        '<a title="&#039;"></a>',
+	        '<a title="&apos;"></a>',
+        ];
+        yield 'encode double quotes' => [
+	        "<a title='" . '"' . "'></a>",
+	        '<a title="&quot;"></a>',
+        ];
+        yield 'preserve double quote encoding' => [
+	        '<a title="&quot;"></a>',
+	        '<a title="&quot;"></a>',
+        ];
+        yield 'preserve double encoded entities' => [
+	        '<a title="Insert &amp;amp; to write an &amp;"></a>',
+	        '<a title="Insert &amp;amp; to write an &amp;"></a>',
+        ];
+        yield 'preserve URLs without "agressive" entity encoding' => [
+	        '<a title="https://example.com/"></a>',
+	        '<a title="https://example.com/"></a>',
+        ];
+        yield 'encode tag specifiers' => [
+            '<a id="</noscript><script>alert(1)</script>"></a>',
+            '<a id="&lt;/noscript&gt;&lt;script&gt;alert(1)&lt;/script&gt;"></a>',
+        ];
+        // Invalid input seems to be removed during parsing step (where?)
+        // therefore ENT_SUBSTITUTE can not operate during serialization
+        // @todo: check masterminds/html5-php whether that behavior is
+        // intended
+        //yield 'substitute invalid unicode in attributes' => [
+        //    "<a title='Hello \x80, Good morning'></a>",
+        //    "<a title='Hello \xEF\xBF\xBD, Good morning'></a>",
+        //];
+        yield 'escape non breaking space' => [
+            "<a title='Hello\xc2\xa0World'></a>",
+            '<a title="Hello&nbsp;World"></a>',
+        ];
+        yield 'encodes json values' => [
+            "<div data-value='{\"Hello\":[{\"w\":\"o\",\"r\":\"ld\"}]}'></a>",
+            '<div data-value="{&quot;Hello&quot;:[{&quot;w&quot;:&quot;o&quot;,&quot;r&quot;:&quot;ld&quot;}]}"></div>'
+        ];
+        yield 'encodes json values containing html' => [
+            "<div data-value='{\"Hello\":\"&lt;span&gt;World&lt;\/span&gt;\"}'></div>",
+            '<div data-value="{&quot;Hello&quot;:&quot;&lt;span&gt;World&lt;\/span&gt;&quot;}"></div>'
+        ];
+
+    }
+
+    /**
+     * @test
+     * @dataProvider attributesAreEncodedDataProvider
+     */
+    public function attributesAreEncoded(string $payload, string $expectation): void
+    {
+        $behavior = (new Behavior())
+            ->withFlags(Behavior::ENCODE_INVALID_TAG | Behavior::REMOVE_UNEXPECTED_CHILDREN)
+            ->withName('scenario-test')
+            ->withTags(
+                (new Behavior\Tag('a', Behavior\Tag::ALLOW_CHILDREN))->addAttrs(
+                    new Behavior\Attr('id'),
+                    new Behavior\Attr('title')
+                ),
+                (new Behavior\Tag('div', Behavior\Tag::ALLOW_CHILDREN))->addAttrs(
+                    new Behavior\Attr('data-value')
+                )
+            );
+
+        $sanitizer = new Sanitizer(
+            $behavior,
+            new CommonVisitor($behavior)
+        );
+        self::assertSame($expectation, $sanitizer->sanitize($payload));
+    }
+
+    public static function specialTagsAreHandledDataProvider(): \Generator
+    {
+        yield 'noscript attribute' => [
+            '<noscript><p id="</noscript><script>alert(1)</script>"></p>',
+            '<noscript><p id="&lt;/noscript&gt;&lt;script&gt;alert(1)&lt;/script&gt;"></p></noscript>',
+        ];
+        yield 'noscript namespaced attribute' => [
+            '<noscript><p test:id="</noscript><script>alert(1)</script>"></p>',
+            '<noscript><p test:id="&lt;/noscript&gt;&lt;script&gt;alert(1)&lt;/script&gt;"></p></noscript>',
+        ];
+        yield 'noscript comment' => [
+            '<noscript><!--</noscript><script>alert(2)</script>--></noscript>',
+            '<noscript><!--&lt;/noscript&gt;&lt;script&gt;alert(2)&lt;/script&gt;--></noscript>',
+        ];
+        yield 'noscript raw text' => [
+            '<noscript><style></noscript><script>alert(3)</script>',
+            '<noscript><style>&lt;/noscript&gt;&lt;script&gt;alert(3)&lt;/script&gt;</style></noscript>',
+        ];
+        yield 'noscript event attribute' => [
+            '<noscript><p onmouseover="alert(4)">value</p></noscript>',
+            '<noscript><p>value</p></noscript>',
+        ];
+    }
+
+    /**
+     * @test
+     * @dataProvider specialTagsAreHandledDataProvider
+     */
+    public function specialTagsAreHandled(string $payload, string $expectation): void
+    {
+        $behavior = (new Behavior())
+            ->withFlags(Behavior::ENCODE_INVALID_TAG | Behavior::REMOVE_UNEXPECTED_CHILDREN)
+            ->withName('scenario-test')
+            ->withTags(
+                (new Behavior\Tag('style', Behavior\Tag::ALLOW_CHILDREN)),
+                (new Behavior\Tag('noscript', Behavior\Tag::ALLOW_CHILDREN)),
+                (new Behavior\Tag('p', Behavior\Tag::ALLOW_CHILDREN))->addAttrs(
+                    new Behavior\Attr('id'),
+                    new Behavior\Attr('test:id')
+                )
+            );
+
+        $sanitizer = new Sanitizer(
+            $behavior,
+            new CommonVisitor($behavior)
+        );
+        self::assertSame($expectation, $sanitizer->sanitize($payload));
+    }
 }

programming_language: PHP