Skip to content

fix: enforce single-property validation in CSSStyleDeclaration.setProperty - #60

Merged
alan-agius4 merged 3 commits into
angular:mainfrom
JeanMeche:fix/css-property-injection
Nov 26, 2026
Merged

alan-agius4 merged 3 commits into
angular:mainfrom
JeanMeche:fix/css-property-injection

Conversation

@JeanMeche

Copy link
Copy Markdown
Member

Summary

Fixes CSS property injection in CSSStyleDeclaration.prototype.setProperty where values containing both ; and the substring data: bypassed the semicolon guard (if (value.includes(";") && !value.includes("data:")) return;), causing parseStyles(property + ":" + value) to parse and serialize multiple CSS declarations into the style attribute.

Changes

  • Replaced the substring data: check and multi-property parseStyles loop in CSSStyleDeclaration.prototype.setProperty with CSS Syntax Level 3–aligned single-declaration validation (isValidPropertyName and isValidStyleValue):
    • Rejects top-level ; (while still allowing semicolons inside valid strings, comments, balanced parentheses/brackets, and url(...) tokens such as url(data:image/png;base64,...)).
    • Rejects unbalanced or mismatched (), [], {} delimiters, unclosed quotes or comments, unescaped newlines in strings (<bad-string-token>), malformed unquoted url(...) tokens (where /* is not a comment), escaped function names (e.g. \75 rl(...)), trailing/invalid backslashes, and !important inside the value.
    • Validates the property name and writes only styles.property[property].
  • Added comprehensive unit tests in test/domino.js (styleSetPropertyValidation) covering both rejected injection/parser-differential payloads and legitimate CSS values.

@JeanMeche
JeanMeche force-pushed the fix/css-property-injection branch from 046c175 to 0f37c66 Compare November 24, 2026 22:27
@alan-agius4
alan-agius4 marked this pull request as ready for review November 25, 2026 07:55

@alan-agius4 alan-agius4 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

Comment thread lib/CSSStyleDeclaration.js Outdated
}

const IMPORTANT_BANG = '!important';
const INVALID_PROPERTY_NAME_RE = /[\s:;'"(){}\[\]\/\\!]/;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Two things on property name handling:

  1. parseStyles() initializes property: {} and priority: {} as plain objects, so Object.prototype keys collide. Calling el.style.setProperty('constructor', 'red') reads inherited Object.prototype.constructor in _serialize() and emits style="constructor: red !function Object() { [native code] };". Also, el.style.setProperty('__proto__', 'red') regresses from returning early (getAttribute('style') === null) to writing style="", because isValidPropertyName('__proto__') passes and _serialize() still runs after the silent assignment. Can we initialize both with Object.create(null) in parseStyles()?
  2. Because INVALID_PROPERTY_NAME_RE is a denylist, it still accepts invalid CSS property names like '--', '123', '@import', 'a<b', and '\x00'. Since property is already lowercased in setProperty(), can we switch to an allowlist regex instead?
const VALID_PROPERTY_NAME_RE = /^(?:--[^\x00-\x20:;'"(){}\[\]\/\\!\x7f]+|-?[a-z_][a-z0-9_-]*)$/;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Two quick additions here:

  • Object.create(null) in parseStyles() also fixes removeProperty('constructor') and setPropertyPriority('constructor', 'important'), which currently hit inherited Object.prototype.constructor and spuriously serialize style="".
  • 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 parsing style="...".

Comment thread lib/CSSStyleDeclaration.js Outdated
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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

A couple of notes on the token regexes:

  1. Perf on data: URIs: In CSS_STRING_RE and CSS_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 500KB data: URIs (~960 us down to ~487 us at 500KB) while keeping disjoint first sets (O(n)).
  2. Nit: [^\x00-\x7f] in CSS_IDENT_RE merges whitespace and punctuation above U+007F (like \u00a0 or \u200b) into a following url( token ("\u00a0url"), skipping the unquoted URL check. Current Blink still treats all >= U+0080 as ident code points so it does not trigger today, but CSS Syntax Level 3 narrowed non-ASCII ident code point to exclude these ranges. Tightening that range avoids a future engine differential.
  3. Minor: CSS_UNQUOTED_URL_RE (\\[^\n\r\f]) rejects valid hex escape plus consumed whitespace/newline URLs like url(a\20 b.png), and CSS_STRING_RE rejects "a\61\nb" (both accepted by Chrome).

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Quick follow-ups on points 2 and 3:

  • On point 2: tightening [^\x00-\x7f] (and excluding lone surrogates) prevents the same url( 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_RE or CSS_UNQUOTED_URL_RE, avoid dropping CSS_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). A charCodeAt loop avoids this completely (or require a character excluded from the unescaped class after the hex digits).

Comment thread lib/CSSStyleDeclaration.js Outdated

// Whitespace (ignored for !important tracking)
CSS_WS_RE.lastIndex = i;
if (CSS_WS_RE.exec(value)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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:

  1. Calling CSS_WS_RE.exec(value) on every character (even when it is not whitespace) and CSS_IDENT_RE.exec(value) on every punctuation character (,, ., %, /, #, !), allocating a match array and substring on every match, including inside parens where token is discarded.
  2. Using .exec() on CSS_COMMENT_RE, CSS_STRING_RE, CSS_QUOTED_URL_OPEN_RE, and CSS_UNQUOTED_URL_RE even though the return value is ignored. Switching to .test() still updates .lastIndex on /y regexes without allocating match arrays or slices, and value.indexOf('*/', i + 2) is much faster for comments.
  3. 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)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Two things here:

  1. Reparse differential with lib/style_parser.js: isValidStyleValue now accepts ; inside CSS comments (/* ; */), escaped semicolons (\;), escaped parens in unquoted url(...) (\)), escaped quotes (\"), and []/{} blocks. However, lib/style_parser.js (used whenever style is reparsed on HTML round trips, setAttribute('style', ...), or cssText) does not handle comments, []/{} nesting, unquoted url(...), or backslash escapes. In fact, style_parser.js lines 50 and 61 check value.charCodeAt(i - 1) !== 92 after i++, which inspects the quote itself instead of the preceding \. As a result, a value like setProperty('color', 'red /* ; position: fixed; --a: */') or setProperty('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 update lib/style_parser.js to stay consistent with these tokenization rules (keeping a fast path when /, \, [, { are not present)?
  2. Perf: var styles = this._parsed; currently runs on line 331 before validation, so rejected calls on elements with unparsed styles still read getAttribute('style'), run parseStyles(), and delete this._names. Moving var styles = this._parsed; after this guard (and inside the value === NO_CHANGE branch) avoids that wasted work (~1.3 to 1.7x faster on rejected calls).

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Two more details to watch out for when updating lib/style_parser.js:

  1. Lines 37-42 (case 40 / case 41) also update parenDepth without checking quote === 0. As a result, setProperty('--x', 'calc(")" ; position: fixed; --a: 1)') passes isValidStyleValue and splits into a separate position: fixed declaration on reparse (and even benign content: "("; corrupts parenDepth for subsequent declarations).
  2. 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 checking i - 2), and make sure /* inside an unquoted url(...) (like url(https://example.com/*)) is not treated as starting a comment.

Comment thread test/domino.js
(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=);');
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Can we also add tests for:

  1. Reparse round trips (domino.createDocument(el.outerHTML) followed by removeProperty/getPropertyValue) for values containing /* ; */, \;, \", \) in url(), [], and {}.
  2. Prototype and invalid property names ('constructor', '__proto__', '--', '123', '@import', '\x00').
  3. setPropertyPriority (covering the NO_CHANGE.trim() fix) and verifying a rejected setProperty does not overwrite an existing valid style attribute.
  4. Standalone / values (rgb(255 0 0 / 50%), calc(100% / 2)), /*/, and a large data: URI.

@alan-agius4 alan-agius4 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

Comment thread lib/CSSStyleDeclaration.js Outdated
if (token.includes('\\')) {
return false;
}
if (token.toLowerCase() === 'url') {

@alan-agius4 alan-agius4 Nov 25, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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 (&lt;!--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 alan-agius4 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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:

  • \x00 and lone surrogates (all browsers): HTML5 attribute parsing, UTF-8 serialization, and CSS Syntax Level 3 §3.3 preprocessing replace both with U+FFFD, which is a valid CSS3 non-ASCII ident code point (0xfdf0–0xfffd). Browsers parse \x00url( / \ud800url( as a <function-token>, while isValidStyleValue parses url( as an unquoted <url-token>.
  • Non-ASCII non-ident code points like \u200b and \u00a0 (live in Chrome/Blink): Blink still treats all code points >= U+0080 as 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) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

Comment thread lib/style_parser.js Outdated
* @returns An array of style property name and value pairs, e.g. `['color', 'red', 'height',
* 'auto']`
*/
function isUrlOpen(value, parenIdx) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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):

  1. Non-ASCII ident characters before url( (isUrlOpen only checks ASCII [a-zA-Z0-9_-]): 'a\u00e9url(a/* ); position: fixed; --a: */)' and 'a\ud83d\ude00url(a/* ); position: fixed; --a: */)'.
  2. Escaped < before !--url( (isUrlOpen matches <!-- at parenIdx - 7..4 without knowing < was escaped by \): '\\<!--url(a/* ); position: fixed; --a: */)'.
  3. #url(, @url(, and hex-escape + consumed space like #\61 url( (once # and @ are tokenized in isValidStyleValue): '#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), set urlState = -1.
  • case 60 (<): if followed by !--, advance past !--; set urlState = 0.
  • case 45 (-): if urlState === 0 and followed by ->, advance past -> and set urlState = 0; else urlState = -1.
  • case 35 (#) / case 64 (@): set urlState = -1.
  • case 40 ((): enter unquoted url(...) scanning only when urlState === 3, then reset urlState = 0.
  • Comments/strings/brackets/delimiters reset urlState = 0; other ident chars (a-z, A-Z, 0-9, _, >= 0x80) advance 0->1->2->3 for u/r/l, else -1.

Comment thread test/domino.js Resolved
@alan-agius4
alan-agius4 merged commit b9790ce into angular:main Nov 26, 2026
8 checks passed
JeanMeche added a commit to JeanMeche/angular that referenced this pull request Nov 26, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants