XSS from raw HTML in react-markdown

XSS from rendering raw HTML in react-markdown

Description

By default, react-markdown displays embedded HTML as text. You can omit it with skipHtml. Adding rehype-raw turns the HTML into elements, so untrusted Markdown then needs a sanitization step. Check older configurations for allowDangerousHtml or escapeHtml={false}.

Potential impact

Code inserted into the page can alter what users see or read account information available to the page.

Remediation

  • Keep the default rendering for user-supplied Markdown. If you need HTML, run rehype-sanitize after rehype-raw and allow only the tags and attributes the feature requires.
  • If you override URL transformation, allow only the schemes you need and reject javascript: and data:.

Examples

Before

tsx
import ReactMarkdown from "react-markdown";
import rehypeRaw from "rehype-raw";

function UnsafeComponent({ markdown }) {
  // Unsafe: parse raw HTML from untrusted Markdown
  return <ReactMarkdown rehypePlugins={[rehypeRaw]}>{markdown}</ReactMarkdown>;
}

After

tsx
import ReactMarkdown from "react-markdown";
import rehypeRaw from "rehype-raw";
import rehypeSanitize from "rehype-sanitize";

function SafeComponent({ markdown }) {
  // Safer default: do not parse raw HTML
  return <ReactMarkdown>{markdown}</ReactMarkdown>;
}

function SafeHtmlComponent({ trustedButNeedsHtml }) {
  // Sanitize HTML when it must be allowed
  return (
    <ReactMarkdown rehypePlugins={[rehypeRaw, rehypeSanitize]}>
      {trustedButNeedsHtml}
    </ReactMarkdown>
  );
}

SafeComponent uses the default rendering. SafeHtmlComponent parses the HTML first and renders only the elements and attributes allowed by its sanitization policy.

References