diff --git a/.github/lsan.supp b/.github/lsan.supp new file mode 100644 index 0000000..4d985e3 --- /dev/null +++ b/.github/lsan.supp @@ -0,0 +1,6 @@ +# Facts that live for the whole process are built once, inside a OnceLock, and +# leaked on purpose so readers get `&'static` values: text in `os::keep`, the +# OS records in `os::from_facts`. A unit test that builds one directly drops +# the only reference, which LeakSanitizer reports. +leak:sys_lib::os::keep +leak:sys_lib::os::from_facts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1cca18e..bb3d0fd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -262,6 +262,49 @@ jobs: MIRIFLAGS: "-Zmiri-disable-isolation" PROPTEST_CASES: "16" + asan: + name: AddressSanitizer (${{ matrix.name }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + include: + - name: Linux + os: ubuntu-latest + target: x86_64-unknown-linux-gnu + leaks: "1" + # LeakSanitizer does not run on macOS. + - name: macOS + os: macos-latest + target: aarch64-apple-darwin + leaks: "0" + steps: + - uses: actions/checkout@v5 + - uses: dtolnay/rust-toolchain@nightly + - uses: Swatinem/rust-cache@v2 + with: + key: asan + # Readable leak stacks, which the suppressions in .github/lsan.supp + # match against. + - name: Find a symbolizer + if: runner.os == 'Linux' + run: | + s=$(command -v llvm-symbolizer || ls /usr/bin/llvm-symbolizer-* 2>/dev/null | sort -V | tail -1) + test -n "$s" + echo "ASAN_SYMBOLIZER_PATH=$s" >> "$GITHUB_ENV" + # Every test, the FFI backends included, with each allocation and + # access checked (threat T12). Naming the target keeps build scripts + # out of the instrumented build. Allocation stacks are unwound from + # debug information: std is built without frame pointers, so the fast + # unwinder drops the frame that called into it. + - name: Tests under AddressSanitizer + run: cargo test --target ${{ matrix.target }} --all-features --lib --tests + env: + RUSTFLAGS: "-Zsanitizer=address" + ASAN_OPTIONS: "detect_leaks=${{ matrix.leaks }}:detect_stack_use_after_return=1:fast_unwind_on_malloc=0" + LSAN_OPTIONS: "suppressions=${{ github.workspace }}/.github/lsan.supp:print_suppressions=1" + PROPTEST_CASES: "32" + # A DLL in the import table that a stripped-down Windows lacks stops the whole # program before `main`, so a real binary runs where the fewest DLLs exist. nanoserver: diff --git a/.github/workflows/fuzz-round.yml b/.github/workflows/fuzz-round.yml new file mode 100644 index 0000000..8a1443d --- /dev/null +++ b/.github/workflows/fuzz-round.yml @@ -0,0 +1,84 @@ +name: Fuzz round + +# One round of the long fuzz run (fuzz.yml, `rounds` input): every target for +# `seconds`, starting from the corpus the previous round left in the cache. +on: + workflow_call: + inputs: + seconds: + type: string + required: true + round: + type: string + required: true + +env: + FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true" + +jobs: + fuzz: + name: Round ${{ inputs.round }} (${{ matrix.target }}) + runs-on: ubuntu-latest + timeout-minutes: 345 + strategy: + fail-fast: false + # Eight at a time, so the long run leaves runners for other work. + max-parallel: 8 + matrix: + target: + - os_release + - release + - version + - cpu_list + - cpuinfo + - cpu_name + - proc_status + - mountinfo + - cgroup + - pid_file + - instance_id + - bytes_display + - procfs + - smbios + - uevent + - resolv + - utmp + - windows_zones + - fingerprint + - pci_ids + steps: + - uses: actions/checkout@v5 + - uses: dtolnay/rust-toolchain@nightly + - uses: Swatinem/rust-cache@v2 + with: + workspaces: fuzz + key: ${{ matrix.target }} + - name: Install cargo-fuzz + uses: taiki-e/install-action@v2 + with: + tool: cargo-fuzz + - name: Restore the corpus + uses: actions/cache/restore@v4 + with: + path: fuzz/corpus/${{ matrix.target }} + key: corpus-${{ matrix.target }}-${{ github.run_id }}-${{ inputs.round }} + restore-keys: corpus-${{ matrix.target }}- + - name: Fuzz + run: | + mkdir -p "fuzz/corpus/${{ matrix.target }}" + echo "corpus: $(ls "fuzz/corpus/${{ matrix.target }}" | wc -l) inputs" + cargo fuzz run --target x86_64-unknown-linux-gnu ${{ matrix.target }} \ + "fuzz/corpus/${{ matrix.target }}" tests/fixtures -- \ + -max_total_time=${{ inputs.seconds }} -print_final_stats=1 + - name: Save the corpus + if: always() + uses: actions/cache/save@v4 + with: + path: fuzz/corpus/${{ matrix.target }} + key: corpus-${{ matrix.target }}-${{ github.run_id }}-${{ inputs.round }} + - uses: actions/upload-artifact@v5 + if: failure() + with: + name: crash-round${{ inputs.round }}-${{ matrix.target }} + path: fuzz/artifacts/ + retention-days: 30 diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index dc3429a..a9c4ce3 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -1,8 +1,10 @@ name: Fuzz -# Ten minutes per parser every night (dev/PLAN.md section 19.1); 24 hours per -# target is run by hand before 0.8. Crashes are uploaded as artifacts and fixed -# test-first (fuzz/README.md). +# Ten minutes per parser every night (dev/PLAN.md section 19.1). The long runs +# before a release (`long`): 24 hours of fuzzing per target, as five chained +# rounds of fuzz-round.yml, each starting from the corpus the last one saved, +# and the soak run (bench/src/bin/soak.rs) for as long as a hosted job may run. +# Crashes are uploaded as artifacts and fixed test-first (fuzz/README.md). on: schedule: - cron: "17 3 * * *" @@ -11,6 +13,10 @@ on: seconds: description: Seconds per target default: "600" + long: + description: 24 hours per target in five rounds, and the soak runs + type: boolean + default: false env: FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true" @@ -18,6 +24,7 @@ env: jobs: fuzz: name: Fuzz (${{ matrix.target }}) + if: ${{ !inputs.long }} runs-on: ubuntu-latest strategy: fail-fast: false @@ -42,6 +49,7 @@ jobs: - utmp - windows_zones - fingerprint + - pci_ids steps: - uses: actions/checkout@v5 - uses: dtolnay/rust-toolchain@nightly @@ -66,3 +74,59 @@ jobs: name: crash-${{ matrix.target }} path: fuzz/artifacts/ retention-days: 30 + + round1: + if: ${{ inputs.long }} + uses: ./.github/workflows/fuzz-round.yml + with: + seconds: "17400" + round: "1" + + round2: + needs: round1 + if: ${{ !cancelled() && inputs.long }} + uses: ./.github/workflows/fuzz-round.yml + with: + seconds: "17400" + round: "2" + + round3: + needs: round2 + if: ${{ !cancelled() && inputs.long }} + uses: ./.github/workflows/fuzz-round.yml + with: + seconds: "17400" + round: "3" + + round4: + needs: round3 + if: ${{ !cancelled() && inputs.long }} + uses: ./.github/workflows/fuzz-round.yml + with: + seconds: "17400" + round: "4" + + round5: + needs: round4 + if: ${{ !cancelled() && inputs.long }} + uses: ./.github/workflows/fuzz-round.yml + with: + seconds: "17400" + round: "5" + + soak: + name: Soak (${{ matrix.os }}) + if: ${{ inputs.long }} + runs-on: ${{ matrix.os }} + timeout-minutes: 355 + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + steps: + - uses: actions/checkout@v5 + - uses: dtolnay/rust-toolchain@stable + - name: Soak, 5 h 40 min (the hosted job limit is 6 h) + working-directory: bench + shell: bash + run: cargo run --release --bin soak -- 20400 diff --git a/CHANGELOG.md b/CHANGELOG.md index 81dd6ae..0d37c44 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,60 @@ --- +## [0.8.0] - 2026-12-02 + +Hardening: every threat in the model has a named attack test, the process +guard is as strict on Windows as on Unix, and the release went through a +24-hour fuzz run per parser and a soak run. + +### Added + +- `docs/SECURITY.md`: what the crate guarantees, every threat with its + defence, its cost, and its test, and how to report a vulnerability. +- An AddressSanitizer job on Linux and macOS that runs every test. +- A soak run (`bench/src/bin/soak.rs`) that calls every reading in a loop and + fails if memory or open descriptors grow, and the long runs before a release + (`fuzz.yml` with `long`: 24 hours per fuzz target, and the soak run). + +### Changed + +- **Windows process guard:** a missing lock directory is created for this + account, `SYSTEM`, and `Administrators` alone, and a lock directory another + account can change is refused, as group- or world-writable directories are + on Unix. A program that used a directory under `C:\ProgramData` directly + must move its lock to a private directory. The default directory is created + the same way. +- `Error::AlreadyRunning` names a pid only when that process is running and + started before its pid file was written; otherwise the pid is `None`. It + never names a process that cannot be the other copy. +- `mem::total()`, `mem::host_total()`, and `mem::limit()` read only what they + return: no VM counters for a total, and on Linux no soft or swap limit files + for the total. macOS and FreeBSD read the installed memory once. +- macOS memory and CPU readings no longer fetch and return the host port on + every call, and `device::id` finds the platform device by path instead of + searching the registry. +- The minimum Windows is 10 version 1511, or Server 2016. +- Requires path-lib 1.3 (with the `guard` feature). + +### Fixed + +- Windows disk busy time no longer reads 0% for a while after the clock is set + back, or one spike after it is set forward. +- Error codes are read straight after the call that failed, and calls that set + none (`getloadavg`, `localtime_r`, a `proc_listallpids` or `proc_pidinfo` + answer of 0) report `Malformed` instead of a stale or zero code. +- FreeBSD `disk::io_totals()` asks again when a disk comes or goes during the + read, instead of failing once. +- A Windows drive whose product string has no terminator no longer carries the + next fields into the drive's name, and only a cloud's fixed asset tag is kept + from the firmware table. +- The message for a user without a home directory had stray spaces. +- A very long CPU name, such as a crafted `model name` in a container's + `/proc/cpuinfo`, no longer takes seconds to minutes to clean: names are cut + to 256 bytes first. Real ones are at most 48. + +--- + ## [0.7.0] - 2026-11-11 Optimisation: every reading measured against the crates people use for it, the @@ -406,7 +460,8 @@ The scaffold and the plan. No functional code yet. `dev/ROADMAP.md`. - `tests/fixtures/` and `fuzz/` skeletons. -[Unreleased]: https://github.com/jamesgober/sys-lib/compare/v0.7.0...HEAD +[Unreleased]: https://github.com/jamesgober/sys-lib/compare/v0.8.0...HEAD +[0.8.0]: https://github.com/jamesgober/sys-lib/compare/v0.7.0...v0.8.0 [0.7.0]: https://github.com/jamesgober/sys-lib/compare/v0.6.0...v0.7.0 [0.6.0]: https://github.com/jamesgober/sys-lib/compare/v0.5.1...v0.6.0 [0.5.1]: https://github.com/jamesgober/sys-lib/compare/v0.5.0...v0.5.1 diff --git a/Cargo.toml b/Cargo.toml index ec33ab3..f3f0ee7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ # ============================================================================= [package] name = "sys-lib" -version = "0.7.0" +version = "0.8.0" # Minimum Supported Rust Version (MSRV) # 1.89: `std::fs::File::lock` and `File::try_lock` are stable from 1.89.0, so @@ -103,7 +103,7 @@ device-id = ["dep:crypt-io"] clock-lib = { version = "1.1", optional = true, default-features = false, features = ["std"] } crypt-io = { version = "1.2.2", optional = true, default-features = false, features = ["std", "mac-blake3", "zeroize"] } id-forge = { version = "1.0", optional = true, default-features = false, features = ["ulid"] } -path-lib = { version = "1.0", optional = true } +path-lib = { version = "1.3", optional = true } # DEV DEPENDENCIES @@ -129,6 +129,7 @@ windows-sys = { version = "0.61", features = [ "Win32_NetworkManagement_Ndis", "Win32_Networking_WinSock", "Win32_Security", + "Win32_Security_Authorization", "Win32_System_Diagnostics_Debug", "Win32_System_Diagnostics_ToolHelp", "Win32_System_LibraryLoader", diff --git a/README.md b/README.md index 6469cef..0b00e0e 100644 --- a/README.md +++ b/README.md @@ -9,9 +9,10 @@
Crates.io Downloads - docs.rs + Documentation CI MSRV + License

@@ -29,7 +30,7 @@ MSRV is 1.89+ (Rust 2024 edition). unsafe is denied at the crate root and allowed only in one OS module per platform.

