Make WordPress Core

Opened 5 weeks ago

Closed 4 weeks ago

#66308 closed defect (bug) (wontfix)

wp_inline_script_attributes() filter may receive different data from tag contents

Reported by: jonsurrell Owned by: jonsurrell
Priority: normal Milestone:
Component: Script Loader Version: 7.0
Severity: normal Keywords: has-patch
Cc: Focuses:

Description

wp_get_inline_script_tag() passes $data to the wp_inline_script_attributes filter, then sets it as the script text. Since r61477, set_modifiable_text() escapes <script and </script in JavaScript and JSON, so the printed text can differ from the $data the filter received. A callback that derives an attribute from the text, such as a CSP hash, produces a value that does not match the element, and the browser blocks the script.

The wp_get_inline_style_tag() proposed in #51325 uses the same order.

Demo

Run this in the ​PHP playground. The filter sends a CSP header with a SHA-256 hash of each $data it receives. The second tag is built in the proposed order.

<?php
require '/wordpress/wp-load.php';

function csp_hash_filter( array $attrs, string $data ): array {
        static $hashes = array();
        $hashes[] = "'sha256-" . base64_encode( hash( 'sha256', $data, true ) ) . "'";

        // Replaces the previous header, so the last call sends every hash.
        header( 'Content-Security-Policy: script-src ' . implode( ' ', $hashes ) );

        return $attrs;
}
add_filter( 'wp_inline_script_attributes', 'csp_hash_filter', 10, 2 );

$data = 'console.log( "Script close tag: </script>" );';

// Current order: the filter receives $data, then the text is escaped.
$tag = wp_get_inline_script_tag( $data );

// Proposed order: set the text, then filter the escaped text.
$p = new WP_HTML_Tag_Processor( '<script></script>' );
$p->next_tag();
$p->set_modifiable_text( "\nconsole.log( 'this will run' );\n{$data}\n" );
$attrs = apply_filters( 'wp_inline_script_attributes', array(), $p->get_modifiable_text() );
foreach ( $attrs as $name => $value ) {
        $p->set_attribute( $name, $value );
}

wp_print_inline_script_tag( 'console.log( "control" );' );
echo $tag;
echo $p->get_updated_html();

Console:

control
Executing inline script violates the following Content Security Policy directive 'script-src 'sha256-ta8ExYU6WED0Qq+0oUgCHBRgM+E2psIYiLIUE/HMppE=' 'sha256-lPZFdb/Bh8cW6dGaOKYSrc90IeCmfrc2rzM9nqcDva4=' 'sha256-/oR+0ngC8GFwuvt1Iixz+NvT5farfxZXcehSaViuGzM=''. Either the 'unsafe-inline' keyword, a hash ('sha256-FmwQ15jlLhrBUbl+sH5AQcSzx2JEW0USL4HgkmQIexw='), or a nonce ('nonce-...') is required to enable inline execution. The action has been blocked.
this will run
Script close tag: </script>

The filter hashed </script>; the browser hashed the printed </\u0073cript>.

Proposed fix

Set the modifiable text first and return '' if that fails, pass get_modifiable_text() to the filter, then set the attributes. SCRIPT and STYLE are atomic tokens, so no seek is needed. get_modifiable_text() also converts CR and CRLF to LF, so it returns the text the browser hashes. Callbacks would then receive the escaped text, which differs from today only when the text contains <script or </script.

Change History (12)

This ticket was mentioned in ​PR #14274 on ​WordPress/wordpress-develop by ​@jonsurrell.


5 weeks ago
#1

  • Keywords has-patch has-unit-tests added

wp_get_inline_script_tag() passed $data to the wp_inline_script_attributes filter and then set it as the SCRIPT text. Since r61477, set_modifiable_text() escapes <script and </script in JavaScript and JSON, so the printed text can differ from what the filter received. A callback that derives an attribute from the text, such as a CSP hash, produces a value that does not match the element, and the browser blocks the script.

The filter now receives get_modifiable_text(): the text as a browser parses it from the printed tag, with <script and </script escaped and CR and CRLF normalized to LF.

