Blocking mixed content from potentially trustworthy origins (127.0.0.0/8)

放肆的年华 提交于 2021-01-29 14:43:48

问题


Mixed content isn't blocked for potentially trustworthy origins, including IP addresses from 127.0.0.0 to 127.255.255.255. Can browsers be configured to block mixed content for such addresses? This would make local testing easier.


回答1:


I have found no browser settings to treat potentially trusted domains as untrusted, BUT here are several options to make 127.0.0.1 and untrusted domains behave the same, or to generate a report of items that would normally generate a warning.

XHR

For XHR, adding an entry to your hosts file is enough (tested in Firefox 73.0.1 & Chrome 80.0.3987).

# /etc/hosts
127.0.0.1 example.com

XHR requests from https://example.com to http://example.com will be blocked by the Mixed Content rules. Note that XHR is still subject CORS and may additionally be blocked by the CORS policy.

This also applies to WebSockets and several other connection types.

<img> and other non-XHR

I have found no way to generate only a warning for images or other connection types (you can see a nearly-exhaustive list with examples at Mixed Content Examples).

There are two options if you wish 127.0.0.1 to behave as if it were a regular domain:

  • Block Mixed Content entirely (this may even help future-proof your site) using a Content Security Policy (CSP)
  • Get the browser to generate a report of elements which would have generated a warning

Blocking Mixed Content

Add this CSP directive to allow only HTTPS images.

Content-Security-Policy: image-src https:

Use default-src instead of image-src to allow only HTTPS for all other connection types. List of other connection types and their directives.

Generating a report

Add this CSP directive to get the browser to POST a JSON report of resources that would have been blocked.

Content-Security-Policy-Report-Only: default-src https:; report-uri /your-endpoint

Here's some Express code to do that.

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())) );
});

A test server is available at https://github.com/codebling/mixed-content-test



来源:https://stackoverflow.com/questions/60456809/blocking-mixed-content-from-potentially-trustworthy-origins-127-0-0-0-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!