File._get_disk_file: filenames with NUL / non-UTF-8 extension bytes raise ValueError/UnicodeDecodeError instead of FileError
Les mainteneurs répondent en général sous 1 jour
Personne n'a encore pris cette issue.
Évaluation
- Difficulté
- 2/5
- Temps estimé
- 1-3 heures
- Accessibilité débutants
- 85/100
Piste de recherche
Commence dans python_multipart/multipart.py autour des trois emplacements aux lignes 550, 560 et 574 : lis File._get_disk_file avec le contrat d'exception dans THREAT_MODEL.md. Lance le reproducer de l'issue avec UPLOAD_KEEP_EXTENSIONS=True pour confirmer le ValueError qui s'échappe, puis convertis ValueError/UnicodeDecodeError à ces emplacements en FileError et ajoute des tests pour un nom de fichier avec NUL et une extension non UTF-8. Terminé signifie que les noms malformés lèvent FileError tandis que les noms de fichier bénins se parsent encore.
Rédigé par le modèle d'indexation à partir du texte de l'issue.
Description
Hi! Filing this as a public bug per THREAT_MODEL.md — "What does not count" → "Report these as public issues if you think they are bugs." So: exception-contract bug on malformed input, not a vulnerability claim.
What happens
File._get_disk_file guards its sinks with except OSError (multipart.py:551, :575), and computes the tempfile suffix with a decode that sits outside any try (multipart.py:560). But the underlying calls can raise non-OSError exceptions on attacker-controlled filename= bytes:
| Site | Call | Attacker input that raises |
|---|---|---|
multipart.py:550 |
open(path, "w+b") |
ValueError: embedded null byte (filename contains NUL) |
multipart.py:560 |
self._ext.decode(sys.getfilesystemencoding()) |
UnicodeDecodeError (extension bytes not valid UTF-8) |
multipart.py:574 |
tempfile.NamedTemporaryFile(suffix=suffix, ...) |
ValueError: open: embedded null character in path (NUL in extension) |
ValueError/UnicodeDecodeError are not OSError, so the documented contract — "Malformed input raises FormParserError or one of its subclasses" (Security goals in THREAT_MODEL.md) — is bypassed and the raw exception escapes FormParser/parse_form into the calling application.
Reachability: UPLOAD_KEEP_FILENAME=True (with UPLOAD_DIR) or UPLOAD_KEEP_EXTENSIONS=True, plus a part larger than MAX_MEMORY_FILE_SIZE (default 1 MiB) so flush_to_disk runs. The filename bytes survive parse_options_header (latin-1 roundtrip) and os.path.basename/os.path.splitext untouched, including NUL and \xff.
Reproducer
"""python-multipart 0.0.34 reproducer: NUL in filename= escapes the FileError contract."""
import sys
from python_multipart.exceptions import FileError
from python_multipart.multipart import FormParser
body = (
b"--bnd\r\n"
b'Content-Disposition: form-data; name="f"; filename="a.tx\x00t"\r\n'
b"Content-Type: application/octet-stream\r\n\r\n"
+ b"A" * (1024 * 1024 + 16) # > MAX_MEMORY_FILE_SIZE (1 MiB default) forces flush_to_disk
+ b"\r\n--bnd--\r\n"
)
parser = FormParser("multipart/form-data", lambda f: None, lambda f: None,
boundary="bnd", config={"UPLOAD_KEEP_EXTENSIONS": True})
try:
parser.write(body)
parser.finalize()
except FileError as exc:
print("contract kept ->", type(exc).__name__, ":", exc); sys.exit(1)
except Exception as exc:
print(f"BUG: {type(exc).__name__} escaped the FileError contract: {exc}"); sys.exit(0)
print("clean parse (no disk write?)"); sys.exit(1)
$ python3 -m venv v && ./v/bin/pip install python-multipart==0.0.34 && ./v/bin/python repro.py
BUG: ValueError escaped the FileError contract: open: embedded null character in path
Verified against the 0.0.34 PyPI wheel and the 0.0.34 tag source, on Python 3.14 (host) and 3.12 (python:3.12-slim container). The same three escape variants fire with UPLOAD_KEEP_FILENAME=True + UPLOAD_DIR (open() path).
Control: the same NUL filename with MAX_MEMORY_FILE_SIZE=float("inf") (no flush → no disk write) parses cleanly — so it is specifically the disk-write path that converts the NUL byte into an escaping exception.
Suggested fix
Catch the concrete non-OSError failure modes at all three sites and convert them to FileError, e.g.:
tmp_file = open(path, "w+b")
- except OSError:
+ except (OSError, ValueError):
and in the else branch, move the suffix decode inside the existing try:
- suffix = self._ext.decode(sys.getfilesystemencoding()) if keep_extensions else None
...
try:
+ suffix = self._ext.decode(sys.getfilesystemencoding()) if keep_extensions else None
tmp_file = cast(BufferedRandom, tempfile.NamedTemporaryFile(suffix=suffix, delete=delete_tmp, dir=dir))
- except OSError:
+ except (OSError, ValueError, UnicodeDecodeError):
With that change the reproducer flips to contract kept -> FileError : Error creating named temporary file, and a benign filename keeps parsing cleanly (verified on a patched build). Happy to open a PR if you'd like — the patch is 6 insertions / 7 deletions against 0.0.34.
- Langage dominant
- Python
- Étoiles
- 539
- Forks
- 109
- Merge moyen
- 6 h 35 min
- PR mergées (30 j)
- 20
Préparer son environnement
- Aucun Dockerfile ni fichier Docker Compose
- Aucun modèle de pull request
- Lire le guide de contribution
Par où commencer
- Lisez l'issue en entier, puis le guide de contribution du projet.
- Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
- Forkez le dépôt et travaillez sur une branche.
- Ouvrez une pull request qui référence le numéro de l'issue.
Autres issues de Kludex/python-multipart
-
Clarify or handle non-Latin-1 str input in parse_options_headerPeut-être à nouveau libre Une pull request pour cette issue a été fermée sans être fusionnée. Ouverte
Difficulté 4/5 3-5 jours Accessibilité débutants 42/100
Kludex/python-multipart#319 · 1 commentaire ·
Les mainteneurs répondent en général sous 1 jour
-
Skip header area?Peut-être pris @Kludex l’a pris il y a 225 jours. Ouverte
Difficulté 3/5 1-2 jours Accessibilité débutants 48/100
Kludex/python-multipart#59 · 3 commentaires ·
Les mainteneurs répondent en général sous 1 jour
Toutes les issues de Kludex/python-multipart
Issues similaires
-
Difficulté 2/5 1-3 heures Accessibilité débutants 65/100
Les mainteneurs répondent en général sous 3 jours
-
enhancement
Difficulté 2/5 1-3 heures Accessibilité débutants 74/100
Les mainteneurs répondent en général sous 11 jours
-
Difficulté 2/5 1-3 heures Accessibilité débutants 80/100
FuRongJun-1999/dsh-memory#1000 ·
Les mainteneurs répondent en général sous 1 jour
-
Difficulté 2/5 1-3 heures Accessibilité débutants 68/100
gcivil-nyu-org/team5-mon-fall26#154 ·
Les mainteneurs répondent en général sous 1 jour
-
docs: reorder interface definition before fetch-libs and link PostgreSQL/library docs in tutorialOuverte
Difficulté 1/5 Moins d'une heure Accessibilité débutants 90/100
Les mainteneurs répondent en général sous 3 jours