The Tag Processor chooses the escaping from the type and language attributes when the text is set, so the tag is built from the caller's attributes first, the filter runs on that text, and when the filter changes the attributes the tag is built again from the filtered array. Two consequences:

  • The filter no longer runs when the caller's attributes make the data unembeddable. The function ran it and then returned '' before.
  • A callback that changes type or language between a recognized and an unrecognized content type changes the escaping of the printed text after the filter saw it. The filter docblock states this.

Tests cover the escaped text, newline normalization, attribute replacement, and both failure paths.

Use of AI Tools

AI assistance: Yes
Tool(s): Claude Code
Model(s): Claude Fable 5.1
Used for: Implementation, tests, review and description.

​@jonsurrell commented on ​PR #14274:


5 weeks ago
#2

This is a tricky problem because the resulting script tag contents depend on the type (or language) attribute to apply escaping rules to the content.

If the filter is applied first, the filter function may be passed script data that isn't what's actually printed. But if the filter is applied after, then the attributes necessary for escaping may not have been applied so escaping may be applied incorrectly or not applied at all.

I don't think the same problem applies to ​https://github.com/WordPress/wordpress-develop/pull/13250 because the content type of style tags is CSS.

​@jonsurrell commented on ​PR #14274:


5 weeks ago
#3

This seems like a change in contract. Instead I think we should document the limitation and consider workarounds if it's essential that the filter see the exact contents that will be printed in the script tag.

#4 @jonsurrell
5 weeks ago

I think this just needs a documentation change that the actual content may change after it's sent to the filter.

#5 @westonruter
5 weeks ago

  • Keywords needs-patch added; has-patch has-unit-tests removed

If the filter is applied first, the filter function may be passed script data that isn't what's actually printed. But if the filter is applied after, then the attributes necessary for escaping may not have been applied so escaping may be applied incorrectly or not applied at all.

Oh, good point. For example, the Web Worker Offloading plugin which supplies a type of text/partytown:

​https://github.com/WordPress/performance/blob/3517200c00ed0cbbc628842fc1b32947dbb4f711/plugins/web-worker-offloading/helper.php#L169-L190

What if there was a new helper function that escaped the script content for a fixed type that cannot be filtered? The documentation could reference that in any attribute filters when they are changing the type in addition to applying a CSP hash. Otherwise, if they're just adding a CSP nonce then this is irrelevant.

#6 @westonruter
5 weeks ago

  • Owner set to jonsurrell

This ticket was mentioned in ​PR #14281 on ​WordPress/wordpress-develop by ​@jonsurrell.


5 weeks ago
#7

  • Keywords has-patch added; needs-patch removed

The wp_inline_script_attributes filter receives $data before set_modifiable_text() escapes <script and </script in JavaScript and JSON script text (since r61477), so a callback that derives a value from $data, such as a CSP hash, may not match the printed text. Document this on the filter's $data parameter.

Use of AI Tools

AI assistance: Yes
Tool(s): Claude Code
Model(s): Claude Fable 5.1
Used for: Docblock wording and description.

#8 follow-up: @jonsurrell
5 weeks ago

At this point I think a documentation change to note the limitation and suggest a workaround in niche cases is the best thing to do. It's a limitation we're aware of at this point, but it doesn't seem to impact users. At least I haven't seen any reports of the issue. ​This PR makes a documentation change.


