Lab 14: Security & CSP

Time: 60 minutes | Level: Architect | Docker: node:20-alpine

Overview

CSS security engineering: Content-Security-Policy for styles (nonce-based and hash-based), CSS injection attack vectors, CSS exfiltration attacks via attribute selectors, Subresource Integrity, and eliminating unsafe-inline.


Step 1: Content-Security-Policy Fundamentals

CSP style-src directive controls which CSS can execute:

INSECURE (allows any inline styles):
  Content-Security-Policy: style-src 'self' 'unsafe-inline'

SECURE (hash-based inline):
  Content-Security-Policy: style-src 'self' 'sha256-<hash>'

SECURE (nonce-based inline):
  Content-Security-Policy: style-src 'self' 'nonce-<random>'

SECURE (no inline at all):
  Content-Security-Policy: style-src 'self'

Level of restriction (weakest → strongest):
  unsafe-inline → nonce → hash → 'self' only → none

Step 2: Nonce-Based CSP

💡 The nonce must be cryptographically random (≥128 bits) and unique per request. Never reuse nonces — they lose their security value.


Step 3: Hash-Based CSP


Step 4: CSS Injection Attacks


Step 5: CSS Exfiltration Attacks


Step 6: Subresource Integrity (SRI)


Step 7: Complete CSP Header Strategy


Step 8: Capstone — CSP Hash Generator

📸 Verified Output:


Summary

Attack Vector
Risk
Mitigation

unsafe-inline

XSS via injected styles

Use nonce or hash

Dynamic CSS injection

CSS exfiltration

Whitelist + sanitize

External stylesheet

Supply chain attack

SRI integrity hash

Attribute exfiltration

Data leak via selectors

CSP img-src + connect-src

User-controlled url()

SSRF / data exfiltration

Block external img-src

Clickjacking via CSS

UI redressing

frame-ancestors 'none'

Last updated