kobako 0.31.0 → 0.32.0
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.
- checksums.yaml +4 -4
- data/.githooks/linux-tests.sh +29 -0
- data/.release-please-manifest.json +1 -1
- data/CHANGELOG.md +125 -0
- data/Cargo.lock +457 -494
- data/README.md +2 -3
- data/ROADMAP.md +0 -1
- data/crates/kobako-runtime/CHANGELOG.md +90 -0
- data/crates/kobako-runtime/Cargo.toml +14 -15
- data/crates/kobako-runtime/README.md +1 -1
- data/crates/kobako-runtime/src/cred.rs +32 -20
- data/crates/kobako-runtime/src/filesystem/bind/fid.rs +300 -22
- data/crates/kobako-runtime/src/filesystem/bind/lookup.rs +56 -22
- data/crates/kobako-runtime/src/filesystem/bind/unicode.rs +109 -0
- data/crates/kobako-runtime/src/filesystem/bind/walk.rs +33 -14
- data/crates/kobako-runtime/src/filesystem/bind.rs +393 -220
- data/crates/kobako-runtime/src/filesystem/overlay/stack/copy_up.rs +2 -0
- data/crates/kobako-runtime/src/filesystem/overlay/stack.rs +9 -10
- data/crates/kobako-runtime/src/filesystem/overlay.rs +277 -46
- data/crates/kobako-runtime/src/filesystem/rdir.rs +8 -27
- data/crates/kobako-runtime/src/filesystem/testing.rs +31 -0
- data/crates/kobako-runtime/src/filesystem/tmpfs.rs +47 -13
- data/crates/kobako-runtime/src/filesystem.rs +2 -0
- data/crates/kobako-runtime/src/fork.rs +239 -16
- data/crates/kobako-runtime/src/limits.rs +17 -41
- data/crates/kobako-runtime/src/locking/seqlock.rs +29 -3
- data/crates/kobako-runtime/src/locking.rs +508 -113
- data/crates/kobako-runtime/src/memcg.rs +83 -160
- data/crates/kobako-runtime/src/mount.rs +0 -30
- data/crates/kobako-runtime/src/net/connections.rs +53 -13
- data/crates/kobako-runtime/src/net/egress.rs +44 -24
- data/crates/kobako-runtime/src/net/http.rs +888 -456
- data/crates/kobako-runtime/src/net/lookup.rs +150 -50
- data/crates/kobako-runtime/src/net/namespace.rs +97 -95
- data/crates/kobako-runtime/src/net/reactor.rs +298 -203
- data/crates/kobako-runtime/src/net/resolv/darwin.rs +8 -3
- data/crates/kobako-runtime/src/net/resolv/stub/tests.rs +50 -0
- data/crates/kobako-runtime/src/net/resolv/stub.rs +29 -23
- data/crates/kobako-runtime/src/net/resolv/windows.rs +14 -44
- data/crates/kobako-runtime/src/net/resolv.rs +39 -15
- data/crates/kobako-runtime/src/net/skbuff.rs +109 -0
- data/crates/kobako-runtime/src/net/socket.rs +51 -52
- data/crates/kobako-runtime/src/net/task.rs +223 -0
- data/crates/kobako-runtime/src/net/tcp.rs +410 -158
- data/crates/kobako-runtime/src/net/tls.rs +65 -3
- data/crates/kobako-runtime/src/net/transport.rs +72 -47
- data/crates/kobako-runtime/src/net/udp.rs +231 -129
- data/crates/kobako-runtime/src/net.rs +3 -0
- data/crates/kobako-runtime/src/sched.rs +244 -58
- data/crates/kobako-runtime/src/security.rs +27 -16
- data/crates/kobako-runtime/src/vfs/dentry.rs +80 -41
- data/crates/kobako-runtime/src/vfs/file.rs +52 -53
- data/crates/kobako-runtime/src/vfs/kern_path.rs +24 -11
- data/crates/kobako-runtime/src/vfs/namei.rs +399 -184
- data/crates/kobako-runtime/src/vfs/namespace.rs +123 -40
- data/crates/kobako-runtime/src/vfs/stat.rs +105 -16
- data/crates/kobako-runtime/src/vfs.rs +1 -0
- data/crates/kobako-runtime/src/wait.rs +75 -50
- data/crates/kobako-transport/CHANGELOG.md +7 -0
- data/crates/kobako-transport/Cargo.toml +1 -1
- data/crates/kobako-transport/README.md +1 -1
- data/crates/kobako-wasmtime/CHANGELOG.md +47 -0
- data/crates/kobako-wasmtime/Cargo.toml +27 -6
- data/crates/kobako-wasmtime/README.md +3 -3
- data/crates/kobako-wasmtime/src/abi.rs +2 -1
- data/crates/kobako-wasmtime/src/ambient.rs +11 -2
- data/crates/kobako-wasmtime/src/cache/unix.rs +95 -0
- data/crates/kobako-wasmtime/src/cache/windows.rs +359 -0
- data/crates/kobako-wasmtime/src/cache.rs +88 -103
- data/crates/kobako-wasmtime/src/driver.rs +40 -27
- data/crates/kobako-wasmtime/src/invocation.rs +21 -7
- data/crates/kobako-wasmtime/src/lib.rs +2 -0
- data/crates/kobako-wasmtime/src/limiter.rs +78 -25
- data/crates/kobako-wasmtime/src/preview1/descriptors.rs +13 -17
- data/crates/kobako-wasmtime/src/preview1/differential/mount.rs +4 -5
- data/crates/kobako-wasmtime/src/preview1/differential.rs +1 -1
- data/crates/kobako-wasmtime/src/preview1/fd.rs +23 -19
- data/crates/kobako-wasmtime/src/preview1/mount_view.rs +130 -197
- data/crates/kobako-wasmtime/src/preview1/path.rs +3 -3
- data/crates/kobako-wasmtime/src/preview1/poll.rs +28 -22
- data/crates/kobako-wasmtime/src/preview1/random.rs +125 -0
- data/crates/kobako-wasmtime/src/preview1/testing.rs +31 -0
- data/crates/kobako-wasmtime/src/preview1.rs +85 -9
- data/crates/kobako-wasmtime/src/preview2/filesystem.rs +2 -2
- data/crates/kobako-wasmtime/src/preview2/host.rs +609 -249
- data/crates/kobako-wasmtime/src/preview2/http.rs +299 -215
- data/crates/kobako-wasmtime/src/preview2/io.rs +17 -4
- data/crates/kobako-wasmtime/src/preview2/table.rs +24 -72
- data/crates/kobako-wasmtime/src/trap.rs +68 -23
- data/crates/kobako-wasmtime/src/waits.rs +59 -0
- data/crates/kobako-wasmtime/src/wasi.rs +91 -10
- data/crates/kobako-wasmtime/witx/wasi_snapshot_preview1.witx +13 -0
- data/data/kobako.wasm +0 -0
- data/ext/kobako/Cargo.toml +6 -2
- data/ext/kobako/src/escape.rs +332 -26
- data/ext/kobako/src/filesystem/grants.rs +5 -7
- data/ext/kobako/src/filesystem/ruby.rs +10 -3
- data/ext/kobako/src/filesystem.rs +47 -8
- data/ext/kobako/src/fork.rs +72 -0
- data/ext/kobako/src/gvl.rs +499 -76
- data/ext/kobako/src/handoff.rs +490 -0
- data/ext/kobako/src/lib.rs +10 -0
- data/ext/kobako/src/network.rs +5 -3
- data/ext/kobako/src/pinned_value.rs +28 -15
- data/ext/kobako/src/runtime/bridge.rs +32 -25
- data/ext/kobako/src/runtime.rs +74 -43
- data/lib/kobako/catalog/handles.rb +9 -5
- data/lib/kobako/codec/decoder.rb +1 -1
- data/lib/kobako/codec/state.rb +2 -18
- data/lib/kobako/codec/value_budget.rb +4 -4
- data/lib/kobako/codec.rb +5 -6
- data/lib/kobako/errors.rb +4 -7
- data/lib/kobako/filesystem.rb +1 -1
- data/lib/kobako/fork.rb +42 -0
- data/lib/kobako/handle.rb +1 -2
- data/lib/kobako/sandbox.rb +17 -36
- data/lib/kobako/sandbox_options.rb +7 -9
- data/lib/kobako/usage.rb +4 -2
- data/lib/kobako/version.rb +1 -1
- data/lib/kobako.rb +2 -2
- data/sig/kobako/catalog/handles.rbs +2 -0
- data/sig/kobako/codec/state.rbs +0 -4
- data/sig/kobako/codec/value_budget.rbs +1 -1
- data/sig/kobako/codec.rbs +2 -2
- data/sig/kobako/errors.rbs +0 -3
- data/sig/kobako/fork.rbs +17 -0
- data/sig/kobako/runtime.rbs +2 -2
- data/sig/kobako/sandbox.rbs +3 -12
- data/sig/kobako/sandbox_options.rbs +0 -2
- metadata +15 -4
- data/lib/kobako/pool.rb +0 -162
- data/sig/core/thread.rbs +0 -6
- data/sig/kobako/pool.rbs +0 -46
|
@@ -1,5 +1,52 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.22.0](https://github.com/elct9620/kobako/compare/kobako-wasmtime-v0.21.0...kobako-wasmtime-v0.22.0) (2026-11-27)
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
### ⚠ BREAKING CHANGES
|
|
7
|
+
|
|
8
|
+
* **runtime:** vfs::cp_new_stat returns Result<Kstat, Errno> and vfs::ino_of returns Result<u64, Errno> in place of Kstat and u64; a Wasm Driver passes their EOVERFLOW to the guest.
|
|
9
|
+
* **wasmtime:** a guest no longer reads EINTR from a call its run's deadline or interrupt ended; the run ends there as a timeout or an interrupt.
|
|
10
|
+
* **runtime:** memory_limit measures the guest's own memory only; host buffers no longer answer ENOMEM or fail a request as internal.
|
|
11
|
+
* **memcg:** a run whose start function, global initializers, table growth, or request grow past memory_limit now raises Kobako::MemoryLimitError, growth of several memories and the GC heap adds up, and Usage#memory_peak includes them. Raise memory_limit by that growth to keep the earlier headroom.
|
|
12
|
+
* **filesystem:** an Overlay directory over N Bind Layers takes N of an invocation's `open_file_limit`; raise the limit by the Layers each held directory spans.
|
|
13
|
+
* **net:** TcpSock::send_room counts the Invocation's memory, and MemoryBudget::peak, and so Usage::memory_peak, can pass the limit by a permitted write as well as a forced read, at most 68 KiB more per open connection.
|
|
14
|
+
* **vfs:** a FileOperations implementing iterate_shared must also return true from has_iterate_shared, or its listings answer NotADirectory.
|
|
15
|
+
* **vfs:** a guest now holds one preopen, `/`, at descriptor 3, instead of one per outermost Mount named by its path. A Guest Binary built on wasi-libc is unaffected; one that reads a Mount through descriptor 3 directly walks from `/` now, or the Host App mounts its Filesystem at `/`. `kobako_runtime::mount::outermost_of` is removed; a Wasm Driver opens `Cred::root` instead.
|
|
16
|
+
|
|
17
|
+
### Features
|
|
18
|
+
|
|
19
|
+
* **http:** stream a request body as the guest writes it ([ed2b571](https://github.com/elct9620/kobako/commit/ed2b571820d46b1fdfff577b3c8257fd7c63ce71))
|
|
20
|
+
* **runtime:** tell how many datagrams a UDP socket holds unread ([48df527](https://github.com/elct9620/kobako/commit/48df52794238e2c13e27cc45f78e31e24101d82e))
|
|
21
|
+
* **vfs:** preopen the guest's root alone, beneath which every Mount stands ([2a6d18d](https://github.com/elct9620/kobako/commit/2a6d18d78814f0529b15e109bbcd50f8b372e51b))
|
|
22
|
+
* **wasmtime:** bound what one host call copies out of the guest by memory_limit ([044090e](https://github.com/elct9620/kobako/commit/044090eef9430584d970b0bd0a773fd37ce61ffc))
|
|
23
|
+
* **wasmtime:** let a forked child on macOS run Sandboxes on any Thread ([a78375a](https://github.com/elct9620/kobako/commit/a78375a440614eb14dee722365702bb3bab5a23c))
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
### Bug Fixes
|
|
27
|
+
|
|
28
|
+
* **filesystem:** charge each host directory an Overlay holds to the caller ([437ada0](https://github.com/elct9620/kobako/commit/437ada00b268cf793cee8e7fadee1067dd0a4bf7))
|
|
29
|
+
* **memcg:** charge every growth from the run's Store past what the binary declares ([44c7a8b](https://github.com/elct9620/kobako/commit/44c7a8bdc444b96a5d34a137a72b4e2f3c292d80))
|
|
30
|
+
* **net:** keep an output stream's permit whole once its memory fills ([2b641cc](https://github.com/elct9620/kobako/commit/2b641ccee300a160d39c5edf691487d05ac4e365))
|
|
31
|
+
* **net:** move each request on the thread that waits for it ([425f82a](https://github.com/elct9620/kobako/commit/425f82abc5fc0b78774d0ae4e448a13a547bac29))
|
|
32
|
+
* **runtime:** count only the guest's descriptors against the open-file cap ([b0deca2](https://github.com/elct9620/kobako/commit/b0deca26519684729f37bf288a6a40f28968f9d0))
|
|
33
|
+
* **runtime:** hold what the host keeps for a run by counts, not memory ([5428293](https://github.com/elct9620/kobako/commit/54282932e5f8a523d3d9e79275b846265102a22f))
|
|
34
|
+
* **runtime:** number a hermetic invocation's entries in the order it meets them ([4e23399](https://github.com/elct9620/kobako/commit/4e23399eca979ae4526735c72e34133907dceeb3))
|
|
35
|
+
* **vfs:** keep each Filesystem's moves to the walks on it ([42062b9](https://github.com/elct9620/kobako/commit/42062b9c2f22e00f6317fa92ebd6abe2b3fd76b0))
|
|
36
|
+
* **vfs:** refuse a listing of a file without iterate_shared before locking it ([34eb327](https://github.com/elct9620/kobako/commit/34eb3273cd537ccbd2b7a3592ece38da79d60d2f))
|
|
37
|
+
* **wasmtime:** answer random_get a page at a time into the guest's buffer ([d55aa1d](https://github.com/elct9620/kobako/commit/d55aa1da4082902e3b3f6b664b64ac50ee25d9b0))
|
|
38
|
+
* **wasmtime:** ask the OS for a permissive guest's entropy on each draw ([fcfaca4](https://github.com/elct9620/kobako/commit/fcfaca49d0067d1d372e24e680004d04cd0f41ee))
|
|
39
|
+
* **wasmtime:** end a run as a host call returns once the run is to stop ([f5840c6](https://github.com/elct9620/kobako/commit/f5840c687f91d18fb01bb426d577f9c4e208b277))
|
|
40
|
+
* **wasmtime:** fail a refused growth as memory.grow does, not by ending the run ([8cd50be](https://github.com/elct9620/kobako/commit/8cd50bed12c18ea0b906b3e2fe1d6310194e34f2))
|
|
41
|
+
* **wasmtime:** fail the caller when the host has no thread or room ([855734f](https://github.com/elct9620/kobako/commit/855734fcaf97cae11e80a6e9f83492bc2c292a2b))
|
|
42
|
+
* **wasmtime:** open a cached artifact on Windows as wasmtime maps one ([4be7e9b](https://github.com/elct9620/kobako/commit/4be7e9b8b371f3dc95490da024ca72fa1a0c7597))
|
|
43
|
+
* **wasmtime:** stop a guest that only computes once its run takes a fatal signal ([32990b6](https://github.com/elct9620/kobako/commit/32990b63cd6ae16c5d8a0e473a218d46d29c8919))
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
### Performance Improvements
|
|
47
|
+
|
|
48
|
+
* **wasmtime:** cache compiled Guest Binaries on disk on Windows too ([76ca86e](https://github.com/elct9620/kobako/commit/76ca86e3aab83d239e1d0b4ebbcd21e2aec14bf3))
|
|
49
|
+
|
|
3
50
|
## [0.21.0](https://github.com/elct9620/kobako/compare/kobako-wasmtime-v0.20.0...kobako-wasmtime-v0.21.0) (2026-11-18)
|
|
4
51
|
|
|
5
52
|
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
|
|
16
16
|
[package]
|
|
17
17
|
name = "kobako-wasmtime"
|
|
18
|
-
version = "0.
|
|
18
|
+
version = "0.22.0"
|
|
19
19
|
edition = "2021"
|
|
20
20
|
# The toolchain this crate is built and tested on, the first whose stripped
|
|
21
21
|
# Apple binary macOS 26 loads.
|
|
@@ -34,10 +34,10 @@ exclude = ["tests/"]
|
|
|
34
34
|
# The engine-neutral contract this crate implements. The version pin
|
|
35
35
|
# rides the linked release group; the path keeps in-tree builds (and
|
|
36
36
|
# the Ruby gem, which ships both crates) resolving locally.
|
|
37
|
-
kobako-runtime = { version = "0.
|
|
37
|
+
kobako-runtime = { version = "0.22.0", path = "../kobako-runtime" }
|
|
38
38
|
# The fixed tier: the Envelope this driver shuttles and the ABI
|
|
39
39
|
# values it drives the exports against.
|
|
40
|
-
kobako-transport = { version = "0.
|
|
40
|
+
kobako-transport = { version = "0.22.0", path = "../kobako-transport" }
|
|
41
41
|
# wasmtime — host-side embedder for kobako.wasm. We disable default-features
|
|
42
42
|
# and opt back in only what kobako needs: a Cranelift-backed runtime that can
|
|
43
43
|
# compile a pre-built wasm32-wasip1 module on the host triple, plus the `wat`
|
|
@@ -61,6 +61,10 @@ wasmtime = { version = "50.0.1", default-features = false, features = [
|
|
|
61
61
|
# its own descriptor table. `p1` is the only feature kobako asks for; it
|
|
62
62
|
# enables `p2` itself, while `p0` and `p3` stay off.
|
|
63
63
|
wasmtime-wasi = { version = "50.0.1", default-features = false, features = ["p1"] }
|
|
64
|
+
# rand names the generator wasmtime-wasi takes for a guest's entropy;
|
|
65
|
+
# `sys_rng` asks the OS on each draw, so a forked child holds no state that
|
|
66
|
+
# repeats its parent's draws, as a thread's ThreadRng does.
|
|
67
|
+
rand = { version = "0.10.1", default-features = false, features = ["sys_rng"] }
|
|
64
68
|
# wiggle generates the preview1 calls kobako answers from `witx/`, as it
|
|
65
69
|
# generates wasmtime-wasi's, so each takes its arguments and writes its answer
|
|
66
70
|
# as wasmtime-wasi does. It rides wasmtime's release train.
|
|
@@ -71,9 +75,13 @@ wiggle = { version = "50.0.1", default-features = false, features = ["wasmtime"]
|
|
|
71
75
|
sha2 = "0.11"
|
|
72
76
|
|
|
73
77
|
[dev-dependencies]
|
|
74
|
-
# wasmparser
|
|
75
|
-
#
|
|
76
|
-
wasmparser = "0.
|
|
78
|
+
# wasmparser reads the bundled Guest Binary, to witness what each ABI export
|
|
79
|
+
# can call and what the binary imports.
|
|
80
|
+
wasmparser = "0.263.0"
|
|
81
|
+
|
|
82
|
+
# libc forks a test's process, to witness what a child keeps of its parent.
|
|
83
|
+
[target.'cfg(unix)'.dev-dependencies]
|
|
84
|
+
libc = "0.2.191"
|
|
77
85
|
|
|
78
86
|
[build-dependencies]
|
|
79
87
|
# build.rs generates the WASI 0.2 imports a Guest Binary links as a core
|
|
@@ -85,8 +93,21 @@ wit-bindgen-core = "0.63.0"
|
|
|
85
93
|
# hands back to cargo.
|
|
86
94
|
anyhow = "1.0.102"
|
|
87
95
|
|
|
96
|
+
[features]
|
|
97
|
+
# Off by default, as in wasmtime, so a host whose crash reporter takes
|
|
98
|
+
# faults over a Mach port, as breakpad does, still sees the guest's apart
|
|
99
|
+
# from its own. On, a guest's faults on macOS arrive as POSIX signals, which
|
|
100
|
+
# a forked child keeps; one setting holds for the whole process.
|
|
101
|
+
posix-signals-on-macos = []
|
|
102
|
+
|
|
88
103
|
# rustix reaches the cache directory through one descriptor, checked by
|
|
89
104
|
# owner, so the unsafe artifact deserialize reads only what that
|
|
90
105
|
# directory holds (see cache.rs); std has no `*at` calls.
|
|
91
106
|
[target.'cfg(unix)'.dependencies]
|
|
92
107
|
rustix = { version = "1.1.4", features = ["fs", "process"] }
|
|
108
|
+
|
|
109
|
+
# windows-sys reads and sets the cache directory's owner and DACL, which std
|
|
110
|
+
# cannot, so the unsafe artifact deserialize trusts it only as rustix lets
|
|
111
|
+
# Unix trust it.
|
|
112
|
+
[target.'cfg(windows)'.dependencies]
|
|
113
|
+
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_SystemServices", "Win32_System_Threading"] }
|
|
@@ -11,11 +11,11 @@ contract surface.
|
|
|
11
11
|
| Mechanic | What the driver holds |
|
|
12
12
|
|---|---|
|
|
13
13
|
| Compilation | process-wide Engine and compiled-Module caches |
|
|
14
|
-
| Disk cache | AOT `.cwasm` artifacts
|
|
14
|
+
| Disk cache | AOT `.cwasm` artifacts in a user-private directory, keyed by content and engine |
|
|
15
15
|
| Instantiation | a pre-linked `InstancePre` per guest path, a fresh instance per invocation |
|
|
16
16
|
| Bounds | epoch-based wall-clock deadlines on setup and on each invocation, and the per-invocation linear-memory cap |
|
|
17
17
|
| Ambient denial | under the default hermetic profile, frozen clocks and a constant RNG |
|
|
18
|
-
| Filesystems |
|
|
18
|
+
| Filesystems | one preopen, the root every Mount stands beneath, and its own capped descriptor table |
|
|
19
19
|
| WASI 0.2 imports | the `wasi:sockets`, `wasi:http` client, `wasi:io`, and clock subscriptions a core module links, generated from `wit/` |
|
|
20
20
|
|
|
21
21
|
Each invocation discards its Store once it ends, so nothing one leaves
|
|
@@ -29,7 +29,7 @@ Add the crate beside `kobako-runtime` to run a Guest Binary through its
|
|
|
29
29
|
|
|
30
30
|
```toml
|
|
31
31
|
[dependencies]
|
|
32
|
-
kobako-wasmtime = "0.
|
|
32
|
+
kobako-wasmtime = "0.22.0" # x-release-please-version
|
|
33
33
|
```
|
|
34
34
|
|
|
35
35
|
## License
|
|
@@ -29,7 +29,8 @@ pub(crate) fn verify(
|
|
|
29
29
|
let wasi = Wasi::for_probe().map_err(|t| SetupError::Dead(t.to_string()))?;
|
|
30
30
|
// The memory budget stays off: it arms per invocation, and the probe is
|
|
31
31
|
// none.
|
|
32
|
-
let mut store = WtStore::
|
|
32
|
+
let mut store = WtStore::try_new(load_engine()?, Invocation::new(wasi))
|
|
33
|
+
.map_err(|err| SetupError::Dead(format!("failed to create the probe's store: {err}")))?;
|
|
33
34
|
trap::arm_deadline(&mut store, setup_timeout);
|
|
34
35
|
let past_deadline = |err: &wasmtime::Error| {
|
|
35
36
|
matches!(trap::cap_trap_of(err), Some(Trap::Timeout(_))).then(|| {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
//! The guest's time and entropy at the WASI layer — the one ambient
|
|
2
2
|
//! authority that separates the hermetic profile from permissive. `Wasi::new`
|
|
3
|
-
//! wires the frozen sources on `Hermetic
|
|
4
|
-
//! `Permissive`; `Clocks` is what the guest reads its time from under either.
|
|
3
|
+
//! wires the frozen sources on `Hermetic`, and the live clock and the OS's
|
|
4
|
+
//! entropy on `Permissive`; `Clocks` is what the guest reads its time from under either.
|
|
5
5
|
//!
|
|
6
6
|
//! `wasmtime-wasi`'s `WasiCtxBuilder` defaults the guest's `wasi:clocks` to
|
|
7
7
|
//! the host wall / monotonic clock and `wasi:random` to a fresh per-context
|
|
@@ -18,6 +18,8 @@
|
|
|
18
18
|
|
|
19
19
|
use std::time::{Duration, Instant};
|
|
20
20
|
|
|
21
|
+
use rand::rand_core::UnwrapErr;
|
|
22
|
+
use rand::rngs::SysRng;
|
|
21
23
|
use wasmtime_wasi::clocks::WallClock;
|
|
22
24
|
use wasmtime_wasi::random::Deterministic;
|
|
23
25
|
use wasmtime_wasi::{HostMonotonicClock, HostWallClock};
|
|
@@ -56,6 +58,13 @@ pub(crate) fn deterministic_rng() -> Deterministic {
|
|
|
56
58
|
Deterministic::new(vec![0])
|
|
57
59
|
}
|
|
58
60
|
|
|
61
|
+
/// The host's entropy, asked of the OS on each draw: a generator seeded once
|
|
62
|
+
/// from a thread's `ThreadRng`, as wasmtime-wasi's default is, draws the
|
|
63
|
+
/// same bytes in a forked child as in its parent.
|
|
64
|
+
pub(crate) fn host_rng() -> UnwrapErr<SysRng> {
|
|
65
|
+
UnwrapErr(SysRng)
|
|
66
|
+
}
|
|
67
|
+
|
|
59
68
|
/// The host's monotonic clock read from a fixed origin. The guest's
|
|
60
69
|
/// `clock_time_get` and a wait it subscribes to share it, so both agree on
|
|
61
70
|
/// what an instant means.
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
//! The cache directory on Unix, reached through one descriptor: every step
|
|
2
|
+
//! after the trust check goes through it, so a path swapped after the check
|
|
3
|
+
//! reaches nothing.
|
|
4
|
+
|
|
5
|
+
use std::ffi::{OsStr, OsString};
|
|
6
|
+
use std::fs;
|
|
7
|
+
use std::io;
|
|
8
|
+
use std::os::unix::ffi::OsStrExt;
|
|
9
|
+
use std::os::unix::fs::DirBuilderExt;
|
|
10
|
+
use std::path::{Path, PathBuf};
|
|
11
|
+
use std::sync::atomic::{AtomicU64, Ordering};
|
|
12
|
+
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
|
13
|
+
|
|
14
|
+
use rustix::fd::OwnedFd;
|
|
15
|
+
use rustix::fs::{
|
|
16
|
+
fstat, fsync, open, openat, renameat, statat, unlinkat, AtFlags, Dir, Mode, OFlags,
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
pub(super) struct PrivateDir(OwnedFd);
|
|
20
|
+
|
|
21
|
+
impl PrivateDir {
|
|
22
|
+
/// Create `dir` owner-only (`0700`) so no other local user can plant an
|
|
23
|
+
/// artifact the unsafe deserialize would trust.
|
|
24
|
+
pub(super) fn create(dir: &Path) -> io::Result<()> {
|
|
25
|
+
fs::DirBuilder::new()
|
|
26
|
+
.recursive(true)
|
|
27
|
+
.mode(0o700)
|
|
28
|
+
.create(dir)
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/// `dir`, once it upholds the trust the unsafe deserialize relies on: a
|
|
32
|
+
/// directory rather than a link in its place, owned by the current
|
|
33
|
+
/// effective user and writable by no one else.
|
|
34
|
+
pub(super) fn open(dir: &Path) -> Option<Self> {
|
|
35
|
+
let flags = OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC;
|
|
36
|
+
let fd = open(dir, flags, Mode::empty()).ok()?;
|
|
37
|
+
let stat = fstat(&fd).ok()?;
|
|
38
|
+
let owned = stat.st_uid == rustix::process::geteuid().as_raw();
|
|
39
|
+
(owned && stat.st_mode & 0o022 == 0).then_some(Self(fd))
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/// The entry `name`, opened to read without following a link.
|
|
43
|
+
pub(super) fn open_entry(&self, name: &OsStr) -> Option<fs::File> {
|
|
44
|
+
let flags = OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC;
|
|
45
|
+
let fd = openat(&self.0, name, flags, Mode::empty()).ok()?;
|
|
46
|
+
Some(fs::File::from(fd))
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/// A temp file no other writer shares: two threads of one process storing
|
|
50
|
+
/// the same artifact at once would otherwise write into one file, and a
|
|
51
|
+
/// reader could load the interleaved bytes the unsafe deserialize trusts.
|
|
52
|
+
pub(super) fn create_temp(&self, name: &OsStr) -> Option<(PathBuf, fs::File)> {
|
|
53
|
+
static NEXT_TEMP: AtomicU64 = AtomicU64::new(0);
|
|
54
|
+
let serial = NEXT_TEMP.fetch_add(1, Ordering::Relaxed);
|
|
55
|
+
let tmp = Path::new(name).with_extension(format!("tmp{}.{serial}", std::process::id()));
|
|
56
|
+
let flags =
|
|
57
|
+
OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC;
|
|
58
|
+
let fd = openat(&self.0, &tmp, flags, Mode::RUSR | Mode::WUSR).ok()?;
|
|
59
|
+
Some((tmp, fs::File::from(fd)))
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/// Move `tmp` over `name`, syncing the directory so the new name
|
|
63
|
+
/// survives a crash; whether it moved.
|
|
64
|
+
pub(super) fn rename(&self, tmp: &Path, name: &OsStr) -> bool {
|
|
65
|
+
let moved = renameat(&self.0, tmp, &self.0, name).is_ok();
|
|
66
|
+
if moved {
|
|
67
|
+
let _ = fsync(&self.0);
|
|
68
|
+
}
|
|
69
|
+
moved
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/// Each entry's name and when it was last modified, read without
|
|
73
|
+
/// following a link; one whose time cannot be read is left out.
|
|
74
|
+
pub(super) fn entries(&self) -> Vec<(OsString, SystemTime)> {
|
|
75
|
+
let Ok(mut entries) = Dir::read_from(&self.0) else {
|
|
76
|
+
return Vec::new();
|
|
77
|
+
};
|
|
78
|
+
let mut found = Vec::new();
|
|
79
|
+
while let Some(Ok(entry)) = entries.read() {
|
|
80
|
+
let name = entry.file_name();
|
|
81
|
+
let modified = statat(&self.0, name, AtFlags::SYMLINK_NOFOLLOW)
|
|
82
|
+
.ok()
|
|
83
|
+
.and_then(|stat| u64::try_from(stat.st_mtime).ok())
|
|
84
|
+
.map(|secs| UNIX_EPOCH + Duration::from_secs(secs));
|
|
85
|
+
if let Some(modified) = modified {
|
|
86
|
+
found.push((OsStr::from_bytes(name.to_bytes()).to_owned(), modified));
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
found
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
pub(super) fn remove(&self, name: &OsStr) {
|
|
93
|
+
let _ = unlinkat(&self.0, name, AtFlags::empty());
|
|
94
|
+
}
|
|
95
|
+
}
|
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
//! The cache directory on Windows, held open without sharing deletion, so it
|
|
2
|
+
//! is neither renamed nor replaced while held. An entry is reached by its path
|
|
3
|
+
//! beneath it, so each one opened is checked to stand in the held directory
|
|
4
|
+
//! itself; Windows lets anyone bypass traversal, so an entry is trusted only
|
|
5
|
+
//! as its directory is.
|
|
6
|
+
|
|
7
|
+
use std::ffi::{c_void, OsStr, OsString};
|
|
8
|
+
use std::fs;
|
|
9
|
+
use std::io;
|
|
10
|
+
use std::os::windows::ffi::{OsStrExt, OsStringExt};
|
|
11
|
+
use std::os::windows::fs::{MetadataExt, OpenOptionsExt};
|
|
12
|
+
use std::os::windows::io::AsRawHandle;
|
|
13
|
+
use std::path::{Path, PathBuf};
|
|
14
|
+
use std::ptr;
|
|
15
|
+
use std::sync::atomic::{AtomicU64, Ordering};
|
|
16
|
+
use std::time::SystemTime;
|
|
17
|
+
|
|
18
|
+
use windows_sys::Win32::Foundation::{
|
|
19
|
+
CloseHandle, LocalFree, ERROR_ALREADY_EXISTS, GENERIC_ALL, GENERIC_WRITE, HANDLE,
|
|
20
|
+
};
|
|
21
|
+
use windows_sys::Win32::Security::Authorization::{
|
|
22
|
+
ConvertSidToStringSidW, ConvertStringSecurityDescriptorToSecurityDescriptorW, GetSecurityInfo,
|
|
23
|
+
SDDL_REVISION_1, SE_FILE_OBJECT,
|
|
24
|
+
};
|
|
25
|
+
use windows_sys::Win32::Security::{
|
|
26
|
+
EqualSid, GetAce, GetTokenInformation, IsWellKnownSid, TokenUser, WinBuiltinAdministratorsSid,
|
|
27
|
+
WinLocalSystemSid, ACCESS_ALLOWED_ACE, ACL, DACL_SECURITY_INFORMATION,
|
|
28
|
+
OWNER_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR, PSID, SECURITY_ATTRIBUTES, TOKEN_QUERY,
|
|
29
|
+
TOKEN_USER,
|
|
30
|
+
};
|
|
31
|
+
use windows_sys::Win32::Storage::FileSystem::{
|
|
32
|
+
CreateDirectoryW, GetFinalPathNameByHandleW, DELETE, FILE_APPEND_DATA,
|
|
33
|
+
FILE_ATTRIBUTE_REPARSE_POINT, FILE_DELETE_CHILD, FILE_FLAG_BACKUP_SEMANTICS,
|
|
34
|
+
FILE_FLAG_OPEN_REPARSE_POINT, FILE_GENERIC_EXECUTE, FILE_GENERIC_READ, FILE_LIST_DIRECTORY,
|
|
35
|
+
FILE_NAME_NORMALIZED, FILE_READ_ATTRIBUTES, FILE_SHARE_READ, FILE_SHARE_WRITE,
|
|
36
|
+
FILE_WRITE_ATTRIBUTES, FILE_WRITE_DATA, FILE_WRITE_EA, READ_CONTROL, WRITE_DAC, WRITE_OWNER,
|
|
37
|
+
};
|
|
38
|
+
use windows_sys::Win32::System::SystemServices::ACCESS_ALLOWED_ACE_TYPE;
|
|
39
|
+
use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
|
|
40
|
+
|
|
41
|
+
/// Every right that changes what an object holds or who may change it.
|
|
42
|
+
const WRITE_RIGHTS: u32 = FILE_WRITE_DATA
|
|
43
|
+
| FILE_APPEND_DATA
|
|
44
|
+
| FILE_WRITE_EA
|
|
45
|
+
| FILE_DELETE_CHILD
|
|
46
|
+
| FILE_WRITE_ATTRIBUTES
|
|
47
|
+
| DELETE
|
|
48
|
+
| WRITE_DAC
|
|
49
|
+
| WRITE_OWNER
|
|
50
|
+
| GENERIC_WRITE
|
|
51
|
+
| GENERIC_ALL;
|
|
52
|
+
|
|
53
|
+
pub(super) struct PrivateDir {
|
|
54
|
+
path: PathBuf,
|
|
55
|
+
/// Held so the directory stays where it was checked.
|
|
56
|
+
_held: fs::File,
|
|
57
|
+
/// Where the directory stands, as each entry opened is compared to it.
|
|
58
|
+
resolved: PathBuf,
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
impl PrivateDir {
|
|
62
|
+
/// Create `dir` and the directories above it; `dir` itself takes a
|
|
63
|
+
/// protected DACL granting only the current user, SYSTEM, and the
|
|
64
|
+
/// Administrators, so no other local user can plant an artifact the
|
|
65
|
+
/// unsafe deserialize would trust.
|
|
66
|
+
pub(super) fn create(dir: &Path) -> io::Result<()> {
|
|
67
|
+
if let Some(parent) = dir.parent() {
|
|
68
|
+
fs::create_dir_all(parent)?;
|
|
69
|
+
}
|
|
70
|
+
let user = current_user()?;
|
|
71
|
+
let sddl = format!(
|
|
72
|
+
"D:P(A;OICI;FA;;;{})(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)",
|
|
73
|
+
user.string()?
|
|
74
|
+
);
|
|
75
|
+
let descriptor = Descriptor::from_sddl(&sddl)?;
|
|
76
|
+
let attributes = SECURITY_ATTRIBUTES {
|
|
77
|
+
nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
|
|
78
|
+
lpSecurityDescriptor: descriptor.0,
|
|
79
|
+
bInheritHandle: 0,
|
|
80
|
+
};
|
|
81
|
+
let wide = wide(dir.as_os_str());
|
|
82
|
+
// SAFETY: `wide` is NUL-terminated and `attributes` points at a
|
|
83
|
+
// descriptor that lives until the call returns.
|
|
84
|
+
if unsafe { CreateDirectoryW(wide.as_ptr(), &attributes) } != 0 {
|
|
85
|
+
return Ok(());
|
|
86
|
+
}
|
|
87
|
+
match io::Error::last_os_error() {
|
|
88
|
+
err if err.raw_os_error() == Some(ERROR_ALREADY_EXISTS as i32) => Ok(()),
|
|
89
|
+
err => Err(err),
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/// `dir`, once it upholds the trust the unsafe deserialize relies on: a
|
|
94
|
+
/// directory rather than a link in its place, owned by the current user,
|
|
95
|
+
/// and writable by no one else but SYSTEM and the Administrators, who may
|
|
96
|
+
/// write anything.
|
|
97
|
+
pub(super) fn open(dir: &Path) -> Option<Self> {
|
|
98
|
+
let held = fs::OpenOptions::new()
|
|
99
|
+
.access_mode(FILE_LIST_DIRECTORY | FILE_READ_ATTRIBUTES | READ_CONTROL)
|
|
100
|
+
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
|
|
101
|
+
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
|
|
102
|
+
.open(dir)
|
|
103
|
+
.ok()?;
|
|
104
|
+
let metadata = held.metadata().ok()?;
|
|
105
|
+
if !metadata.is_dir() || is_reparse_point(&metadata) || !trusted(&held) {
|
|
106
|
+
return None;
|
|
107
|
+
}
|
|
108
|
+
let resolved = resolved_path(&held)?;
|
|
109
|
+
Some(Self {
|
|
110
|
+
path: dir.to_path_buf(),
|
|
111
|
+
_held: held,
|
|
112
|
+
resolved,
|
|
113
|
+
})
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/// The entry `name`, opened without following a link as wasmtime opens a
|
|
117
|
+
/// file to map: readable and executable, its code mapped as such, and
|
|
118
|
+
/// shared only with readers, so its bytes stay as read while mapped. It
|
|
119
|
+
/// may also refresh its own time.
|
|
120
|
+
pub(super) fn open_entry(&self, name: &OsStr) -> Option<fs::File> {
|
|
121
|
+
let file = fs::OpenOptions::new()
|
|
122
|
+
.access_mode(FILE_GENERIC_READ | FILE_GENERIC_EXECUTE | FILE_WRITE_ATTRIBUTES)
|
|
123
|
+
.share_mode(FILE_SHARE_READ)
|
|
124
|
+
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
|
|
125
|
+
.open(self.path.join(name))
|
|
126
|
+
.ok()?;
|
|
127
|
+
let metadata = file.metadata().ok()?;
|
|
128
|
+
let beneath = resolved_path(&file)?.parent() == Some(self.resolved.as_path());
|
|
129
|
+
(metadata.is_file() && !is_reparse_point(&metadata) && beneath && trusted(&file))
|
|
130
|
+
.then_some(file)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/// A temp file no other writer shares: two threads of one process storing
|
|
134
|
+
/// the same artifact at once would otherwise write into one file, and a
|
|
135
|
+
/// reader could load the interleaved bytes the unsafe deserialize trusts.
|
|
136
|
+
pub(super) fn create_temp(&self, name: &OsStr) -> Option<(PathBuf, fs::File)> {
|
|
137
|
+
static NEXT_TEMP: AtomicU64 = AtomicU64::new(0);
|
|
138
|
+
let serial = NEXT_TEMP.fetch_add(1, Ordering::Relaxed);
|
|
139
|
+
let tmp = Path::new(name).with_extension(format!("tmp{}.{serial}", std::process::id()));
|
|
140
|
+
let file = fs::OpenOptions::new()
|
|
141
|
+
.write(true)
|
|
142
|
+
.create_new(true)
|
|
143
|
+
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
|
|
144
|
+
.open(self.path.join(&tmp))
|
|
145
|
+
.ok()?;
|
|
146
|
+
Some((tmp, file))
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/// Move `tmp` over `name`; whether it moved. One another process holds
|
|
150
|
+
/// open stays, as Windows refuses to replace it.
|
|
151
|
+
pub(super) fn rename(&self, tmp: &Path, name: &OsStr) -> bool {
|
|
152
|
+
fs::rename(self.path.join(tmp), self.path.join(name)).is_ok()
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/// Each entry's name and when it was last modified, read without
|
|
156
|
+
/// following a link; one whose time cannot be read is left out.
|
|
157
|
+
pub(super) fn entries(&self) -> Vec<(OsString, SystemTime)> {
|
|
158
|
+
let Ok(entries) = fs::read_dir(&self.path) else {
|
|
159
|
+
return Vec::new();
|
|
160
|
+
};
|
|
161
|
+
entries
|
|
162
|
+
.filter_map(Result::ok)
|
|
163
|
+
.filter_map(|entry| {
|
|
164
|
+
let modified = fs::symlink_metadata(entry.path()).ok()?.modified().ok()?;
|
|
165
|
+
Some((entry.file_name(), modified))
|
|
166
|
+
})
|
|
167
|
+
.collect()
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
pub(super) fn remove(&self, name: &OsStr) {
|
|
171
|
+
let _ = fs::remove_file(self.path.join(name));
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
fn is_reparse_point(metadata: &fs::Metadata) -> bool {
|
|
176
|
+
metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/// Where `file` stands once every link on its way is resolved.
|
|
180
|
+
fn resolved_path(file: &fs::File) -> Option<PathBuf> {
|
|
181
|
+
let handle = file.as_raw_handle() as HANDLE;
|
|
182
|
+
let mut buf = vec![0u16; 512];
|
|
183
|
+
loop {
|
|
184
|
+
// SAFETY: `buf` holds `buf.len()` wide characters for the call to fill.
|
|
185
|
+
let len = unsafe {
|
|
186
|
+
GetFinalPathNameByHandleW(
|
|
187
|
+
handle,
|
|
188
|
+
buf.as_mut_ptr(),
|
|
189
|
+
buf.len() as u32,
|
|
190
|
+
FILE_NAME_NORMALIZED,
|
|
191
|
+
)
|
|
192
|
+
} as usize;
|
|
193
|
+
match len {
|
|
194
|
+
0 => return None,
|
|
195
|
+
len if len < buf.len() => return Some(OsString::from_wide(&buf[..len]).into()),
|
|
196
|
+
len => buf.resize(len, 0),
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/// Whether only the user, SYSTEM, and the Administrators own `file` or hold
|
|
202
|
+
/// a right to change it, its inheritable entries included, as what they
|
|
203
|
+
/// grant reaches each entry created beneath. An owner may grant itself any
|
|
204
|
+
/// right, and an elevated process's objects are owned by the Administrators.
|
|
205
|
+
fn trusted(file: &fs::File) -> bool {
|
|
206
|
+
let Ok(user) = current_user() else {
|
|
207
|
+
return false;
|
|
208
|
+
};
|
|
209
|
+
let mut owner: PSID = ptr::null_mut();
|
|
210
|
+
let mut dacl: *mut ACL = ptr::null_mut();
|
|
211
|
+
let mut descriptor: PSECURITY_DESCRIPTOR = ptr::null_mut();
|
|
212
|
+
// SAFETY: each out-pointer is valid; `descriptor` owns the owner and the
|
|
213
|
+
// DACL, and is freed below.
|
|
214
|
+
let status = unsafe {
|
|
215
|
+
GetSecurityInfo(
|
|
216
|
+
file.as_raw_handle() as HANDLE,
|
|
217
|
+
SE_FILE_OBJECT,
|
|
218
|
+
OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
|
|
219
|
+
&mut owner,
|
|
220
|
+
ptr::null_mut(),
|
|
221
|
+
&mut dacl,
|
|
222
|
+
ptr::null_mut(),
|
|
223
|
+
&mut descriptor,
|
|
224
|
+
)
|
|
225
|
+
};
|
|
226
|
+
if status != 0 {
|
|
227
|
+
return false;
|
|
228
|
+
}
|
|
229
|
+
let descriptor = Descriptor(descriptor);
|
|
230
|
+
// SAFETY: `owner` and `dacl` point into `descriptor`, alive for the scope.
|
|
231
|
+
let trusted =
|
|
232
|
+
unsafe { user.permits(owner) && !dacl.is_null() && grants_write_only_to(dacl, &user) };
|
|
233
|
+
drop(descriptor);
|
|
234
|
+
trusted
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/// Whether every allowing entry of `dacl` that grants a right to change the
|
|
238
|
+
/// object names the user, SYSTEM, or the Administrators.
|
|
239
|
+
///
|
|
240
|
+
/// # Safety
|
|
241
|
+
///
|
|
242
|
+
/// `dacl` must point at a valid ACL.
|
|
243
|
+
unsafe fn grants_write_only_to(dacl: *mut ACL, user: &User) -> bool {
|
|
244
|
+
for index in 0..unsafe { (*dacl).AceCount } {
|
|
245
|
+
let mut ace: *mut c_void = ptr::null_mut();
|
|
246
|
+
// SAFETY: `index` is below the ACL's count.
|
|
247
|
+
if unsafe { GetAce(dacl, u32::from(index), &mut ace) } == 0 {
|
|
248
|
+
return false;
|
|
249
|
+
}
|
|
250
|
+
let allowed = ace.cast::<ACCESS_ALLOWED_ACE>();
|
|
251
|
+
// SAFETY: every ACE starts with its header; an allowing one carries
|
|
252
|
+
// its mask and SID after it.
|
|
253
|
+
let (kind, mask) = unsafe { ((*allowed).Header.AceType, (*allowed).Mask) };
|
|
254
|
+
if u32::from(kind) != ACCESS_ALLOWED_ACE_TYPE || mask & WRITE_RIGHTS == 0 {
|
|
255
|
+
continue;
|
|
256
|
+
}
|
|
257
|
+
let sid: PSID = unsafe { ptr::addr_of_mut!((*allowed).SidStart).cast() };
|
|
258
|
+
// SAFETY: `sid` is the SID the allowing entry holds.
|
|
259
|
+
if !unsafe { user.permits(sid) } {
|
|
260
|
+
return false;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
true
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/// The current process's user, as its token names it.
|
|
267
|
+
struct User(Vec<u8>);
|
|
268
|
+
|
|
269
|
+
impl User {
|
|
270
|
+
fn sid(&self) -> PSID {
|
|
271
|
+
// SAFETY: the buffer holds a `TOKEN_USER` whose SID points within it.
|
|
272
|
+
unsafe { (*self.0.as_ptr().cast::<TOKEN_USER>()).User.Sid }
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/// Whether `sid` is the user, SYSTEM, or the Administrators.
|
|
276
|
+
///
|
|
277
|
+
/// # Safety
|
|
278
|
+
///
|
|
279
|
+
/// `sid` must point at a valid SID.
|
|
280
|
+
unsafe fn permits(&self, sid: PSID) -> bool {
|
|
281
|
+
unsafe {
|
|
282
|
+
EqualSid(sid, self.sid()) != 0
|
|
283
|
+
|| IsWellKnownSid(sid, WinLocalSystemSid) != 0
|
|
284
|
+
|| IsWellKnownSid(sid, WinBuiltinAdministratorsSid) != 0
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/// The SID as SDDL writes it.
|
|
289
|
+
fn string(&self) -> io::Result<String> {
|
|
290
|
+
let mut text = ptr::null_mut();
|
|
291
|
+
// SAFETY: `text` receives a buffer freed below.
|
|
292
|
+
if unsafe { ConvertSidToStringSidW(self.sid(), &mut text) } == 0 {
|
|
293
|
+
return Err(io::Error::last_os_error());
|
|
294
|
+
}
|
|
295
|
+
// SAFETY: `text` is NUL-terminated.
|
|
296
|
+
let len = (0..).take_while(|&i| unsafe { *text.add(i) } != 0).count();
|
|
297
|
+
let string = String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(text, len) });
|
|
298
|
+
unsafe { LocalFree(text.cast()) };
|
|
299
|
+
Ok(string)
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
fn current_user() -> io::Result<User> {
|
|
304
|
+
let mut token: HANDLE = ptr::null_mut();
|
|
305
|
+
// SAFETY: `token` receives a handle closed below.
|
|
306
|
+
if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 {
|
|
307
|
+
return Err(io::Error::last_os_error());
|
|
308
|
+
}
|
|
309
|
+
let mut len = 0;
|
|
310
|
+
// SAFETY: a first call with no buffer answers the length it needs.
|
|
311
|
+
unsafe { GetTokenInformation(token, TokenUser, ptr::null_mut(), 0, &mut len) };
|
|
312
|
+
let mut buf = vec![0u8; len as usize];
|
|
313
|
+
// SAFETY: `buf` holds `len` bytes.
|
|
314
|
+
let filled =
|
|
315
|
+
unsafe { GetTokenInformation(token, TokenUser, buf.as_mut_ptr().cast(), len, &mut len) };
|
|
316
|
+
let result = match filled {
|
|
317
|
+
0 => Err(io::Error::last_os_error()),
|
|
318
|
+
_ => Ok(User(buf)),
|
|
319
|
+
};
|
|
320
|
+
unsafe { CloseHandle(token) };
|
|
321
|
+
result
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/// A security descriptor Windows allocated, freed once dropped.
|
|
325
|
+
struct Descriptor(PSECURITY_DESCRIPTOR);
|
|
326
|
+
|
|
327
|
+
impl Descriptor {
|
|
328
|
+
fn from_sddl(sddl: &str) -> io::Result<Self> {
|
|
329
|
+
let wide = wide(OsStr::new(sddl));
|
|
330
|
+
let mut descriptor = ptr::null_mut();
|
|
331
|
+
// SAFETY: `wide` is NUL-terminated; `descriptor` receives a buffer
|
|
332
|
+
// the drop frees.
|
|
333
|
+
let made = unsafe {
|
|
334
|
+
ConvertStringSecurityDescriptorToSecurityDescriptorW(
|
|
335
|
+
wide.as_ptr(),
|
|
336
|
+
SDDL_REVISION_1,
|
|
337
|
+
&mut descriptor,
|
|
338
|
+
ptr::null_mut(),
|
|
339
|
+
)
|
|
340
|
+
};
|
|
341
|
+
match made {
|
|
342
|
+
0 => Err(io::Error::last_os_error()),
|
|
343
|
+
_ => Ok(Self(descriptor)),
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
impl Drop for Descriptor {
|
|
349
|
+
fn drop(&mut self) {
|
|
350
|
+
if !self.0.is_null() {
|
|
351
|
+
// SAFETY: Windows allocated the descriptor with `LocalAlloc`.
|
|
352
|
+
unsafe { LocalFree(self.0) };
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
fn wide(text: &OsStr) -> Vec<u16> {
|
|
358
|
+
text.encode_wide().chain(Some(0)).collect()
|
|
359
|
+
}
|