来源:https://helmetjs.github.io/docs/csp/

Content Security Policy

In short: the CSP module sets the Content-Security-Policy header which can help protect against malicious injection of JavaScript, CSS, plugins, and more.

The attack

Hackers can do lots of bad things if they can put things onto your webpages.

The nastiest attack is probably cross-site scripting (XSS), which is when a hacker puts malicious JavaScript onto your page. If I can run JavaScript on your page, I can do a lot of bad things, from stealing authentication cookies to logging every user action.

There are other things attackers can do, even if they can’t execute JavaScript. For example, if I could put a tiny, transparent 1x1 image on your site, I could get a pretty good idea of how much traffic your site gets. If I could get a vulnerable browser plugin like Flash to run, I could exploit its flaws and do things you don’t want!

There isn’t one specific attack that the CSP module prevents. The main thing is this: you don’t want anyone putting anything on your webpages that you don’t expect.

Read more:

  • Cross-site scripting on Wikipedia
  • Cross-site Scripting on OWASP
  • “How does a tracking pixel work?” on Quora

The header

One of the tricky things about these injection attacks is that the browser doesn’t know what’s good and what’s bad. How can it tell the difference between a legitimate JavaScript file and a malicious one? In many cases, it can’t…unless you’ve defined a Content Security Policy.

Most modern browsers support a header called Content-Security-Policy, which is effectively a whitelist of things that are allowed to be on your page. You can whitelist JavaScript, CSS, images, plugins, and much more. Things are opt-in, so you’re saying “this stuff is allowed” instead of “this stuff is not allowed”.

Let’s say you’ve got a website that links to no external resources at all—just your stuff. You could set a header that looks like this:

Content-Security-Policy: default-src 'self'

This effectively tells the browser “only load things that are from my own domain”. If you’re running example.com and a user tries to load https://example.com/my-javascript.js, it’ll work just fine. But if a user tries to load http://evil.com/evil.js, it won’t load at all!

Now, let’s say you want to also allow CSS from Bootstrap’s CDN. You could set a CSP that looks like this:

Content-Security-Policy: default-src 'self'; style-src 'self' maxcdn.bootstrapcdn.com

Now we’ve whitelisted 'self' and maxcdn.bootstrapcdn.com. The user will be able to load CSS from there, but nothing else. The user won’t even be able to load JavaScript or images from that URL, either—only stylesheets.

There are a lot of nuances to CSP: what you can and can’t whitelist, browser support for various features, and alternate headers. Refer to the stuff below for more information.

Read more:

  • An introduction to Content Security Policy on HTML5 Rocks
  • Content Security Policy Reference
  • Can I Use Content Security Policy 1.0
  • Can I Use Content Security Policy 2.0

The code

Helmet’s csp module helps set Content Security Policies.

You can use this module as part of Helmet:

// Make sure you run "npm install helmet" to get the Helmet package.
var helmet = require('helmet')app.use(helmet.contentSecurityPolicy({directives: {defaultSrc: ["'self'"],styleSrc: ["'self'", 'maxcdn.bootstrapcdn.com']}
}))

You can also use it as a standalone module:

// Make sure you run "npm install helmet-csp" to get the csp package.
var csp = require('helmet-csp')app.use(csp({directives: {defaultSrc: ["'self'"],styleSrc: ["'self'", 'maxcdn.bootstrapcdn.com']}
}))

This header is not included in the default Helmet bundle.

Directives

All of your CSP directives (like default-srcstyle-src) are placed under the directivesoption.

