HTML安全与防护

🧱 一、重点知识与细节

1. XSS(跨站脚本攻击)

概念:恶意用户向页面注入 JavaScript(或 HTML),执行在其他用户的浏览器中。 示例

<!-- 危险的直接输出用户输入 -->
<p>欢迎:<span id="user"></span></p>
<script>
  document.getElementById('user').innerHTML = location.search; // ❌
</script>

防护方法


2. CSP(内容安全策略)

概念:限制浏览器加载哪些外部资源、执行哪些脚本。 作用:防止 XSS、数据注入、恶意脚本。 示例

<meta http-equiv="Content-Security-Policy" 
      content="default-src 'self'; img-src https://images.example.com; script-src 'self'">

注意细节


3. iframe 安全

风险:外部网站可利用 iframe 注入或窃取信息。 安全做法

<iframe src="https://example.com" sandbox="allow-scripts allow-same-origin"></iframe>

4. HTTPS 与 Mixed Content

问题:HTTPS 页面内若引用 HTTP 资源,会导致“混合内容警告”。 解决方案


5. 表单安全

重点


6. 隐私与追踪控制

示例

<meta name="referrer" content="no-referrer">
<meta http-equiv="Permissions-Policy" content="geolocation=(), microphone=()">

作用


7. 点击劫持(Clickjacking)

防护


8. 可信脚本与外部依赖管理

建议

<script src="https://cdn.example.com/app.js"
        integrity="sha384-xxxxx"
        crossorigin="anonymous"></script>

✅ 二、开发 Checklist

项目检查目标
🔒 HTTPS所有资源均使用 HTTPS
🧱 CSP已设置 Content-Security-Policy
🧩 XSS 防护所有用户输入均转义
🪟 iframe 限制所有外部 iframe 添加 sandbox
📋 表单安全添加 CSRF token、限制上传类型
🕵️ Referrer添加 <meta name="referrer" content="no-referrer">
🧍 权限控制<meta http-equiv="Permissions-Policy">
🧰 外部脚本完整性添加 integritycrossorigin
🚫 Frame 防护添加 X-Frame-Options 或 CSP frame-ancestors
🧼 Cookie 安全服务端设置 HttpOnly; Secure; SameSite=Strict