Mistune directives/include: mutual `.. include::` recursion crashes the renderer with `RecursionError`, denial of service via two attacker-controlled markdown files
위협 신호 · CVSS · EPSS · KEV
이론적 심각도 점수
30일 내 악용 확률 예측
실측 악용 기록 없음
2주 이내 패치 — 우선 조치 대상
CVSS 벡터 · 메트릭
CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:L상세 설명
Summary
Type: Uncontrolled recursion via mutual include. The Include directive checks for direct self-reference (a.md cannot include a.md), but does not detect indirect cycles. Two markdown files that include each other (a.md → includes b.md → includes a.md) cause unbounded recursion until Python's stack limit fires RecursionError. 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. When a.md includes b.md, the recursive block.parse(new_state) call uses dest (b.md) as the new __file__, which then includes a.md (passing the self-check, because the immediate parent file is b.md, not a.md), which then includes b.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 raises RecursionError. Since the directive does not catch the exception, it propagates out of Markdown.parse() and surfaces in the calling code, crashing the request.
Affected Code
File: src/mistune/directives/include.py, lines 28-54.
1relpath = self.parse_title(m) 2dest = os.path.join(os.path.dirname(source_file), relpath) 3dest = os.path.normpath(dest) 4 5if os.path.abspath(dest) == os.path.abspath(source_file): # <-- only catches direct self-include 6 return {"type": "block_error", "raw": "Could not include self: " + relpath} 7 8if not os.path.isfile(dest): 9 return {"type": "block_error", "raw": "Could not find file: " + relpath}10 11with open(dest, "rb") as f:12 content = f.read().decode(encoding)13 14ext = os.path.splitext(relpath)[1]15if ext in {".md", ".markdown", ".mkd"}:16 new_state = block.state_cls()17 new_state.env["__file__"] = dest18 new_state.process(content)19 block.parse(new_state) # <-- recursive parse, no cycle tracking20 return new_state.tokensWhy 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
- Application uses mistune with the
Includedirective enabled. Application accepts user-supplied markdown files (CMS, wiki, multi-user documentation platform, note-taking app, CI/CD doc renderer). - Attacker uploads two markdown files:
a.md:.. include:: b.mdb.md:.. include:: a.md
- Renderer is invoked on
a.md(or any markdown that references this pair).Includedirective includesb.md, which includesa.md, which includesb.md, ... Each recursion adds Python frames. - After ~340 cycle iterations (depending on default
sys.setrecursionlimit(1000)and the per-include frame depth), Python raisesRecursionError: maximum recursion depth exceeded. - The exception is not caught by the directive. It propagates through
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 Include directive 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:
1import os, mistune 2from mistune.directives import RSTDirective, Include 3 4os.makedirs('/tmp/mistune-recur', exist_ok=True) 5with open('/tmp/mistune-recur/a.md', 'w') as f: 6 f.write('A\n\n.. include:: b.md') 7with open('/tmp/mistune-recur/b.md', 'w') as f: 8 f.write('B\n\n.. include:: a.md') 9 10md = mistune.create_markdown(plugins=[RSTDirective([Include()])])11state = md.block.state_cls()12state.env['__file__'] = '/tmp/mistune-recur/a.md'13md.parse('.. include:: b.md', state=state)14# RecursionError: maximum recursion depth exceededThe patched build (with the suggested fix below) returns a block_error token like the existing self-include check, instead of recursing forever.
Suggested Fix
Track included paths in state.env and reject any include that would re-enter a path already on the include stack:
1--- a/src/mistune/directives/include.py 2+++ b/src/mistune/directives/include.py 3@@ -28,8 +28,18 @@ class Include(DirectivePlugin): 4 relpath = self.parse_title(m) 5- dest = os.path.join(os.path.dirname(source_file), relpath) 6- dest = os.path.normpath(dest) 7+ base = os.path.realpath(os.path.dirname(source_file)) 8+ dest = os.path.realpath(os.path.join(base, relpath)) 9+10+ # Track include stack across recursive parses to detect cycles.11+ include_stack = state.env.setdefault("__include_stack__", [])12+ if dest in include_stack or dest == os.path.realpath(source_file):13+ return {14+ "type": "block_error",15+ "raw": "Could not include (cycle): " + relpath,16+ }17 18- if os.path.abspath(dest) == os.path.abspath(source_file):19- return {20- "type": "block_error",21- "raw": "Could not include self: " + relpath,22- }23@@ ... in the markdown-include branch ...24+ include_stack.append(dest)25+ try:26+ new_state = block.state_cls()27+ new_state.env["__file__"] = dest28+ new_state.env["__include_stack__"] = include_stack29+ new_state.process(content)30+ block.parse(new_state)31+ return new_state.tokens32+ finally:33+ include_stack.pop()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 the Include directive safe to enable on user-supplied markdown.
Add a regression test asserting that a 2-cycle and a 3-cycle both produce block_error rather than RecursionError.
AI 심층 분석
공격 시나리오 · 재현 가능한 PoC 페이로드 · 즉시 적용 가능한 차단 패치를 한 번에 받아 보세요. 보안 운영팀이 그대로 점검·티켓팅에 쓸 수 있는 형태로 정리해 드립니다.
참고 자료 6
링크 내용 불러오는 중…