app.use(csp({directives: {defaultSrc: ["'self'", 'default.com'],scriptSrc: ["'self'", "'unsafe-inline'"],sandbox: ['allow-forms', 'allow-scripts'],reportUri: '/report-violation',objectSrc: ["'none'"],upgradeInsecureRequests: true,workerSrc: false  // This is not set.}
}))

Directives can be kebab-cased (like script-src) or camel-cased (like scriptSrc); they are equivalent.

The following directives are supported:

  • base-uri or baseUri
  • block-all-mixed-content or blockAllMixedContent
  • child-src or childSrc
  • connect-src or connectSrc
  • default-src or defaultSrc
  • font-src or fontSrc
  • form-action or formAction
  • frame-ancestors or frameAncestors
  • frame-src or frameSrc
  • img-src or imgSrc
  • manifest-src or manifestSrc
  • media-src or mediaSrc
  • object-src or objectSrc
  • plugin-types or pluginTypes
  • prefetch-src or prefetchSrc
  • report-to or reportTo
  • report-uri or reportUri
  • require-sri-for or requireSriFor
  • sandbox or sandbox
  • script-src or scriptSrc
  • style-src or styleSrc
  • upgrade-insecure-requests or upgradeInsecureRequests
  • worker-src or workerSrc

CSP violations

If you’ve specified a reportUri, browsers will POST any CSP violations to your server. Here’s a simple example of an Express route that handles those reports:

// You need a JSON parser first.
app.use(bodyParser.json({type: ['json', 'application/csp-report']
}))app.post('/report-violation', function (req, res) {if (req.body) {console.log('CSP Violation: ', req.body)} else {console.log('CSP Violation: No data received!')}res.status(204).end()
})

Not all browsers send CSP violations in the same way, so this might require a little work.

Note: If you’re using a CSRF module like csurf, you might have problems handling these violations without a valid CSRF token. The fix is to put your CSP report route above csurf middleware.

This module’s reportOnly option will switch the header to Content-Security-Policy-Report-Only. This instructs browsers to report violations to the reportUri (if specified) but it will not block any resources from loading.

app.use(csp({directives: {// ...},reportOnly: true
})

You may also set this to a function to decide dynamically whether to use reportOnly mode. You could use this for a dynamic kill switch. This function will be called with the request and response objects and must return a boolean.

app.use(csp({directives: {// ...},reportOnly: function (req, res) {if (req.query.cspmode === 'debug') {return true} else {return false}}
})

Browser sniffing

By default, this module will look at the incoming User-Agent header and send different headers depending on the detected browser. For example, Chrome prior to version 25 uses an alternate header called X-WebKit-CSP, and this module handles that. If no browser is detected, this module will set all the headers with the 2.0 spec.

To disable this browser sniffing and assume a modern browser, set the browserSniff option to false.

app.use(csp({directives: {// ...},browserSniff: false
})

To set all headers, including legacy ones, set the setAllHeaders option to true. Note that this will change the value of the headers based on User-Agent. You can disable this by using the browserSniff: false option above.

app.use(csp({directives: {// ...},setAllHeaders: true
})

Old Android browsers can be very buggy. This is false by default.

app.use(csp({directives: {// ...},disableAndroid: true
})

Generating nonces

You can dynamically generate nonces to allow inline <script> tags to be safely evaluated. Here’s a simple example:

var uuid = require('node-uuid')app.use(function (req, res, next) {res.locals.nonce = uuid.v4()next()
})app.use(csp({directives: {scriptSrc: ["'self'",function (req, res) {return "'nonce-" + res.locals.nonce + "'"  // 'nonce-614d9122-d5b0-4760-aecf-3a5d17cf0ac9'}]}
}))app.use(function (req, res) {res.end('<script nonce="' + res.locals.nonce + '">alert(1 + 1);</script>')
})

Using CSP with a CDN

The default behavior of CSP is generate headers tailored for the browser that’s requesting your page. If you have a CDN in front of your application, the CDN may cache the wrong headers, rendering your CSP useless. Make sure to eschew a CDN when using this module or set the browserSniff option to false.

Thanks to the many contributors that helped put Helmet together! Helmet is open source under the MIT License.

Icon by Hand-Drawn Goods, licensed under a CC 3.0 license.

使用helmet.contentSecurityPolicy预防xss攻击相关推荐

  1. PHP预防XSS攻击,ajax跨域攻击的方法

    对网站发动XSS攻击的方式有很多种,仅仅使用php的一些内置过滤函数是对付不了的,即使你将filter_var,mysql_real_escape_string,htmlentities,htmlsp ...

  2. xss过滤器无法处理ajax请求_thunkPHP 预防XSS攻击

    比如在有人恶意在你的输入框中或文本域中输入<script>标签,如果不做处理的话,输入框中的<script>会保存到我们数据库中,等到将这个数据拿出来展示的时候,就等于将这个内 ...

  3. 互联网安全架构平台设计之预防XSS攻击

    互联网安全架构平台设计之预防XSS攻击 文章目录 互联网安全架构平台设计之预防XSS攻击 一.什么是XSS攻击? 二.XSS攻击详解 1.XSS攻击的原理 2.解决方案 三.注意事项 一.什么是XSS ...

  4. 有效预防xss_预防XSS攻击的一些方法整理

    XSS又称CSS,全称Cross SiteScript(跨站脚本攻击), XSS攻击类似于SQL注入攻击,是Web程序中常见的漏洞,XSS属于被动式且用于客户端的攻击方式,所以容易被忽略其危害性.其原 ...

  5. 如何预防 XSS 攻击

    1.XSS 攻击 XSS 攻击,即跨站脚本攻击,它是 Web 程序中常见的漏洞. 原理:攻击者在 Web 页面里植入恶意的脚本代码(css 代码.Javascript 代码等):当其他用户浏览该页面时 ...

  6. 如何预防 XSS 攻击 和 XSRF 攻击

    常见的 web 前端攻击方式有哪些 XSS 跨站请求攻击 XSRF 跨站请求伪造 XSS攻击举例 一个博客网站(请访问正规网站,放心,CSDN应该是安全的),作者发表了一篇博客,其中嵌入了<sc ...

  7. react textarea 空格为什么不换行_React 怎么实现预防XSS 攻击的

    本文首发于政采云前端团队博客:浅谈 React 中的 XSS 攻击 https://www.zoo.team/article/xss-in-react 前言 前端一般会面临 XSS 这样的安全风险,但 ...

  8. 面试问题如何预防xss攻击

    1. XSS攻击原理 XSS原称为CSS(Cross-Site Scripting),因为和层叠样式表(Cascading Style Sheets)重名,所以改称为XSS(X一般有未知的含义,还有扩 ...

  9. ThinkPHP6 预防XSS攻击的一点小建议

    背景 前几天,我们线上项目,出现一些恶意攻击行为: 基本就是恶意用户在一些接口开放的参数上, 填写了类似 <script>alert('搞事情');</script> 的代码, ...

最新文章

  1. 计算机硬件类 计算机网络基础,计算机硬件类计算机网络基础1.doc
  2. [蓝桥杯][基础练习VIP]FJ的字符串-递归
  3. 批量更新数据(BatchUpdate)
  4. java rsa 128_如何用java实现128位密钥的RSA算法
  5. 二维数组各行求和_JS数组reduce()方法详解及高级技巧
  6. 【C语言】为什么指明数组的列数?
  7. TFS 2017 持续集成速记
  8. linux安装向日葵命令行版
  9. ECCV 2022 | 石溪大学联合小鹏汽车提出先验知识指导的无监督领域自适应
  10. MongoDB中balancer操作
  11. 面试题:25匹马最快3匹及扩展
  12. 【期末复习笔记】知识产权法——著作权、专利法、商标权
  13. CentOS7.x 安装 openssh8.4、openssl1.1.1
  14. UltraEdit常用小技巧
  15. ERP主要软件品牌对比
  16. 读《微波工程(第三版)》笔记 (1:麦克斯韦方程组)
  17. 【转】canvas save restore详解(包你懂,绝对不是百度里千篇一律的教程)
  18. debug tools
  19. vue通过axios获取json数据
  20. java 地址反查邮编_地址查邮编示例代码

热门文章

  1. 上海交通大学计算机系过敏意,上海交通大学-电子信息与电气工程学院-电子信息与电气工程学院...
  2. 实用又救急误删恢复软件怎么用你知道吗,一招教你误删恢复文件数据
  3. 如何在win下装ubuntu(硬盘版安装)
  4. haxe programming language语法两片
  5. SpringSide实战(二)----运行SpringSide项目并导入到Eclipse中
  6. 手机下载APK文件后缀名变成txt
  7. Hollong 蓝牙4.0/4.1/4.2 BLE协议监控分析仪
  8. 如何下载小红书平台上的个人分享文章?
  9. 四川山海蓝图:抖音APP有哪些用户来源?
  10. 智能车图像处理8-右环岛状态机与补线