Join our Newsletter — 33% off our NHI Course
Home› Guides› Markdown Rendering Security Guide: XSS, Image Exfiltration and…
Guide Web & API Security

Markdown Rendering Security Guide: XSS, Image Exfiltration and Link Injection

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, under the editorial direction of Lalit Choda Updated 23 November 2026 13 min read
On this page

Markdown looks like plain text, but once it is rendered it becomes HTML, links and image requests, so every place that renders untrusted Markdown is an output channel that needs the same care as any HTML sink. Comment boxes, wikis, issue trackers, README viewers and, above all, chat interfaces for large language models (LLMs) turn Markdown into live markup. When the Markdown comes from a user, a third party document or a model that has read attacker content, the renderer can be used for cross-site scripting (XSS), for silent data exfiltration through image URLs, and for link injection that sends users or tokens somewhere they should not go.

This guide covers how Markdown renderers produce risk, what popular libraries do and do not do by default, why LLM chat surfaces have made image based exfiltration a mainstream problem, and the controls that close each path. It sits alongside our HTML Sanitisation Guide, which covers sanitiser internals in depth; here the focus is the Markdown layer and the decisions you make before and after sanitisation.

Key takeaways

  • Most Markdown libraries pass raw HTML through or leave sanitisation to you. The marked project states plainly that it "does not sanitize the output HTML".
  • Sanitise the final HTML, after all plugins have run, with an allow-list sanitiser. Do not try to filter Markdown text before parsing.
  • Restrict URL schemes on every link and image. Allow http, https and mailto by default and reject javascript:, data: and vbscript:.
  • In LLM interfaces, an auto-loaded Markdown image is a data exfiltration channel: the model can be steered into placing secrets in an image URL query string, and the browser sends them without a click.
  • Control image loading with an allow-list of image hosts, an image proxy or a Content Security Policy img-src directive, not by trusting the model.
  • Treat model output as untrusted input, exactly as the OWASP Top 10 for LLM Applications recommends for improper output handling.

How Markdown becomes an attack surface

A Markdown renderer is a compiler: it takes a lightweight text syntax and emits HTML. Three features of that pipeline create most of the risk.

  • Raw HTML pass-through. The CommonMark specification defines HTML blocks as groups of lines "treated as raw HTML" and passed through without escaping, including blocks that start with <script>, <style> and <textarea>. A spec compliant renderer with HTML enabled will therefore emit script tags if the author writes them.
  • Link and image destinations. Markdown lets authors choose arbitrary URLs for [text](url) and ![alt](url). If the renderer does not check the scheme, a javascript: link becomes clickable script, and an image URL becomes an automatic outbound request.
  • Extensions and plugins. Footnotes, math, diagrams, embeds, autolinking and custom components add new parsers and new output elements. Each one can reintroduce raw HTML or attribute injection that the core parser avoided.

The output is then inserted into a page, usually through innerHTML or a framework equivalent. From that point on the browser treats it as trusted markup with the full privileges of the origin: session cookies, tokens in storage and the ability to call the application's own APIs. That is why an XSS bug in a Markdown preview often has the same impact as one in the core application.

Defaults differ widely, and the safest assumption is that your renderer is not a sanitiser unless its documentation says otherwise.

LibraryDocumented defaultWhat you still need to do
marked (JavaScript)The documentation says "Marked does not sanitize the output HTML" and that "if you are processing potentially unsafe strings, it's important to filter for possible XSS attacks".Pass the output through a sanitiser; the project's own example wraps marked.parse() in DOMPurify.sanitize() and also names js-xss, sanitize-html and insane as options.
react-markdown (React)Described as "secure by default". HTML in the Markdown is escaped or ignored, and defaultUrlTransform allows only http, https, irc, ircs, mailto, xmpp and relative URLs, following GitHub's behaviour.Keep urlTransform safe, review every plugin and custom component, and add rehype-sanitize with an allow-list schema if you enable rehype-raw or third party plugins.

The react-markdown documentation is explicit about where its guarantee ends: setting urlTransform to something insecure "opens you to XSS", the remarkPlugins, rehypePlugins and components you add "may also be insecure", and rehype-raw should only be used "in a trusted environment where you trust the markdown". It also offers skipHtml to ignore HTML entirely, and allowedElements or disallowedElements to limit which tags are rendered.

For other renderers in other languages, check three things in the documentation before shipping: whether raw HTML is enabled by default, whether link and image URLs are validated, and whether the project recommends a sanitiser. If the answer to any of those is unclear, treat the output as unsanitised.

