阿里云主机折上折
  • 微信号
Current Site:Index > The security risks of mixed content

The security risks of mixed content

Author:Chuan Chen 阅读数:3545人阅读 分类: 前端安全

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:

  1. Warning Phase: Display warnings in the console but allow loading
  2. Auto-Upgrade: Attempt to rewrite HTTP requests as HTTPS
  3. Block Loading: Block active content outright; passive content may still load but is marked as insecure
  4. 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

  1. Warnings in the browser developer tools console
  2. Security scanning tools like Lighthouse
  3. 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

  1. Protocol-Relative URLs (no longer recommended):
<script src="//cdn.example.com/script.js"></script>
  1. Enforce HTTPS:
<script src="https://cdn.example.com/script.js"></script>
  1. Content Security Policy (CSP):
Content-Security-Policy: block-all-mixed-content
  1. 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:

  1. Consider switching providers
  2. Proxy requests through your own server
  3. 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:

  1. Use a report URI to collect mixed content warnings
Content-Security-Policy: block-all-mixed-content; report-uri /csp-report
  1. Implement auto-upgrade mechanisms
Content-Security-Policy: upgrade-insecure-requests
  1. 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

  1. Development Environment Configuration:
// Webpack dev server configuration
devServer: {
    https: true,
    proxy: {
        '/api': {
            target: 'https://backend.example.com',
            secure: true
        }
    }
}
  1. Build-Time Checks:
// package.json scripts
"scripts": {
    "lint:security": "grep -r 'http://' ./src --include='*.js' --include='*.html'"
}
  1. 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()}`);
    }
});
  1. 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:

  1. Check Google Search Console's security issues report
  2. Use SEO tools to scan for mixed content
  3. 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:

  1. HTTP/2 Benefits: HTTPS is a prerequisite for HTTP/2
  2. Resource Bundling: Reduce the number of URLs needing fixes
  3. Preloading Secure Resources:
<link rel="preload" href="https://cdn.example.com/font.woff2" as="font">
  1. 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

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.