阻止来自潜在可信来源的混合内容 (127.0.0.0/8)
Blocking mixed content from potentially trustworthy origins (127.0.0.0/8)
混合内容 for ,包括IP地址从127.0.0.0到127.255.255.255。浏览器是否可以配置为阻止此类地址的混合内容?这将使本地测试更容易。
我发现没有浏览器设置将可能受信任的域视为不受信任,但是这里有几个选项可以使 127.0.0.1 和不受信任的域表现相同,或者生成一个通常会产生警告的项目的报告。
XHR
对于 XHR,在 hosts
文件中添加一个条目就足够了(在 Firefox 73.0.1 和 Chrome 80.0.3987 中测试)。
# /etc/hosts
127.0.0.1 example.com
来自 https://example.com to http://example.com 的 XHR 请求将被混合内容规则阻止。请注意,XHR 仍然受制于 CORS,并且可能会被 CORS 策略额外阻止。
这也适用于 WebSockets 和几个 other connection types。
<img>
和其他非 XHR
我没有找到只为图像或其他连接类型生成警告的方法(您可以在 Mixed Content Examples 上看到几乎详尽的示例列表)。
如果您希望 127.0.0.1 像普通域一样运行,有两个选项:
- 使用内容安全策略 (CSP)
完全阻止混合内容(这甚至可以帮助您的网站面向未来)
- 让浏览器生成本应生成警告的元素的报告
阻止混合内容
添加此 CSP 指令以仅允许 HTTPS 图像。
Content-Security-Policy: image-src https:
使用 default-src
而不是 image-src
以仅允许所有其他连接类型使用 HTTPS。 List of other connection types and their directives.
正在生成报告
添加此 CSP 指令以使浏览器 POST 报告本应被阻止的资源 JSON。
Content-Security-Policy-Report-Only: default-src https:; report-uri /your-endpoint
这里有一些 Express 代码可以做到这一点。
let cspCounter = 1;
const CSP_VIOLATION_REPORT_ENDPOINT = '/csp-violation-report-endpoint';
app.use( (req, res, next) => {
res.set('Content-Security-Policy-Report-Only', `default-src https:; report-uri ${CSP_VIOLATION_REPORT_ENDPOINT}`);
next();
});
app.post(CSP_VIOLATION_REPORT_ENDPOINT, (req, res) => {
const reportFile = `/tmp/csp-report-${cspCounter++}.json`;
req.pipe(fs.createWriteStream(reportFile));
req.on('end', () => res.send('ok'));
fs.readFile(reportFile, (err, data) => debug('csp-report')(err || JSON.parse(data.toString())) );
});
混合内容
我发现没有浏览器设置将可能受信任的域视为不受信任,但是这里有几个选项可以使 127.0.0.1 和不受信任的域表现相同,或者生成一个通常会产生警告的项目的报告。
XHR
对于 XHR,在 hosts
文件中添加一个条目就足够了(在 Firefox 73.0.1 和 Chrome 80.0.3987 中测试)。
# /etc/hosts
127.0.0.1 example.com
来自 https://example.com to http://example.com 的 XHR 请求将被混合内容规则阻止。请注意,XHR 仍然受制于 CORS,并且可能会被 CORS 策略额外阻止。
这也适用于 WebSockets 和几个 other connection types。
<img>
和其他非 XHR
我没有找到只为图像或其他连接类型生成警告的方法(您可以在 Mixed Content Examples 上看到几乎详尽的示例列表)。
如果您希望 127.0.0.1 像普通域一样运行,有两个选项:
- 使用内容安全策略 (CSP) 完全阻止混合内容(这甚至可以帮助您的网站面向未来)
- 让浏览器生成本应生成警告的元素的报告
阻止混合内容
添加此 CSP 指令以仅允许 HTTPS 图像。
Content-Security-Policy: image-src https:
使用 default-src
而不是 image-src
以仅允许所有其他连接类型使用 HTTPS。 List of other connection types and their directives.
正在生成报告
添加此 CSP 指令以使浏览器 POST 报告本应被阻止的资源 JSON。
Content-Security-Policy-Report-Only: default-src https:; report-uri /your-endpoint
这里有一些 Express 代码可以做到这一点。
let cspCounter = 1;
const CSP_VIOLATION_REPORT_ENDPOINT = '/csp-violation-report-endpoint';
app.use( (req, res, next) => {
res.set('Content-Security-Policy-Report-Only', `default-src https:; report-uri ${CSP_VIOLATION_REPORT_ENDPOINT}`);
next();
});
app.post(CSP_VIOLATION_REPORT_ENDPOINT, (req, res) => {
const reportFile = `/tmp/csp-report-${cspCounter++}.json`;
req.pipe(fs.createWriteStream(reportFile));
req.on('end', () => res.send('ok'));
fs.readFile(reportFile, (err, data) => debug('csp-report')(err || JSON.parse(data.toString())) );
});