ostrya_sys/lib.rs
1#![deny(unsafe_code)]
2
3//! Wrappers for the Linux fs-verity ioctls and for a read-only memory map.
4//!
5//! A caller seals a file with fs-verity and reads the digest and the
6//! parameters that the kernel holds for the sealed file. The seal has the
7//! parameters that ostree uses: SHA-256, 4096-byte blocks, and no salt. A
8//! caller can also map a file read-only. The only dependency of the crate is
9//! `rustix`.
10//!
11//! # Entry points
12//!
13//! - [`enable_verity`] seals a file with fs-verity.
14//! - [`measure_verity`] returns the fs-verity digest of a sealed file.
15//! - [`read_verity_descriptor`] returns the parameters of a sealed file.
16//! - [`Mmap`] is a read-only memory map of a file.
17//!
18//! # Examples
19//!
20//! The example seals a file and reads its parameters and its digest. The file
21//! system of the file must support fs-verity.
22//!
23//! ```no_run
24//! use std::fs::File;
25//!
26//! use ostrya_sys::{enable_verity, measure_verity, read_verity_descriptor};
27//!
28//! // A read-only descriptor, and no writable descriptor to the file.
29//! let file = File::open("object.file")?;
30//! enable_verity(&file)?;
31//! let desc = read_verity_descriptor(&file)?;
32//! // SHA-256, 4096-byte blocks (2 to the power 12), and no salt.
33//! assert_eq!((desc.hash_algorithm, desc.log_blocksize, desc.salt_size), (1, 12, 0));
34//! let digest: [u8; 32] = measure_verity(&file)?;
35//! # let _ = digest;
36//! # Ok::<(), std::io::Error>(())
37//! ```
38//!
39//! This crate holds all `unsafe` code of the ostrya library crates. A
40//! `SAFETY` comment on each `unsafe` block gives its reasoning.
41
42// All other library crates of ostrya are `#![forbid(unsafe_code)]`. This crate
43// holds the `rustix` calls that need `unsafe` and that no safe `rustix` wrapper
44// gives. The crate root is `#![deny(unsafe_code)]`. Each of the modules `imp`
45// and `mmap` has a scoped `#![allow(unsafe_code)]`, so the audited `unsafe`
46// code stays in these two modules.
47
48mod imp {
49 #![allow(unsafe_code)]
50
51 use std::marker::PhantomData;
52 use std::os::fd::AsFd;
53
54 use rustix::io::{Errno, Result};
55 use rustix::ioctl::{Ioctl, IoctlOutput, Opcode, Setter, Updater, ioctl, opcode};
56
57 /// The SHA-256 fs-verity hash-algorithm identifier.
58 const FS_VERITY_HASH_ALG_SHA256: u32 = 1;
59 /// The fs-verity block size, in bytes.
60 const FS_VERITY_BLOCK_SIZE: u32 = 4096;
61
62 /// The `fsverity_enable_arg` argument of `FS_IOC_ENABLE_VERITY`.
63 ///
64 /// The struct has the layout of the 128-byte kernel UAPI struct. The
65 /// kernel reads each field through the raw pointer. No Rust code reads a
66 /// field, so the struct exists only for the kernel ABI.
67 #[repr(C)]
68 #[derive(Clone, Copy)]
69 #[allow(dead_code)]
70 struct FsverityEnableArg {
71 version: u32,
72 hash_algorithm: u32,
73 block_size: u32,
74 salt_size: u32,
75 salt_ptr: u64,
76 sig_size: u32,
77 reserved1: u32,
78 sig_ptr: u64,
79 reserved2: [u64; 11],
80 }
81
82 /// `FS_IOC_ENABLE_VERITY = _IOW('f', 133, struct fsverity_enable_arg)`. The
83 /// opcode encodes the 128-byte argument size.
84 const FS_IOC_ENABLE_VERITY: Opcode = opcode::write::<FsverityEnableArg>(b'f', 133);
85
86 /// The 4-byte header of the `fsverity_digest` request.
87 ///
88 /// The `FS_IOC_MEASURE_VERITY` request number encodes only the size of
89 /// this header, because the C struct ends in a flexible `digest[]` array.
90 #[repr(C)]
91 #[allow(dead_code)]
92 struct FsverityDigestHeader {
93 digest_algorithm: u16,
94 digest_size: u16,
95 }
96
97 /// `FS_IOC_MEASURE_VERITY = _IOWR('f', 134, struct fsverity_digest)`. The
98 /// request number comes from `FsverityDigestHeader`, the base header of the
99 /// flexible array. The buffer that the call passes is larger.
100 const FS_IOC_MEASURE_VERITY: Opcode = opcode::read_write::<FsverityDigestHeader>(b'f', 134);
101
102 /// A `fsverity_digest` with space for a 32-byte SHA-256 digest.
103 #[repr(C)]
104 #[allow(dead_code)]
105 struct FsverityDigestSha256 {
106 digest_algorithm: u16,
107 digest_size: u16,
108 digest: [u8; 32],
109 }
110
111 /// Enables fs-verity on `fd` with SHA-256, 4096-byte blocks, and no salt.
112 ///
113 /// `fd` must be a read-only descriptor. The kernel refuses the call while a
114 /// process has the file open for writing, also through a writable memory
115 /// map. Other read-only descriptors to the file can stay open. After the
116 /// call, an open of the file for writing fails with `EPERM`.
117 ///
118 /// # Errors
119 ///
120 /// The function returns the `Errno` of the `FS_IOC_ENABLE_VERITY` ioctl.
121 /// The Linux kernel documentation of fs-verity gives these values:
122 ///
123 /// - `ETXTBSY` if the file is open for writing through `fd`, another
124 /// descriptor, or a writable memory map.
125 /// - `EEXIST` if fs-verity is already enabled on the file.
126 /// - `EACCES` if the process has no write access to the file.
127 /// - `EPERM` if the file is append-only, or if the kernel requires a
128 /// built-in signature. This function gives no signature.
129 /// - `EROFS` if the file system is read-only.
130 /// - `EISDIR` if `fd` refers to a directory.
131 /// - `EINVAL` if the file system does not accept a 4096-byte block, or if
132 /// `fd` refers to neither a regular file nor a directory.
133 /// - `ENOTTY` or `EOPNOTSUPP` if the file system or the kernel has no
134 /// fs-verity support.
135 /// - `EINTR` if a fatal signal interrupts the call.
136 /// - Another `Errno` for other failures.
137 ///
138 /// If `fd` is open for writing only, Linux 6.18 on btrfs returns `EBADF`.
139 /// The kernel documentation does not state this value.
140 pub fn enable_verity(fd: impl AsFd) -> Result<()> {
141 enable(fd, &[])
142 }
143
144 /// Enables fs-verity on `fd` with SHA-256, 4096-byte blocks, and `salt`.
145 ///
146 /// The tests use this function to seal a file with parameters that are
147 /// not the parameters of ostree. The descriptor rules of [`enable_verity`]
148 /// apply.
149 ///
150 /// # Errors
151 ///
152 /// - `EINVAL` if the length of `salt` does not fit in a `u32`.
153 /// - `EMSGSIZE` from the kernel if `salt` is longer than 32 bytes.
154 /// - The `Errno` values of [`enable_verity`].
155 #[doc(hidden)]
156 pub fn enable_verity_with_salt(fd: impl AsFd, salt: &[u8]) -> Result<()> {
157 enable(fd, salt)
158 }
159
160 /// Enables fs-verity on `fd` with SHA-256, 4096-byte blocks, and `salt`.
161 /// An empty `salt` gives a null salt pointer.
162 fn enable(fd: impl AsFd, salt: &[u8]) -> Result<()> {
163 let salt_size = u32::try_from(salt.len()).map_err(|_| Errno::INVAL)?;
164 let arg = FsverityEnableArg {
165 version: 1,
166 hash_algorithm: FS_VERITY_HASH_ALG_SHA256,
167 block_size: FS_VERITY_BLOCK_SIZE,
168 salt_size,
169 salt_ptr: if salt.is_empty() {
170 0
171 } else {
172 salt.as_ptr() as u64
173 },
174 sig_size: 0,
175 reserved1: 0,
176 sig_ptr: 0,
177 reserved2: [0; 11],
178 };
179 // SAFETY: `FS_IOC_ENABLE_VERITY` expects a pointer to a
180 // `fsverity_enable_arg`. `FsverityEnableArg` is that 128-byte
181 // `#[repr(C)]` struct. The opcode comes from the same type, so the
182 // memory at the pointer has the size and the layout that the kernel
183 // reads. The kernel only reads the argument. This matches `Setter`, the
184 // rustix pattern for the read-only pointer of an `_IOW` ioctl. A
185 // nonzero `salt_ptr` points to `salt`, which is borrowed for this whole
186 // call. `salt_size` is the length of `salt`, so the kernel reads only
187 // live bytes. The ioctl is synchronous, so the kernel holds no pointer
188 // after it returns.
189 unsafe {
190 let call: Setter<{ FS_IOC_ENABLE_VERITY }, FsverityEnableArg> = Setter::new(arg);
191 ioctl(fd, call)
192 }
193 }
194
195 /// Returns the fs-verity SHA-256 digest that the kernel holds for `fd`.
196 ///
197 /// `fd` must refer to a file with fs-verity enabled, for example by
198 /// [`enable_verity`]. The function returns the digest of each file sealed
199 /// with SHA-256, also with a salt or another block size.
200 /// [`read_verity_descriptor`] returns these parameters.
201 ///
202 /// # Errors
203 ///
204 /// - `EINVAL` if the kernel reports a hash algorithm that is not SHA-256,
205 /// or a digest size that is not 32 bytes.
206 /// - `ENODATA` from the kernel if fs-verity is not enabled on the file.
207 /// - `EOVERFLOW` from the kernel if the digest of the file is longer than
208 /// 32 bytes. A file sealed with SHA-512 has a 64-byte digest.
209 /// - `ENOTTY` or `EOPNOTSUPP` from the kernel if the file system or the
210 /// kernel has no fs-verity support.
211 /// - Another `Errno` from the `FS_IOC_MEASURE_VERITY` ioctl.
212 pub fn measure_verity(fd: impl AsFd) -> Result<[u8; 32]> {
213 let mut digest = FsverityDigestSha256 {
214 digest_algorithm: 0,
215 // On input, `digest_size` is the capacity of the buffer.
216 digest_size: 32,
217 digest: [0u8; 32],
218 };
219 // SAFETY: `FS_IOC_MEASURE_VERITY` reads `digest_size` as the capacity
220 // of the buffer. It writes the algorithm, the size, and the digest
221 // bytes back into the same `fsverity_digest`. `FsverityDigestSha256`
222 // is that struct with space for a 32-byte digest, so the capacity of
223 // 32 bytes is correct. The opcode comes from the base header of the
224 // flexible array, which is the size that the kernel compares against.
225 // `Updater` is the rustix pattern for a read-write pointer.
226 unsafe {
227 let call: Updater<'_, { FS_IOC_MEASURE_VERITY }, FsverityDigestSha256> =
228 Updater::new(&mut digest);
229 ioctl(fd, call)?;
230 }
231 // The kernel reports the algorithm that sealed the file. The bytes are
232 // an ostree digest only for SHA-256 with 32 bytes.
233 if u32::from(digest.digest_algorithm) != FS_VERITY_HASH_ALG_SHA256
234 || digest.digest_size != 32
235 {
236 return Err(Errno::INVAL);
237 }
238 Ok(digest.digest)
239 }
240
241 /// The `FS_IOC_READ_VERITY_METADATA` metadata type that selects the
242 /// fs-verity descriptor.
243 const FS_VERITY_METADATA_TYPE_DESCRIPTOR: u64 = 2;
244 /// The size of `struct fsverity_descriptor`, in bytes.
245 const DESCRIPTOR_SIZE: usize = 256;
246
247 /// The `fsverity_read_metadata_arg` argument of
248 /// `FS_IOC_READ_VERITY_METADATA`.
249 ///
250 /// The struct has the layout of the 40-byte kernel UAPI struct. The kernel
251 /// reads each field and writes no field back.
252 #[repr(C)]
253 #[allow(dead_code)]
254 struct FsverityReadMetadataArg {
255 metadata_type: u64,
256 offset: u64,
257 length: u64,
258 buf_ptr: u64,
259 reserved: u64,
260 }
261
262 /// `FS_IOC_READ_VERITY_METADATA = _IOWR('f', 135, struct
263 /// fsverity_read_metadata_arg)`. The opcode encodes the 40-byte argument
264 /// size.
265 const FS_IOC_READ_VERITY_METADATA: Opcode =
266 opcode::read_write::<FsverityReadMetadataArg>(b'f', 135);
267
268 /// The `FS_IOC_READ_VERITY_METADATA` call.
269 ///
270 /// The kernel writes into the buffer at `buf_ptr` and returns the number of
271 /// bytes that it wrote. No rustix pattern returns this count. The lifetime
272 /// ties the call to the mutable borrow of the buffer, so the buffer lives
273 /// longer than the call.
274 struct ReadMetadata<'a> {
275 arg: FsverityReadMetadataArg,
276 buf: PhantomData<&'a mut [u8]>,
277 }
278
279 impl<'a> ReadMetadata<'a> {
280 /// Returns a request that reads the fs-verity descriptor into `buf`.
281 ///
282 /// The read starts at offset 0. The pointer and the length come from
283 /// the same slice, so the kernel obeys the length of the memory at the
284 /// pointer.
285 fn descriptor(buf: &'a mut [u8]) -> Self {
286 ReadMetadata {
287 arg: FsverityReadMetadataArg {
288 metadata_type: FS_VERITY_METADATA_TYPE_DESCRIPTOR,
289 offset: 0,
290 length: buf.len() as u64,
291 buf_ptr: buf.as_mut_ptr() as u64,
292 reserved: 0,
293 },
294 buf: PhantomData,
295 }
296 }
297 }
298
299 // SAFETY: the opcode is the `_IOWR` number that comes from the argument
300 // type that the kernel expects, and `as_ptr` points at that argument. The
301 // kernel writes into the user buffer that the argument names, so the call
302 // changes user memory and `IS_MUTATING` is true. `output_from_ptr` reads
303 // nothing through the pointer. It converts the non-negative byte count
304 // that a successful call returns.
305 unsafe impl Ioctl for ReadMetadata<'_> {
306 type Output = usize;
307
308 const IS_MUTATING: bool = true;
309
310 fn opcode(&self) -> Opcode {
311 FS_IOC_READ_VERITY_METADATA
312 }
313
314 fn as_ptr(&mut self) -> *mut core::ffi::c_void {
315 (&mut self.arg as *mut FsverityReadMetadataArg).cast()
316 }
317
318 unsafe fn output_from_ptr(
319 out: IoctlOutput,
320 _: *mut core::ffi::c_void,
321 ) -> Result<Self::Output> {
322 usize::try_from(out).map_err(|_| Errno::INVAL)
323 }
324 }
325
326 /// The fs-verity parameters of a sealed file, from its `fsverity_descriptor`.
327 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
328 pub struct VerityDescriptor {
329 /// The format version of the descriptor, which the kernel sets to 1.
330 pub version: u8,
331 /// The identifier of the hash algorithm, 1 for SHA-256.
332 pub hash_algorithm: u8,
333 /// The base-2 logarithm of the Merkle-tree block size, 12 for 4096 bytes.
334 pub log_blocksize: u8,
335 /// The length of the salt in bytes, 0 if the file has no salt.
336 pub salt_size: u8,
337 /// The size of the file data in bytes at the time of the seal.
338 pub data_size: u64,
339 }
340
341 /// Returns the fs-verity parameters that the kernel holds for `fd`.
342 ///
343 /// `fd` must refer to a file with fs-verity enabled. A caller can use the
344 /// result to accept the digest of [`measure_verity`] only for a file
345 /// sealed with the parameters of ostree: SHA-256, 4096-byte blocks, and no
346 /// salt.
347 ///
348 /// # Errors
349 ///
350 /// - `ENODATA` from the kernel if fs-verity is not enabled on the file.
351 /// - `ENOTTY` from the kernel if the file system does not implement
352 /// fs-verity or the `FS_IOC_READ_VERITY_METADATA` ioctl. The ioctl is
353 /// available since Linux 5.12.
354 /// - `EOPNOTSUPP` from the kernel if the kernel or the file system has no
355 /// fs-verity support.
356 /// - `EINTR` from the kernel if a signal interrupts the call before it
357 /// reads data.
358 /// - `EIO` if the kernel returns fewer than 256 bytes, the size of the
359 /// descriptor struct. An interrupt can give a short read.
360 /// - Another `Errno` from the `FS_IOC_READ_VERITY_METADATA` ioctl.
361 pub fn read_verity_descriptor(fd: impl AsFd) -> Result<VerityDescriptor> {
362 let mut buf = [0u8; DESCRIPTOR_SIZE];
363 // SAFETY: `ReadMetadata::descriptor` takes `buf_ptr` and `length` from
364 // the same mutable borrow of `buf`. `buf` is a local that lives longer
365 // than this call, so the kernel writes at most `buf.len()` bytes into
366 // memory that this function owns. The borrow ends when `ioctl`
367 // consumes the request. The ioctl is synchronous, so the kernel holds
368 // no pointer after it returns. The function reads `buf` only after the
369 // call.
370 let n = unsafe { ioctl(fd, ReadMetadata::descriptor(&mut buf))? };
371 if n < DESCRIPTOR_SIZE {
372 return Err(Errno::IO);
373 }
374 Ok(VerityDescriptor {
375 version: buf[0],
376 hash_algorithm: buf[1],
377 log_blocksize: buf[2],
378 salt_size: buf[3],
379 data_size: u64::from_le_bytes(buf[8..16].try_into().expect("8-byte field")),
380 })
381 }
382}
383
384pub use imp::{
385 VerityDescriptor, enable_verity, enable_verity_with_salt, measure_verity,
386 read_verity_descriptor,
387};
388pub use mmap::Mmap;
389
390mod mmap {
391 #![allow(unsafe_code)]
392
393 use std::os::fd::AsFd;
394 use std::ptr::NonNull;
395
396 use rustix::io::{Errno, Result};
397 use rustix::mm::{MapFlags, ProtFlags, mmap, munmap};
398
399 // The static-delta reader of the `ostrya` crate maps a decompressed part or
400 // a source object that it wrote to a temp file. Random access to these
401 // bytes (splice offsets, bspatch source seeks) then costs address space and
402 // demand-paged file cache, and no resident heap. The reader maps only
403 // anonymous temp files that it alone holds, so no other writer can make
404 // one shorter. The reader maps a blob only if the blob is larger than its
405 // heap threshold.
406
407 /// A read-only, private memory map of an open file.
408 ///
409 /// The map is never written. It keeps the mapped pages alive on its own,
410 /// so the caller can close the file descriptor after
411 /// [`Mmap::read_only`] returns.
412 ///
413 /// # Truncation
414 ///
415 /// A read of a mapped page with no file bytes behind it raises `SIGBUS`.
416 /// No safe API can expose this signal, so [`Mmap::read_only`] measures the
417 /// file and refuses a map longer than the file. [`Mmap::as_slice`] is
418 /// sound for the whole life of the map if no writer truncates the file.
419 /// The caller must map only a file that no other writer can truncate.
420 pub struct Mmap {
421 ptr: NonNull<u8>,
422 len: usize,
423 }
424
425 // SAFETY: the map is read-only and owns its region for its whole life.
426 // These two facts make it sound to send the immutable byte view to another
427 // thread, or to share it between threads.
428 unsafe impl Send for Mmap {}
429 unsafe impl Sync for Mmap {}
430
431 impl Mmap {
432 /// Maps the first `len` bytes of `fd` read-only.
433 ///
434 /// `len` must be larger than zero and not larger than the size of the
435 /// file. Because the function refuses a `len` larger than the file, a
436 /// read of the map cannot raise `SIGBUS` while the file keeps its size.
437 ///
438 /// # Errors
439 ///
440 /// - An `Errno` from `fstat` if the function cannot read the size of
441 /// the file.
442 /// - `EINVAL` if `len` is larger than the size of the file.
443 /// - `EINVAL` from `mmap` if `len` is zero.
444 /// - Another `Errno` from `mmap`, for example `EACCES` if `fd` is not
445 /// open for reading.
446 ///
447 /// # Examples
448 ///
449 /// ```
450 /// use std::fs::File;
451 ///
452 /// use ostrya_sys::Mmap;
453 ///
454 /// let path = std::env::temp_dir().join(format!("ostrya-sys-doc-{}", std::process::id()));
455 /// std::fs::write(&path, b"ostree")?;
456 /// let file = File::open(&path)?;
457 /// assert!(Mmap::read_only(&file, 7).is_err(), "longer than the file");
458 /// let map = Mmap::read_only(&file, 6)?;
459 /// // The map stays valid after the descriptor closes.
460 /// drop(file);
461 /// assert_eq!(map.as_slice(), b"ostree");
462 /// std::fs::remove_file(&path)?;
463 /// # Ok::<(), std::io::Error>(())
464 /// ```
465 pub fn read_only(fd: impl AsFd, len: usize) -> Result<Mmap> {
466 // A map longer than the file gives bytes with no file pages behind
467 // them, and a read of these bytes raises SIGBUS. The size check
468 // here prevents this for each caller of this safe function.
469 let size = rustix::fs::fstat(fd.as_fd())?.st_size;
470 match i64::try_from(len) {
471 Ok(len) if len <= size => {}
472 _ => return Err(Errno::INVAL),
473 }
474 // SAFETY: a null address lets the kernel select the place of the
475 // region. PROT_READ with MAP_PRIVATE maps `len` file bytes
476 // read-only. The returned pointer is valid for `len` bytes until
477 // `munmap`, which `Drop` calls exactly once.
478 let ptr = unsafe {
479 mmap(
480 core::ptr::null_mut(),
481 len,
482 ProtFlags::READ,
483 MapFlags::PRIVATE,
484 fd,
485 0,
486 )?
487 };
488 let ptr = NonNull::new(ptr.cast::<u8>()).expect("mmap returns non-null on success");
489 Ok(Mmap { ptr, len })
490 }
491
492 /// Returns the mapped bytes.
493 pub fn as_slice(&self) -> &[u8] {
494 // SAFETY: `ptr` addresses `len` readable, initialized bytes for the
495 // lifetime of `self`, and nothing mutates the region, so a shared
496 // slice over it is valid.
497 unsafe { std::slice::from_raw_parts(self.ptr.as_ptr(), self.len) }
498 }
499
500 /// Returns the length of the map in bytes.
501 pub fn len(&self) -> usize {
502 self.len
503 }
504
505 /// Returns `true` if the map covers zero bytes.
506 ///
507 /// The result is always `false`, because [`Mmap::read_only`] refuses a
508 /// length of zero.
509 pub fn is_empty(&self) -> bool {
510 self.len == 0
511 }
512 }
513
514 impl std::fmt::Debug for Mmap {
515 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
516 f.debug_struct("Mmap").field("len", &self.len).finish()
517 }
518 }
519
520 impl Drop for Mmap {
521 fn drop(&mut self) {
522 // SAFETY: `ptr` and `len` are exactly the address and the length
523 // of the region that `mmap` returned. This call unmaps the region
524 // once, at the end of the life of the map.
525 unsafe {
526 let _ = munmap(self.ptr.as_ptr().cast(), self.len);
527 }
528 }
529 }
530}
531
532#[cfg(test)]
533mod tests {
534 use super::{
535 Mmap, enable_verity, enable_verity_with_salt, measure_verity, read_verity_descriptor,
536 };
537 use std::fs::{File, OpenOptions};
538 use std::io::Write;
539 use std::os::fd::AsFd;
540
541 /// A map of the whole file gives its bytes back. `Mmap::read_only` refuses
542 /// a map longer than the file, because a read past the last file page
543 /// raises `SIGBUS`.
544 #[test]
545 fn maps_the_file_and_refuses_a_longer_map() {
546 let path = std::env::temp_dir().join(format!("ostrya-sys-mmap-{}", std::process::id()));
547 let _ = std::fs::remove_file(&path);
548 let body = b"ostrya mmap bounds";
549 {
550 let mut f = File::create(&path).unwrap();
551 f.write_all(body).unwrap();
552 f.sync_all().unwrap();
553 }
554 let ro = File::open(&path).unwrap();
555
556 let map = Mmap::read_only(ro.as_fd(), body.len()).unwrap();
557 assert_eq!(map.as_slice(), body);
558 assert_eq!(map.len(), body.len());
559 assert!(!map.is_empty());
560
561 // One byte past the end is still inside the mapped page, so only the
562 // explicit size check can refuse it.
563 assert!(
564 Mmap::read_only(ro.as_fd(), body.len() + 1).is_err(),
565 "a map longer than the file must be refused"
566 );
567 // A page past the end, and an empty map.
568 assert!(Mmap::read_only(ro.as_fd(), 8192).is_err());
569 assert!(Mmap::read_only(ro.as_fd(), 0).is_err());
570
571 drop(map);
572 let _ = std::fs::remove_file(&path);
573 }
574
575 /// On a file system with fs-verity support, `enable_verity` seals the file,
576 /// and a later open for writing fails. The measured digest is nonzero and
577 /// stable. If the file system has no fs-verity support, the enable fails
578 /// and the test skips.
579 #[test]
580 fn enable_then_measure_roundtrips() {
581 let path = std::env::temp_dir().join(format!("ostrya-sys-verity-{}", std::process::id()));
582 let _ = std::fs::remove_file(&path);
583 {
584 let mut f = File::create(&path).unwrap();
585 f.write_all(b"hello ostrya verity").unwrap();
586 f.sync_all().unwrap();
587 }
588 // The enable ioctl needs a read-only descriptor and no writable one.
589 let ro = File::open(&path).unwrap();
590 if enable_verity(ro.as_fd()).is_err() {
591 let _ = std::fs::remove_file(&path);
592 return;
593 }
594
595 let measured = measure_verity(ro.as_fd()).unwrap();
596 assert_ne!(measured, [0u8; 32], "a sealed file has a non-zero digest");
597 assert_eq!(
598 measured,
599 measure_verity(ro.as_fd()).unwrap(),
600 "the measured digest is stable"
601 );
602 assert!(
603 OpenOptions::new().write(true).open(&path).is_err(),
604 "a verity-sealed file rejects write-open"
605 );
606 let _ = std::fs::remove_file(&path);
607 }
608
609 /// Writes `body` to a new file named for `tag` and opens it read-only, as
610 /// the enable ioctl needs.
611 fn read_only_file(tag: &str, body: &[u8]) -> (std::path::PathBuf, File) {
612 let path = std::env::temp_dir().join(format!("ostrya-sys-{tag}-{}", std::process::id()));
613 let _ = std::fs::remove_file(&path);
614 {
615 let mut f = File::create(&path).unwrap();
616 f.write_all(body).unwrap();
617 f.sync_all().unwrap();
618 }
619 let ro = File::open(&path).unwrap();
620 (path, ro)
621 }
622
623 /// The descriptor of a file that `enable_verity` sealed names SHA-256,
624 /// 4096-byte blocks, no salt, and the size of the file. The test skips if
625 /// the file system has no fs-verity support.
626 #[test]
627 fn descriptor_reports_the_ostree_parameters() {
628 let body = b"ostrya verity descriptor".repeat(300);
629 let (path, ro) = read_only_file("verity-descriptor", &body);
630 if let Err(e) = enable_verity(ro.as_fd()) {
631 eprintln!("skipping descriptor check: filesystem lacks fs-verity ({e})");
632 let _ = std::fs::remove_file(&path);
633 return;
634 }
635
636 let desc = read_verity_descriptor(ro.as_fd()).unwrap();
637 assert_eq!(desc.version, 1);
638 assert_eq!(desc.hash_algorithm, 1, "SHA-256");
639 assert_eq!(desc.log_blocksize, 12, "4096-byte blocks");
640 assert_eq!(desc.salt_size, 0);
641 assert_eq!(desc.data_size, body.len() as u64);
642 let _ = std::fs::remove_file(&path);
643 }
644
645 /// A file sealed with a salt reports the length of the salt. Its digest is
646 /// not the digest of the same bytes sealed with no salt. The test skips if
647 /// the file system has no fs-verity support.
648 #[test]
649 fn descriptor_reports_a_salt() {
650 let body = b"ostrya salted verity";
651 let (plain_path, plain) = read_only_file("verity-unsalted", body);
652 if let Err(e) = enable_verity(plain.as_fd()) {
653 eprintln!("skipping salt check: filesystem lacks fs-verity ({e})");
654 let _ = std::fs::remove_file(&plain_path);
655 return;
656 }
657 let (path, ro) = read_only_file("verity-salted", body);
658 enable_verity_with_salt(ro.as_fd(), &[0x5a; 8]).unwrap();
659
660 let desc = read_verity_descriptor(ro.as_fd()).unwrap();
661 assert_eq!(desc.hash_algorithm, 1);
662 assert_eq!(desc.log_blocksize, 12);
663 assert_eq!(desc.salt_size, 8);
664 assert_ne!(
665 measure_verity(ro.as_fd()).unwrap(),
666 measure_verity(plain.as_fd()).unwrap(),
667 "the salt changes the digest"
668 );
669 let _ = std::fs::remove_file(&path);
670 let _ = std::fs::remove_file(&plain_path);
671 }
672
673 /// A file without fs-verity has no descriptor to read.
674 #[test]
675 fn descriptor_of_an_unsealed_file_is_an_error() {
676 let (path, ro) = read_only_file("verity-unsealed", b"not sealed");
677 assert!(read_verity_descriptor(ro.as_fd()).is_err());
678 assert!(measure_verity(ro.as_fd()).is_err());
679 let _ = std::fs::remove_file(&path);
680 }
681}