flawopen.com/跨站脚本攻击/Javascript

跨站脚本攻击 in Javascript

高危 CWE-79 Draft — pending review
Language: English Português (Brasil) Español Français Deutsch Русский 简体中文 日本語 हिन्दी 한국어 Bahasa Indonesia
通俗解释 (ELI5)

Imagine a guestbook where a visitor writes a note containing hidden script tags that execute in the browser of the next person who opens the page.

核心概念
output encoding
Converting special markup characters into safe entities so browsers display them as text rather than script.

原理解析

Cross-site scripting happens when untrusted user input is inserted into the DOM without proper HTML output encoding.

真实安全事件

In 2005, the Samy XSS worm infected over 1 million user profiles on MySpace in under 20 hours, forcing the platform offline.

Documented historical AppSec case study.

缺陷代码 vs 修复方案

VULNERABLE
// comment text parsed directly as HTML
function renderComment(el, comment) {
  el.innerHTML =
    `

${comment}

`; }
FIXED
// comment text inserted as safe plain text
function renderComment(el, comment) {
  const p = document.createElement('p');
  p.textContent = comment;
  el.appendChild(p);
}

修复原理

textContent inserts values strictly as plain text, preventing the browser from parsing markup into executable elements.

语言专属陷阱

React dangerouslySetInnerHTML

Explicitly disables React auto-escaping. Must be paired with DOMPurify if used.

常见认知误区

"Frameworks prevent all XSS"

Template escape hatches and direct DOM APIs (innerHTML, outerHTML) bypass framework defenses.

如何检测与排查

grep -rn "\.innerHTML\s*=" --include="*.js" --include="*.ts" . grep -rn "dangerouslySetInnerHTML" --include="*.jsx" --include="*.tsx" .
Configure ESLint rule react/no-danger and DOMPurify for cases where HTML formatting is genuinely required.

防御自查清单

常见问题 (FAQ)

Does Content Security Policy (CSP) replace escaping?

No. CSP provides defense-in-depth, but output encoding remains the primary defense.

参考规范

相关漏洞: SQL Injection Command InjectionPath Traversal