Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JSX为何能防止xss注入攻击 #75

Open
aermin opened this issue Apr 18, 2020 · 0 comments
Open

JSX为何能防止xss注入攻击 #75

aermin opened this issue Apr 18, 2020 · 0 comments
Labels

Comments

@aermin
Copy link
Owner

aermin commented Apr 18, 2020

默认情况下,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

@aermin aermin added the react label Apr 18, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant