Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the HTML5 content security policy?

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

In this article, the editor introduces "what is the HTML5 content security strategy" in detail, the content is detailed, the steps are clear, and the details are handled properly. I hope this article "what is the HTML5 content security strategy" can help you solve your doubts.

The security policy of the World wide Web is rooted in the same origin policy. For example, the code of www.mb5u.com can only access the data of www.mb5u.com, but not http://www.baidu.com. Each source is separated from the rest of the network, creating a secure sandbox for developers. This is perfect in theory, but now attackers have found a clever way to destroy the system.

This is the XSS cross-site scripting attack, which bypasses the homologous strategy through fake content and decoy clicks. This is a big problem, and if the attacker successfully injects the code, a considerable amount of user data will be compromised.

Now we introduce a new and effective security defense strategy to mitigate this risk, which is the content Security Policy (ContentSecurity Policy,CSP).

Source whitelist

The core of the XSS attack is to take advantage of the browser's inability to tell whether the script is injected by a third party or whether it is actually part of your application. For example, the Google + 1 button loads and executes code from https://apis.google.com/js/plusone.js, but we can't expect to tell from the image on the browser whether the code is really from apis.google.com or from apis.evil.example.com. The browser downloads and executes a page request for arbitrary code, regardless of its source.

CSP defines Content-Security-PolicyHTTP headers to allow you to create a whitelist of trusted sources so that browsers only execute and render resources from those sources, rather than blindly trusting everything the server provides. Even if the attacker can find a vulnerability to inject the script, it will not be executed because the source is not included in the whitelist.

Taking the Google + 1 button above as an example, because we believe that apis.google.com provides valid code, as well as ourselves, we can define a policy that allows browsers to execute only scripts from one of the following two sources.

Content-Security-Policy:script-src 'self' https://apis.google.com

Isn't it easy? Script-src can control script-related permissions for specified pages. This way the browser will only download and execute scripts from http://apis.google.com and the page itself.

Once we have defined this policy, the browser will throw an error when it detects the injected code (note which browser it is).

Content security policies apply to all commonly used resources

Although script resources are the most obvious security concern, CSP also provides a rich set of instructions that allow page control to load various types of resources, such as the following:

Content-src: restrict the type of connection (for example, XHR, WebSockets, and EventSource)

Font-src: controls the source of network fonts. For example, you can use Google's web font through font-src https://themes.googleusercontent.com.

Frame-src: lists the sources of frame that can be embedded. For example, frame-src https://youtube.com only allows videos embedded in YouTube.

Img-src: defines the source of loadable images.

Media-src: limit the sources of video and audio.

Object-src: limit the sources of Flash and other plug-ins.

Style-src: similar to Script-src, except for css files.

By default, all settings are turned on without any restrictions. You can separate multiple instructions with semicolons, but similar to script-src https://host1.com;script-src https://host2.com, the second instruction will be ignored. The correct way to write it is script-src https://host1.com https://host2.com.

