Web Security Content Security Policy (CONTENT-SECURITY-POLICY,CSP) detailed

Source: Internet
Author: User
Tags http post

1.CSP Introduction

Content security Policy, or CSP, is a trusted whitelist mechanism to limit whether a site can contain some source content and mitigate a wide range of content injection vulnerabilities, such as XSS. Simply put, we can stipulate that our website only accepts the requested resources we specify. The default configuration does not allow inline code execution ( <script> block content, inline events, inline styles), and suppresses the execution of eval (), Newfunction (), SetTimeout ([string], ...), and setinterval ([string], ...).

How to use 2.CSP

CSPs can be specified in two ways: HTTP headers and HTML.

    • Used in HTTP headers by definition:

      "Content-Security-Policy:" 策略集
    • Used in HTML meta tags by definition:

      <meta http-equiv="content-security-policy" content="策略集">

A policy is a syntax that defines the content of a CSP.

If the HTTP header and the META tag define the CSP at the same time, the HTTP header will be taken precedence.

Once defined, any external resources that do not conform to the CSP policy will be blocked from loading.

3.CSP Syntax 3.1 policy

Each strategy is composed of instruction and instruction values:

Content-Security-Policy:指令1 指令值1

The policy and policy are separated by semicolons, for example:

Content-Security-Policy:指令1 指令值1;指令2 指令值2;指令3 指令值3

In one policy, if there are multiple instruction values in one instruction, the instruction values are separated by a null number:

Content-Security-Policy:指令a 指令值a1 指令值a2
3.2 CSP directive
    • DEFAULT-SRC: Defines the default load policy for all types of resources (js/image/css/font/ajax/iframe/multimedia, etc.), and if a type resource does not have a separate policy defined, the default is used.
    • SCRIPT-SRC: Defines the load policy for JavaScript.
    • STYLE-SRC: Defines the load policy for the style.
    • IMG-SRC: Defines the load policy for the picture.
    • FONT-SRC: Defines the load policy for the font.
    • MEDIA-SRC: Defines the loading strategy for multimedia, such as audio tags <audio> and video tags <video> .
    • OBJECT-SRC: Defines the load policy for the plug-in, such as: <object> ,, <embed> <applet> .
    • CHILD-SRC: Defines the load policy for the framework, for example: <frame> <iframe> .
    • CONNECT-SRC: Defines a load policy for requests such as Ajax/websocket. When not allowed, the browser simulates a response with a status of 400.
    • Sandbox: Defines the sandbox-specific restrictions, equivalent to <iframe> the sandbox properties.
    • Report-uri: tells the browser which address to submit the log information to if the requested resource is not allowed by policy.
    • Form-action: Defines the load policy for a submitted form to a specific source.
    • Referrer: Defines the load policy for referrer.
    • REFLECTED-XSS: Defines the use policy for XSS filters.
3.3 CSP Instruction Value
Instruction Value Description
* Allow any content to load
' None ' Do not allow any content to load
' Self ' Allow loading of content from the same source
Www.a.com Allow resources for the specified domain name to be loaded
*.a.com Allow resources to load a.com any subdomain
Https://a.com Allow loading of a.com HTTPS resources
Https Allow HTTPS resources to be loaded
Data Allow data to be loaded: protocol, for example: Base64 encoded picture
' Unsafe-inline ' Allows inline resources to be loaded, such as style properties, onclick, inline js, inline CSS, and more
' Unsafe-eval ' Allows dynamic JS code to be loaded, such as eval ()
4.CSP Example
    • Example 1

      All content comes from the site's own domain:

      Content-Security-Policy:default-src ‘self‘
    • Example 2

      All content comes from the site's own domain, as well as other subdomains (if the site's address is: a.com):

      Content-Security-Policy:default-src ‘self‘ *.a.com
    • Example 3

      Web site accepts images from any domain, specifies the domain (a.com) of audio, video, and scripts for multiple specified domains (a.com, B.Com)

      Content-Security-Policy:default-src ‘self‘;img-src *;media-src a.com;script-src a.com b.com
    • Web site prepared by the online CSP: http://cspisawesome.com/

