@@ -648,31 +648,66 @@ def _fd_realpath(fd):
648648 return None
649649
650650
651- def _hardened_read_open (raw_path , mode , context , required_root , ** kwargs ):
652- """Open ``raw_path`` for reading, closing the symlink-swap TOCTOU and the
653- hardlink escape that a path-only ``validate_path`` cannot.
651+ def _os_open_flags (mode ):
652+ """Translate a :func:`builtins.open` *mode* string into ``os.open()`` flags.
653+
654+ Mirrors the read/write/create/append/truncate intent of *mode* so the
655+ hardened opener can add ``O_NOFOLLOW`` on top of exactly what the caller
656+ asked for. POSIX only.
657+ """
658+ chars = set (mode )
659+ if "x" in chars :
660+ creat = os .O_CREAT | os .O_EXCL
661+ elif "w" in chars :
662+ creat = os .O_CREAT | os .O_TRUNC
663+ elif "a" in chars :
664+ creat = os .O_CREAT | os .O_APPEND
665+ else : # "r" -- open existing, no create
666+ creat = 0
667+ if "+" in chars :
668+ access = os .O_RDWR
669+ elif chars & {"w" , "a" , "x" }:
670+ access = os .O_WRONLY
671+ else :
672+ access = os .O_RDONLY
673+ return access | creat
674+
675+
676+ def _hardened_open (raw_path , mode , context , required_root , ** kwargs ):
677+ """Open ``raw_path`` for read *or* write, closing the symlink-swap TOCTOU and
678+ the hardlink escape that a path-only ``validate_path`` cannot.
654679
655680 1. Open ``raw_path`` with ``O_NOFOLLOW`` so its final component is never
656681 followed as a symlink. Unlike opening a re-resolved path, this is atomic:
657682 the kernel either opens the real inode at that path or fails, so a symlink
658683 swapped in after the caller's ``validate_path`` cannot redirect the open
659- (TOCTOU). Corpora contain no symlinked files, so rejecting a final-
660- component symlink outright is safe and fail-closed.
684+ (TOCTOU). On the write side this stops an attacker who plants/swaps
685+ ``<root>/pkg`` -> ``/etc/...`` between the check and a ``retrieve()`` /
686+ model write from redirecting the write outside the root -- the symmetric
687+ counterpart of the read-side content leak (CWE-59, GHSA-f794 class).
688+ Corpora/data files are never symlinks, so refusing a final-component
689+ symlink outright is fail-closed.
661690 2. ``fstat`` the descriptor and refuse ``st_nlink > 1``: a hardlink is another
662691 name for the same inode with no symlink to resolve, so an in-root hardlink
663- to an outside inode would otherwise leak its contents (CWE-59, GHSA-f794
664- class). Multiply-linked corpus files are not expected.
692+ to an outside inode would otherwise be read or written through.
665693 3. Re-validate the *opened descriptor's* real path (from the kernel, not by
666694 re-resolving the string) so a swapped intermediate directory symlink that
667695 redirected the open to an outside inode is still caught.
668696
669- POSIX only; callers fall back to :func:`builtins.open` elsewhere.
697+ A newly created file is given ``0600`` permissions so a write into a shared
698+ temp dir is not left group-/world-readable (CWE-377/378). POSIX only;
699+ callers fall back to :func:`builtins.open` elsewhere.
670700 """
671701 import errno
672702
673- flags = os .O_RDONLY | getattr (os , "O_NOFOLLOW" , 0 ) | getattr (os , "O_CLOEXEC" , 0 )
703+ flags = (
704+ _os_open_flags (mode )
705+ | getattr (os , "O_NOFOLLOW" , 0 )
706+ | getattr (os , "O_CLOEXEC" , 0 )
707+ )
674708 try :
675- fd = os .open (raw_path , flags )
709+ # 0o600 is only consulted when O_CREAT is in flags (write/append/x modes).
710+ fd = os .open (raw_path , flags , 0o600 )
676711 except OSError as e :
677712 if e .errno in (errno .ELOOP , errno .EMLINK ):
678713 raise PermissionError (
@@ -699,7 +734,19 @@ def _hardened_read_open(raw_path, mode, context, required_root, **kwargs):
699734 except BaseException :
700735 os .close (fd )
701736 raise
702- return os .fdopen (fd , mode , ** kwargs )
737+ try :
738+ return os .fdopen (fd , mode , ** kwargs )
739+ except BaseException :
740+ # os.open() accepts some mode strings that os.fdopen() rejects (e.g. an
741+ # empty or malformed mode); without this the descriptor would leak and
742+ # repeated calls could exhaust the fd table (DoS).
743+ os .close (fd )
744+ raise
745+
746+
747+ # Back-compat alias: the opener now handles write modes too, but external
748+ # callers/tests may still import the original read-only name.
749+ _hardened_read_open = _hardened_open
703750
704751
705752def open (file , mode = "r" , * , context = "pathsec.open" , required_root = None , ** kwargs ):
@@ -734,17 +781,19 @@ def open(file, mode="r", *, context="pathsec.open", required_root=None, **kwargs
734781
735782 # 4. Execution Substitution: validate and open the pure primitive, discarding the original object
736783 validate_path (raw_path , context = context , required_root = required_root )
737- # 5. For read modes under enforcement on POSIX, additionally close the
738- # validate-then-open symlink TOCTOU and the hardlink escape that a path-based
739- # check cannot see. Write/append/update flows and non-POSIX keep the plain
740- # open (their containment is unchanged from before).
741- if ENFORCE and os .name == "posix" and _is_readonly_mode (mode ):
784+ # 5. Under enforcement on POSIX, additionally close the validate-then-open
785+ # symlink TOCTOU and the hardlink escape that a path-based check cannot see.
786+ # This now covers read *and* write/append/update modes: the write side is the
787+ # symmetric counterpart of the read-side leak -- a symlink swapped in at the
788+ # destination after validate_path would otherwise let a retrieve()/model write
789+ # land outside the root (CWE-59). Non-POSIX keeps the plain open.
790+ if ENFORCE and os .name == "posix" :
742791 # The hardened path owns this open entirely: it raises PermissionError /
743792 # ValueError on a security violation and the usual OSError (e.g.
744793 # FileNotFoundError) on a genuine open failure. We must NOT fall back to
745794 # builtins.open on OSError -- retrying the raw path would follow a symlink
746795 # the hardened open deliberately refused, reopening the TOCTOU leak.
747- return _hardened_read_open (raw_path , mode , context , required_root , ** kwargs )
796+ return _hardened_open (raw_path , mode , context , required_root , ** kwargs )
748797 return builtins .open (raw_path , mode = mode , ** kwargs )
749798
750799
0 commit comments