当前位置:网站首页>关于CSP及其相关实现
关于CSP及其相关实现
2022-06-09 10:47:00 【Johnny丶me】
CSP
- Content Security Policy 内容安全策略
- 产生XSS攻击的原因是用户数据被当做程序执行
- 转义替换虽然不是很正规,但是最适合XSS的解决方案
- 除了转义替换,我们要来说下CSP, 它是浏览器和web标准制定的
- CSP用于指定哪些内容是可以执行的,哪些是不可执行的
- 我们只需要将用户输入的部分标记为不可执行,就不会产生危害
- CSP是HTTP头,里面规定了哪些来源可以限制,比如:
- child-src connect-src default-src
- font-src frame-src img-src
- manifest-src media-src object-src
- script-src style-src worker-src
- 针对这些内容中的某一项,比如script脚本,我们可以指定哪些可信,哪些不可信,它定义了很多来源
- <host-source> <scheme-source> ‘self’
- ‘unsafe-inline’ ‘unsafe-eval’ ‘none’
- ‘nonce-<base64-value>’ <hash-source>
- ‘strict-dynamic’
- 具体可以参考:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/CSP
- 具体用法可以设置HTTP头, 如:
ctx.set(`Content-Security-Policy`, `script-src 'self'`) - 如果我们的页面中想要执行某一段代码怎么办呢?
- 我们可以使用nonce参数,在我们的页面上和HTTP头上统一一个随机的nonce,这样攻击者就无计可施了
- 比如在前端页面模板中的脚本
<!-- pug 模板引擎 --> script(none='123456') var a = 1; console.log(a); - 在后端响应头上
ctx.set(`Content-Security-Policy`, `script-src 'self' 'nonce-123456'`) - 这里的123456可以动态设置一个随机的字符串参数, 这样的话前后端保持nonce统一
- 每次刷新页面都要重新获取一个新的随机字符串
- 还可以用下面一种方法来处理
// 后端进行加密 var content = `要加密的脚本代码写在这里`; var crypto = require('crypto'); var hash = crypto.createHash('sha256'); hash.update(content); var str = hash.digest('base64'); console.log(str); // 这段str代码是加密后的脚本代码,是一段hash值 - 上面使用了sha256的加密算法计算出执行代码的hash值
- 我们可以在响应头上设置
ctx.set(`Content-Security-Policy`, `script-src 'self' 'sha256-这里填写上面计算出的str变量值'`) - 在页面模板上,代码格式和内容需要保持和加密时保持一致
<!-- pug 模板引擎 --> script 要加密的脚本代码写在这里
边栏推荐
猜你喜欢

第二章应用层

最新版,最新资料

Cyclodextrin metal organic framework( β- Cd-mof) loaded with dimercaptosuccinic acid( β- CD-MOF/DMSA) β- Drug loading mechanism of cyclodextrin metal organic framework

C# 图片验证码简单例子

Tidb cloud launched Google cloud marketplace, empowering global developers with a new stack of real-time HTAP databases

基于任务调度的企业级分布式批处理方案

【基础知识】~ 硬核/软核/固核、PWM/SPWM、斐波那契数列、大端模式存储、傅里叶变换、奈奎斯特采样定律、芯片选型、基尔霍夫定律、FIR/IIR 滤波器

What are the application advantages of 3D digital sand table display

你知道多少,深度解析,值得收藏

TemplateDoesNotExist at /users/register/
随机推荐
One question per day -1200 Minimum absolute difference
Document writing specification
Introduction and simple use of protobuf
TemplateDoesNotExist at /users/register/
Simple example of C # picture verification code
Enterprise distributed batch processing scheme based on task scheduling
使用五数概括法来确定数据集中的孤立点
Data asset management: how to manage the data assets of an enterprise?
深耕十年,玄武云科技终于稳坐快消SaaS龙头宝座
Clunky hero v0.96 Chinese version
Gaussdb (DWS) data migration [Gauss is not a mathematician this time]
OpenKruise v1.2:新增 PersistentPodState 实现有状态 Pod 拓扑固定与 IP 复用
jvm内存溢出练习记录
Shutter popup shutter shutter_ easyloading
Course design of network sniffer design based on C language
精智达冲刺科创板:年营收4.58亿 中小企业基金是股东
Monomer mode
【mysql进阶】利用执行计划explain优化sql(二)
The method of array traversal in JS
The latest Camtasia 2022 free computer screen recording tool