hugh 的个人博客

Everyday is a new day

CPS报告收集 - 前端监控

csp

全称: Content-Security-Policy

是一种通过给浏览器加资源白名单的方式,进行站点保护的手段

可以有效的预防和阻止 类似 XSS、运营商劫持之类的攻击

CSP 报告

如果你的站点目前还不适合强制使用 CSP 拦截, 那么可以开启 Content-Security-Policy-Report-Only

开启方法如下

在服务端响应时,加入 Content-Security-Policy-Report-Only 的头部,

指定规则和report-uri

注: Content-security-policy 规则可以直接在 meta 头部标签指定, 但是 report-uri 属性不支持在 meta 设置

report-uri 将接受到一个 POST 请求

参数 JSON 包含如下属性

document-uri: 发生违规的文档的 URI。

referrer: 违规发生处的文档引用(地址)。

blocked-uri: 被 CSP 阻止的资源 URI。如果被阻止的 URI 来自不同的源而非文档 URI,那么被阻止的资源 URI 会被删减,仅保留协议,主机和端口号。

violated-directive: 违反的策略名称。

original-policy:Content-Security-Policy HTTP 头部中指明的原始策略。

使用

1. nodejs 下

利用 helmet-csp

范例如下

var express = require('express');
const csp = require('helmet-csp')
var app = express();
app.use(csp({
	// Specify directives as normal.
	directives: {
		defaultSrc: ["'self'", 'default.com'],
		scriptSrc: ["'self'", "'unsafe-inline'"],
		styleSrc: ['style.com'],
		fontSrc: ["'self'", 'fonts.com'],
		imgSrc: ['img.com', 'data:'],
		reportUri: 'http://localhost:9999/api/track/csp-report/group/test',
		objectSrc: ["'none'"],
	},
	
	
	// This module will detect common mistakes in your directives and throw errors
	// if it finds any. To disable this, enable "loose mode".
	loose: false,
	
	// Set to true if you only want browsers to report errors, not block them.
	// You may also set this to a function(req, res) in order to decide dynamically
	// whether to use reportOnly mode, e.g., to allow for a dynamic kill switch.
	reportOnly: true,
	
	// Set to true if you want to blindly set all headers: Content-Security-Policy,
	// X-WebKit-CSP, and X-Content-Security-Policy.
	setAllHeaders: false,
	
	// Set to true if you want to disable CSP on Android where it can be buggy.
	disableAndroid: false,
	
	// Set to false if you want to completely disable any user-agent sniffing.
	// This may make the headers less compatible but it will be much faster.
	// This defaults to `true`.
	browserSniff: true
}))

 
app.get('/', function (req, res) {
	res.send(`<html> <head><style> body{ color: red; } </style> </head> <body>this is a csp test</body> </html>`);
});

 
app.listen(3000, function () {
	console.log('Example app listening on port 3000!');
});

访问 localhost:3000,会触发 CSS 拦截报告的消息

[Report Only] Refused to apply inline style because it violates the following Content Security Policy directive: "style-src style.com". Either the 'unsafe-inline' keyword, a hash ('sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU='), or a nonce ('nonce-...') is required to enable inline execution.

同时发送一条记录到 report 服务

服务端需要设置 bodyParser.json 支持 application/csp-report 格式的数据

显示结果如下, 样式并不会被影响

2. pathon

def middleware(request, response):
response['Content-Security-Policy-Report-Only'] = 

"default-src 'self'; " 

"report-uri http://locahost:9000/api/track/csp-report/group/test"
return response

标题:CPS报告收集 - 前端监控
作者:hugh0524
地址:https://blog.uproject.cn/articles/2019/09/11/1568176109810.html