简体   繁体   English

反应:危险地SetInnerHTML

[英]React: dangerouslySetInnerHTML

I've question about dangerouslySetInnerHTML, is it dangerous to use it, when the html comes from my api or there is no difference and maybe attacked anyway?我对 dangerouslySetInnerHTML 有疑问,当 html 来自我的 api 或者没有区别并且可能无论如何都可能受到攻击时,使用它是否危险? Thanks谢谢

When the HTML comes from any API is when it's most dangerous to use dangerouslySetInnerHTML .当 HTML 来自任何API 时,使用dangerouslySetInnerHTML是最危险的。

This is covered in the docs : 文档中对此进行了介绍:

In general, setting HTML from code is risky because it's easy to inadvertently expose your users to a cross-site scripting (XSS) attack.通常,从代码中设置 HTML 是有风险的,因为很容易无意中将您的用户暴露给跨站点脚本 (XSS) 攻击。

Essentially, the issue is that if your server doesn't properly sanitise user input, you open your site up to attacks that React protects you from by default.本质上,问题在于,如果你的服务器没有正确清理用户输入,你就会打开你的网站,让 React 默认保护你免受攻击。 For example, lets say you allow users to write comments on your website, and your API sends back those comments in HTML.例如,假设您允许用户在您的网站上写评论,并且您的 API 将这些评论发回 HTML 中。 If a user writes a comment like eg如果用户写了一个评论,例如

my comment <img src="./404" onerror="alert('test')" />

then eg that JavaScript code might be executed whenever someone else views that comment, unless you remember to protect against that when processing the comments.然后例如 JavaScript 代码可能会在其他人查看该评论时执行,除非您记得在处理评论时防止这种情况发生。


I'd recommend returning your data from your API in a different format (eg JSON), and then processing it into React elements on the frontend.我建议以不同的格式(例如 JSON)从 API 返回您的数据,然后在前端将其处理为 React 元素。

DangerouslySetInnerHTML DangerouslySetInnerHTML

Yes, there's potential concern.是的,有潜在的担忧。 Although, you'll gain some extra performance, since react doesn't compare the dangerouslySetInnerHTML field with Virtual DOM.虽然,您将获得一些额外的性能,因为 react 不会将 dangerouslySetInnerHTML 字段与虚拟 DOM 进行比较。

HOW EXACTLTY IT'S DANGEROUS?到底有多危险?

If user add some malicious code into the comments / other inputs and this data renders on the dangerouslySetInnerHTML field via API, your application deal with XSS Attack ([https://owasp.org/www-community/attacks/xss/][1]).如果用户在评论/其他输入中添加了一些恶意代码,并且此数据通过 API 呈现在 dangerouslySetInnerHTML 字段上,则您的应用程序将处理 XSS 攻击([https://owasp.org/www-community/attacks/xss/][1 ])。

HOW CAN POTENTIAL XSS BE PREVENTED?如何预防潜在的 XSS?

Based on the best practices, it's best to sanitize the dangerouslySetInnerHTML element with some external modules like: DOMPurify (https://github.com/cure53/DOMPurify).根据最佳实践,最好使用一些外部模块清理危险的SetInnerHTML 元素,例如:DOMPurify (https://github.com/cure53/DOMPurify)。 It will remove/filter out the potentially malicious code from the HTML and prevent XSS.它将从 HTML 中删除/过滤掉潜在的恶意代码并防止 XSS。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM