org.sonar.l10n.javascript.rules.javascript.S5728.html Maven / Gradle / Ivy
Content security policy (CSP) (fetch directives) is a W3C standard which is used by a server to specify,
via a http header, the origins from where the browser is allowed to load resources. It can help to mitigate the risk of cross site scripting (XSS)
attacks and reduce privileges used by an application. If the website doesn’t define CSP header the browser will apply same-origin policy by default.
Content-Security-Policy: default-src 'self'; script-src ‘self ‘ http://www.example.com
In the above example, all resources are allowed from the website where this header is set and script resources fetched from example.com are also
authorized:
<img src="selfhostedimage.png></script> <!-- will be loaded because default-src 'self'; directive is applied -->
<img src="http://www.example.com/image.png></script> <!-- will NOT be loaded because default-src 'self'; directive is applied -->
<script src="http://www.example.com/library.js></script> <!-- will be loaded because script-src ‘self ‘ http://www.example.comdirective is applied -->
<script src="selfhostedscript.js></script> <!-- will be loaded because script-src ‘self ‘ http://www.example.com directive is applied -->
<script src="http://www.otherexample.com/library.js></script> <!-- will NOT be loaded because script-src ‘self ‘ http://www.example.comdirective is applied -->
Ask Yourself Whether
- The resources of the application are fetched from various untrusted locations.
There is a risk if you answered yes to this question.
Recommended Secure Coding Practices
Implement content security policy fetch directives, in particular default-src directive and continue to properly sanitize and validate all
inputs of the application, indeed CSP fetch directives is only a tool to reduce the impact of cross site scripting attacks.
Sensitive Code Example
In a Express.js application, the code is sensitive if the helmet contentSecurityPolicy
middleware is disabled:
const express = require('express');
const helmet = require('helmet');
let app = express();
app.use(
helmet({
contentSecurityPolicy: false, // sensitive
})
);
Compliant Solution
In a Express.js application, a standard way to implement CSP is the helmet contentSecurityPolicy
middleware:
const express = require('express');
const helmet = require('helmet');
let app = express();
app.use(helmet.contentSecurityPolicy()); // Compliant
See
- OWASP - Top 10 2021 Category A5 - Security Misconfiguration
- w3.org - Content Security Policy Level 3
- OWASP - Top 10 2017 Category A6 - Security
Misconfiguration
- developer.mozilla.org - Content Security Policy (CSP)