Repository navigation
KSES: Add wp_kses_sanitize_srcset() for image candidate lists - #14811
adamsilverstein wants to merge 6 commits into
Conversation
A srcset value is a comma-separated list of image candidate strings, not a single URL, so passing it through wp_kses_bad_protocol() or esc_url() either misses candidates or corrupts the list. This function segments the value following the HTML specification's srcset parsing algorithm and removes candidates whose URL uses a disallowed protocol. It takes decoded attribute text and returns decoded text, leaving HTML decoding and encoding to the caller, and returns the input string itself when every candidate is allowed. Nothing calls it yet; wiring it into KSES by tag and attribute follows separately. See https://core.trac.wordpress.org/ticket/29807
|
The following accounts have interacted with this PR and/or linked issues. I will continue to update these lists as activity occurs. Core Committers: Use this line as a base for the props when committing in SVN: To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook. Props Bot commandsYou can trigger Props Bot actions by commenting on this PR:
|
Test using WordPress PlaygroundThe changes in this pull request can previewed and tested using a WordPress Playground instance. WordPress Playground is an experimental project that creates a full WordPress instance entirely within the browser. Some things to be aware of
For more details about these limitations and more, check out the Limitations page in the WordPress Playground documentation. |
westonruter
left a comment
There was a problem hiding this comment.
A couple nits. Also sending up a Claude review momentarily.
westonruter
left a comment
There was a problem hiding this comment.
🤖 Comment by Claude Opus 5.5
A medium-effort review of wp_kses_sanitize_srcset() turned up one tokenizer mismatch with the HTML spec that lets a disallowed URL through, plus some simplification opportunities. Each was reproduced against this branch:
'a.jpg 1x(,)/?,javascript:alert(1) 2x' → returned unchanged
'a.jpg 1x(,)z,javascript:alert(1) 2x' → 'a.jpg 1x('
'a.jpg 1x(,)z, b.jpg 2x' → unchanged (correct)
The practical impact is limited, since browsers do not execute javascript: URLs in image candidates, but the sanitizer and the browser end up seeing different URLs, which defeats the function's contract. Details are in the inline comments.
Declare return types on the test methods and data providers and a type on the allowed protocols property, as suggested in review. See #29807.
The HTML srcset parser treats a comma between `(` and `)` in the descriptors as part of the descriptor, so ending candidates at the first comma let the sanitizer and the browser disagree on the URLs: a value like `a.jpg 1x(,)/?,javascript:alert(1) 2x` came back unchanged, and rebuilding could truncate allowed candidates. Track parentheses while scanning descriptors, and replace the restart and rebuild pass with a single pass that collects kept candidates. See #29807.
|
Thanks @westonruter, the parens one was a real miss. Pushed fixes in 144732e and the typing nits in 77ce137. Claude worked through the review items, notes below:
|
dmsnell
left a comment
There was a problem hiding this comment.
while reading through this I stumbled upon a part of the spec that makes me wonder if our security threats match what we’re applying. the javascript: scheme appears inert inside srcset, but that’s based on some wording in the spec and an ad-hoc test in Chrome, Safari, and Firefox
| * following the HTML specification's srcset parsing algorithm, so a comma only | ||
| * separates candidates when it ends a URL or its descriptors. A comma inside a URL, | ||
| * as produced by image CDN resizers, belongs to the URL, and one inside parentheses | ||
| * in the descriptors belongs to the descriptors. |
There was a problem hiding this comment.
The comma descriptions might be clearer as Example: code snippets in the docblock, with explanatory comments if necessary.
/**
*
* Example:
*
* // The first comma is part of the URL.
* '/?id=4,15 2x` === wp_kses_sanitize_srcset( '/?id=4,15 2x, ,' );
*
* // The first comma is part of the descriptor.
* '/atat.png 2,x` === wp_kses_sanitize_srcset( '/atat.png 2,x, ,' );
*/I don’t know the spec as well as you, and I know that the parseable values are broader than the allowable values (e.g. the descriptor should be only numbers plus x or w, but parses parentheses and all sorts of other characters), so my example is probably wrong in some way, and definitely not representative, but I think these pictures can clarify a lot for readers
There was a problem hiding this comment.
good idea, we could give several representative examples.
| * | ||
| * Each URL is checked with {@see wp_kses_bad_protocol()}. A candidate whose URL that | ||
| * check would change is removed in full, descriptors included, because stripping a | ||
| * scheme and keeping the rest would rewrite the URL rather than remove it, and |
There was a problem hiding this comment.
stripping a scheme and keeping the rest would rewrite the URL rather than remove it
this reads a bit unclear to me. do we not modify other URLs through wp_kses_bad_protocol()? I am definitely in favor of rejecting invalid values outright, but I can’t follow the goals with this comment.
There was a problem hiding this comment.
i can try to clarify it, its saying: each url in the srcset is checked with wp_kses_bad_protocol and if the result is changed (eg it removed something) the url itself is removed from the srcset.
There was a problem hiding this comment.
if the result is changed (eg it removed something) the url itself is removed from the srcset.
this is the part I was confused about, because I thought the purpose of wp_kses_bad_protocol() was to sanitize URLs. that is, other places in Core accept modified values.
I see now that some places in Core also reject it if not identical to the input, which is preferable.
What about, instead of “any URLs that change are removed,” we specify tighter?
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.
| * Each URL is checked with {@see wp_kses_bad_protocol()}. A candidate whose URL that | ||
| * check would change is removed in full, descriptors included, because stripping a | ||
| * scheme and keeping the rest would rewrite the URL rather than remove it, and | ||
| * descriptors left behind would be read as the next candidate's URL. As in |
There was a problem hiding this comment.
This might just be me, but I would think this behavior is obvious, or is possibly clearer with less elaboration.
/**
*
* Entire image candidate strings are removed when they contain problematic URLs.
*
*/There was a problem hiding this comment.
yes, there is a bit of repetition here, I'll clean it up.
| * {@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. When every candidate is allowed, the input is returned | ||
| * unchanged. Otherwise the remaining candidates are rejoined with `, `. |
There was a problem hiding this comment.
Some basic examples here would be helpful. Not even tricky edge cases, but just a show of the behavior.
It’s probably also wise to not differentiate unchanged inputs. We did that for some HTML API stuff and then walked back on it. While it’s nice to preserve inputs, in the KSES domain, normalization can be more valuable than preservation.
I’m thinking specifically of inputs such as those containing extra whitespace. It’s benign according to the spec, but if we are performing a sanitizing function, then it’s also good to think of all of the downstream code which might be doing something silly like explode( ', ', $srcset );
For normative srcset values the principle holds: the output will be the reference-equal string passed into it, but that’s not a contract we make for callers. In fact, that gives us the freedom to say “everything that comes out of here will be more like developers expect it to be” as long as we don’t change the semantics (e.g. no output will contain empty image candidate strings like ,, or , ,)
There was a problem hiding this comment.
makes sense! thanks for the guidance.
| public function data_allowed_values_are_returned_unchanged(): array { | ||
| return array( | ||
| 'empty value' => array( '' ), | ||
| 'whitespace only' => array( " \t\n" ), |
There was a problem hiding this comment.
this is an example where I think we could reasonably say that the return value should be normalized to an empty string
| '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' ), | ||
| 'no whitespace after the comma' => array( 'image1.jpg 1x,image2.jpg 2x' ), | ||
| 'extra whitespace is preserved' => array( ' image1.jpg 1x , image2.jpg 2x ' ), |
There was a problem hiding this comment.
w.r.t. normalization, if we were to do that, this would be image1.jpg 1x, image2.jpg 2x on output
There was a problem hiding this comment.
I agree we should normalize the whitespace
| 'newlines are preserved' => array( "image1.jpg 1x,\nimage2.jpg 2x" ), | ||
| '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' ), |
There was a problem hiding this comment.
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
| $candidate = substr( $srcset, $candidate_at, $at - $candidate_at ); | ||
| } else { | ||
| $candidate = $url; | ||
| } |
There was a problem hiding this comment.
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 asrcsetbe rejected? I think so, but would be nice to verify - descriptor may be
[0-9]+wor-?(?:[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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 insrcsetfor the same reason it is inert insrc, so the case for checking it is policy consistency rather than script execution.Fetch's scheme fetch only handles
about,blob,data,fileand HTTP(S) and returns a network error for anything else, which is the console error Chrome and Safari show. The same step applies toimg src. The browser-native Sanitizer API goes further and only stripsjavascript:from navigating attributes (a/area href,form action,formaction), leavingimg srcalone entirely, and modern Angular's sanitizer has a test asserting thatsrcset="/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.htmlSo the reasons to keep the check are the same ones that keep it on
srctoday:
wp_allowed_protocols()is a content policy, not an execution guard.img src="data:..."is stripped in post context now, and browsers do loaddata:candidates fromsrcset, so an uncheckedsrcsetwould 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
srcorhref: Picturefill doesimg.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 doesa.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 0wis a parse error and never becomes a candidate), the parse rules are looser than the valid syntax (1.xparses,-1xis rejected as not greater than zero,his only allowed next tow), 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?
There was a problem hiding this comment.
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. 🙃
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
Returning the input unchanged when every candidate is allowed let values the HTML parser treats as parse errors, such as `,,,,` or `a.jpg 1x,, b.jpg 2x`, pass through verbatim. Rejoin the kept candidates with `, ` in every case, so empty candidates and surrounding whitespace never reach the output and callers get a single predictable shape. Add examples to the docblock, drop the repeated explanation of why a candidate is removed whole, and add tests for separator normalization, URL syntax characters passing through untouched, and whitespace ending a URL before a scheme can form. See #29807. Claude-Session: https://claude.ai/code/session_018vwYjRp3dvMdHs8fzQbqqN
State that a URL is rejected when sanitizing it would produce a different URL, and show the comma rules as examples instead of prose, as suggested in review. Note why the comparison ignores case.
Trac ticket: https://core.trac.wordpress.org/ticket/29807
First of a small stack splitting up #6184 along the lines @dmsnell suggested there: the srcset parser on its own, then wiring it into KSES by tag and attribute, then the allowed-HTML additions for
picture,sourceandsrcset.This PR only adds
wp_kses_sanitize_srcset( string $srcset, array $allowed_protocols ): stringplus tests. Nothing calls it yet.What it does:
wp_kses_bad_protocol()and drops the whole candidate, descriptors included, when that check would change it. Descriptors are skipped, not validated.,and trailing whitespace trimmed.Changes from the version in #6184, all following the review feedback there: no "multi-URI attributes" concept or filter, no
,/ lookahead, nowp_kses_no_null()or whitespace tolerance inside schemes, and no validation of descriptors. Parentheses in descriptors are tracked only to find where a candidate ends, as the spec does, so a comma inside them does not split the candidate. Thea.jpg 2q,javascript:...case that was documented as a known limitation is now handled, since the comma after an invalid descriptor ends the candidate the same way it does in the browser.Naming: I went with
wp_kses_sanitize_srcset()since srcset (andimagesrcsetonlink) is the only attribute with this syntax. Happy to rename if something likeimage_candidatesreads better.Testing
npm run test:php -- --group kses- the new tests are intests/phpunit/tests/kses/wpKsesSanitizeSrcset.php. PHPStan at level 10 is clean on the new code.AI Use
Claude Code drafted the code and this description from the review thread on #6184, and I steered. I will review and test.