probebox 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- probebox/__init__.py +88 -0
- probebox/_acl.py +209 -0
- probebox/_filelock.py +53 -0
- probebox/_net.py +37 -0
- probebox/_safefs.py +713 -0
- probebox/_version.py +14 -0
- probebox/_win32.py +614 -0
- probebox/budget.py +320 -0
- probebox/cli.py +1042 -0
- probebox/compare.py +568 -0
- probebox/config.py +387 -0
- probebox/contracts.py +575 -0
- probebox/discover/__init__.py +1 -0
- probebox/discover/audit.py +937 -0
- probebox/discover/configs.py +267 -0
- probebox/discover/cross_asset.py +223 -0
- probebox/discover/instructions.py +139 -0
- probebox/discover/probe.py +464 -0
- probebox/discover/render.py +298 -0
- probebox/discover/sanitize.py +587 -0
- probebox/discover/servers.py +334 -0
- probebox/discover/sources.py +428 -0
- probebox/fingerprints.py +297 -0
- probebox/hooks.py +288 -0
- probebox/html_report.py +510 -0
- probebox/init_config.py +789 -0
- probebox/probes/__init__.py +1 -0
- probebox/probes/attack_server.py +367 -0
- probebox/probes/constants.py +64 -0
- probebox/probes/mcp/__init__.py +84 -0
- probebox/probes/mcp/__main__.py +6 -0
- probebox/probes/mcp/faults.py +380 -0
- probebox/probes/mcp/policy.py +155 -0
- probebox/probes/mcp/proxy.py +2030 -0
- probebox/probes/mcp/proxy_policy.py +856 -0
- probebox/probes/mcp/runtime.py +167 -0
- probebox/probes/mcp/server.py +422 -0
- probebox/probes/mcp/tools.py +500 -0
- probebox/probes/probe_state.py +719 -0
- probebox/probes/sandbox.py +84 -0
- probebox/reporting.py +673 -0
- probebox/runner.py +1684 -0
- probebox/sarif.py +318 -0
- probebox/scenarios/__init__.py +1 -0
- probebox/scenarios/evaluator.py +771 -0
- probebox/scenarios/schema.py +712 -0
- probebox/scenarios/suite.yaml +1273 -0
- probebox/skills/__init__.py +1 -0
- probebox/skills/agent_runtime.py +187 -0
- probebox/skills/audit.py +284 -0
- probebox/skills/dynamic.py +971 -0
- probebox/skills/fences.py +103 -0
- probebox/skills/inputs.py +154 -0
- probebox/skills/model_worker.py +54 -0
- probebox/skills/skill_rules.yaml +15 -0
- probebox/standards.py +87 -0
- probebox/strategies/__init__.py +21 -0
- probebox/strategies/candidates.py +98 -0
- probebox/strategies/replay.py +83 -0
- probebox/strategies/transforms.py +230 -0
- probebox/targets/__init__.py +14 -0
- probebox/targets/_python_worker.py +473 -0
- probebox/targets/base.py +192 -0
- probebox/targets/cli_target.py +577 -0
- probebox/targets/http_target.py +964 -0
- probebox/targets/python_target.py +210 -0
- probebox/telemetry.py +879 -0
- probebox/utils.py +340 -0
- probebox-1.0.0.dist-info/METADATA +437 -0
- probebox-1.0.0.dist-info/RECORD +73 -0
- probebox-1.0.0.dist-info/WHEEL +4 -0
- probebox-1.0.0.dist-info/entry_points.txt +2 -0
- probebox-1.0.0.dist-info/licenses/LICENSE +21 -0
probebox/_safefs.py
ADDED
|
@@ -0,0 +1,713 @@
|
|
|
1
|
+
"""Bounded access to local files that never follows a link and reads through verified handles.
|
|
2
|
+
|
|
3
|
+
Nothing is concluded from a path alone. A file is read only from a handle that is itself a
|
|
4
|
+
regular file, reached without traversing a symbolic link, a junction or any other reparse
|
|
5
|
+
point, so an entry swapped between listing and reading cannot redirect the read. Untrusted
|
|
6
|
+
input must also have a single name: a hard link is refused. POSIX opens each component with
|
|
7
|
+
``O_NOFOLLOW`` relative to its parent and works through that descriptor from then on; Windows
|
|
8
|
+
opens with ``FILE_FLAG_OPEN_REPARSE_POINT`` and checks, through the handle, the object's
|
|
9
|
+
attributes and its true path.
|
|
10
|
+
|
|
11
|
+
An opened directory is kept and used for everything done below it. Closing it and reopening
|
|
12
|
+
the same path later would prove nothing about what the second open reached.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import ctypes
|
|
18
|
+
import errno
|
|
19
|
+
import os
|
|
20
|
+
import stat
|
|
21
|
+
import sys
|
|
22
|
+
import weakref
|
|
23
|
+
from collections.abc import Iterator
|
|
24
|
+
from typing import NamedTuple
|
|
25
|
+
|
|
26
|
+
from probebox._acl import (
|
|
27
|
+
ADMINISTRATORS,
|
|
28
|
+
CREATOR_OWNER,
|
|
29
|
+
OWNER_RIGHTS,
|
|
30
|
+
PRINCIPAL_NAMES,
|
|
31
|
+
SYSTEM,
|
|
32
|
+
Ace,
|
|
33
|
+
AclError,
|
|
34
|
+
parse_acl,
|
|
35
|
+
parse_sid,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
if os.name == "nt":
|
|
39
|
+
from probebox import _win32
|
|
40
|
+
|
|
41
|
+
FILE = "file"
|
|
42
|
+
DIR = "dir"
|
|
43
|
+
LINK = "link"
|
|
44
|
+
OTHER = "other"
|
|
45
|
+
ANY_SIZE = 2**63 - 1
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class SafeFsError(ValueError):
|
|
49
|
+
"""An object was refused before any of its content was read.
|
|
50
|
+
|
|
51
|
+
``reason`` is a fixed word for callers to branch on: ``missing``, ``link``, ``escape``
|
|
52
|
+
(reached somewhere other than where it was asked for), ``special`` (not a regular file or a
|
|
53
|
+
directory), ``not-a-directory``, ``limit``, ``unverifiable`` (it is there but could not be
|
|
54
|
+
examined), ``unsafe-name``, ``unavailable``. The message is for people.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
def __init__(self, message: str, reason: str = "special", *, withdrawn: bool = False):
|
|
58
|
+
super().__init__(message)
|
|
59
|
+
self.reason = reason
|
|
60
|
+
self.withdrawn = withdrawn
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class Ownership(NamedTuple):
|
|
64
|
+
"""Who owns an object, and whether accounts other than its owner may write to it."""
|
|
65
|
+
|
|
66
|
+
owner: str
|
|
67
|
+
shared_writable: bool
|
|
68
|
+
detail: str = ""
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _kind_from_mode(mode: int) -> str:
|
|
72
|
+
if stat.S_ISLNK(mode):
|
|
73
|
+
return LINK
|
|
74
|
+
if stat.S_ISDIR(mode):
|
|
75
|
+
return DIR
|
|
76
|
+
return FILE if stat.S_ISREG(mode) else OTHER
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _is_reparse_point(info: os.stat_result) -> bool:
|
|
80
|
+
return bool(getattr(info, "st_reparse_tag", 0) or getattr(info, "st_file_attributes", 0) & 0x400)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _check_file(size: int, links: int, maximum: int, kind_error: str, size_error: str, single_link: bool) -> None:
|
|
84
|
+
"""A handle is accepted only as a regular file within the byte limit and, by default, with
|
|
85
|
+
one name. ``single_link`` is dropped only for a file that another name cannot make less
|
|
86
|
+
trustworthy, such as one published under a second name for a moment."""
|
|
87
|
+
if links < 1:
|
|
88
|
+
raise SafeFsError(_WITHDRAWN_FILE, "missing", withdrawn=True)
|
|
89
|
+
if single_link and links != 1:
|
|
90
|
+
raise SafeFsError(kind_error, "special")
|
|
91
|
+
if size > maximum:
|
|
92
|
+
raise SafeFsError(size_error, "limit")
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _check_name(name: str) -> None:
|
|
96
|
+
"""A single component: nothing that could name an object outside the directory."""
|
|
97
|
+
if (not isinstance(name, str) or not name or name in (".", "..") or "/" in name or "\\" in name
|
|
98
|
+
or "\0" in name):
|
|
99
|
+
raise SafeFsError("unsafe name", "unsafe-name")
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _is_gone(error: OSError) -> bool:
|
|
103
|
+
return isinstance(error, FileNotFoundError) or getattr(error, "winerror", None) == 2
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class _Opened:
|
|
107
|
+
def __enter__(self):
|
|
108
|
+
return self
|
|
109
|
+
|
|
110
|
+
def __exit__(self, *_: object) -> None:
|
|
111
|
+
self.close()
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
if os.name != "nt":
|
|
115
|
+
|
|
116
|
+
def _posix_extended_acl_reason(fd: int) -> str:
|
|
117
|
+
"""Fail closed if an open POSIX directory carries an extended ACL that may grant writes."""
|
|
118
|
+
if sys.platform == "darwin":
|
|
119
|
+
try:
|
|
120
|
+
libc = ctypes.CDLL(None, use_errno=True)
|
|
121
|
+
libc.acl_get_fd_np.argtypes = [ctypes.c_int, ctypes.c_int]
|
|
122
|
+
libc.acl_get_fd_np.restype = ctypes.c_void_p
|
|
123
|
+
libc.acl_free.argtypes = [ctypes.c_void_p]
|
|
124
|
+
libc.acl_free.restype = ctypes.c_int
|
|
125
|
+
ctypes.set_errno(0)
|
|
126
|
+
acl = libc.acl_get_fd_np(fd, 0x100) # ACL_TYPE_EXTENDED
|
|
127
|
+
if acl:
|
|
128
|
+
libc.acl_free(acl)
|
|
129
|
+
return "extended macOS ACL present"
|
|
130
|
+
err = ctypes.get_errno()
|
|
131
|
+
if err in (0, errno.ENOENT, errno.ENOTSUP, getattr(errno, "EOPNOTSUPP", errno.ENOTSUP)):
|
|
132
|
+
return ""
|
|
133
|
+
return f"extended ACL could not be verified (errno {err})"
|
|
134
|
+
except (OSError, AttributeError):
|
|
135
|
+
return ""
|
|
136
|
+
if hasattr(os, "listxattr"):
|
|
137
|
+
try:
|
|
138
|
+
attrs = os.listxattr(fd)
|
|
139
|
+
except OSError as error:
|
|
140
|
+
if error.errno in (errno.ENOTSUP, getattr(errno, "EOPNOTSUPP", errno.ENOTSUP), errno.ENOSYS, errno.ENODATA if hasattr(errno, "ENODATA") else -1):
|
|
141
|
+
return ""
|
|
142
|
+
return f"extended ACL could not be verified ({type(error).__name__})"
|
|
143
|
+
if "system.posix_acl_access" in attrs:
|
|
144
|
+
return "extended POSIX ACL present"
|
|
145
|
+
return ""
|
|
146
|
+
|
|
147
|
+
class OpenedFile(_Opened):
|
|
148
|
+
"""A regular file held open by descriptor, never reached through a link."""
|
|
149
|
+
|
|
150
|
+
def __init__(self, fd: int):
|
|
151
|
+
self.fd = fd
|
|
152
|
+
self._stream = None
|
|
153
|
+
self._single_link = True
|
|
154
|
+
|
|
155
|
+
@classmethod
|
|
156
|
+
def _take(cls, fd: int, *, maximum: int, kind_error: str, size_error: str, single_link: bool) -> OpenedFile:
|
|
157
|
+
try:
|
|
158
|
+
info = os.fstat(fd)
|
|
159
|
+
if not stat.S_ISREG(info.st_mode):
|
|
160
|
+
raise SafeFsError(kind_error, "special")
|
|
161
|
+
_check_file(info.st_size, info.st_nlink, maximum, kind_error, size_error, single_link)
|
|
162
|
+
child = cls(fd)
|
|
163
|
+
child._single_link = single_link
|
|
164
|
+
return child
|
|
165
|
+
except BaseException:
|
|
166
|
+
os.close(fd)
|
|
167
|
+
raise
|
|
168
|
+
|
|
169
|
+
@classmethod
|
|
170
|
+
def _open_fd(cls, name: str, directory_fd: int | None) -> int:
|
|
171
|
+
flags = os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC
|
|
172
|
+
try:
|
|
173
|
+
return os.open(name, flags) if directory_fd is None else os.open(name, flags, dir_fd=directory_fd)
|
|
174
|
+
except FileNotFoundError as error:
|
|
175
|
+
raise SafeFsError("no such file", "missing") from error
|
|
176
|
+
except OSError as error:
|
|
177
|
+
if error.errno == errno.ELOOP:
|
|
178
|
+
raise SafeFsError("linked or special file", "link") from error
|
|
179
|
+
raise
|
|
180
|
+
|
|
181
|
+
@classmethod
|
|
182
|
+
def open(cls, path, *, maximum: int, kind_error: str, size_error: str) -> OpenedFile:
|
|
183
|
+
if not hasattr(os, "O_NOFOLLOW"):
|
|
184
|
+
raise SafeFsError("safe filesystem reader unavailable on this platform", "unavailable")
|
|
185
|
+
return cls._take(cls._open_fd(os.fspath(path), None), maximum=maximum, kind_error=kind_error,
|
|
186
|
+
size_error=size_error, single_link=True)
|
|
187
|
+
|
|
188
|
+
def read(self, *, maximum: int) -> bytes:
|
|
189
|
+
info = os.fstat(self.fd)
|
|
190
|
+
if not stat.S_ISREG(info.st_mode):
|
|
191
|
+
raise SafeFsError("linked or special file", "special")
|
|
192
|
+
_check_file(info.st_size, info.st_nlink, maximum, "linked or special file", "file byte limit exceeded",
|
|
193
|
+
self._single_link)
|
|
194
|
+
if self._stream is None:
|
|
195
|
+
self._stream = os.fdopen(self.fd, "rb")
|
|
196
|
+
data = self._stream.read(maximum + 1)
|
|
197
|
+
if len(data) > maximum:
|
|
198
|
+
raise SafeFsError("file byte limit exceeded", "limit")
|
|
199
|
+
return data
|
|
200
|
+
|
|
201
|
+
def ownership(self) -> Ownership:
|
|
202
|
+
return Ownership(str(os.fstat(self.fd).st_uid), False)
|
|
203
|
+
|
|
204
|
+
def close(self) -> None:
|
|
205
|
+
if self._stream is not None:
|
|
206
|
+
self._stream, stream = None, self._stream
|
|
207
|
+
stream.close()
|
|
208
|
+
else:
|
|
209
|
+
os.close(self.fd)
|
|
210
|
+
|
|
211
|
+
class OpenedDir(_Opened):
|
|
212
|
+
"""A directory held open by descriptor; children are opened relative to it."""
|
|
213
|
+
|
|
214
|
+
def __init__(self, fd: int, location: str):
|
|
215
|
+
self.fd = fd
|
|
216
|
+
self.location = location
|
|
217
|
+
info = os.fstat(fd)
|
|
218
|
+
self.identity = (info.st_dev, info.st_ino)
|
|
219
|
+
|
|
220
|
+
@classmethod
|
|
221
|
+
def open(cls, path) -> OpenedDir:
|
|
222
|
+
if not hasattr(os, "O_NOFOLLOW") or os.scandir not in os.supports_fd:
|
|
223
|
+
raise SafeFsError("safe filesystem reader unavailable on this platform", "unavailable")
|
|
224
|
+
try:
|
|
225
|
+
fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC)
|
|
226
|
+
except OSError as error:
|
|
227
|
+
if error.errno in (errno.ELOOP, errno.ENOTDIR):
|
|
228
|
+
raise SafeFsError("expected a directory", "link" if error.errno == errno.ELOOP else "not-a-directory") from error
|
|
229
|
+
raise
|
|
230
|
+
try:
|
|
231
|
+
return cls(fd, os.path.abspath(os.fspath(path)))
|
|
232
|
+
except BaseException:
|
|
233
|
+
os.close(fd)
|
|
234
|
+
raise
|
|
235
|
+
|
|
236
|
+
def entries(self) -> Iterator[tuple[str, str]]:
|
|
237
|
+
with os.scandir(self.fd) as listing:
|
|
238
|
+
for entry in listing:
|
|
239
|
+
try:
|
|
240
|
+
mode = entry.stat(follow_symlinks=False).st_mode
|
|
241
|
+
except FileNotFoundError:
|
|
242
|
+
continue # Gone between listing and examining: nothing is reported for it.
|
|
243
|
+
yield entry.name, _kind_from_mode(mode)
|
|
244
|
+
|
|
245
|
+
def open_child_dir(self, name: str, *, spelled: bool = False) -> OpenedDir:
|
|
246
|
+
_check_name(name)
|
|
247
|
+
try:
|
|
248
|
+
fd = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC, dir_fd=self.fd)
|
|
249
|
+
except FileNotFoundError as error:
|
|
250
|
+
raise SafeFsError("no such directory", "missing") from error
|
|
251
|
+
except OSError as error:
|
|
252
|
+
if error.errno in (errno.ELOOP, errno.ENOTDIR):
|
|
253
|
+
# Some systems say "not a directory" of a link where none may be followed.
|
|
254
|
+
try:
|
|
255
|
+
kind = _kind_from_mode(os.stat(name, dir_fd=self.fd, follow_symlinks=False).st_mode)
|
|
256
|
+
except OSError:
|
|
257
|
+
raise SafeFsError("not a directory", "not-a-directory") from error
|
|
258
|
+
raise SafeFsError("links and special files are not accepted" if kind == LINK else "not a directory",
|
|
259
|
+
"link" if kind == LINK else "not-a-directory") from error
|
|
260
|
+
raise
|
|
261
|
+
try:
|
|
262
|
+
return OpenedDir(fd, os.path.join(self.location, name))
|
|
263
|
+
except BaseException:
|
|
264
|
+
os.close(fd)
|
|
265
|
+
raise
|
|
266
|
+
|
|
267
|
+
def open_file(self, name: str, *, maximum: int = ANY_SIZE, size_error: str = "file byte limit exceeded",
|
|
268
|
+
single_link: bool = True) -> OpenedFile:
|
|
269
|
+
_check_name(name)
|
|
270
|
+
return OpenedFile._take(OpenedFile._open_fd(name, self.fd), maximum=maximum,
|
|
271
|
+
kind_error="linked or special file", size_error=size_error, single_link=single_link)
|
|
272
|
+
|
|
273
|
+
def read_file(self, name: str, *, maximum: int, single_link: bool = True) -> bytes:
|
|
274
|
+
with self.open_file(name, maximum=maximum, single_link=single_link) as child:
|
|
275
|
+
return child.read(maximum=maximum)
|
|
276
|
+
|
|
277
|
+
def ownership(self) -> Ownership:
|
|
278
|
+
info = os.fstat(self.fd)
|
|
279
|
+
reasons: list[str] = []
|
|
280
|
+
if info.st_mode & stat.S_IWOTH:
|
|
281
|
+
reasons.append("world-writable (o+w)")
|
|
282
|
+
if info.st_mode & stat.S_IWGRP:
|
|
283
|
+
reasons.append("group-writable (g+w)")
|
|
284
|
+
acl_reason = _posix_extended_acl_reason(self.fd)
|
|
285
|
+
if acl_reason:
|
|
286
|
+
reasons.append(acl_reason)
|
|
287
|
+
return Ownership(str(info.st_uid), bool(reasons), "; ".join(reasons))
|
|
288
|
+
|
|
289
|
+
def create_file(self, name: str):
|
|
290
|
+
"""Create one new file, exclusively; a file of that name must not already exist."""
|
|
291
|
+
_check_name(name)
|
|
292
|
+
fd = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, 0o600, dir_fd=self.fd)
|
|
293
|
+
return os.fdopen(fd, "wb")
|
|
294
|
+
|
|
295
|
+
def publish(self, source: str, destination: str) -> None:
|
|
296
|
+
"""Give ``source`` the second name ``destination``; fails if ``destination`` exists."""
|
|
297
|
+
_check_name(source)
|
|
298
|
+
_check_name(destination)
|
|
299
|
+
os.link(source, destination, src_dir_fd=self.fd, dst_dir_fd=self.fd, follow_symlinks=False)
|
|
300
|
+
|
|
301
|
+
def replace_file(self, source: str, destination: str) -> None:
|
|
302
|
+
"""Atomically replace ``destination`` with ``source`` inside this directory."""
|
|
303
|
+
_check_name(source)
|
|
304
|
+
_check_name(destination)
|
|
305
|
+
os.replace(source, destination, src_dir_fd=self.fd, dst_dir_fd=self.fd)
|
|
306
|
+
|
|
307
|
+
def remove(self, name: str) -> None:
|
|
308
|
+
_check_name(name)
|
|
309
|
+
os.unlink(name, dir_fd=self.fd)
|
|
310
|
+
|
|
311
|
+
def close(self) -> None:
|
|
312
|
+
os.close(self.fd)
|
|
313
|
+
|
|
314
|
+
else:
|
|
315
|
+
|
|
316
|
+
class OpenedFile(_Opened):
|
|
317
|
+
"""A regular file held open by handle, never reached through a link."""
|
|
318
|
+
|
|
319
|
+
def __init__(self, handle: int, info: _win32.ObjectInfo):
|
|
320
|
+
self.handle = handle
|
|
321
|
+
self.info = info
|
|
322
|
+
self._single_link = True
|
|
323
|
+
|
|
324
|
+
@classmethod
|
|
325
|
+
def _take(cls, handle: int, info: _win32.ObjectInfo, final: str, *, maximum: int, kind_error: str,
|
|
326
|
+
size_error: str, single_link: bool, expected: str) -> OpenedFile:
|
|
327
|
+
"""Take ownership of an open handle once it has proved to be an acceptable file.
|
|
328
|
+
|
|
329
|
+
``expected`` is the one path the handle is allowed to have: the directory's true path
|
|
330
|
+
plus the entry's name, or the operator's own path. ``final`` is where the handle says
|
|
331
|
+
its object is, read from the handle before anything else was. A handle found under
|
|
332
|
+
another path that still has a name was reached through a link that appeared after the
|
|
333
|
+
entry was listed, so it is not the object that was asked for.
|
|
334
|
+
"""
|
|
335
|
+
try:
|
|
336
|
+
if info.is_link or not info.is_regular_file:
|
|
337
|
+
raise SafeFsError(kind_error, "link" if info.is_link else "special")
|
|
338
|
+
if _withdrawn(expected, final, info):
|
|
339
|
+
raise SafeFsError(_WITHDRAWN_FILE, "missing", withdrawn=True)
|
|
340
|
+
if final != expected:
|
|
341
|
+
raise SafeFsError(kind_error, "escape")
|
|
342
|
+
_check_file(info.size, info.links, maximum, kind_error, size_error, single_link)
|
|
343
|
+
child = cls(handle, info)
|
|
344
|
+
child._single_link = single_link
|
|
345
|
+
return child
|
|
346
|
+
except BaseException:
|
|
347
|
+
_win32.close(handle)
|
|
348
|
+
raise
|
|
349
|
+
|
|
350
|
+
@classmethod
|
|
351
|
+
def open(cls, path, *, maximum: int, kind_error: str, size_error: str) -> OpenedFile:
|
|
352
|
+
_refuse_devices(path)
|
|
353
|
+
handle, info, final = _win32.open_object(path, read=True, security=True)
|
|
354
|
+
# A file named by the operator is accepted wherever its own path leads; what must
|
|
355
|
+
# hold is that it is a regular file reached without a link in its last component.
|
|
356
|
+
return cls._take(handle, info, final, maximum=maximum, kind_error=kind_error, size_error=size_error,
|
|
357
|
+
single_link=True, expected=final)
|
|
358
|
+
|
|
359
|
+
def read(self, *, maximum: int) -> bytes:
|
|
360
|
+
if not self.handle:
|
|
361
|
+
raise SafeFsError("file is no longer open", "special")
|
|
362
|
+
_check_file(self.info.size, self.info.links, maximum, "linked or special file",
|
|
363
|
+
"file byte limit exceeded", self._single_link)
|
|
364
|
+
handle, self.handle = self.handle, 0 # The stream owns the handle from here on.
|
|
365
|
+
data = _win32.read_stream(handle).read(maximum + 1)
|
|
366
|
+
if len(data) > maximum:
|
|
367
|
+
raise SafeFsError("file byte limit exceeded", "limit")
|
|
368
|
+
return data
|
|
369
|
+
|
|
370
|
+
def ownership(self) -> Ownership:
|
|
371
|
+
return Ownership(_acl_owner(self.handle), False)
|
|
372
|
+
|
|
373
|
+
def close(self) -> None:
|
|
374
|
+
if self.handle:
|
|
375
|
+
_win32.close(self.handle)
|
|
376
|
+
self.handle = 0
|
|
377
|
+
|
|
378
|
+
def _close_win_handle(cell: list[int]) -> None:
|
|
379
|
+
if cell and cell[0]:
|
|
380
|
+
handle = cell.pop()
|
|
381
|
+
if handle:
|
|
382
|
+
_win32.close(handle)
|
|
383
|
+
|
|
384
|
+
class OpenedDir(_Opened):
|
|
385
|
+
"""A verified directory held open and pinned against rename or deletion.
|
|
386
|
+
|
|
387
|
+
The directory is opened with ``FILE_LIST_DIRECTORY`` and without ``FILE_SHARE_DELETE``,
|
|
388
|
+
and its handle stays open until ``close()``. While held, Windows refuses any rename or
|
|
389
|
+
removal of this directory or its ancestors, so its verified true path cannot be swapped
|
|
390
|
+
out for another directory underneath subsequent reads, writes, or listings.
|
|
391
|
+
"""
|
|
392
|
+
|
|
393
|
+
def __init__(self, path: str, identity: tuple[int, int], handle: int):
|
|
394
|
+
self.path = path
|
|
395
|
+
self.location = display_path(path)
|
|
396
|
+
self.identity = identity
|
|
397
|
+
self._handle_cell: list[int] = [handle]
|
|
398
|
+
weakref.finalize(self, _close_win_handle, self._handle_cell)
|
|
399
|
+
|
|
400
|
+
def _require_handle(self) -> int:
|
|
401
|
+
if not self._handle_cell or not self._handle_cell[0]:
|
|
402
|
+
raise SafeFsError("directory is no longer open", "unavailable")
|
|
403
|
+
return self._handle_cell[0]
|
|
404
|
+
|
|
405
|
+
@classmethod
|
|
406
|
+
def open(cls, path) -> OpenedDir:
|
|
407
|
+
_refuse_devices(path)
|
|
408
|
+
if is_link(path):
|
|
409
|
+
raise SafeFsError("links and special files are not accepted", "link")
|
|
410
|
+
if not (os.path.isdir(path) or os.path.isfile(path)):
|
|
411
|
+
raise SafeFsError("expected a directory", "special")
|
|
412
|
+
handle, info, final = _win32.open_object(path, security=True, pin_dir=True)
|
|
413
|
+
try:
|
|
414
|
+
if info.is_link or not info.is_directory:
|
|
415
|
+
raise SafeFsError("expected a directory", "link" if info.is_link else "not-a-directory")
|
|
416
|
+
return cls(final, info.identity, handle)
|
|
417
|
+
except BaseException:
|
|
418
|
+
_win32.close(handle)
|
|
419
|
+
raise
|
|
420
|
+
|
|
421
|
+
def entries(self) -> Iterator[tuple[str, str]]:
|
|
422
|
+
"""Every name in the directory with what it is, as far as each was proved.
|
|
423
|
+
|
|
424
|
+
Because this directory's handle is held open without ``FILE_SHARE_DELETE``, the
|
|
425
|
+
directory itself cannot be replaced while listed. Child files still share delete so
|
|
426
|
+
concurrent processes using this directory can operate normally: an entry removed or
|
|
427
|
+
renamed inside this directory while being opened is skipped; anything found outside
|
|
428
|
+
this directory's pinned true path is refused as an escape.
|
|
429
|
+
"""
|
|
430
|
+
self._require_handle()
|
|
431
|
+
with os.scandir(self.path) as listing:
|
|
432
|
+
for entry in listing:
|
|
433
|
+
self._require_handle()
|
|
434
|
+
expected = _below(self.path, entry.name)
|
|
435
|
+
try:
|
|
436
|
+
handle, info, final = _win32.open_object(expected)
|
|
437
|
+
except FileNotFoundError:
|
|
438
|
+
continue # Gone between listing and opening: nothing is reported for it.
|
|
439
|
+
except OSError as error:
|
|
440
|
+
raise SafeFsError("an entry could not be examined", "unverifiable") from error
|
|
441
|
+
_win32.close(handle)
|
|
442
|
+
if _withdrawn(expected, final, info):
|
|
443
|
+
continue
|
|
444
|
+
if final != expected:
|
|
445
|
+
raise SafeFsError("links and special files are not accepted", "escape")
|
|
446
|
+
kind = LINK if info.is_link else DIR if info.is_directory else FILE if info.is_regular_file else OTHER
|
|
447
|
+
yield entry.name, kind
|
|
448
|
+
|
|
449
|
+
def open_child_dir(self, name: str, *, spelled: bool = False) -> OpenedDir:
|
|
450
|
+
"""Open a direct child directory and keep it pinned until closed.
|
|
451
|
+
|
|
452
|
+
``spelled`` accepts the child under the name the disk gives it rather than the one
|
|
453
|
+
asked for, for a directory the operator named: case and short names are spellings.
|
|
454
|
+
"""
|
|
455
|
+
self._require_handle()
|
|
456
|
+
_check_name(name)
|
|
457
|
+
expected = _below(self.path, name)
|
|
458
|
+
try:
|
|
459
|
+
handle, info, final = _win32.open_object(expected, security=True, pin_dir=True)
|
|
460
|
+
except FileNotFoundError as error:
|
|
461
|
+
raise SafeFsError("no such directory", "missing") from error
|
|
462
|
+
try:
|
|
463
|
+
if info.is_link:
|
|
464
|
+
raise SafeFsError("links and special files are not accepted", "link")
|
|
465
|
+
if not info.is_directory:
|
|
466
|
+
raise SafeFsError("not a directory", "not-a-directory")
|
|
467
|
+
if _withdrawn(expected, final, info, renamed=not spelled):
|
|
468
|
+
raise SafeFsError(_WITHDRAWN_DIRECTORY, "missing", withdrawn=True)
|
|
469
|
+
if final != expected and not (spelled and _directly_inside(self.path, final)):
|
|
470
|
+
raise SafeFsError("links and special files are not accepted", "escape")
|
|
471
|
+
return OpenedDir(final, info.identity, handle)
|
|
472
|
+
except BaseException:
|
|
473
|
+
_win32.close(handle)
|
|
474
|
+
raise
|
|
475
|
+
|
|
476
|
+
def open_file(self, name: str, *, maximum: int = ANY_SIZE, size_error: str = "file byte limit exceeded",
|
|
477
|
+
single_link: bool = True) -> OpenedFile:
|
|
478
|
+
self._require_handle()
|
|
479
|
+
_check_name(name)
|
|
480
|
+
expected = _below(self.path, name)
|
|
481
|
+
try:
|
|
482
|
+
handle, info, final = _win32.open_object(expected, read=True, security=True)
|
|
483
|
+
except FileNotFoundError as error:
|
|
484
|
+
raise SafeFsError("no such file", "missing") from error
|
|
485
|
+
return OpenedFile._take(handle, info, final, maximum=maximum, kind_error="linked or special file",
|
|
486
|
+
size_error=size_error, single_link=single_link, expected=expected)
|
|
487
|
+
|
|
488
|
+
def read_file(self, name: str, *, maximum: int, single_link: bool = True) -> bytes:
|
|
489
|
+
with self.open_file(name, maximum=maximum, single_link=single_link) as child:
|
|
490
|
+
return child.read(maximum=maximum)
|
|
491
|
+
|
|
492
|
+
def ownership(self) -> Ownership:
|
|
493
|
+
return _ownership_from(self._require_handle())
|
|
494
|
+
|
|
495
|
+
def create_file(self, name: str) -> object:
|
|
496
|
+
"""Create one new file, exclusively; a file of that name must not already exist."""
|
|
497
|
+
self._require_handle()
|
|
498
|
+
_check_name(name)
|
|
499
|
+
# Under the extended path form this names a file in this pinned directory or fails; a
|
|
500
|
+
# device or a link of the same name makes it fail, never opens something else.
|
|
501
|
+
descriptor = os.open(_below(self.path, name), os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_BINARY, 0o600)
|
|
502
|
+
try:
|
|
503
|
+
return os.fdopen(descriptor, "wb")
|
|
504
|
+
except BaseException:
|
|
505
|
+
os.close(descriptor)
|
|
506
|
+
raise
|
|
507
|
+
|
|
508
|
+
def publish(self, source: str, destination: str) -> None:
|
|
509
|
+
"""Give ``source`` the name ``destination``; fails if ``destination`` exists.
|
|
510
|
+
|
|
511
|
+
On Windows a rename never replaces an existing file, which is the same exclusive
|
|
512
|
+
claim a hard link makes on POSIX.
|
|
513
|
+
"""
|
|
514
|
+
self._require_handle()
|
|
515
|
+
_check_name(source)
|
|
516
|
+
_check_name(destination)
|
|
517
|
+
os.rename(_below(self.path, source), _below(self.path, destination))
|
|
518
|
+
|
|
519
|
+
def replace_file(self, source: str, destination: str) -> None:
|
|
520
|
+
"""Atomically replace ``destination`` with ``source`` inside this pinned directory."""
|
|
521
|
+
self._require_handle()
|
|
522
|
+
_check_name(source)
|
|
523
|
+
_check_name(destination)
|
|
524
|
+
os.replace(_below(self.path, source), _below(self.path, destination))
|
|
525
|
+
|
|
526
|
+
def remove(self, name: str) -> None:
|
|
527
|
+
self._require_handle()
|
|
528
|
+
_check_name(name)
|
|
529
|
+
os.unlink(_below(self.path, name))
|
|
530
|
+
|
|
531
|
+
def close(self) -> None:
|
|
532
|
+
_close_win_handle(self._handle_cell)
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
def _below(parent: str, name: str) -> str:
|
|
536
|
+
"""``name`` inside ``parent``, for a true path in the extended-length form. The root of a
|
|
537
|
+
drive already ends in a separator, and every other directory does not."""
|
|
538
|
+
return parent + name if parent.endswith("\\") else parent + "\\" + name
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
def _directly_inside(parent: str, path: str) -> bool:
|
|
542
|
+
"""Whether the true path ``path`` is that of something directly inside ``parent``."""
|
|
543
|
+
return path.startswith(parent if parent.endswith("\\") else parent + "\\")
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
_WITHDRAWN_FILE = "the file was removed or renamed while it was being opened"
|
|
547
|
+
_WITHDRAWN_DIRECTORY = "the directory was removed or renamed while it was being opened"
|
|
548
|
+
|
|
549
|
+
|
|
550
|
+
def _withdrawn(expected: str, final: str, info: _win32.ObjectInfo, *, renamed: bool = True) -> bool:
|
|
551
|
+
"""Whether the object opened as ``expected`` no longer has that name.
|
|
552
|
+
|
|
553
|
+
A listing never keeps the owner's other processes out of the directory, and this handle
|
|
554
|
+
shares the object with all of them, so it may be removed or renamed at any moment. A removed
|
|
555
|
+
object goes on existing for the handle that is open on it, with no name left at all; one
|
|
556
|
+
renamed inside its own directory is found under its new name there. In both cases the name
|
|
557
|
+
it was listed by is no longer its, and nothing may be reported under that name.
|
|
558
|
+
|
|
559
|
+
An object found under any other path still has a name, and one this directory did not give
|
|
560
|
+
it: that is what a link in the way leaves, and it is not this case. ``renamed`` is off where
|
|
561
|
+
another name in this directory is expected of a good object, as for a directory the operator
|
|
562
|
+
named in a spelling the disk does not use.
|
|
563
|
+
"""
|
|
564
|
+
return info.links == 0 or (renamed and final != expected and _same_directory(expected, final))
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
def _same_directory(one: str, other: str) -> bool:
|
|
568
|
+
"""Whether two true paths are names of objects directly inside one directory."""
|
|
569
|
+
return one.rsplit("\\", 1)[0] == other.rsplit("\\", 1)[0]
|
|
570
|
+
|
|
571
|
+
|
|
572
|
+
def _acl_owner(handle: int) -> str:
|
|
573
|
+
owner, _ = _win32.security_bytes(handle)
|
|
574
|
+
return parse_sid(owner)
|
|
575
|
+
|
|
576
|
+
|
|
577
|
+
def untrusted_writers(aces: list[Ace], trusted: set[str]) -> tuple[list[str], list[int]]:
|
|
578
|
+
"""Which write grants in an access list go to an account or group that is not trusted, and
|
|
579
|
+
which entries could not be read and might be one.
|
|
580
|
+
|
|
581
|
+
Trusted are the owner, SYSTEM, the Administrators group, the placeholders that resolve to
|
|
582
|
+
whoever creates or owns the object (which is the owner again), and this logon session. A grant
|
|
583
|
+
to anyone else, and any entry whose type cannot be read, makes the object shared.
|
|
584
|
+
"""
|
|
585
|
+
others: list[str] = []
|
|
586
|
+
for ace in aces:
|
|
587
|
+
if not ace.grants_write:
|
|
588
|
+
continue
|
|
589
|
+
if ace.sid is None:
|
|
590
|
+
label = "an unreadable write grant"
|
|
591
|
+
elif ace.sid in trusted:
|
|
592
|
+
continue
|
|
593
|
+
else:
|
|
594
|
+
label = PRINCIPAL_NAMES.get(ace.sid, "another account or group")
|
|
595
|
+
if label not in others:
|
|
596
|
+
others.append(label)
|
|
597
|
+
unreadable = sorted({ace.type for ace in aces if ace.unparsed and not ace.grants_write})
|
|
598
|
+
return others, unreadable
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
def _ownership_from(handle: int) -> Ownership:
|
|
602
|
+
"""Who owns an open object, and whether anyone but its owner may write to it.
|
|
603
|
+
|
|
604
|
+
Only the owner, SYSTEM, the Administrators group, the creator placeholders and this exact
|
|
605
|
+
process's own logon session SID are trusted with write access. Any other trustee (including
|
|
606
|
+
another account's logon session) or unreadable entry makes the object shared.
|
|
607
|
+
"""
|
|
608
|
+
owner_bytes, acl_bytes = _win32.security_bytes(handle)
|
|
609
|
+
user, _ = _win32.current_user()
|
|
610
|
+
trusted = {user, SYSTEM, ADMINISTRATORS, CREATOR_OWNER, OWNER_RIGHTS}
|
|
611
|
+
logon_sid = _win32.current_logon_sid()
|
|
612
|
+
if logon_sid:
|
|
613
|
+
trusted.add(logon_sid)
|
|
614
|
+
try:
|
|
615
|
+
owner = parse_sid(owner_bytes)
|
|
616
|
+
if acl_bytes is None:
|
|
617
|
+
return Ownership(owner, True, "no access list: everyone has full access")
|
|
618
|
+
aces = parse_acl(acl_bytes)
|
|
619
|
+
except AclError as error:
|
|
620
|
+
return Ownership(owner_bytes.hex(), True, f"security information could not be read: {error}")
|
|
621
|
+
others, unreadable = untrusted_writers(aces, trusted)
|
|
622
|
+
detail = "; ".join([*(f"writable by {other}" for other in others),
|
|
623
|
+
*(f"entry of unknown type 0x{kind:X}" for kind in unreadable)])
|
|
624
|
+
return Ownership(owner, bool(others or unreadable), detail)
|
|
625
|
+
|
|
626
|
+
|
|
627
|
+
_DEVICE_PREFIXES = ("\\\\?\\GLOBALROOT", "\\\\.\\", "\\??\\")
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
def _refuse_devices(path) -> None:
|
|
631
|
+
"""The device namespaces are never input, whatever a caller assembled."""
|
|
632
|
+
text = os.fspath(path) if not isinstance(path, bytes) else os.fsdecode(path)
|
|
633
|
+
if text.startswith(_DEVICE_PREFIXES):
|
|
634
|
+
raise SafeFsError("a device is not a file", "special")
|
|
635
|
+
|
|
636
|
+
|
|
637
|
+
def open_path(path, *, file_maximum: int, file_kind_error: str, file_size_error: str):
|
|
638
|
+
"""Open ``path`` without following a link to it: a verified directory, or a regular file.
|
|
639
|
+
|
|
640
|
+
Nothing is opened before its kind is known from the path's own record, so a device or a
|
|
641
|
+
special file is refused without being opened. An open file says nothing about what it holds;
|
|
642
|
+
callers decide by suffix whether it is input they accept.
|
|
643
|
+
"""
|
|
644
|
+
if os.name != "nt":
|
|
645
|
+
mode = os.lstat(path).st_mode
|
|
646
|
+
if stat.S_ISDIR(mode):
|
|
647
|
+
return OpenedDir.open(path)
|
|
648
|
+
if not stat.S_ISREG(mode):
|
|
649
|
+
raise SafeFsError(file_kind_error, "link" if stat.S_ISLNK(mode) else "special")
|
|
650
|
+
return OpenedFile.open(path, maximum=file_maximum, kind_error=file_kind_error, size_error=file_size_error)
|
|
651
|
+
info = os.lstat(path)
|
|
652
|
+
if _is_reparse_point(info):
|
|
653
|
+
raise SafeFsError(file_kind_error, "link")
|
|
654
|
+
if stat.S_ISDIR(info.st_mode):
|
|
655
|
+
return OpenedDir.open(path)
|
|
656
|
+
if not stat.S_ISREG(info.st_mode):
|
|
657
|
+
raise SafeFsError(file_kind_error, "special")
|
|
658
|
+
return OpenedFile.open(path, maximum=file_maximum, kind_error=file_kind_error, size_error=file_size_error)
|
|
659
|
+
|
|
660
|
+
|
|
661
|
+
def owned_by_current_account(ownership: Ownership) -> bool:
|
|
662
|
+
"""Whether the current account owns an object, as the platform counts ownership.
|
|
663
|
+
|
|
664
|
+
On Windows an elevated administrator's objects are owned by the Administrators group rather
|
|
665
|
+
than by the administrator's own account. That group, like SYSTEM, is trusted with ownership
|
|
666
|
+
on the machine.
|
|
667
|
+
"""
|
|
668
|
+
if os.name != "nt":
|
|
669
|
+
return ownership.owner == str(os.getuid())
|
|
670
|
+
if ownership.owner in (ADMINISTRATORS, SYSTEM):
|
|
671
|
+
return True
|
|
672
|
+
user, _ = _win32.current_user()
|
|
673
|
+
return ownership.owner == user
|
|
674
|
+
|
|
675
|
+
|
|
676
|
+
def path_identity(path: str | os.PathLike[str]) -> tuple[int, int] | None:
|
|
677
|
+
"""Directory/file identity in the exact same tuple representation as ``OpenedDir.identity``."""
|
|
678
|
+
if os.name == "nt":
|
|
679
|
+
return _win32.path_identity(path)
|
|
680
|
+
try:
|
|
681
|
+
info = os.stat(path)
|
|
682
|
+
except OSError:
|
|
683
|
+
return None
|
|
684
|
+
return info.st_dev, info.st_ino
|
|
685
|
+
|
|
686
|
+
|
|
687
|
+
def normalize_lexical(path: str) -> str:
|
|
688
|
+
"""A path in a comparable form without touching the file system: no link is resolved and no
|
|
689
|
+
share is contacted. Use it for paths that come from configuration files."""
|
|
690
|
+
return os.path.normcase(os.path.normpath(path))
|
|
691
|
+
|
|
692
|
+
|
|
693
|
+
def display_path(path: str | os.PathLike[str]) -> str:
|
|
694
|
+
"""An absolute path in the ordinary form, whatever form it was given in."""
|
|
695
|
+
if os.name != "nt":
|
|
696
|
+
return os.path.abspath(os.fspath(path))
|
|
697
|
+
text = os.path.abspath(os.fspath(path))
|
|
698
|
+
if text.startswith("\\\\?\\UNC\\"):
|
|
699
|
+
return "\\\\" + text[8:]
|
|
700
|
+
if text.startswith("\\\\?\\") and len(text) > 6 and text[5] == ":":
|
|
701
|
+
return text[4:]
|
|
702
|
+
# A volume with no drive letter has no ordinary form; the extended one still names it exactly.
|
|
703
|
+
return text
|
|
704
|
+
|
|
705
|
+
|
|
706
|
+
def is_link(path) -> bool:
|
|
707
|
+
"""True for a symbolic link, a junction or any other reparse point at ``path``."""
|
|
708
|
+
try:
|
|
709
|
+
if os.name == "nt":
|
|
710
|
+
return _is_reparse_point(os.lstat(path))
|
|
711
|
+
return os.path.islink(path)
|
|
712
|
+
except FileNotFoundError:
|
|
713
|
+
return False
|