path-jail 0.2.0__tar.gz → 0.3.0__tar.gz
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.
- {path_jail-0.2.0 → path_jail-0.3.0}/Cargo.lock +25 -25
- {path_jail-0.2.0 → path_jail-0.3.0}/Cargo.toml +4 -4
- {path_jail-0.2.0 → path_jail-0.3.0}/PKG-INFO +46 -21
- {path_jail-0.2.0 → path_jail-0.3.0}/README.md +42 -17
- {path_jail-0.2.0 → path_jail-0.3.0}/pyproject.toml +2 -2
- {path_jail-0.2.0 → path_jail-0.3.0}/python/path_jail/__init__.py +3 -1
- {path_jail-0.2.0 → path_jail-0.3.0}/python/path_jail/__init__.pyi +8 -3
- {path_jail-0.2.0 → path_jail-0.3.0}/src/lib.rs +24 -5
- {path_jail-0.2.0 → path_jail-0.3.0}/tests/test_jail.py +50 -2
- {path_jail-0.2.0 → path_jail-0.3.0}/.github/workflows/ci.yml +0 -0
- {path_jail-0.2.0 → path_jail-0.3.0}/.github/workflows/release.yml +0 -0
- {path_jail-0.2.0 → path_jail-0.3.0}/.gitignore +0 -0
- {path_jail-0.2.0 → path_jail-0.3.0}/LICENSE-APACHE +0 -0
- {path_jail-0.2.0 → path_jail-0.3.0}/LICENSE-MIT +0 -0
- {path_jail-0.2.0 → path_jail-0.3.0}/python/path_jail/py.typed +0 -0
|
@@ -4,15 +4,15 @@ version = 4
|
|
|
4
4
|
|
|
5
5
|
[[package]]
|
|
6
6
|
name = "autocfg"
|
|
7
|
-
version = "1.5.
|
|
7
|
+
version = "1.5.1"
|
|
8
8
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
9
|
-
checksum = "
|
|
9
|
+
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
|
10
10
|
|
|
11
11
|
[[package]]
|
|
12
12
|
name = "cfg-if"
|
|
13
|
-
version = "1.0.
|
|
13
|
+
version = "1.0.5"
|
|
14
14
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
15
|
-
checksum = "
|
|
15
|
+
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
|
16
16
|
|
|
17
17
|
[[package]]
|
|
18
18
|
name = "heck"
|
|
@@ -31,9 +31,9 @@ dependencies = [
|
|
|
31
31
|
|
|
32
32
|
[[package]]
|
|
33
33
|
name = "libc"
|
|
34
|
-
version = "0.2.
|
|
34
|
+
version = "0.2.190"
|
|
35
35
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
36
|
-
checksum = "
|
|
36
|
+
checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78"
|
|
37
37
|
|
|
38
38
|
[[package]]
|
|
39
39
|
name = "memoffset"
|
|
@@ -46,19 +46,19 @@ dependencies = [
|
|
|
46
46
|
|
|
47
47
|
[[package]]
|
|
48
48
|
name = "once_cell"
|
|
49
|
-
version = "1.21.
|
|
49
|
+
version = "1.21.4"
|
|
50
50
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
51
|
-
checksum = "
|
|
51
|
+
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
|
52
52
|
|
|
53
53
|
[[package]]
|
|
54
54
|
name = "path_jail"
|
|
55
|
-
version = "0.
|
|
55
|
+
version = "0.5.0"
|
|
56
56
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
57
|
-
checksum = "
|
|
57
|
+
checksum = "90ffcdca91ae4938ba61a95df85ce23c14ae81f8a70f69ca94784e6ea320d8a8"
|
|
58
58
|
|
|
59
59
|
[[package]]
|
|
60
60
|
name = "path_jail_py"
|
|
61
|
-
version = "0.
|
|
61
|
+
version = "0.3.0"
|
|
62
62
|
dependencies = [
|
|
63
63
|
"path_jail",
|
|
64
64
|
"pyo3",
|
|
@@ -66,15 +66,15 @@ dependencies = [
|
|
|
66
66
|
|
|
67
67
|
[[package]]
|
|
68
68
|
name = "portable-atomic"
|
|
69
|
-
version = "1.
|
|
69
|
+
version = "1.15.0"
|
|
70
70
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
71
|
-
checksum = "
|
|
71
|
+
checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
|
|
72
72
|
|
|
73
73
|
[[package]]
|
|
74
74
|
name = "proc-macro2"
|
|
75
|
-
version = "1.0.
|
|
75
|
+
version = "1.0.107"
|
|
76
76
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
77
|
-
checksum = "
|
|
77
|
+
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
|
78
78
|
dependencies = [
|
|
79
79
|
"unicode-ident",
|
|
80
80
|
]
|
|
@@ -144,24 +144,24 @@ dependencies = [
|
|
|
144
144
|
|
|
145
145
|
[[package]]
|
|
146
146
|
name = "quote"
|
|
147
|
-
version = "1.0.
|
|
147
|
+
version = "1.0.47"
|
|
148
148
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
149
|
-
checksum = "
|
|
149
|
+
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
|
150
150
|
dependencies = [
|
|
151
151
|
"proc-macro2",
|
|
152
152
|
]
|
|
153
153
|
|
|
154
154
|
[[package]]
|
|
155
155
|
name = "rustversion"
|
|
156
|
-
version = "1.0.
|
|
156
|
+
version = "1.0.23"
|
|
157
157
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
158
|
-
checksum = "
|
|
158
|
+
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
|
|
159
159
|
|
|
160
160
|
[[package]]
|
|
161
161
|
name = "syn"
|
|
162
|
-
version = "2.0.
|
|
162
|
+
version = "2.0.119"
|
|
163
163
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
164
|
-
checksum = "
|
|
164
|
+
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
|
|
165
165
|
dependencies = [
|
|
166
166
|
"proc-macro2",
|
|
167
167
|
"quote",
|
|
@@ -170,15 +170,15 @@ dependencies = [
|
|
|
170
170
|
|
|
171
171
|
[[package]]
|
|
172
172
|
name = "target-lexicon"
|
|
173
|
-
version = "0.13.
|
|
173
|
+
version = "0.13.5"
|
|
174
174
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
175
|
-
checksum = "
|
|
175
|
+
checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
|
|
176
176
|
|
|
177
177
|
[[package]]
|
|
178
178
|
name = "unicode-ident"
|
|
179
|
-
version = "1.0.
|
|
179
|
+
version = "1.0.26"
|
|
180
180
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
181
|
-
checksum = "
|
|
181
|
+
checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
|
|
182
182
|
|
|
183
183
|
[[package]]
|
|
184
184
|
name = "unindent"
|
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
[package]
|
|
2
2
|
name = "path_jail_py"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.3.0"
|
|
4
4
|
edition = "2021"
|
|
5
5
|
license = "MIT OR Apache-2.0"
|
|
6
6
|
description = "Python bindings for path_jail - secure filesystem sandbox"
|
|
7
7
|
repository = "https://github.com/tenuo-ai/path-jail-python"
|
|
8
|
-
homepage = "https://tenuo.
|
|
8
|
+
homepage = "https://tenuo.ai"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
[lib]
|
|
11
11
|
name = "path_jail"
|
|
12
12
|
crate-type = ["cdylib"]
|
|
13
13
|
|
|
14
14
|
[dependencies]
|
|
15
|
-
path_jail = "0.
|
|
15
|
+
path_jail = "0.5"
|
|
16
16
|
pyo3 = { version = "0.24", features = ["extension-module", "abi3-py39"] }
|
|
17
17
|
|
|
18
18
|
[package.metadata]
|
|
19
|
-
authors = ["Niki A. <dev@tenuo.
|
|
19
|
+
authors = ["Niki A. <dev@tenuo.ai>"]
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: path-jail
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Classifier: Development Status :: 4 - Beta
|
|
5
5
|
Classifier: Intended Audience :: Developers
|
|
6
6
|
Classifier: License :: OSI Approved :: MIT License
|
|
@@ -22,13 +22,13 @@ License-File: LICENSE-APACHE
|
|
|
22
22
|
License-File: LICENSE-MIT
|
|
23
23
|
Summary: Secure filesystem sandbox. Restricts paths to a root directory, preventing traversal attacks.
|
|
24
24
|
Keywords: security,filesystem,sandbox,path,traversal
|
|
25
|
-
Home-Page: https://tenuo.
|
|
25
|
+
Home-Page: https://tenuo.ai
|
|
26
26
|
License: MIT OR Apache-2.0
|
|
27
27
|
Requires-Python: >=3.9
|
|
28
28
|
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
|
|
29
|
-
Project-URL: Homepage, https://tenuo.dev
|
|
30
|
-
Project-URL: Repository, https://github.com/tenuo-ai/path-jail-python
|
|
31
29
|
Project-URL: Documentation, https://github.com/tenuo-ai/path-jail-python#readme
|
|
30
|
+
Project-URL: Homepage, https://tenuo.ai
|
|
31
|
+
Project-URL: Repository, https://github.com/tenuo-ai/path-jail-python
|
|
32
32
|
|
|
33
33
|
# path-jail
|
|
34
34
|
|
|
@@ -61,8 +61,8 @@ path1 = jail.join("2025/report.pdf")
|
|
|
61
61
|
path2 = jail.join("data.csv")
|
|
62
62
|
|
|
63
63
|
# These raise ValueError:
|
|
64
|
-
jail.join("../../etc/passwd")
|
|
65
|
-
jail.join("/etc/passwd")
|
|
64
|
+
jail.join("../../etc/passwd") # Path traversal
|
|
65
|
+
jail.join("/etc/passwd") # Absolute path
|
|
66
66
|
```
|
|
67
67
|
|
|
68
68
|
## Why path-jail?
|
|
@@ -164,6 +164,10 @@ try:
|
|
|
164
164
|
except ValueError as e:
|
|
165
165
|
# Path escapes jail, broken symlink, or invalid path
|
|
166
166
|
print(f"Rejected: {e}")
|
|
167
|
+
except OSError as e:
|
|
168
|
+
# An existing component couldn't be inspected (e.g. permission denied).
|
|
169
|
+
# Fail closed: treat it as a rejection, not as a missing file.
|
|
170
|
+
print(f"Cannot verify: {e}")
|
|
167
171
|
except TypeError as e:
|
|
168
172
|
# Invalid type (not str or PathLike)
|
|
169
173
|
print(f"Bad input: {e}")
|
|
@@ -173,9 +177,12 @@ Creating a jail can also fail:
|
|
|
173
177
|
|
|
174
178
|
```python
|
|
175
179
|
try:
|
|
176
|
-
jail = Jail("/
|
|
180
|
+
jail = Jail("/var/uploads")
|
|
177
181
|
except OSError as e:
|
|
178
|
-
# Root doesn't exist or
|
|
182
|
+
# Root doesn't exist or can't be read
|
|
183
|
+
print(f"Invalid root: {e}")
|
|
184
|
+
except ValueError as e:
|
|
185
|
+
# Root is a file, or a filesystem root like "/"
|
|
179
186
|
print(f"Invalid root: {e}")
|
|
180
187
|
```
|
|
181
188
|
|
|
@@ -188,17 +195,18 @@ from path_jail import Jail
|
|
|
188
195
|
UPLOAD_DIR = "/var/uploads"
|
|
189
196
|
jail = Jail(UPLOAD_DIR)
|
|
190
197
|
|
|
198
|
+
|
|
191
199
|
def save_upload(user_id: str, filename: str, data: bytes) -> str:
|
|
192
200
|
"""Safely save an uploaded file."""
|
|
193
201
|
# Validate and build path
|
|
194
202
|
safe_path = jail.join(f"{user_id}/{filename}")
|
|
195
|
-
|
|
203
|
+
|
|
196
204
|
# Create parent directories
|
|
197
205
|
Path(safe_path).parent.mkdir(parents=True, exist_ok=True)
|
|
198
|
-
|
|
206
|
+
|
|
199
207
|
# Write file
|
|
200
208
|
Path(safe_path).write_bytes(data)
|
|
201
|
-
|
|
209
|
+
|
|
202
210
|
# Return relative path for database storage
|
|
203
211
|
return jail.relative(safe_path)
|
|
204
212
|
```
|
|
@@ -208,19 +216,22 @@ def save_upload(user_id: str, filename: str, data: bytes) -> str:
|
|
|
208
216
|
### FastAPI
|
|
209
217
|
|
|
210
218
|
```python
|
|
211
|
-
from
|
|
219
|
+
from pathlib import Path
|
|
220
|
+
|
|
221
|
+
from fastapi import FastAPI, HTTPException, UploadFile
|
|
212
222
|
from path_jail import Jail
|
|
213
223
|
|
|
214
224
|
app = FastAPI()
|
|
215
225
|
uploads = Jail("/var/uploads")
|
|
216
226
|
|
|
227
|
+
|
|
217
228
|
@app.post("/upload/{filename:path}")
|
|
218
229
|
async def upload(filename: str, file: UploadFile):
|
|
219
230
|
try:
|
|
220
231
|
safe_path = uploads.join(filename)
|
|
221
232
|
except ValueError:
|
|
222
233
|
raise HTTPException(400, "Invalid filename")
|
|
223
|
-
|
|
234
|
+
|
|
224
235
|
Path(safe_path).parent.mkdir(parents=True, exist_ok=True)
|
|
225
236
|
Path(safe_path).write_bytes(await file.read())
|
|
226
237
|
return {"path": filename}
|
|
@@ -236,13 +247,14 @@ from path_jail import Jail
|
|
|
236
247
|
app = Flask(__name__)
|
|
237
248
|
uploads = Jail("/var/uploads")
|
|
238
249
|
|
|
250
|
+
|
|
239
251
|
@app.route("/upload/<path:filename>", methods=["POST"])
|
|
240
252
|
def upload(filename):
|
|
241
253
|
try:
|
|
242
254
|
safe_path = uploads.join(filename)
|
|
243
255
|
except ValueError:
|
|
244
256
|
abort(400, "Invalid filename")
|
|
245
|
-
|
|
257
|
+
|
|
246
258
|
Path(safe_path).parent.mkdir(parents=True, exist_ok=True)
|
|
247
259
|
request.files["file"].save(safe_path)
|
|
248
260
|
return {"path": filename}
|
|
@@ -258,12 +270,13 @@ from path_jail import Jail
|
|
|
258
270
|
|
|
259
271
|
uploads = Jail(settings.MEDIA_ROOT)
|
|
260
272
|
|
|
273
|
+
|
|
261
274
|
def upload(request, filename):
|
|
262
275
|
try:
|
|
263
276
|
safe_path = uploads.join(filename)
|
|
264
277
|
except ValueError:
|
|
265
278
|
return HttpResponseBadRequest("Invalid filename")
|
|
266
|
-
|
|
279
|
+
|
|
267
280
|
Path(safe_path).parent.mkdir(parents=True, exist_ok=True)
|
|
268
281
|
with open(safe_path, "wb") as f:
|
|
269
282
|
for chunk in request.FILES["file"].chunks():
|
|
@@ -306,12 +319,23 @@ path-jail validates paths at call time. A symlink could be created between valid
|
|
|
306
319
|
```python
|
|
307
320
|
safe_path = jail.join("file.txt") # Validated
|
|
308
321
|
# Attacker creates symlink here
|
|
309
|
-
open(safe_path)
|
|
322
|
+
open(safe_path) # Escapes!
|
|
310
323
|
```
|
|
311
324
|
|
|
312
325
|
**Mitigations:**
|
|
313
|
-
-
|
|
326
|
+
- Open with `O_NOFOLLOW` so a symlink swapped in at the final component is
|
|
327
|
+
refused (intermediate directories are still unprotected):
|
|
328
|
+
```python
|
|
329
|
+
import os
|
|
330
|
+
|
|
331
|
+
fd = os.open(safe_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644)
|
|
332
|
+
with os.fdopen(fd, "wb") as f:
|
|
333
|
+
f.write(data)
|
|
334
|
+
```
|
|
314
335
|
- Use container/chroot isolation for strong guarantees
|
|
336
|
+
- The Rust crate's `guard` feature makes validate-and-open a single
|
|
337
|
+
kernel-checked step on Linux x86_64/aarch64 with kernel 5.6+; it is not
|
|
338
|
+
exposed in these bindings yet.
|
|
315
339
|
|
|
316
340
|
#### Windows Reserved Device Names
|
|
317
341
|
|
|
@@ -319,8 +343,8 @@ On Windows, filenames like `CON`, `PRN`, `AUX`, `NUL`, `COM1`-`COM9`, `LPT1`-`LP
|
|
|
319
343
|
|
|
320
344
|
```python
|
|
321
345
|
# If an attacker uploads "CON.txt":
|
|
322
|
-
safe_path = jail.join("CON.txt")
|
|
323
|
-
open(safe_path)
|
|
346
|
+
safe_path = jail.join("CON.txt") # Returns "C:\uploads\CON.txt"
|
|
347
|
+
open(safe_path) # Opens console device, not file!
|
|
324
348
|
```
|
|
325
349
|
|
|
326
350
|
**Impact:** Denial of Service (thread hangs or data vanishes). Not a filesystem escape.
|
|
@@ -355,8 +379,8 @@ jail.join("SECRET.TXT") # Not in blocklist, but same file!
|
|
|
355
379
|
Windows silently strips trailing dots and spaces from filenames:
|
|
356
380
|
|
|
357
381
|
```python
|
|
358
|
-
jail.join("file.txt.")
|
|
359
|
-
jail.join("file.txt ")
|
|
382
|
+
jail.join("file.txt.") # Becomes "file.txt"
|
|
383
|
+
jail.join("file.txt ") # Becomes "file.txt"
|
|
360
384
|
|
|
361
385
|
# Could bypass extension checks:
|
|
362
386
|
if not filename.endswith(".exe"):
|
|
@@ -406,6 +430,7 @@ When comparing paths, always canonicalize your expected values:
|
|
|
406
430
|
|
|
407
431
|
```python
|
|
408
432
|
import os
|
|
433
|
+
|
|
409
434
|
assert result == os.path.realpath("/var/uploads/file.txt")
|
|
410
435
|
```
|
|
411
436
|
|
|
@@ -29,8 +29,8 @@ path1 = jail.join("2025/report.pdf")
|
|
|
29
29
|
path2 = jail.join("data.csv")
|
|
30
30
|
|
|
31
31
|
# These raise ValueError:
|
|
32
|
-
jail.join("../../etc/passwd")
|
|
33
|
-
jail.join("/etc/passwd")
|
|
32
|
+
jail.join("../../etc/passwd") # Path traversal
|
|
33
|
+
jail.join("/etc/passwd") # Absolute path
|
|
34
34
|
```
|
|
35
35
|
|
|
36
36
|
## Why path-jail?
|
|
@@ -132,6 +132,10 @@ try:
|
|
|
132
132
|
except ValueError as e:
|
|
133
133
|
# Path escapes jail, broken symlink, or invalid path
|
|
134
134
|
print(f"Rejected: {e}")
|
|
135
|
+
except OSError as e:
|
|
136
|
+
# An existing component couldn't be inspected (e.g. permission denied).
|
|
137
|
+
# Fail closed: treat it as a rejection, not as a missing file.
|
|
138
|
+
print(f"Cannot verify: {e}")
|
|
135
139
|
except TypeError as e:
|
|
136
140
|
# Invalid type (not str or PathLike)
|
|
137
141
|
print(f"Bad input: {e}")
|
|
@@ -141,9 +145,12 @@ Creating a jail can also fail:
|
|
|
141
145
|
|
|
142
146
|
```python
|
|
143
147
|
try:
|
|
144
|
-
jail = Jail("/
|
|
148
|
+
jail = Jail("/var/uploads")
|
|
145
149
|
except OSError as e:
|
|
146
|
-
# Root doesn't exist or
|
|
150
|
+
# Root doesn't exist or can't be read
|
|
151
|
+
print(f"Invalid root: {e}")
|
|
152
|
+
except ValueError as e:
|
|
153
|
+
# Root is a file, or a filesystem root like "/"
|
|
147
154
|
print(f"Invalid root: {e}")
|
|
148
155
|
```
|
|
149
156
|
|
|
@@ -156,17 +163,18 @@ from path_jail import Jail
|
|
|
156
163
|
UPLOAD_DIR = "/var/uploads"
|
|
157
164
|
jail = Jail(UPLOAD_DIR)
|
|
158
165
|
|
|
166
|
+
|
|
159
167
|
def save_upload(user_id: str, filename: str, data: bytes) -> str:
|
|
160
168
|
"""Safely save an uploaded file."""
|
|
161
169
|
# Validate and build path
|
|
162
170
|
safe_path = jail.join(f"{user_id}/{filename}")
|
|
163
|
-
|
|
171
|
+
|
|
164
172
|
# Create parent directories
|
|
165
173
|
Path(safe_path).parent.mkdir(parents=True, exist_ok=True)
|
|
166
|
-
|
|
174
|
+
|
|
167
175
|
# Write file
|
|
168
176
|
Path(safe_path).write_bytes(data)
|
|
169
|
-
|
|
177
|
+
|
|
170
178
|
# Return relative path for database storage
|
|
171
179
|
return jail.relative(safe_path)
|
|
172
180
|
```
|
|
@@ -176,19 +184,22 @@ def save_upload(user_id: str, filename: str, data: bytes) -> str:
|
|
|
176
184
|
### FastAPI
|
|
177
185
|
|
|
178
186
|
```python
|
|
179
|
-
from
|
|
187
|
+
from pathlib import Path
|
|
188
|
+
|
|
189
|
+
from fastapi import FastAPI, HTTPException, UploadFile
|
|
180
190
|
from path_jail import Jail
|
|
181
191
|
|
|
182
192
|
app = FastAPI()
|
|
183
193
|
uploads = Jail("/var/uploads")
|
|
184
194
|
|
|
195
|
+
|
|
185
196
|
@app.post("/upload/{filename:path}")
|
|
186
197
|
async def upload(filename: str, file: UploadFile):
|
|
187
198
|
try:
|
|
188
199
|
safe_path = uploads.join(filename)
|
|
189
200
|
except ValueError:
|
|
190
201
|
raise HTTPException(400, "Invalid filename")
|
|
191
|
-
|
|
202
|
+
|
|
192
203
|
Path(safe_path).parent.mkdir(parents=True, exist_ok=True)
|
|
193
204
|
Path(safe_path).write_bytes(await file.read())
|
|
194
205
|
return {"path": filename}
|
|
@@ -204,13 +215,14 @@ from path_jail import Jail
|
|
|
204
215
|
app = Flask(__name__)
|
|
205
216
|
uploads = Jail("/var/uploads")
|
|
206
217
|
|
|
218
|
+
|
|
207
219
|
@app.route("/upload/<path:filename>", methods=["POST"])
|
|
208
220
|
def upload(filename):
|
|
209
221
|
try:
|
|
210
222
|
safe_path = uploads.join(filename)
|
|
211
223
|
except ValueError:
|
|
212
224
|
abort(400, "Invalid filename")
|
|
213
|
-
|
|
225
|
+
|
|
214
226
|
Path(safe_path).parent.mkdir(parents=True, exist_ok=True)
|
|
215
227
|
request.files["file"].save(safe_path)
|
|
216
228
|
return {"path": filename}
|
|
@@ -226,12 +238,13 @@ from path_jail import Jail
|
|
|
226
238
|
|
|
227
239
|
uploads = Jail(settings.MEDIA_ROOT)
|
|
228
240
|
|
|
241
|
+
|
|
229
242
|
def upload(request, filename):
|
|
230
243
|
try:
|
|
231
244
|
safe_path = uploads.join(filename)
|
|
232
245
|
except ValueError:
|
|
233
246
|
return HttpResponseBadRequest("Invalid filename")
|
|
234
|
-
|
|
247
|
+
|
|
235
248
|
Path(safe_path).parent.mkdir(parents=True, exist_ok=True)
|
|
236
249
|
with open(safe_path, "wb") as f:
|
|
237
250
|
for chunk in request.FILES["file"].chunks():
|
|
@@ -274,12 +287,23 @@ path-jail validates paths at call time. A symlink could be created between valid
|
|
|
274
287
|
```python
|
|
275
288
|
safe_path = jail.join("file.txt") # Validated
|
|
276
289
|
# Attacker creates symlink here
|
|
277
|
-
open(safe_path)
|
|
290
|
+
open(safe_path) # Escapes!
|
|
278
291
|
```
|
|
279
292
|
|
|
280
293
|
**Mitigations:**
|
|
281
|
-
-
|
|
294
|
+
- Open with `O_NOFOLLOW` so a symlink swapped in at the final component is
|
|
295
|
+
refused (intermediate directories are still unprotected):
|
|
296
|
+
```python
|
|
297
|
+
import os
|
|
298
|
+
|
|
299
|
+
fd = os.open(safe_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644)
|
|
300
|
+
with os.fdopen(fd, "wb") as f:
|
|
301
|
+
f.write(data)
|
|
302
|
+
```
|
|
282
303
|
- Use container/chroot isolation for strong guarantees
|
|
304
|
+
- The Rust crate's `guard` feature makes validate-and-open a single
|
|
305
|
+
kernel-checked step on Linux x86_64/aarch64 with kernel 5.6+; it is not
|
|
306
|
+
exposed in these bindings yet.
|
|
283
307
|
|
|
284
308
|
#### Windows Reserved Device Names
|
|
285
309
|
|
|
@@ -287,8 +311,8 @@ On Windows, filenames like `CON`, `PRN`, `AUX`, `NUL`, `COM1`-`COM9`, `LPT1`-`LP
|
|
|
287
311
|
|
|
288
312
|
```python
|
|
289
313
|
# If an attacker uploads "CON.txt":
|
|
290
|
-
safe_path = jail.join("CON.txt")
|
|
291
|
-
open(safe_path)
|
|
314
|
+
safe_path = jail.join("CON.txt") # Returns "C:\uploads\CON.txt"
|
|
315
|
+
open(safe_path) # Opens console device, not file!
|
|
292
316
|
```
|
|
293
317
|
|
|
294
318
|
**Impact:** Denial of Service (thread hangs or data vanishes). Not a filesystem escape.
|
|
@@ -323,8 +347,8 @@ jail.join("SECRET.TXT") # Not in blocklist, but same file!
|
|
|
323
347
|
Windows silently strips trailing dots and spaces from filenames:
|
|
324
348
|
|
|
325
349
|
```python
|
|
326
|
-
jail.join("file.txt.")
|
|
327
|
-
jail.join("file.txt ")
|
|
350
|
+
jail.join("file.txt.") # Becomes "file.txt"
|
|
351
|
+
jail.join("file.txt ") # Becomes "file.txt"
|
|
328
352
|
|
|
329
353
|
# Could bypass extension checks:
|
|
330
354
|
if not filename.endswith(".exe"):
|
|
@@ -374,6 +398,7 @@ When comparing paths, always canonicalize your expected values:
|
|
|
374
398
|
|
|
375
399
|
```python
|
|
376
400
|
import os
|
|
401
|
+
|
|
377
402
|
assert result == os.path.realpath("/var/uploads/file.txt")
|
|
378
403
|
```
|
|
379
404
|
|
|
@@ -4,7 +4,7 @@ build-backend = "maturin"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "path-jail"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.3.0"
|
|
8
8
|
description = "Secure filesystem sandbox. Restricts paths to a root directory, preventing traversal attacks."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = { text = "MIT OR Apache-2.0" }
|
|
@@ -27,7 +27,7 @@ classifiers = [
|
|
|
27
27
|
]
|
|
28
28
|
|
|
29
29
|
[project.urls]
|
|
30
|
-
Homepage = "https://tenuo.
|
|
30
|
+
Homepage = "https://tenuo.ai"
|
|
31
31
|
Repository = "https://github.com/tenuo-ai/path-jail-python"
|
|
32
32
|
Documentation = "https://github.com/tenuo-ai/path-jail-python#readme"
|
|
33
33
|
|
|
@@ -25,7 +25,8 @@ class Jail:
|
|
|
25
25
|
root: Path to the jail root directory (must exist)
|
|
26
26
|
|
|
27
27
|
Raises:
|
|
28
|
-
|
|
28
|
+
ValueError: If root is a filesystem root or not a directory
|
|
29
|
+
OSError: If root does not exist or cannot be read
|
|
29
30
|
"""
|
|
30
31
|
...
|
|
31
32
|
|
|
@@ -50,6 +51,8 @@ class Jail:
|
|
|
50
51
|
|
|
51
52
|
Raises:
|
|
52
53
|
ValueError: If path would escape the jail or is absolute
|
|
54
|
+
OSError: If an existing path component cannot be inspected
|
|
55
|
+
(e.g. permission denied)
|
|
53
56
|
"""
|
|
54
57
|
...
|
|
55
58
|
|
|
@@ -65,6 +68,7 @@ class Jail:
|
|
|
65
68
|
|
|
66
69
|
Raises:
|
|
67
70
|
ValueError: If path is outside the jail or not absolute
|
|
71
|
+
OSError: If the path cannot be inspected
|
|
68
72
|
"""
|
|
69
73
|
...
|
|
70
74
|
|
|
@@ -79,6 +83,7 @@ class Jail:
|
|
|
79
83
|
|
|
80
84
|
Raises:
|
|
81
85
|
ValueError: If path is outside the jail
|
|
86
|
+
OSError: If the path cannot be inspected
|
|
82
87
|
"""
|
|
83
88
|
...
|
|
84
89
|
|
|
@@ -100,8 +105,8 @@ def join(root: _PathLike, path: _PathLike) -> str:
|
|
|
100
105
|
prefix for paths exceeding 250 characters.
|
|
101
106
|
|
|
102
107
|
Raises:
|
|
103
|
-
ValueError: If path would escape the jail
|
|
104
|
-
OSError: If root does not exist
|
|
108
|
+
ValueError: If path would escape the jail, or root is not a directory
|
|
109
|
+
OSError: If root does not exist, or a path component cannot be inspected
|
|
105
110
|
|
|
106
111
|
Note:
|
|
107
112
|
On Windows, returns standard paths (e.g. ``C:\\...``) when possible.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#![allow(clippy::useless_conversion)]
|
|
2
2
|
|
|
3
3
|
use ::path_jail::{Jail as RustJail, JailError};
|
|
4
|
-
use pyo3::exceptions::{
|
|
4
|
+
use pyo3::exceptions::{PyOSError, PyTypeError, PyValueError};
|
|
5
5
|
use pyo3::prelude::*;
|
|
6
6
|
use pyo3::types::PyString;
|
|
7
7
|
use std::path::PathBuf;
|
|
@@ -89,6 +89,18 @@ fn extract_path(obj: &Bound<'_, PyAny>) -> PyResult<PathBuf> {
|
|
|
89
89
|
Err(PyTypeError::new_err("expected str or os.PathLike object"))
|
|
90
90
|
}
|
|
91
91
|
|
|
92
|
+
/// Convert an OS error without discarding its numeric error code.
|
|
93
|
+
fn io_error_to_py(err: std::io::Error) -> PyErr {
|
|
94
|
+
let message = err.to_string();
|
|
95
|
+
match err.raw_os_error() {
|
|
96
|
+
#[cfg(windows)]
|
|
97
|
+
Some(code) => PyOSError::new_err((0, message, Option::<String>::None, code)),
|
|
98
|
+
#[cfg(not(windows))]
|
|
99
|
+
Some(code) => PyOSError::new_err((code, message)),
|
|
100
|
+
None => err.into(),
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
92
104
|
/// Convert JailError to Python exception
|
|
93
105
|
fn to_py_err(err: JailError) -> PyErr {
|
|
94
106
|
match err {
|
|
@@ -104,7 +116,9 @@ fn to_py_err(err: JailError) -> PyErr {
|
|
|
104
116
|
JailError::InvalidPath(reason) => {
|
|
105
117
|
PyValueError::new_err(format!("invalid path: {}", reason))
|
|
106
118
|
}
|
|
107
|
-
|
|
119
|
+
// Filesystem root or non-directory. (A missing root surfaces as Io.)
|
|
120
|
+
err @ JailError::InvalidRoot { .. } => PyValueError::new_err(err.to_string()),
|
|
121
|
+
JailError::Io(err) => io_error_to_py(err),
|
|
108
122
|
// Handle future error variants from path_jail crate
|
|
109
123
|
_ => PyValueError::new_err(format!("path_jail error: {}", err)),
|
|
110
124
|
}
|
|
@@ -129,7 +143,8 @@ impl Jail {
|
|
|
129
143
|
/// root: Path to the jail root directory (must exist)
|
|
130
144
|
///
|
|
131
145
|
/// Raises:
|
|
132
|
-
///
|
|
146
|
+
/// ValueError: If root is a filesystem root or not a directory
|
|
147
|
+
/// OSError: If root does not exist or cannot be read
|
|
133
148
|
#[new]
|
|
134
149
|
fn new(root: &Bound<'_, PyAny>) -> PyResult<Self> {
|
|
135
150
|
let path = extract_path(root)?;
|
|
@@ -153,6 +168,8 @@ impl Jail {
|
|
|
153
168
|
///
|
|
154
169
|
/// Raises:
|
|
155
170
|
/// ValueError: If path would escape the jail or is absolute
|
|
171
|
+
/// OSError: If an existing path component cannot be inspected
|
|
172
|
+
/// (e.g. permission denied)
|
|
156
173
|
fn join(&self, path: &Bound<'_, PyAny>) -> PyResult<String> {
|
|
157
174
|
let path = extract_path(path)?;
|
|
158
175
|
self.inner
|
|
@@ -172,6 +189,7 @@ impl Jail {
|
|
|
172
189
|
///
|
|
173
190
|
/// Raises:
|
|
174
191
|
/// ValueError: If path is outside the jail or not absolute
|
|
192
|
+
/// OSError: If the path cannot be inspected
|
|
175
193
|
fn contains(&self, path: &Bound<'_, PyAny>) -> PyResult<String> {
|
|
176
194
|
let path = extract_path(path)?;
|
|
177
195
|
self.inner
|
|
@@ -191,6 +209,7 @@ impl Jail {
|
|
|
191
209
|
///
|
|
192
210
|
/// Raises:
|
|
193
211
|
/// ValueError: If path is outside the jail
|
|
212
|
+
/// OSError: If the path cannot be inspected
|
|
194
213
|
fn relative(&self, path: &Bound<'_, PyAny>) -> PyResult<String> {
|
|
195
214
|
let path = extract_path(path)?;
|
|
196
215
|
self.inner
|
|
@@ -227,8 +246,8 @@ impl Jail {
|
|
|
227
246
|
/// Absolute path inside the jail
|
|
228
247
|
///
|
|
229
248
|
/// Raises:
|
|
230
|
-
/// ValueError: If path would escape the jail
|
|
231
|
-
///
|
|
249
|
+
/// ValueError: If path would escape the jail, or root is not a directory
|
|
250
|
+
/// OSError: If root does not exist, or a path component cannot be inspected
|
|
232
251
|
///
|
|
233
252
|
/// Example:
|
|
234
253
|
/// >>> from path_jail import join
|
|
@@ -46,8 +46,9 @@ class TestJail:
|
|
|
46
46
|
assert paths_equal(jail.root, os.path.realpath(jail_dir))
|
|
47
47
|
|
|
48
48
|
def test_create_jail_nonexistent(self):
|
|
49
|
-
with pytest.raises(
|
|
49
|
+
with pytest.raises(FileNotFoundError) as exc_info:
|
|
50
50
|
Jail("/nonexistent/path")
|
|
51
|
+
assert exc_info.value.errno is not None
|
|
51
52
|
|
|
52
53
|
def test_join_simple(self, jail_dir):
|
|
53
54
|
jail = Jail(jail_dir)
|
|
@@ -99,6 +100,12 @@ class TestJail:
|
|
|
99
100
|
with pytest.raises(ValueError, match="escapes"):
|
|
100
101
|
jail.contains(outside_path)
|
|
101
102
|
|
|
103
|
+
def test_contains_missing_path_is_os_error(self, jail_dir):
|
|
104
|
+
jail = Jail(jail_dir)
|
|
105
|
+
missing = os.path.join(jail_dir, "missing.txt")
|
|
106
|
+
with pytest.raises(FileNotFoundError):
|
|
107
|
+
jail.contains(missing)
|
|
108
|
+
|
|
102
109
|
def test_relative(self, jail_dir):
|
|
103
110
|
jail = Jail(jail_dir)
|
|
104
111
|
test_file = os.path.join(jail_dir, "subdir", "file.txt")
|
|
@@ -109,6 +116,12 @@ class TestJail:
|
|
|
109
116
|
# On Windows, path separator might differ
|
|
110
117
|
assert normalize_path(result) == os.path.join("subdir", "file.txt")
|
|
111
118
|
|
|
119
|
+
def test_relative_missing_path_is_os_error(self, jail_dir):
|
|
120
|
+
jail = Jail(jail_dir)
|
|
121
|
+
missing = os.path.join(jail_dir, "missing.txt")
|
|
122
|
+
with pytest.raises(FileNotFoundError):
|
|
123
|
+
jail.relative(missing)
|
|
124
|
+
|
|
112
125
|
def test_repr(self, jail_dir):
|
|
113
126
|
jail = Jail(jail_dir)
|
|
114
127
|
assert "Jail(" in repr(jail)
|
|
@@ -323,7 +336,7 @@ class TestSecurityEdgeCases:
|
|
|
323
336
|
result = jail.join(special)
|
|
324
337
|
# If it works, verify it's inside the jail
|
|
325
338
|
assert normalize_path(result).startswith(normalize_path(jail.root))
|
|
326
|
-
except ValueError:
|
|
339
|
+
except (ValueError, OSError):
|
|
327
340
|
pass # Also acceptable to reject
|
|
328
341
|
|
|
329
342
|
def test_backslash_on_unix(self, jail_dir):
|
|
@@ -385,3 +398,38 @@ class TestSecurityEdgeCases:
|
|
|
385
398
|
jail = Jail(jail_dir)
|
|
386
399
|
result = jail.join("subdir/")
|
|
387
400
|
assert normalize_path(result).startswith(normalize_path(jail.root))
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
class TestCoreBehavior:
|
|
404
|
+
"""Behavior that comes from the path_jail 0.5 core."""
|
|
405
|
+
|
|
406
|
+
def test_non_directory_root_is_value_error(self, jail_dir):
|
|
407
|
+
file_root = os.path.join(jail_dir, "file.txt")
|
|
408
|
+
with open(file_root, "w"):
|
|
409
|
+
pass
|
|
410
|
+
with pytest.raises(ValueError, match="not a directory"):
|
|
411
|
+
Jail(file_root)
|
|
412
|
+
|
|
413
|
+
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX permissions")
|
|
414
|
+
@pytest.mark.skipif(
|
|
415
|
+
hasattr(os, "geteuid") and os.geteuid() == 0, reason="root bypasses permissions"
|
|
416
|
+
)
|
|
417
|
+
def test_unreadable_component_fails_closed(self, jail_dir):
|
|
418
|
+
locked = os.path.join(jail_dir, "locked")
|
|
419
|
+
os.mkdir(locked)
|
|
420
|
+
os.chmod(locked, 0)
|
|
421
|
+
try:
|
|
422
|
+
jail = Jail(jail_dir)
|
|
423
|
+
# 0.2 treated the unreadable component as nonexistent and returned
|
|
424
|
+
# a path; 0.5 reports the I/O error instead.
|
|
425
|
+
with pytest.raises(PermissionError):
|
|
426
|
+
jail.join("locked/file.txt")
|
|
427
|
+
finally:
|
|
428
|
+
os.chmod(locked, 0o700)
|
|
429
|
+
|
|
430
|
+
def test_version_matches_metadata(self):
|
|
431
|
+
from importlib.metadata import version
|
|
432
|
+
|
|
433
|
+
import path_jail
|
|
434
|
+
|
|
435
|
+
assert path_jail.__version__ == version("path-jail")
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|