Commit 26223d3d97 for wordpress.org

commit 26223d3d97c2fc6279c7bbd886a13df39c01557f
Author: dmsnell <dmsnell@git.wordpress.org>
Date:   Thu Dec 3 20:10:05 2026 +0000

    KSES: Normalize text content while preserving escaped characters.

    When `wp_kses()` was rewritten to rely on the HTML API for its HTML parsing, a decision was made to fully-normalize text nodes, un-escaping text and re-escaping deterministically. This raised several issues relating to syntax which had been intentionally esacped. Notably, `wp_kses()` could create Shortcodes where they had been prevented by escaping the square brackets.

    This patch walks back most of that change, preserving text that has been escaped. However, it still applies a weakened normalization to prevent downstream risk. Namely, it ensures the following properties of the output HTML text nodes and attribute values:

     - Escaped characters remain escaped.
     - Un-escaped syntax characters will be escaped.
     - All character references will terminate in a semicolon to remove ambiguity.
     - All leading zero digits are removed from numeric character references.
     - Hexadecimal numeric character comprise a lowercase `x` and uppercase hex digits.
     - Invalid numeric character references are replced by the Unicode Replacement Character.

    Given the undecidedness of knowing which original characters were escaped when attribute values are modified by filtering funtions, if an attribute value is changed during sanitization, it will be entirely re-encoded as it was before this patch.

    Developed in: https://github.com/WordPress/wordpress-develop/pull/15971
    Discussed in: https://core.trac.wordpress.org/ticket/66673

    Follow-up to r64233.

    Props abcd95, dmsnell, jonsurrell, mmtr86, salvatorecorsi, therssoftware.
    Fixes #66673, See #66208.

    Built from https://develop.svn.wordpress.org/trunk@65901


    git-svn-id: http://core.svn.wordpress.org/trunk@64930 1a063a9b-81f0-0310-95a4-ce76da25c4cd

diff --git a/wp-includes/kses.php b/wp-includes/kses.php
index c92f6d9e12..cf8489406e 100644
--- a/wp-includes/kses.php
+++ b/wp-includes/kses.php
@@ -1197,43 +1197,165 @@ function wp_sanitize_html_kses( $content, $allowed_html, $allowed_protocols = ar
 		}

 		/**
-		 * Sets the value of a given HTML attribute, adjusting URL attributes
-		 * to ensure compatibility with legacy {@see wp_kses()} behavior.
+		 * Returns a representation of the given substring of input HTML text content where the
+		 * character references are normalized and unescaped syntax characters are escaped.
 		 *
 		 * @since 7.2.0
 		 * @access private
+		 * @ignore
 		 *
-		 * @param string      $name  Name of HTML attribute to set.
-		 * @param string|true $value Value to set; `true` for boolean attribute.
-		 * @return bool Whether the attribute was set.
+		 * @param 'data'|'attribute' $context Apply decoding rules pertaining to the appropriate context.
+		 * @param string             $html    Raw HTML document containing the referenced text content.
+		 * @param int                $start   The text span starts here.
+		 * @param int                $length  The text span extends this many bytes.
+		 * @return string Normalized text node content.
 		 */
