Kenan
Assistant Engineer
Assistant Engineer
  • UID621
  • Fans1
  • Follows0
  • Posts55
Reads:2298Replies:0

[Share]Get started with Content Security Policy

Created#
More Posted time:Oct 21, 2016 9:50 AM
Abstract:  XSS (Cross Site Scripting) attacks are the most common and harmful web page security loophole. This article introduces how to use Content Security Policy (CSP) to prevent XSS attacks.
Get started with Content Security Policy

XSS (Cross Site Scripting) attacks are the most common and harmful web page security loophole.


A lot of programming effort is required to prevent them, which is very troublesome. Many have proposed automatically disabling external injection of malicious scripts by the browsers - a fundamental way to solve the issue. This is how the Content Security Policy (CSP in short) came into being. This article introduces how to use Content Security Policy (CSP) to prevent XSS attacks.


I. Introduction
CSP is essentially a whitelist mechanism. Developers clearly tell the clients which external resources can be loaded and executed, which is equal to providing a whitelist. All of its implementation and execution are completed by the browsers, and developers only provide the configuration. CSP greatly enhances the web page security. Even if the attackers find the loophole, they cannot inject the script, unless they gain the control over a trusted host in the whitelist.
There are two ways to activate CSP. One way is through the Content-Security-Policy field in the HTTP header.


   Content-Security-Policy: script-src 'self'; object-src 'none';
   style-src cdn.example.org third-party.org; child-src https:

The other way is through the <meta> tag of the web page.  
<meta http-equiv="Content-Security-Policy" content="script-src 'self'; object-src 'none'; style-src cdn.example.org third-party.org; child-src https:">

In the code above, CSP has the following configuration.
• Script: Only trust the current domain name
• <Object> tag: Do not trust any URL, that is, do not load any resources
• Style sheet: Only trust cdn.example.org and third-party.org
• Frame: HTTPS protocol must be used for loading
• Other resources: No limits
After CSP is activated, external resources that do not conform to the CSP will be blocked from being loaded.
Chrome error prompt.


Firefox error prompt.


II. Restriction options
CSP offers many restriction options involving various aspects of the security.
2.1 Resource loading restrictions
The options below limit the loading of various resources.
• Script-src: external scripts
• Style-src: style sheets
• Img-src: images
• Media-src: media files (audios and videos)
• Font-src: font files
• Object-src: plug-ins (such as Flash)
• Child-src: frameworks
• Frame-ancestors: embedded external resources (such as <frame>, <iframe>, <embed> and <applet>)
• Connect-src: HTTP connections (through XHR, WebSockets, EventSource and so on)
• Worker-src: worker scripts
• Manifest-src: manifest scripts
2.2 The default-src option
The default-src option is used to set the default values of the above options.
Content-Security-Policy: default-src 'self'

The above code limits all the external resources and only resources can only be loaded from the current domain name. If a single restriction option (such as font-src) and default-src are configured at the same time, the former will overwrite the latter, that is, the font file will adopt the font-src value, while other resources still adopt the default-src value.
2.3 URL restrictions
Sometimes, the web page will be associated with other URLs, and restrictions can apply.
Frame-ancestors: limits web pages embedded in the framework
Base-uri: limits <base#href>
Form-action: limits <form#action>
2.4. Miscellaneous
Some other security-related functions are also integrated in the CSP.
Block-all-mixed-content: HTTPS web pages cannot load HTTP resources (enabled in browsers by default)
Upgrade-insecure-requests: Automatically changes all the HTTP links for loading external resources on the web page to the HTTPS protocol
Plugin-types: limits the available plug-in formats
Sandbox: limits the browser behavior, such as pop-up windows
2.5 The report-uri option
Sometimes, we not only want to prevent XSS attacks, but also wants to record such behavior. The report-uri option tells the browser to which URL should the injection behavior be reported to.
    Content-Security-Policy: default-src 'self'; ...; report-uri /my_amazing_csp_report_parser;
The code above specifies to report the injection behavior to /my_amazing_csp_report_parser.
The browser will send a JSON object through the POST method. An example is provided below.
{
  "csp-report": {
    "document-uri": "http://example.org/page.html",
    "referrer": "http://evil.example.com/",
    "blocked-uri": "http://evil.example.com/evil.js",
    "violated-directive": "script-src 'self' https://apis.google.com",
    "original-policy": "script-src 'self' https://apis.google.com; report-uri http://example.org/my_amazing_csp_report_parser"
  }
}




III. Content-Security-Policy-Report-Only
Apart from Content-Security-Policy, there is also a Content-Security-Policy-Report-Only field which indicates not to execute the restriction options but only to record the behavior that violates the restriction. It must be used in combination with the report-uri option.
Content-Security-Policy-Report-Only: default-src 'self'; ...; report-uri /my_amazing_csp_report_parser;

IV. Option values
Every restriction options can be configured with the following several values and such values constitute the whitelist.
Host name: example.org, https://example.com:443
Path: example.org/resources/js/
Wildcard: *.example.org,*://*.example.com:* (indicates any protocol, any sub-domain name and any port)
Protocol name: https:, data:
Keyword ‘self’: current domain name, quotation marks required.
Keyword ‘none’: disables loading any external resources, quotation marks required.
Multiple values can be in parallel, separated by spaces.
Content-Security-Policy: script-src 'self' https://apis.google.com

If the same restriction option is used for multiple times, only the first application takes effect.
# Wrong: script-src https://host1.com; script-src https://host2.com
    # Correct: script-src https://host1.com https://host2.com


If a restriction option is not configured, it means it allows any values by default.
V. Special values of script-src
Apart from general values, the script-src option also supports some special values. Note: the values must be put within single quotation marks.
‘Unsafe-inline’: allows the embedded &lt;script> tags and event listening functions on the execution page
Unsafe-eval: allows character strings in code for execution, such as using eval, setTimeout, setInterval and Function functions.
Nonce value: An authorization token will be given for every HTTP response, and the token is required for the embedded scripts on the page for execution.
Hash value: lists the hash values of the allowed script code for execution. Only the embedded scripts with a matched hash value can be executed on the page.
An example of the nonce value is as follows. When the server sends the web page, it tells the browser a random token.


This token is required for the embedded scripts on the page to be executed.
<script nonce=EDNnf03nceIOfn39fn3e9h3sdfa> // some code </script>

The example for the hash value is as follows. The server gives a hash value of the code allowed to be executed.
Content-Security-Policy: script-src 'sha256-qznLcsROx4GACP2dm0UCKCzCG-HiZ1guq6ZZDob_Tng='

The code below will be allowed for execution, because its hash value matches.
<script>alert('Hello, world.');</script>

Note: When calculating the hash value, the <script> tag is not included.
Apart from the script-src option, the nonce value and hash value can also be used in the style-src option to control the embedded style sheet on the page.
VI. Notes worth attention
(1) The script-src and object-src options are required, unless you have configured default-src.
Because the attackers can evade all the other restrictions as long as they inject the scripts. The object-src is required because external scripts can be executed in the Flash.
(2) The script-src option cannot use the unsafe-inline keyword (unless in combination with a nonce value), and data:URL is not allowed, either.
Below are two examples of malicious attacks.
<img src="x" onerror="evil()"> <script src="data:text/javascript,evil()"></script>

(3) Do pay attention to the callback function of JSONP.
<script src="/path/jsonp?callback=alert(document.domain)//"> </script>

In the code above, although the loaded scripts are from the current domain name, attackers can execute malicious code through modifying the callback function.
Guest