Kestrel
대시보드로 돌아가기
CVE-2026-59930MEDIUM· 4.3MITRENVDGHSA대응게시일: 2026. 07. 08.수정일: 2026. 07. 20.

Mistune toc / TableOfContents directive: heading IDs use predictable `toc_N` numbering with no slugification, allowing collision with attacker-controlled `id="toc_N"` content

위협 신호 · CVSS · EPSS · KEV

정기 패치· 높은 악용 신호 없음
CVSS
4.3medium

이론적 심각도 점수

EPSS
0.1%상위 96.4%

30일 내 악용 확률 예측

KEV
미등재

실측 악용 기록 없음

권장 대응 기한60일 이내CISA SSVC 기준

계획된 패치 주기 내 조치(60일 이내)

외부 노출· KEV 미등재 · 자동화 어려움 · 부분 영향 · 외부 노출

CVSS 벡터 · 메트릭

악용 경로
공격 벡터네트워크
공격 복잡도낮음
필요 권한불필요
사용자 상호작용필요
범위불변
영향
기밀성 영향없음
무결성 영향낮음
가용성 영향없음
버전별 점수
CVSS 3.14.3MODERATE
CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N

상세 설명

Summary

Type: Predictable identifier generation. The toc plugin and TableOfContents directive both default to generating heading IDs of the form toc_1, toc_2, toc_3, ... with no input-derived component. An attacker who can place a heading anywhere in the document can predict which toc_N ID it will receive, and can inject HTML elsewhere (in a non-heading context) that uses the same id="toc_N" to either (a) shadow the legitimate heading anchor, breaking same-page navigation, or (b) collide with CSS or JavaScript that targets #toc_N selectors, redirecting click handlers and styling to attacker-chosen content.
File: src/mistune/toc.py line 36-37 (heading_id = lambda token, index: "toc_" + str(index + 1)); src/mistune/directives/toc.py line 33 (same default).
Root cause: the default heading_id callback ignores the heading's text content and uses only the headings's order in the document. Two documents rendered together (or one document with attacker-influenced headings spliced into trusted content) produce overlapping toc_N IDs. Because id attribute uniqueness is required by HTML, browsers behaviour on duplicate IDs is undefined; document.getElementById('toc_1') returns the first match, getElementsByTagName + querySelector semantics differ across paths, and CSS rules targeting #toc_1 apply to whichever element matches first in tree order.

Affected Code

File: src/mistune/toc.py, lines 33-39.

python
1def add_toc_hook(md, min_level=1, max_level=3, heading_id=None):
2 if heading_id is None:
3 def heading_id(token, index):
4 return "toc_" + str(index + 1) # <-- BUG: index-only ID, no slug derived from heading text

File: src/mistune/directives/toc.py, lines 32-33.

python
1class TableOfContents(DirectivePlugin):
2 def __init__(self, min_level=1, max_level=3):
3 # ...
4
5 def generate_heading_id(self, token, index):
6 return "toc_" + str(index + 1) # <-- BUG: same predictable scheme

Why it's wrong: the standard markdown-engine convention (used by GitHub-flavoured Markdown, Sphinx, MkDocs, pandoc, every modern markdown renderer in production) is to slugify the heading TEXT for the ID — <h1 id="introduction">Introduction</h1> — with a numeric suffix appended only when slug collisions occur. mistune's default punts the slugification entirely and produces purely positional IDs that an attacker can predict in O(1).

