Repository navigation
fix: enforce single-property validation in CSSStyleDeclaration.setProperty - #60
Conversation
046c175 to
0f37c66
Compare
alan-agius4
left a comment
There was a problem hiding this comment.
Thanks for putting this fix together. The SIMPLE_VALUE_RE fast path is a nice win for common values, and moving .trim() inside if (value !== NO_CHANGE) also fixes an existing crash in setPropertyPriority().
There are a few things worth addressing before landing: a parser differential between isValidStyleValue and lib/style_parser.js when styles are reparsed, Object.prototype collisions on property names like constructor and __proto__, and a hot path perf/allocation regression on CSS function values (rgba(), calc(), var(), translate3d(), etc.).
See the inline comments for details.
| } | ||
|
|
||
| const IMPORTANT_BANG = '!important'; | ||
| const INVALID_PROPERTY_NAME_RE = /[\s:;'"(){}\[\]\/\\!]/; |
There was a problem hiding this comment.
Two things on property name handling:
parseStyles()initializesproperty: {}andpriority: {}as plain objects, soObject.prototypekeys collide. Callingel.style.setProperty('constructor', 'red')reads inheritedObject.prototype.constructorin_serialize()and emitsstyle="constructor: red !function Object() { [native code] };". Also,el.style.setProperty('__proto__', 'red')regresses from returning early (getAttribute('style') === null) to writingstyle="", becauseisValidPropertyName('__proto__')passes and_serialize()still runs after the silent assignment. Can we initialize both withObject.create(null)inparseStyles()?- Because
INVALID_PROPERTY_NAME_REis a denylist, it still accepts invalid CSS property names like'--','123','@import','a<b', and'\x00'. Sincepropertyis already lowercased insetProperty(), can we switch to an allowlist regex instead?
const VALID_PROPERTY_NAME_RE = /^(?:--[^\x00-\x20:;'"(){}\[\]\/\\!\x7f]+|-?[a-z_][a-z0-9_-]*)$/;There was a problem hiding this comment.
Two quick additions here:
Object.create(null)inparseStyles()also fixesremoveProperty('constructor')andsetPropertyPriority('constructor', 'important'), which currently hit inheritedObject.prototype.constructorand spuriously serializestyle="".- On the custom-property branch of the allowlist regex: since
_serialize()writes property names verbatim without CSS-escaping them, restricting--*to valid unescaped<dashed-ident>characters (disallowing ASCII punctuation like.,<,,,+) avoids emitting invalid CSS declarations that browsers drop when parsingstyle="...".
| const CSS_WS_RE = /[ \t\n\r\f]+/y; | ||
| const CSS_COMMENT_RE = /\/\*[\s\S]*?\*\//y; | ||
| const CSS_STRING_RE = /"(?:\\(?:\r\n|[\s\S])|[^"\\\n\r\f])*"|'(?:\\(?:\r\n|[\s\S])|[^'\\\n\r\f])*'/y; | ||
| const CSS_IDENT_RE = /(?:[a-zA-Z0-9_-]|[^\x00-\x7f]|\\(?:[0-9a-fA-F]{1,6}(?:\r\n|[ \t\n\r\f])?|[^\n\r\f]))+/y; |
There was a problem hiding this comment.
A couple of notes on the token regexes:
- Perf on
data:URIs: InCSS_STRING_REandCSS_UNQUOTED_URL_RE, the common unescaped branch has no+quantifier, so V8 loops per character through the alternation on every byte of a long URL or string. Unrolling them (e.g."[^"\\\n\r\f]*(?:\\(?:\r\n|[\s\S])[^"\\\n\r\f]*)*"and(?:[^'"()\\ \t\n\r\f\x00-\x08\x0b\x0e-\x1f\x7f]+|\\[^\n\r\f])+) roughly halves validation latency on 1KB to 500KBdata:URIs (~960 us down to ~487 us at 500KB) while keeping disjoint first sets (O(n)). - Nit:
[^\x00-\x7f]inCSS_IDENT_REmerges whitespace and punctuation above U+007F (like\u00a0or\u200b) into a followingurl(token ("\u00a0url"), skipping the unquoted URL check. Current Blink still treats all>= U+0080as ident code points so it does not trigger today, but CSS Syntax Level 3 narrowednon-ASCII ident code pointto exclude these ranges. Tightening that range avoids a future engine differential. - Minor:
CSS_UNQUOTED_URL_RE(\\[^\n\r\f]) rejects valid hex escape plus consumed whitespace/newline URLs likeurl(a\20 b.png), andCSS_STRING_RErejects"a\61\nb"(both accepted by Chrome).
There was a problem hiding this comment.
Quick follow-ups on points 2 and 3:
- On point 2: tightening
[^\x00-\x7f](and excluding lone surrogates) prevents the sameurl(bypass class (\u00a0url(a/*); position: fixed; --a: */)) on engines implementing CSS Syntax Level 3's narrowed non-ASCII ident table. - On point 3 (ReDoS caveat): if adding hex-escape + whitespace support to
CSS_STRING_REorCSS_UNQUOTED_URL_RE, avoid droppingCSS_IDENT_RE's\\(?:[0-9a-fA-F]{1,6}(?:\r\n|[ \t\n\r\f])?|[^\n\r\f])directly into a regex that expects a closing quote or). Overlapping hex digits and unescaped characters cause exponential backtracking on unclosed inputs like'"' + '\\aaaaaa'.repeat(25). AcharCodeAtloop avoids this completely (or require a character excluded from the unescaped class after the hex digits).
|
|
||
| // Whitespace (ignored for !important tracking) | ||
| CSS_WS_RE.lastIndex = i; | ||
| if (CSS_WS_RE.exec(value)) { |
There was a problem hiding this comment.
On SSR hot paths, SIMPLE_VALUE_RE gives a ~5 to 8x speedup over parseStyles on simple values, but values containing CSS functions (rgba(...), translate3d(...), calc(...), var(...), linear-gradient(...)) regress ~1.3 to 2.5x in validation (~1.05 to 1.41x end to end) and allocate up to 3.3x more heap (~2.4 KB/op on linear-gradient(...) + url(...)).
The main overhead in this loop comes from:
- Calling
CSS_WS_RE.exec(value)on every character (even when it is not whitespace) andCSS_IDENT_RE.exec(value)on every punctuation character (,,.,%,/,#,!), allocating a match array and substring on every match, including inside parens wheretokenis discarded. - Using
.exec()onCSS_COMMENT_RE,CSS_STRING_RE,CSS_QUOTED_URL_OPEN_RE, andCSS_UNQUOTED_URL_REeven though the return value is ignored. Switching to.test()still updates.lastIndexon/yregexes without allocating match arrays or slices, andvalue.indexOf('*/', i + 2)is much faster for comments. - Eagerly allocating
const stack = []even when there are no brackets (16 / 9,"Helvetica Neue",url(data:...)).
Switching to .test() with charCodeAt guards, indexOf('*/', i + 2), and a lazy stack recovers ~2 to 2.6x on CSS functions (~1.25 to 1.4x end to end SSR) with ~0 B/op. Going a step further with a charCodeAt loop (similar to lib/style_parser.js, delegating quoted strings and unquoted url(...) to unrolled .test() regexes) gets ~5.7 to 6.7x on CSS functions while keeping the fast data: URI path.
Nit: SIMPLE_VALUE_RE also excludes / unconditionally, so 16 / 9 or 14px/1.5 take the slow path even though / only matters before *.
| // Validate that `property` and `value` represent a single CSS declaration | ||
| // without top-level semicolons, unbalanced delimiters/quotes/comments, or | ||
| // trailing `!important` priority. | ||
| if (!isValidPropertyName(property) || !isValidStyleValue(value)) { |
There was a problem hiding this comment.
Two things here:
- Reparse differential with
lib/style_parser.js:isValidStyleValuenow accepts;inside CSS comments (/* ; */), escaped semicolons (\;), escaped parens in unquotedurl(...)(\)), escaped quotes (\"), and[]/{}blocks. However,lib/style_parser.js(used wheneverstyleis reparsed on HTML round trips,setAttribute('style', ...), orcssText) does not handle comments,[]/{}nesting, unquotedurl(...), or backslash escapes. In fact,style_parser.jslines 50 and 61 checkvalue.charCodeAt(i - 1) !== 92afteri++, which inspects the quote itself instead of the preceding\. As a result, a value likesetProperty('color', 'red /* ; position: fixed; --a: */')orsetProperty('font-family', 'Foo\\; position: fixed')is accepted, gets split into separate properties on reparse, and if the original property is subsequently removed or updated,position: fixed;becomes a live CSS declaration. Can we updatelib/style_parser.jsto stay consistent with these tokenization rules (keeping a fast path when/,\,[,{are not present)? - Perf:
var styles = this._parsed;currently runs on line 331 before validation, so rejected calls on elements with unparsed styles still readgetAttribute('style'), runparseStyles(), and deletethis._names. Movingvar styles = this._parsed;after this guard (and inside thevalue === NO_CHANGEbranch) avoids that wasted work (~1.3 to 1.7x faster on rejected calls).
There was a problem hiding this comment.
Two more details to watch out for when updating lib/style_parser.js:
- Lines 37-42 (
case 40/case 41) also updateparenDepthwithout checkingquote === 0. As a result,setProperty('--x', 'calc(")" ; position: fixed; --a: 1)')passesisValidStyleValueand splits into a separateposition: fixeddeclaration on reparse (and even benigncontent: "(";corruptsparenDepthfor subsequent declarations). - When fixing backslash escapes and adding comment skipping: handle even backslashes inside strings (e.g.
"foo\\"by advancing past the escaped char on\rather than only checkingi - 2), and make sure/*inside an unquotedurl(...)(likeurl(https://example.com/*)) is not treated as starting a comment.
| (a.getAttribute('style') === null).should.equal(true); | ||
| a.style.backgroundImage = 'url(data:image/png;base64,iVBORw0KGgo=)'; | ||
| a.getAttribute('style').should.equal('background-image: url(data:image/png;base64,iVBORw0KGgo=);'); | ||
| }; |
There was a problem hiding this comment.
Can we also add tests for:
- Reparse round trips (
domino.createDocument(el.outerHTML)followed byremoveProperty/getPropertyValue) for values containing/* ; */,\;,\",\)inurl(),[], and{}. - Prototype and invalid property names (
'constructor','__proto__','--','123','@import','\x00'). setPropertyPriority(covering theNO_CHANGE.trim()fix) and verifying a rejectedsetPropertydoes not overwrite an existing validstyleattribute.- Standalone
/values (rgb(255 0 0 / 50%),calc(100% / 2)),/*/, and a largedata:URI.
alan-agius4
left a comment
There was a problem hiding this comment.
Follow-up: found a live direct CSS property injection bypass via <CDO-token> (<!--url(...)) that works in Chrome without reparsing, plus a few follow-up notes on the existing threads.
| if (token.includes('\\')) { | ||
| return false; | ||
| } | ||
| if (token.toLowerCase() === 'url') { |
There was a problem hiding this comment.
There is a direct CSS property injection bypass here via <CDO-token> (<!--).
Because isValidStyleValue does not tokenize <!--, < and ! are consumed as single-char delimiters and CSS_IDENT_RE then merges -- with a following url into '--url'. That skips the token.toLowerCase() === 'url' check, pushes ( onto stack as an ordinary paren, and allows ; position: fixed; ... to be hidden inside a quoted string or /* ... */ comment. After HTML serialization (<!--url(...) decodes back to <!--url(...)), browsers tokenize <!-- as <CDO-token> and url(...) as an unquoted <url-token>/<bad-url-token> terminating at the first ), turning position: fixed; into a live declaration (verified in Chrome):
// All pass isValidStyleValue() and inject `position: fixed;` in Chrome:
el.style.setProperty('background-image', "<!--url(https://a.example/'x);position:fixed;--a:')");
el.style.setProperty('background-image', "<!--url(https://a.example/*);position:fixed;--a:/**/)");
el.style.setProperty('background-image', "a<!--url(https://a.example/'x);position:fixed;--a:')");
el.style.setProperty('color', 'calc(<!--url(a/*)); position: fixed; --a: */))');Consuming <!-- (and --> for symmetry) before punctuation/ident matching closes this:
if (ch === '<' && value[i + 1] === '!' && value[i + 2] === '-' && value[i + 3] === '-') {
if (stack.length === 0) {
prevToken = lastToken;
lastToken = '<!--';
}
i += 4;
continue;
}Please also add test cases covering these <!--url(...) payloads (both top-level and nested inside calc(...)).
alan-agius4
left a comment
There was a problem hiding this comment.
Thanks for the thorough update — the charCodeAt rewrite is great (now faster than main across CSS functions and large data: URIs), and everything from the previous round was addressed.
Fuzzing the updated tokenizer and style_parser.js against Chrome turned up a few remaining gaps before landing: two live CSS property injection bypasses in the inverse url(-differential direction (#url(...)/@url(...) and \x00/lone-surrogate/non-ASCII-non-ident prefixes before url(), a few reparse split edge cases in lib/style_parser.js's isUrlOpen(), and two minor edge cases.
See the inline comments for details and suggested fixes.
| continue; | ||
| } | ||
|
|
||
| // Ident / number / dimension / escape sequence |
There was a problem hiding this comment.
There is a live all-browser CSS property injection bypass here because # (<hash-token>) and @ (<at-keyword-token>) are not tokenized before falling through as single-char delimiters.
In isValidStyleValue, # and @ are consumed as delimiters, so url(a/*) is scanned as an unquoted <url-token> (where /* is not a comment) followed by a valid <string-token>. Per CSS Syntax Level 3 §4.3.1, browsers tokenize #url as <hash-token> and @url as <at-keyword-token>, making ( a normal <(-token> block where /* opens a comment swallowing ) ", */ closes it, ) closes (, and ; position: fixed; executes as a live declaration (verified in Chrome):
// Both pass isValidStyleValue() and apply `position: fixed` in Chrome:
el.style.setProperty('background-image', '#url(a/*) "*/); position: fixed; --a: "');
el.style.setProperty('background-image', '@url(a/*) "*/); position: fixed; --a: "');
// Same for `##url(...)`, `@@url(...)`, and nested inside `calc(...)`.Tokenizing <hash-token> (# followed by an ident code point or valid escape) and <at-keyword-token> (@ followed by a valid ident-start sequence per CSS Syntax Level 3 §4.3.10) before the ident/delimiter branches — consuming the ident sequence without running the url( check — closes this.
| continue; | ||
| } | ||
|
|
||
| // Other punctuation / delimiters |
There was a problem hiding this comment.
The same inverse url( differential also triggers for U+0000, lone surrogates (\ud800–\udfff), and non-ASCII code points >= U+0080 outside CSS Syntax Level 3's narrowed ident table:
\x00and lone surrogates (all browsers): HTML5 attribute parsing, UTF-8 serialization, and CSS Syntax Level 3 §3.3 preprocessing replace both withU+FFFD, which is a valid CSS3 non-ASCII ident code point (0xfdf0–0xfffd). Browsers parse\x00url(/\ud800url(as a<function-token>, whileisValidStyleValueparsesurl(as an unquoted<url-token>.- Non-ASCII non-ident code points like
\u200band\u00a0(live in Chrome/Blink): Blink still treats all code points>= U+0080as ident code points, so narrowing the ident table fixes the CSS3-engine direction (\u200burl(a/*); ... */)) but opens the reverse direction in Chrome:
// All pass isValidStyleValue() and apply `position: fixed` in Chrome:
el.style.setProperty('background-image', '\x00url(a/*) "*/); position: fixed; --a: "');
el.style.setProperty('background-image', '\ud800url(a/*) "*/); position: fixed; --a: "');
el.style.setProperty('background-image', '\u200burl(a/*) "*/); position: fixed; --a: "');
el.style.setProperty('background-image', 'a\u00a0url(a/*) "*/); position: fixed; --a: "');Tracking a boolean prevAmbiguousUrlPrefix — set to ch === 0 || ch >= 0x80 in this delimiter fallback (which valid non-ASCII idents and surrogate pairs never reach), reset to false on every other token (including whitespace and comments), and returning false when url( is seen with prevAmbiguousUrlPrefix === true — closes both directions across Blink and CSS3 engines without rejecting valid CSS.
| // Pass in a string like "margin-left: 5px; border-style: solid" | ||
| // and this function returns an object like | ||
| // {"margin-left":"5px", "border-style":"solid"} | ||
| function parseStyles(value) { |
There was a problem hiding this comment.
Minor reparse edge case in parseStyles() (lines 459–462): value.endsWith(IMPORTANT_BANG) does not check whether ! is escaped by an odd number of preceding backslashes.
Calling el.style.setProperty('--x', 'foo\\!important') is accepted by isValidStyleValue (valid single ident with escaped !), but on reparse parseStyles() strips !important, setting priority['--x'] = 'important' and leaving property['--x'] = 'foo\\' (a trailing backslash). Counting contiguous \ characters immediately before !important and only stripping when the count is even fixes this.
| * @returns An array of style property name and value pairs, e.g. `['color', 'red', 'height', | ||
| * 'auto']` | ||
| */ | ||
| function isUrlOpen(value, parenIdx) { |
There was a problem hiding this comment.
Because isUrlOpen() looks backwards with an ASCII-only heuristic, several values accepted by isValidStyleValue still split into a live position: fixed; declaration on round-trip (domino.createDocument(el.outerHTML) + removeProperty):
- Non-ASCII ident characters before
url((isUrlOpenonly checks ASCII[a-zA-Z0-9_-]):'a\u00e9url(a/* ); position: fixed; --a: */)'and'a\ud83d\ude00url(a/* ); position: fixed; --a: */)'. - Escaped
<before!--url((isUrlOpenmatches<!--atparenIdx - 7..4without knowing<was escaped by\):'\\<!--url(a/* ); position: fixed; --a: */)'. #url(,@url(, and hex-escape + consumed space like#\61 url((once#and@are tokenized inisValidStyleValue):'#url(a/* ); position: fixed; --a: */)','@url(a/* ); position: fixed; --a: */)','#\\61 url(a/* ); position: fixed; --a: */)'.
Replacing the backwards isUrlOpen() lookup with a small forward urlState integer in parse() (0 = token boundary, 1/2/3 = u/ur/url, -1 = inside ident/#/@/\/non-ASCII) avoids lookbehind issues completely:
case 92(\): skip next char (and if hex digit, consume up to 5 more hex digits + optional single CSS whitespace), seturlState = -1.case 60(<): if followed by!--, advance past!--; seturlState = 0.case 45(-): ifurlState === 0and followed by->, advance past->and seturlState = 0; elseurlState = -1.case 35(#) /case 64(@): seturlState = -1.case 40((): enter unquotedurl(...)scanning only whenurlState === 3, then reseturlState = 0.- Comments/strings/brackets/delimiters reset
urlState = 0; other ident chars (a-z,A-Z,0-9,_,>= 0x80) advance0->1->2->3foru/r/l, else-1.
Update `@angular/domino` to commit `b9790cece4dff4f248ce8a2f6e24042b6de2f39a` (angular/domino#60), which enforces CSS Syntax Level 3 single-declaration validation in `CSSStyleDeclaration.prototype.setProperty`. This prevents CSS property injection via single-property style bindings (`[style.<prop>]`, `[style.<prop>.<unit>]`, `[style.--<var>]`) during SSR.
Summary
Fixes CSS property injection in
CSSStyleDeclaration.prototype.setPropertywhere values containing both;and the substringdata:bypassed the semicolon guard (if (value.includes(";") && !value.includes("data:")) return;), causingparseStyles(property + ":" + value)to parse and serialize multiple CSS declarations into thestyleattribute.Changes
data:check and multi-propertyparseStylesloop inCSSStyleDeclaration.prototype.setPropertywith CSS Syntax Level 3–aligned single-declaration validation (isValidPropertyNameandisValidStyleValue):;(while still allowing semicolons inside valid strings, comments, balanced parentheses/brackets, andurl(...)tokens such asurl(data:image/png;base64,...)).(),[],{}delimiters, unclosed quotes or comments, unescaped newlines in strings (<bad-string-token>), malformed unquotedurl(...)tokens (where/*is not a comment), escaped function names (e.g.\75 rl(...)), trailing/invalid backslashes, and!importantinside the value.styles.property[property].test/domino.js(styleSetPropertyValidation) covering both rejected injection/parser-differential payloads and legitimate CSS values.