Sub topic 12
Security: Content Security Policy and Inline Styles
This chapter covers how a Content Security Policy (CSP) changes the way the three CSS methods behave, and what you can do when a policy blocks your styles. It assumes you can write a rule with a selector, property and value. It also assumes you know how the style attribute, the style element and the link element work, and that you can read an HTTP response header.
Why styles are a security concern
CSS looks harmless next to JavaScript, but it can still be abused. If an attacker can inject markup into your page, they may also be able to inject styles. Injected styles can do the following:
- Hide real content and show fake content, such as a counterfeit login prompt.
- Cover buttons with invisible elements so users click something they did not intend to (clickjacking).
- Leak data. Attribute selectors combined with
background-image: url(...)can make the browser send requests that reveal the value of an attribute, such as a token in a hidden form field.
A Content Security Policy is a defence against this kind of injection. It is a rule set the server sends with the page. The browser enforces it and refuses to load or apply anything the policy does not allow.
What a Content Security Policy is
A CSP is delivered as an HTTP response header. It contains one or more directives. Each directive names a kind of resource and lists the sources the browser may load it from.
Content-Security-Policy: style-src 'self'This policy has one directive, style-src, which controls where CSS can come from. The value 'self' means "the same origin as this page". An origin is the combination of scheme, host and port, for example https://example.com:443.
Note that the quotes around 'self' are part of the syntax. Without them, self would be read as a hostname.
The effect on the three methods is the part that surprises people:
| Method | Allowed by `style-src 'self'`? | Why |
|---|---|---|
| `<link rel="stylesheet" href="/css/site.css">` | Yes, if the file is on the same origin | The file is fetched from an allowed source |
| `<style>` element | No | The CSS is written into the page, not fetched from a source |
| `style="..."` attribute | No | Same reason, the CSS is inline |
Under a strict policy, external stylesheets are the only method that works without extra configuration. Inline CSS is blocked by default.
What "blocked" looks like
When a policy blocks inline CSS, the page still loads, but the affected styles are not applied. The following page would render with default browser styles if the server sent the header above:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Blocked inline styles</title>
<style>
p { color: darkblue; }
</style>
</head>
<body>
<p>The style element above is blocked.</p>
<p style="color: crimson;">The style attribute is blocked too.</p>
</body>
</html>Both paragraphs appear in the default colour. The browser developer console shows an error. In Chrome it reads along the lines of "Refused to apply inline style because it violates the following Content Security Policy directive". The exact wording differs between browsers, but the console is the first place to look when styles are missing on a site that uses a CSP.
Directives that matter for CSS
style-src is the main directive, but two related directives let you treat the element and the attribute differently.
| Directive | Controls |
|---|---|
| `style-src` | All CSS: linked files, `style` elements, and `style` attributes |
| `style-src-elem` | Linked stylesheets and `style` elements |
| `style-src-attr` | `style` attributes only |
| `default-src` | Fallback for any resource type that has no directive of its own |
If style-src is missing, the browser falls back to default-src. If both are missing, CSS is not restricted at all. The more specific directives, style-src-elem and style-src-attr, override style-src for their own targets. This lets you, for example, allow style elements through a nonce while blocking all style attributes.
Ways to allow inline styles
You have three options when your site needs inline CSS under a policy. They differ greatly in safety.
Option 1: `'unsafe-inline'`
Content-Security-Policy: style-src 'self' 'unsafe-inline'This allows every inline style. It is easy and it works, but it removes most of the protection that style-src gives you against injected CSS. The keyword name is a deliberate warning.
Option 2: a nonce
A nonce is a random value that the server generates fresh for each response. The server puts it in the header and in the nonce attribute of each style element it wants to allow.
Content-Security-Policy: style-src 'self' 'nonce-r4nd0mValue123'<style nonce="r4nd0mValue123">
p { color: darkblue; }
</style>The browser applies only the style elements whose nonce matches the header. An attacker who injects a <style> element cannot guess the value, so the injected element is ignored.
Two details matter in practice:
- The nonce must be unpredictable and must change on every response. A fixed nonce in your template is the same as no protection.
- Nonces apply to
styleelements. They do not apply tostyleattributes. The attribute has nononceattribute of its own.
Option 3: a hash
A hash policy allows one exact piece of CSS. You compute a SHA-256, SHA-384 or SHA-512 hash of the content between the <style> tags and list it in the header.
Content-Security-Policy: style-src 'self' 'sha256-BASE64HASHGOESHERE='The hash is of the exact characters, including whitespace and newlines. Change one space in the CSS and the hash no longer matches. Hashes suit static pages whose inline CSS never changes. For pages that are generated per request, nonces are easier.
You can find the correct hash by loading the page and reading the console. Browsers print the hash they computed when they block an inline style.
Comparing the options
| Option | Safe against injected CSS? | Works for `style` attributes? | Extra work |
|---|---|---|---|
| `'unsafe-inline'` | No | Yes | None |
| Nonce | Yes | No | Server must generate a nonce per response |
| Hash | Yes | Only with `'unsafe-hashes'` | Recompute whenever the CSS changes |
The 'unsafe-hashes' keyword lets hashes match inline event handlers and style attributes. It weakens the policy somewhat, because it allows that specific attribute content wherever it appears.
The practical way to comply: move styles out
The cleanest way to satisfy a strict policy is to avoid inline CSS altogether. Replace style attributes with classes, and put the rules in an external stylesheet.
Before:
<p style="color: crimson; font-weight: bold;">Warning: low disk space.</p>After:
<link rel="stylesheet" href="/css/site.css">
<p class="warning">Warning: low disk space.</p>/* /css/site.css */
.warning {
color: crimson;
font-weight: bold;
}This page works under style-src 'self' with no relaxations. It also follows the maintenance advice from earlier chapters: one rule can serve many elements.
Styles set from JavaScript
The style attribute rule has a subtlety. A script that sets styles through the CSSOM (the browser's object model for CSS) is treated differently from markup that carries a style attribute.
<script src="/js/app.js"></script>// Allowed under style-src 'self': this uses the CSSOM, not markup.
document.querySelector("p").style.color = "crimson";
// Blocked under style-src 'self': this inserts a style attribute as text.
document.querySelector("p").setAttribute("style", "color: crimson;");Assigning to element.style.color or calling element.style.setProperty(...) is allowed. Calling setAttribute("style", ...) or inserting HTML that contains a style attribute is checked against the policy and blocked. If your site must change styles dynamically, prefer toggling classes with classList.add() or using the CSSOM properties.
Other places a CSP affects CSS
@import. Stylesheets loaded with@importare checked againststyle-srclike any other fetch. The imported URL must match an allowed source.- Fonts and images in CSS. A
url()inside a rule is governed by other directives, notstyle-src. Fonts needfont-src, and background images needimg-src. Your stylesheet can load understyle-srcand still have its font blocked. - Third-party stylesheets. Linking to a CDN needs that host in the policy, for example
style-src 'self' https://cdn.example.com. - Report-only mode. The
Content-Security-Policy-Report-Onlyheader logs violations without blocking anything. Use it to find which inline styles you have before you enforce a policy.
Content-Security-Policy-Report-Only: style-src 'self'; report-uri /csp-reportsA safe rollout process
Adding a policy to an existing site can break pages. A sequence that limits the risk:
- Send the policy in report-only mode and collect the violation reports.
- Find each inline
styleelement andstyleattribute that triggers a report. - Move the rules to an external stylesheet and replace attributes with classes.
- For the
styleelements you cannot move, add nonces. - Switch from report-only to the enforcing header.
- Keep monitoring reports after the switch.
Where this fits in choosing a method
This chapter feeds the decision covered in the next part of the tutorial. The security trade-off can be stated simply. External stylesheets work under the strictest policies. Internal style elements need a nonce or hash. Inline style attributes need 'unsafe-inline' or 'unsafe-hashes', which weakens the policy. If your site has, or may later adopt, a CSP, that is a strong reason to prefer external styles.
Exercises
Exercise
A server sends Content-Security-Policy: style-src 'self'. A page has a linked file /css/site.css on the same origin, a <style> element in the head, and a paragraph with style="color: red;". Which of the three are applied?
Show answer
Only the linked stylesheet. The style element and the style attribute are inline CSS, which style-src 'self' blocks because it does not include 'unsafe-inline', a nonce, or a matching hash.
Exercise
Your page needs one <style> element. You want to allow it without using 'unsafe-inline'. Describe two ways to do so, and name one situation where each is the better choice.
Show answer
Use a nonce: the server generates a random value per response, puts 'nonce-VALUE' in the header, and adds nonce="VALUE" to the style element. This suits pages generated for each request. Or use a hash: compute the SHA-256 hash of the exact CSS text and list 'sha256-...' in the header. This suits a static page whose inline CSS never changes.
Exercise
Under style-src 'self', which of these JavaScript lines is blocked, and why? (a) el.style.color = "red"; (b) el.setAttribute("style", "color: red;");
Show answer
Line (b) is blocked. It creates a style attribute from text, which counts as inline CSS and is checked against the policy. Line (a) uses the CSSOM, which the policy does not block.