Content Security Policy

Time:2021-3-9

Content security policy (CSP) is used to detect and prevent web pages from loading illegal resources. It can reduce the harm of XSS attacks and data injection attacks. This paper describes how to use CSP and service access CSP process.

brief introduction

The main work of CSP is to define a set of white list rules for loading page resources. Browsers use CSP rules to match all resources, prohibit loading resources that do not conform to the rules, and report illegal resource requests.

CSP function: reduce the harm of web pages after XSS attack. In fact, CSP works only after XSS attacks occur, preventing illegal resources injected by requests. CSP does not directly prevent XSS attacks.

Usage

CSP is mainly used in two ways: setting response headerContent-Security-PolicyAnd usemetalabel.

Response header

It is defined in the response header of HTML request

Content security policy: instruction 1 instruction value 1 instruction value 2; instruction 2 instruction value 1;

example:

Content-Security-Policy: srcipt-src 'self' *.test.com'; img-src: https: data:;

Later, we will focus on the specific instructions and instruction values in CSP, which can be found inDefining rulesSee the specific introduction in.

meta

Define in HTML file of web page

<meta
  http-equiv="Content-Security-Policy"
  Content = "instruction 1 instruction value 1 instruction value 2; instruction 2 instruction value 1;"
>

example:

<html>
  <head>
    <meta
      http-equiv="Content-Security-Policy"
      content="srcipt-src 'self' *.test.com'; img-src: https: data:;"
    >
  </head>
  <body>...</body>
</html>

Note: since HTML documents are parsed from top to bottom, meta should be written at the top as far as possible to ensure that all resource requests can be constrained.

effect

All the resources matched by CSP rules can be requested normally. Once there is an illegal resource request, the browser will immediately block it. The blocking effect is as follows

Content Security Policy

Defining rules

CSP rules are mainly composed of instruction and instruction value. Instruction is used to define resource type and instruction value is used to define resource request address rules.

example:

Content-Security-Policy: srcipt-src 'self' *.test.com';

In the CSP rule above,script-srcIs the script resource loading instruction,'self'and*.test.comIs the instruction value. When loading JS script, only the rules defined by the instruction value can be loaded normally.

instructions

instructions explain Examples
default-src Define the default loading policy for all types of resources. When the following instructions are not defined, the browser will use themdefault-srcVerify the defined rules 'self' *.test.com
script-src Define JavaScript resource loading policy 'self' js.test.com
style-src Define the loading policy of the style file 'self' css.test.com
img-src Define the loading policy of image file 'self' img.test.com
font-src Define the loading policy of font file 'self' font.test.com
connect-src Define the loading policy of XHR, websocket and other requests. When the request does not conform to the defined rules, the browser will simulate a response with a response status code of 400 'self'
object-src definition<object> <embed> <applet>Loading strategy of equal label 'self'
media-src definition<audio> <video>Loading strategy of multimedia HTML tag resources 'self'
frame-src [obsolete] define iframe tag resource loading strategy (new instruction: child SRC) 'self'
sandbox Enable sandbox for the requested resource, similar toSandbox function in iframe allow-scripts
report-uri Define the reporting address. When a resource is intercepted, the browser requests the URI with the intercepted resource information. (valid only if defined in response header) https://csp.test.com/report
child-src [csp2] defines the loading strategy of subwindows (iframe, pop-up window, etc.) 'self' *.test.com
form-action [csp2] defines the source rules for form submission 'self'
frame-ancestors [csp2] defines which pages can be loaded with ifram and object 'self'
plugin-types [csp2] defines which plug-ins can be loaded on the page

Instruction value