XSS through Markdown

XSS through Markdown usually arrives by one of four routes.

  1. Raw HTML. An author writes <img src=x onerror=...> or a script block directly. If HTML is enabled and nothing sanitises the output, it runs.
  2. Dangerous URL schemes. A link such as [click](javascript:...) renders as an anchor that executes on click. Variants use mixed case, whitespace, entity encoding or data: URLs to slip past naive string checks.
  3. Attribute breakout. Poorly written renderers or plugins build HTML with string concatenation. A quote character in a link title, alt text or code block language label can close the attribute and inject a new event handler.
  4. Post-render manipulation. Client code that runs after rendering, for example a syntax highlighter or a diagram library, may read text content and write it back as HTML, undoing earlier escaping.

The control that covers all four is the same: sanitise the final HTML that will reach the DOM, using a maintained allow-list sanitiser, after every Markdown plugin and post-processor has run. Our Cross-Site Scripting (XSS) Prevention Guide covers the wider XSS defence set, and the Trusted Types and DOM XSS Prevention Guide shows how to force every innerHTML write in a page through a policy, which is a strong backstop for Markdown previews.

Pre-filtering the Markdown text with regular expressions does not work. The same HTML can be written in many forms, and the parser's interpretation, not your filter's, decides what reaches the browser.

Image exfiltration in LLM and agent interfaces

LLM chat interfaces almost always render model output as Markdown, so the model can produce headings, tables and images. That makes the renderer the bridge between a prompt injection and a data leak.

The pattern works like this:

  1. The model reads untrusted content, such as a web page, an email, a shared document or a tool result, that contains hidden instructions. This is indirect prompt injection, catalogued by MITRE ATLAS as AML.T0051 LLM Prompt Injection.
  2. The instructions tell the model to collect something sensitive from its context, such as earlier conversation turns, retrieved documents, API keys or tokens visible to an agent.
  3. The model is told to output a Markdown image whose URL points to an attacker controlled server, with the data appended in the query string or path.
  4. The chat interface renders the image. The browser fetches the URL automatically, and the attacker's server logs the data. The user sees, at most, a broken image icon.

No click is needed, and the request comes from the user's own browser, so network controls on the model provider's side do not see it. The same technique works with links if users are persuaded to click, and with any other element that triggers an automatic fetch. MITRE ATLAS tracks the outcome as AML.T0057 LLM Data Leakage, and the transport is a form of T1567 Exfiltration Over Web Service.

The OWASP entry for LLM05:2025 Improper Output Handling describes the general problem: when "JavaScript or Markdown is generated by the LLM and returned to a user", the browser interprets it, and it recommends that teams "encode model output back to users to mitigate undesired code execution by JavaScript or Markdown". Its references include research titled "Markdown images can steal your chat data".

The risk is higher for agents because they hold credentials. An agent with a GitHub token, a cloud key or an OAuth grant has non-human identity secrets in its context, and an exfiltration path through the renderer can leak them. Our Investigating Agent-Initiated Data Exfiltration guide covers what to do once this has happened.

Controls for image exfiltration

  • Do not auto-load external images from model output. Render them as links, show a placeholder that the user must click, or drop them.
  • Allow-list image hosts. If images are needed, only load them from your own domains or a short, reviewed list.
  • Proxy images. Route images through a server side proxy that strips query strings, checks the host and caches content, so the original URL never reaches the user's browser.
  • Set a strict Content Security Policy. An img-src directive that lists only trusted origins blocks the fetch even if a rogue image tag reaches the DOM. OWASP recommends strict CSP for LLM generated content. See our Content Security Policy Guide.
  • Keep secrets out of model context. The best defence for a token is that the model never sees it. Agents should call tools that hold credentials, not paste them into prompts.

Links are less dangerous than images because they need a click, but they are a common route for phishing and token theft inside trusted interfaces.

  • Misleading link text. Markdown lets link text differ from the destination. A model or user can write a link that reads like your login page but goes elsewhere. Show the destination host on hover or next to external links.
  • Scheme abuse. Allow-list schemes rather than block-listing. React-markdown's default list, which mirrors GitHub, is a sensible starting point.
  • Data in link URLs. As with images, a model can be told to put secrets in a link's query string. Strip or block query strings on links to unknown hosts in high risk contexts.
  • Referrer and opener leakage. Add rel="noopener noreferrer" and, for user content, nofollow or ugc to external links so the destination cannot script the opener window or read internal URLs.
  • Autolinking. Linkify extensions turn bare text into links. Apply the same scheme and host checks to these generated links.

