Skip to main content

ostrya_sys/
lib.rs

1#![deny(unsafe_code)]
2
3//! Audited `unsafe` syscall wrappers the pure-Rust crates cannot express.
4//!
5//! The rest of the workspace is `#![forbid(unsafe_code)]`. This crate holds the
6//! `rustix` calls that require `unsafe` and cannot be reached through a safe
7//! wrapper: the fs-verity ioctls and a read-only memory map. It is
8//! `#![deny(unsafe_code)]` at the crate root with a scoped
9//! `#![allow(unsafe_code)]` on each `imp`/`mmap` module, so the audited surface
10//! stays confined. Its only dependency is `rustix`.
11//!
12//! The fs-verity entry points target the parameters ostree uses: SHA-256,
13//! 4096-byte blocks, and a zero-length salt. [`Mmap`] backs the static-delta
14//! reader, giving it random access to a decompressed part or source object that
15//! lives in a temp file rather than on the heap.
16
17mod imp {
18    #![allow(unsafe_code)]
19
20    use std::os::fd::AsFd;
21
22    use rustix::io::Result;
23    use rustix::ioctl::{Opcode, Setter, Updater, ioctl, opcode};
24
25    /// The SHA-256 fs-verity hash-algorithm identifier.
26    const FS_VERITY_HASH_ALG_SHA256: u32 = 1;
27    /// The fs-verity block size, in bytes.
28    const FS_VERITY_BLOCK_SIZE: u32 = 4096;
29
30    /// The `fsverity_enable_arg` passed to `FS_IOC_ENABLE_VERITY`, matching the
31    /// 128-byte `#[repr(C)]` kernel UAPI struct. Every field feeds the ioctl
32    /// through the raw pointer; none is read back, so the struct exists for the
33    /// kernel ABI rather than for Rust reads.
34    #[repr(C)]
35    #[derive(Clone, Copy)]
36    #[allow(dead_code)]
37    struct FsverityEnableArg {
38        version: u32,
39        hash_algorithm: u32,
40        block_size: u32,
41        salt_size: u32,
42        salt_ptr: u64,
43        sig_size: u32,
44        reserved1: u32,
45        sig_ptr: u64,
46        reserved2: [u64; 11],
47    }
48
49    /// `FS_IOC_ENABLE_VERITY = _IOW('f', 133, struct fsverity_enable_arg)`. The
50    /// opcode encodes the 128-byte argument size.
51    const FS_IOC_ENABLE_VERITY: Opcode = opcode::write::<FsverityEnableArg>(b'f', 133);
52
53    /// The header of the `fsverity_digest` request. The kernel encodes only
54    /// this 4-byte prefix in the `FS_IOC_MEASURE_VERITY` request number, because
55    /// the C struct ends in a flexible `digest[]` array.
56    #[repr(C)]
57    #[allow(dead_code)]
58    struct FsverityDigestHeader {
59        digest_algorithm: u16,
60        digest_size: u16,
61    }
62
63    /// `FS_IOC_MEASURE_VERITY = _IOWR('f', 134, struct fsverity_digest)`. The
64    /// request number is computed from the flexible-array base header, not from
65    /// the digest-sized buffer actually passed.
66    const FS_IOC_MEASURE_VERITY: Opcode = opcode::read_write::<FsverityDigestHeader>(b'f', 134);
67
68    /// A `fsverity_digest` sized for a 32-byte (SHA-256) digest.
69    #[repr(C)]
70    #[allow(dead_code)]
71    struct FsverityDigestSha256 {
72        digest_algorithm: u16,
73        digest_size: u16,
74        digest: [u8; 32],
75    }
76
77    /// Enable fs-verity on `fd` with SHA-256, 4096-byte blocks, and a zero
78    /// salt.
79    ///
80    /// The kernel refuses `FS_IOC_ENABLE_VERITY` while any writable descriptor
81    /// to the inode is open, so `fd` must be a read-only descriptor and the
82    /// sole open descriptor to the inode.
83    pub fn enable_verity(fd: impl AsFd) -> Result<()> {
84        let arg = FsverityEnableArg {
85            version: 1,
86            hash_algorithm: FS_VERITY_HASH_ALG_SHA256,
87            block_size: FS_VERITY_BLOCK_SIZE,
88            salt_size: 0,
89            salt_ptr: 0,
90            sig_size: 0,
91            reserved1: 0,
92            sig_ptr: 0,
93            reserved2: [0; 11],
94        };
95        // SAFETY: `FS_IOC_ENABLE_VERITY` expects a pointer to a
96        // `fsverity_enable_arg`. `FsverityEnableArg` is that 128-byte
97        // `#[repr(C)]` struct and the opcode is computed from the same type, so
98        // the pointed-to region has the size and layout the kernel reads. The
99        // kernel only reads the argument, matching `Setter`, rustix's
100        // read-only-pointer pattern for `_IOW` ioctls.
101        unsafe {
102            let call: Setter<{ FS_IOC_ENABLE_VERITY }, FsverityEnableArg> = Setter::new(arg);
103            ioctl(fd, call)
104        }
105    }
106
107    /// Measure the fs-verity SHA-256 digest the kernel holds for `fd`.
108    ///
109    /// `fd` must refer to a file with fs-verity enabled; the digest returned is
110    /// the same value [`enable_verity`] sealed the inode with.
111    pub fn measure_verity(fd: impl AsFd) -> Result<[u8; 32]> {
112        let mut digest = FsverityDigestSha256 {
113            digest_algorithm: 0,
114            // The input `digest_size` is the caller's buffer capacity.
115            digest_size: 32,
116            digest: [0u8; 32],
117        };
118        // SAFETY: `FS_IOC_MEASURE_VERITY` reads `digest_size` as the buffer
119        // capacity and writes the algorithm, size, and digest bytes back into
120        // the same `fsverity_digest`. `FsverityDigestSha256` is that struct
121        // sized for a 32-byte digest, so the 32-byte capacity is honest, and
122        // the opcode is derived from the flexible-array base header the kernel
123        // compares against. `Updater` is rustix's read-write-pointer pattern.
124        unsafe {
125            let call: Updater<'_, { FS_IOC_MEASURE_VERITY }, FsverityDigestSha256> =
126                Updater::new(&mut digest);
127            ioctl(fd, call)?;
128        }
129        Ok(digest.digest)
130    }
131}
132
133pub use imp::{enable_verity, measure_verity};
134pub use mmap::Mmap;
135
136mod mmap {
137    #![allow(unsafe_code)]
138
139    use std::os::fd::AsFd;
140    use std::ptr::NonNull;
141
142    use rustix::io::{Errno, Result};
143    use rustix::mm::{MapFlags, ProtFlags, mmap, munmap};
144
145    /// A read-only, private memory map of an open file.
146    ///
147    /// The static-delta reader maps a decompressed part or source object that
148    /// was spilled to a temp file, so random access (splice offsets, bspatch
149    /// source seeks) costs address space and demand-paged file cache rather than
150    /// resident heap. The mapping is never written and keeps the underlying
151    /// pages alive on its own, so the caller may drop the file descriptor once
152    /// the map exists.
153    ///
154    /// A mapping must not extend past the end of its file: reading a mapped page
155    /// with no file bytes behind it raises `SIGBUS`, which no safe API may
156    /// expose. [`Mmap::read_only`] therefore measures the file itself and
157    /// rejects an over-long request, and [`Mmap::as_slice`] is sound for the map's
158    /// whole lifetime as long as nothing truncates the file underneath it. The
159    /// static-delta reader maps only anonymous temp files it alone holds, so no
160    /// other writer can shrink one.
161    pub struct Mmap {
162        ptr: NonNull<u8>,
163        len: usize,
164    }
165
166    // SAFETY: the mapping is read-only and owns its region for its whole
167    // lifetime, so handing the immutable byte view to another thread is sound.
168    unsafe impl Send for Mmap {}
169    unsafe impl Sync for Mmap {}
170
171    impl Mmap {
172        /// Map the first `len` bytes of `fd` read-only.
173        ///
174        /// `len` must be nonzero and must not exceed the file's size. A zero
175        /// length returns `EINVAL` from `mmap`, and a length past the end of the
176        /// file returns `EINVAL` from the size check below, so a map that would
177        /// fault on read cannot be built.
178        pub fn read_only(fd: impl AsFd, len: usize) -> Result<Mmap> {
179            // A map longer than the file would hand out bytes with no file pages
180            // behind them, and touching those raises SIGBUS. Measuring the file
181            // here keeps that impossible for every caller of this safe function.
182            let size = rustix::fs::fstat(fd.as_fd())?.st_size;
183            match i64::try_from(len) {
184                Ok(len) if len <= size => {}
185                _ => return Err(Errno::INVAL),
186            }
187            // SAFETY: a null address lets the kernel place the region; PROT_READ
188            // with MAP_PRIVATE maps `len` file bytes read-only. The returned
189            // pointer is valid for `len` bytes until `munmap`, which `Drop`
190            // performs exactly once.
191            let ptr = unsafe {
192                mmap(
193                    core::ptr::null_mut(),
194                    len,
195                    ProtFlags::READ,
196                    MapFlags::PRIVATE,
197                    fd,
198                    0,
199                )?
200            };
201            let ptr = NonNull::new(ptr.cast::<u8>()).expect("mmap returns non-null on success");
202            Ok(Mmap { ptr, len })
203        }
204
205        /// The mapped bytes.
206        pub fn as_slice(&self) -> &[u8] {
207            // SAFETY: `ptr` addresses `len` readable, initialized bytes for the
208            // lifetime of `self`, and nothing mutates the region, so a shared
209            // slice over it is valid.
210            unsafe { std::slice::from_raw_parts(self.ptr.as_ptr(), self.len) }
211        }
212
213        /// The mapped length in bytes.
214        pub fn len(&self) -> usize {
215            self.len
216        }
217
218        /// Whether the map covers zero bytes. Always false in practice, since
219        /// callers map only when the blob exceeds the heap threshold.
220        pub fn is_empty(&self) -> bool {
221            self.len == 0
222        }
223    }
224
225    impl std::fmt::Debug for Mmap {
226        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
227            f.debug_struct("Mmap").field("len", &self.len).finish()
228        }
229    }
230
231    impl Drop for Mmap {
232        fn drop(&mut self) {
233            // SAFETY: `ptr`/`len` are exactly the address and length `mmap`
234            // returned, unmapped once here at end of life.
235            unsafe {
236                let _ = munmap(self.ptr.as_ptr().cast(), self.len);
237            }
238        }
239    }
240}
241
242#[cfg(test)]
243mod tests {
244    use super::{Mmap, enable_verity, measure_verity};
245    use std::fs::{File, OpenOptions};
246    use std::io::Write;
247    use std::os::fd::AsFd;
248
249    /// A map of the whole file reads its bytes back; a map longer than the file
250    /// is refused, since reading past the last file page would raise `SIGBUS`.
251    #[test]
252    fn maps_the_file_and_refuses_a_longer_map() {
253        let path = std::env::temp_dir().join(format!("ostrya-sys-mmap-{}", std::process::id()));
254        let _ = std::fs::remove_file(&path);
255        let body = b"ostrya mmap bounds";
256        {
257            let mut f = File::create(&path).unwrap();
258            f.write_all(body).unwrap();
259            f.sync_all().unwrap();
260        }
261        let ro = File::open(&path).unwrap();
262
263        let map = Mmap::read_only(ro.as_fd(), body.len()).unwrap();
264        assert_eq!(map.as_slice(), body);
265        assert_eq!(map.len(), body.len());
266        assert!(!map.is_empty());
267
268        // One byte past the end still lies inside the mapped page, so only the
269        // explicit size check can reject it.
270        assert!(
271            Mmap::read_only(ro.as_fd(), body.len() + 1).is_err(),
272            "a map longer than the file must be refused"
273        );
274        // A page past the end, and an empty map.
275        assert!(Mmap::read_only(ro.as_fd(), 8192).is_err());
276        assert!(Mmap::read_only(ro.as_fd(), 0).is_err());
277
278        drop(map);
279        let _ = std::fs::remove_file(&path);
280    }
281
282    /// Enabling verity on a filesystem that supports it seals the file (a later
283    /// write-open is rejected) and the measured digest is non-zero and stable.
284    /// Where the filesystem lacks verity the enable fails and the test skips.
285    #[test]
286    fn enable_then_measure_roundtrips() {
287        let path = std::env::temp_dir().join(format!("ostrya-sys-verity-{}", std::process::id()));
288        let _ = std::fs::remove_file(&path);
289        {
290            let mut f = File::create(&path).unwrap();
291            f.write_all(b"hello ostrya verity").unwrap();
292            f.sync_all().unwrap();
293        }
294        // The enable ioctl needs the sole open descriptor to be read-only.
295        let ro = File::open(&path).unwrap();
296        if enable_verity(ro.as_fd()).is_err() {
297            let _ = std::fs::remove_file(&path);
298            return;
299        }
300
301        let measured = measure_verity(ro.as_fd()).unwrap();
302        assert_ne!(measured, [0u8; 32], "a sealed file has a non-zero digest");
303        assert_eq!(
304            measured,
305            measure_verity(ro.as_fd()).unwrap(),
306            "the measured digest is stable"
307        );
308        assert!(
309            OpenOptions::new().write(true).open(&path).is_err(),
310            "a verity-sealed file rejects write-open"
311        );
312        let _ = std::fs::remove_file(&path);
313    }
314}