Some conversations on r61477 were about ​registering escaping functions for different types (credit @dmsnell). The idea is that plugins could register escaping functions for different MIME types and the HTML API could apply them. This is also tied to having a proper MIME parsing (#64427).


I explored this a bit more and discovered that this isn't limited to escaping, so this problem is not new. It seems to impact any of the ways that the contents may differ when inspected by the browser parsing the HTML:

<?php
require '/wordpress/wp-load.php';

$data = "console.log(`#Processed#\n\nCRLF:\r\nNUL:\0\nSCRIPT CLOSE:</script>`);";
$raw = "<script>\nconsole.log(`#Processed#\n\nCRLF:\r\nNUL:\0\nSCRIPT CLOSE:</\\u0073cript>`);\n</script>";
$raw_preproc = "<script>\rconsole.log(`#Processed#\r\n\nCRLF:\r\nNUL:\u{FFFD}\nSCRIPT CLOSE:</\\u0073cript>`);\r</script>";


  function filter( array $attrs, string $data ): array {
    static $hashes = array();
    
    $p = new WP_HTML_Tag_Processor('<script></script>');
    $p->next_tag();
    // should find first case-insensitive, but for demo:
    $type = $attrs['type'] ?? null;
    if ( is_string( $type ) ) {
      $p->set_attribute('type', $type);
    }
    $p->set_modifiable_text($data);
    // Uncomment to fix the hash mismatch problem:
    // $data = $p->get_modifiable_text();
    
    $hashes[] = "'sha256-" . base64_encode( hash( 'sha256', $data, true ) ) . "'";

    // Replaces the previous header, so the last call sends every hash.
    header( 'Content-Security-Policy: script-src ' . implode( ' ', $hashes ) );

    return $attrs;
  }
    
add_filter(
  'wp_inline_script_attributes',
  'filter',
  10,
  2
);

$tag = wp_get_inline_script_tag( $data );
echo $raw;
echo $raw_preproc;
echo $tag;

All three tags share a hash in the browser. I'm very happy to report that get_modifiable_text() returns the same text, so it is the value to hash. This means that things like null-byte to � and newline normalization must be applied.


This problem is niche and limited to situations where it's important to read the script contents as the browser will. The example above includes a workaround I'll extract here. The idea is to register the filter late (so the modified attributes are read) and apply the same logic that will be applied to produce the tag. Then read the contents from get_modifiable_text() for hashing:

function filter( array $attrs, string $data ): array {
    static $hashes = array();

    // Based on https://github.com/WordPress/wordpress-develop/blob/576f6bba8fe6df48b8557da4b5aaed68a6b16cfa/src/wp-includes/script-loader.php#L3628-L3651
        $processor = new WP_HTML_Tag_Processor( '<script></script>' );
        $processor->next_tag();
        foreach ( $attrs as $name => $value ) {
                if ( null !== $processor->get_attribute( $name ) ) {
                        continue;
                }
                $processor->set_attribute( $name, $value ?? true );
        }
    if ( ! $processor->set_modifiable_text($data) ) {
      return $attrs;
    }
    $data = $processor->get_modifiable_text();
    
    $hashes[] = "'sha256-" . base64_encode( hash( 'sha256', $data, true ) ) . "'";

    header( 'Content-Security-Policy: script-src ' . implode( ' ', $hashes ) );
    return $attrs;
}
add_filter(
  'wp_inline_script_attributes',
  'filter',
  PHP_INT_MAX,
  2
);

Another alternative is to use wp_finalized_template_enhancement_output_buffer, walk the HTML for SCRIPT tags, hash their contents (via HTML API get_modifiable_text()) and send the header. I believe that's only available on the frontend at this time.

#9 in reply to: ↑ 8 @westonruter
4 weeks ago

Replying to jonsurrell:

Another alternative is to use wp_finalized_template_enhancement_output_buffer, walk the HTML for SCRIPT tags, hash their contents (via HTML API get_modifiable_text()) and send the header. I believe that's only available on the frontend at this time.

If I understand correctly, this would pretty much defeat the purpose of CSP in the first place. If someone injected a SCRIPT tag in post content or comment text or something, then adding the CSP hashes (or CSP nonce attributes) via the wp_finalized_template_enhancement_output_buffer filter would erroneously include any malicious scripts. It's important that CSP only be set via scripts explicitly created with wp_get_inline_script_tag().

#10 @jonsurrell
4 weeks ago

In 64496:

Script Loader: Document wp_inline_script_attributes $data parameter quirk.

Developed in: ​https://github.com/WordPress/wordpress-develop/pull/14281

Props jonsurrell, westonruter.
See #65860, #66308.

​@jonsurrell commented on ​PR #14281:


4 weeks ago
#11

Merged in r64496.

#12 @jonsurrell
4 weeks ago

  • Milestone 7.2
  • Resolution → wontfix
  • Status assigned → closed

this would pretty much defeat the purpose of CSP in the first place

It does remove some of the value of CSP, that's true. It still protects against some things like scripts generated on the client.


r64496 documents an appropriate workaround. I'm going to close this as wontfix. Most normal flows should work find with the input data and the exceptions that require exact data can use the workaround (and pay the cost).

Fixing this generally would add undesirable complexity from the potential races between filtered type/langauge attributes and the escaped output.

Note: See TracTickets for help on using tickets.