The vulnerability exists in the mistune library because it fails to properly sanitize user-controllable input when generating HTML headings and table of contents. Specifically, the id attribute of a heading and the href attribute in the table of contents were constructed using string concatenation without proper escaping.
The analysis of the commits between the vulnerable version 3.2.0 and the patched version 3.2.1 revealed two key fixes.
-
In src/mistune/renderers/html.py, the heading method of the HTMLRenderer class was modified to use escape_text() on the _id variable before including it in the id attribute of the generated heading tag. This prevents attackers from breaking out of the id attribute and injecting malicious attributes.
-
In src/mistune/toc.py, the render_toc_ul function was updated to use escape() on the k variable (the heading ID) before inserting it into the href attribute of the anchor tag in the table of contents. This mitigates the risk of XSS through the table of contents links.
By exploiting this vulnerability, an attacker could inject malicious JavaScript code that would be executed in the context of the user's browser, leading to session hijacking, DOM manipulation, or other client-side attacks. The vulnerable functions HTMLRenderer.heading and render_toc_ul would appear in a runtime profile when the vulnerability is triggered.