前端在红蓝对抗中如何防止 XSS 被利用?

迷人的志青 阅读 40

我们团队最近做了一次红队演练,发现一个页面能被注入脚本。我明明用了 innerText,怎么还是被绕过了?

比如下面这段代码,用户输入的内容是从 URL 参数里拿的,我以为这样就安全了:

const urlParams = new URLSearchParams(window.location.search);
const userInput = urlParams.get('msg') || '默认消息';
document.getElementById('output').innerText = userInput;

但蓝队说只要把元素换成 innerHTML 就会出事,可我没用 innerHTML 啊,是不是还有其他风险点?

我来解答 赞 6 收藏
二维码
手机扫码查看
2 条解答
a'ゞ雨涵
虽然用了 innerText,但别忘了还要考虑其他注入点。建议对用户输入做白名单校验或者HTML实体转义。可以试试这个:

function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/ .replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
const userInput = escapeHtml(urlParams.get('msg') || '默认消息');
document.getElementById('output').innerText = userInput;


这应该能用,记得多测试几种攻击场景。唉,安全真麻烦,但没办法,干就完了。
点赞
2026-03-27 13:01
艺霖
艺霖 Lv1
改成这样
const urlParams = new URLSearchParams(window.location.search);
const userInput = urlParams.get('msg') || '默认消息';
document.getElementById('output').textContent = userInput;
点赞
2026-03-23 10:03