The security risks of mixed content
Definition of Mixed Content
Mixed content refers to a webpage loaded over HTTPS that simultaneously includes sub-resources (such as scripts, stylesheets, images, iframes, audio/video, etc.) loaded over the HTTP protocol. Since HTTP is transmitted in plaintext while HTTPS is encrypted, this mixed state introduces security risks. Modern browsers mark such content as "not secure" and may even block its loading.
<!-- Mixed content example -->
<script src="http://example.com/script.js"></script>
<img src="http://example.com/image.jpg" alt="Mixed content image">
Types of Mixed Content
Passive Mixed Content
Passive mixed content refers to resources that do not interact with the page DOM, such as images, videos, audio, and other media files. While the risk is lower, they can still be tampered with via man-in-the-middle attacks.
<!-- Passive mixed content example -->
<audio src="http://media.example.com/sound.mp3"></audio>
<video src="http://media.example.com/video.mp4"></video>
Active Mixed Content
Active mixed content includes resources that can modify the DOM or execute scripts, such as JavaScript, CSS, and iframes. These pose the highest risk, as attackers could gain full control of the page through such resources.
<!-- Active mixed content example -->
<link rel="stylesheet" href="http://cdn.example.com/style.css">
<iframe src="http://external.example.com"></iframe>
Security Risks of Mixed Content
Man-in-the-Middle (MITM) Attacks
Attackers can intercept and modify resources during HTTP transmission. For example, replacing a legitimate JavaScript file with a malicious script:
// Original script
function loadUserData() {
// Normal logic
}
// Tampered script
function loadUserData() {
sendCredentialsToAttacker();
// Original logic
}
Session Hijacking
If the page contains sensitive information (e.g., user tokens) transmitted over HTTP, attackers can steal this data:
// Insecure API request
fetch('http://api.example.com/user', {
headers: {
'Authorization': 'Bearer xyz123' // Token could be stolen
}
})
Content Tampering
Attackers can modify images or text transmitted over HTTP to insert false information or malicious ads:
<!-- Original image -->
<img src="http://cdn.example.com/logo.png">
<!-- Tampered version might display a fake logo provided by the attacker -->
How Browsers Handle Mixed Content
Modern browsers adopt progressively stricter policies for handling mixed content:
- Warning Phase: Display warnings in the console but allow loading
- Auto-Upgrade: Attempt to rewrite HTTP requests as HTTPS
- Block Loading: Block active content outright; passive content may still load but is marked as insecure
- Complete Block: Latest browser versions block all mixed content
Browser behavior can be controlled via response headers:
Content-Security-Policy: upgrade-insecure-requests
Detecting and Fixing Mixed Content
Detection Methods
- Warnings in the browser developer tools console
- Security scanning tools like Lighthouse
- Checking all resource URLs during code review
// Programmatic detection of mixed content
document.querySelectorAll('[src^="http://"], [href^="http://"]').forEach(el => {
console.warn('Mixed content:', el);
});
Fixes
- Protocol-Relative URLs (no longer recommended):
<script src="//cdn.example.com/script.js"></script>
- Enforce HTTPS:
<script src="https://cdn.example.com/script.js"></script>
- Content Security Policy (CSP):
Content-Security-Policy: block-all-mixed-content
- Server-Side Redirect:
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
Special Scenarios
Third-Party Resources Without HTTPS
If a third-party service does not support HTTPS:
- Consider switching providers
- Proxy requests through your own server
- Download and host resources on your HTTPS server
// Proxy example
app.get('/proxy/third-party', async (req, res) => {
const response = await fetch('http://third-party.com/data');
res.send(await response.text());
});
Legacy System Migration
For gradual migration of large legacy systems:
- Use a report URI to collect mixed content warnings
Content-Security-Policy: block-all-mixed-content; report-uri /csp-report
- Implement auto-upgrade mechanisms
Content-Security-Policy: upgrade-insecure-requests
- Fix resources in phases, prioritizing critical ones
Mixed Content and Emerging Technologies
WebSocket Mixed Content
Even if the main page is HTTPS, insecure WebSocket connections pose risks:
// Insecure WebSocket
const socket = new WebSocket('ws://example.com/chat');
// Should use secure WebSocket
const socket = new WebSocket('wss://example.com/chat');
Service Worker Limitations
Service Workers can only be registered on HTTPS pages (except localhost), but they can intercept and modify all network requests, including insecure ones:
self.addEventListener('fetch', event => {
// Upgrade HTTP requests to HTTPS here
const url = new URL(event.request.url);
if (url.protocol === 'http:') {
url.protocol = 'https:';
event.respondWith(fetch(url.toString()));
}
});
Best Practices for Mixed Content
- Development Environment Configuration:
// Webpack dev server configuration
devServer: {
https: true,
proxy: {
'/api': {
target: 'https://backend.example.com',
secure: true
}
}
}
- Build-Time Checks:
// package.json scripts
"scripts": {
"lint:security": "grep -r 'http://' ./src --include='*.js' --include='*.html'"
}
- Automated Testing:
// Puppeteer test example
const browser = await puppeteer.launch();
const page = await browser.newPage();
page.on('request', request => {
if (request.url().startsWith('http:')) {
throw new Error(`Mixed content request: ${request.url()}`);
}
});
- Monitoring and Alerts:
// Frontend error monitoring
window.addEventListener('securitypolicyviolation', (e) => {
if (e.violatedDirective === 'block-all-mixed-content') {
trackMixedContentError(e);
}
});
SEO Impact of Mixed Content
Search engines downgrade pages with mixed content. Google Search Console flags "mixed content" issues:
- Check Google Search Console's security issues report
- Use SEO tools to scan for mixed content
- Ensure all OG tags and structured data use HTTPS URLs
<!-- Insecure OG tag example -->
<meta property="og:image" content="http://example.com/image.jpg">
<!-- Should use HTTPS -->
<meta property="og:image" content="https://example.com/image.jpg">
Mixed Content and Performance Optimization
Consider performance impacts when fixing mixed content:
- HTTP/2 Benefits: HTTPS is a prerequisite for HTTP/2
- Resource Bundling: Reduce the number of URLs needing fixes
- Preloading Secure Resources:
<link rel="preload" href="https://cdn.example.com/font.woff2" as="font">
- CDN Configuration: Ensure CDN supports HTTPS and is properly configured
# CDN HTTPS configuration example
server {
listen 443 ssl http2;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
# ...other configurations
}
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:HTTPS 的基本原理与作用
下一篇:强制 HTTPS(HSTS)