For example, if you have an application that needs to load all resources from a content distribution network (CDN, such as https://cdn.example.net) and knows that you don't need any frame or plug-ins, your strategy might look like this:

Content-Security-Policy:default-src https://cdn.example.net; frame-src 'none'; object-src' none'

Details

The HTTP header I use in the example is Content-Security-Policy, but modern browsers have provided support through prefixes: Firefox uses Xmuri ContentlySecurityKit using X-WebKit-CSP PolicyMae WebKit. There will be a gradual transition to a unified standard in the future.

Policies can be set according to each different page, which provides a great deal of flexibility. Because some pages of your site may have Google + 1 buttons, while others don't.

The source list of each instruction can be quite flexible, you can specify the mode (data:, https:), or specify the hostname in a range (example.com, which matches any source, any mode, and any port on the host), or specify a complete URI (https://example.com:443, specifically https protocol, example.com domain name, port 443).

You can also use four keywords in the source list:

"none": you may not expect to match anything

"self": same as the current source, but does not contain subdomains

"unsafe-inline": allows inline Javascript and CSS

"unsafe-eval": mechanisms that allow text to JS, such as eval

Please note that these keywords need quotation marks.

Sand box

Here is another instruction worth discussing: sandbox. Somewhat inconsistent with other instructions, it is mainly about controlling the behavior taken on the page, rather than the resources that the page can load. If this property is set, the page behaves like a frame with the sandbox property set. This has a wide range of impact on the page, such as preventing form submission and so on. This is a bit beyond the scope of this article, but you can find more information in the "sandbox flag setting" section of the HTML5 specification.

Harmful inline code

CSP is based on the source whitelist, but it does not address the biggest source of XSS attacks: inline script injection. If an attacker can inject a script tag (sendMyDataToEvilDotCom ();) that contains harmful code, the browser does not have a good mechanism to distinguish the tag. CSP can only solve this problem by banning inline scripts altogether.

This prohibition includes not only the script tags embedded in the script, but also inline event handlers and javascrpt: this URL. You need to put the contents of the script tag in an external file and replace _ javascript: and with the appropriate addEventListener. For example, you might put the following form:

Function doAmazingThings () {

Alert ('YOU AM AMAZING')

}

Am I amazing?

Rewrite it in the following form:

Am I amazing?

/ / amazing.js

Function doAmazingThings () {

Alert ('YOU AM AMAZING')

}

Document.addEventListener ('DOMContentReady', function () {

Document.getElementById ('amazing')

.addEventListener ('click', doAmazingThings)

});

Whether you use CSP or not, the above code actually has a greater advantage. Inline JavaScript is a complete mix of structure and behavior, and you shouldn't do that. In addition, outreach resources are easier to cache in browsers, easier for developers to understand, and easier to compile and compress. If you use outreach code, you will write better code.

Inline styles need to be handled in the same way, and both style attributes and style tags need to be extracted into an external stylesheet. This can prevent all kinds of magical data leakage.

If you have to have inline scripts and styles, you can set the 'unsafe-inline' value for the script-src or style-src property. But don't do this. Banning inline scripts is the biggest security guarantee provided by CSP, and banning inline styles can make your application more secure and robust. It's a tradeoff, but it's worth it.

Eval

Even if the attacker cannot inject the script directly, he may induce your application to convert the inserted text into an executable script and execute it itself. Eval (), newFunction (), setTimeout ([string],...) And setInterval ([string],...) Could be a carrier of this danger. CSP's strategy for this risk is to block these carriers altogether.

This has some impact on the way you build your application:

Parse JSON through the built-in JSON.parse instead of relying on eval. All browsers after IE8 support native JSON operations, which is completely secure.

Rewrite the way you call setTimeout and setInterval by inlining functions instead of strings. For example:

SetTimeout ("document.querySelector ('a'). Style.display = 'none';", 10)

It can be rewritten as:

SetTimeout (function () {document.querySelector ('a'). Style.display = 'none';}, 10)

Avoid inline templates at run time: many template libraries use new Function () to speed up template generation. This is great for dynamic programs, but it is risky for malicious text.

Report

CSP can block untrusted resources on the server side is very useful for users, but it is very useful for us to get various notifications sent to the server, so that we can identify and fix any malicious script injection. To do this, you can use the report-uri command to instruct the browser to send an intercept report in JSON format to an address.

Content-Security-Policy: default-src 'self';...; report-uri / my_amazing_csp_report_parser

The report will look like this:

{

"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"

}

}

It contains information that will help you identify interceptions, including the page where the interception occurred (document-uri), the page's referrer, the resources that violate the page policy (blocked-uri), the instructions violated (violated-directive), and all content security policies on the page (original-policy).

Practical usage

CSP is now available on Chrome 16 + and Firefox 4 + browsers, and it is expected to have limited support on IE10. Safari is not currently supported, but the nightly build of WebKit is already available, so Safari is expected to provide support in the following iterations.

Let's look at some common use cases:

Actual case 1: social media widget

Google + 1 button includes scripts from https://apis.google.com and iframe embedded from https://plusone.google.com. Your strategy needs to include these sources to use the Google + 1 button. The simplest strategy is script-src https://apis.google.com; frame-src https://plusone.google.com. You also need to make sure that the JS fragments provided by Google are stored in an external JS file.

There are many implementations of Facebook's Like button. I suggest you stick with the iframe version because it is well isolated from the rest of your site. This requires the use of frame-src https://facebook.com directives. Please note that by default, the iframe code provided by Facebook uses the relative path / / facebook.com, please change this code to https://facebook.com Magi HTTP you don't have to use it.

Twitter's Tweet button depends on script and frame, both from https://platform.twitter.com (Twitter provides relative URL by default, please edit the code when copying to specify HTTPS mode).

Other platforms have similar situations and can be solved in a similar way. I suggest setting default-src to none, and then check the console to see which resources you need to use to make sure widget works properly.

Using multiple widget is simple: just merge all the policy instructions and remember to put the settings of the same instruction together. If you want to use the above three widget, the strategy will look like this:

Script-src https://apis.google.com https://platform.twitter.com; frame-src https://plusone.google.com https://facebook.com https://platform.twitter.com

Actual case 2: defense

Suppose you visit a bank website and want to make sure that only the resources you need are loaded. In this case, start setting a default permission to block all content (default-src 'none') and build the policy from scratch.

For example, bank websites need to load images, styles, and scripts from CDN from https://cdn.mybank.net, and connect to https://api.mybank.com/ through XHR to pull various data, and you need to use frame, but the frame comes from non-third-party local pages. There is no Flash, fonts or other content on the site. In this case, the strictest CSP headers we can send are:

Content-Security-Policy: default-src 'none'; script-src https://cdn.mybank.net; style-src https://cdn.mybank.net; img-src https://cdn.mybank.net; connect-src https://api.mybank.com; frame-src' self'

Actual case 3: use SSL only

A wedding ring forum administrator wants all resources to be loaded in a secure way, but doesn't really want to write too much code; rewriting a large number of third-party forum inline scripts and styles of code is beyond his ability. So the following strategies will be very useful:

Content-Security-Policy: default-src https:; script-src https: 'unsafe-inline'; style-src https:' unsafe-inline'

Although default-src specifies https, scripts and styles do not inherit automatically. Each instruction will completely override the default resource type.

The future

The W3C Web Application Security working Group is working on the details of the content security policy specification, and version 1.0 is about to enter the final revision stage, which is very close to the content described in this article. While the public-webappsec@ mail group is discussing version 1.1, browser vendors are also working to consolidate and improve the implementation of CSP.

CSP 1.1 has some interesting features on the artboard that are worth listing separately:

Add policy through the meta tag: the preferred setting for CSP is the HTTP header, which is very useful, but it is more straightforward through markup or scripting, but it has not been finalized yet. WebKit has implemented the feature of setting permissions through the meta element, so you can now try the following settings under Chrome: add to the document header.

You can even add policies through scripts at run time.

DOM API: if this feature is added in the next iteration of CSP, you can query the page's current security policy through Javascript and adjust it according to different circumstances. For example, your code implementation may be slightly different if eval () is available or not. This is very useful for the authors of the JS framework; and the API specification is still very uncertain, and you can find the latest iterative version in the scripting interface section of the draft specification.

New directives: many new directives are under discussion, including script-nonce: only explicitly specified script elements can be used with inline scripts; plugin-types: this limits the type of plug-ins; and form-action: allows form to be submitted only to specific sources.

After reading this, the article "what is the HTML5 content security strategy" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report