Course contentsShow
← Security
Lesson 659 of 3,05214. Web Security - XSS and Content InjectionFree lesson

script-src Directive Deep Dive

Controlling script execution sources, understanding inline scripts, and the dangers of unsafe directives.

script-src Directive Deep Dive

What you'll learn: How the script-src directive controls where JavaScript can execute from and why inline scripts create security risks.

What is script-src?

The script-src directive is CSP's most critical line of defense against XSS attacks. It explicitly defines which sources are allowed to execute JavaScript on your page. Think of it as a whitelist bouncer at a club—only scripts from approved sources get in.

Basic Syntax

Content-Security-Policy: script-src 'self' https://trusted.example.com

This policy allows scripts from:

  • Your own domain ('self')
  • The specific trusted domain listed

Any script from elsewhere gets blocked by the browser.

The Inline Script Problem

By default, script-src blocks all inline JavaScript—including <script> tags in your HTML, onclick handlers, and javascript: URLs. This might seem harsh, but inline scripts are the primary XSS attack vector. If an attacker injects <script>alert(1)</script>, a strict CSP stops it cold.

Unsafe Directives: Convenient but Dangerous

'unsafe-inline' — Allows inline scripts. This essentially disables CSP's XSS protection. It's like leaving your front door unlocked because finding your keys is inconvenient.

Content-Security-Policy: script-src 'self' 'unsafe-inline'

'unsafe-eval' — Permits eval() and similar dangerous JavaScript functions that execute strings as code. Attackers love this.

Both directives defeat CSP's purpose and should be avoided. Use nonces or hashes instead for legitimate inline scripts (covered in later lessons).

Why This Matters

Most XSS exploits rely on executing attacker-controlled JavaScript. By restricting script sources, script-src creates a powerful barrier even when input validation fails.

Key Takeaway: The script-src directive is your primary XSS defense mechanism—it whitelists JavaScript sources, blocks inline scripts by default, and should never use 'unsafe-inline' or 'unsafe-eval' in production without compelling justification.