- Status: 0.7.0, feature complete and measured. The boot kit, the live readings (memory, CPU, disks, network, pressure, this process), detection and identity (virtualization, form factor, topology, power, DNS, the time zone, firmware, launch context, summary(), an application-scoped device id), and now the server readiness, benchmark environment, and security posture reports, temperatures, graphics adapters, and explicit roots for monitoring agents. Linux (64-bit, and 32-bit glibc on x86 and Arm), macOS, Windows, and FreeBSD; Android and iOS best effort. 0.7 measured every reading against the crates people use for it (docs/PERFORMANCE.md); 0.8 to 1.0 harden; the API is in docs/API.md. Design: dev/PLAN.md; schedule: dev/ROADMAP.md. + Status: 0.8.0, feature complete, measured, and hardened. The boot kit, the live readings (memory, CPU, disks, network, pressure, this process), detection and identity (virtualization, form factor, topology, power, DNS, the time zone, firmware, launch context, summary(), an application-scoped device id), and now the server readiness, benchmark environment, and security posture reports, temperatures, graphics adapters, and explicit roots for monitoring agents. Linux (64-bit, and 32-bit glibc on x86 and Arm), macOS, Windows, and FreeBSD; Android and iOS best effort. 0.7 measured every reading against the crates people use for it (docs/PERFORMANCE.md); 0.8 hardened it, with every threat and its test in docs/SECURITY.md; the API is in docs/API.md. Design: dev/PLAN.md; schedule: dev/ROADMAP.md.
@@ -40,15 +41,22 @@ Static facts read once and cached (OS name and version, CPU model, core counts, CPU features, caches, topology, virtualization, form factor); live readings read fresh on every call with no allocation for single values (memory, swap, uptime, load, disk space, this process's memory and CPU time); caller-owned samplers for values that need two readings (CPU usage, network rates); the boot kit (build info, instance info, process guard); and an opt-in device id derived with a keyed hash, so raw hardware identifiers never leave the library. It does not read other processes' details, change system settings, or run in the background; the few readings that walk the process table (`host::processes()` on macOS and FreeBSD, `process::threads()` on Windows) say so and their cost. -## Quick start +## Installation Cargo's rename makes the crate `sys` in your code: ```toml [dependencies] -sys = { package = "sys-lib", version = "0.7" } +sys = { package = "sys-lib", version = "0.8" } + +# The application-scoped device id (brings crypt-io's BLAKE3 stack): +sys = { package = "sys-lib", version = "0.8", features = ["device-id"] } ``` +The default features are `instance` (instance info) and `guard` (the process guard). `default-features = false` keeps every reading and report and brings no dependency at all. + +## Quick start + Tier 1 is one plain call per fact. Static facts are read once and cached, so every later call costs about a nanosecond: diff --git a/bench/src/bin/soak.rs b/bench/src/bin/soak.rs new file mode 100644 index 0000000..cc682a0 --- /dev/null +++ b/bench/src/bin/soak.rs @@ -0,0 +1,90 @@ +//! The soak run (dev/PLAN.md section 19, threat T12): every reading in a loop +//! for `seconds` (default 600), with this process's resident memory and open +//! descriptors (handles on Windows) sampled every 30 s. After the first tenth of +//! the run, neither may grow: descriptors not at all, memory by at most 10% +//! plus 4 MiB (allocator noise). Exits 1 when either grows. +//! +//! `cargo run --release --bin soak -- 28800` for the 8 hours of the release +//! checklist. + +use std::{ + process::ExitCode, + time::{Duration, Instant}, +}; + +use sys_lib as sys; + +fn every_reading(cpu: &mut sys::cpu::Sampler, disk: &mut sys::disk::IoSampler, net: &mut sys::net::Sampler) { + let _ = (sys::os::info(), sys::os::is_64bit(), sys::os::form_factor()); + let _ = (sys::cpu::count(), sys::cpu::name(), sys::cpu::topology()); + let _ = (sys::cpu::load(), sys::cpu::times(), sys::cpu::frequency()); + let _ = (sys::cpu::current_frequency(), sys::cpu::quota(), sys::cpu::pressure()); + let _ = (sys::mem::snapshot(), sys::mem::activity(), sys::mem::events()); + let _ = (sys::mem::huge_pages(), sys::mem::modules(), sys::mem::pressure()); + let _ = (sys::mem::total(), sys::mem::limit(), sys::mem::host_total()); + let _ = (sys::disk::list(), sys::disk::of("."), sys::disk::space(".")); + let _ = (sys::disk::io_totals(), sys::disk::io_counters(), sys::disk::pressure()); + let _ = (sys::net::interfaces(), sys::net::totals(), sys::net::counters()); + let _ = (sys::net::connections(), sys::net::primary(), sys::net::dns()); + let _ = (sys::host::name(), sys::host::uptime(), sys::host::processes()); + let _ = (sys::host::open_files(), sys::host::timezone(), sys::host::sessions()); + let _ = (sys::host::clock_sync(), sys::host::model(), sys::host::firmware()); + let _ = (sys::process::user(), sys::process::is_elevated(), sys::process::limits()); + let _ = (sys::process::memory_detail(), sys::process::cpu_time(), sys::process::io()); + let _ = (sys::process::threads(), sys::process::launch()); + let _ = (sys::virt::detect(), sys::virt::cloud()); + let _ = (sys::power::batteries(), sys::power::on_ac()); + let _ = (sys::sensors::temperatures(), sys::gpu::list()); + let _ = (sys::security::posture(), sys::bench::environment(), sys::summary()); + let _ = sys::readiness::report_for(sys::readiness::Profile::Database, "."); + let _ = (sys::device::id("com.example.soak"), sys::device::report()); + let _ = (cpu.sample(), disk.sample(), net.sample()); +} + +/// Resident bytes and open descriptors now. +fn usage() -> (u64, usize) { + let resident = sys::process::memory().map_or(0, |b| b.raw()); + let files = sys::process::open_files().unwrap_or(0); + (resident, files) +} + +fn main() -> ExitCode { + let seconds: u64 = std::env::args().nth(1).and_then(|s| s.parse().ok()).unwrap_or(600); + let run = Duration::from_secs(seconds); + let warm = run / 10; + let every = Duration::from_secs(30).min(run / 20).max(Duration::from_secs(1)); + let (mut cpu, mut disk, mut net) = ( + sys::cpu::Sampler::new().expect("a CPU sampler"), + sys::disk::IoSampler::new().expect("a disk sampler"), + sys::net::Sampler::new().expect("a network sampler"), + ); + let start = Instant::now(); + let mut next = start; + let (mut calls, mut base, mut worst) = (0u64, (0u64, 0usize), (0u64, 0usize)); + println!("{:>8} {:>10} {:>12} {:>6}", "seconds", "calls", "resident", "files"); + while start.elapsed() < run { + every_reading(&mut cpu, &mut disk, &mut net); + calls += 1; + if Instant::now() >= next { + next += every; + let (resident, files) = usage(); + println!("{:>8} {calls:>10} {resident:>12} {files:>6}", start.elapsed().as_secs()); + if start.elapsed() < warm { + base = (base.0.max(resident), base.1.max(files)); + } else { + worst = (worst.0.max(resident), worst.1.max(files)); + } + } + } + let limit = base.0 + base.0 / 10 + (4 << 20); + println!( + "warm-up peak: {} bytes, {} files; after: {} bytes, {} files; {calls} rounds of every reading", + base.0, base.1, worst.0, worst.1 + ); + if worst.1 > base.1 || worst.0 > limit { + println!("GROWTH: memory above {limit} bytes or descriptors above {}", base.1); + return ExitCode::FAILURE; + } + println!("no growth"); + ExitCode::SUCCESS +} diff --git a/dev/PLAN.md b/dev/PLAN.md index 3218a4f..d288aaf 100644 --- a/dev/PLAN.md +++ b/dev/PLAN.md @@ -765,7 +765,7 @@ Attackers: a local unprivileged user; a hostile container image or orchestrator | T2 | cross-application correlation of device ids | keyed hash with an application-derived key; optional secret | two app ids on one fixture: Hamming distance over many pairs averages about 61 of 122 bits; secret changes the id | one key derivation, under 0.5 µs [est.] | | T3 | device id used as authentication, then spoofed | documentation; no API implying verification; `AdminReset` as a change event | doc test asserts the warning paragraph; API review checklist | none | | T4 | path or value injection through the environment (`TZ=../../etc/shadow`, hostile `LANG`, a `HOST_PROC`-style redirect) | no root overrides from the environment; `TZ`, `LC_*`, `LANG` validated and never used to open files; guard and interface names validated | hostile values set: no file outside the fixed list is opened (the fixture root records every path), values rejected or ignored | under 50 ns per validation [est.] | -| T5 | TOCTOU on `/proc` (pid reuse, files changing between reads) | only `/proc/self` and `/proc/1`; one open per file, read to EOF; combined values clamped to invariants | fixture backend changing values between reads; invariants hold for every interleaving | clamping under 5 ns | +| T5 | TOCTOU on `/proc` (pid reuse, files changing between reads) | only `/proc/self` and `/proc/1`, and the guard's one read of a lock holder's start time, checked against its pid file (D-112); one open per file, read to EOF; combined values clamped to invariants | fixture backend changing values between reads; invariants hold for every interleaving | clamping under 5 ns | | T6 | untrusted `/proc` and `/sys` in containers (huge or negative numbers, binary junk, enormous files) | safe, bounded, checked parsers, no recursion, fuzzed | fuzz target per parser; proptest "never panics, never exceeds budget"; fixtures with `u64::MAX`, negatives, NUL bytes, 10 MB files | none measurable | | T7 | resource exhaustion through huge files or lists (100 000 mounts, 4 096 CPUs) | per-file budget 1 MiB; list budgets (mounts 4 096, interfaces 4 096, CPUs 16 384) checked before allocation; `TooLarge` | fixtures one over each budget: `TooLarge`, allocation within budget (counting allocator) | none in the normal case | | T8 | hangs on dead network filesystems or removable drives | network filesystems skipped by default; `SEM_FAILCRITICALERRORS` around Windows volume calls | Linux CI with an unreachable NFS mount: `disk::list()` within 100 ms; Windows empty removable drive: no dialog | none | @@ -1276,3 +1276,12 @@ Other ideas: | D-109 | 2026-11-11 | `disk::of` (and the readiness and posture lookups) stream mountinfo, keeping only the best match, bounded by 16 MiB read; the entry budget stays on `disk::list` | the whole table counted against `max_mounts`, so past 4 096 mounts (a busy Kubernetes node) a lookup that needs one entry failed | | D-110 | 2026-11-11 | The readiness report's data-directory filesystem check shows the filesystem only, and `Display` prints control characters in found values as `?` | the mount source can name a server, an account, or a volume GUID, in a report made to be logged; a source with a line break forged report rows | | D-111 | 2026-11-11 | Windows reads the host name once per process | `GetComputerNameExW` reads the registry (about 100 µs on a busy host) and a new name takes effect only at restart | +| D-112 | 2026-11-29 | `AlreadyRunning { pid }` names a pid only when that process is running and started no later than the pid file was written (2 s slack); otherwise the file is read again up to 5 times 10 ms apart, then `None` | the holder writes its pid after it locks, a pid file can be left by an earlier run, and pids are reused: a pid that cannot be the holder must never be offered to an operator who will stop it. Reading another process's start time (`/proc//stat`, `proc_pidinfo`, `kern.proc.pid`, `GetProcessTimes`) is the one read of another process, and only on this refusal path | +| D-113 | 2026-11-29 | On Windows a missing lock directory is created with a protected access list for this account, `SYSTEM`, and `Administrators`, and every lock directory must pass path-lib's `check_owner` with `Others::MayRead`; the default directory comes from `ensure_private` (path-lib 1.3) | the Unix mode and owner checks had no Windows counterpart: under `ProgramData` any local user could create the lock file first, refuse every start, or write the pid an operator is told to stop | +| D-114 | 2026-11-29 | `MemWant` gains `free` (the host's free and available counters) and `detail` (the soft and swap limits); `mem::total()`, `host_total()`, and `limit()` ask only for what they return, and macOS and FreeBSD read the installed memory once | each Tier 1 reading performs only the reads it needs: the total needed no VM counters (and failed in a sandbox that refuses them), and Linux read one more file per cgroup ancestor for limits it then dropped | +| D-115 | 2026-11-29 | Windows disk busy time keeps its clock origin while `QueryTime` runs with the uptime, and re-anchors when the two part by more than 1 s | `QueryTime` is the wall clock: a step back of S read 0% busy until S of real busy time had passed, a step forward one spike; the origin keeps the exact driver timestamps in the normal case | +| D-116 | 2026-11-29 | The minimum Windows is 10 version 1511 and Server 2016; `IsWow64Process2` and the Windows 8 calls stay linked, not looked up | Rust's own standard library needs Windows 10, the 1507 release (LTSB 2015) is out of support, and a run-time lookup per call adds code for no supported system | +| D-117 | 2026-11-29 | `cpu::available()` on Windows counts every processor of each group a process spans | Windows has no call for a process's per-group affinity; a process restricted to part of several groups (a job object's group affinity) may be over-counted, documented in PLATFORM-NOTES | +| D-118 | 2026-11-29 | The owners of CoreFoundation, IOKit, and Mach objects (`Cf::new`, `Cf::lent`, `Io::new`, `Io::matching`, `SendRight::from_raw`, `ProcessorInfo::from_raw`) are `unsafe fn` with a `# Safety` section | they release or read whatever they are given; a Get-rule reference passed to `Cf::new` would compile without `unsafe` and be released twice | +| D-119 | 2026-11-29 | The 24-hour fuzz run is five chained rounds on GitHub's runners (`fuzz.yml`, `long`), eight targets at a time, each round starting from the corpus the last saved | a hosted job stops at 6 hours; eight at a time (about 60 hours for the whole run) leaves runners for every other repository's CI | +| D-120 | 2026-11-29 | macOS keeps the host name port for the life of the process (fetched again in a child after `fork`), and reads the device anchors from the service plane's root by path, matching by class only when that fails | `mach_host_self` and the `mach_port_deallocate` that returns its reference were two traps in every memory and CPU reading; `IOServiceGetMatchingService` searches the registry where a path lookup goes straight to the platform device, which is the gap to machine-uid in `docs/PERFORMANCE.md` | diff --git a/dev/ROADMAP.md b/dev/ROADMAP.md index 10e4564..171ef64 100644 --- a/dev/ROADMAP.md +++ b/dev/ROADMAP.md @@ -86,12 +86,12 @@ Exit: every target in `PLAN.md` section 18 measured and published; at least 20% ## v0.8.0 - Hardening Exit: no open finding; every threat has a passing attack test. -- [ ] The remaining items of the independent review of 0.6.0 (tracked with the review). -- [ ] The readings marked open in `docs/PERFORMANCE.md`, macOS `device::id` and `mem::snapshot` first. -- [ ] Fuzzing: 24 hours per target with no finding open (the new parsers included: diskstats, vmstat, PSI, resolv.conf, utmp, sysctl text, SMBIOS types 0, 2, 17). -- [ ] Attack tests for T1 to T16 complete; `docs/SECURITY.md` with the cost of each defence. -- [ ] Soak: 8 hours, no growth in memory, descriptors, handles, CF references. -- [ ] AddressSanitizer job on Linux and macOS clean; the `hostile` fixture passes every function without panic. +- [x] The guard, memory, error-code, and Windows hardening items left from 0.7 (D-112 to D-118). +- [ ] The readings marked open in `docs/PERFORMANCE.md`, macOS `device::id` and `mem::snapshot` first: macOS `mem::snapshot()` went from 0.3x to 0.8x and `device::id` from 11.5 to 8.6 µs (D-120), and Linux `disk::list()` now clears the bar; the rest stay open in `docs/PERFORMANCE.md` and are carried into the pre-1.0 pass. +- [x] Fuzzing: 24 hours per target with no finding open (the new parsers included: diskstats, vmstat, PSI, resolv.conf, utmp, sysctl text, SMBIOS types 0, 2, 17). All 20 targets, about 190 billion inputs, no crash; the one finding (quadratic cleaning of long CPU names) fixed with a test and fuzzed again (results in `docs/SECURITY.md`). +- [x] Attack tests for T1 to T16 complete; `docs/SECURITY.md` with the cost of each defence. +- [x] Soak: 8 hours, no growth in memory, descriptors, handles, CF references. 8 hours on a Windows 11 workstation, and 5 h 40 min (the hosted job limit) on Linux, macOS, and Windows runners; a leaked CF reference shows as resident growth (results in `docs/SECURITY.md`). +- [x] AddressSanitizer job on Linux and macOS clean; the `hostile` fixture passes every function without panic. Leak checking on Linux; the values kept for the life of the process are the only suppression (`.github/lsan.supp`). ## v0.9.0 - Alpha and beta Exit: both integrations run on every listed environment; two weeks without an API change; every document checked against the build. diff --git a/docs/API.md b/docs/API.md index fa68676..1840d45 100644 --- a/docs/API.md +++ b/docs/API.md @@ -94,11 +94,11 @@ Costs are estimates (marked [est.]) until they are measured in `0.7.0`; measured ```toml [dependencies] -sys = { package = "sys-lib", version = "0.4" } +sys = { package = "sys-lib", version = "0.8" } # Without instance info and the process guard (no dependencies at all): -# sys = { package = "sys-lib", version = "0.4", default-features = false } +# sys = { package = "sys-lib", version = "0.8", default-features = false } # With device identity (from 0.5): -# sys = { package = "sys-lib", version = "0.7", features = ["device-id"] } +# sys = { package = "sys-lib", version = "0.8", features = ["device-id"] } ``` The package is `sys-lib` on crates.io (`sys` and `system` were taken). Cargo's rename makes it `sys` in your code, so every file writes `sys::os::name()` with no import line. Without the rename (`sys-lib = "0.4"`), add `use sys_lib as sys;` at the top of a file and the code is the same. @@ -918,7 +918,7 @@ What the guard does, in order: | Step | Linux and macOS | Windows | |---|---|---| | 1. open-file limit, checked | `OpenFilesTooLow` if the hard `RLIMIT_NOFILE` is below the minimum, before anything else, so a refusal changes nothing (a second copy started under a low limit gets this error, not `AlreadyRunning`) | not applicable | -| 2. lock directory | the default (above), or an explicit `lock_dir`, created with mode 0700 if missing; refused if it is a symlink, group- or world-writable, owned by another user, or on a network filesystem (`nfs`, `cifs`, `smb2`, `fuse.sshfs`, WSL's `drvfs` and `9p`) unless `allow_network_lock(true)` | refused if it is a reparse point or on a remote drive unless allowed; a missing directory inherits its parent's permissions, and ownership is not checked, so choose a parent other users cannot write to (not `C:\ProgramData` itself) | +| 2. lock directory | the default (above), or an explicit `lock_dir`, created with mode 0700 if missing; refused if it is a symlink, group- or world-writable, owned by another user, or on a network filesystem (`nfs`, `cifs`, `smb2`, `fuse.sshfs`, WSL's `drvfs` and `9p`) unless `allow_network_lock(true)` | refused if it is a reparse point or on a remote drive unless allowed; a missing directory is created with an access list for this account, `SYSTEM`, and `Administrators` alone, and a directory another account can change (one under `C:\ProgramData`, say) is refused (D-113) | | 3. single-instance lock | `/.lock` opened with `O_NOFOLLOW`, then checked (the opened file must be the one inspected, by device and inode, and owned by this user), locked with `File::try_lock`, then checked again, so a file deleted or replaced between the open and the lock is never the one held (three tries); the OS releases the lock when the process dies, even after `kill -9` | the same file, `File::try_lock`, reparse points refused, opened without delete sharing, so the held file cannot be deleted or renamed | | 4. pid file | `/.pid` written after the lock is held, with `path_lib::write_atomic` | same (the locked file cannot be read by another process, so the pid lives beside it) | | 5. open-file limit, raised | soft limit raised to the target, capped at the hard limit, on Linux at `/proc/sys/fs/nr_open`, and on macOS at `kern.maxfilesperproc` | not applicable (no per-process descriptor count for sockets); reported as unlimited | @@ -930,7 +930,7 @@ Errors, each saying what to do: | Error | When | The message tells the operator | |---|---|---| -| `AlreadyRunning { pid, lock_file }` | another copy holds the lock | the lock file, and the pid when the pid file is readable: a hint to check, not proof (just after a copy starts the file can still hold the previous run's pid, which may since belong to another program) | +| `AlreadyRunning { pid, lock_file }` | another copy holds the lock | the lock file, and the pid when the pid file names a running process that started before the file was written; otherwise `None`. Still a hint to check, not proof: a program that forks after the guard leaves its parent's pid behind (D-112) | | `RunDirUnavailable { path, source }` | the directory cannot be created or written, is a symlink, is writable by others, or is on a network filesystem | the path, the reason, and the fix (`chmod 700`, a local directory, `allow_network_lock`) | | `OpenFilesTooLow { have, need }` | the hard limit is below the minimum | what to raise: `LimitNOFILE=` in the systemd unit, `ulimit -Hn`, or launchd's limits | | `InvalidInput` | the name failed validation | the rule | diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.md index 9e76aa4..fad527f 100644 --- a/docs/PERFORMANCE.md +++ b/docs/PERFORMANCE.md @@ -1,6 +1,6 @@ # Performance -Measured for 0.7.0 on GitHub's runners, the same machines for every change, by the `Bench` workflow (`.github/workflows/bench.yml`) on the release pull request. The targets and the bar are in `dev/PLAN.md` section 18: at least 20% faster than the best competitor for each reading, at equal correctness, or a recorded reason. +Measured for 0.8.0 on GitHub's runners, the same machines for every change, by the `Bench` workflow (`.github/workflows/bench.yml`) on the release pull request. The targets and the bar are in `dev/PLAN.md` section 18: at least 20% faster than the best competitor for each reading, at equal correctness, or a recorded reason. ## Machines @@ -13,7 +13,7 @@ Measured for 0.7.0 on GitHub's runners, the same machines for every change, by t | macOS Apple M1 (`macos-latest`) | Apple M1, virtual | 3 | 7 GB | | macOS Intel (`macos-15-intel`) | Intel Core i7-8700B | 4 | 14 GB | -Rust 1.99.1, release profile, `strip = true`. The competitors: sysinfo 0.40, num_cpus 1.17, os_info 3.15 (default features off), raw-cpuid 11.6, machine-uid 0.6, with blake3 1.8 for the keyed hash a caller of machine-uid would add. +Rust 1.100.1, release profile, `strip = true`. The competitors: sysinfo 0.40, num_cpus 1.17, os_info 3.15 (default features off), raw-cpuid 11.6, machine-uid 0.6, with blake3 1.8 for the keyed hash a caller of machine-uid would add. ## Method @@ -29,43 +29,43 @@ Each cell is sys-lib / the competitor (how many times faster sys-lib is; below 1 | Reading | Compared with | Linux x86-64 | Linux Arm64 | Docker 1 GiB, 2 CPUs | Windows | macOS Apple M1 | macOS Intel | |---|---|---|---|---|---|---|---| -| `os::name()`, warm | sysinfo `System::name` | 6.5 ns / 5.17 µs (795.4x) | 0.9 ns / 2.59 µs (2877.8x) | 3.9 ns / 9.14 µs (2343.6x) | 7.3 ns / 50 ns (6.8x) | 1.2 ns / 1.03 µs (858.3x) | 1.2 ns / 1.72 µs (1433.3x) | -| `cpu::physical()`, warm | num_cpus `get_physical` | 1.9 ns / 70 µs (36847.4x) | 0.8 ns / 12.4 µs (15487.5x) | 1.2 ns / 72.3 µs (60216.7x) | 2.2 ns / 6.5e+02 ns (294.5x) | 1.4 ns / 1.34 µs (957.1x) | 1 ns / 1.78 µs (1780.0x) | -| `cpu::has(Avx2)` | raw-cpuid | 1.9 ns / 3 µs (1578.9x) | n/a | 1.5 ns / 2.34 µs (1560.0x) | 1.9 ns / 13.6 µs (7168.4x) | n/a | 1.2 ns / 20.4 µs (16958.3x) | -| `mem::snapshot()` | sysinfo `refresh_memory` + `cgroup_limits` | 31 µs / 51.2 µs (1.7x) | 13.6 µs / 24.6 µs (1.8x) | 56.2 µs / 74.1 µs (1.3x) | 1.3 µs / 8.99 µs (6.9x) | 4.98 µs / 1.72 µs (0.3x) | 5.76 µs / 2.23 µs (0.4x) | -| `cpu::Sampler::sample()` | sysinfo `refresh_cpu_usage` + global | 13.8 µs / 54.9 µs (4.0x) | 6.21 µs / 38.8 µs (6.3x) | 13.6 µs / 76.8 µs (5.7x) | 6.95 µs / 61.6 µs (8.9x) | 9.8 µs / 74.9 µs (7.6x) | 12.1 µs / 53 µs (4.4x) | -| `process::memory()` | sysinfo refresh of this pid | 5.85 µs / 45.2 µs (7.7x) | 2.65 µs / 20.4 µs (7.7x) | 6 µs / 45.5 µs (7.6x) | 3.1e+02 ns / 1.6 ms (5124.9x) | 1.35 µs / 30.9 µs (22.9x) | 1.26 µs / 42.2 µs (33.5x) | -| `disk::list()` | sysinfo `Disks::new_with_refreshed_list` | 112 µs / 133 µs (1.2x) | 48.7 µs / 61.7 µs (1.3x) | 76.6 µs / 135 µs (1.8x) | 173 µs / 233 µs (1.3x) | 170 µs / 21.4 ms (126.0x) | 141 µs / 13.2 ms (93.8x) | -| `disk::IoSampler::sample()` | sysinfo `Disks::refresh` (usage) | 35.8 µs / 90.6 µs (2.5x) | 14.3 µs / 41.7 µs (2.9x) | 36.5 µs / 109 µs (3.0x) | 18.5 µs / 194 µs (10.5x) | 239 µs / 13.1 ms (54.8x) | 50.2 µs / 11.1 ms (221.4x) | -| `net::interfaces()` | sysinfo `Networks::new_with_refreshed_list` | 1.09 ms / 1.17 ms (1.1x) | 238 µs / 302 µs (1.3x) | 129 µs / 192 µs (1.5x) | 1.4 ms / 2.06 ms (1.5x) | 73.8 µs / 316 µs (4.3x) | 72 µs / 262 µs (3.6x) | -| `host::uptime()` | sysinfo `System::uptime` | 29 ns / 6.26 µs (213.7x) | 35 ns / 3.09 µs (88.5x) | 22 ns / 6.96 µs (313.5x) | 3.8 ns / 8.2 ns (2.2x) | 40 ns / 6.3e+02 ns (15.8x) | 36 ns / 1.02 µs (28.5x) | -| `host::processes()` | sysinfo process refresh, count | 103 µs / 6.02 ms (58.2x) | 43.7 µs / 3 ms (68.7x) | 29.9 µs / 51.1 µs (1.7x) | 8.95 µs / 1.82 ms (203.4x) | 9.28 µs / 5.32 ms (573.3x) | 10.4 µs / 5.44 ms (522.6x) | -| `device::id(app)` | machine-uid `get` + keyed BLAKE3 | 5.09 µs / 5.43 µs (1.1x) | 2.82 µs / 2.87 µs (1.0x) | n/a | 9.54 µs / 8.03 µs (0.8x) | 11.5 µs / 1.98 µs (0.2x) | 31.7 µs / 3.3 µs (0.1x) | +| `os::name()`, warm | sysinfo `System::name` | 5.5 ns / 1.54 µs (280.0x) | 0.9 ns / 2.58 µs (2866.7x) | 5.5 ns / 2.8 µs (509.1x) | 3.9 ns / 38 ns (9.9x) | 1.6 ns / 1.31 µs (818.8x) | 1.4 ns / 1.69 µs (1207.1x) | +| `cpu::physical()`, warm | num_cpus `get_physical` | 1 ns / 34.5 µs (34490.0x) | 0.8 ns / 12.4 µs (15562.5x) | 1 ns / 34.6 µs (34600.0x) | 1 ns / 2.5e+02 ns (252.6x) | 1.5 ns / 1.32 µs (880.0x) | 1 ns / 1.79 µs (1790.0x) | +| `cpu::has(Avx2)` | raw-cpuid | 1.1 ns / 3.77 µs (3427.3x) | n/a | 1.1 ns / 3.78 µs (3436.4x) | 1 ns / 11.9 µs (11910.0x) | n/a | 1.2 ns / 20.4 µs (17000.0x) | +| `mem::snapshot()` | sysinfo `refresh_memory` + `cgroup_limits` | 10.1 µs / 17.9 µs (1.8x) | 13.8 µs / 24.8 µs (1.8x) | 20.6 µs / 30.2 µs (1.5x) | 6e+02 ns / 7.65 µs (12.8x) | 1.85 µs / 1.47 µs (0.8x) | 3.15 µs / 2.22 µs (0.7x) | +| `cpu::Sampler::sample()` | sysinfo `refresh_cpu_usage` + global | 6.5 µs / 72.3 µs (11.1x) | 6.25 µs / 71.5 µs (11.4x) | 6.71 µs / 83 µs (12.4x) | 5.32 µs / 138 µs (25.9x) | 7.13 µs / 63.6 µs (8.9x) | 14.9 µs / 63.4 µs (4.3x) | +| `process::memory()` | sysinfo refresh of this pid | 1.52 µs / 13.3 µs (8.8x) | 2.63 µs / 20.5 µs (7.8x) | 1.81 µs / 15.9 µs (8.8x) | 1.4e+02 ns / 1.2 ms (8421.1x) | 8.1e+02 ns / 23.9 µs (29.7x) | 1.27 µs / 39.4 µs (31.1x) | +| `disk::list()` | sysinfo `Disks::new_with_refreshed_list` | 31.9 µs / 70.9 µs (2.2x) | 49 µs / 110 µs (2.2x) | 21.6 µs / 70.5 µs (3.3x) | 75.4 µs / 116 µs (1.5x) | 81.5 µs / 8.34 ms (102.3x) | 138 µs / 12 ms (86.9x) | +| `disk::IoSampler::sample()` | sysinfo `Disks::refresh` (usage) | 13.1 µs / 34.5 µs (2.6x) | 14.4 µs / 45.6 µs (3.2x) | 14.8 µs / 59.8 µs (4.0x) | 11.1 µs / 97.9 µs (8.8x) | 55 µs / 7.34 ms (133.4x) | 47.6 µs / 10.9 ms (229.8x) | +| `net::interfaces()` | sysinfo `Networks::new_with_refreshed_list` | 58.8 µs / 81 µs (1.4x) | 660 µs / 711 µs (1.1x) | 42.8 µs / 63 µs (1.5x) | 698 µs / 981 µs (1.4x) | 40.6 µs / 184 µs (4.5x) | 71.2 µs / 257 µs (3.6x) | +| `host::uptime()` | sysinfo `System::uptime` | 23 ns / 1.82 µs (78.1x) | 35 ns / 3.19 µs (91.1x) | 23 ns / 2.33 µs (100.0x) | 2 ns / 5.2 ns (2.6x) | 37 ns / 5.4e+02 ns (14.8x) | 36 ns / 1.03 µs (28.8x) | +| `host::processes()` | sysinfo process refresh, count | 47.6 µs / 2.27 ms (47.7x) | 44.7 µs / 3.17 ms (70.9x) | 14.6 µs / 21.8 µs (1.5x) | 7.22 µs / 1.18 ms (163.4x) | 8.56 µs / 4.85 ms (566.6x) | 9.58 µs / 4.83 ms (504.2x) | +| `device::id(app)` | machine-uid `get` + keyed BLAKE3 | 1.6 µs / 1.71 µs (1.1x) | 2.64 µs / 2.99 µs (1.1x) | n/a | 4.87 µs / 5.71 µs (1.2x) | 8.64 µs / 2.01 µs (0.2x) | 21.1 µs / 3.34 µs (0.2x) | | Reports, warm | Linux x86-64 | Linux Arm64 | Docker 1 GiB, 2 CPUs | Windows | macOS Apple M1 | macOS Intel | |---|---|---|---|---|---|---| -| `summary()` | 102 µs | 46.4 µs | 101 µs | 3.93 µs | 6.02 µs | 12.7 µs | -| `readiness::report(Database)` | 178 µs | 81.6 µs | 164 µs | 642 µs | 13.2 µs | 25.6 µs | -| `security::posture()` | 644 µs | 198 µs | 218 µs | 75.8 µs | 1.6e+02 ns | 3.2e+02 ns | +| `summary()` | 31.1 µs | 46.9 µs | 37.8 µs | 1.74 µs | 4.87 µs | 7.57 µs | +| `readiness::report(Database)` | 54.4 µs | 83 µs | 62.4 µs | 362 µs | 9.36 µs | 15 µs | +| `security::posture()` | 212 µs | 394 µs | 79.4 µs | 50.9 µs | 1.9e+02 ns | 3.2e+02 ns | ## Cold | First call, fresh process | Compared with | Linux x86-64 | Linux Arm64 | Docker 1 GiB, 2 CPUs | Windows | macOS Apple M1 | macOS Intel | |---|---|---|---|---|---|---|---| -| `os::name()` | os_info get | 28.2 µs / 7.67 ms (271.9x) | 34.6 µs / 6.48 ms (187.2x) | 29.2 µs / 541 µs (18.5x) | 47.1 µs / 37.1 µs (0.8x) | 20.6 µs / 126 µs (6.1x) | 31.7 µs / 175 µs (5.5x) | -| `os::name()` | sysinfo System::name | 28.2 µs / 13.8 µs (0.5x) | 34.6 µs / 15.9 µs (0.5x) | 29.2 µs / 16.7 µs (0.6x) | 47.1 µs / 3.9 µs (0.1x) | 20.6 µs / 5.1 µs (0.2x) | 31.7 µs / 5.6 µs (0.2x) | -| `cpu::logical()` | num_cpus get | 23.2 µs / 94.1 µs (4.1x) | 32.1 µs / 70.7 µs (2.2x) | 21.4 µs / 86.6 µs (4.0x) | 7 µs / 4.5 µs (0.6x) | 9.3 µs / 2.5 µs (0.3x) | 11.1 µs / 1.5 µs (0.1x) | -| `cpu::physical()` | num_cpus get_physical | 85.3 µs / 92.3 µs (1.1x) | 96.7 µs / 86.8 µs (0.9x) | 73 µs / 87.7 µs (1.2x) | 13.8 µs / 6.7 µs (0.5x) | 13.4 µs / 7.7 µs (0.6x) | 18.1 µs / 6.7 µs (0.4x) | -| `mem::snapshot()` | sysinfo memory + cgroup_limits | 135 µs / 100 µs (0.7x) | 109 µs / 73.8 µs (0.7x) | 150 µs / 124 µs (0.8x) | 8.6 µs / 53.3 µs (6.2x) | 20.8 µs / 54.5 µs (2.6x) | 21.1 µs / 53.3 µs (2.5x) | -| `device::id(app)` | machine-uid get + keyed blake3 | 21 µs / 18.6 µs (0.9x) | 20.1 µs / 11.9 µs (0.6x) | 19.6 µs / 17.3 µs (0.9x) | 61.8 µs / 54.9 µs (0.9x) | 105 µs / 26.7 µs (0.3x) | 204 µs / 73.3 µs (0.4x) | -| `summary()` | | 568 µs | 362 µs | 524 µs | 167 µs | 66.9 µs | 112 µs | +| `os::name()` | os_info get | 18.5 µs / 5.09 ms (275.3x) | 36.8 µs / 8.03 ms (218.2x) | 20.1 µs / 446 µs (22.2x) | 49.1 µs / 35.8 µs (0.7x) | 19.8 µs / 106 µs (5.3x) | 41.4 µs / 222 µs (5.4x) | +| `os::name()` | sysinfo System::name | 18.5 µs / 8 µs (0.4x) | 36.8 µs / 19.1 µs (0.5x) | 20.1 µs / 9.6 µs (0.5x) | 49.1 µs / 3.9 µs (0.1x) | 19.8 µs / 2.6 µs (0.1x) | 41.4 µs / 6.2 µs (0.1x) | +| `cpu::logical()` | num_cpus get | 13.3 µs / 46.6 µs (3.5x) | 37.1 µs / 86.7 µs (2.3x) | 13 µs / 41.4 µs (3.2x) | 8.5 µs / 5 µs (0.6x) | 6.4 µs / 2 µs (0.3x) | 13.7 µs / 1.8 µs (0.1x) | +| `cpu::physical()` | num_cpus get_physical | 49.6 µs / 48.7 µs (1.0x) | 104 µs / 102 µs (1.0x) | 50.6 µs / 48.5 µs (1.0x) | 17.8 µs / 7.7 µs (0.4x) | 7.2 µs / 3.5 µs (0.5x) | 20.4 µs / 7.8 µs (0.4x) | +| `mem::snapshot()` | sysinfo memory + cgroup_limits | 72.2 µs / 59 µs (0.8x) | 126 µs / 84 µs (0.7x) | 79.7 µs / 73 µs (0.9x) | 11.3 µs / 86.6 µs (7.7x) | 15.8 µs / 34 µs (2.2x) | 24.7 µs / 53.5 µs (2.2x) | +| `device::id(app)` | machine-uid get + keyed blake3 | 14.6 µs / 11.3 µs (0.8x) | 22.4 µs / 14.8 µs (0.7x) | 14.1 µs / 12.5 µs (0.9x) | 44.2 µs / 34.3 µs (0.8x) | 70.6 µs / 25.7 µs (0.4x) | 147 µs / 72.5 µs (0.5x) | +| `summary()` | | 267 µs | 413 µs | 279 µs | 164 µs | 63.4 µs | 113 µs | ## Footprint | Measure | Target | Measured | |---|---|---| | Third-party runtime dependencies | 0 | 0 by default (clock-lib, id-forge, path-lib, and mod-rand through them, all first-party); `device-id` brings crypt-io's BLAKE3 stack; `--no-default-features`: none | -| Added to a stripped binary using every module | under 300 KiB [est.] | 337 to 665 KiB, below | +| Added to a stripped binary using every module | under 300 KiB [est.] | 337 to 670 KiB, below | | Clean release build of the crate | under 2 s [est.] | 17 to 27 s on a shared 32-CPU machine (not measured on the runners) | | Descriptors held between calls | 0 (the guard 1) | 0, checked by `tests/descriptors.rs` | | Allocations per scalar live reading | 0 | 0, checked by `tests/alloc.rs` | @@ -73,11 +73,11 @@ Each cell is sys-lib / the competitor (how many times faster sys-lib is; below 1 | Runner | Added | Baseline binary | With every module | |---|---|---|---| -| Linux x86-64 | 665 KiB | 328 KiB | 994 KiB | +| Linux x86-64 | 670 KiB | 329 KiB | 1000 KiB | | Linux Arm64 | 512 KiB | 324 KiB | 837 KiB | -| Windows | 527 KiB | 127 KiB | 654 KiB | -| macOS Apple M1 | 337 KiB | 334 KiB | 671 KiB | -| macOS Intel | 403 KiB | 316 KiB | 719 KiB | +| Windows | 565 KiB | 127 KiB | 693 KiB | +| macOS Apple M1 | 337 KiB | 334 KiB | 672 KiB | +| macOS Intel | 403 KiB | 320 KiB | 724 KiB | ## Below the bar @@ -85,16 +85,15 @@ Every reading not at least 20% ahead, with the reason as far as it is known. Tho | Reading | Where | Result | Reason | |---|---|---|---| -| `mem::snapshot()` warm | macOS | 0.3x, 0.4x | **Open.** sys-lib also reads the swap usage and the memory pressure level, which sysinfo's memory refresh leaves out; not yet confirmed as the whole gap. | -| `disk::list()` warm | Linux x86-64 | 1.2x | **Open.** Each mount's kind (SSD, HDD, removable) comes from two sysfs files; on Arm64 and in Docker the same code is 1.3x and 1.8x ahead. | -| `net::interfaces()` warm | Linux x86-64 | 1.1x | **Open.** sys-lib fills each interface's kind, speed, and MTU from sysfs, which sysinfo does not report, so the data is not equal; on Arm64 it is 1.3x ahead. | -| `device::id(app)` warm and cold | Linux, Windows; macOS | 0.8x to 1.1x; 0.1x to 0.4x | Identifiers are never cached (threat T1), so both sides read the same source on every call and the hash is the same. **Open** on macOS, where sys-lib's IOKit lookup costs 10 to 30 µs against 2 to 3 µs. | -| `os::name()` cold against os_info | Windows | 0.8x | **Open.** The first call fills every OS fact (name, version, build, edition) from the registry in one cache; os_info reads fewer values. | -| `os::name()` cold against sysinfo | everywhere | 0.1x to 0.6x | Not the plan's comparator: sysinfo's `System::name` reads only the distribution name, while the first `os::name()` fills every OS fact. Against os_info, the comparator in the plan, it is 5x to 270x ahead outside Windows. | +| `mem::snapshot()` warm | macOS | 0.8x, 0.7x | **Open.** Up from 0.3x and 0.4x in 0.7, now that the host port is kept instead of fetched on every reading. sys-lib also reads the swap usage and the memory pressure level, which sysinfo's memory refresh leaves out. | +| `net::interfaces()` warm | Linux Arm64 | 1.1x | **Open.** sys-lib fills each interface's kind, speed, and MTU from sysfs, which sysinfo does not report, so the data is not equal; on x86-64 and in Docker it is 1.4x and 1.5x ahead. | +| `device::id(app)` warm and cold | Linux, Windows; macOS | 0.7x to 1.2x; 0.2x to 0.5x | Identifiers are never cached (threat T1), so both sides read the same source on every call and the hash is the same. **Open** on macOS, where the IOKit lookup still costs 9 to 21 µs against 2 to 3 µs (11 to 32 µs in 0.7, before it went by path). | +| `os::name()` cold against os_info | Windows | 0.7x | **Open.** The first call fills every OS fact (name, version, build, edition) from the registry in one cache; os_info reads fewer values. | +| `os::name()` cold against sysinfo | everywhere | 0.1x to 0.5x | Not the plan's comparator: sysinfo's `System::name` reads only the distribution name, while the first `os::name()` fills every OS fact. Against os_info, the comparator in the plan, it is 5x to 275x ahead outside Windows. | | `cpu::logical()`, `cpu::physical()` cold | Windows, macOS | 0.1x to 0.6x (a few µs) | **Open.** Both sides make one or two system calls; the difference is a few microseconds, likely the first execution of a larger binary's code. On Linux, the target platform for this row, `cpu::logical()` is 2x to 4x ahead. | -| `cpu::physical()` cold | Linux | 0.9x to 1.2x | **Open.** sys-lib reads the topology files (one list per package), num_cpus parses `/proc/cpuinfo`; on 4-CPU runners the walk is as costly as the parse. | -| `mem::snapshot()` cold | Linux, Docker | 0.7x, 0.8x | The first call finds the process's cgroup and caches the paths, which makes every later call cheaper (1.3x to 1.8x ahead warm, with the container limit). | -| Binary size | every platform | 337 to 665 KiB | The estimate counted sys-lib's code only; the measurement includes the parts of std that every module brings (formatting, filesystem, errors). D-103 removed 26 KiB of duplicated generic code. | +| `cpu::physical()` cold | Linux | 1.0x | **Open.** sys-lib reads the topology files (one list per package), num_cpus parses `/proc/cpuinfo`; on 4-CPU runners the walk is as costly as the parse. | +| `mem::snapshot()` cold | Linux, Docker | 0.7x to 0.9x | The first call finds the process's cgroup and caches the paths, which makes every later call cheaper (1.5x to 1.8x ahead warm, with the container limit). | +| Binary size | every platform | 337 to 670 KiB | The estimate counted sys-lib's code only; the measurement includes the parts of std that every module brings (formatting, filesystem, errors). D-103 removed 26 KiB of duplicated generic code. | | Build time | | 17 to 27 s | The estimate was for a crate a tenth of this size (47 000 lines today). | ## Reproducing diff --git a/docs/PLATFORM-NOTES.md b/docs/PLATFORM-NOTES.md index 1e139ff..fc21b25 100644 --- a/docs/PLATFORM-NOTES.md +++ b/docs/PLATFORM-NOTES.md @@ -74,6 +74,9 @@ Everything below is checked by compiling and on CI runners, which are virtual ma - Nano Server: CI runs a real binary there, so the imports load. user32, tbs, and powrprof are loaded at run time from System32 (D-070): on Nano Server `gpu::list()` is `Unsupported` and the power plan, TPM, and turbo fields are unknown. - **Reports.** `sensors::temperatures()` lists drives only; there is no unprivileged documented CPU temperature. The readiness report's ephemeral-port check is `Unknown` (no documented source), and the open-file check passes (handles have no per-process limit). `security::posture()` reads the registry for Secure Boot, VBS, HVCI, and the firewall (true or false only when every profile agrees); BitLocker is `None`. - `process::threads()` takes a process snapshot: tens of milliseconds on a host with many processes. +- **Minimum version:** Windows 10 version 1511, or Windows Server 2016 (D-116). Older builds do not load a binary that links sys-lib (`IsWow64Process2`). +- `cpu::available()` counts every processor of each processor group the process spans: Windows has no call for a process's affinity within several groups (D-117). On machines with one group (64 processors or fewer) the count follows the affinity mask exactly. +- **Process guard:** a missing lock directory is created private (this account, `SYSTEM`, and `Administrators`), and a lock directory other accounts can change is refused, as on Unix (D-113). ## Android diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..2792df6 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,14 @@ +# sys-lib documentation + +| Document | What it covers | +|---|---| +| [API.md](./API.md) | Every public item, the version it arrived in, its cost, and examples | +| [ARCHITECTURE.md](./ARCHITECTURE.md) | How the crate is built: the platform boundary, the parsers, caching | +| [SOURCES.md](./SOURCES.md) | Where each value comes from on each operating system | +| [PLATFORM-NOTES.md](./PLATFORM-NOTES.md) | What differs by platform, and the readings a platform cannot answer | +| [PERFORMANCE.md](./PERFORMANCE.md) | Measured costs against the crates people use instead, and the method | +| [SECURITY.md](./SECURITY.md) | What the crate guarantees, the threats and their tests, and how to report a vulnerability | +| [DEVICE-ID.md](./DEVICE-ID.md) | How the application-scoped device id is derived, and what it is not for | +| [release/](./release/) | The notes for each release | + +The design and the decision log are in [`dev/PLAN.md`](../dev/PLAN.md), the schedule in [`dev/ROADMAP.md`](../dev/ROADMAP.md), and every change in [`CHANGELOG.md`](../CHANGELOG.md). diff --git a/docs/SECURITY.md b/docs/SECURITY.md new file mode 100644 index 0000000..491eb64 --- /dev/null +++ b/docs/SECURITY.md @@ -0,0 +1,55 @@ +# Security + +sys-lib reads facts about the machine for the program that links it. Most of what it reads comes from places the program does not control: `/proc` and `/sys` inside a container whose image or orchestrator may be hostile, firmware tables, the registry, the environment, and files such as `/etc/os-release`. A reading that panics, hangs, or allocates without bound on such input takes the calling service down with it, so for sys-lib that is a security bug, even when memory safety holds. + +## Reporting + +Report a vulnerability privately through GitHub's security advisories for `jamesgober/sys-lib`, or by email to me@jamesgober.com. Please include the platform, the version, the features in use, and the input (a file's content, a mount table) that triggers it. + +## What the crate guarantees + +- **No panic on any input.** Every reading returns a value that keeps its invariants or an error. Every parser is safe Rust, bounded, without recursion, fuzzed, and run under Miri. +- **No hang.** Network filesystems are never touched by default; Windows volume calls run with critical-error dialogs off; a FIFO where a file is expected is opened without blocking and refused. +- **Bounded memory.** Every file read has a budget (1 MiB), every list a count limit checked before allocating, and every size-then-fill system call at most three tries; past a budget the answer is `TooLarge`. +- **No subprocess.** No reading starts a program, so a planted `PATH` cannot change an answer. Only the build helper runs `git` and `$RUSTC`, at build time. +- **No identifier leaves `device`.** Raw hardware identifiers live in a fixed buffer, wiped after hashing; errors, `Debug`, `Display`, and reports carry none. +- **`unsafe` only at the system-call boundary.** It is confined to the platform modules, one operation per block, each with a `SAFETY` comment (both enforced by clippy). Every C struct has a size, alignment, and field-offset check against the platform headers on every target. + +## Threats and defences + +The full model, with the attackers considered, is in `dev/PLAN.md` section 14. + +| Id | Threat | Defence | Cost | Test | +|---|---|---|---|---| +| T1 | Raw hardware identifiers disclosed through logs, errors, `Debug`, `Display`, or the API | raw values exist only inside `device`, in a fixed buffer wiped after hashing; `Error` carries no values; `summary()` has no identifiers | one wipe of a 256-byte buffer per identifier read | `test_attack_t1_no_output_contains_a_raw_identifier`, `test_attack_t1_fingerprint_debug_names_anchors_only` | +| T2 | One device id correlated across applications | a keyed hash with a key derived from the application id; an optional secret | one key derivation per call, inside the `device::id` figures in `docs/PERFORMANCE.md` | `test_attack_t2_applications_see_unrelated_fingerprints` | +| T3 | A device id used to authenticate a machine, then spoofed | documentation; nothing in the API implies verification | none | `test_attack_t3_the_warning_is_in_the_documentation` | +| T4 | Paths or values injected through the environment (`TZ=../../etc/shadow`, a hostile `LANG`, a `HOST_PROC`-style redirect) | no root override from the environment; `TZ`, `LC_*`, and `LANG` validated and never used to open a file; guard and interface names validated | a validation of a few bytes | `test_attack_t4_hostile_environment_changes_no_answer` | +| T5 | Files that change between reads, and pids reused | only `/proc/self` and `/proc/1` are read, plus, when the guard refuses to start, the start time of the process its pid file names; one open per file, read to the end; combined values clamped to their invariants | a few comparisons per reading | `test_attack_t5_values_read_at_different_instants_keep_invariants`, `test_attack_t9_pid_names_only_a_process_that_can_hold_the_lock` | +| T6 | Hostile `/proc` and `/sys` in a container: huge or negative numbers, binary junk, enormous files | safe, bounded, checked parsers without recursion; a fuzz target for every parser | none measurable | `test_attack_t6_hostile_values_in_every_file_never_panic`, `test_attack_t6_hostile_brand_strings_clean_in_bounded_time`, the fuzz targets | +| T7 | Resource exhaustion through huge files or lists (100 000 mounts, 4 096 CPUs) | a 1 MiB budget per file; list budgets (4 096 mounts and interfaces, 16 384 CPUs) checked before allocating; the mount lookup streams the table with a 16 MiB budget | none in the normal case | `test_attack_t7_oversized_files_and_lists_are_too_large` | +| T8 | Hangs on a dead network filesystem, a FIFO, or a removable drive | network filesystems skipped by default; files outside `/proc` and `/sys` opened non-blocking and required to be regular files; critical-error dialogs off around Windows volume calls | one `fstat` per file opened outside `/proc` and `/sys` | `test_attack_t8_network_mounts_are_never_listed_by_default`, `test_linux_root_fifo_does_not_block` | +| T9 | Attacks on the guard's lock file: a symbolic link at the lock path, a lock file planted first, a directory other users can write to, a lock file deleted while held, a pid that names another program | the lock directory must belong to this user and be closed to others (mode and owner on Unix, the access list on Windows) and is created that way; no-follow open; the locked file checked against the path; on Windows the held file cannot be deleted; a reported pid must name a running process that started before its pid file was written | one `stat` and one `fstat` when the guard starts (about 2 µs); on Windows one access-list check | `test_attack_t9_symlinked_lock_file_is_refused`, `test_attack_t9_writable_lock_dir_is_refused`, `test_attack_t9_symlinked_lock_dir_is_refused`, `test_attack_t9_windows_lock_dir_is_private_and_checked`, `test_attack_t9_pid_names_only_a_process_that_can_hold_the_lock`, `test_guard_is_held_until_the_lock_file_is_replaced`, `tests/guard.rs` | +| T10 | The guard's umask change racing other threads | the guard runs before threads; it warns when more are running; the umask is set once | one file read when the guard starts | `test_attack_t10_guard_after_threads_warns_and_sets_the_umask_once` | +| T11 | Build and instance information disclosing the build host, user, or source path | `BuildInfo::public()`; no build host, user, or path recorded; values validated before `rustc-env` | none at run time | `test_attack_t11_nothing_records_host_user_or_path`, `test_attack_t11_public_shows_name_and_version_only`, `test_attack_t11_writers_escape_hostile_values` | +| T12 | Memory-safety bugs at the system-call boundary: wrong layouts, overruns in size-then-fill loops, leaked handles or references | `unsafe` confined to the platform modules; layout checks on every target; at most three tries per size-then-fill loop; lengths checked before slicing; release on drop; the owners of CoreFoundation, IOKit, and Mach objects are `unsafe fn` | none | `test_attack_t12_no_reading_holds_a_descriptor`, the layout tests, Miri on the parsers, the AddressSanitizer job (Linux, macOS), the soak run | +| T13 | Identifying values (host name, user, MAC address) leaving the machine in logs | documented as identifying; excluded from `summary()`; the readiness report shows no mount source | none | `test_attack_t13_summary_has_no_identifying_values`, `test_readiness_display_cannot_be_forged_and_names_no_source` | +| T14 | A spoofed environment (`KUBERNETES_SERVICE_HOST`, a planted `/.dockerenv`, fake DMI strings) | detection is advisory, every piece of evidence carries its strength, and the docs forbid security decisions on it | none | `test_attack_t14_environment_is_weak_evidence` | +| T15 | Malformed firmware tables: bad lengths, missing terminators, structure loops | a bounded SMBIOS parser: each structure checked against the table end, at most 4 096 structures, no recursion; a drive's product string ends at the next field | none | `test_attack_t15_hostile_smbios_tables_stop_cleanly`, the `smbios` fuzz target | +| T16 | A planted program run in place of a system tool (`PATH` with a fake `lsb_release`) | no subprocess at run time | none | `tests/attack_t16_subprocess.rs`, the CI check that `src/` starts no program | + +## Long runs + +Before each release, every fuzz target runs for 24 hours (five chained rounds on GitHub's runners, `fuzz.yml` with `long`), and the soak run (`bench/src/bin/soak.rs`) calls every reading in a loop and fails if this process's memory or open descriptors grow. + +For 0.8.0: + +| Run | Where | Length | Result | +|---|---|---|---| +| Soak | Linux (`ubuntu-latest`) | 5 h 40 min, 20 349 rounds | no growth: 3.3 MiB resident and 5 descriptors from start to end | +| Soak | macOS (`macos-latest`) | 5 h 40 min, 18 743 rounds | no growth: 7.3 MiB at the warm-up peak, at most 6.9 MiB after; 10 descriptors | +| Soak | Windows (`windows-latest`) | 5 h 40 min, 143 705 rounds | no growth: 9.8 MiB at the warm-up peak, at most 10.0 MiB after; 160 handles | +| Soak | Windows 11 workstation | 8 h, 153 626 rounds | no growth: 11.2 MiB at the warm-up peak, at most 11.3 MiB after; 176 handles | +| Fuzz | Linux (`ubuntu-latest`) | 24 h for each of the 20 targets, in five rounds | no crash; about 190 billion inputs in all, from 1.1 billion (`procfs`) to 32 billion (`pid_file`) per target | + +The fuzz run found one slow input and no crash. `cpu_name` ran only 6 million inputs, fewer each round, as its corpus collected names that took one cleaning pass per word: cleaning was quadratic in the name's length, and a 1 MiB name in a container's `/proc/cpuinfo` would have taken about a minute. Names are now cut to 256 bytes before cleaning (real ones are at most 48); `test_attack_t6_hostile_brand_strings_clean_in_bounded_time` covers it, and the target ran again for an hour after the fix. diff --git a/docs/release/v0.8.0.md b/docs/release/v0.8.0.md new file mode 100644 index 0000000..ea7a55c --- /dev/null +++ b/docs/release/v0.8.0.md @@ -0,0 +1,36 @@ +# sys-lib v0.8.0 - Hardening + +**Every threat has a test.** Each of the sixteen threats in the model (leaked identifiers, hostile `/proc` in a container, lock-file attacks, planted programs, malformed firmware tables, and the rest) now has an attack test named after it, and `docs/SECURITY.md` lists each one with its defence, what the defence costs, and the test that proves it. Before this release every fuzz target ran for 24 hours, every test ran under AddressSanitizer on Linux and macOS, and a soak run called every reading for hours on Linux, macOS, and Windows without memory or descriptors growing. + +## The process guard + +- **Windows is now as strict as Unix.** A missing lock directory is created private to this account (plus `SYSTEM` and `Administrators`), and a lock directory another account can change is refused, as a group- or world-writable directory is on Unix. +- `Error::AlreadyRunning` names a pid only when that process is running and started before its pid file was written. A stale or reused pid gives `None`, so an operator is never pointed at an unrelated program. + +## Faster + +- `mem::total()`, `mem::host_total()`, and `mem::limit()` read only what they return. +- macOS keeps its host port instead of fetching it on every reading: warm `mem::snapshot()` went from 5 µs to under 2 µs on Apple silicon. +- macOS `device::id` finds the platform device by path instead of searching the registry. + +## Fixed + +- A very long CPU name, such as a crafted `model name` in a container's `/proc/cpuinfo`, took time quadratic in its length to clean (about a minute for 1 MiB). Names are now cut to 256 bytes first; real ones are at most 48. The 24-hour fuzz run found it. +- Windows disk busy time no longer goes wrong for a while after the clock is changed. +- Error codes are read straight after the call that failed; calls that set none report `Malformed`. +- FreeBSD disk totals ask again when a disk comes or goes during the read. +- A Windows drive's name can no longer pick up the fields after it, and only a cloud's fixed asset tag is kept from the firmware table. + +## Upgrading + +```toml +[dependencies] +sys = { package = "sys-lib", version = "0.8" } +``` + +Two changes can be noticed: + +- On Windows, a program that kept its lock directly in a shared directory such as `C:\ProgramData` gets `Error::RunDirUnavailable` (a permission-denied source) and has to move it to a directory only its account can change. +- The minimum Windows is 10 version 1511, or Server 2016. + +The changelog lists everything. diff --git a/src/error.rs b/src/error.rs index e3be26a..79cf5f1 100644 --- a/src/error.rs +++ b/src/error.rs @@ -94,10 +94,10 @@ pub enum Error { }, /// The process guard found another copy holding the lock. AlreadyRunning { - /// The other copy's process id from its pid file, when readable. A - /// hint, not proof: the file can still hold an earlier run's pid - /// for a moment after a copy starts, and that pid may since belong - /// to another program. Check it before stopping it. + /// The other copy's process id from its pid file, when that names a + /// running process that started before the file was written. A hint, + /// not proof (a program that forks after the guard leaves its + /// parent's pid behind): check it before stopping it. pid: Option, /// The lock file. lock_file: PathBuf, diff --git a/src/lib.rs b/src/lib.rs index 2b9d17a..2775d40 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -11,7 +11,7 @@ //! //! ## Tier 1 //! -//! Add it with Cargo's rename, `sys = { package = "sys-lib", version = "0.7" }`, +//! Add it with Cargo's rename, `sys = { package = "sys-lib", version = "0.8" }`, //! and every file writes `sys::`; without the rename, `use sys_lib as sys;` //! does the same (the examples use that form so they compile either way). //! One plain call per fact; static facts are read once and cached: @@ -49,8 +49,9 @@ //! //! ## Status //! -//! `0.7.0`, optimisation: every reading measured against the crates people -//! use for it, with the numbers in `docs/PERFORMANCE.md`. Feature complete +//! `0.8.0`, hardening: every threat in the model has an attack test, with the +//! defences and their costs in `docs/SECURITY.md`; every reading is measured +//! against the crates people use for it in `docs/PERFORMANCE.md`. Feature complete //! since `0.6`: the boot kit ([`os`], [`cpu`], [`host`], [`process`], //! [`build`], and instance info), the live readings ([`mem`], [`disk`], //! [`net`]), [`virt`], [`power`], [`summary()`], the environment reports, diff --git a/src/linux/mem.rs b/src/linux/mem.rs index 1ac8359..2d95739 100644 --- a/src/linux/mem.rs +++ b/src/linux/mem.rs @@ -153,8 +153,16 @@ pub(crate) fn read( .map(|c| c.saturating_sub(stat_value(root, &p.stat, b"inactive_file").unwrap_or(0))); raw.limit = Some(MemoryLimit { hard: Bytes::new(hard), - soft: bytes_file(root, &p.soft).map(Bytes::new), - swap: tightest(root, &p.swap_max).map(Bytes::new), + soft: want + .detail + .then(|| bytes_file(root, &p.soft)) + .flatten() + .map(Bytes::new), + swap: want + .detail + .then(|| tightest(root, &p.swap_max)) + .flatten() + .map(Bytes::new), source: LimitSource::Cgroup2, }); raw.limited_used = used; @@ -169,9 +177,16 @@ pub(crate) fn read( .map(|c| { c.saturating_sub(stat_value(root, &p.stat, b"total_inactive_file").unwrap_or(0)) }); - let soft = bytes_file(root, &p.soft).filter(|&v| v < V1_UNLIMITED); + let soft = want + .detail + .then(|| bytes_file(root, &p.soft)) + .flatten() + .filter(|&v| v < V1_UNLIMITED); // memory.memsw is memory plus swap; the swap share is the difference. - let swap = bytes_file(root, &p.memsw) + let swap = want + .detail + .then(|| bytes_file(root, &p.memsw)) + .flatten() .filter(|&v| v < V1_UNLIMITED) .map(|memsw| memsw.saturating_sub(hard)); raw.limit = Some(MemoryLimit { @@ -342,6 +357,41 @@ mod tests { assert_eq!(m.limit.unwrap().soft, Some(Bytes::from_mib(200))); } + #[test] + fn test_linux_mem_total_reads_only_what_it_needs() { + // The total and the limit agree; only the limit reads the soft and + // swap files (one more per ancestor), and only snapshots read usage. + let name = "wsl2-systemd-scope-limited"; + let cg = fixtures::cgroups(name); + let paths = MemPaths::new(&cg); + let opened = |want: MemWant| { + let (root, log) = fixtures::root(name).recording(); + let raw = read(&root, paths.as_ref(), cg.lxcfs.meminfo, want).unwrap(); + let files = log.lock().unwrap().clone(); + (from_raw(raw), files) + }; + let reads = + |files: &[String], leaf: &str| files.iter().filter(|p| p.ends_with(leaf)).count(); + let (total, files) = opened(MemWant::TOTAL); + assert_eq!(total.total, Bytes::from_mib(256)); + for leaf in [ + "memory.high", + "memory.swap.max", + "memory.current", + "memory.stat", + ] { + assert_eq!( + reads(&files, leaf), + 0, + "{leaf} read for the total: {files:?}" + ); + } + let (limit, files) = opened(MemWant::LIMIT); + assert_eq!(limit.limit.unwrap().soft, Some(Bytes::from_mib(200))); + assert!(reads(&files, "memory.swap.max") > 0, "{files:?}"); + assert_eq!(reads(&files, "memory.current"), 0, "{files:?}"); + } + #[test] fn test_linux_mem_cgroup_v1_hierarchical_limit() { // E-4: the v1 memory controller. diff --git a/src/linux/process.rs b/src/linux/process.rs index ef2036b..cf4b888 100644 --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -78,19 +78,40 @@ pub(crate) fn status_number(root: &Root, key: &[u8]) -> Result> { /// When this process started: `stat` field 22 (ticks since boot) after the /// boot time. pub(crate) fn started_at(root: &Root, ticks_per_sec: u64, boot: SystemTime) -> Result { + started_from(root, "/proc/self/stat", ticks_per_sec, boot) +} + +/// When process `pid` started, for the guard's check of a pid file (D-112): +/// the one read of another process's `/proc` entry. +#[cfg(feature = "guard")] +pub(crate) fn started_at_pid( + root: &Root, + pid: u32, + ticks_per_sec: u64, + boot: SystemTime, +) -> Result { + started_from(root, &format!("/proc/{pid}/stat"), ticks_per_sec, boot) +} + +fn started_from( + root: &Root, + stat: &str, + ticks_per_sec: u64, + boot: SystemTime, +) -> Result { let ticks = root .with( - "/proc/self/stat", + stat, "process start", - "/proc/self/stat", + "/proc//stat", procfs::stat_start_ticks, )? - .ok_or_else(|| malformed("/proc/self/stat"))?; + .ok_or_else(|| malformed("/proc//stat"))?; let hz = ticks_per_sec.max(1); let since_boot = Duration::from_secs(ticks / hz) + Duration::from_nanos((ticks % hz) * 1_000_000_000 / hz); boot.checked_add(since_boot) - .ok_or_else(|| malformed("/proc/self/stat")) + .ok_or_else(|| malformed("/proc//stat")) } /// Storage I/O: `/proc/self/io` (`read_bytes`, `write_bytes` count storage; diff --git a/src/linux/virt.rs b/src/linux/virt.rs index 1f0a8ea..38c6222 100644 --- a/src/linux/virt.rs +++ b/src/linux/virt.rs @@ -223,7 +223,7 @@ mod tests { } #[test] - fn test_virt_t14_environment_is_weak_evidence() { + fn test_attack_t14_environment_is_weak_evidence() { // E-87: the variable alone says Kubernetes, weakly. let env = Env { kubernetes_host: true, diff --git a/src/mem.rs b/src/mem.rs index 19c56ee..7a21da0 100644 --- a/src/mem.rs +++ b/src/mem.rs @@ -137,33 +137,70 @@ pub(crate) struct MemWant { pub(crate) usage: bool, /// Swap, and on Windows the cache. pub(crate) swap: bool, + /// The machine's free and available memory. Without it a backend may + /// report the total alone, with nothing available. + pub(crate) free: bool, + /// The soft and swap parts of the limit (Linux reads one more file per + /// cgroup ancestor for them). + pub(crate) detail: bool, } impl MemWant { + /// The machine's total alone. + pub(crate) const HOST_TOTAL: MemWant = MemWant { + limit: false, + usage: false, + swap: false, + free: false, + detail: false, + }; + /// The machine's total and free memory. pub(crate) const HOST: MemWant = MemWant { limit: false, usage: false, swap: false, + free: true, + detail: false, }; + /// The total, inside the hard limit when there is one. pub(crate) const TOTAL: MemWant = MemWant { limit: true, usage: false, swap: false, + free: false, + detail: false, + }; + /// The limit with its soft and swap parts. + pub(crate) const LIMIT: MemWant = MemWant { + limit: true, + usage: false, + swap: false, + free: false, + detail: true, }; + /// Used and free memory, inside the limit when there is one. pub(crate) const USED: MemWant = MemWant { limit: true, usage: true, swap: false, + free: true, + detail: false, }; + /// Swap alone. pub(crate) const SWAP: MemWant = MemWant { limit: false, usage: false, swap: true, + free: false, + detail: false, }; + /// Everything. pub(crate) const ALL: MemWant = MemWant { limit: true, usage: true, swap: true, + free: true, + detail: true, }; /// Everything, for the backend tests. #[cfg(test)] @@ -331,7 +368,7 @@ pub fn snapshot() -> Result { /// /// As [`total`]. pub fn host_total() -> Result { - read(MemWant::HOST).map(|m| m.host_total) + read(MemWant::HOST_TOTAL).map(|m| m.host_total) } /// Memory available on the machine, ignoring any limit. @@ -353,7 +390,7 @@ pub fn host_free() -> Result { /// /// As [`total`]. pub fn limit() -> Result> { - read(MemWant::TOTAL).map(|m| m.limit) + read(MemWant::LIMIT).map(|m| m.limit) } /// Swap space. All zero when there is none (E-31). zram counts as swap; zswap diff --git a/src/os.rs b/src/os.rs index ba9bbd1..0d63c74 100644 --- a/src/os.rs +++ b/src/os.rs @@ -543,9 +543,12 @@ pub(crate) const fn form_from_pm_profile(profile: u8) -> Option { } /// A static fact's text, kept for the life of the process. Called only from -/// `OnceLock` initialisers, so each string is stored once. +/// `OnceLock` initialisers, so each string is stored once. The text is copied +/// so that every string kept this way is allocated here, which is the one +/// place the leak checker's suppression (`.github/lsan.supp`) names. pub(crate) fn keep(s: String) -> &'static str { - Box::leak(s.into_boxed_str()) + let kept: Box = s.as_str().into(); + Box::leak(kept) } fn keep_opt(s: Option) -> Option<&'static str> { diff --git a/src/parse/cpu_name.rs b/src/parse/cpu_name.rs index 81b94ef..1a0717f 100644 --- a/src/parse/cpu_name.rs +++ b/src/parse/cpu_name.rs @@ -10,8 +10,12 @@ /// Processor"), so the rules run until nothing changes: a cleaned name never /// cleans further. Each pass that changes the name shortens it or turns its /// whitespace into single spaces, so the loop ends. +/// +/// A pass can remove as little as one word, so the name is first cut to +/// [`MAX_RAW`] bytes: a hostile name (a container's `/proc/cpuinfo` can hold +/// one of 1 MiB) costs microseconds, not minutes. pub(crate) fn clean(raw: &str) -> String { - let mut name = clean_once(raw); + let mut name = clean_once(cut(raw, MAX_RAW)); loop { let next = clean_once(&name); if next == name { @@ -21,6 +25,23 @@ pub(crate) fn clean(raw: &str) -> String { } } +/// The longest brand string cleaned. CPUID's is 48 bytes, and the names the +/// registry, sysctl, and `/proc/cpuinfo` report on real machines are as +/// short; the rest of a longer one is dropped. +pub(crate) const MAX_RAW: usize = 256; + +/// `s` cut to at most `max` bytes, at a character boundary. +fn cut(s: &str, max: usize) -> &str { + if s.len() <= max { + return s; + } + let mut end = max; + while !s.is_char_boundary(end) { + end -= 1; + } + &s[..end] +} + /// One pass of [`clean`]'s rules. fn clean_once(raw: &str) -> String { // Marks vanish rather than becoming spaces: "FX(tm)-8350" is "FX-8350". @@ -166,6 +187,27 @@ pub(crate) fn arm_name(parts: &[(u32, u32)]) -> Option { mod tests { use super::*; + #[test] + #[cfg_attr(miri, ignore = "a megabyte of input is hours under Miri")] + fn test_attack_t6_hostile_brand_strings_clean_in_bounded_time() { + // Each of these takes one pass per word or mark to clean in full, and + // a container's /proc/cpuinfo can hold a 1 MiB name. + let words = format!("Intel {}", "a-core processor ".repeat(60_000)); + let marks = format!("{}{}", "(T".repeat(200_000), "M)".repeat(200_000)); + let freqs = format!("Intel{}", " @1GHz".repeat(170_000)); + for hostile in [words, marks, freqs] { + let start = std::time::Instant::now(); + let name = clean(&hostile); + assert!(name.len() <= MAX_RAW, "{}", name.len()); + assert_eq!(clean(&name), name); + let took = start.elapsed(); + assert!(took < std::time::Duration::from_millis(50), "{took:?}"); + } + // The cut never splits a character. + assert!(clean(&"é".repeat(MAX_RAW)).len() <= MAX_RAW); + assert_eq!(cut("aé", 2), "a"); + } + /// Real brand strings, as `/proc/cpuinfo`, `machdep.cpu.brand_string`, and the /// Windows registry report them, with the expected clean name. const CORPUS: &[(&str, &str)] = &[ diff --git a/src/parse/smbios.rs b/src/parse/smbios.rs index 80cecdc..ead7a42 100644 --- a/src/parse/smbios.rs +++ b/src/parse/smbios.rs @@ -501,7 +501,7 @@ pub(crate) mod tests { } #[test] - fn test_smbios_hostile_tables_stop_cleanly() { + fn test_attack_t15_hostile_smbios_tables_stop_cleanly() { // T15: lengths past the end, too short, no terminator, huge counts. assert_eq!(structures(&[]).count(), 0); assert_eq!(structures(&[1, 200, 0, 0]).count(), 0); diff --git a/src/process/guard.rs b/src/process/guard.rs index 2abf58d..c6e3988 100644 --- a/src/process/guard.rs +++ b/src/process/guard.rs @@ -165,9 +165,9 @@ pub struct GuardBuilder { impl GuardBuilder { /// The directory for the lock and pid files. The default depends only on /// the user (see [`guard`]); a database should pass its data directory. - /// Created owner-only (0700) on Unix when missing; on Windows it inherits - /// its parent's permissions, so choose a parent other users cannot write - /// to (not `C:\ProgramData` itself). + /// Created for this user alone when missing (mode 0700 on Unix; on + /// Windows an access list for this account, `SYSTEM`, and + /// `Administrators`), and refused when other users can change it. #[must_use] pub fn lock_dir(mut self, dir: impl Into) -> Self { self.lock_dir = Some(dir.into()); @@ -423,7 +423,7 @@ fn lock_file(dir: &Path, lock_path: &Path, pid_path: &Path) -> Result { Ok(()) => {} Err(fs::TryLockError::WouldBlock) => { return Err(Error::AlreadyRunning { - pid: read_pid(pid_path), + pid: holder_pid(pid_path), lock_file: lock_path.to_path_buf(), }); } @@ -481,7 +481,7 @@ fn default_dir(name: &str) -> Result { Path::new(name), io::ErrorKind::NotFound, &format!( - "user {uid} has no home directory in the account database for the default lock; pass lock_dir" + "user {uid} has no home directory in the account database for the default lock; pass lock_dir" ), ) })?; @@ -523,7 +523,9 @@ fn runtime_dir(name: &str) -> Result { let app = path_lib::App::new(name) .map_err(|e| unavailable(Path::new(name), io::ErrorKind::InvalidInput, &e.to_string()))?; let dir = app.dir(path_lib::Kind::Runtime).to_path_buf(); - app.ensure(path_lib::Kind::Runtime).map_err(|e| { + // Private: on Windows a directory under one that other accounts can + // write to would otherwise inherit their rights. + app.ensure_private(path_lib::Kind::Runtime).map_err(|e| { unavailable( &dir, io::ErrorKind::Other, @@ -533,20 +535,27 @@ fn runtime_dir(name: &str) -> Result { Ok(dir) } +/// Creates a missing lock directory for this user alone: mode 0700 on Unix, +/// a protected access list for this account, `SYSTEM`, and `Administrators` +/// on Windows. fn create_owner_only(dir: &Path) -> Result<()> { if fs::symlink_metadata(dir).is_ok() { return Ok(()); } - let mut builder = fs::DirBuilder::new(); - builder.recursive(true); - #[cfg(unix)] - { - use std::os::unix::fs::DirBuilderExt; - builder.mode(0o700); - } - builder - .create(dir) - .map_err(|e| unavailable(dir, e.kind(), &format!("it cannot be created: {e}"))) + #[cfg(windows)] + let created = sys::create_private_dir(dir); + #[cfg(not(windows))] + let created = { + let mut builder = fs::DirBuilder::new(); + builder.recursive(true); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + builder.mode(0o700); + } + builder.create(dir) + }; + created.map_err(|e| unavailable(dir, e.kind(), &format!("it cannot be created: {e}"))) } /// The lock directory must be a real, owner-only directory (threat T9). @@ -595,6 +604,18 @@ fn check_dir(dir: &Path) -> Result<()> { "it is a junction or link; use the real directory", )); } + // The Windows counterpart of the mode and owner checks: owned by this + // account (or SYSTEM, or Administrators), and no other account may + // create, change, or delete anything in it. + if let Err(e) = path_lib::check_owner(dir, path_lib::Others::MayRead) { + return Err(unavailable( + dir, + io::ErrorKind::PermissionDenied, + &format!( + "other accounts could replace the lock file ({e}); use a directory only this account can change" + ), + )); + } } Ok(()) } @@ -663,7 +684,45 @@ fn open_lock_file(dir: &Path, path: &Path) -> Result { Ok(file) } -/// The other copy's pid from its pid file, read strictly (at most 128 bytes). +/// The pid of the copy holding the lock, when its pid file names a running +/// process that started before the file was written. Anything else (the +/// holder has locked but not yet written its pid, a pid file left by an +/// earlier run, a pid since reused) is retried briefly, then `None`: a pid +/// never names a process that cannot be the holder (D-112). +fn holder_pid(path: &Path) -> Option { + for attempt in 0..PID_READS { + if attempt > 0 { + std::thread::sleep(PID_RETRY); + } + if let Some(pid) = read_pid(path).filter(|&pid| names_holder(path, pid)) { + return Some(pid); + } + } + None +} + +/// How many times [`holder_pid`] reads the pid file, [`PID_RETRY`] apart. +const PID_READS: u32 = 5; +const PID_RETRY: std::time::Duration = std::time::Duration::from_millis(10); + +/// Whether `pid`, read from the pid file at `path`, can be the lock holder: +/// running, and started no later than the file was written (a file left by +/// an earlier run that happens to name this process fails the second test). +fn names_holder(path: &Path, pid: u32) -> bool { + let (Some(started), Ok(written)) = ( + sys::process_started(pid), + fs::metadata(path).and_then(|m| m.modified()), + ) else { + return false; + }; + // Start times on Linux are reckoned from a boot time in whole seconds, and + // some filesystems keep modification times to 2 s. + started <= written + PID_CLOCK_SLACK +} + +const PID_CLOCK_SLACK: std::time::Duration = std::time::Duration::from_secs(2); + +/// The pid in a pid file, read strictly (at most 128 bytes). fn read_pid(path: &Path) -> Option { let mut data = Vec::with_capacity(pid_file::MAX_BYTES + 1); File::open(path) @@ -879,7 +938,7 @@ mod tests { #[cfg(unix)] #[test] - fn test_guard_lock_path_is_symlink_refuses() { + fn test_attack_t9_symlinked_lock_file_is_refused() { // E-64, T9: a symlink planted at the lock path. let dir = temp_dir("symlink"); create_owner_only(&dir).unwrap(); @@ -897,7 +956,7 @@ mod tests { #[cfg(unix)] #[test] - fn test_guard_world_writable_dir_refuses() { + fn test_attack_t9_writable_lock_dir_is_refused() { // E-64, T9: a directory other users can write to. use std::os::unix::fs::PermissionsExt; let dir = temp_dir("writable"); @@ -915,7 +974,7 @@ mod tests { #[cfg(unix)] #[test] - fn test_guard_symlinked_dir_refuses() { + fn test_attack_t9_symlinked_lock_dir_is_refused() { let dir = temp_dir("dirlink"); let real = temp_dir("dirlink-real"); create_owner_only(&real).unwrap(); @@ -930,6 +989,72 @@ mod tests { let _ = fs::remove_dir_all(&real); } + #[test] + fn test_attack_t9_pid_names_only_a_process_that_can_hold_the_lock() { + // The pid in AlreadyRunning is checked before it is reported. + let dir = temp_dir("pid-hint"); + let build = || { + Guard::builder("h") + .lock_dir(&dir) + .keep_umask() + .open_files_target(0) + .open_files_minimum(0) + .build() + }; + let held = build().unwrap(); + let pid_file = dir.join("h.pid"); + let refused_pid = || match build() { + Err(Error::AlreadyRunning { pid, .. }) => pid, + other => panic!("expected AlreadyRunning, got {other:?}"), + }; + // The holder's own pid file: named. + assert_eq!(refused_pid(), Some(std::process::id())); + // A pid no process can have (above Linux's PID_MAX_LIMIT, odd for + // Windows, past the BSD and macOS maximum): not named. + fs::write(&pid_file, b"4194305\n").unwrap(); + assert_eq!(refused_pid(), None); + // A running process (this one) that started after the file was + // written, as when a pid is reused: not named. + fs::write(&pid_file, format!("{}\n", std::process::id())).unwrap(); + let hour_ago = std::time::SystemTime::now() - std::time::Duration::from_secs(3600); + File::options() + .write(true) + .open(&pid_file) + .unwrap() + .set_modified(hour_ago) + .unwrap(); + assert_eq!(refused_pid(), None); + drop(held); + let _ = fs::remove_dir_all(&dir); + } + + #[cfg(windows)] + #[test] + fn test_attack_t9_windows_lock_dir_is_private_and_checked() { + // Under ProgramData, where every user may create folders and a + // new folder inherits that, a plain directory is refused, and the one + // the guard creates is private. + let base = std::env::var_os("ProgramData") + .map_or_else(|| PathBuf::from(r"C:\ProgramData"), PathBuf::from) + .join(format!("sys-lib-guard-acl-{}", std::process::id())); + let _ = fs::remove_dir_all(&base); + let plain = base.join("plain"); + fs::create_dir_all(&plain).unwrap(); + let refused = check_dir(&plain); + let created = base.join("created"); + create_owner_only(&created).unwrap(); + let private = path_lib::check_owner(&created, path_lib::Others::NoAccess); + let checked = check_dir(&created); + let _ = fs::remove_dir_all(&base); + assert!( + matches!(&refused, Err(Error::RunDirUnavailable { source, .. }) + if source.kind() == io::ErrorKind::PermissionDenied), + "{refused:?}" + ); + private.unwrap(); + checked.unwrap(); + } + #[test] fn test_guard_stale_pid_file_is_replaced() { // E-63: a pid file left by a crashed run while the lock is free. diff --git a/src/summary.rs b/src/summary.rs index 52b5d5d..0822f7e 100644 --- a/src/summary.rs +++ b/src/summary.rs @@ -224,8 +224,8 @@ mod tests { } #[test] - fn test_summary_t13_no_identifying_values() { - // T13: the host name and the user name stay out. + fn test_attack_t13_summary_has_no_identifying_values() { + // T13: the host name, the user name, and every MAC address stay out. let s = summary(); let (mut kv, mut j) = (String::new(), String::new()); s.write_kv(&mut kv).unwrap(); @@ -238,6 +238,12 @@ mod tests { if let Ok(u) = crate::process::user() { secrets.push(u.name); } + for interface in crate::net::interfaces().unwrap_or_default() { + if let Some(mac) = interface.mac { + secrets.push(mac.to_string()); + secrets.push(mac.to_string().to_uppercase().replace(':', "-")); + } + } for secret in secrets.iter().filter(|s| s.len() >= 4) { // A machine named after its OS or CPU would match by accident. if s.os.contains(secret.as_str()) || s.kernel.contains(secret.as_str()) { diff --git a/src/sys/apple/cpu.rs b/src/sys/apple/cpu.rs index b92a87f..9336b80 100644 --- a/src/sys/apple/cpu.rs +++ b/src/sys/apple/cpu.rs @@ -55,6 +55,16 @@ struct ProcessorInfo { } impl ProcessorInfo { + /// Takes the array `host_processor_info` mapped. + /// + /// # Safety + /// + /// `addr` is null or `len` integers the kernel mapped into this task for + /// this code, which nothing else deallocates. + unsafe fn from_raw(addr: *mut c_int, len: u32) -> ProcessorInfo { + ProcessorInfo { addr, len } + } + fn as_slice(&self) -> &[c_int] { if self.addr.is_null() { return &[]; @@ -109,7 +119,9 @@ fn load_info() -> Result<(ProcessorInfo, usize)> { if kr != ffi::KERN_SUCCESS { return Err(kern_error(WHAT, "host_processor_info", kr)); } - Ok((ProcessorInfo { addr, len }, cpus as usize)) + // SAFETY: on success the kernel mapped `len` integers at `addr` for this code. + let info = unsafe { ProcessorInfo::from_raw(addr, len) }; + Ok((info, cpus as usize)) } /// The sum of every core's counters in the flat array (`CPU_STATE_MAX` ticks @@ -178,11 +190,7 @@ pub(crate) fn load() -> Result> { let n = unsafe { ffi::getloadavg(avg.as_mut_ptr(), 3) }; match n { 3 => Ok(Some(Load::new(avg[0] as f32, avg[1] as f32, avg[2] as f32))), - n if n < 0 => Err(super::os_error( - "load average", - "getloadavg", - super::last_errno(), - )), + // -1 sets no errno (POSIX), so there is no code to report. _ => Err(Error::Malformed { what: "load average", source: "getloadavg", diff --git a/src/sys/apple/device.rs b/src/sys/apple/device.rs index c85263a..77f0623 100644 --- a/src/sys/apple/device.rs +++ b/src/sys/apple/device.rs @@ -18,13 +18,15 @@ fn platform_string( out: &mut [u8; ANCHOR_BUF], canonical: fn(&[u8], &mut [u8; ANCHOR_BUF]) -> Reading, ) -> Reading { - let Some(platform) = Io::service(c"IOPlatformExpertDevice") else { - return Reading::Absent; - }; let Ok(key) = Cf::string("device identity", key) else { return Reading::Absent; }; - let Some(value) = platform.property(&key) else { + // The root of the service plane is the platform device: a path lookup, + // where matching by class searches the registry (several times the cost). + let value = Io::at_path(c"IOService:/") + .and_then(|root| root.property(&key)) + .or_else(|| Io::service(c"IOPlatformExpertDevice")?.property(&key)); + let Some(value) = value else { return Reading::Absent; }; let mut text = Raw::new(); diff --git a/src/sys/apple/disk.rs b/src/sys/apple/disk.rs index 4994974..e54a0da 100644 --- a/src/sys/apple/disk.rs +++ b/src/sys/apple/disk.rs @@ -440,12 +440,15 @@ mod iokit { if kr != ffi::KERN_SUCCESS { return Err(kern_error(WHAT, "IOServiceGetMatchingServices", kr)); } - let Some(iterator) = Io::new(iterator) else { + // SAFETY: on success the call returned 0 or an iterator this code owns. + let Some(iterator) = (unsafe { Io::new(iterator) }) else { return Ok(()); }; for n in 0..=MAX_DRIVERS { // SAFETY: `iterator` is a live iterator this function owns. - let Some(driver) = Io::new(unsafe { ffi::IOIteratorNext(iterator.0) }) else { + let next = unsafe { ffi::IOIteratorNext(iterator.0) }; + // SAFETY: the iterator returns 0 or an object this code now owns. + let Some(driver) = (unsafe { Io::new(next) }) else { return Ok(()); }; if n == MAX_DRIVERS { diff --git a/src/sys/apple/host.rs b/src/sys/apple/host.rs index dab0e40..f7786c7 100644 --- a/src/sys/apple/host.rs +++ b/src/sys/apple/host.rs @@ -84,7 +84,8 @@ fn set_load(what: &'static str) -> Result { if kr != ffi::KERN_SUCCESS { return Err(kern_error(what, "processor_set_default", kr)); } - let set = SendRight(set); + // SAFETY: on success the call added one user reference for this code. + let set = unsafe { SendRight::from_raw(set) }; let mut info = ffi::ProcessorSetLoadInfo::default(); let mut count = ffi::PROCESSOR_SET_LOAD_INFO_COUNT; // SAFETY: `info` is `count` `natural_t` units of writable memory; the @@ -143,10 +144,19 @@ fn pid_count(what: &'static str) -> Result { for _ in 0..3 { // SAFETY: a null buffer asks for the estimate only. let estimate = unsafe { ffi::proc_listallpids(core::ptr::null_mut(), 0) }; - let estimate = usize::try_from(estimate) - .ok() - .filter(|&n| n > 0) - .ok_or_else(|| super::os_error(what, "proc_listallpids", super::last_errno()))?; + let code = super::last_errno(); + let estimate = match usize::try_from(estimate) { + Ok(n) if n > 0 => n, + // 0 sets no errno: there is no code to report. + Ok(_) => { + return Err(Error::Malformed { + what, + source: "proc_listallpids", + line: None, + }); + } + Err(_) => return Err(super::os_error(what, "proc_listallpids", code)), + }; let room = estimate.saturating_add(64); if room > MAX_PIDS { return Err(Error::TooLarge { @@ -199,10 +209,11 @@ fn local_offset(what: &'static str) -> Result<(i32, Option)> { // SAFETY: `now` is a readable `time_t` and `tm` a writable `struct tm`. let result = unsafe { ffi::localtime_r(&raw const now, tm.as_mut_ptr()) }; if result.is_null() { - return Err(Error::Os { + // localtime_r does not promise errno: no code to report. + return Err(Error::Malformed { what, - call: "localtime_r", - code: super::last_errno(), + source: "localtime_r", + line: None, }); } // SAFETY: zeroed is a valid `struct tm` (integers and a null pointer), and @@ -241,11 +252,14 @@ pub(crate) fn locale() -> Option<(String, String)> { /// Finder has, with no `LANG` set. #[cfg(target_os = "macos")] fn system_locale() -> Option<(String, String)> { - // SAFETY: no arguments; the returned reference is owned by `Cf`. - let locale = super::iokit::Cf::new(unsafe { ffi::CFLocaleCopyCurrent() })?; - // SAFETY: `locale` is a live CFLocale; the identifier it returns is owned by - // it, and `lent` ties the borrow to `locale`. - let id = locale.lent(unsafe { ffi::CFLocaleGetIdentifier(locale.raw()) })?; + // SAFETY: no arguments. + let raw = unsafe { ffi::CFLocaleCopyCurrent() }; + // SAFETY: a Copy-rule result: null or one reference. + let locale = unsafe { super::iokit::Cf::new(raw) }?; + // SAFETY: `locale` is a live CFLocale. + let raw = unsafe { ffi::CFLocaleGetIdentifier(locale.raw()) }; + // SAFETY: a Get-rule result from `locale`, which keeps it alive. + let id = unsafe { locale.lent(raw) }?; let mut buf = [0u8; crate::parse::locale::MAX_LOCALE]; let raw = core::str::from_utf8(id.text(&mut buf)?).ok()?; let tag = crate::parse::locale::tag(raw)?; diff --git a/src/sys/apple/iokit.rs b/src/sys/apple/iokit.rs index cb843bc..da5131f 100644 --- a/src/sys/apple/iokit.rs +++ b/src/sys/apple/iokit.rs @@ -17,7 +17,13 @@ impl Cf { /// Takes the one reference a Create or Copy function returned; null is `None`. /// The owner is made only for a real object: `then_some` would make one for /// null too and drop it, which is `CFRelease(NULL)`, a crash. - pub(super) fn new(object: ffi::CfRef) -> Option { + /// + /// # Safety + /// + /// `object` is null or a reference this code owns and nothing else + /// releases (the Create and Copy rules). A Get-rule reference here would + /// be released twice. + pub(super) unsafe fn new(object: ffi::CfRef) -> Option { if object.is_null() { None } else { @@ -39,7 +45,8 @@ impl Cf { 0, ) }; - Cf::new(object).ok_or_else(|| kern_error(what, "CFStringCreateWithBytes", 0)) + // SAFETY: a Create-rule result: null or one reference. + unsafe { Cf::new(object) }.ok_or_else(|| kern_error(what, "CFStringCreateWithBytes", 0)) } /// The reference, for a call that only reads it. @@ -57,7 +64,12 @@ impl Cf { /// A reference the Get rule lends out of this object: CoreFoundation keeps /// it alive as long as `self`, and null is `None`. - pub(super) fn lent(&self, object: ffi::CfRef) -> Option> { + /// + /// # Safety + /// + /// `object` is null or a reference a Get function returned from `self`, + /// which `self` keeps alive. + pub(super) unsafe fn lent(&self, object: ffi::CfRef) -> Option> { (!object.is_null()).then_some(Ref { object, owner: PhantomData, @@ -206,13 +218,22 @@ pub(super) struct Io(pub(super) ffi::IoObject); impl Io { /// Takes an object an IOKit call returned; 0 is `None`, and nothing is /// released for it (see `Cf::new`). - pub(super) fn new(object: ffi::IoObject) -> Option { + /// + /// # Safety + /// + /// `object` is 0 or an object this code owns and nothing else releases. + pub(super) unsafe fn new(object: ffi::IoObject) -> Option { if object == 0 { None } else { Some(Io(object)) } } /// The service a matching dictionary finds. The dictionary's one reference - /// is consumed on every path, so `matching` must not be used again. - pub(super) fn matching(matching: ffi::CfRef) -> Option { + /// is consumed on every path. + /// + /// # Safety + /// + /// `matching` is null or a matching dictionary with one reference this + /// code owns, not used again after the call. + pub(super) unsafe fn matching(matching: ffi::CfRef) -> Option { if matching.is_null() { return None; } @@ -220,7 +241,8 @@ impl Io { // consumes; the object returned, if any, is owned by the result. let service = unsafe { ffi::IOServiceGetMatchingService(ffi::IO_MAIN_PORT_DEFAULT, matching) }; - Io::new(service) + // SAFETY: the call returns 0 or a service this code owns. + unsafe { Io::new(service) } } /// The first service of an IOKit class. @@ -228,7 +250,8 @@ impl Io { // SAFETY: the class name is NUL-terminated. The dictionary returned // carries one reference, which `matching` consumes. let matching = unsafe { ffi::IOServiceMatching(class.as_ptr()) }; - Io::matching(matching) + // SAFETY: the dictionary just returned, used nowhere else. + unsafe { Io::matching(matching) } } /// The registry entry at `path` (`IODeviceTree:/chosen`). @@ -237,7 +260,8 @@ impl Io { // owned by the result. let entry = unsafe { ffi::IORegistryEntryFromPath(ffi::IO_MAIN_PORT_DEFAULT, path.as_ptr()) }; - Io::new(entry) + // SAFETY: the call returns 0 or an entry this code owns. + unsafe { Io::new(entry) } } /// The BSD device's media (`disk3s1`). @@ -246,7 +270,8 @@ impl Io { // one reference, which `matching` consumes. let matching = unsafe { ffi::IOBSDNameMatching(ffi::IO_MAIN_PORT_DEFAULT, 0, name.as_ptr()) }; - Io::matching(matching) + // SAFETY: the dictionary just returned, used nowhere else. + unsafe { Io::matching(matching) } } /// A copy of a property of this registry entry. @@ -254,9 +279,11 @@ impl Io { // SAFETY: `self.0` is a live registry entry and `key` a live `CFString`; // the null allocator is the default one. The result, if any, carries // one reference, owned by the returned value. - Cf::new(unsafe { + let object = unsafe { ffi::IORegistryEntryCreateCFProperty(self.0, key.raw(), core::ptr::null(), 0) - }) + }; + // SAFETY: a Create-rule result: null or one reference. + unsafe { Cf::new(object) } } /// Calls `f` with each service of an IOKit class (its subclasses @@ -286,13 +313,16 @@ impl Io { if kr != ffi::KERN_SUCCESS { return Err(kern_error(what, "IOServiceGetMatchingServices", kr)); } - let Some(iterator) = Io::new(iterator) else { + // SAFETY: on success the call returned 0 or an iterator this code owns. + let Some(iterator) = (unsafe { Io::new(iterator) }) else { return Ok(()); }; for n in 0..=max { // SAFETY: `iterator` is a live iterator this function owns; the // object returned, if any, is owned by `service`. - let Some(service) = Io::new(unsafe { ffi::IOIteratorNext(iterator.0) }) else { + let next = unsafe { ffi::IOIteratorNext(iterator.0) }; + // SAFETY: the iterator returns 0 or an object this code now owns. + let Some(service) = (unsafe { Io::new(next) }) else { return Ok(()); }; if n == max { @@ -328,7 +358,8 @@ impl Io { let kr = unsafe { ffi::IORegistryEntryGetParentEntry(self.0, c"IOService".as_ptr(), &raw mut parent) }; - let parent = Io::new(parent)?; + // SAFETY: the call leaves 0 or a parent this code owns. + let parent = unsafe { Io::new(parent) }?; (kr == ffi::KERN_SUCCESS).then_some(parent) } @@ -339,7 +370,8 @@ impl Io { let kr = unsafe { ffi::IORegistryEntryGetChildEntry(self.0, c"IOService".as_ptr(), &raw mut child) }; - let child = Io::new(child)?; + // SAFETY: the call leaves 0 or a child this code owns. + let child = unsafe { Io::new(child) }?; (kr == ffi::KERN_SUCCESS).then_some(child) } } @@ -359,8 +391,10 @@ mod tests { fn test_iokit_null_is_none_and_never_released() { // A property a registry entry does not have comes back null: before the // fix, taking it released NULL and CoreFoundation stopped the process. - assert!(Cf::new(core::ptr::null()).is_none()); - assert!(Io::new(0).is_none()); + // SAFETY: null and 0 are never released. + assert!(unsafe { Cf::new(core::ptr::null()) }.is_none()); + // SAFETY: as above. + assert!(unsafe { Io::new(0) }.is_none()); let platform = Io::service(c"IOPlatformExpertDevice").unwrap(); let missing = Cf::string("test", "sys-lib: no such property").unwrap(); assert!(platform.property(&missing).is_none()); diff --git a/src/sys/apple/mem.rs b/src/sys/apple/mem.rs index 08392ef..aec1ce0 100644 --- a/src/sys/apple/mem.rs +++ b/src/sys/apple/mem.rs @@ -18,8 +18,14 @@ pub(crate) fn memory_modules() -> Result> { pub(crate) fn memory(want: MemWant) -> Result { const WHAT: &str = "memory"; - let total = super::sysctl_int(c"hw.memsize").map_err(|e| e.into_error(WHAT, c"hw.memsize"))?; - let vm = vm_statistics(WHAT)?; + let total = host_total(WHAT)?; + // The total alone needs no VM counters (and works in a sandbox that + // refuses `host_statistics64`). + let vm = if want.free { + vm_statistics(WHAT)? + } else { + ffi::VmStatistics64::default() + }; let swap = if want.swap { Some(swap()?) } else { None }; let raw = raw_from(total, &vm, kernel_page_size(), swap); #[cfg(target_os = "ios")] @@ -84,6 +90,17 @@ fn raw_from(total: u64, vm: &ffi::VmStatistics64, page: u64, swap: Option<(u64, } } +/// `hw.memsize`, read once: the installed memory of a Mac cannot change while +/// it runs. +fn host_total(what: &'static str) -> Result { + static TOTAL: OnceLock = OnceLock::new(); + if let Some(&total) = TOTAL.get() { + return Ok(total); + } + let total = super::sysctl_int(c"hw.memsize").map_err(|e| e.into_error(what, c"hw.memsize"))?; + Ok(*TOTAL.get_or_init(|| total)) +} + /// The host's VM counters. fn vm_statistics(what: &'static str) -> Result { let host = SendRight::host(what)?; diff --git a/src/sys/apple/mod.rs b/src/sys/apple/mod.rs index 863211f..53dbcec 100644 --- a/src/sys/apple/mod.rs +++ b/src/sys/apple/mod.rs @@ -26,6 +26,7 @@ mod topology; use std::{ ffi::{CStr, c_char, c_void}, mem::MaybeUninit, + sync::atomic::{AtomicU64, Ordering}, time::Duration, }; #[cfg(feature = "guard")] @@ -214,15 +215,42 @@ fn own_pid() -> i32 { struct SendRight(ffi::MachPort); impl SendRight { - /// The host's name port. - fn host(what: &'static str) -> Result { + /// Takes a send right. + /// + /// # Safety + /// + /// This code holds one user reference to `port`, which nothing else + /// returns. + unsafe fn from_raw(port: ffi::MachPort) -> SendRight { + SendRight(port) + } + + /// The host's name port, fetched once per process: each + /// `mach_host_self` is a trap and adds a user reference that would have + /// to be returned with another. The name is fetched again in a child + /// after `fork`, whose port names are its own. Two threads racing here + /// each add a reference to the same name, which this process keeps. + fn host(what: &'static str) -> Result { + static CACHED: AtomicU64 = AtomicU64::new(0); + let pid = std::process::id(); + let cached = CACHED.load(Ordering::Relaxed); + if cached != 0 && (cached >> 32) as u32 == pid { + return Ok(HostPort(cached as u32)); + } match ffi::mach_host_self() { 0 => Err(kern_error(what, "mach_host_self", 0)), - port => Ok(SendRight(port)), + port => { + CACHED.store((u64::from(pid) << 32) | u64::from(port), Ordering::Relaxed); + Ok(HostPort(port)) + } } } } +/// The host's name port, held for the life of the process (never returned). +#[derive(Clone, Copy)] +struct HostPort(ffi::MachPort); + impl Drop for SendRight { fn drop(&mut self) { // SAFETY: this value owns one user reference to the right; returning diff --git a/src/sys/apple/net.rs b/src/sys/apple/net.rs index d9331f8..dc605a4 100644 --- a/src/sys/apple/net.rs +++ b/src/sys/apple/net.rs @@ -390,16 +390,20 @@ fn dynamic_store() -> Option> { // SAFETY: `name` is a live `CFString`; a null allocator is the default one, // and the callback and context are optional. The result, if any, carries // one reference. - let store = Cf::new(unsafe { + let store = unsafe { ffi::SCDynamicStoreCreate( core::ptr::null(), name.raw(), core::ptr::null(), core::ptr::null_mut(), ) - })?; + }; + // SAFETY: a Create-rule result: null or one reference. + let store = unsafe { Cf::new(store) }?; // SAFETY: both are live objects. The result, if any, carries one reference. - let value = Cf::new(unsafe { ffi::SCDynamicStoreCopyValue(store.raw(), key.raw()) })?; + let value = unsafe { ffi::SCDynamicStoreCopyValue(store.raw(), key.raw()) }; + // SAFETY: a Copy-rule result: null or one reference. + let value = unsafe { Cf::new(value) }?; let value = value.get(); let mut text = Vec::new(); each_word(value.value(&servers), |server| { diff --git a/src/sys/apple/power.rs b/src/sys/apple/power.rs index 3190589..bd2d2ef 100644 --- a/src/sys/apple/power.rs +++ b/src/sys/apple/power.rs @@ -186,7 +186,9 @@ fn pack_from(description: Ref<'_>, keys: &Keys) -> Pack { #[cfg(target_os = "macos")] fn snapshot() -> Option { // SAFETY: the call takes nothing; the result, if any, carries one reference. - Cf::new(unsafe { ffi::IOPSCopyPowerSourcesInfo() }) + let raw = unsafe { ffi::IOPSCopyPowerSourcesInfo() }; + // SAFETY: a Copy-rule result: null or one reference. + unsafe { Cf::new(raw) } } /// Every internal battery, or `None` when the system gives no snapshot. @@ -195,13 +197,16 @@ fn packs(keys: &Keys) -> Option> { let blob = snapshot()?; // SAFETY: `blob` is a live snapshot; the result, if any, carries one // reference (the Copy rule). - let list = Cf::new(unsafe { ffi::IOPSCopyPowerSourcesList(blob.raw()) })?; + let raw = unsafe { ffi::IOPSCopyPowerSourcesList(blob.raw()) }; + // SAFETY: a Copy-rule result: null or one reference. + let list = unsafe { Cf::new(raw) }?; let mut out = Vec::new(); for source in list.get().items(MAX_SOURCES) { // SAFETY: `blob` is a live snapshot and `source` an element of its list; // the dictionary is borrowed from `blob` (the Get rule). let description = unsafe { ffi::IOPSGetPowerSourceDescription(blob.raw(), source.raw()) }; - if let Some(description) = blob.lent(description) + // SAFETY: a Get-rule result from `blob`, which keeps it alive. + if let Some(description) = unsafe { blob.lent(description) } && is_internal(description, keys) { out.push(pack_from(description, keys)); @@ -266,10 +271,9 @@ pub(crate) fn on_ac() -> Result> { // SAFETY: `blob` is a live snapshot; the string is borrowed, not owned. let source = unsafe { ffi::IOPSGetProvidingPowerSourceType(blob.raw()) }; let mut buf = [0u8; 32]; - Ok(blob - .lent(source) - .and_then(|s| s.text(&mut buf)) - .and_then(mains_from)) + // SAFETY: a Get-rule result from `blob`, which keeps it alive. + let source = unsafe { blob.lent(source) }; + Ok(source.and_then(|s| s.text(&mut buf)).and_then(mains_from)) } /// iOS answers no public call. diff --git a/src/sys/apple/process.rs b/src/sys/apple/process.rs index e26b99f..5ae390f 100644 --- a/src/sys/apple/process.rs +++ b/src/sys/apple/process.rs @@ -133,19 +133,17 @@ unsafe impl super::Plain for ffi::ProcBsdinfo {} /// flavour's struct. #[cfg(target_os = "macos")] fn pid_info(what: &'static str, flavor: c_int) -> Result { + pid_info_of(super::own_pid(), what, flavor) +} + +/// [`pid_info`] for process `pid`. +#[cfg(target_os = "macos")] +fn pid_info_of(pid: c_int, what: &'static str, flavor: c_int) -> Result { let mut info = T::default(); let size = c_int::try_from(core::mem::size_of::()).unwrap_or(c_int::MAX); // SAFETY: `info` is `size` writable bytes; the kernel writes at most // `size`, and `Plain` makes any bytes it writes a valid `T`. - let n = unsafe { - ffi::proc_pidinfo( - super::own_pid(), - flavor, - 0, - (&raw mut info).cast::(), - size, - ) - }; + let n = unsafe { ffi::proc_pidinfo(pid, flavor, 0, (&raw mut info).cast::(), size) }; if n <= 0 { return Err(os_error(what, "proc_pidinfo", last_errno())); } @@ -221,10 +219,19 @@ pub(crate) fn open_files() -> Result { // SAFETY: a null buffer asks for the size the list may need. let need = unsafe { ffi::proc_pidinfo(pid, ffi::PROC_PIDLISTFDS, 0, core::ptr::null_mut(), 0) }; - let need = usize::try_from(need) - .ok() - .filter(|&n| n > 0) - .ok_or_else(|| os_error(WHAT, "proc_pidinfo", last_errno()))?; + let code = last_errno(); + let need = match usize::try_from(need) { + Ok(n) if n > 0 => n, + // 0 sets no errno: there is no code to report. + Ok(_) => { + return Err(Error::Malformed { + what: WHAT, + source: "proc_pidinfo", + line: None, + }); + } + Err(_) => return Err(os_error(WHAT, "proc_pidinfo", code)), + }; let entries = need.div_ceil(ENTRY); let buf: &mut [u64] = if entries <= FD_STACK { &mut stack @@ -302,6 +309,21 @@ pub(crate) fn started_at() -> Result { }) } +/// When process `pid` started, while it exists and this user may read it. +#[cfg(all(target_os = "macos", feature = "guard"))] +pub(crate) fn process_started(pid: u32) -> Option { + let pid = c_int::try_from(pid).ok().filter(|&p| p > 0)?; + let info: ffi::ProcBsdinfo = + pid_info_of(pid, "process start time", ffi::PROC_PIDTBSDINFO).ok()?; + start_time(info.start_tvsec, info.start_tvusec) +} + +/// libproc is not public on iOS. +#[cfg(all(not(target_os = "macos"), feature = "guard"))] +pub(crate) fn process_started(_pid: u32) -> Option { + None +} + /// libproc is not public on iOS. #[cfg(not(target_os = "macos"))] pub(crate) fn started_at() -> Result { diff --git a/src/sys/freebsd/cpu.rs b/src/sys/freebsd/cpu.rs index 79118b2..32d98dc 100644 --- a/src/sys/freebsd/cpu.rs +++ b/src/sys/freebsd/cpu.rs @@ -193,11 +193,7 @@ pub(crate) fn load() -> Result> { let n = unsafe { ffi::getloadavg(avg.as_mut_ptr(), 3) }; match n { 3 => Ok(Some(Load::new(avg[0] as f32, avg[1] as f32, avg[2] as f32))), - n if n < 0 => Err(super::os_error( - "load average", - "getloadavg", - super::last_errno(), - )), + // -1 sets no errno (POSIX), so there is no code to report. _ => Err(Error::Malformed { what: "load average", source: "getloadavg", diff --git a/src/sys/freebsd/ffi.rs b/src/sys/freebsd/ffi.rs index ef63671..607f513 100644 --- a/src/sys/freebsd/ffi.rs +++ b/src/sys/freebsd/ffi.rs @@ -37,6 +37,7 @@ pub(crate) const O_NOFOLLOW: c_int = 0x0100; pub(crate) const EPERM: c_int = 1; pub(crate) const ENOENT: c_int = 2; pub(crate) const ENOMEM: c_int = 12; +pub(crate) const EBUSY: c_int = 16; pub(crate) const EACCES: c_int = 13; pub(crate) const EINVAL: c_int = 22; /// `ERANGE`: a buffer was too small. @@ -629,6 +630,7 @@ mod tests { #[test] fn test_ffi_freebsd_constants_match_libc() { assert_eq!(O_NOFOLLOW, libc::O_NOFOLLOW); + assert_eq!(EBUSY, libc::EBUSY); assert_eq!( (EPERM, ENOENT, ENOMEM, EACCES, EINVAL, ERANGE), ( diff --git a/src/sys/freebsd/host.rs b/src/sys/freebsd/host.rs index c80ea49..5ba4eca 100644 --- a/src/sys/freebsd/host.rs +++ b/src/sys/freebsd/host.rs @@ -129,10 +129,11 @@ fn local_offset(what: &'static str) -> Result<(i32, Option)> { // SAFETY: `now` is a readable `time_t` and `tm` a writable `struct tm`. let result = unsafe { ffi::localtime_r(&raw const now, tm.as_mut_ptr()) }; if result.is_null() { - return Err(Error::Os { + // localtime_r does not promise errno: no code to report. + return Err(Error::Malformed { what, - call: "localtime_r", - code: super::last_errno(), + source: "localtime_r", + line: None, }); } // SAFETY: zeroed is a valid `struct tm` (integers and a null pointer), and diff --git a/src/sys/freebsd/mem.rs b/src/sys/freebsd/mem.rs index 4f84868..6c11421 100644 --- a/src/sys/freebsd/mem.rs +++ b/src/sys/freebsd/mem.rs @@ -31,15 +31,29 @@ struct Pages { } pub(crate) fn memory(want: MemWant) -> Result { - let total = super::sysctl_int(c"hw.physmem").map_err(|e| e.into_error(WHAT, c"hw.physmem"))?; - let pages = Pages { - free: counter(c"vm.stats.vm.v_free_count", WHAT)?, - inactive: counter(c"vm.stats.vm.v_inactive_count", WHAT)?, + let total = host_total()?; + let pages = if want.free { + Pages { + free: counter(c"vm.stats.vm.v_free_count", WHAT)?, + inactive: counter(c"vm.stats.vm.v_inactive_count", WHAT)?, + } + } else { + Pages::default() }; let swap = if want.swap { Some(swap()?) } else { None }; Ok(raw_from(total, pages, page_size() as u64, swap)) } +/// `hw.physmem`, read once: FreeBSD does not add memory to a running system. +fn host_total() -> Result { + static TOTAL: OnceLock = OnceLock::new(); + if let Some(&total) = TOTAL.get() { + return Ok(total); + } + let total = super::sysctl_int(c"hw.physmem").map_err(|e| e.into_error(WHAT, c"hw.physmem"))?; + Ok(*TOTAL.get_or_init(|| total)) +} + /// The public raw reading from the page counters. Available is free plus /// inactive: the pages the kernel reclaims without writing anything. The /// laundry queue (dirty pages waiting for the pager) is not available until diff --git a/src/sys/freebsd/mod.rs b/src/sys/freebsd/mod.rs index 4f73962..d55f234 100644 --- a/src/sys/freebsd/mod.rs +++ b/src/sys/freebsd/mod.rs @@ -250,8 +250,9 @@ const STACK_SYSCTL: usize = 16 << 10; /// Calls `f` with a sysctl of variable size: in a stack buffer when it fits, /// else in a heap buffer bounded at `max` bytes (checked before allocating). -/// Entries appearing between the size query and the read (`ENOMEM`) mean -/// asking again, at most three times. +/// Entries appearing between the size query and the read (`ENOMEM`), or a +/// table that changed while it was copied (`EBUSY`: `kern.devstat.all` when a +/// disk comes or goes), mean asking again, at most three times. fn with_sysctl( what: &'static str, source: &'static str, @@ -278,7 +279,7 @@ fn with_sysctl( }; match sysctl_raw(key, Some(buf)) { Ok(len) => return f(&buf[..len.min(buf.len())]), - Err(ffi::ENOMEM) => {} + Err(ffi::ENOMEM | ffi::EBUSY) => {} Err(code) => return Err(os_error(what, source, code)), } } diff --git a/src/sys/freebsd/process.rs b/src/sys/freebsd/process.rs index 85a7bfb..314ddf9 100644 --- a/src/sys/freebsd/process.rs +++ b/src/sys/freebsd/process.rs @@ -29,12 +29,12 @@ impl Kinfo { /// `sysctl {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid}`; a record of another /// size than the layout read here is `Malformed`. fn own(what: &'static str) -> Result { - let mib = [ - ffi::CTL_KERN, - ffi::KERN_PROC, - ffi::KERN_PROC_PID, - super::own_pid(), - ]; + Kinfo::of(super::own_pid(), what) + } + + /// [`Kinfo::own`] for process `pid`. + fn of(pid: c_int, what: &'static str) -> Result { + let mib = [ffi::CTL_KERN, ffi::KERN_PROC, ffi::KERN_PROC_PID, pid]; let mut buf = [0u8; ffi::KINFO_PROC_SIZE]; let len = super::sysctl_raw(Key::Mib(&mib), Some(&mut buf)) .map_err(|code| os_error(what, KINFO, code))?; @@ -226,6 +226,14 @@ fn start_time(sec: i64, usec: i64) -> Option { SystemTime::UNIX_EPOCH.checked_add(core::time::Duration::new(sec, usec * 1_000)) } +/// When process `pid` started, while it exists. +#[cfg(feature = "guard")] +pub(crate) fn process_started(pid: u32) -> Option { + let pid = c_int::try_from(pid).ok().filter(|&p| p > 0)?; + let info = Kinfo::of(pid, "process start time").ok()?; + info.start().and_then(|(sec, usec)| start_time(sec, usec)) +} + /// `ki_start`. pub(crate) fn started_at() -> Result { const WHAT: &str = "process start time"; diff --git a/src/sys/linux/live.rs b/src/sys/linux/live.rs index 4b4d497..0b1639d 100644 --- a/src/sys/linux/live.rs +++ b/src/sys/linux/live.rs @@ -594,6 +594,12 @@ pub(crate) fn started_at() -> Result { tree::process::started_at(&ROOT, clk_tck(), boot_time()?) } +/// When process `pid` started, while it exists. +#[cfg(feature = "guard")] +pub(crate) fn process_started(pid: u32) -> Option { + tree::process::started_at_pid(&ROOT, pid, clk_tck(), boot_time().ok()?).ok() +} + pub(crate) fn process_io() -> Result { tree::process::io(&ROOT) } diff --git a/src/sys/unsupported.rs b/src/sys/unsupported.rs index 15ca17c..1424860 100644 --- a/src/sys/unsupported.rs +++ b/src/sys/unsupported.rs @@ -92,6 +92,11 @@ pub(crate) fn effective_uid() -> Option { None } +#[cfg(feature = "guard")] +pub(crate) fn process_started(_pid: u32) -> Option { + None +} + #[cfg(all(feature = "guard", unix))] pub(crate) fn home_dir(_uid: u32) -> Option { None diff --git a/src/sys/windows/disk.rs b/src/sys/windows/disk.rs index 1fe555a..6dfb378 100644 --- a/src/sys/windows/disk.rs +++ b/src/sys/windows/disk.rs @@ -6,7 +6,7 @@ use std::{ mem::{offset_of, size_of}, os::windows::ffi::{OsStrExt, OsStringExt}, path::{Path, PathBuf}, - sync::OnceLock, + sync::atomic::{AtomicU64, Ordering}, time::Duration, }; @@ -155,12 +155,13 @@ pub(crate) fn disks(options: &ListOptions) -> Result> { let mut roots = Vec::new(); let mut letters = 0u32; let volumes = volume_roots(options, &mut roots, &mut letters)?; - let drives = drive_roots(options, &mut roots, letters)?; - if !volumes && !drives { + if let Err(code) = drive_roots(options, &mut roots, letters)? + && !volumes + { return Err(Error::Os { what: "disk list", call: "GetLogicalDriveStringsW", - code: last_error(), + code, }); } let mut serials: Vec = Vec::new(); @@ -316,14 +317,22 @@ fn add_volume( Ok(()) } -/// Adds the drive letters no volume claimed; false when they cannot be listed. -fn drive_roots(options: &ListOptions, roots: &mut Vec, letters: u32) -> Result { +/// Adds the drive letters no volume claimed; the error code when they cannot +/// be listed. +fn drive_roots( + options: &ListOptions, + roots: &mut Vec, + letters: u32, +) -> Result> { // 26 roots of 4 units ("C:\" and its NUL) and the final NUL. let mut buf = [0u16; 128]; // SAFETY: `buf` is writable for its length in units. let n = unsafe { ffi::GetLogicalDriveStringsW(buf.len() as u32, buf.as_mut_ptr()) } as usize; - if n == 0 || n >= buf.len() { - return Ok(false); + if n == 0 { + return Ok(Err(last_error())); + } + if n >= buf.len() { + return Ok(Err(ffi::ERROR_INSUFFICIENT_BUFFER as i32)); } for path in multi_sz(&buf[..n]) { let Some(letter) = drive_letter(path) else { @@ -339,7 +348,7 @@ fn drive_roots(options: &ListOptions, roots: &mut Vec, letters: u32) -> Re }; push(roots, root, options)?; } - Ok(true) + Ok(Ok(())) } /// What `GetDriveTypeW` says the storage is: a fixed drive is one [`fixed_kind`] @@ -724,13 +733,36 @@ fn each_drive(mut f: impl FnMut(u32, &ffi::DiskPerformance)) -> Result<()> { } } -/// The clock reading busy time is measured from: the first query's clock -/// minus the uptime then (both 100 ns units), fixed for the process. +/// The clock reading busy time is measured from: the query's clock minus the +/// uptime (both 100 ns units), kept while the wall clock runs with the uptime. fn clock_origin(query_time: u64) -> u64 { - static ORIGIN: OnceLock = OnceLock::new(); - *ORIGIN.get_or_init(|| query_time.saturating_sub(ffi::GetTickCount64().saturating_mul(10_000))) + static ORIGIN: AtomicU64 = AtomicU64::new(0); + let uptime = ffi::GetTickCount64().saturating_mul(10_000); + let kept = ORIGIN.load(Ordering::Relaxed); + let origin = anchored(kept, query_time, uptime); + if origin != kept { + ORIGIN.store(origin, Ordering::Relaxed); + } + origin +} + +/// The origin for a query at `query_time` with the system up `uptime`: `kept` +/// unless there is none or the wall clock has stepped (NTP, a manual change) +/// more than [`CLOCK_STEP`] away from the uptime since, when it is re-anchored. +/// Without this a step back of S would read 0% busy until S of real busy time +/// had passed, and a step forward would read one spike. +fn anchored(kept: u64, query_time: u64, uptime: u64) -> u64 { + let fresh = query_time.saturating_sub(uptime); + if kept == 0 || kept.abs_diff(fresh) > CLOCK_STEP { + fresh + } else { + kept + } } +/// One second in 100 ns units: well above the tick count's 16 ms resolution. +const CLOCK_STEP: u64 = 10_000_000; + /// Busy time: the time the counters cover minus idle time. `QueryTime` is the /// system time of the query (wall clock, 100 ns since 1601), not a span, so it /// is taken from `origin`: with a fixed origin the difference between two @@ -873,6 +905,29 @@ mod tests { assert_eq!(busy_time(0, 0, origin), Duration::ZERO); } + #[test] + fn test_disk_windows_busy_time_survives_a_clock_step() { + // 100 ns units. The first query sets the origin; queries that + // run with the uptime keep it, to within the tick resolution. + let (query, up) = (5_000_000_000_000u64, 1_000_000_000u64); + let origin = anchored(0, query, up); + assert_eq!(origin, query - up); + assert_eq!( + anchored(origin, query + 300_000_000, up + 300_160_000), + origin + ); + // The wall clock stepped back an hour: re-anchored, so busy time + // keeps counting instead of reading zero for an hour. + let back = query + 300_000_000 - 36_000_000_000; + let moved = anchored(origin, back, up + 300_000_000); + assert_eq!(moved, back - (up + 300_000_000)); + let idle = 200_000_000; + assert_eq!( + busy_time(back, idle, moved), + hundred_ns(up + 300_000_000 - idle) + ); + } + #[test] fn test_disk_windows_wide_paths_short_long_and_nul() { let short = with_wide_path(Path::new(r"C:\x"), |p| Ok(p.to_vec())).unwrap(); diff --git a/src/sys/windows/ffi.rs b/src/sys/windows/ffi.rs index 442b226..2cadd99 100644 --- a/src/sys/windows/ffi.rs +++ b/src/sys/windows/ffi.rs @@ -391,6 +391,44 @@ layout!(TokenElevation, size = 4, align = 4); pub(crate) const TOKEN_ELEVATION_CLASS: i32 = 20; /// `TOKEN_QUERY` access right (winnt.h). pub(crate) const TOKEN_QUERY: u32 = 0x0008; +/// `TOKEN_INFORMATION_CLASS::TokenUser` (winnt.h). +pub(crate) const TOKEN_USER_CLASS: i32 = 1; + +/// `SID_AND_ATTRIBUTES` (winnt.h), the body of `TOKEN_USER`. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub(crate) struct SidAndAttributes { + pub(crate) sid: *mut c_void, + pub(crate) attributes: u32, +} +#[cfg(target_pointer_width = "64")] +layout!(SidAndAttributes, size = 16, align = 8); +#[cfg(target_pointer_width = "32")] +layout!(SidAndAttributes, size = 8, align = 4); + +/// `SECURITY_ATTRIBUTES` (minwinbase.h). +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub(crate) struct SecurityAttributes { + pub(crate) length: u32, + pub(crate) security_descriptor: *mut c_void, + pub(crate) inherit_handle: Bool, +} +#[cfg(target_pointer_width = "64")] +layout!(SecurityAttributes, size = 24, align = 8); +#[cfg(target_pointer_width = "32")] +layout!(SecurityAttributes, size = 12, align = 4); + +/// `SDDL_REVISION_1` (sddl.h). +pub(crate) const SDDL_REVISION_1: u32 = 1; +/// `ERROR_ALREADY_EXISTS` (winerror.h). +pub(crate) const ERROR_ALREADY_EXISTS: u32 = 183; +/// `PROCESS_QUERY_LIMITED_INFORMATION` access right (winnt.h). +pub(crate) const PROCESS_QUERY_LIMITED_INFORMATION: u32 = 0x1000; +/// `SYNCHRONIZE` access right (winnt.h): wait on the process. +pub(crate) const PROCESS_SYNCHRONIZE: u32 = 0x0010_0000; +/// `WAIT_TIMEOUT` (winerror.h): the object is not signalled. +pub(crate) const WAIT_TIMEOUT: u32 = 0x102; /// `STORAGE_PROPERTY_QUERY` (winioctl.h). #[repr(C)] @@ -447,6 +485,8 @@ layout!(StorageDeviceDescriptor, size = 40, align = 4); pub(crate) mod sdd { pub(crate) const VENDOR_ID_OFFSET: usize = 12; pub(crate) const PRODUCT_ID_OFFSET: usize = 16; + pub(crate) const PRODUCT_REVISION_OFFSET: usize = 20; + pub(crate) const SERIAL_NUMBER_OFFSET: usize = 24; pub(crate) const BUS_TYPE: usize = 28; } @@ -1217,6 +1257,11 @@ dll!("kernel32.dll" { ) -> Bool; // handleapi.h pub(crate) fn CloseHandle(handle: Handle) -> Bool; + // fileapi.h + pub(crate) fn CreateDirectoryW(path: *const u16, attributes: *const SecurityAttributes) -> Bool; + // processthreadsapi.h, synchapi.h + pub(crate) fn OpenProcess(access: u32, inherit: Bool, process_id: u32) -> Handle; + pub(crate) fn WaitForSingleObject(handle: Handle, milliseconds: u32) -> u32; // timezoneapi.h pub(crate) fn GetDynamicTimeZoneInformation(info: *mut DynamicTimeZoneInformation) -> u32; // winnls.h @@ -1261,6 +1306,14 @@ dll!("advapi32.dll" { ) -> Bool; // winbase.h pub(crate) fn GetUserNameW(buffer: *mut u16, size: *mut u32) -> Bool; + // sddl.h + pub(crate) fn ConvertSidToStringSidW(sid: *mut c_void, string: *mut *mut u16) -> Bool; + pub(crate) fn ConvertStringSecurityDescriptorToSecurityDescriptorW( + sddl: *const u16, + revision: u32, + descriptor: *mut *mut c_void, + length: *mut u32, + ) -> Bool; pub(crate) fn LookupPrivilegeValueW(system: *const u16, name: *const u16, luid: *mut Luid) -> Bool; }); @@ -1388,6 +1441,10 @@ mod tests { use super::*; same_layout!(FileTime, f::FILETIME, low => dwLowDateTime, high => dwHighDateTime); + same_layout!(SidAndAttributes, sec::SID_AND_ATTRIBUTES, sid => Sid, attributes => Attributes); + same_layout!(SecurityAttributes, sec::SECURITY_ATTRIBUTES, + length => nLength, security_descriptor => lpSecurityDescriptor, + inherit_handle => bInheritHandle); same_layout!(MemoryStatusEx, si::MEMORYSTATUSEX, length => dwLength, memory_load => dwMemoryLoad, total_phys => ullTotalPhys, avail_phys => ullAvailPhys, total_page_file => ullTotalPageFile, @@ -1612,6 +1669,8 @@ mod tests { type D = io::STORAGE_DEVICE_DESCRIPTOR; assert!(offset_of!(D, VendorIdOffset) == sdd::VENDOR_ID_OFFSET); assert!(offset_of!(D, ProductIdOffset) == sdd::PRODUCT_ID_OFFSET); + assert!(offset_of!(D, ProductRevisionOffset) == sdd::PRODUCT_REVISION_OFFSET); + assert!(offset_of!(D, SerialNumberOffset) == sdd::SERIAL_NUMBER_OFFSET); assert!(offset_of!(D, BusType) == sdd::BUS_TYPE); type T = io::STORAGE_TEMPERATURE_DATA_DESCRIPTOR; assert!(offset_of!(T, CriticalTemperature) == temperature::CRITICAL); @@ -1725,6 +1784,12 @@ mod tests { assert!(TH32CS_SNAPTHREAD == th::TH32CS_SNAPTHREAD); assert!(TOKEN_ELEVATION_CLASS == sec::TokenElevation); assert!(TOKEN_QUERY == sec::TOKEN_QUERY); + assert!(TOKEN_USER_CLASS == sec::TokenUser); + assert!(SDDL_REVISION_1 == sec::Authorization::SDDL_REVISION_1); + assert!(ERROR_ALREADY_EXISTS == f::ERROR_ALREADY_EXISTS); + assert!(PROCESS_QUERY_LIMITED_INFORMATION == thr::PROCESS_QUERY_LIMITED_INFORMATION); + assert!(PROCESS_SYNCHRONIZE == thr::PROCESS_SYNCHRONIZE); + assert!(WAIT_TIMEOUT == f::WAIT_TIMEOUT); assert!( FILE_ATTRIBUTE_REPARSE_POINT == windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT diff --git a/src/sys/windows/firmware.rs b/src/sys/windows/firmware.rs index 983326a..bd870c6 100644 --- a/src/sys/windows/firmware.rs +++ b/src/sys/windows/firmware.rs @@ -62,6 +62,10 @@ impl Table { table.len = needed; return Ok(table); } + if needed == 0 { + // Read now: dropping `table` frees memory, which may set it. + return Err(last_error()); + } size = needed; } Err(ffi::ERROR_INSUFFICIENT_BUFFER as i32) @@ -102,8 +106,14 @@ fn parsed() -> core::result::Result<&'static Parsed, i32> { .get_or_init(|| { let table = Table::read()?; let structures = structures_of(table.raw()); + let mut facts = smbios::facts(structures); + // The asset tag can identify the machine: only a cloud's fixed + // tag, which the detection needs, is kept. + facts.asset_tag = facts + .asset_tag + .filter(|tag| crate::virt::CLOUD_ASSET_TAGS.contains(&tag.as_str())); Ok(Parsed { - facts: smbios::facts(structures), + facts, modules: smbios::memory_devices(structures), }) }) diff --git a/src/sys/windows/mod.rs b/src/sys/windows/mod.rs index 9a1a708..5832106 100644 --- a/src/sys/windows/mod.rs +++ b/src/sys/windows/mod.rs @@ -511,6 +511,167 @@ pub(crate) fn open_files_ceiling() -> Option { None } +/// Creates `dir` with a protected access list for this account, `SYSTEM`, +/// and `Administrators` alone, set as it is created, the Windows counterpart +/// of mode 0700. Missing parents are created as usual. A directory that +/// appeared meanwhile is left for the caller's checks. +#[cfg(feature = "guard")] +pub(crate) fn create_private_dir(dir: &Path) -> std::io::Result<()> { + use std::os::windows::ffi::OsStrExt; + if let Some(parent) = dir.parent().filter(|p| !p.as_os_str().is_empty()) { + std::fs::create_dir_all(parent)?; + } + let user = token_user_sid()?; + let sddl = wide(&format!( + "D:P(A;OICI;FA;;;{user})(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)" + )); + let mut descriptor = core::ptr::null_mut(); + // SAFETY: `sddl` is NUL-terminated; `descriptor` is a writable pointer + // slot; a null length pointer is allowed. + let ok = unsafe { + ffi::ConvertStringSecurityDescriptorToSecurityDescriptorW( + sddl.as_ptr(), + ffi::SDDL_REVISION_1, + &raw mut descriptor, + core::ptr::null_mut(), + ) + }; + if ok == 0 { + return Err(std::io::Error::last_os_error()); + } + let descriptor = LocalMemory(descriptor); + let attributes = ffi::SecurityAttributes { + length: u32::try_from(core::mem::size_of::()).unwrap_or(u32::MAX), + security_descriptor: descriptor.0, + inherit_handle: 0, + }; + let path: Vec = dir + .as_os_str() + .encode_wide() + .chain(std::iter::once(0)) + .collect(); + // SAFETY: `path` is NUL-terminated; `attributes` points to the descriptor, + // which lives until `descriptor` drops after the call. + let ok = unsafe { ffi::CreateDirectoryW(path.as_ptr(), &raw const attributes) }; + if ok == 0 { + let e = std::io::Error::last_os_error(); + if e.raw_os_error() != Some(ffi::ERROR_ALREADY_EXISTS as i32) { + return Err(e); + } + } + Ok(()) +} + +/// This process's user, as a SID string (`S-1-5-21-...`). +#[cfg(feature = "guard")] +fn token_user_sid() -> std::io::Result { + let mut token = core::ptr::null_mut(); + // SAFETY: the pseudo-handle of this process is always valid; `token` is writable. + let ok = unsafe { + ffi::OpenProcessToken(ffi::GetCurrentProcess(), ffi::TOKEN_QUERY, &raw mut token) + }; + if ok == 0 { + return Err(std::io::Error::last_os_error()); + } + let token = Owned(token); + // TOKEN_USER plus the SID it points to: a SID is at most 68 bytes. + let mut buf = [0usize; 16]; + let mut needed = 0u32; + // SAFETY: `token` is open for query; `buf` is the size passed, aligned for + // TOKEN_USER. + let ok = unsafe { + ffi::GetTokenInformation( + token.0, + ffi::TOKEN_USER_CLASS, + buf.as_mut_ptr().cast::(), + u32::try_from(core::mem::size_of_val(&buf)).unwrap_or(u32::MAX), + &raw mut needed, + ) + }; + if ok == 0 { + return Err(std::io::Error::last_os_error()); + } + // SAFETY: the call succeeded, so `buf` starts with a TOKEN_USER; `buf` is + // aligned for it. + let user = unsafe { buf.as_ptr().cast::().read() }; + let mut text = core::ptr::null_mut(); + // SAFETY: `user.sid` is the valid SID the token returned, inside `buf`; + // `text` is a writable pointer slot. + let ok = unsafe { ffi::ConvertSidToStringSidW(user.sid, &raw mut text) }; + if ok == 0 { + return Err(std::io::Error::last_os_error()); + } + let text = LocalMemory(text.cast::()); + let units = text.0.cast::(); + let mut len = 0usize; + // SAFETY: the string is NUL-terminated, and a SID string is under 200 + // units, so every unit read up to the NUL is inside it. + while len < 256 { + let unit = units.wrapping_add(len); + // SAFETY: as above, `unit` is inside the string. + if unsafe { *unit } == 0 { + break; + } + len += 1; + } + // SAFETY: the `len` units before the NUL were just read. + let units = unsafe { core::slice::from_raw_parts(units, len) }; + Ok(String::from_utf16_lossy(units)) +} + +/// Memory from `LocalAlloc`, freed on drop. +struct LocalMemory(*mut c_void); + +impl Drop for LocalMemory { + fn drop(&mut self) { + // SAFETY: the OS allocated the memory with LocalAlloc; it is freed once. + unsafe { ffi::LocalFree(self.0) }; + } +} + +/// When process `pid` started, if it is still running and this account may +/// query it: the guard's check of a pid file (D-112). +#[cfg(feature = "guard")] +pub(crate) fn process_started(pid: u32) -> Option { + // SAFETY: plain values; a null handle is failure. + let handle = unsafe { + ffi::OpenProcess( + ffi::PROCESS_QUERY_LIMITED_INFORMATION | ffi::PROCESS_SYNCHRONIZE, + 0, + pid, + ) + }; + if handle.is_null() { + return None; + } + let handle = Owned(handle); + // An exited process can still be opened while handles to it remain. + // SAFETY: `handle` is open with SYNCHRONIZE. + if unsafe { ffi::WaitForSingleObject(handle.0, 0) } != ffi::WAIT_TIMEOUT { + return None; + } + let (mut creation, mut exit, mut kernel, mut user) = ( + ffi::FileTime::default(), + ffi::FileTime::default(), + ffi::FileTime::default(), + ffi::FileTime::default(), + ); + // SAFETY: `handle` is open with query access; the outputs are writable. + let ok = unsafe { + ffi::GetProcessTimes( + handle.0, + &raw mut creation, + &raw mut exit, + &raw mut kernel, + &raw mut user, + ) + }; + if ok == 0 { + return None; + } + filetime_to_system(creation.get()) +} + #[cfg(feature = "guard")] pub(crate) fn lock_open_options(options: &mut OpenOptions) { use std::os::windows::fs::OpenOptionsExt; diff --git a/src/sys/windows/report.rs b/src/sys/windows/report.rs index bc1b6e7..ab83b7c 100644 --- a/src/sys/windows/report.rs +++ b/src/sys/windows/report.rs @@ -15,7 +15,7 @@ use std::{ }; use super::{ - Key, Owned, + Key, LocalMemory, Owned, cpu::power_info, detect::firmware_kind, disk::{MAX_DRIVES, MISSES, drive_path}, @@ -139,7 +139,21 @@ fn product_of(bytes: &[u8]) -> Option { if at < size_of::() - 1 { return None; } - let rest = bytes.get(at..)?; + // The string ends at its NUL, and never past the next string the + // descriptor names: a driver that leaves out the NUL must not carry the + // revision or the serial number into the name. + let next = [ + ffi::sdd::VENDOR_ID_OFFSET, + ffi::sdd::PRODUCT_REVISION_OFFSET, + ffi::sdd::SERIAL_NUMBER_OFFSET, + ] + .into_iter() + .filter_map(|field| u32_at(bytes, field)) + .map(|o| o as usize) + .filter(|&o| o > at) + .min() + .unwrap_or(usize::MAX); + let rest = bytes.get(at..next.min(bytes.len()))?; let end = rest.iter().position(|&b| b == 0).unwrap_or(rest.len()); let text: String = rest[..end.min(64)] .iter() @@ -442,16 +456,6 @@ fn power_api() -> Option<&'static PowerApi> { .as_ref() } -/// Memory from `LocalAlloc`, freed on drop. -struct LocalMemory(*mut c_void); - -impl Drop for LocalMemory { - fn drop(&mut self) { - // SAFETY: the OS allocated the memory with LocalAlloc; it is freed once. - unsafe { ffi::LocalFree(self.0) }; - } -} - /// The `PERSONALITY` value of a plan based on High performance /// (`powercfg /qh`: 0 Power saver, 1 High performance, 2 Balanced). const PERSONALITY_HIGH_PERFORMANCE: u32 = 1; @@ -1141,6 +1145,11 @@ mod tests { assert_eq!(product_of(&[]), None); let long = with(40, &[b'A'; 100]); assert_eq!(product_of(&long).map(|s| s.len()), Some(64)); + // No NUL after the product: it still ends where the serial begins. + let mut unterminated = with(40, b"Model XSERIAL123\0"); + let serial = ffi::sdd::SERIAL_NUMBER_OFFSET; + unterminated[serial..serial + 4].copy_from_slice(&47u32.to_ne_bytes()); + assert_eq!(product_of(&unterminated).as_deref(), Some("Model X")); assert_eq!(drive_name(3, Some("X")), "X (PhysicalDrive3)"); assert_eq!(drive_name(0, None), "PhysicalDrive0"); } diff --git a/src/virt.rs b/src/virt.rs index dfc1849..3cdae2d 100644 --- a/src/virt.rs +++ b/src/virt.rs @@ -208,6 +208,11 @@ pub fn cloud() -> Option { *FACTS.get_or_init(crate::sys::cloud) } +/// The chassis asset tags that name a cloud: Azure's, then Oracle's. No other +/// asset tag is kept, since a tag can identify a machine. +pub(crate) const CLOUD_ASSET_TAGS: [&str; 2] = + ["7783-7084-3265-9085-8269-3286-77", "OracleCloud.com"]; + /// The firmware strings the detection reads, from sysfs or SMBIOS. #[cfg_attr(target_vendor = "apple", allow(dead_code))] #[derive(Clone, Copy, Debug, Default)] @@ -313,10 +318,10 @@ pub(crate) fn cloud_from_dmi(dmi: &Dmi<'_>, hypervisor: Option) -> O return Some(*c); } // Azure's asset tag is a fixed string; Oracle's is too. - if dmi.asset_tag == "7783-7084-3265-9085-8269-3286-77" { + if dmi.asset_tag == CLOUD_ASSET_TAGS[0] { return Some(Cloud::Azure); } - if dmi.asset_tag == "OracleCloud.com" { + if dmi.asset_tag == CLOUD_ASSET_TAGS[1] { return Some(Cloud::Oracle); } match hypervisor { diff --git a/tests/descriptors.rs b/tests/descriptors.rs index dc443d4..2a1aae4 100644 --- a/tests/descriptors.rs +++ b/tests/descriptors.rs @@ -93,7 +93,7 @@ fn every_reading() { } #[test] -fn test_no_reading_holds_a_descriptor() { +fn test_attack_t12_no_reading_holds_a_descriptor() { // The first pass opens what std and the OS open once for a process (the // loader's libraries, std's random seed): those stay, and are not // sys-lib's. The second pass must open nothing that outlives it.