Description
React inserts the string supplied to __html as HTML when you use dangerouslySetInnerHTML. Untrusted markup in CMS content, converted Markdown, or comments can run code in the page.
Potential impact
Injected code can access data or tokens available to the page, call APIs with the user’s privileges, or change what the page displays.
Remediation
- To display text, use the ordinary JSX expression
{html}. - If the feature needs HTML formatting, sanitize it with an HTML sanitizer such as DOMPurify and pass the result unchanged to
__html.
Examples
Before
javascript
import React from "react";
export function Bad({ html }) {
return <section dangerouslySetInnerHTML={{ __html: html }} />;
}
After
javascript
import React from "react";
import DOMPurify from "dompurify";
export function Good({ html }) {
return <section dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(html) }} />;
}
Good passes html to DOMPurify.sanitize immediately before rendering the result.
Limits of striptags options
javascript
import React from "react";
import stripTags from "striptags";
export function UnsafeAllowedTags({ html }) {
return <section dangerouslySetInnerHTML={{ __html: stripTags(html, "<img>") }} />;
}
export function UnsafeReplacement({ html }) {
return <section dangerouslySetInnerHTML={{ __html: stripTags(html, [], "<img src=x onerror=alert(1)>") }} />;
}
export function DefaultStripping({ html }) {
return <section dangerouslySetInnerHTML={{ __html: stripTags(html) }} />;
}
stripTags can leave attributes on allowed tags, and its replacement string can reintroduce HTML. Use an HTML sanitizer for values passed to __html.