HTTP - Content security policy (CSP)

About

CSP 1) is a security response header that defines the behaviors that are trusted in your HTML page.

In particular, it may restrict by defining the allowed host and origin of fetched resources.

CSP can be used to detect and mitigate against the effects of certain attacks, such as:

CSP is particularly powerful as it includes directives such as script-src that specifies what are valid, allowed sources for JavaScript.

Example

Basic: Allowing all Third party script from a host

Content-Security-Policy: script-src https://example.com/
<script src="https://not-example.com/js/library.js"></script>

Allow resources by path matching (bootstrap example)

This CSP will allow scripts and stylesheet from Boostrap.

Content-Security-Policy: default-src https://cdn.jsdelivr.net/npm/[email protected]/

This security policy will match:

There is actually no match expression on the path, you need to terminate the path with a forward slash to match the rest of the path.

Allow resources by nonce matching

This method relies on the generation of a nonce for each request / page generation.

Example:

  • given this nonce in the HTTP header
Content-Security-Policy: script-src 'nonce-{SERVER-GENERATED-NONCE}'
  • You can allow a resource script in your HTML tag by specifying the nonce.
<script nonce='{SERVER-GENERATED-NONCE}'>...</script>

Block HTTP call on HTTPS page

 
<meta http-equiv="Content-Security-Policy" content="block-all-mixed-content" />

Reporting

Content-Security-Policy-Report-Only: default-src 'self' *.ezoic.net; img-src www.googletagmanager.com ; report-uri https://api.gerardnico.com/csp 

Example of Json send. The definition can be found in the specification.

{
  "csp-report": {
    "document-uri": "http://example.com/signup.html",
    "referrer": "",
    "blocked-uri": "http://example.com/css/style.css",
    "violated-directive": "style-src cdn.example.com",
    "original-policy": "default-src 'none'; style-src cdn.example.com; report-uri /_/csp-reports",
    "disposition": "report"
  }
}

Syntax

Content-Security-Policy: <policy-directive>; <policy-directive>
  • With a few exceptions, policies mostly involve specifying server origins and script endpoints.
  • Your policy should include a default-src policy directive, which is a fallback for other resource types when they don't have policies of their own

Doc

More info

Google Publisher tag

Ref: If you have a Content Security Policy (CSP) on your site, the restrictions of the CSP also apply to AMPHTML ads in friendly iframes. In that case, call googletag.pubads().setForceSafeFrame(true) before making any ad requests, to allow the ad to render in a cross-domain iframe without the CSP's restrictions

Read: