Core Components of CSP

Core Components of CSP

Understanding CSP requires familiarity with its core components: directives, source values, and keywords. Directives control different types of resources (scripts, styles, images, etc.), while source values specify where these resources can originate. Keywords provide special instructions for handling specific scenarios.

Directives are the building blocks of CSP policies. Each directive controls a specific type of resource or behavior:

  • default-src: Serves as a fallback for other resource types
  • script-src: Controls which scripts can be executed
  • style-src: Defines allowed sources for stylesheets
  • img-src: Specifies valid sources for images
  • connect-src: Controls which URLs can be loaded using script interfaces
  • font-src: Defines valid sources for fonts
  • object-src: Controls sources for plugins like Flash
  • media-src: Specifies valid sources for audio and video
  • frame-src: Controls sources for frames and iframes

Source values tell the browser where resources can be loaded from:

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

Common source values include:

  • 'self': The same origin as the document
  • 'none': No sources allowed
  • Specific URLs: https://example.com
  • Wildcards: *.example.com
  • Schemes: https: or data:

Keywords provide special behaviors:

  • 'unsafe-inline': Allows inline scripts or styles
  • 'unsafe-eval': Permits JavaScript eval() and similar functions
  • 'strict-dynamic': Enables scripts to load additional scripts
  • 'nonce-{random}': Allows specific inline scripts via a cryptographic nonce
  • 'sha256-{hash}': Permits scripts matching a specific hash