Wednesday, September 20, 2017

CSP (Content Security Policy)

CSP (Content Security Policy) is a tool which developers can use to lock down their applications in various ways, mitigating the risk of content injection vulnerabilities such as cross-site scripting, and reducing the privilege with which their applications execute.

CSP is not intended as a first line of defense against content injection vulnerabilities. Instead, CSP is best used as defense-in-depth. It reduces the harm that a malicious injection can cause, but it is not a replacement for careful input validation and output encoding.

Besides CSP, Web application should try to avoid Cross-site Scripting (XSS), Cross-Site Request Forgery (CSRF) etc security attacks.

There are two options to implement CSP, one is on server side through HTTP response header, the other is client side through HTML meta element. Here are the details:

The Content-Security-Policy HTTP response header field is the preferred mechanism for delivering a policy from a server to a client.
Content-Security-Policy: script-src 'self';
                         report-to csp-reporting-endpoint
The Content-Security-Policy-Report-Only HTTP response header field allows web developers to experiment with policies by monitoring (but not enforcing) their effects.
Content-Security-Policy-Report-Only: script-src 'self';
                                     report-to csp-reporting-endpoint
A Document may deliver a policy via one or more HTML meta elements whose http-equiv attributes are an ASCII case-insensitive match for the string "Content-Security-Policy".
<meta http-equiv="Content-Security-Policy" content="script-src 'self'">
There are many directives including script-src, frame-src, style-src, image-src etc to define the content security policies. For details, please check out https://www.w3.org/TR/CSP

2 comments:

  1. https://content-security-policy.com/
    Content-Security-Policy Examples
    Here a few common scenarios for content security policies:

    Allow everything but only from the same origin

    default-src 'self';
    Only Allow Scripts from the same origin

    script-src 'self';
    Allow Google Analytics, Google AJAX CDN and Same Origin

    script-src 'self' www.google-analytics.com ajax.googleapis.com;
    Starter Policy

    This policy allows images, scripts, AJAX, and CSS from the same origin, and does not allow any other resources to load (eg object, frame, media, etc). It is a good starting point for many sites.

    default-src 'none'; script-src 'self'; connect-src 'self'; img-src 'self'; style-src 'self';

    ReplyDelete


  2. ‘self’
    ‘unsafe-inline’
    ‘unsafe-eval’
    ‘none’
    ‘nonce-’

    ‘strict-dynamic’
    ‘report-sample’

    ReplyDelete