5.CSP Default Features
  • block inline code execution

    CSPs in addition to using the whitelist mechanism, blocking inline code execution under the default configuration is the maximum security against content injection. The inline code
    here includes: <script> block contents, inline events, inline styles.

    (1) script code, <script>......<scritp>

    for <script> block content is completely unenforceable. For example:

      <script>getyourcookie () </script>  

    (2) inline events.

      <a href= "" onclick= "Handleclick ();" ></a> <a href= "Javascript:handleclick (); ></a>  

    (3) inline style

      <div style= "Display:none" ></div>  

    Although SCRIPT-SRC and style-src have been provided with the "unsafe-inline" directive to enable the execution of inline code, the "Unsafe-inline" is used sparingly for security purposes.

  • Eval-related features are disabled

    The user enters a string and is then escaped by a function such as eval () to be executed as a script. This type of attack is more common. So the CSP default configuration, eval (), Newfunction (), SetTimeout ([string], ...) and setinterval ([string], ...) are forbidden to run.
    Like what:

    alert(eval("foo.bar.baz"));window.setTimeout("alert(‘hi‘)", 10); window.setInterval("alert(‘hi‘)", 10); new Function("return foo.bar.baz");

    If you want to do this, you can convert the string to an inline function to execute.

    alert(foo && foo.bar && foo.bar.baz);window.setTimeout(function() { alert(‘hi‘); }, 10);window.setInterval(function() { alert(‘hi‘); }, 10);function() { return foo && foo.bar && foo.bar.baz };

    The same CSP also provides "unsafe-eval" to open functions such as eval (), but it is strongly not recommended to use the "unsafe-eval" directive.

6.CSP Analysis Report

You can use the Report-uri directive to send the browser an HTTP POST request to transmit the attack report in JSON format to the address you specify. Next, we'll show you how your site is configured to receive attack reports.

  • Enable reporting

    By default, the violation report is not sent. In order to be able to use the violation report, you must use the Report-uri directive and provide at least one receive address.

    Content-Security-Policy: default-src self; report-uri http://reportcollector.example.com/collector.cgi

    If you want your browser to report only reports and not block anything, you can use the Content-security-policy-report-only header instead.

  • Violation report Syntax

    The report JSON object contains the following data:

    blocked-uri:被阻止的违规资源document-uri:拦截违规行为发生的页面original-policy:Content-Security-Policy头策略的所有内容referrer:页面的referrerstatus-code:HTTP响应状态violated-directive:违规的指令
  • Examples of violation reports

    The CSP in http://example.com/signup.html specifies that only cdn.example.com CSS styles can be loaded.

    Content-Security-Policy: default-src ‘none‘; style-src cdn.example.com; report-uri /test/csp-report.php

    The code in signup.html is similar to this:

    <!DOCTYPE html>

    Can you find the error from the code above? The policy is to allow only CSS styles in the cdn.example.com to be loaded. But signup.html tries to load the STYLE.CSS style of its own domain. This violates the policy, the browser sends the POST request to the http://example.com/test/csp-report.php to submit the report, the sending format is the JSON format.

    { "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", }}

    You can see from above that Blocked-uri gives a detailed block address http://example.com/css/style.css, but it is not always the case. For example, when attempting to load a CSS style from Http://anothercdn.example.com/stylesheet.css, the browser will not transmit the full path and will only give the http://anothercdn.example.com/address. This is done to prevent the leakage of sensitive information across domains.

    The server-side csp-report.php code can write this:

    <?php $file = fopen(‘csp-report.txt‘, ‘a‘);$json = file_get_contents(‘php://input‘);$csp = json_decode($json, true);foreach ($csp[‘csp-report‘] as $key => $val) { fwrite($file, $key . ‘: ‘ . $val . "");}fwrite($file, ‘End of report.‘ . "");fclose($file);?>
7. Reference Links
    • Http://www.ruanyifeng.com/blog/2016/09/csp.html
    • http://blog.topsec.com.cn/ad_lab/content-security-policy/
    • 79978761
    • Https://www.jianshu.com/p/b223c5b9d5ab
    • https://content-security-policy.com/
    • Https://www.imuo.com/a/f7566a17dcfe788216bbc5245e91a631fcc259bfac97dc7f94bf8002ba38fa21
    • https://w3c.github.io/webappsec-csp/#intro
    • Https://kuaibao.qq.com/s/20180522G095D900?refer=spider

Web Security Content Security Policy (CONTENT-SECURITY-POLICY,CSP) detailed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.