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. [`read_verity_descriptor`]
14//! reports the parameters a sealed file carries, so a caller can accept the
15//! kernel's digest only for a file sealed with those parameters. [`Mmap`] backs the static-delta
16//! reader, giving it random access to a decompressed part or source object that
17//! lives in a temp file rather than on the heap.
18
19mod imp {
20    #![allow(unsafe_code)]
21
22    use std::marker::PhantomData;
23    use std::os::fd::AsFd;
24
25    use rustix::io::{Errno, Result};
26    use rustix::ioctl::{Ioctl, IoctlOutput, Opcode, Setter, Updater, ioctl, opcode};
27
28    /// The SHA-256 fs-verity hash-algorithm identifier.
29    const FS_VERITY_HASH_ALG_SHA256: u32 = 1;
30    /// The fs-verity block size, in bytes.
31    const FS_VERITY_BLOCK_SIZE: u32 = 4096;
32
33    /// The `fsverity_enable_arg` passed to `FS_IOC_ENABLE_VERITY`, matching the
34    /// 128-byte `#[repr(C)]` kernel UAPI struct. Every field feeds the ioctl
35    /// through the raw pointer; none is read back, so the struct exists for the
36    /// kernel ABI rather than for Rust reads.
37    #[repr(C)]
38    #[derive(Clone, Copy)]
39    #[allow(dead_code)]
40    struct FsverityEnableArg {
41        version: u32,
42        hash_algorithm: u32,
43        block_size: u32,
44        salt_size: u32,
45        salt_ptr: u64,
46        sig_size: u32,
47        reserved1: u32,
48        sig_ptr: u64,
49        reserved2: [u64; 11],
50    }
51
52    /// `FS_IOC_ENABLE_VERITY = _IOW('f', 133, struct fsverity_enable_arg)`. The
53    /// opcode encodes the 128-byte argument size.
54    const FS_IOC_ENABLE_VERITY: Opcode = opcode::write::<FsverityEnableArg>(b'f', 133);
55
56    /// The header of the `fsverity_digest` request. The kernel encodes only
57    /// this 4-byte prefix in the `FS_IOC_MEASURE_VERITY` request number, because
58    /// the C struct ends in a flexible `digest[]` array.
59    #[repr(C)]
60    #[allow(dead_code)]
61    struct FsverityDigestHeader {
62        digest_algorithm: u16,
63        digest_size: u16,
64    }
65
66    /// `FS_IOC_MEASURE_VERITY = _IOWR('f', 134, struct fsverity_digest)`. The
67    /// request number is computed from the flexible-array base header, not from
68    /// the digest-sized buffer actually passed.
69    const FS_IOC_MEASURE_VERITY: Opcode = opcode::read_write::<FsverityDigestHeader>(b'f', 134);
70
71    /// A `fsverity_digest` sized for a 32-byte (SHA-256) digest.
72    #[repr(C)]
73    #[allow(dead_code)]
74    struct FsverityDigestSha256 {
75        digest_algorithm: u16,
76        digest_size: u16,
77        digest: [u8; 32],
78    }
79
80    /// Enable fs-verity on `fd` with SHA-256, 4096-byte blocks, and a zero
81    /// salt.
82    ///
83    /// The kernel refuses `FS_IOC_ENABLE_VERITY` while any writable descriptor
84    /// to the inode is open, so `fd` must be a read-only descriptor and the
85    /// sole open descriptor to the inode.
86    pub fn enable_verity(fd: impl AsFd) -> Result<()> {
87        enable(fd, &[])
88    }
89
90    /// Enable fs-verity on `fd` with SHA-256, 4096-byte blocks, and `salt`.
91    ///
92    /// The tests use this to make a file sealed with parameters other than the
93    /// ones ostree uses. The kernel refuses a salt longer than 32 bytes. The
94    /// descriptor rules of [`enable_verity`] apply.
95    #[doc(hidden)]
96    pub fn enable_verity_with_salt(fd: impl AsFd, salt: &[u8]) -> Result<()> {
97        enable(fd, salt)
98    }
99
100    /// Enable fs-verity on `fd` with SHA-256, 4096-byte blocks, and `salt`. An
101    /// empty salt passes a null salt pointer.
102    fn enable(fd: impl AsFd, salt: &[u8]) -> Result<()> {
103        let salt_size = u32::try_from(salt.len()).map_err(|_| Errno::INVAL)?;
104        let arg = FsverityEnableArg {
105            version: 1,
106            hash_algorithm: FS_VERITY_HASH_ALG_SHA256,
107            block_size: FS_VERITY_BLOCK_SIZE,
108            salt_size,
109            salt_ptr: if salt.is_empty() {
110                0
111            } else {
112                salt.as_ptr() as u64
113            },
114            sig_size: 0,
115            reserved1: 0,
116            sig_ptr: 0,
117            reserved2: [0; 11],
118        };
119        // SAFETY: `FS_IOC_ENABLE_VERITY` expects a pointer to a
120        // `fsverity_enable_arg`. `FsverityEnableArg` is that 128-byte
121        // `#[repr(C)]` struct and the opcode is computed from the same type, so
122        // the pointed-to region has the size and layout the kernel reads. The
123        // kernel only reads the argument, matching `Setter`, rustix's
124        // read-only-pointer pattern for `_IOW` ioctls. A nonzero `salt_ptr`
125        // addresses `salt`, which is borrowed for this whole call, and
126        // `salt_size` is its length, so the kernel reads only live bytes. The
127        // ioctl is synchronous, so the kernel holds no pointer after it returns.
128        unsafe {
129            let call: Setter<{ FS_IOC_ENABLE_VERITY }, FsverityEnableArg> = Setter::new(arg);
130            ioctl(fd, call)
131        }
132    }
133
134    /// Measure the fs-verity SHA-256 digest the kernel holds for `fd`.
135    ///
136    /// `fd` must refer to a file with fs-verity enabled; the digest returned is
137    /// the same value [`enable_verity`] sealed the inode with.
138    pub fn measure_verity(fd: impl AsFd) -> Result<[u8; 32]> {
139        let mut digest = FsverityDigestSha256 {
140            digest_algorithm: 0,
141            // The input `digest_size` is the caller's buffer capacity.
142            digest_size: 32,
143            digest: [0u8; 32],
144        };
145        // SAFETY: `FS_IOC_MEASURE_VERITY` reads `digest_size` as the buffer
146        // capacity and writes the algorithm, size, and digest bytes back into
147        // the same `fsverity_digest`. `FsverityDigestSha256` is that struct
148        // sized for a 32-byte digest, so the 32-byte capacity is honest, and
149        // the opcode is derived from the flexible-array base header the kernel
150        // compares against. `Updater` is rustix's read-write-pointer pattern.
151        unsafe {
152            let call: Updater<'_, { FS_IOC_MEASURE_VERITY }, FsverityDigestSha256> =
153                Updater::new(&mut digest);
154            ioctl(fd, call)?;
155        }
156        // A file sealed with another algorithm reports that algorithm. The
157        // bytes returned are an ostree digest only for SHA-256 with 32 bytes.
158        if u32::from(digest.digest_algorithm) != FS_VERITY_HASH_ALG_SHA256
159            || digest.digest_size != 32
160        {
161            return Err(Errno::INVAL);
162        }
163        Ok(digest.digest)
164    }
165
166    /// The `FS_IOC_READ_VERITY_METADATA` metadata type that selects the
167    /// fs-verity descriptor.
168    const FS_VERITY_METADATA_TYPE_DESCRIPTOR: u64 = 2;
169    /// The size of `struct fsverity_descriptor`, in bytes.
170    const DESCRIPTOR_SIZE: usize = 256;
171
172    /// The `fsverity_read_metadata_arg` passed to
173    /// `FS_IOC_READ_VERITY_METADATA`, matching the 40-byte `#[repr(C)]` kernel
174    /// UAPI struct. The kernel reads every field and writes none of them back.
175    #[repr(C)]
176    #[allow(dead_code)]
177    struct FsverityReadMetadataArg {
178        metadata_type: u64,
179        offset: u64,
180        length: u64,
181        buf_ptr: u64,
182        reserved: u64,
183    }
184
185    /// `FS_IOC_READ_VERITY_METADATA = _IOWR('f', 135, struct
186    /// fsverity_read_metadata_arg)`. The opcode encodes the 40-byte argument
187    /// size.
188    const FS_IOC_READ_VERITY_METADATA: Opcode =
189        opcode::read_write::<FsverityReadMetadataArg>(b'f', 135);
190
191    /// The `FS_IOC_READ_VERITY_METADATA` call. The kernel writes into the
192    /// buffer `buf_ptr` addresses and returns the number of bytes it wrote,
193    /// which no rustix pattern returns. The lifetime ties the call to the
194    /// mutable borrow of that buffer, so the buffer outlives the call.
195    struct ReadMetadata<'a> {
196        arg: FsverityReadMetadataArg,
197        buf: PhantomData<&'a mut [u8]>,
198    }
199
200    impl<'a> ReadMetadata<'a> {
201        /// A request for the file's descriptor into `buf`, from offset 0. The
202        /// pointer and length come from the one slice, so the length the
203        /// kernel honors is the length of the memory behind the pointer.
204        fn descriptor(buf: &'a mut [u8]) -> Self {
205            ReadMetadata {
206                arg: FsverityReadMetadataArg {
207                    metadata_type: FS_VERITY_METADATA_TYPE_DESCRIPTOR,
208                    offset: 0,
209                    length: buf.len() as u64,
210                    buf_ptr: buf.as_mut_ptr() as u64,
211                    reserved: 0,
212                },
213                buf: PhantomData,
214            }
215        }
216    }
217
218    // SAFETY: the opcode is the `_IOWR` number computed from the argument type
219    // the kernel expects, and `as_ptr` points at that argument. The kernel
220    // writes into the user buffer the argument names, so the call mutates user
221    // memory and `IS_MUTATING` is true. `output_from_ptr` reads nothing
222    // through the pointer; it converts the non-negative byte count a
223    // successful call returns.
224    unsafe impl Ioctl for ReadMetadata<'_> {
225        type Output = usize;
226
227        const IS_MUTATING: bool = true;
228
229        fn opcode(&self) -> Opcode {
230            FS_IOC_READ_VERITY_METADATA
231        }
232
233        fn as_ptr(&mut self) -> *mut core::ffi::c_void {
234            (&mut self.arg as *mut FsverityReadMetadataArg).cast()
235        }
236
237        unsafe fn output_from_ptr(
238            out: IoctlOutput,
239            _: *mut core::ffi::c_void,
240        ) -> Result<Self::Output> {
241            usize::try_from(out).map_err(|_| Errno::INVAL)
242        }
243    }
244
245    /// The fields of a file's `fsverity_descriptor` that name the parameters
246    /// the file was sealed with.
247    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
248    pub struct VerityDescriptor {
249        /// The descriptor format version. The kernel writes 1.
250        pub version: u8,
251        /// The hash-algorithm identifier. SHA-256 is 1.
252        pub hash_algorithm: u8,
253        /// The base-2 logarithm of the Merkle-tree block size. 4096 bytes is 12.
254        pub log_blocksize: u8,
255        /// The salt length in bytes. Zero when the file has no salt.
256        pub salt_size: u8,
257        /// The size of the file's data in bytes when it was sealed.
258        pub data_size: u64,
259    }
260
261    /// Read the fs-verity descriptor the kernel holds for `fd`.
262    ///
263    /// `fd` must refer to a file with fs-verity enabled. A file without
264    /// fs-verity returns `ENODATA`, and a kernel without the ioctl returns
265    /// `ENOTTY`. A descriptor shorter than the 256-byte struct returns `EIO`.
266    pub fn read_verity_descriptor(fd: impl AsFd) -> Result<VerityDescriptor> {
267        let mut buf = [0u8; DESCRIPTOR_SIZE];
268        // SAFETY: `ReadMetadata::descriptor` takes `buf_ptr` and `length` from
269        // the one mutable borrow of `buf`, a local that lives past this call,
270        // so the kernel writes at most `buf.len()` bytes into memory this
271        // function owns. The borrow ends when `ioctl` consumes the request.
272        // The ioctl is synchronous, so the kernel holds no pointer after it
273        // returns, and `buf` is read only after the call.
274        let n = unsafe { ioctl(fd, ReadMetadata::descriptor(&mut buf))? };
275        if n < DESCRIPTOR_SIZE {
276            return Err(Errno::IO);
277        }
278        Ok(VerityDescriptor {
279            version: buf[0],
280            hash_algorithm: buf[1],
281            log_blocksize: buf[2],
282            salt_size: buf[3],
283            data_size: u64::from_le_bytes(buf[8..16].try_into().expect("8-byte field")),
284        })
285    }
286}
287
288pub use imp::{
289    VerityDescriptor, enable_verity, enable_verity_with_salt, measure_verity,
290    read_verity_descriptor,
291};
292pub use mmap::Mmap;
293
294mod mmap {
295    #![allow(unsafe_code)]
296
297    use std::os::fd::AsFd;
298    use std::ptr::NonNull;
299
300    use rustix::io::{Errno, Result};
301    use rustix::mm::{MapFlags, ProtFlags, mmap, munmap};
302
303    /// A read-only, private memory map of an open file.
304    ///
305    /// The static-delta reader maps a decompressed part or source object that
306    /// was spilled to a temp file, so random access (splice offsets, bspatch
307    /// source seeks) costs address space and demand-paged file cache rather than
308    /// resident heap. The mapping is never written and keeps the underlying
309    /// pages alive on its own, so the caller may drop the file descriptor once
310    /// the map exists.
311    ///
312    /// A mapping must not extend past the end of its file: reading a mapped page
313    /// with no file bytes behind it raises `SIGBUS`, which no safe API may
314    /// expose. [`Mmap::read_only`] therefore measures the file itself and
315    /// rejects an over-long request, and [`Mmap::as_slice`] is sound for the map's
316    /// whole lifetime as long as nothing truncates the file underneath it. The
317    /// static-delta reader maps only anonymous temp files it alone holds, so no
318    /// other writer can shrink one.
319    pub struct Mmap {
320        ptr: NonNull<u8>,
321        len: usize,
322    }
323
324    // SAFETY: the mapping is read-only and owns its region for its whole
325    // lifetime, so handing the immutable byte view to another thread is sound.
326    unsafe impl Send for Mmap {}
327    unsafe impl Sync for Mmap {}
328
329    impl Mmap {
330        /// Map the first `len` bytes of `fd` read-only.
331        ///
332        /// `len` must be nonzero and must not exceed the file's size. A zero
333        /// length returns `EINVAL` from `mmap`, and a length past the end of the
334        /// file returns `EINVAL` from the size check below, so a map that would
335        /// fault on read cannot be built.
336        pub fn read_only(fd: impl AsFd, len: usize) -> Result<Mmap> {
337            // A map longer than the file would hand out bytes with no file pages
338            // behind them, and touching those raises SIGBUS. Measuring the file
339            // here keeps that impossible for every caller of this safe function.
340            let size = rustix::fs::fstat(fd.as_fd())?.st_size;
341            match i64::try_from(len) {
342                Ok(len) if len <= size => {}
343                _ => return Err(Errno::INVAL),
344            }
345            // SAFETY: a null address lets the kernel place the region; PROT_READ
346            // with MAP_PRIVATE maps `len` file bytes read-only. The returned
347            // pointer is valid for `len` bytes until `munmap`, which `Drop`
348            // performs exactly once.
349            let ptr = unsafe {
350                mmap(
351                    core::ptr::null_mut(),
352                    len,
353                    ProtFlags::READ,
354                    MapFlags::PRIVATE,
355                    fd,
356                    0,
357                )?
358            };
359            let ptr = NonNull::new(ptr.cast::<u8>()).expect("mmap returns non-null on success");
360            Ok(Mmap { ptr, len })
361        }
362
363        /// The mapped bytes.
364        pub fn as_slice(&self) -> &[u8] {
365            // SAFETY: `ptr` addresses `len` readable, initialized bytes for the
366            // lifetime of `self`, and nothing mutates the region, so a shared
367            // slice over it is valid.
368            unsafe { std::slice::from_raw_parts(self.ptr.as_ptr(), self.len) }
369        }
370
371        /// The mapped length in bytes.
372        pub fn len(&self) -> usize {
373            self.len
374        }
375
376        /// Whether the map covers zero bytes. Always false in practice, since
377        /// callers map only when the blob exceeds the heap threshold.
378        pub fn is_empty(&self) -> bool {
379            self.len == 0
380        }
381    }
382
383    impl std::fmt::Debug for Mmap {
384        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
385            f.debug_struct("Mmap").field("len", &self.len).finish()
386        }
387    }
388
389    impl Drop for Mmap {
390        fn drop(&mut self) {
391            // SAFETY: `ptr`/`len` are exactly the address and length `mmap`
392            // returned, unmapped once here at end of life.
393            unsafe {
394                let _ = munmap(self.ptr.as_ptr().cast(), self.len);
395            }
396        }
397    }
398}
399
400#[cfg(test)]
401mod tests {
402    use super::{
403        Mmap, enable_verity, enable_verity_with_salt, measure_verity, read_verity_descriptor,
404    };
405    use std::fs::{File, OpenOptions};
406    use std::io::Write;
407    use std::os::fd::AsFd;
408
409    /// A map of the whole file reads its bytes back; a map longer than the file
410    /// is refused, since reading past the last file page would raise `SIGBUS`.
411    #[test]
412    fn maps_the_file_and_refuses_a_longer_map() {
413        let path = std::env::temp_dir().join(format!("ostrya-sys-mmap-{}", std::process::id()));
414        let _ = std::fs::remove_file(&path);
415        let body = b"ostrya mmap bounds";
416        {
417            let mut f = File::create(&path).unwrap();
418            f.write_all(body).unwrap();
419            f.sync_all().unwrap();
420        }
421        let ro = File::open(&path).unwrap();
422
423        let map = Mmap::read_only(ro.as_fd(), body.len()).unwrap();
424        assert_eq!(map.as_slice(), body);
425        assert_eq!(map.len(), body.len());
426        assert!(!map.is_empty());
427
428        // One byte past the end still lies inside the mapped page, so only the
429        // explicit size check can reject it.
430        assert!(
431            Mmap::read_only(ro.as_fd(), body.len() + 1).is_err(),
432            "a map longer than the file must be refused"
433        );
434        // A page past the end, and an empty map.
435        assert!(Mmap::read_only(ro.as_fd(), 8192).is_err());
436        assert!(Mmap::read_only(ro.as_fd(), 0).is_err());
437
438        drop(map);
439        let _ = std::fs::remove_file(&path);
440    }
441
442    /// Enabling verity on a filesystem that supports it seals the file (a later
443    /// write-open is rejected) and the measured digest is non-zero and stable.
444    /// Where the filesystem lacks verity the enable fails and the test skips.
445    #[test]
446    fn enable_then_measure_roundtrips() {
447        let path = std::env::temp_dir().join(format!("ostrya-sys-verity-{}", std::process::id()));
448        let _ = std::fs::remove_file(&path);
449        {
450            let mut f = File::create(&path).unwrap();
451            f.write_all(b"hello ostrya verity").unwrap();
452            f.sync_all().unwrap();
453        }
454        // The enable ioctl needs the sole open descriptor to be read-only.
455        let ro = File::open(&path).unwrap();
456        if enable_verity(ro.as_fd()).is_err() {
457            let _ = std::fs::remove_file(&path);
458            return;
459        }
460
461        let measured = measure_verity(ro.as_fd()).unwrap();
462        assert_ne!(measured, [0u8; 32], "a sealed file has a non-zero digest");
463        assert_eq!(
464            measured,
465            measure_verity(ro.as_fd()).unwrap(),
466            "the measured digest is stable"
467        );
468        assert!(
469            OpenOptions::new().write(true).open(&path).is_err(),
470            "a verity-sealed file rejects write-open"
471        );
472        let _ = std::fs::remove_file(&path);
473    }
474
475    /// Write `body` to a fresh file named for `tag` and open it read-only, the
476    /// descriptor the enable ioctl needs.
477    fn read_only_file(tag: &str, body: &[u8]) -> (std::path::PathBuf, File) {
478        let path = std::env::temp_dir().join(format!("ostrya-sys-{tag}-{}", std::process::id()));
479        let _ = std::fs::remove_file(&path);
480        {
481            let mut f = File::create(&path).unwrap();
482            f.write_all(body).unwrap();
483            f.sync_all().unwrap();
484        }
485        let ro = File::open(&path).unwrap();
486        (path, ro)
487    }
488
489    /// The descriptor of a file [`enable_verity`] sealed names SHA-256,
490    /// 4096-byte blocks, no salt, and the file's size. Skips where the
491    /// filesystem lacks verity.
492    #[test]
493    fn descriptor_reports_the_ostree_parameters() {
494        let body = b"ostrya verity descriptor".repeat(300);
495        let (path, ro) = read_only_file("verity-descriptor", &body);
496        if let Err(e) = enable_verity(ro.as_fd()) {
497            eprintln!("skipping descriptor check: filesystem lacks fs-verity ({e})");
498            let _ = std::fs::remove_file(&path);
499            return;
500        }
501
502        let desc = read_verity_descriptor(ro.as_fd()).unwrap();
503        assert_eq!(desc.version, 1);
504        assert_eq!(desc.hash_algorithm, 1, "SHA-256");
505        assert_eq!(desc.log_blocksize, 12, "4096-byte blocks");
506        assert_eq!(desc.salt_size, 0);
507        assert_eq!(desc.data_size, body.len() as u64);
508        let _ = std::fs::remove_file(&path);
509    }
510
511    /// A file sealed with a salt reports the salt length, and its digest
512    /// differs from the digest of the same bytes sealed without a salt. Skips
513    /// where the filesystem lacks verity.
514    #[test]
515    fn descriptor_reports_a_salt() {
516        let body = b"ostrya salted verity";
517        let (plain_path, plain) = read_only_file("verity-unsalted", body);
518        if let Err(e) = enable_verity(plain.as_fd()) {
519            eprintln!("skipping salt check: filesystem lacks fs-verity ({e})");
520            let _ = std::fs::remove_file(&plain_path);
521            return;
522        }
523        let (path, ro) = read_only_file("verity-salted", body);
524        enable_verity_with_salt(ro.as_fd(), &[0x5a; 8]).unwrap();
525
526        let desc = read_verity_descriptor(ro.as_fd()).unwrap();
527        assert_eq!(desc.hash_algorithm, 1);
528        assert_eq!(desc.log_blocksize, 12);
529        assert_eq!(desc.salt_size, 8);
530        assert_ne!(
531            measure_verity(ro.as_fd()).unwrap(),
532            measure_verity(plain.as_fd()).unwrap(),
533            "the salt changes the digest"
534        );
535        let _ = std::fs::remove_file(&path);
536        let _ = std::fs::remove_file(&plain_path);
537    }
538
539    /// A file without fs-verity has no descriptor to read.
540    #[test]
541    fn descriptor_of_an_unsealed_file_is_an_error() {
542        let (path, ro) = read_only_file("verity-unsealed", b"not sealed");
543        assert!(read_verity_descriptor(ro.as_fd()).is_err());
544        assert!(measure_verity(ro.as_fd()).is_err());
545        let _ = std::fs::remove_file(&path);
546    }
547}