The downstream impacts:

  • Same-page links with [click](#toc_1) go to whichever element with id="toc_1" appears first in tree order. If the attacker can land any HTML element with id="toc_1" before the real heading (via inline_html with escape=False, via the include-directive HTML branch, via attacker-supplied content earlier in the document), navigation is hijacked.
  • CSS rules targeting #toc_1 apply to the wrong element.
  • JavaScript bound to document.getElementById('toc_1') operates on the wrong element.
  • The TOC's own <a href="#toc_1"> link in the rendered TOC list points to whichever element wins the duplicate-ID race.

Exploit Chain

  1. Application uses mistune with add_toc_hook(md) or TableOfContents directive enabled (the documented setup for sites with TOC support).
  2. Application renders an attacker-supplied document, or splices attacker content into a trusted document. With escape=False (or via the include-directive .html branch covered by my prior advisory), the attacker can place <a id="toc_1">...</a> anywhere in the document.
  3. mistune assigns id="toc_1" to the first heading. Now there are two elements with id="toc_1" in the page.
  4. The rendered TOC contains <a href="#toc_1">First heading</a>. Clicking it navigates to whichever element with id="toc_1" appears first in tree order. If the attacker placed their <a id="toc_1"> BEFORE the heading, navigation is hijacked.
  5. Same-page CSS / JS / aria-described references to #toc_1 similarly redirect.

Security Impact

Severity: sec-low. Not a direct XSS or RCE; the issue is identifier confusion that enables UI-redirection / navigation-hijack attacks. The realistic attacker capability is "make an internal anchor link go to attacker content instead of the real heading", or "make a CSS selector apply to attacker content", or "break aria/screen-reader associations".
Attacker capability: with the ability to plant any HTML element with id="toc_N" in the document, hijack <a href="#toc_N"> navigation and any CSS/JS targeting that ID. With escape=False, this is straightforward. With escape=True, the attacker needs another vector to land a raw id attribute (one of the include-directive branches, a sibling tooling pipeline that lets HTML through, etc.).
Preconditions: application uses TOC + the default heading_id callback. If the application provides its own heading_id (e.g., one based on slugified heading text, with collision suffixes), this finding does not apply.
Differential: PoC-verified against mistune@3.2.1:

python
1import mistune
2from mistune.directives import RSTDirective, TableOfContents
3md = mistune.create_markdown(plugins=[RSTDirective([TableOfContents()])])
4
5print(md('''
6.. toc::
7
8# Heading 1
9
10# Heading 2
11'''))
12
13# Output (note: id="toc_1" / id="toc_2", purely positional):
14# <details class="toc" open>
15# <summary>Table of Contents</summary>
16# <ul>
17# <li><a href="#toc_1">Heading 1</a></li>
18# <li><a href="#toc_2">Heading 2</a></li>
19# </ul>
20# </details>
21# <h1 id="toc_1">Heading 1</h1>
22# <h1 id="toc_2">Heading 2</h1>

The patched build (with the suggested fix below) produces text-derived slugs like id="heading-1" and id="heading-2", which are tied to content rather than position.

Suggested Fix

Default to slugifying the heading text:

python
1--- a/src/mistune/toc.py
2+++ b/src/mistune/toc.py
3@@ -33,9 +33,18 @@ def add_toc_hook(md, min_level=1, max_level=3, heading_id=None):
4 if heading_id is None:
5+ import re
6+ _slug_re = re.compile(r"[^a-z0-9]+")
7+ seen = {}
8 def heading_id(token, index):
9- return "toc_" + str(index + 1)
10+ text = striptags(md.renderer(md.inline(token["text"], {}), BlockState()))
11+ slug = _slug_re.sub("-", text.lower()).strip("-") or "section"
12+ n = seen.get(slug, 0)
13+ seen[slug] = n + 1
14+ return slug if n == 0 else f"{slug}-{n}"

Same change applies to src/mistune/directives/toc.py:33. Existing applications that have hardcoded #toc_N anchors will break; document the migration in the changelog and consider providing an opt-out flag for the legacy behaviour. Add a regression test that asserts heading IDs are slug-derived, not position-derived, and that collisions get a -N suffix.

AI 심층 분석

공격 시나리오 · 재현 가능한 PoC 페이로드 · 즉시 적용 가능한 차단 패치를 한 번에 받아 보세요. 보안 운영팀이 그대로 점검·티켓팅에 쓸 수 있는 형태로 정리해 드립니다.