-		public function set_attribute( $name, $value ): bool {
-			$lower_name = strtolower( $name );
-			$is_url_ish = in_array( $lower_name, $this->uri_attributes, true );
+		private static function normalize_text( string $context, string $html, int $start, int $length ): string {
+			$output     = '';
+			$ref_length = 0;
+			$at         = $start;
+			$was_at     = $start;
+			$end        = $start + $length;
+
+			while ( $at < $end ) {
+				$next_at = $at + strcspn( $html, '&', $at, $end - $at );
+				if ( $next_at >= $end ) {
+					break;
+				}

-			if ( ! $is_url_ish || ! is_string( $value ) ) {
-				return parent::set_attribute( $name, $value );
-			}
+				$decoded = WP_HTML_Decoder::read_character_reference( $context, $html, $next_at, $ref_length );

-			$escaped = strtr(
-				$value,
-				array(
-					'<' => '&lt;',
-					'>' => '&gt;',
-					'&' => '&amp;',
-					'"' => '&quot;',
-					"'" => '&apos;',
-				)
-			);
+				/**
+				 * Decoding past the end of the text span might return a different decode than
+				 * one which decodes a truncated string.
+				 *
+				 * In the cases of a failure to decode, the length of seven bytes comes from the
+				 * fact that the longest matchable named character references containing no
+				 * semicolons are seven ASCII bytes long. It’s exactly these situations within
+				 * attributes where the following character might impact what’s decoded; this is
+				 * what {@see WP_HTML_Decoder::read_character_reference()} might see since it
+				 * doesn’t allow specifying a final offset at which to stop searching.
+				 *
+				 * Therefore, if a match failed within that distance from the end inside an HTML
+				 * attribute’s value, then it is best to cut off the trailing part of the input
+				 * and normalize that separately.
+				 *
+				 * Example:
+				 *
+				 *     '&middot=' is rejected when the length is seven because the following '='
+				 *                is not unambiguous. However, that '=' was not part of the span
+				 *                of text to decode.
+				 *
+				 *     '&middot' on the other hand, has no ambiguous follower, and will thus be
+				 *               decoded in attribute value contexts.
+				 */
+				$remaining_length = $start + $length - $next_at;
+				if (
+					$end < strlen( $html ) &&
+					(
+						( null !== $decoded && $ref_length > $remaining_length ) ||
+						( null === $decoded && 'attribute' === $context && $remaining_length <= 7 )
+					)
+				) {
+					$output .= substr( $html, $was_at, $next_at - $was_at );
+					$output .= self::normalize_text( $context, substr( $html, $next_at, $remaining_length ), 0, $remaining_length );
+					$was_at  = $end;
+					break;
+				}

-			// Set a benign placeholder to replace below.
-			if ( ! parent::set_attribute( $name, true ) ) {
-				return false;
+				/*
+				 * Failure to decode implies that there’s an unescaped AMPERSAND character; escape it.
+				 */
+				if ( null === $decoded ) {
+					$output .= substr( $html, $was_at, $next_at - $was_at );
+					$output .= '&amp;';
+					$at      = $next_at + 1;
+					$was_at  = $at;
+					continue;
+				}
+
+				$has_semicolon = ';' === $html[ $next_at + $ref_length - 1 ];
+
+				if ( '#' === $html[ $next_at + 1 ] ) {
+					/*
+					 * Given that the character decoded at least partially, there are
+					 * certain guarantees on the syntax forms here. The only exceptions
+					 * are where the decoder returns U+FFFD because the digits failed
+					 * to represent a valid code point.
+					 */
+					$digits_end     = $next_at + $ref_length - ( $has_semicolon ? 1 : 0 );
+					$hex_sigil      = $html[ $next_at + 2 ];
+					$is_hex         = 'x' === $hex_sigil || 'X' === $hex_sigil;
+					$digits_at      = $next_at + ( $is_hex ? 3 : 2 );
+					$zero_count     = strspn( $html, '0', $digits_at, $digits_end - $digits_at );
+					$non_zero_start = $digits_at + $zero_count;
+					$digit_count    = $digits_end - $non_zero_start;
+					$has_no_lowers  = strcspn( $html, 'abcdef', $digits_at + $zero_count, $digit_count ) === $digit_count;
+
+					/*
+					 * Only an actual numeric character reference indicating U+FFFD should be retained;
+					 * other malformed sequences should actually receive the U+FFFD in the output.
+					 */
+					if (
+						"\u{FFFD}" === $decoded &&
+						( 0 === $digit_count || 0 !== substr_compare( $html, $is_hex ? 'FFFD' : '65533', $digits_at + $zero_count, $digit_count, true ) )
+					) {
+						$output .= substr( $html, $was_at, $next_at - $was_at );
+						$output .= "\u{FFFD}";
+						$at      = $next_at + $ref_length;
+						$was_at  = $at;
+						continue;
+					}
+
+					// Fully-normalized numeric character references may be passed through.
+					if ( 0 === $zero_count && $has_semicolon && ( ! $is_hex || ( 'x' === $hex_sigil && $has_no_lowers ) ) ) {
+						$at = $next_at + $ref_length;
+						continue;
+					}
+
+					// Otherwise rebuild them.
+					$sigil   = $is_hex ? 'x' : '';
+					$digits  = strtoupper( substr( $html, $digits_at + $zero_count, $digit_count ) );
+					$output .= substr( $html, $was_at, $next_at - $was_at );
+					$output .= "&#{$sigil}{$digits};";
+					$at      = $next_at + $ref_length;
+					$was_at  = $at;
+					continue;
+				}
+
+				// Semicolon-terminated named character references may pass through.
+				if ( $has_semicolon ) {
+					$at = $next_at + $ref_length;
+					continue;
+				}
+
+				// Otherwise add the missing semicolon.
+				$output .= substr( $html, $was_at, $next_at + $ref_length - $was_at );
+				$output .= ';';
+				$at      = $next_at + $ref_length;
+				$was_at  = $at;
 			}

-			$this->lexical_updates[ $lower_name ]->text = " {$lower_name}=\"{$escaped}\"";
+			if ( $start === $was_at ) {
+				$output = substr( $html, $start, $length );
+			} elseif ( $was_at < $end ) {
+				$output .= substr( $html, $was_at, $end - $was_at );
+			}

-			return true;
+			return strtr(
+				$output,
+				'attribute' === $context
+					? array(
+						'<' => '&lt;',
+						'>' => '&gt;',
+						'"' => '&quot;',
+						"'" => '&apos;',
+					)
+					: array(
+						'<' => '&lt;',
+						'>' => '&gt;',
+					)
+			);
 		}

 		/**
@@ -1454,6 +1576,7 @@ function wp_sanitize_html_kses( $content, $allowed_html, $allowed_protocols = ar
 		public function sanitize() {
 			$template_depth            = 0;
 			$output                    = '';
+			$input_special_newline_at  = PHP_INT_MIN;
 			$special_newline_at        = PHP_INT_MIN;
 			$foreign_content_starts_at = PHP_INT_MAX;
 			$open_blocks               = array();
@@ -1485,6 +1608,10 @@ function wp_sanitize_html_kses( $content, $allowed_html, $allowed_protocols = ar
 				$is_closer  = $this->is_tag_closer();
 				$here       = $this->get_span();

+				if ( ! $is_closer && 'html' === $namespace && ( 'PRE' === $token_name || 'LISTING' === $token_name ) ) {
+					$input_special_newline_at = $here->start + $here->length;
+				}
+
 				/*
 				 * Prevent allowing NOSCRIPT elements whose parsing rules change
 				 * based on whether the scripting flag is enabled in a browser.
@@ -1555,22 +1682,7 @@ function wp_sanitize_html_kses( $content, $allowed_html, $allowed_protocols = ar
 					( ! $is_closer && $is_in_svg_html_integration_point )
 				);

-				/*
-				 * While content inside integration points is generally not allowed here,
-				 * character data inside the MathML text elements _is_ allowed. This is
-				 * because the rules only change slightly: NULL bytes are removed instead
-				 * of being replaced with the Unicode replacement character U+FFFD; and
-				 * active formats are reconstructed. The format reconstruction doesn’t
-				 * occur here but a browser will still do so; this sanitizer is generally
-				 * unaware of nesting structure.
-				 */
-				if ( $is_in_text_integration_point && '#text' === $token_type ) {
-					$this->change_parsing_namespace( 'html' );
-					$text = $this->get_modifiable_text();
-					$this->change_parsing_namespace( $namespace );
-				} else {
-					$text = $this->get_modifiable_text();
-				}
+				$text = ( '#text' !== $token_type ) ? $this->get_modifiable_text() : '';

 				/*
 				 * Enter the foreign content and change the parsing namespace
@@ -1646,26 +1758,43 @@ function wp_sanitize_html_kses( $content, $allowed_html, $allowed_protocols = ar
 							break;
 						}

-						$needs_special_newline = (
-							strlen( $output ) === $special_newline_at &&
-							1 === strspn( $text, "\n\r", 0, 1 )
-						);
+						$text = self::normalize_text( 'data', $this->html, $here->start, $here->length );
+						$text = str_replace( array( "\r\n", "\r" ), "\n", $text );

-						$text = strtr(
-							$text,
-							array(
-								"\r" => '&#xD;',
-								'<'  => '&lt;',
-								'&'  => '&amp;',
-								'>'  => '&gt;',
-							)
-						);
+						/*
+						 * A PRE or LISTING element consumes a leading newline even if stripped from the
+						 * output, so detect and remove one, remembering the original leading newline.
+						 */
+						$special_newline = "\n";
+						if ( $here->start === $input_special_newline_at ) {
+							$starting_char  = $text[0] ?? '';
+							$newline_length = 1;
+							if ( '&' === $starting_char ) {
+								$starting_char = WP_HTML_Decoder::read_character_reference( 'data', $text, 0, $newline_length );
+							}

-						if ( $needs_special_newline ) {
-							$output .= "\n{$text}";
-						} else {
-							$output .= $text;
+							if ( "\n" === $starting_char ) {
+								$special_newline = substr( $text, 0, $newline_length );
+								$text            = substr( $text, $newline_length );
+							}
 						}
+
+						$text = ( 'html' === $namespace || $is_in_text_integration_point )
+							? str_replace( "\x00", '', $text )
+							: str_replace( "\x00", "\u{FFFD}", $text );
+
+						if ( strlen( $output ) === $special_newline_at && strlen( $text ) > 0 ) {
+							$starting_char = $text[0];
+							if ( '&' === $starting_char ) {
+								$starting_char = WP_HTML_Decoder::read_character_reference( 'data', $text );
+							}
+
+							if ( 1 === strspn( $starting_char, "\r\n", 0, 1 ) ) {
+								$output .= $special_newline;
+							}
+						}
+
+						$output .= $text;
 						break;

 					/*
@@ -1951,8 +2080,9 @@ function wp_sanitize_html_kses( $content, $allowed_html, $allowed_protocols = ar
 									continue;
 								}

-								$raw_value = $this->get_attribute( $name );
-								$value     = is_string( $raw_value ) ? $raw_value : '';
+								$raw_value   = $this->get_attribute( $name );
+								$value       = is_string( $raw_value ) ? $raw_value : '';
+								$given_value = $value;

 								// Process the style attribute through CSS sanitization.
 								if ( 'style' === $name ) {
@@ -1987,13 +2117,68 @@ function wp_sanitize_html_kses( $content, $allowed_html, $allowed_protocols = ar
 									}
 								}

-								$did_set = ( true === $raw_value && '' === $value )
-									? $tag_maker->set_attribute( $name, true )
-									: $tag_maker->set_attribute( $name, $value );
+								// All updates are enqueued as boolean placeholders.
+								if ( ! $tag_maker->set_attribute( $name, true ) ) {
+									continue;
+								}
+
+								$should_remain_true = true === $raw_value && '' === $value;

-								if ( $did_set ) {
-									unset( $required_attributes[ $name ] );
+								if ( ! $should_remain_true ) {
+									$lower_name = strtolower( $name );
+									$escaped    = null;
+
+									/*
+									 * If the value did not change through sanitization, then preserve
+									 * as much of the original escaping as possible.
+									 *
+									 * Fetch the original value by modifying it from the input string,
+									 * reading the span, and then erasing the update.
+									 */
+									if (
+										is_string( $raw_value ) &&
+										$given_value === $value &&
+										$this->set_attribute( $lower_name, true )
+									) {
+										$original     = $this->lexical_updates[ $lower_name ];
+										$original_at  = $original->start;
+										$original_end = $original->start + $original->length;
+										unset( $this->lexical_updates[ $lower_name ] );
+
+										// Assignment follows the first `=` not at the beginning of the attribute name.
+										$equals_at = $original_at + 1 + strcspn( $this->html, '=', $original_at + 1, $original->length - 1 );
+										if ( $equals_at < $original_end && 1 === strspn( $this->html, '"\'', $original_end - 1, 1 ) ) {
+											// This might be a quoted attribute; find the opening quote.
+											$quoting_at = $equals_at + 1 + strspn( $this->html, " \t\f\r\n", $equals_at + 1, $original_end - $equals_at - 1 );
+											if ( $this->html[ $original_end - 1 ] === $this->html[ $quoting_at ] ) {
+												$escaped = self::normalize_text( 'attribute', $this->html, $quoting_at + 1, $original_end - $quoting_at - 2 );
+												$escaped = str_replace( "\r\n", "\n", $escaped );
+												$escaped = str_replace( "\r", "\n", $escaped );
+												$escaped = str_replace( "\x00", "\u{FFFD}", $escaped );
+											}
+										}
+									}
+
+									if ( ! isset( $escaped ) ) {
+										$escaped = strtr(
+											$value,
+											array(
+												"\r" => '&#xD;',
+												'"'  => '&quot;',
+												"'"  => '&apos;',
+												'<'  => '&lt;',
+												'&'  => '&amp;',
+												'>'  => '&gt;',
+												'['  => '&#x5B;',
+												']'  => '&#x5D;',
+											)
+										);
+									}
+
+									$tag_maker->lexical_updates[ $lower_name ]->text = " {$lower_name}=\"{$escaped}\"";
 								}
+
+								unset( $required_attributes[ $name ] );
 							}
 						}

