返回 last30days-skill
private_files.py
根目录 / skills / last30days / scripts / lib / private_files.py
1 """Private local files."""
2
3 import errno
4 import os
5 import secrets
6 import stat
7 import tempfile
8 import time
9 from pathlib import Path
10
11 _WINDOWS_SHARING_VIOLATION = 32
12 _IS_JUNCTION = getattr(os.path, "isjunction", None)
13 _GETEUID = getattr(os, "geteuid", None)
14 _OS_LSTAT = os.lstat
15 _OS_READLINK = os.readlink
16 _OS_GETCWD = os.getcwd
17 _MAX_SYMLINK_HOPS = 40
18
19
20 def _group_writable_by_other_user(st: os.stat_result, euid: int) -> bool:
21 """Return True if a group-writable mode grants write access to another non-root user."""
22 if not (st.st_mode & stat.S_IWGRP):
23 return False
24 try:
25 import grp
26 import pwd
27
28 pw = pwd.getpwuid(euid)
29 gr = grp.getgrgid(st.st_gid)
30 except (ImportError, KeyError):
31 return True
32 other_members = set(gr.gr_mem) - {pw.pw_name, "root"}
33 if other_members:
34 return True
35 if hasattr(pwd, "getpwall"):
36 try:
37 for entry in pwd.getpwall():
38 if entry.pw_uid not in (euid, 0) and entry.pw_gid == st.st_gid:
39 return True
40 except OSError:
41 return True
42 if st.st_gid == 0:
43 return False
44 if st.st_gid == pw.pw_gid and gr.gr_name == pw.pw_name:
45 return False
46 return True
47
48
49 def _is_writable_by_others(st: os.stat_result, euid: int) -> bool:
50 return bool(st.st_mode & stat.S_IWOTH) or _group_writable_by_other_user(st, euid)
51
52
53 def _stat_directory_nofollow(directory: Path) -> os.stat_result:
54 """Stat ``directory`` without following symlinks or requiring read/list permission."""
55 st = _OS_LSTAT(directory)
56 if stat.S_ISLNK(st.st_mode):
57 raise OSError(errno.ELOOP, f"Refusing to follow symlink directory: {directory}")
58 if not stat.S_ISDIR(st.st_mode):
59 raise OSError(f"Expected a directory for private file: {directory}")
60 return st
61
62
63 def _check_ancestor_dir(directory: Path, st: os.stat_result, euid: int) -> None:
64 if not stat.S_ISDIR(st.st_mode):
65 raise OSError(f"Expected a directory ancestor for private file: {directory}")
66 if st.st_uid not in (euid, 0):
67 raise OSError(f"Refusing to use directory under untrusted owner: {directory}")
68 if _is_writable_by_others(st, euid) and not (st.st_mode & stat.S_ISVTX):
69 raise OSError(
70 f"Refusing to use directory under writable non-sticky ancestor: {directory}"
71 )
72
73
74 def _verify_private_directory_chain(parent: Path, *, allow_root_owner: bool = False) -> None:
75 """Verify the parent directory and its ancestors cannot be modified by other users."""
76 if _GETEUID is None:
77 return
78 euid = _GETEUID()
79 parent_st = _stat_directory_nofollow(parent)
80 allowed_parent_uids = (euid, 0) if allow_root_owner else (euid,)
81 if parent_st.st_uid not in allowed_parent_uids:
82 raise OSError(f"Refusing to use private directory owned by another user: {parent}")
83 if _is_writable_by_others(parent_st, euid):
84 raise OSError(f"Refusing to use private directory writable by other users: {parent}")
85
86 for ancestor in parent.parents:
87 anc_st = _stat_directory_nofollow(ancestor)
88 _check_ancestor_dir(ancestor, anc_st, euid)
89
90
91 def _resolve_trusted_parent_dir(parent: Path, *, allow_root_owner: bool = False) -> Path:
92 """Resolve ``parent`` hop-by-hop, allowing only trusted symlinks in trusted directories."""
93 if _GETEUID is None:
94 return parent.resolve()
95 euid = _GETEUID()
96 abs_parent = parent if parent.is_absolute() else Path(_OS_GETCWD()) / parent
97 anchor = abs_parent.anchor or "/"
98 pending = list(abs_parent.parts[1:])
99 current = Path(anchor)
100 current_st = _stat_directory_nofollow(current)
101 _check_ancestor_dir(current, current_st, euid)
102 hops = 0
103
104 while pending:
105 part = pending.pop(0)
106 if not part or part == ".":
107 continue
108 if part == "..":
109 current = current.parent
110 current_st = _stat_directory_nofollow(current)
111 _check_ancestor_dir(current, current_st, euid)
112 continue
113
114 candidate = current / part
115 cand_st = _OS_LSTAT(candidate)
116 if stat.S_ISLNK(cand_st.st_mode):
117 if _is_writable_by_others(current_st, euid):
118 raise OSError(
119 errno.ELOOP,
120 f"Refusing to follow symlink in directory writable by other users: {candidate}",
121 )
122 if cand_st.st_uid not in (euid, 0):
123 raise OSError(
124 errno.ELOOP,
125 f"Refusing to follow symlink owned by another user: {candidate}",
126 )
127 if current_st.st_uid not in (euid, 0):
128 raise OSError(
129 errno.ELOOP,
130 f"Refusing to follow symlink in untrusted directory: {candidate}",
131 )
132
133 hops += 1
134 if hops > _MAX_SYMLINK_HOPS:
135 raise OSError(errno.ELOOP, f"Too many symbolic links in private path: {parent}")
136
137 link_target = Path(_OS_READLINK(candidate))
138 if link_target.is_absolute():
139 target_anchor = link_target.anchor or "/"
140 pending = list(link_target.parts[1:]) + pending
141 current = Path(target_anchor)
142 current_st = _stat_directory_nofollow(current)
143 _check_ancestor_dir(current, current_st, euid)
144 else:
145 pending = list(link_target.parts) + pending
146 continue
147
148 if pending:
149 _check_ancestor_dir(candidate, cand_st, euid)
150 current = candidate
151 current_st = cand_st
152
153 _verify_private_directory_chain(current, allow_root_owner=allow_root_owner)
154 return current
155
156
157 def _reject_symlink_or_nonregular(path: Path) -> None:
158 """Reject symlinks, Windows junctions, and non-regular existing paths without dereferencing."""
159 if _IS_JUNCTION is not None and _IS_JUNCTION(path):
160 raise OSError(f"Refusing to follow junction: {path}")
161 try:
162 mode = path.lstat().st_mode
163 except FileNotFoundError:
164 return
165 if stat.S_ISLNK(mode):
166 raise OSError(errno.ELOOP, f"Refusing to follow symlink: {path}")
167 if not stat.S_ISREG(mode):
168 raise OSError(f"Expected a regular private file: {path}")
169
170
171 def _resolve_parent_only(path: Path, *, allow_root_owner: bool = False) -> Path:
172 """Resolve and validate only the parent directory so a leaf symlink is never dereferenced."""
173 path = Path(path)
174 if path.name in ("", ".", ".."):
175 raise OSError(f"Expected a regular private file path: {path}")
176 _reject_symlink_or_nonregular(path)
177 resolved_parent = _resolve_trusted_parent_dir(
178 path.parent, allow_root_owner=allow_root_owner
179 )
180 resolved = resolved_parent / path.name
181 _reject_symlink_or_nonregular(resolved)
182 return resolved
183
184
185 def replace_private_text(path: Path, content: str) -> None:
186 """Publish UTF-8 text atomically from an owner-only temporary file."""
187 if os.name == "posix":
188 path = _resolve_parent_only(path)
189 else:
190 _reject_symlink_or_nonregular(path)
191 staged = tempfile.NamedTemporaryFile(
192 mode="w", encoding="utf-8", dir=path.parent, prefix=f".{path.name}.", delete=False,
193 )
194 try:
195 with staged:
196 if os.name == "posix" and hasattr(os, "fchmod"):
197 os.fchmod(staged.fileno(), 0o600)
198 staged.write(content)
199 _reject_symlink_or_nonregular(path)
200 # On Windows, a reader without delete sharing can briefly block atomic replacement.
201 for retries_left in range(3, -1, -1):
202 try:
203 os.replace(staged.name, path)
204 break
205 except OSError as exc:
206 if (
207 not retries_left
208 or os.name != "nt"
209 or getattr(exc, "winerror", None) != _WINDOWS_SHARING_VIOLATION
210 ):
211 raise
212 time.sleep(0.05)
213 finally:
214 Path(staged.name).unlink(missing_ok=True)
215
216
217 def prepare_private_sqlite_files(path: Path, *, create: bool = False) -> Path:
218 """Set owner-only modes before SQLite can create files from the database mode."""
219 if os.name != "posix":
220 if hasattr(path, "lstat"):
221 _reject_symlink_or_nonregular(path)
222 for suffix in ("-wal", "-shm", "-journal"):
223 _reject_symlink_or_nonregular(Path(f"{path}{suffix}"))
224 return path
225
226 path = _resolve_parent_only(path, allow_root_owner=not create)
227 nofollow = getattr(os, "O_NOFOLLOW", 0)
228 nonblock = getattr(os, "O_NONBLOCK", 0)
229 cloexec = getattr(os, "O_CLOEXEC", 0)
230
231 if create:
232 try:
233 fd = os.open(
234 path,
235 os.O_CREAT | os.O_EXCL | os.O_WRONLY | nofollow | cloexec,
236 0o600,
237 )
238 except FileExistsError:
239 pass
240 except OSError as exc:
241 if exc.errno == errno.ELOOP:
242 raise OSError(errno.ELOOP, f"Refusing to follow symlink for SQLite file: {path}") from exc
243 raise
244 else:
245 try:
246 st = os.fstat(fd)
247 if not stat.S_ISREG(st.st_mode):
248 raise OSError(f"Expected a regular SQLite file: {path}")
249 if stat.S_IMODE(st.st_mode) != 0o600:
250 os.fchmod(fd, 0o600)
251 finally:
252 os.close(fd)
253
254 sidecars = (Path(f"{path}{suffix}") for suffix in ("-wal", "-shm", "-journal"))
255 for candidate in (path, *sidecars):
256 try:
257 fd = os.open(candidate, os.O_RDONLY | nofollow | nonblock | cloexec)
258 except FileNotFoundError:
259 if candidate == path:
260 raise
261 continue
262 except OSError as exc:
263 if exc.errno == errno.ELOOP:
264 raise OSError(errno.ELOOP, f"Refusing to follow symlink for SQLite file: {candidate}") from exc
265 raise
266 try:
267 st = os.fstat(fd)
268 if not stat.S_ISREG(st.st_mode):
269 raise OSError(f"Expected a regular SQLite file: {candidate}")
270 if stat.S_IMODE(st.st_mode) != 0o600:
271 os.fchmod(fd, 0o600)
272 finally:
273 os.close(fd)
274 return path
275
276
277 def write_private_text(path: Path, content: str, *, encoding: str | None = None) -> int:
278 """Write text atomically with owner-only permissions before any bytes on POSIX."""
279 if os.name != "posix":
280 _reject_symlink_or_nonregular(path)
281 return path.write_text(content, encoding=encoding)
282
283 path = _resolve_parent_only(path)
284 stage_flags = (
285 os.O_CREAT
286 | os.O_EXCL
287 | os.O_WRONLY
288 | getattr(os, "O_NOFOLLOW", 0)
289 | getattr(os, "O_NONBLOCK", 0)
290 | getattr(os, "O_CLOEXEC", 0)
291 )
292 stage_path: Path | None = None
293 fd = -1
294 for _ in range(32):
295 candidate = path.parent / f".{path.name}.{secrets.token_hex(8)}.tmp"
296 try:
297 fd = os.open(candidate, stage_flags, 0o600)
298 stage_path = candidate
299 break
300 except FileExistsError:
301 continue
302 if stage_path is None:
303 raise FileExistsError(f"Could not allocate private staging file for {path}")
304
305 try:
306 try:
307 st = os.fstat(fd)
308 if not stat.S_ISREG(st.st_mode):
309 raise OSError(f"Expected a regular private file: {stage_path}")
310 os.fchmod(fd, 0o600)
311 stream = os.fdopen(fd, "w", encoding=encoding)
312 except BaseException:
313 os.close(fd)
314 raise
315 with stream:
316 written = stream.write(content)
317 stream.flush()
318 _reject_symlink_or_nonregular(path)
319 os.replace(stage_path, path)
320 stage_path = None
321 return written
322 finally:
323 if stage_path is not None:
324 stage_path.unlink(missing_ok=True)
325
325 lines PYTHON