Building a safe rendering pipeline

A sound pipeline has a fixed order, and every stage has one job.

  1. Parse with HTML disabled unless you have a clear need for raw HTML. Most user and model content does not need it.
  2. Validate URLs during rendering with an allow-list of schemes, and for images an allow-list of hosts.
  3. Run plugins and post-processors. Keep the list short and reviewed.
  4. Sanitise the final HTML with an allow-list sanitiser such as DOMPurify in the browser or a maintained server side library, using a configuration limited to the tags and attributes your Markdown features need.
  5. Insert into the DOM through a single, audited function, ideally enforced by Trusted Types.
  6. Back it with CSP that blocks inline script and restricts img-src, connect-src and frame-src.

Where should sanitisation run? Server side sanitisation protects every client and stored copy, but must match the browser's parsing. Client side sanitisation with a DOM based library sees exactly what the browser sees. Many teams do both: sanitise on save to protect stored data and exports, and sanitise again on render. Pin library versions and update promptly, since sanitiser bypasses are found and fixed regularly.

Markdown in LLM applications: design choices

For teams building chat, copilot or agent interfaces, a few design choices remove most of the risk before any sanitiser is involved.

  • Define the output contract. Decide which Markdown features the model may use, for example headings, lists, tables, code blocks and links to approved domains, and render nothing else.
  • Use a restricted renderer for model output. Disable raw HTML, external images and embeds by default, even if the same product allows them for human authors.
  • Separate trusted and untrusted content. Content retrieved from the web or from user files should be marked as untrusted, and responses that draw on it should get the strictest rendering profile.
  • Log rendered URLs. OWASP recommends logging and monitoring LLM outputs. Recording the hosts that appear in rendered links and images gives you a signal for exfiltration attempts.
  • Limit agent privileges. OWASP also recommends limiting the model's privileges to what users need. The less an agent can read, the less it can leak.

Testing and detection

Add Markdown specific cases to your test suite and your security reviews.

  • Unit tests that feed known XSS payloads through the full render path and assert that no event handler attributes, script elements or dangerous schemes survive.
  • Tests for mixed case and encoded schemes, whitespace inside URLs and quotes inside titles and alt text.
  • Prompt injection tests for LLM features: place instructions in a retrieved document that ask for an image pointing to a test domain you control, and confirm the interface does not fetch it.
  • CSP violation reporting enabled in production, so blocked image or script loads show up as events.
  • Monitoring for outbound requests from your web front end to unexpected image hosts. Adapt this monitoring to your logging platform.

Our AI Agent Security Testing Checklist includes wider tests for agent tool use and data handling.

Common failure patterns

  • Assuming the renderer sanitises. Teams pick a fast renderer and never read the security note, then ship raw HTML pass-through.
  • Sanitising before plugins. A sanitiser runs, then a highlighter or embed plugin writes new HTML that is never checked.
  • Block-listing schemes. Filters that look for the string javascript: miss encoded and mixed case forms.
  • Trusting the model. Interfaces render model output with the same profile as staff authored content, so a prompt injection gets full HTML and image loading.
  • Auto-loading images from any host. The single most common LLM exfiltration path, and one of the easiest to close.
  • Different rules in different surfaces. The web app is hardened but the email digest, mobile view, PDF export or IDE extension renders the same Markdown with a weaker library.
  • Weak or missing CSP. No img-src restriction, or unsafe-inline left in script-src, removes the backstop.

Practitioner checklist

  • Inventory every place your products render Markdown, including previews, notifications, exports and LLM chat.
  • For each, record the library, version, whether raw HTML is enabled and whether output is sanitised.
  • Disable raw HTML for user and model content unless there is a documented need.
  • Enforce an allow-list of URL schemes for links and images.
  • Sanitise final HTML with a maintained allow-list sanitiser after all plugins run.
  • Block or proxy external images in LLM output; allow-list image hosts.
  • Deploy CSP with restrictive img-src and no inline script, and collect violation reports.
  • Keep credentials out of model context and limit agent privileges.
  • Add XSS and prompt injection exfiltration cases to automated tests.
  • Track renderer and sanitiser versions in dependency management and patch quickly.

Standards and references

Related NHI Mgmt Group resources: HTML Sanitisation Guide · Cross-Site Scripting (XSS) Prevention Guide · Content Security Policy Guide · AML.T0051 LLM Prompt Injection

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick both boxes to continue.