@@ -2029,18 +2214,26 @@ function wp_sanitize_html_kses( $content, $allowed_html, $allowed_protocols = ar

 								case 'TEXTAREA':
 								case 'TITLE':
-									/*
-									 * RCDATA nodes can be safely escaped, but this must be
-									 * done after enqueuing the update to avoid double-escaping.
-									 */
-									$tag_maker->set_modifiable_text( $text );
-									$tag_maker->lexical_updates['modifiable text']->text = strtr(
-										$tag_maker->lexical_updates['modifiable text']->text,
+									// Extract the raw text span via temporarily modifying the modifiable text.
+									$this->set_modifiable_text( '' );
+									$raw_text_bounds = $this->lexical_updates['modifiable text'];
+									unset( $this->lexical_updates['modifiable text'] );
+
+									$normalized_text = self::normalize_text( 'data', $this->html, $raw_text_bounds->start, $raw_text_bounds->length );
+									$normalized_text = strtr(
+										$normalized_text,
 										array(
 											"\x00" => "\u{FFFD}",
 											"\r"   => '&#xD;',
 										)
 									);
+
+									/*
+									 * RCDATA nodes can be safely escaped, but this must be
+									 * done after enqueuing the update to avoid double-escaping.
+									 */
+									$tag_maker->set_modifiable_text( '' );
+									$tag_maker->lexical_updates['modifiable text']->text = $normalized_text;
 									break;

 								case 'NOEMBED':
diff --git a/wp-includes/version.php b/wp-includes/version.php
index 4e50c3aa36..138555e875 100644
--- a/wp-includes/version.php
+++ b/wp-includes/version.php
@@ -16,7 +16,7 @@
  *
  * @global string $wp_version
  */
-$wp_version = '7.3-alpha-65900';
+$wp_version = '7.3-alpha-65901';

 /**
  * Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.