aermin / blog

📝 My blog / notes

Home Page:https://www.aermin.top/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

JSX为何能防止xss注入攻击

aermin opened this issue · comments

默认情况下,React DOM在渲染它们之前先转义JSX中嵌入的任何值。这样可以确保您永远不会注入未在应用程序中明确编写的任何内容。一切在呈现之前都会转换为字符串。这有助于防止XSS(跨站点脚本)攻击。

会将用户输入的,跟HTML符号相同的转义掉。

比如

1)  &lt;   转义成 <

 2)  &gt;  转义成  >

 3)  &amp;   转义成  &

pic1

pic2

image

从上图可看出,react在render之前, 会将字符转义, <img 其实上在html中是&lt;img 的存在,不会和<img /> 标签混淆

当然,如果你使用React 提供的dangerouslySetInnerHTML属性,这将导致JSX不会帮你转义特殊字符。

const aboutUserText = "<img onerror='alert(\"Hacked!\");' src='invalid-image' />";

class AboutUserComponent extends React.Component {
  render() {
    return (
      <div dangerouslySetInnerHTML={{"__html": aboutUserText}} />
    );
  }
}

ReactDOM.render(<AboutUserComponent />, document.querySelector("#app"))

这样将形成一个XSS攻击,每当render的时候,都会跳出一个弹窗,也就是<img onerror='alert(\"Hacked!\");' src='invalid-image' /> 被当成真的一个<img />标签去执行。

image

Reference

https://reactjs.org/docs/introducing-jsx.html

https://stackoverflow.com/questions/7381974/which-characters-need-to-be-escaped-in-html

https://stackoverflow.com/questions/33644499/what-does-it-mean-when-they-say-react-is-xss-protected