Instruction value explain Examples
* All contents are loaded normally img-src *;
'none' No resources are allowed to load img-src 'none';
'self' Allow loading of homologous resources img-src 'self';
'unsafe-inline' Allow loading inline content (for example: style, onclick, inline JS, inline CSS, etc.) srcript-url 'unsafe-inline';
'unsafe-eval' Allows dynamic JS code to be loaded (for example:eval() script-src 'unsafe-eval';
http: Allow loading HTTP protocol resources img-src http:;
https: Allow loading of HTTPS protocol resources img-src https:;
data: Data protocol is allowed (data protocol is used to load Base64 images in CSS) img-src data:;
domain name Allow loading all the HTTPS protocol resources under the domain name img-src test.com;
route Allow loading all HTTPS protocol resources in this path img-src test.com/img/;
wildcard *.test.comIt is allowed to load all the resources of the HTTPS protocol under the subdomain name (any subdomain name);*://*.test.com:*The original meaning of this matching logic is any protocol, any subdomain name, any port, but in the actual test process, it is found that this instruction value has no effect img-src *.test.com;

Actual business development

We have learned about the basic usage of CSP, and then we will talk about the next business access CSP process. Since the browser will prohibit the loading of resources that violate CSP rules, we need to conduct a series of verification on CSP before we can go online. Next, we will take you step by step to complete the deployment of business CSP rules.

Organize resource address

<!– window.performance.getEntries().map(info => info.name).filter(str => !!~str.indexOf(‘:’)) –>
In the web page, the browser providesperformance.getEntries()Interface, which is used to obtain the resource information loaded by the web pageinitiatorTypeThe (resource type) attribute knows which instruction the resource belongs to,name(resource address) defines the instruction values.

For simplicity, we will only definedefault-srcWith this instruction, all resource loading tests go directlydefault-srcDefined rules.

const entries = window.performance.getEntries()
const names = entries.map(info => info.name);

Generating CSP rules

const parseReg = /^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;
const httpList = [];
const httpsList = [];
const otherProtocol = [];

//Separate HTTPS, HTTP and other protocol resources
names.forEach(str => {
  const parse = parseReg.exec(str);

  //Measured *: // * test.com : * does not match test.com Any protocol, any subdomain name, any port, so HTTP and HTTPS are separated here
  if (['https', 'http'].includes(parse[1])) {
    const domain = parse[3];
    const midProduct = domain.split('.');
    const midProductLen = midProduct.length;
    const childDomain = midProductLen > 2 ? `*.${midProduct.slice(midProductLen - 2).join('.')}` : domain;

    if (parse[1] === 'https') {
      httpsList.push(childDomain);
    } else {
      httpList.push(`http://${childDomain}`);
    }
  } else {
    otherProtocol.push(parse[1]);
  }
});

const domains = new Set(otherProtocol.concat(httpsList).concat(httpList))
const defaultSrc = [...domains].join(' ');

So we can get a simpler onedefault-srcInstruction value, if the inlin code still exists in the project or theevalFunction dynamic execution of JS code, you need todefault-srcIn the configuration of additional values, specific should add what content, you can in theInstruction valueSee.

Local testing

In the Google browser plug-in application, addCSP MitigatorPlug in, and then configure the page address and CSP rule information.

Content Security Policy

After the plug-in content is configured, click start to start the test. Enter the business page, check which resources in the console do not comply with the CSP rules, and then complete the CSP rules according to the error.

Content Security Policy

If there is no resource loading that violates the CSP rules in the local test, we can consider putting the CSP rules into the existing network for testing. It’s just that the response header used in the current network is notContent-Security-PolicyInstead ofContent-Security-Policy-Report-OnlyThe next section will introduce the current network test in detail.

Current network test

In general, browsers will prohibit loading resources that violate CSP rules, which requires high accuracy for CSP. If we accidentally miss a rule, it will affect the normal display of the page, which will undoubtedly bring great pressure to developers. In order to solve this problem, the browser providesContent-Security-Policy-Report-OnlyThe response header only reports the resources that violate the CSP rules, and does not prohibit the loading of resources. In this way, we can use the reported illegal resource data to gradually complete the CSP rules without affecting the business usage.

After the resource is blocked, the content reported by the browser is as follows:
Content Security Policy

If there is a legal resource in the reported blocked data, we need to write the resource to the rule. After updating, we can write the rule to the ruleCSP MitigatorPlug in, and then use it in the page consolefetchFunction to request the previously reported resource address. If the console does not report the problem of loading forbidden, then the latest CSP rule is valid. After a period of optimization, CSP optimization, continue to writeContent-Security-Policy-Report-OnlyObservation was made in the response head.

Officially launched

If you confirm that the resources reported by CSP are only illegal resources, you can change the response header toContent-Security-Policy. When the response header is changed toContent-Security-PolicyIn the future, resources that violate the CSP rules will be prohibited from loading and will be reported at the same time.

reference resources

Recommended Today

Analysis of super comprehensive MySQL statement locking (Part 1)

A series of articles: Analysis of super comprehensive MySQL statement locking (Part 1) Analysis of super comprehensive MySQL statement locking (Part 2) Analysis of super comprehensive MySQL statement locking (Part 2) Preparation in advance Build a system to store heroes of the Three KingdomsheroTable: CREATE TABLE hero ( number INT, name VARCHAR(100), country varchar(100), PRIMARY […]