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
89 changes: 89 additions & 0 deletions src/wp-includes/kses.php
Original file line number Diff line number Diff line change
Expand Up @@ -3228,6 +3228,95 @@ function wp_kses_bad_protocol_once2( $scheme, $allowed_protocols ) {
}
}

/**
* Removes image candidates with a disallowed URL protocol from a `srcset` value.
*
* A `srcset` attribute holds a comma-separated list of image candidate strings,
* each a URL optionally followed by whitespace and width or density descriptors.
* The value is split into candidates following the HTML specification's srcset
* parsing algorithm.
*
* Each URL is checked with {@see wp_kses_bad_protocol()}, and if that sanitization
* would produce a different URL, it is rejected and its entire image candidate
* string is removed from the `srcset`. As in {@see esc_url()}, a URL starting with
* `/` cannot carry a scheme and is kept as is. Descriptors are not validated.
*
* The remaining candidates are rejoined with `, `, so whitespace around them and
* empty candidates do not survive into the result.
*
* Example:
*
* // A candidate with a disallowed protocol is removed.
* 'a.jpg 1x, c.jpg 3x' === wp_kses_sanitize_srcset( 'a.jpg 1x, javascript:alert(1) 2x, c.jpg 3x', $protocols );
*
* // A comma inside a URL is part of the URL.
* 'https://cdn.example/w=400,q=80/a.jpg 400w' === wp_kses_sanitize_srcset( 'https://cdn.example/w=400,q=80/a.jpg 400w', $protocols );
*
* // A comma inside parentheses in the descriptors is part of the descriptors.
* 'a.jpg 1x(,), b.jpg 2x' === wp_kses_sanitize_srcset( 'a.jpg 1x(,),b.jpg 2x', $protocols );
*
* // Separators are normalized.
* 'a.jpg 1x, b.jpg 2x' === wp_kses_sanitize_srcset( " a.jpg 1x ,,\n b.jpg 2x ", $protocols );
*
* The value must be decoded attribute text, as returned by
* {@see WP_HTML_Tag_Processor::get_attribute()}, not raw HTML containing character
* references. The returned value is decoded text too; callers writing it back into
* HTML must escape it.
*
* @since 7.2.0
*
* @link https://html.spec.whatwg.org/multipage/images.html#parsing-a-srcset-attribute
*
* @param string $srcset Decoded `srcset` attribute value.
* @param string[] $allowed_protocols Array of allowed URL protocols.
* @return string The value without candidates whose URL uses a disallowed protocol.
*/
function wp_kses_sanitize_srcset( string $srcset, array $allowed_protocols ): string {
$whitespace = " \t\f\r\n";
$length = strlen( $srcset );
$at = 0;
$kept = array();

while ( $at < $length ) {
$at += strspn( $srcset, "{$whitespace},", $at );
if ( $at >= $length ) {
break;
}

// The URL is the run of non-whitespace characters, less any commas ending it.
$candidate_at = $at;
$url_length = strcspn( $srcset, $whitespace, $at );
$url = rtrim( substr( $srcset, $at, $url_length ), ',' );
$at += $url_length;

/*
* A URL ended by a comma has no descriptors. Otherwise they run to the next
* comma outside parentheses, or to the end when a parenthesis is left open.
*/
if ( strlen( $url ) === $url_length ) {
while ( $at < $length ) {
$at += strcspn( $srcset, ',(', $at );
if ( $at >= $length || ',' === $srcset[ $at ] ) {
break;
}

$closing_at = strpos( $srcset, ')', $at );
$at = false === $closing_at ? $length : $closing_at + 1;
}
$candidate = substr( $srcset, $candidate_at, $at - $candidate_at );
} else {
$candidate = $url;
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

with this framed as a sanitizer for srcset, do you think it’s worth going a bit further on the normalization aspect, given that the allowable values are reasonably limited?

  • drop empty URLs. maybe it already does this via wp_kses_bad_protocol(), but would ,,,, as a srcset be rejected? I think so, but would be nice to verify
  • descriptor may be [0-9]+w or -?(?:[0-9]+)?(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?x

referencing a non-interactive, optionally animated, image resource that is neither paged nor scripted.

this makes me wonder, do we know for sure that there is a security risk inherent in srcset? Safari, Firefox, and Chrome all reject this:

<img src="https://s.wp.com/i/atat.png" srcset="javascript:alert(1) 600w">

Firefox shows no error, but Chrome and Safari both show an error in the dev tools indicating that the URL or scheme or format is not allowed.

@adamsilverstein adamsilverstein Oct 28, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

drop empty URLs. maybe it already does this via wp_kses_bad_protocol(), but would ,,,, as a srcset be rejected? I think so, but would be nice to verify

I think so, I'll add a test to verify.

do we know for sure that there is a security risk inherent in srcset? Safari, Firefox, and Chrome all reject this

Good question. My assumption was we would want the same sort of sanitization as esc_url for (each url in) srcset. I thought these two resources would be treated the same and have the same inherent security risks. That may not be correct - I'll research further to confirm what the exact security risk is for urls and srcset and how/if it would be exploited.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for pushing on this, it made me go check what browsers actually do instead of assuming.

I had Claude dig through the specs and a few other sanitizers, here is the summary:

Short version: javascript: is inert in srcset for the same reason it is inert in src, so the case for checking it is policy consistency rather than script execution.

Fetch's scheme fetch only handles about, blob, data, file and HTTP(S) and returns a network error for anything else, which is the console error Chrome and Safari show. The same step applies to img src. The browser-native Sanitizer API goes further and only strips javascript: from navigating attributes (a/area href, form action, formaction), leaving img src alone entirely, and modern Angular's sanitizer has a test asserting that srcset="/foo.png 400px, javascript:evil() 23px" passes through untouched. See https://fetch.spec.whatwg.org/#scheme-fetch and https://github.com/web-platform-tests/wpt/blob/master/sanitizer-api/sanitizer-javascript-url.html

So the reasons to keep the check are the same ones that keep it on src today:

  • wp_allowed_protocols() is a content policy, not an execution guard. img src="data:..." is stripped in post context now, and browsers do load data: candidates from srcset, so an unchecked srcset would be a way around that. AngularJS shipped exactly this gap as CVE-2024-8372 (scored 4.3, content spoofing via "bypass image source restrictions", not XSS). See https://nvd.nist.gov/vuln/detail/CVE-2024-8372
  • Plenty of JS copies candidate URLs into src or href: Picturefill does img.src = bestCandidate.url, lightboxes commonly pick the largest candidate for the link, and feeds, email clients and apps render post content with their own rules. Sanitizers that treat srcset carefully (JustHTML, the .NET HtmlSanitizer, the AngularJS fix) check each candidate; DOMPurify runs its URI regex over the whitespace-stripped whole value, which in practice only checks the first one.

On the normalization points: ,,,, currently comes back unchanged (verified on the branch), as does a.jpg 1x,, b.jpg 2x. Both are parse errors in the spec, and always rejoining with , fixes them along with the whitespace cases. Descriptor validation seems worth leaving out of this PR: browsers already drop a candidate whose descriptor fails to parse (a.jpg 0w is a parse error and never becomes a candidate), the parse rules are looser than the valid syntax (1.x parses, -1x is rejected as not greater than zero, h is only allowed next to w), and the note on #6184 was that validating descriptors raises questions about syntax-valid but semantically wrong values.

Normalization and the extra tests are pushed in b04ba88. Does that framing match your read of the risk, and would you want descriptor validation as a follow up?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this was an honest question on what you consider worthwhile to sanitize.

that Claude assessment corresponds to my reading of the spec. makes me wonder why we are removing javascript: schemes from IMG src if it’s also benign. 🙃

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

its a reasonable question.

i guess the only convincing reason besides developer expectations I see is if we want to protect some older browsers that don't sanitize correctly, or other places/contexts you might copy the image to, like an email or chat app. It might be good to try to reproduce those vectors and measure the effort of sanitization as well. There is also the cost of trying to convince developers not sanitizing their URLs is just fine after so many years of teaching them the opposite.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

that’s all true, but if we’re adding complexity to guard against attacks in browsers we don’t support, we also run the risk of introducing new vectors of attack we hadn’t considered.

I’m not sure how we could copy/paste the srcset URLs into other apps, but you can use my clipboard viewer to help inspect it (not a replacement for testing the copy/paste into the other apps).

the important thing with the clipboard viewer is that you want to paste into it without any other copy/pastes in between, as the browser will tend to send out a multi-part paste object, and if you do something like paste through a terminal or other app it might lose one or more of the parts.

when I select your GitHub avatar and paste it in there, this is what it shows. I did not test with any unwanted URL patterns. I often see pastes with the image data embedded as a data URI

Screenshot 2026-10-28 at 6 08 21 PM


// The comparison ignores case because wp_kses_bad_protocol() lowercases an allowed scheme.
if ( '/' === $url[0] || 0 === strcasecmp( wp_kses_bad_protocol( $url, $allowed_protocols ), $url ) ) {
$kept[] = rtrim( $candidate, $whitespace );
}
}

return implode( ', ', $kept );
}

/**
* Converts and fixes HTML entities.
*
Expand Down
194 changes: 194 additions & 0 deletions tests/phpunit/tests/kses/wpKsesSanitizeSrcset.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
<?php
/**
* Test wp_kses_sanitize_srcset() function.
*
* @group kses
*
* @covers ::wp_kses_sanitize_srcset
*/
class Tests_Kses_WpKsesSanitizeSrcset extends WP_UnitTestCase {

/**
* Allowed protocols used by every test.
*
* @var string[]
*/
protected array $allowed_protocols;

public function set_up(): void {
parent::set_up();
$this->allowed_protocols = wp_allowed_protocols();
}

/**
* @ticket 29807
*
* @dataProvider data_allowed_values_are_returned_unchanged
*
* @param string $srcset Value whose candidates are all allowed.
*/
public function test_allowed_values_are_returned_unchanged( string $srcset ): void {
$this->assertSame( $srcset, wp_kses_sanitize_srcset( $srcset, $this->allowed_protocols ) );
}

/**
* @return array<string, array{string}>
*/
public function data_allowed_values_are_returned_unchanged(): array {
return array(
'empty value' => array( '' ),
'single URL, no descriptor' => array( 'image.jpg' ),
'relative URLs' => array( 'path/to/test.png 1x, path/to/test-2x.png 2x' ),
'root-relative URLs' => array( '/test.png 1x, /test-2x.png 2x' ),
'protocol-relative URLs' => array( '//cdn.example.com/img-300.jpg 300w, //cdn.example.com/img-600.jpg 600w' ),
'absolute URLs with width descriptors' => array( 'https://example.com/small.jpg 480w, https://example.com/medium.jpg 800w, https://example.com/large.jpg 1200w' ),
'uppercase scheme' => array( 'HTTPS://example.com/a.jpg 1x, Http://example.com/b.jpg 2x' ),
'decimal density descriptors' => array( 'image-1x.jpg 1x, image-1.5x.jpg 1.5x, image-2x.jpg 2x' ),
'no descriptor on the last candidate' => array( 'small.jpg 300w, medium.jpg 600w, large.jpg' ),
'tab between URL and descriptor' => array( "image1.jpg\t1x, image2.jpg\t2x" ),
'URL syntax characters are kept as is' => array( '/image-service?yolo=meme&size=large 2x, /image-service?size=small&q="80" 1x' ),
'commas inside a URL belong to the URL' => array( 'http://localhost/test.png,big 1x, http://localhost/test.png,medium 2x' ),
'CDN resizer URLs with commas' => array( 'https://resizer.example/cdn-cgi/image/format=auto,onerror=redirect,quality=80,width=412,height=275,dpr=1,fit=crop,gravity=0.5x0.5/https://bucket.example/photo.jpg 412w, https://resizer.example/cdn-cgi/image/format=auto,quality=80,width=824,height=550/https://bucket.example/photo.jpg 824w' ),
'CDN resizer URL without descriptor' => array( 'https://cdn.example/image/format=auto,quality=80/img.jpg 400w, https://cdn.example/image/format=auto,quality=80/img-large.jpg' ),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it would be helpful somewhere to pass a URL containing syntax characters to show that these are raw-in/raw-out, maybe in another test function. an example I can think of is /image-service?yolo=meme&size=large 2x, and this would have to use assertSame() and not assertEquivalentHTML() because we’re comparing plaintext, not HTML

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, will add!

'root-relative URL containing a colon' => array( '/images/a:b.jpg 1x' ),
'comma inside descriptor parentheses' => array( 'a.jpg 1x(,)z, b.jpg 2x' ),
'unclosed descriptor parenthesis' => array( 'a.jpg 1x(, javascript:alert(1) 2x' ),
'descriptors are not sanitized as URLs' => array( 'a.jpg javascript:alert(1), b.jpg 2x' ),
'whitespace ends the URL before a scheme forms' => array( "a.jpg 1x, java\tscript:alert(1) 2x" ),
);
}

/**
* @ticket 29807
*
* @dataProvider data_separators_are_normalized
*
* @param string $srcset Value with irregular whitespace or commas between candidates.
* @param string $expected Value with the candidates rejoined with `, `.
*/
public function test_separators_are_normalized( string $srcset, string $expected ): void {
$this->assertSame( $expected, wp_kses_sanitize_srcset( $srcset, $this->allowed_protocols ) );
}

/**
* @return array<string, array{string, string}>
*/
public function data_separators_are_normalized(): array {
return array(
'whitespace only' => array( " \t\n", '' ),
'commas only' => array( ',,,,', '' ),
'commas and whitespace only' => array( ' , , ', '' ),
'no whitespace after the comma' => array( 'image1.jpg 1x,image2.jpg 2x', 'image1.jpg 1x, image2.jpg 2x' ),
'surrounding whitespace' => array( ' image1.jpg 1x , image2.jpg 2x ', 'image1.jpg 1x, image2.jpg 2x' ),
'newline after the comma' => array( "image1.jpg 1x,\nimage2.jpg 2x", 'image1.jpg 1x, image2.jpg 2x' ),
'empty candidate between two commas' => array( 'image1.jpg 1x,, image2.jpg 2x', 'image1.jpg 1x, image2.jpg 2x' ),
'empty candidate with whitespace' => array( 'image1.jpg 1x, , image2.jpg 2x', 'image1.jpg 1x, image2.jpg 2x' ),
'trailing comma' => array( 'image1.jpg 1x, image2.jpg 2x,', 'image1.jpg 1x, image2.jpg 2x' ),
'leading comma' => array( ', image1.jpg 1x', 'image1.jpg 1x' ),
'comma after descriptor parentheses' => array( 'a.jpg 1x(,),b.jpg 2x', 'a.jpg 1x(,), b.jpg 2x' ),
);
}

/**
* @ticket 29807
*
* @dataProvider data_candidates_with_disallowed_protocols_are_removed
*
* @param string $srcset Value containing at least one disallowed candidate.
* @param string $expected Value with those candidates removed.
*/
public function test_candidates_with_disallowed_protocols_are_removed( string $srcset, string $expected ): void {
$this->assertSame( $expected, wp_kses_sanitize_srcset( $srcset, $this->allowed_protocols ) );
}

/**
* @return array<string, array{string, string}>
*/
public function data_candidates_with_disallowed_protocols_are_removed(): array {
return array(
'first candidate' => array(
'bad://localhost/test.png 1x, http://localhost/test-2x.png 2x',
'http://localhost/test-2x.png 2x',
),
'last candidate' => array(
'http://localhost/test.png 1x, bad://localhost/test-2x.png 2x',
'http://localhost/test.png 1x',
),
'middle candidate' => array(
'image-1x.jpg 1x, javascript:alert(1) 1.5x, image-2x.jpg 2x',
'image-1x.jpg 1x, image-2x.jpg 2x',
),
'only candidate' => array(
'javascript:alert(1) 1x',
'',
),
'every candidate' => array(
'javascript:alert(1) 1x, data:text/html,<script>alert(1)</script> 2x',
'',
),
'two in a row' => array(
'a.jpg 1x, javascript:alert(1) 2x, vbscript:msgbox(1) 3x, d.jpg 4x',
'a.jpg 1x, d.jpg 4x',
),
'data URL' => array(
'data:image/png;base64,iVBORw0KGgo= 1x, https://example.com/a.jpg 2x',
'https://example.com/a.jpg 2x',
),
'URL with commas and a disallowed scheme' => array(
'http://localhost/test.png,big 1x, bad://localhost/test.png,medium 2x',
'http://localhost/test.png,big 1x',
),
'descriptor-less candidate after a comma' => array(
'safe.jpg, javascript:alert(1)',
'safe.jpg',
),
'comma-joined URLs form one candidate' => array(
'safe.jpg,javascript:alert(1) 2x',
'',
),
'comma attached to an invalid descriptor' => array(
'a.jpg 2q,javascript:alert(1) 2x',
'a.jpg 2q',
),
'scheme that empties under wp_kses_bad_protocol' => array(
'a:b:c:d:e:f:g 100w, safe.jpg 200w',
'safe.jpg 200w',
),
'emptied scheme without descriptor' => array(
'a:b:c:d:e:f:g, safe.jpg 200w',
'safe.jpg 200w',
),
'irregular separators around a removed candidate' => array(
" a.jpg 1x ,\n\tjavascript:alert(1) 2x ,b.jpg 3x ",
'a.jpg 1x, b.jpg 3x',
),
'allowed scheme is kept in its original case' => array(
'HTTPS://example.com/a.jpg 1x, javascript:alert(1) 2x',
'HTTPS://example.com/a.jpg 1x',
),
'comma inside descriptor parentheses' => array(
'a.jpg 1x(,)z,javascript:alert(1) 2x',
'a.jpg 1x(,)z',
),
'URL after descriptor parentheses that look scheme-less' => array(
'a.jpg 1x(,)/?,javascript:alert(1) 2x',
'a.jpg 1x(,)/?',
),
'unclosed parenthesis runs to the end' => array(
'javascript:alert(1) 1x(, a.jpg 2x',
'',
),
);
}

/**
* @ticket 29807
*/
public function test_respects_the_given_allowed_protocols(): void {
$srcset = 'https://example.com/a.jpg 1x, ftp://example.com/b.jpg 2x';

$this->assertSame( $srcset, wp_kses_sanitize_srcset( $srcset, array( 'https', 'ftp' ) ) );
$this->assertSame( 'https://example.com/a.jpg 1x', wp_kses_sanitize_srcset( $srcset, array( 'https' ) ) );
$this->assertSame( '', wp_kses_sanitize_srcset( $srcset, array() ) );
}
}
Loading