news 2026/8/21 22:26:55

从头说下DOM XSS

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
从头说下DOM XSS

Demo此问题

1. 写个html 叫test.html吧

<!doctype html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <title>DOM XSS test:test.html</title> </head> <body> <h1>DOM XSS test:test.html</h1> <div id="app"></div> <script> const params = new URLSearchParams(location.search); const msg = params.get('msg') || 'hello'; console.log('msg =', msg); // ← 自检:确认读到 < ...> document.getElementById('app').innerHTML = `<p>${msg}</p>`; </script> </body> </html>

2 powershell 启动web

python -m http.server 8000

3 浏览器访问 localhost:8000/test.html?msg=<img%20src=x%20οnerrοr=alert(1)>

4 看到个弹窗

原因

它直接将用户可控的 URL 参数(msg)拼接到 innerHTML,未做任何转义或过滤。攻击者可以通过构造恶意的 msg 参数注入 JavaScript 代码,从而执行任意脚本。

运行中debug所见

修复方式

1. 输入验证与输出编码

  • 输入验证:对来自location,document.URL,document.referrer,window.name等的值进行严格校验,只允许预期格式(如数字、固定字符串)。
  • 输出编码:在插入 HTML 时使用合适的编码:
    • HTML 内容 →textContentinnerText
    • 属性值 →setAttribute()
    • URL → 使用encodeURIComponent()

2. 避免危险的 DOM API

  • 禁止使用
    • innerHTML,outerHTML,document.write()
  • 替代方案
    • 使用textContentcreateElement()+appendChild()来构建安全 DOM。
<script> const params = new URLSearchParams(location.search); const msg = params.get('msg') || 'hello'; const mode = (params.get('mode') || 'text').toLowerCase(); const app = document.getElementById('app'); // 方案 1:纯文本渲染(默认) function renderText(s){ const p = document.createElement('p'); p.textContent = s; // ✅ 不解析为 HTML app.replaceChildren(p); } // 方案 2:白名单消毒(示例实现,生产用成熟库更好) function renderSanitized(html){ const allowedTags = new Set(['b','i','em','strong','u','a','code','pre','br']); const allowedAttrs = { 'a': new Set(['href','title']) }; const parser = new DOMParser(); const doc = parser.parseFromString(html, 'text/html'); const fragment = document.createDocumentFragment(); const walk = (node, outParent) => { if (node.nodeType === Node.TEXT_NODE) { outParent.appendChild(node.cloneNode()); return; } if (node.nodeType === Node.ELEMENT_NODE) { const tag = node.tagName.toLowerCase(); if (!allowedTags.has(tag)) { Array.from(node.childNodes).forEach(child => walk(child, outParent)); // 剥离不安全标签,仅保留文本/安全子节点 return; } const el = document.createElement(tag); for (const attr of Array.from(node.attributes)) { const name = attr.name.toLowerCase(), value = attr.value; if (name.startsWith('on')) continue; // 禁止事件属性 const allowSet = allowedAttrs[tag]; if (allowSet && !allowSet.has(name)) continue; if (tag === 'a' && name === 'href') { try { const u = new URL(value, location.origin); if (!['http:', 'https:', 'mailto:'].includes(u.protocol.toLowerCase())) continue; // 禁止 javascript:/data:/file:/vbscript: } catch (e) { continue; } } el.setAttribute(name, value); } Array.from(node.childNodes).forEach(child => walk(child, el)); outParent.appendChild(el); } }; Array.from(doc.body.childNodes).forEach(n => walk(n, fragment)); app.replaceChildren(fragment); } if (mode === 'sanitize') renderSanitized(msg); else renderText(msg); </script>
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/8/20 3:44:12

Node.js ES模块安全风险分析:顶层await在webshell中的隐蔽利用

Node.js ES模块安全风险分析&#xff1a;顶层await在webshell中的隐蔽利用 【免费下载链接】webshell This is a webshell open source project 项目地址: https://gitcode.com/gh_mirrors/we/webshell 随着Node.js对ES模块的全面支持&#xff0c;开发者享受到了现代化J…

作者头像 李华
网站建设 2026/8/21 9:20:00

从零开始学量子计算,手把手教你用VSCode调试Shor算法

第一章&#xff1a;从零开始理解Shor算法的核心原理Shor算法是量子计算领域最具突破性的成果之一&#xff0c;由彼得肖尔于1994年提出&#xff0c;能够高效分解大整数&#xff0c;从而对基于RSA的公钥密码体系构成潜在威胁。该算法的核心思想是将整数分解问题转化为周期查找问题…

作者头像 李华
网站建设 2026/8/21 2:45:55

Unity口型同步终极指南:从零实现自然语音动画

Unity口型同步终极指南&#xff1a;从零实现自然语音动画 【免费下载链接】LipSync LipSync for Unity3D 根据语音生成口型动画 支持fmod 项目地址: https://gitcode.com/gh_mirrors/lip/LipSync 还在为游戏角色说话时嘴唇僵硬而烦恼吗&#xff1f;LipSync为Unity开发者…

作者头像 李华
网站建设 2026/8/21 13:41:18

Mission Planner:开启无人机智能飞行的全新体验

Mission Planner&#xff1a;开启无人机智能飞行的全新体验 【免费下载链接】MissionPlanner 项目地址: https://gitcode.com/gh_mirrors/mis/MissionPlanner 还在为复杂的无人机操作而烦恼吗&#xff1f;Mission Planner这款专业的无人机控制软件将成为你飞行旅程中的…

作者头像 李华
网站建设 2026/8/21 13:15:19

【Docker Offload性能飞跃指南】:3种你必须知道的任务分发模式

第一章&#xff1a;Docker Offload性能优化的背景与意义在现代云原生架构中&#xff0c;容器化技术已成为应用部署的核心手段。Docker 作为最广泛使用的容器运行时&#xff0c;其性能表现直接影响到服务响应速度、资源利用率以及整体系统稳定性。随着微服务规模扩大&#xff0c…

作者头像 李华
网站建设 2026/8/21 0:13:14

AMD GPU部署FlashAttention实战指南:突破大模型训练瓶颈

你的训练正在遭遇什么瓶颈&#xff1f; 【免费下载链接】flash-attention Fast and memory-efficient exact attention 项目地址: https://gitcode.com/GitHub_Trending/fl/flash-attention 当你试图在AMD MI200/MI300 GPU上训练大语言模型时&#xff0c;是否经常遇到这…

作者头像 李华