diff --git a/tutorials/html/16-security/content-security-policy.mdx b/tutorials/html/16-security/content-security-policy.mdx new file mode 100644 index 000000000..6f81c1f68 --- /dev/null +++ b/tutorials/html/16-security/content-security-policy.mdx @@ -0,0 +1,576 @@ +--- +id: html-sec-content-security-policy +title: "Content Security Policy (CSP)" +sidebar_label: "Content Security Policy" +sidebar_position: 8 +slug: /html/security/content-security-policy +description: "Learn how a Content Security Policy tells the browser which sources of scripts, styles, images, frames and forms to trust. Covers directives, source values, nonces, report-only rollout, and the meta tag's limits, with a live policy tester and a directive matcher." +keywords: + - content security policy + - CSP header + - CSP meta tag + - script-src + - default-src + - nonce + - unsafe-inline + - frame-ancestors + - report-only + - learn HTML + - CodeHarborHub HTML +tags: [html, web-development, beginner, security, csp, xss, headers, frontend] +--- + +import {useState} from 'react'; + +export const cspPage = "https://www.example.com/"; + +export const cspResources = [ + {id: "r1", label: "Inline script in the page", dir: "script-src", kind: "inline"}, + {id: "r2", label: 'Inline script with nonce="r4nd0m"', dir: "script-src", kind: "inline", nonce: "r4nd0m"}, + {id: "r3", label: "onclick attribute on a button", dir: "script-src", kind: "attr"}, + {id: "r4", label: "Script from /app.js (your site)", dir: "script-src", kind: "url", url: "https://www.example.com/app.js"}, + {id: "r5", label: "Script from cdn.example.net", dir: "script-src", kind: "url", url: "https://cdn.example.net/lib.js"}, + {id: "r6", label: "Stylesheet from /site.css (your site)", dir: "style-src", kind: "url", url: "https://www.example.com/site.css"}, + {id: "r7", label: "style attribute on an element", dir: "style-src", kind: "attr"}, + {id: "r8", label: "Image from /logo.png (your site)", dir: "img-src", kind: "url", url: "https://www.example.com/logo.png"}, + {id: "r9", label: "Image from images.example.org", dir: "img-src", kind: "url", url: "https://images.example.org/photo.jpg"}, + {id: "r10", label: "Image as a data: address", dir: "img-src", kind: "url", url: "data:image/png;base64,AAAA"}, + {id: "r11", label: "Font from fonts.example.com", dir: "font-src", kind: "url", url: "https://fonts.example.com/body.woff2"}, + {id: "r12", label: "Frame from widgets.example.net", dir: "frame-src", kind: "url", url: "https://widgets.example.net/map"}, + {id: "r13", label: "fetch() call to api.example.com", dir: "connect-src", kind: "url", url: "https://api.example.com/data"} +]; + +export const cspPresets = { + none: "", + starter: "default-src 'self'; img-src 'self' https://images.example.org data:; font-src https://fonts.example.com; frame-src https://widgets.example.net; connect-src 'self' https://api.example.com; object-src 'none'; base-uri 'self'; frame-ancestors 'self'", + nonce: "default-src 'self'; script-src 'self' 'nonce-r4nd0m'; style-src 'self'; img-src 'self' https://images.example.org data:; font-src https://fonts.example.com; frame-src https://widgets.example.net; connect-src 'self' https://api.example.com; object-src 'none'; base-uri 'self'; frame-ancestors 'self'", + loose: "default-src *; script-src * 'unsafe-inline' 'unsafe-eval' data:" +}; + +export function parseCsp(text) { + const map = Object.create(null); + text.split(";").forEach(function (part) { + const t = part.trim().split(/\s+/).filter(Boolean); + if (t.length === 0) return; + const name = t[0].toLowerCase(); + if (!(name in map)) map[name] = t.slice(1); + }); + return map; +} + +export function sourceMatches(src, urlText, pageText) { + let u; + let page; + try { + u = new URL(urlText, pageText); + page = new URL(pageText); + } catch (e) { + return false; + } + const s = src.trim(); + const low = s.toLowerCase(); + if (low === "'none'") return false; + if (low === "*") return ["http:", "https:", "ws:", "wss:"].indexOf(u.protocol) !== -1; + if (low === "'self'") return u.origin === page.origin; + if (/^[a-z][a-z0-9+.-]*:$/.test(low)) return u.protocol === low || (low === "http:" && u.protocol === "https:"); + if (low.charAt(0) === "'") return false; + let rest = low; + let scheme = null; + const sm = rest.match(/^([a-z][a-z0-9+.-]*):\/\//); + if (sm) { + scheme = sm[1] + ":"; + rest = rest.slice(sm[0].length); + } + rest = rest.split("/")[0]; + let port = null; + const pm = rest.match(/:(\d+|\*)$/); + if (pm) { + port = pm[1]; + rest = rest.slice(0, rest.length - pm[0].length); + } + if (scheme) { + if (!(u.protocol === scheme || (scheme === "http:" && u.protocol === "https:"))) return false; + } else if (u.protocol !== page.protocol && u.protocol !== "https:") { + return false; + } + let hostOk; + if (rest === "*") hostOk = true; + else if (rest.indexOf("*.") === 0) hostOk = u.hostname.length > rest.length - 1 && u.hostname.slice(-(rest.length - 1)) === rest.slice(1); + else hostOk = u.hostname === rest; + if (!hostOk) return false; + if (port && port !== "*") return u.port === port; + return true; +} + +export function resourceAllowed(res, sources) { + if (res.kind === "url") { + return sources.some(function (s) { return sourceMatches(s, res.url, cspPage); }); + } + const lower = sources.map(function (s) { return s.toLowerCase(); }); + const hasNonceOrHash = lower.some(function (s) { return /^'(nonce-|sha(256|384|512)-)/.test(s); }); + if (res.kind === "inline" && res.nonce && lower.indexOf("'nonce-" + res.nonce.toLowerCase() + "'") !== -1) return true; + return lower.indexOf("'unsafe-inline'") !== -1 && !hasNonceOrHash; +} + +export function evaluateCsp(text) { + const map = parseCsp(text); + return cspResources.map(function (res) { + let via = null; + let sources = null; + if (map[res.dir]) { via = res.dir; sources = map[res.dir]; } + else if (map["default-src"]) { via = "default-src"; sources = map["default-src"]; } + if (sources === null) return {res: res, allowed: true, via: "no rule"}; + return {res: res, allowed: resourceAllowed(res, sources), via: via}; + }); +} + +export function lintCsp(text) { + const map = parseCsp(text); + const out = []; + const scriptSources = (map["script-src"] || map["default-src"] || null); + const lower = (scriptSources || []).map(function (s) { return s.toLowerCase(); }); + const hasNonce = lower.some(function (s) { return /^'(nonce-|sha(256|384|512)-)/.test(s); }); + if (text.trim() === "") { + out.push({level: "problem", text: "No policy: the browser applies no restrictions."}); + return out; + } + if (scriptSources === null) out.push({level: "problem", text: "No script-src or default-src, so scripts are unrestricted."}); + if (lower.indexOf("'unsafe-inline'") !== -1 && !hasNonce) out.push({level: "problem", text: "'unsafe-inline' in the script rules lets injected inline scripts run, which removes most of CSP's protection against XSS."}); + if (lower.indexOf("'unsafe-inline'") !== -1 && hasNonce) out.push({level: "tip", text: "Browsers ignore 'unsafe-inline' when a nonce or hash is present. It is only a fallback for very old browsers."}); + if (/'unsafe-eval'/i.test(text)) out.push({level: "problem", text: "'unsafe-eval' allows eval and similar functions to turn text into code."}); + if (lower.indexOf("*") !== -1 || lower.indexOf("https:") !== -1 || lower.indexOf("http:") !== -1) out.push({level: "problem", text: "A wildcard or a bare scheme in the script rules lets almost any site supply scripts."}); + if (lower.indexOf("data:") !== -1) out.push({level: "problem", text: "data: in the script rules lets attackers run scripts written straight into an address."}); + if (!map["object-src"] && !(map["default-src"] && map["default-src"].map(function (s) { return s.toLowerCase(); }).indexOf("'none'") !== -1)) out.push({level: "tip", text: "Add object-src 'none' to switch off old plugin content."}); + if (!map["base-uri"]) out.push({level: "tip", text: "Add base-uri 'self' so an injected base tag cannot redirect your relative links."}); + if (!map["frame-ancestors"]) out.push({level: "tip", text: "Add frame-ancestors (as a header) to control who may frame your pages."}); + if (out.length === 0) out.push({level: "good", text: "No warnings from this simple check."}); + return out; +} + +export function CspTester() { + const [text, setText] = useState(cspPresets.starter); + const rows = evaluateCsp(text); + const lint = lintCsp(text); + const blocked = rows.filter(function (r) { return !r.allowed; }).length; + const colors = {problem: "#c0392b", tip: "#b9770e", good: "#1e8449"}; + const labels = {problem: "Problem", tip: "Tip", good: "Good"}; + return ( +
+

Your page is {cspPage}. Edit the policy, or load an example.

+
+ + + + +
+ +