ostrya_sys/lib.rs
1#![deny(unsafe_code)]
2
3//! Wrappers for the Linux fs-verity ioctls, a read-only memory map, the loop
4//! device, a sealed memory file, namespace descriptors, ID-mapped mounts,
5//! and socket credentials.
6//!
7//! A caller seals a file with fs-verity and reads the digest and the
8//! parameters that the kernel holds for the sealed file. The seal has the
9//! parameters that ostree uses: SHA-256, 4096-byte blocks, and no salt. A
10//! caller can also map a file read-only. On Linux, a caller attaches a file
11//! to a loop device, and writes bytes to a memory file that it then seals.
12//! It reads the type and the owner of a namespace, sets an ID mapping on a
13//! detached mount, reads the groups of the peer of a Unix socket, and takes
14//! the socket that systemd passes. The crate depends on `rustix`. On Linux
15//! it also depends on `libc`, for the two calls that `rustix` does not give:
16//! `mount_setattr` and `SO_PEERGROUPS`.
17//!
18//! # Entry points
19//!
20//! - [`enable_verity`] seals a file with fs-verity.
21//! - [`measure_verity`] returns the fs-verity digest of a sealed file.
22//! - [`read_verity_descriptor`] returns the parameters of a sealed file.
23//! - [`Mmap`] is a read-only memory map of a file.
24//! - [`LoopDevice::attach`] attaches a file to a free loop device with a
25//! [`LoopConfig`]. Linux only.
26//! - [`sealable_memfd`] creates a memory file that accepts seals, and
27//! [`seal_contents`] seals its bytes and its size. Linux only.
28//! - [`ns_type`] returns the type of a namespace, and [`ns_owner_userns`]
29//! returns the user namespace that owns it. Linux only.
30//! - [`mount_setattr_idmap`] sets an ID mapping on a detached mount. Linux
31//! only.
32//! - [`peer_groups`] returns the supplementary groups of the peer of a Unix
33//! socket. Linux only.
34//! - [`systemd_listen_fd`] takes the one socket that systemd passes. Linux
35//! only.
36//!
37//! # Examples
38//!
39//! The example seals a file and reads its parameters and its digest. The file
40//! system of the file must support fs-verity.
41//!
42//! ```no_run
43//! use std::fs::File;
44//!
45//! use ostrya_sys::{enable_verity, measure_verity, read_verity_descriptor};
46//!
47//! // A read-only descriptor, and no writable descriptor to the file.
48//! let file = File::open("object.file")?;
49//! enable_verity(&file)?;
50//! let desc = read_verity_descriptor(&file)?;
51//! // SHA-256, 4096-byte blocks (2 to the power 12), and no salt.
52//! assert_eq!((desc.hash_algorithm, desc.log_blocksize, desc.salt_size), (1, 12, 0));
53//! let digest: [u8; 32] = measure_verity(&file)?;
54//! # let _ = digest;
55//! # Ok::<(), std::io::Error>(())
56//! ```
57//!
58//! This crate holds all `unsafe` code of the ostrya library crates. A
59//! `SAFETY` comment on each `unsafe` block gives its reasoning.
60
61// All other library crates of ostrya are `#![forbid(unsafe_code)]`. This crate
62// holds the `rustix` calls that need `unsafe` and that no safe `rustix` wrapper
63// gives. The crate root is `#![deny(unsafe_code)]`. Each of the modules `imp`,
64// `mmap`, `loop_dev`, `ns`, and `sock` has a scoped `#![allow(unsafe_code)]`,
65// so the audited `unsafe` code stays in these five modules.
66
67mod imp {
68 #![allow(unsafe_code)]
69
70 use std::marker::PhantomData;
71 use std::os::fd::AsFd;
72
73 use rustix::io::{Errno, Result};
74 use rustix::ioctl::{Ioctl, IoctlOutput, Opcode, Setter, Updater, ioctl, opcode};
75
76 /// The SHA-256 fs-verity hash-algorithm identifier.
77 const FS_VERITY_HASH_ALG_SHA256: u32 = 1;
78 /// The fs-verity block size, in bytes.
79 const FS_VERITY_BLOCK_SIZE: u32 = 4096;
80
81 /// The `fsverity_enable_arg` argument of `FS_IOC_ENABLE_VERITY`.
82 ///
83 /// The struct has the layout of the 128-byte kernel UAPI struct. The
84 /// kernel reads each field through the raw pointer. No Rust code reads a
85 /// field, so the struct exists only for the kernel ABI.
86 #[repr(C)]
87 #[derive(Clone, Copy)]
88 #[allow(dead_code)]
89 struct FsverityEnableArg {
90 version: u32,
91 hash_algorithm: u32,
92 block_size: u32,
93 salt_size: u32,
94 salt_ptr: u64,
95 sig_size: u32,
96 reserved1: u32,
97 sig_ptr: u64,
98 reserved2: [u64; 11],
99 }
100
101 /// `FS_IOC_ENABLE_VERITY = _IOW('f', 133, struct fsverity_enable_arg)`. The
102 /// opcode encodes the 128-byte argument size.
103 const FS_IOC_ENABLE_VERITY: Opcode = opcode::write::<FsverityEnableArg>(b'f', 133);
104
105 /// The 4-byte header of the `fsverity_digest` request.
106 ///
107 /// The `FS_IOC_MEASURE_VERITY` request number encodes only the size of
108 /// this header, because the C struct ends in a flexible `digest[]` array.
109 #[repr(C)]
110 #[allow(dead_code)]
111 struct FsverityDigestHeader {
112 digest_algorithm: u16,
113 digest_size: u16,
114 }
115
116 /// `FS_IOC_MEASURE_VERITY = _IOWR('f', 134, struct fsverity_digest)`. The
117 /// request number comes from `FsverityDigestHeader`, the base header of the
118 /// flexible array. The buffer that the call passes is larger.
119 const FS_IOC_MEASURE_VERITY: Opcode = opcode::read_write::<FsverityDigestHeader>(b'f', 134);
120
121 /// A `fsverity_digest` with space for a 32-byte SHA-256 digest.
122 #[repr(C)]
123 #[allow(dead_code)]
124 struct FsverityDigestSha256 {
125 digest_algorithm: u16,
126 digest_size: u16,
127 digest: [u8; 32],
128 }
129
130 /// Enables fs-verity on `fd` with SHA-256, 4096-byte blocks, and no salt.
131 ///
132 /// `fd` must be a read-only descriptor. The kernel refuses the call while a
133 /// process has the file open for writing, also through a writable memory
134 /// map. Other read-only descriptors to the file can stay open. After the
135 /// call, an open of the file for writing fails with `EPERM`.
136 ///
137 /// # Errors
138 ///
139 /// The function returns the `Errno` of the `FS_IOC_ENABLE_VERITY` ioctl.
140 /// The Linux kernel documentation of fs-verity gives these values:
141 ///
142 /// - `ETXTBSY` if the file is open for writing through `fd`, another
143 /// descriptor, or a writable memory map.
144 /// - `EEXIST` if fs-verity is already enabled on the file.
145 /// - `EACCES` if the process has no write access to the file.
146 /// - `EPERM` if the file is append-only, or if the kernel requires a
147 /// built-in signature. This function gives no signature.
148 /// - `EROFS` if the file system is read-only.
149 /// - `EISDIR` if `fd` refers to a directory.
150 /// - `EINVAL` if the file system does not accept a 4096-byte block, or if
151 /// `fd` refers to neither a regular file nor a directory.
152 /// - `ENOTTY` or `EOPNOTSUPP` if the file system or the kernel has no
153 /// fs-verity support.
154 /// - `EINTR` if a fatal signal interrupts the call.
155 /// - Another `Errno` for other failures.
156 ///
157 /// If `fd` is open for writing only, Linux 6.18 on btrfs returns `EBADF`.
158 /// The kernel documentation does not state this value.
159 pub fn enable_verity(fd: impl AsFd) -> Result<()> {
160 enable(fd, &[])
161 }
162
163 /// Enables fs-verity on `fd` with SHA-256, 4096-byte blocks, and `salt`.
164 ///
165 /// The tests use this function to seal a file with parameters that are
166 /// not the parameters of ostree. The descriptor rules of [`enable_verity`]
167 /// apply.
168 ///
169 /// # Errors
170 ///
171 /// - `EINVAL` if the length of `salt` does not fit in a `u32`.
172 /// - `EMSGSIZE` from the kernel if `salt` is longer than 32 bytes.
173 /// - The `Errno` values of [`enable_verity`].
174 #[doc(hidden)]
175 pub fn enable_verity_with_salt(fd: impl AsFd, salt: &[u8]) -> Result<()> {
176 enable(fd, salt)
177 }
178
179 /// Enables fs-verity on `fd` with SHA-256, 4096-byte blocks, and `salt`.
180 /// An empty `salt` gives a null salt pointer.
181 fn enable(fd: impl AsFd, salt: &[u8]) -> Result<()> {
182 let salt_size = u32::try_from(salt.len()).map_err(|_| Errno::INVAL)?;
183 let arg = FsverityEnableArg {
184 version: 1,
185 hash_algorithm: FS_VERITY_HASH_ALG_SHA256,
186 block_size: FS_VERITY_BLOCK_SIZE,
187 salt_size,
188 salt_ptr: if salt.is_empty() {
189 0
190 } else {
191 salt.as_ptr() as u64
192 },
193 sig_size: 0,
194 reserved1: 0,
195 sig_ptr: 0,
196 reserved2: [0; 11],
197 };
198 // SAFETY: `FS_IOC_ENABLE_VERITY` expects a pointer to a
199 // `fsverity_enable_arg`. `FsverityEnableArg` is that 128-byte
200 // `#[repr(C)]` struct. The opcode comes from the same type, so the
201 // memory at the pointer has the size and the layout that the kernel
202 // reads. The kernel only reads the argument. This matches `Setter`, the
203 // rustix pattern for the read-only pointer of an `_IOW` ioctl. A
204 // nonzero `salt_ptr` points to `salt`, which is borrowed for this whole
205 // call. `salt_size` is the length of `salt`, so the kernel reads only
206 // live bytes. The ioctl is synchronous, so the kernel holds no pointer
207 // after it returns.
208 unsafe {
209 let call: Setter<{ FS_IOC_ENABLE_VERITY }, FsverityEnableArg> = Setter::new(arg);
210 ioctl(fd, call)
211 }
212 }
213
214 /// Returns the fs-verity SHA-256 digest that the kernel holds for `fd`.
215 ///
216 /// `fd` must refer to a file with fs-verity enabled, for example by
217 /// [`enable_verity`]. The function returns the digest of each file sealed
218 /// with SHA-256, also with a salt or another block size.
219 /// [`read_verity_descriptor`] returns these parameters.
220 ///
221 /// # Errors
222 ///
223 /// - `EINVAL` if the kernel reports a hash algorithm that is not SHA-256,
224 /// or a digest size that is not 32 bytes.
225 /// - `ENODATA` from the kernel if fs-verity is not enabled on the file.
226 /// - `EOVERFLOW` from the kernel if the digest of the file is longer than
227 /// 32 bytes. A file sealed with SHA-512 has a 64-byte digest.
228 /// - `ENOTTY` or `EOPNOTSUPP` from the kernel if the file system or the
229 /// kernel has no fs-verity support.
230 /// - Another `Errno` from the `FS_IOC_MEASURE_VERITY` ioctl.
231 pub fn measure_verity(fd: impl AsFd) -> Result<[u8; 32]> {
232 let mut digest = FsverityDigestSha256 {
233 digest_algorithm: 0,
234 // On input, `digest_size` is the capacity of the buffer.
235 digest_size: 32,
236 digest: [0u8; 32],
237 };
238 // SAFETY: `FS_IOC_MEASURE_VERITY` reads `digest_size` as the capacity
239 // of the buffer. It writes the algorithm, the size, and the digest
240 // bytes back into the same `fsverity_digest`. `FsverityDigestSha256`
241 // is that struct with space for a 32-byte digest, so the capacity of
242 // 32 bytes is correct. The opcode comes from the base header of the
243 // flexible array, which is the size that the kernel compares against.
244 // `Updater` is the rustix pattern for a read-write pointer.
245 unsafe {
246 let call: Updater<'_, { FS_IOC_MEASURE_VERITY }, FsverityDigestSha256> =
247 Updater::new(&mut digest);
248 ioctl(fd, call)?;
249 }
250 // The kernel reports the algorithm that sealed the file. The bytes are
251 // an ostree digest only for SHA-256 with 32 bytes.
252 if u32::from(digest.digest_algorithm) != FS_VERITY_HASH_ALG_SHA256
253 || digest.digest_size != 32
254 {
255 return Err(Errno::INVAL);
256 }
257 Ok(digest.digest)
258 }
259
260 /// The `FS_IOC_READ_VERITY_METADATA` metadata type that selects the
261 /// fs-verity descriptor.
262 const FS_VERITY_METADATA_TYPE_DESCRIPTOR: u64 = 2;
263 /// The size of `struct fsverity_descriptor`, in bytes.
264 const DESCRIPTOR_SIZE: usize = 256;
265
266 /// The `fsverity_read_metadata_arg` argument of
267 /// `FS_IOC_READ_VERITY_METADATA`.
268 ///
269 /// The struct has the layout of the 40-byte kernel UAPI struct. The kernel
270 /// reads each field and writes no field back.
271 #[repr(C)]
272 #[allow(dead_code)]
273 struct FsverityReadMetadataArg {
274 metadata_type: u64,
275 offset: u64,
276 length: u64,
277 buf_ptr: u64,
278 reserved: u64,
279 }
280
281 /// `FS_IOC_READ_VERITY_METADATA = _IOWR('f', 135, struct
282 /// fsverity_read_metadata_arg)`. The opcode encodes the 40-byte argument
283 /// size.
284 const FS_IOC_READ_VERITY_METADATA: Opcode =
285 opcode::read_write::<FsverityReadMetadataArg>(b'f', 135);
286
287 /// The `FS_IOC_READ_VERITY_METADATA` call.
288 ///
289 /// The kernel writes into the buffer at `buf_ptr` and returns the number of
290 /// bytes that it wrote. No rustix pattern returns this count. The lifetime
291 /// ties the call to the mutable borrow of the buffer, so the buffer lives
292 /// longer than the call.
293 struct ReadMetadata<'a> {
294 arg: FsverityReadMetadataArg,
295 buf: PhantomData<&'a mut [u8]>,
296 }
297
298 impl<'a> ReadMetadata<'a> {
299 /// Returns a request that reads the fs-verity descriptor into `buf`.
300 ///
301 /// The read starts at offset 0. The pointer and the length come from
302 /// the same slice, so the kernel obeys the length of the memory at the
303 /// pointer.
304 fn descriptor(buf: &'a mut [u8]) -> Self {
305 ReadMetadata {
306 arg: FsverityReadMetadataArg {
307 metadata_type: FS_VERITY_METADATA_TYPE_DESCRIPTOR,
308 offset: 0,
309 length: buf.len() as u64,
310 buf_ptr: buf.as_mut_ptr() as u64,
311 reserved: 0,
312 },
313 buf: PhantomData,
314 }
315 }
316 }
317
318 // SAFETY: the opcode is the `_IOWR` number that comes from the argument
319 // type that the kernel expects, and `as_ptr` points at that argument. The
320 // kernel writes into the user buffer that the argument names, so the call
321 // changes user memory and `IS_MUTATING` is true. `output_from_ptr` reads
322 // nothing through the pointer. It converts the non-negative byte count
323 // that a successful call returns.
324 unsafe impl Ioctl for ReadMetadata<'_> {
325 type Output = usize;
326
327 const IS_MUTATING: bool = true;
328
329 fn opcode(&self) -> Opcode {
330 FS_IOC_READ_VERITY_METADATA
331 }
332
333 fn as_ptr(&mut self) -> *mut core::ffi::c_void {
334 (&mut self.arg as *mut FsverityReadMetadataArg).cast()
335 }
336
337 unsafe fn output_from_ptr(
338 out: IoctlOutput,
339 _: *mut core::ffi::c_void,
340 ) -> Result<Self::Output> {
341 usize::try_from(out).map_err(|_| Errno::INVAL)
342 }
343 }
344
345 /// The fs-verity parameters of a sealed file, from its `fsverity_descriptor`.
346 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
347 pub struct VerityDescriptor {
348 /// The format version of the descriptor, which the kernel sets to 1.
349 pub version: u8,
350 /// The identifier of the hash algorithm, 1 for SHA-256.
351 pub hash_algorithm: u8,
352 /// The base-2 logarithm of the Merkle-tree block size, 12 for 4096 bytes.
353 pub log_blocksize: u8,
354 /// The length of the salt in bytes, 0 if the file has no salt.
355 pub salt_size: u8,
356 /// The size of the file data in bytes at the time of the seal.
357 pub data_size: u64,
358 }
359
360 /// Returns the fs-verity parameters that the kernel holds for `fd`.
361 ///
362 /// `fd` must refer to a file with fs-verity enabled. A caller can use the
363 /// result to accept the digest of [`measure_verity`] only for a file
364 /// sealed with the parameters of ostree: SHA-256, 4096-byte blocks, and no
365 /// salt.
366 ///
367 /// # Errors
368 ///
369 /// - `ENODATA` from the kernel if fs-verity is not enabled on the file.
370 /// - `ENOTTY` from the kernel if the file system does not implement
371 /// fs-verity or the `FS_IOC_READ_VERITY_METADATA` ioctl. The ioctl is
372 /// available since Linux 5.12.
373 /// - `EOPNOTSUPP` from the kernel if the kernel or the file system has no
374 /// fs-verity support.
375 /// - `EINTR` from the kernel if a signal interrupts the call before it
376 /// reads data.
377 /// - `EIO` if the kernel returns fewer than 256 bytes, the size of the
378 /// descriptor struct. An interrupt can give a short read.
379 /// - Another `Errno` from the `FS_IOC_READ_VERITY_METADATA` ioctl.
380 pub fn read_verity_descriptor(fd: impl AsFd) -> Result<VerityDescriptor> {
381 let mut buf = [0u8; DESCRIPTOR_SIZE];
382 // SAFETY: `ReadMetadata::descriptor` takes `buf_ptr` and `length` from
383 // the same mutable borrow of `buf`. `buf` is a local that lives longer
384 // than this call, so the kernel writes at most `buf.len()` bytes into
385 // memory that this function owns. The borrow ends when `ioctl`
386 // consumes the request. The ioctl is synchronous, so the kernel holds
387 // no pointer after it returns. The function reads `buf` only after the
388 // call.
389 let n = unsafe { ioctl(fd, ReadMetadata::descriptor(&mut buf))? };
390 if n < DESCRIPTOR_SIZE {
391 return Err(Errno::IO);
392 }
393 Ok(VerityDescriptor {
394 version: buf[0],
395 hash_algorithm: buf[1],
396 log_blocksize: buf[2],
397 salt_size: buf[3],
398 data_size: u64::from_le_bytes(buf[8..16].try_into().expect("8-byte field")),
399 })
400 }
401}
402
403pub use imp::{
404 VerityDescriptor, enable_verity, enable_verity_with_salt, measure_verity,
405 read_verity_descriptor,
406};
407pub use mmap::Mmap;
408
409mod mmap {
410 #![allow(unsafe_code)]
411
412 use std::os::fd::AsFd;
413 use std::ptr::NonNull;
414
415 use rustix::io::{Errno, Result};
416 use rustix::mm::{MapFlags, ProtFlags, mmap, munmap};
417
418 // The static-delta reader of the `ostrya` crate maps a decompressed part or
419 // a source object that it wrote to a temp file. Random access to these
420 // bytes (splice offsets, bspatch source seeks) then costs address space and
421 // demand-paged file cache, and no resident heap. The reader maps only
422 // anonymous temp files that it alone holds, so no other writer can make
423 // one shorter. The reader maps a blob only if the blob is larger than its
424 // heap threshold.
425
426 /// A read-only, private memory map of an open file.
427 ///
428 /// The map is never written. It keeps the mapped pages alive on its own,
429 /// so the caller can close the file descriptor after
430 /// [`Mmap::read_only`] returns.
431 ///
432 /// # Truncation
433 ///
434 /// A read of a mapped page with no file bytes behind it raises `SIGBUS`.
435 /// No safe API can expose this signal, so [`Mmap::read_only`] measures the
436 /// file and refuses a map longer than the file. [`Mmap::as_slice`] is
437 /// sound for the whole life of the map if no writer truncates the file.
438 /// The caller must map only a file that no other writer can truncate.
439 pub struct Mmap {
440 ptr: NonNull<u8>,
441 len: usize,
442 }
443
444 // SAFETY: the map is read-only and owns its region for its whole life.
445 // These two facts make it sound to send the immutable byte view to another
446 // thread, or to share it between threads.
447 unsafe impl Send for Mmap {}
448 unsafe impl Sync for Mmap {}
449
450 impl Mmap {
451 /// Maps the first `len` bytes of `fd` read-only.
452 ///
453 /// `len` must be larger than zero and not larger than the size of the
454 /// file. Because the function refuses a `len` larger than the file, a
455 /// read of the map cannot raise `SIGBUS` while the file keeps its size.
456 ///
457 /// # Errors
458 ///
459 /// - An `Errno` from `fstat` if the function cannot read the size of
460 /// the file.
461 /// - `EINVAL` if `len` is larger than the size of the file.
462 /// - `EINVAL` from `mmap` if `len` is zero.
463 /// - Another `Errno` from `mmap`, for example `EACCES` if `fd` is not
464 /// open for reading.
465 ///
466 /// # Examples
467 ///
468 /// ```
469 /// use std::fs::File;
470 ///
471 /// use ostrya_sys::Mmap;
472 ///
473 /// let path = std::env::temp_dir().join(format!("ostrya-sys-doc-{}", std::process::id()));
474 /// std::fs::write(&path, b"ostree")?;
475 /// let file = File::open(&path)?;
476 /// assert!(Mmap::read_only(&file, 7).is_err(), "longer than the file");
477 /// let map = Mmap::read_only(&file, 6)?;
478 /// // The map stays valid after the descriptor closes.
479 /// drop(file);
480 /// assert_eq!(map.as_slice(), b"ostree");
481 /// std::fs::remove_file(&path)?;
482 /// # Ok::<(), std::io::Error>(())
483 /// ```
484 pub fn read_only(fd: impl AsFd, len: usize) -> Result<Mmap> {
485 // A map longer than the file gives bytes with no file pages behind
486 // them, and a read of these bytes raises SIGBUS. The size check
487 // here prevents this for each caller of this safe function.
488 let size = rustix::fs::fstat(fd.as_fd())?.st_size;
489 match i64::try_from(len) {
490 Ok(len) if len <= size => {}
491 _ => return Err(Errno::INVAL),
492 }
493 // SAFETY: a null address lets the kernel select the place of the
494 // region. PROT_READ with MAP_PRIVATE maps `len` file bytes
495 // read-only. The returned pointer is valid for `len` bytes until
496 // `munmap`, which `Drop` calls exactly once.
497 let ptr = unsafe {
498 mmap(
499 core::ptr::null_mut(),
500 len,
501 ProtFlags::READ,
502 MapFlags::PRIVATE,
503 fd,
504 0,
505 )?
506 };
507 let ptr = NonNull::new(ptr.cast::<u8>()).expect("mmap returns non-null on success");
508 Ok(Mmap { ptr, len })
509 }
510
511 /// Returns the mapped bytes.
512 pub fn as_slice(&self) -> &[u8] {
513 // SAFETY: `ptr` addresses `len` readable, initialized bytes for the
514 // lifetime of `self`, and nothing mutates the region, so a shared
515 // slice over it is valid.
516 unsafe { std::slice::from_raw_parts(self.ptr.as_ptr(), self.len) }
517 }
518
519 /// Returns the length of the map in bytes.
520 pub fn len(&self) -> usize {
521 self.len
522 }
523
524 /// Returns `true` if the map covers zero bytes.
525 ///
526 /// The result is always `false`, because [`Mmap::read_only`] refuses a
527 /// length of zero.
528 pub fn is_empty(&self) -> bool {
529 self.len == 0
530 }
531 }
532
533 impl std::fmt::Debug for Mmap {
534 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
535 f.debug_struct("Mmap").field("len", &self.len).finish()
536 }
537 }
538
539 impl Drop for Mmap {
540 fn drop(&mut self) {
541 // SAFETY: `ptr` and `len` are exactly the address and the length
542 // of the region that `mmap` returned. This call unmaps the region
543 // once, at the end of the life of the map.
544 unsafe {
545 let _ = munmap(self.ptr.as_ptr().cast(), self.len);
546 }
547 }
548 }
549}
550
551#[cfg(target_os = "linux")]
552pub use loop_dev::{
553 LO_FLAGS_AUTOCLEAR, LO_FLAGS_DIRECT_IO, LO_FLAGS_READ_ONLY, LoopConfig, LoopDevice,
554};
555#[cfg(target_os = "linux")]
556pub use memfd::{seal_contents, sealable_memfd};
557#[cfg(target_os = "linux")]
558pub use ns::{mount_setattr_idmap, ns_owner_userns, ns_type};
559#[cfg(target_os = "linux")]
560pub use sock::{peer_groups, systemd_listen_fd};
561
562#[cfg(target_os = "linux")]
563mod loop_dev {
564 #![allow(unsafe_code)]
565
566 use std::os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd};
567
568 use rustix::fs::{CWD, Mode, OFlags, openat};
569 use rustix::io::{Errno, Result};
570 use rustix::ioctl::{Getter, Ioctl, IoctlOutput, Opcode, Setter, ioctl};
571
572 /// The loop device is read-only.
573 pub const LO_FLAGS_READ_ONLY: u32 = 1;
574 /// The kernel detaches the backing file at the last close of the device.
575 pub const LO_FLAGS_AUTOCLEAR: u32 = 4;
576 /// The loop device reads the backing file with direct I/O.
577 pub const LO_FLAGS_DIRECT_IO: u32 = 16;
578
579 /// `LOOP_GET_STATUS64`. The loop ioctls use fixed numbers, not the
580 /// `_IOC` encoding.
581 const LOOP_GET_STATUS64: Opcode = 0x4C05;
582 /// `LOOP_CONFIGURE`.
583 const LOOP_CONFIGURE: Opcode = 0x4C0A;
584 /// `LOOP_CTL_GET_FREE`, an ioctl of `/dev/loop-control`.
585 const LOOP_CTL_GET_FREE: Opcode = 0x4C82;
586 /// The number of attempts of [`LoopDevice::attach`] when another process
587 /// takes the free device first.
588 const ATTACH_ATTEMPTS: u32 = 10;
589
590 /// The `loop_info64` struct of the kernel UAPI, 232 bytes.
591 #[repr(C)]
592 #[derive(Clone, Copy)]
593 #[allow(dead_code)]
594 struct LoopInfo64 {
595 lo_device: u64,
596 lo_inode: u64,
597 lo_rdevice: u64,
598 lo_offset: u64,
599 lo_sizelimit: u64,
600 lo_number: u32,
601 lo_encrypt_type: u32,
602 lo_encrypt_key_size: u32,
603 lo_flags: u32,
604 lo_file_name: [u8; 64],
605 lo_crypt_name: [u8; 64],
606 lo_encrypt_key: [u8; 32],
607 lo_init: [u64; 2],
608 }
609
610 /// The `loop_config` struct of the kernel UAPI, 304 bytes. The kernel
611 /// reads each field through the raw pointer of `LOOP_CONFIGURE`.
612 #[repr(C)]
613 #[allow(dead_code)]
614 struct LoopConfigRaw {
615 fd: u32,
616 block_size: u32,
617 info: LoopInfo64,
618 reserved: [u64; 8],
619 }
620
621 const _: () = assert!(size_of::<LoopInfo64>() == 232);
622 const _: () = assert!(size_of::<LoopConfigRaw>() == 304);
623 const _: () = assert!(std::mem::offset_of!(LoopConfigRaw, info) == 8);
624 const _: () = assert!(std::mem::offset_of!(LoopInfo64, lo_flags) == 52);
625
626 /// The `LOOP_CTL_GET_FREE` call. The kernel returns the number of a free
627 /// loop device as the result of the ioctl. No rustix pattern returns this
628 /// value.
629 struct GetFree;
630
631 // SAFETY: `LOOP_CTL_GET_FREE` takes no argument and reads no user memory,
632 // so the null pointer of `as_ptr` is never read. The call changes no user
633 // memory, so `IS_MUTATING` is false. `output_from_ptr` reads nothing
634 // through the pointer. It converts the non-negative device number that a
635 // successful call returns.
636 unsafe impl Ioctl for GetFree {
637 type Output = u32;
638
639 const IS_MUTATING: bool = false;
640
641 fn opcode(&self) -> Opcode {
642 LOOP_CTL_GET_FREE
643 }
644
645 fn as_ptr(&mut self) -> *mut core::ffi::c_void {
646 core::ptr::null_mut()
647 }
648
649 unsafe fn output_from_ptr(
650 out: IoctlOutput,
651 _: *mut core::ffi::c_void,
652 ) -> Result<Self::Output> {
653 u32::try_from(out).map_err(|_| Errno::INVAL)
654 }
655 }
656
657 /// The configuration of a new loop device.
658 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
659 pub struct LoopConfig {
660 /// The logical block size of the device in bytes. The value 0 lets
661 /// the kernel choose the default.
662 pub block_size: u32,
663 /// The device is read-only.
664 pub read_only: bool,
665 /// The kernel detaches the backing file at the last close of the
666 /// device.
667 pub autoclear: bool,
668 /// The device reads the backing file with direct I/O where the
669 /// kernel accepts it. [`LoopDevice::attach`] tells which.
670 pub direct_io: bool,
671 }
672
673 impl LoopConfig {
674 /// Returns the `lo_flags` value of the configuration.
675 fn flags(&self) -> u32 {
676 let mut flags = 0;
677 if self.read_only {
678 flags |= LO_FLAGS_READ_ONLY;
679 }
680 if self.autoclear {
681 flags |= LO_FLAGS_AUTOCLEAR;
682 }
683 if self.direct_io {
684 flags |= LO_FLAGS_DIRECT_IO;
685 }
686 flags
687 }
688 }
689
690 /// An open loop device with a backing file.
691 ///
692 /// The value holds an open descriptor of `/dev/loopN`. With
693 /// [`LoopConfig::autoclear`], the kernel detaches the backing file at the
694 /// last close of the device. A file system that the device holds keeps
695 /// the device open until its unmount.
696 #[derive(Debug)]
697 pub struct LoopDevice {
698 fd: OwnedFd,
699 number: u32,
700 }
701
702 impl LoopDevice {
703 /// Attaches `backing` to a free loop device with `cfg`.
704 ///
705 /// The call asks `/dev/loop-control` for a free device, opens
706 /// `/dev/loopN`, and configures it with `LOOP_CONFIGURE` in one step.
707 /// The open is read-only for [`LoopConfig::read_only`], and for
708 /// reading and writing otherwise. If another process configures the
709 /// same device first, the kernel returns `EBUSY`, and the call tries
710 /// the next free device, up to 10 times.
711 ///
712 /// If the kernel refuses [`LoopConfig::direct_io`] with `EINVAL`, the
713 /// call configures the same device again without direct I/O. A
714 /// backing file that does not accept direct I/O gives this refusal.
715 ///
716 /// `LOOP_CONFIGURE` is available since Linux 5.8.
717 ///
718 /// # Errors
719 ///
720 /// - An `Errno` from the open of `/dev/loop-control` or of
721 /// `/dev/loopN`, for example `EACCES` or `EPERM` for a process with
722 /// no access to the loop devices.
723 /// - An `Errno` from `LOOP_CTL_GET_FREE`.
724 /// - `EBUSY` if 10 attempts find the device taken.
725 /// - `EINVAL` from `LOOP_CONFIGURE` if the kernel refuses a value of
726 /// `cfg` other than [`LoopConfig::direct_io`].
727 /// - Another `Errno` from `LOOP_CONFIGURE`.
728 pub fn attach(backing: impl AsFd, cfg: &LoopConfig) -> Result<LoopDevice> {
729 let control = openat(
730 CWD,
731 "/dev/loop-control",
732 OFlags::RDWR | OFlags::CLOEXEC,
733 Mode::empty(),
734 )?;
735 let backing_fd = u32::try_from(backing.as_fd().as_raw_fd()).map_err(|_| Errno::BADF)?;
736 let access = if cfg.read_only {
737 OFlags::RDONLY
738 } else {
739 OFlags::RDWR
740 };
741 let mut attempts = 0;
742 loop {
743 attempts += 1;
744 // SAFETY: `GetFree` is the `LOOP_CTL_GET_FREE` request, which
745 // takes no argument. The kernel reads and writes no user
746 // memory.
747 let number = unsafe { ioctl(&control, GetFree)? };
748 let fd = openat(
749 CWD,
750 format!("/dev/loop{number}"),
751 access | OFlags::CLOEXEC,
752 Mode::empty(),
753 )?;
754 let mut result = configure(&fd, backing_fd, cfg.block_size, cfg.flags());
755 if result == Err(Errno::INVAL) && cfg.direct_io {
756 let flags = cfg.flags() & !LO_FLAGS_DIRECT_IO;
757 result = configure(&fd, backing_fd, cfg.block_size, flags);
758 }
759 match result {
760 Ok(()) => return Ok(LoopDevice { fd, number }),
761 Err(Errno::BUSY) if attempts < ATTACH_ATTEMPTS => continue,
762 Err(e) => return Err(e),
763 }
764 }
765 }
766
767 /// Returns the number `N` of the device `/dev/loopN`.
768 pub fn number(&self) -> u32 {
769 self.number
770 }
771
772 /// Returns the `lo_flags` value that the kernel holds for the device.
773 ///
774 /// The value is a combination of [`LO_FLAGS_READ_ONLY`],
775 /// [`LO_FLAGS_AUTOCLEAR`], [`LO_FLAGS_DIRECT_IO`], and other flags of
776 /// the kernel. A kernel can clear [`LO_FLAGS_DIRECT_IO`] when the
777 /// backing file does not accept direct I/O.
778 ///
779 /// # Errors
780 ///
781 /// - `ENXIO` if the device has no backing file.
782 /// - Another `Errno` from `LOOP_GET_STATUS64`.
783 pub fn flags(&self) -> Result<u32> {
784 // SAFETY: `LOOP_GET_STATUS64` writes one `loop_info64` to the
785 // pointer. `LoopInfo64` is that 232-byte `#[repr(C)]` struct, so
786 // the kernel writes inside the buffer of `Getter`. Each field is
787 // an integer or an integer array, so each bit pattern that the
788 // kernel writes is a valid value.
789 let info = unsafe {
790 let call: Getter<{ LOOP_GET_STATUS64 }, LoopInfo64> = Getter::new();
791 ioctl(&self.fd, call)?
792 };
793 Ok(info.lo_flags)
794 }
795 }
796
797 /// Runs `LOOP_CONFIGURE` on the loop device `fd` with the backing file
798 /// `backing_fd`, the block size `block_size`, and the flags `flags`.
799 fn configure(fd: &OwnedFd, backing_fd: u32, block_size: u32, flags: u32) -> Result<()> {
800 let raw = LoopConfigRaw {
801 fd: backing_fd,
802 block_size,
803 info: LoopInfo64 {
804 lo_device: 0,
805 lo_inode: 0,
806 lo_rdevice: 0,
807 lo_offset: 0,
808 lo_sizelimit: 0,
809 lo_number: 0,
810 lo_encrypt_type: 0,
811 lo_encrypt_key_size: 0,
812 lo_flags: flags,
813 lo_file_name: [0; 64],
814 lo_crypt_name: [0; 64],
815 lo_encrypt_key: [0; 32],
816 lo_init: [0; 2],
817 },
818 reserved: [0; 8],
819 };
820 // SAFETY: `LOOP_CONFIGURE` expects a pointer to a `loop_config`.
821 // `LoopConfigRaw` is that 304-byte `#[repr(C)]` struct, and the
822 // compile-time asserts pin its size and its field offsets. The kernel
823 // only reads the argument, which matches `Setter`. `backing_fd` names
824 // a descriptor that the caller of `LoopDevice::attach` keeps open for
825 // the whole call. The kernel takes its own reference to the backing
826 // file, so the caller can close it after the call. The ioctl is
827 // synchronous, so the kernel holds no pointer after it returns.
828 unsafe {
829 let call: Setter<{ LOOP_CONFIGURE }, LoopConfigRaw> = Setter::new(raw);
830 ioctl(fd, call)
831 }
832 }
833
834 impl AsFd for LoopDevice {
835 fn as_fd(&self) -> BorrowedFd<'_> {
836 self.fd.as_fd()
837 }
838 }
839}
840
841#[cfg(target_os = "linux")]
842mod memfd {
843 use std::os::fd::{AsFd, OwnedFd};
844
845 use rustix::fs::{MemfdFlags, SealFlags, fcntl_add_seals, memfd_create};
846 use rustix::io::Result;
847
848 /// Creates an anonymous memory file that accepts seals.
849 ///
850 /// The file has the flags `MFD_CLOEXEC`, `MFD_ALLOW_SEALING`, and
851 /// `MFD_NOEXEC_SEAL`, so no process can execute it. `name` shows in
852 /// `/proc/<pid>/fd` as `/memfd:<name>`. The memory of the file counts
853 /// against the memory cgroup of the process until the last reference to
854 /// the file closes.
855 ///
856 /// # Errors
857 ///
858 /// - `EINVAL` if `name` is longer than 249 bytes, or if the kernel does
859 /// not know `MFD_NOEXEC_SEAL`, which Linux 6.3 adds.
860 /// - Another `Errno` from `memfd_create`.
861 pub fn sealable_memfd(name: &str) -> Result<OwnedFd> {
862 memfd_create(
863 name,
864 MemfdFlags::CLOEXEC | MemfdFlags::ALLOW_SEALING | MemfdFlags::NOEXEC_SEAL,
865 )
866 }
867
868 /// Seals the content of a memory file from [`sealable_memfd`].
869 ///
870 /// The call adds `F_SEAL_WRITE`, `F_SEAL_GROW`, `F_SEAL_SHRINK`, and
871 /// `F_SEAL_SEAL`. After the call, no process can change the bytes or the
872 /// size of the file, and no process can remove a seal.
873 ///
874 /// # Errors
875 ///
876 /// - `EBUSY` if a writable shared memory map of the file exists.
877 /// - `EPERM` if the file has `F_SEAL_SEAL` already.
878 /// - Another `Errno` from `fcntl(F_ADD_SEALS)`.
879 pub fn seal_contents(fd: impl AsFd) -> Result<()> {
880 fcntl_add_seals(
881 fd,
882 SealFlags::WRITE | SealFlags::GROW | SealFlags::SHRINK | SealFlags::SEAL,
883 )
884 }
885}
886
887#[cfg(target_os = "linux")]
888mod ns {
889 #![allow(unsafe_code)]
890
891 use std::os::fd::{AsFd, AsRawFd, FromRawFd, OwnedFd, RawFd};
892
893 use rustix::io::{Errno, Result};
894 use rustix::ioctl::{Ioctl, IoctlOutput, Opcode, ioctl, opcode};
895 use rustix::thread::LinkNameSpaceType;
896
897 /// The ioctl group of the namespace file descriptors.
898 const NSIO: u8 = 0xb7;
899 /// `NS_GET_USERNS = _IO(0xb7, 0x1)`: the owner user namespace.
900 const NS_GET_USERNS: Opcode = opcode::none(NSIO, 0x1);
901 /// `NS_GET_NSTYPE = _IO(0xb7, 0x3)`: the `CLONE_NEW*` type.
902 const NS_GET_NSTYPE: Opcode = opcode::none(NSIO, 0x3);
903
904 /// A namespace ioctl that takes no argument and returns an integer as
905 /// the result of the call.
906 struct NoArg {
907 opcode: Opcode,
908 }
909
910 // SAFETY: the two namespace requests that use this type take no argument
911 // and read no user memory, so the null pointer of `as_ptr` is never read.
912 // The calls change no user memory, so `IS_MUTATING` is false.
913 // `output_from_ptr` reads nothing through the pointer. It returns the
914 // non-negative integer that a successful call returns.
915 unsafe impl Ioctl for NoArg {
916 type Output = IoctlOutput;
917
918 const IS_MUTATING: bool = false;
919
920 fn opcode(&self) -> Opcode {
921 self.opcode
922 }
923
924 fn as_ptr(&mut self) -> *mut core::ffi::c_void {
925 core::ptr::null_mut()
926 }
927
928 unsafe fn output_from_ptr(
929 out: IoctlOutput,
930 _: *mut core::ffi::c_void,
931 ) -> Result<Self::Output> {
932 Ok(out)
933 }
934 }
935
936 /// Returns the type of the namespace that `fd` refers to.
937 ///
938 /// `fd` is a descriptor of a namespace file, for example an open
939 /// `/proc/<pid>/ns/user`.
940 ///
941 /// # Errors
942 ///
943 /// - `ENOTTY` if `fd` does not refer to a namespace.
944 /// - `EOPNOTSUPP` if the kernel returns a type that rustix does not
945 /// name.
946 /// - Another `Errno` from `NS_GET_NSTYPE`.
947 pub fn ns_type(fd: impl AsFd) -> Result<LinkNameSpaceType> {
948 // SAFETY: `NS_GET_NSTYPE` takes no argument. The kernel reads and
949 // writes no user memory and returns the type as the result.
950 let raw = unsafe {
951 ioctl(
952 fd,
953 NoArg {
954 opcode: NS_GET_NSTYPE,
955 },
956 )?
957 };
958 let raw = u32::try_from(raw).map_err(|_| Errno::INVAL)?;
959 [
960 LinkNameSpaceType::Time,
961 LinkNameSpaceType::Mount,
962 LinkNameSpaceType::ControlGroup,
963 LinkNameSpaceType::HostNameAndNISDomainName,
964 LinkNameSpaceType::InterProcessCommunication,
965 LinkNameSpaceType::User,
966 LinkNameSpaceType::ProcessID,
967 LinkNameSpaceType::Network,
968 ]
969 .into_iter()
970 .find(|ty| *ty as u32 == raw)
971 .ok_or(Errno::OPNOTSUPP)
972 }
973
974 /// Returns a descriptor of the user namespace that owns the namespace
975 /// `fd`.
976 ///
977 /// The new descriptor has the close-on-exec flag.
978 ///
979 /// # Errors
980 ///
981 /// - `ENOTTY` if `fd` does not refer to a namespace.
982 /// - `EINVAL` if `fd` refers to a user namespace with no parent, the
983 /// initial user namespace.
984 /// - `EPERM` if the owner is outside the user namespace of the process.
985 /// - Another `Errno` from `NS_GET_USERNS`.
986 pub fn ns_owner_userns(fd: impl AsFd) -> Result<OwnedFd> {
987 // SAFETY: `NS_GET_USERNS` takes no argument. The kernel reads and
988 // writes no user memory. A successful call returns a new descriptor
989 // that no other value owns, so `OwnedFd` takes ownership of it.
990 unsafe {
991 let raw = ioctl(
992 fd,
993 NoArg {
994 opcode: NS_GET_USERNS,
995 },
996 )?;
997 Ok(OwnedFd::from_raw_fd(raw as RawFd))
998 }
999 }
1000
1001 /// Sets an ID mapping on the detached mount `mount`, with the user
1002 /// namespace `userns`.
1003 ///
1004 /// The call is `mount_setattr(2)` with `AT_EMPTY_PATH` and
1005 /// `MOUNT_ATTR_IDMAP`. After the call, the mount shows each file owner
1006 /// through the mapping of `userns`: the owner `0` in the file system
1007 /// shows as the user that `0` in `userns` maps to. rustix has no
1008 /// `mount_setattr`, so the call goes through the `syscall` function of
1009 /// libc.
1010 ///
1011 /// # Errors
1012 ///
1013 /// - `EPERM` if the process has no `CAP_SYS_ADMIN` in the user namespace
1014 /// that owns the mount, or none in `userns`.
1015 /// - `EINVAL` if `mount` is not a detached mount that was never attached,
1016 /// if it has a mapping already, if `userns` is the initial user
1017 /// namespace, or if the file system does not support ID-mapped mounts.
1018 /// - `EBADF` if `userns` is not a descriptor of a user namespace.
1019 /// - `ENOSYS` before Linux 5.12.
1020 /// - Another `Errno` from `mount_setattr`.
1021 pub fn mount_setattr_idmap(mount: impl AsFd, userns: impl AsFd) -> Result<()> {
1022 let attr = libc::mount_attr {
1023 attr_set: libc::MOUNT_ATTR_IDMAP,
1024 attr_clr: 0,
1025 propagation: 0,
1026 userns_fd: u64::try_from(userns.as_fd().as_raw_fd()).map_err(|_| Errno::BADF)?,
1027 };
1028 // SAFETY: the arguments are the descriptor of the mount, a pointer to
1029 // an empty C string that lives for the call, the flags, a pointer to
1030 // a `mount_attr` that lives for the call, and its size. The kernel
1031 // only reads the path and the struct, and holds no pointer after the
1032 // call returns. `libc::mount_attr` is the 32-byte UAPI struct. The
1033 // call creates and closes no descriptor.
1034 let ret = unsafe {
1035 libc::syscall(
1036 libc::SYS_mount_setattr,
1037 mount.as_fd().as_raw_fd(),
1038 c"".as_ptr(),
1039 libc::AT_EMPTY_PATH as libc::c_uint,
1040 &raw const attr,
1041 size_of::<libc::mount_attr>(),
1042 )
1043 };
1044 if ret < 0 {
1045 return Err(Errno::from_io_error(&std::io::Error::last_os_error()).unwrap_or(Errno::IO));
1046 }
1047 Ok(())
1048 }
1049
1050 const _: () = assert!(size_of::<libc::mount_attr>() == 32);
1051}
1052
1053#[cfg(target_os = "linux")]
1054mod sock {
1055 #![allow(unsafe_code)]
1056
1057 use std::ffi::OsStr;
1058 use std::os::fd::{AsFd, AsRawFd, FromRawFd, OwnedFd};
1059 use std::sync::atomic::{AtomicBool, Ordering};
1060
1061 use rustix::io::{Errno, FdFlags, Result, fcntl_setfd};
1062
1063 /// The descriptor of the first socket that systemd passes,
1064 /// `SD_LISTEN_FDS_START`.
1065 const LISTEN_FD: i32 = 3;
1066
1067 /// The number of groups that the first `SO_PEERGROUPS` call has space
1068 /// for.
1069 const FIRST_GROUPS: usize = 64;
1070
1071 /// Returns the raw ids of the supplementary groups of the peer of the
1072 /// Unix socket `sock`. The peer must have at most `max` groups.
1073 ///
1074 /// The kernel records the groups when the peer connects, or when it
1075 /// creates the socket pair. The list is in the order of the kernel.
1076 ///
1077 /// # Errors
1078 ///
1079 /// - `ERANGE` if the peer has more than `max` groups.
1080 /// - `ENODATA` if the socket has no peer credentials, for example a
1081 /// listening socket.
1082 /// - `ENOTSOCK` if `sock` is not a socket, and `ENOPROTOOPT` if it is not
1083 /// a Unix socket.
1084 /// - Another `Errno` from `getsockopt(SO_PEERGROUPS)`.
1085 pub fn peer_groups(sock: impl AsFd, max: usize) -> Result<Vec<u32>> {
1086 let fd = sock.as_fd().as_raw_fd();
1087 let mut groups: Vec<libc::gid_t> = vec![0; FIRST_GROUPS.min(max)];
1088 loop {
1089 let mut len = libc::socklen_t::try_from(groups.len() * size_of::<libc::gid_t>())
1090 .map_err(|_| Errno::RANGE)?;
1091 // SAFETY: the buffer holds `len` bytes and lives for the call.
1092 // The kernel writes at most `len` bytes to it, and writes the
1093 // length of its data or the length that it needs to `len`.
1094 let ret = unsafe {
1095 libc::getsockopt(
1096 fd,
1097 libc::SOL_SOCKET,
1098 libc::SO_PEERGROUPS,
1099 groups.as_mut_ptr().cast(),
1100 &raw mut len,
1101 )
1102 };
1103 let need = len as usize / size_of::<libc::gid_t>();
1104 if ret == 0 {
1105 groups.truncate(need);
1106 return Ok(groups);
1107 }
1108 let errno = Errno::from_io_error(&std::io::Error::last_os_error()).unwrap_or(Errno::IO);
1109 if errno != Errno::RANGE || need <= groups.len() || need > max {
1110 return Err(errno);
1111 }
1112 groups.resize(need, 0);
1113 }
1114 }
1115
1116 /// Set when [`systemd_listen_fd`] takes the descriptor.
1117 static TAKEN: AtomicBool = AtomicBool::new(false);
1118
1119 /// Returns the one socket that systemd passes to the process, and sets
1120 /// its close-on-exec flag.
1121 ///
1122 /// systemd passes the socket as descriptor 3 and sets the environment
1123 /// variables `LISTEN_PID` and `LISTEN_FDS`. The call accepts them only
1124 /// when `LISTEN_PID` is the process id of this process and `LISTEN_FDS`
1125 /// is `1`. It returns `None` if neither variable is set. The call takes
1126 /// the descriptor once in the life of the process. It leaves the
1127 /// environment as it is, so a child process that the caller starts must
1128 /// not inherit the two variables.
1129 ///
1130 /// # Errors
1131 ///
1132 /// - `EINVAL` if only one of the two variables is set, if `LISTEN_PID`
1133 /// is not the process id of this process, or if `LISTEN_FDS` is not
1134 /// `1`.
1135 /// - `EALREADY` if an earlier call took the descriptor.
1136 /// - `EBADF` if descriptor 3 is not open.
1137 pub fn systemd_listen_fd() -> Result<Option<OwnedFd>> {
1138 let pid = std::env::var_os("LISTEN_PID");
1139 let fds = std::env::var_os("LISTEN_FDS");
1140 if !listen_vars_match(pid.as_deref(), fds.as_deref(), std::process::id())? {
1141 return Ok(None);
1142 }
1143 if TAKEN.swap(true, Ordering::SeqCst) {
1144 return Err(Errno::ALREADY);
1145 }
1146 // SAFETY: `fcntl(F_GETFD)` takes a raw descriptor number and reads no
1147 // memory of the process. A closed descriptor 3 gives `EBADF` and no
1148 // other effect. No Rust value holds the descriptor during the call.
1149 let flags = unsafe { libc::fcntl(LISTEN_FD, libc::F_GETFD) };
1150 if flags < 0 {
1151 return Err(Errno::from_io_error(&std::io::Error::last_os_error()).unwrap_or(Errno::IO));
1152 }
1153 // SAFETY: the probe shows that descriptor 3 is open. systemd passed
1154 // it to this process for its own use, and `TAKEN` makes sure that one
1155 // `OwnedFd` alone takes it.
1156 let fd = unsafe { OwnedFd::from_raw_fd(LISTEN_FD) };
1157 fcntl_setfd(
1158 &fd,
1159 FdFlags::from_bits_retain(flags as u32) | FdFlags::CLOEXEC,
1160 )?;
1161 Ok(Some(fd))
1162 }
1163
1164 /// Checks the values of `LISTEN_PID` and `LISTEN_FDS` for the process
1165 /// `own_pid`. Returns `false` if neither is set.
1166 pub(crate) fn listen_vars_match(
1167 pid: Option<&OsStr>,
1168 fds: Option<&OsStr>,
1169 own_pid: u32,
1170 ) -> Result<bool> {
1171 match (pid, fds) {
1172 (None, None) => Ok(false),
1173 (Some(pid), Some(fds)) => {
1174 let pid_ok = pid.to_str().and_then(|s| s.parse::<u32>().ok()) == Some(own_pid);
1175 if pid_ok && fds == "1" {
1176 Ok(true)
1177 } else {
1178 Err(Errno::INVAL)
1179 }
1180 }
1181 _ => Err(Errno::INVAL),
1182 }
1183 }
1184}
1185
1186#[cfg(test)]
1187mod tests {
1188 use super::{
1189 Mmap, enable_verity, enable_verity_with_salt, measure_verity, read_verity_descriptor,
1190 };
1191 use std::fs::{File, OpenOptions};
1192 use std::io::Write;
1193 use std::os::fd::AsFd;
1194
1195 /// A map of the whole file gives its bytes back. `Mmap::read_only` refuses
1196 /// a map longer than the file, because a read past the last file page
1197 /// raises `SIGBUS`.
1198 #[test]
1199 fn maps_the_file_and_refuses_a_longer_map() {
1200 let path = std::env::temp_dir().join(format!("ostrya-sys-mmap-{}", std::process::id()));
1201 let _ = std::fs::remove_file(&path);
1202 let body = b"ostrya mmap bounds";
1203 {
1204 let mut f = File::create(&path).unwrap();
1205 f.write_all(body).unwrap();
1206 f.sync_all().unwrap();
1207 }
1208 let ro = File::open(&path).unwrap();
1209
1210 let map = Mmap::read_only(ro.as_fd(), body.len()).unwrap();
1211 assert_eq!(map.as_slice(), body);
1212 assert_eq!(map.len(), body.len());
1213 assert!(!map.is_empty());
1214
1215 // One byte past the end is still inside the mapped page, so only the
1216 // explicit size check can refuse it.
1217 assert!(
1218 Mmap::read_only(ro.as_fd(), body.len() + 1).is_err(),
1219 "a map longer than the file must be refused"
1220 );
1221 // A page past the end, and an empty map.
1222 assert!(Mmap::read_only(ro.as_fd(), 8192).is_err());
1223 assert!(Mmap::read_only(ro.as_fd(), 0).is_err());
1224
1225 drop(map);
1226 let _ = std::fs::remove_file(&path);
1227 }
1228
1229 /// On a file system with fs-verity support, `enable_verity` seals the file,
1230 /// and a later open for writing fails. The measured digest is nonzero and
1231 /// stable. If the file system has no fs-verity support, the enable fails
1232 /// and the test skips.
1233 #[test]
1234 fn enable_then_measure_roundtrips() {
1235 let path = std::env::temp_dir().join(format!("ostrya-sys-verity-{}", std::process::id()));
1236 let _ = std::fs::remove_file(&path);
1237 {
1238 let mut f = File::create(&path).unwrap();
1239 f.write_all(b"hello ostrya verity").unwrap();
1240 f.sync_all().unwrap();
1241 }
1242 // The enable ioctl needs a read-only descriptor and no writable one.
1243 let ro = File::open(&path).unwrap();
1244 if enable_verity(ro.as_fd()).is_err() {
1245 let _ = std::fs::remove_file(&path);
1246 return;
1247 }
1248
1249 let measured = measure_verity(ro.as_fd()).unwrap();
1250 assert_ne!(measured, [0u8; 32], "a sealed file has a non-zero digest");
1251 assert_eq!(
1252 measured,
1253 measure_verity(ro.as_fd()).unwrap(),
1254 "the measured digest is stable"
1255 );
1256 assert!(
1257 OpenOptions::new().write(true).open(&path).is_err(),
1258 "a verity-sealed file rejects write-open"
1259 );
1260 let _ = std::fs::remove_file(&path);
1261 }
1262
1263 /// Writes `body` to a new file named for `tag` and opens it read-only, as
1264 /// the enable ioctl needs.
1265 fn read_only_file(tag: &str, body: &[u8]) -> (std::path::PathBuf, File) {
1266 let path = std::env::temp_dir().join(format!("ostrya-sys-{tag}-{}", std::process::id()));
1267 let _ = std::fs::remove_file(&path);
1268 {
1269 let mut f = File::create(&path).unwrap();
1270 f.write_all(body).unwrap();
1271 f.sync_all().unwrap();
1272 }
1273 let ro = File::open(&path).unwrap();
1274 (path, ro)
1275 }
1276
1277 /// The descriptor of a file that `enable_verity` sealed names SHA-256,
1278 /// 4096-byte blocks, no salt, and the size of the file. The test skips if
1279 /// the file system has no fs-verity support.
1280 #[test]
1281 fn descriptor_reports_the_ostree_parameters() {
1282 let body = b"ostrya verity descriptor".repeat(300);
1283 let (path, ro) = read_only_file("verity-descriptor", &body);
1284 if let Err(e) = enable_verity(ro.as_fd()) {
1285 eprintln!("skipping descriptor check: filesystem lacks fs-verity ({e})");
1286 let _ = std::fs::remove_file(&path);
1287 return;
1288 }
1289
1290 let desc = read_verity_descriptor(ro.as_fd()).unwrap();
1291 assert_eq!(desc.version, 1);
1292 assert_eq!(desc.hash_algorithm, 1, "SHA-256");
1293 assert_eq!(desc.log_blocksize, 12, "4096-byte blocks");
1294 assert_eq!(desc.salt_size, 0);
1295 assert_eq!(desc.data_size, body.len() as u64);
1296 let _ = std::fs::remove_file(&path);
1297 }
1298
1299 /// A file sealed with a salt reports the length of the salt. Its digest is
1300 /// not the digest of the same bytes sealed with no salt. The test skips if
1301 /// the file system has no fs-verity support.
1302 #[test]
1303 fn descriptor_reports_a_salt() {
1304 let body = b"ostrya salted verity";
1305 let (plain_path, plain) = read_only_file("verity-unsalted", body);
1306 if let Err(e) = enable_verity(plain.as_fd()) {
1307 eprintln!("skipping salt check: filesystem lacks fs-verity ({e})");
1308 let _ = std::fs::remove_file(&plain_path);
1309 return;
1310 }
1311 let (path, ro) = read_only_file("verity-salted", body);
1312 enable_verity_with_salt(ro.as_fd(), &[0x5a; 8]).unwrap();
1313
1314 let desc = read_verity_descriptor(ro.as_fd()).unwrap();
1315 assert_eq!(desc.hash_algorithm, 1);
1316 assert_eq!(desc.log_blocksize, 12);
1317 assert_eq!(desc.salt_size, 8);
1318 assert_ne!(
1319 measure_verity(ro.as_fd()).unwrap(),
1320 measure_verity(plain.as_fd()).unwrap(),
1321 "the salt changes the digest"
1322 );
1323 let _ = std::fs::remove_file(&path);
1324 let _ = std::fs::remove_file(&plain_path);
1325 }
1326
1327 /// A file without fs-verity has no descriptor to read.
1328 #[test]
1329 fn descriptor_of_an_unsealed_file_is_an_error() {
1330 let (path, ro) = read_only_file("verity-unsealed", b"not sealed");
1331 assert!(read_verity_descriptor(ro.as_fd()).is_err());
1332 assert!(measure_verity(ro.as_fd()).is_err());
1333 let _ = std::fs::remove_file(&path);
1334 }
1335}
1336
1337/// Tests of the loop device and the memory-file helpers.
1338///
1339/// The tests of the loop device need access to `/dev/loop-control`, which a
1340/// root process has. Without access, they skip. If `OSTRYA_REQUIRE_MOUNT` is
1341/// set, a missing access fails them.
1342#[cfg(all(test, target_os = "linux"))]
1343mod linux_tests {
1344 use super::{
1345 LO_FLAGS_AUTOCLEAR, LO_FLAGS_DIRECT_IO, LO_FLAGS_READ_ONLY, LoopConfig, LoopDevice,
1346 seal_contents, sealable_memfd,
1347 };
1348 use std::fs::File;
1349 use std::io::{Read, Seek, SeekFrom, Write};
1350 use std::os::fd::{AsFd, OwnedFd};
1351 use std::time::{Duration, Instant};
1352
1353 use rustix::fs::SealFlags;
1354 use rustix::io::Errno;
1355
1356 /// The environment variable that turns the skip of a test with no access
1357 /// to the loop devices into a failure.
1358 const REQUIRE_MOUNT: &str = "OSTRYA_REQUIRE_MOUNT";
1359
1360 /// The read-only, auto-clearing configuration with 4096-byte blocks.
1361 const BASE: LoopConfig = LoopConfig {
1362 block_size: 4096,
1363 read_only: true,
1364 autoclear: true,
1365 direct_io: false,
1366 };
1367
1368 /// Attaches `backing` with `cfg`. Returns `None` and prints a message if
1369 /// the process has no access to the loop devices and
1370 /// [`REQUIRE_MOUNT`] is not set.
1371 fn attach_or_skip(backing: impl AsFd, cfg: &LoopConfig) -> Option<LoopDevice> {
1372 match LoopDevice::attach(backing, cfg) {
1373 Ok(dev) => Some(dev),
1374 Err(e @ (Errno::ACCESS | Errno::PERM | Errno::NOENT)) => {
1375 assert!(
1376 std::env::var_os(REQUIRE_MOUNT).is_none(),
1377 "{REQUIRE_MOUNT} is set and the process has no access to the loop devices ({e})"
1378 );
1379 eprintln!("skipped: no access to the loop devices ({e})");
1380 None
1381 }
1382 Err(e) => panic!("attach failed: {e}"),
1383 }
1384 }
1385
1386 /// Returns the backing file that the kernel names for device `number`,
1387 /// or `None` if the device has no backing file.
1388 fn backing_file(number: u32) -> Option<String> {
1389 std::fs::read_to_string(format!("/sys/block/loop{number}/loop/backing_file"))
1390 .ok()
1391 .map(|s| s.trim_end().to_owned())
1392 }
1393
1394 /// Waits up to 5 seconds until device `number` no longer has the backing
1395 /// file `backing`. The release of an auto-clearing device can finish
1396 /// after the last close returns. Another test can take the same device
1397 /// after the release, with another backing file.
1398 fn wait_detached(number: u32, backing: &str) {
1399 let deadline = Instant::now() + Duration::from_secs(5);
1400 while backing_file(number).as_deref() == Some(backing) {
1401 assert!(Instant::now() < deadline, "loop{number} stays attached");
1402 std::thread::sleep(Duration::from_millis(20));
1403 }
1404 }
1405
1406 /// Returns a sealed memory file that holds 16 KiB.
1407 fn sealed_image() -> OwnedFd {
1408 let fd = sealable_memfd("ostrya-sys-loop").unwrap();
1409 let mut file = File::from(fd);
1410 file.write_all(&[0x5a; 16384]).unwrap();
1411 seal_contents(&file).unwrap();
1412 file.into()
1413 }
1414
1415 /// A sealed memory file refuses a write, a larger size, a smaller size,
1416 /// and a removal of the seal, and still reads.
1417 #[test]
1418 fn a_sealed_memfd_refuses_each_change() {
1419 let fd = sealable_memfd("ostrya-sys-seal").unwrap();
1420 let mut file = File::from(fd);
1421 file.write_all(b"sealed bytes").unwrap();
1422 seal_contents(&file).unwrap();
1423
1424 let seals = rustix::fs::fcntl_get_seals(&file).unwrap();
1425 assert!(
1426 seals
1427 .contains(SealFlags::WRITE | SealFlags::GROW | SealFlags::SHRINK | SealFlags::SEAL)
1428 );
1429 file.seek(SeekFrom::Start(0)).unwrap();
1430 assert!(file.write_all(b"x").is_err(), "a write is refused");
1431 assert_eq!(
1432 rustix::fs::ftruncate(&file, 64).unwrap_err(),
1433 Errno::PERM,
1434 "a larger size is refused"
1435 );
1436 assert_eq!(
1437 rustix::fs::ftruncate(&file, 1).unwrap_err(),
1438 Errno::PERM,
1439 "a smaller size is refused"
1440 );
1441 assert_eq!(seal_contents(&file).unwrap_err(), Errno::PERM);
1442
1443 let mut back = String::new();
1444 file.seek(SeekFrom::Start(0)).unwrap();
1445 file.read_to_string(&mut back).unwrap();
1446 assert_eq!(back, "sealed bytes");
1447 }
1448
1449 /// A loop device on a regular file holds the flags of its configuration
1450 /// and names the file. At the last close, the kernel detaches it.
1451 #[test]
1452 fn an_auto_clearing_device_detaches_at_the_last_close() {
1453 let path = std::env::temp_dir().join(format!("ostrya-sys-loop-{}", std::process::id()));
1454 std::fs::write(&path, vec![0u8; 16384]).unwrap();
1455 let file = File::open(&path).unwrap();
1456 let Some(dev) = attach_or_skip(&file, &BASE) else {
1457 let _ = std::fs::remove_file(&path);
1458 return;
1459 };
1460 let flags = dev.flags().unwrap();
1461 assert_eq!(
1462 flags & (LO_FLAGS_READ_ONLY | LO_FLAGS_AUTOCLEAR),
1463 LO_FLAGS_READ_ONLY | LO_FLAGS_AUTOCLEAR
1464 );
1465 let number = dev.number();
1466 let backing = backing_file(number).unwrap();
1467 assert_eq!(backing, path.to_str().unwrap());
1468
1469 drop(file);
1470 drop(dev);
1471 wait_detached(number, &backing);
1472 let _ = std::fs::remove_file(&path);
1473 }
1474
1475 /// A sealed memory file backs a loop device with a request for direct
1476 /// I/O. If the kernel refuses direct I/O on it, the device attaches
1477 /// without direct I/O. The test prints the flags that the kernel holds.
1478 #[test]
1479 fn a_sealed_memfd_backs_a_loop_device() {
1480 let image = sealed_image();
1481 let cfg = LoopConfig {
1482 direct_io: true,
1483 ..BASE
1484 };
1485 let Some(dev) = attach_or_skip(&image, &cfg) else {
1486 return;
1487 };
1488 let flags = dev.flags().unwrap();
1489 eprintln!(
1490 "loop{} flags {flags:#x}, direct I/O {}",
1491 dev.number(),
1492 flags & LO_FLAGS_DIRECT_IO != 0
1493 );
1494 assert_ne!(flags & LO_FLAGS_READ_ONLY, 0);
1495 let number = dev.number();
1496 let backing = backing_file(number).unwrap();
1497 drop(image);
1498 drop(dev);
1499 wait_detached(number, &backing);
1500 }
1501}
1502
1503/// Tests of the namespace, ID-mapping, and socket helpers. They run as any
1504/// user.
1505#[cfg(all(test, target_os = "linux"))]
1506mod ns_sock_tests {
1507 use super::{
1508 mount_setattr_idmap, ns_owner_userns, ns_type, peer_groups, sock::listen_vars_match,
1509 systemd_listen_fd,
1510 };
1511 use std::ffi::OsStr;
1512 use std::os::fd::{AsFd, AsRawFd, OwnedFd};
1513 use std::process::Command;
1514
1515 use rustix::fs::{CWD, Mode, OFlags, fstat, openat};
1516 use rustix::io::{Errno, FdFlags};
1517 use rustix::thread::LinkNameSpaceType;
1518
1519 /// The name of the ignored test that the descriptor test runs in a child
1520 /// process.
1521 const LISTEN_CHILD: &str = "ns_sock_tests::listen_fd_child";
1522
1523 /// Opens `/proc/thread-self/ns/<name>`.
1524 fn own_ns(name: &str) -> OwnedFd {
1525 openat(
1526 CWD,
1527 format!("/proc/thread-self/ns/{name}"),
1528 OFlags::RDONLY | OFlags::CLOEXEC,
1529 Mode::empty(),
1530 )
1531 .unwrap()
1532 }
1533
1534 /// Returns the device and the inode of `fd`.
1535 fn dev_ino(fd: impl AsFd) -> (u64, u64) {
1536 let st = fstat(fd).unwrap();
1537 (st.st_dev, st.st_ino)
1538 }
1539
1540 #[test]
1541 fn a_namespace_has_its_type() {
1542 assert_eq!(ns_type(own_ns("user")).unwrap(), LinkNameSpaceType::User);
1543 assert_eq!(ns_type(own_ns("mnt")).unwrap(), LinkNameSpaceType::Mount);
1544 assert_eq!(ns_type(own_ns("net")).unwrap(), LinkNameSpaceType::Network);
1545 let file = std::fs::File::open("/proc/self/status").unwrap();
1546 assert_eq!(ns_type(&file).unwrap_err(), Errno::NOTTY);
1547 }
1548
1549 #[test]
1550 fn the_user_namespace_of_the_process_owns_its_mount_namespace() {
1551 let owner = ns_owner_userns(own_ns("mnt")).unwrap();
1552 assert_eq!(dev_ino(&owner), dev_ino(own_ns("user")));
1553 assert_eq!(ns_type(&owner).unwrap(), LinkNameSpaceType::User);
1554 let flags = rustix::io::fcntl_getfd(&owner).unwrap();
1555 assert!(flags.contains(FdFlags::CLOEXEC));
1556 }
1557
1558 /// A directory descriptor is not a detached mount. Without the privilege
1559 /// the kernel refuses the call with `EPERM`. With it, the kernel refuses
1560 /// the descriptor or the initial user namespace with `EINVAL`.
1561 #[test]
1562 fn an_idmap_of_a_plain_directory_is_refused() {
1563 let dir = openat(
1564 CWD,
1565 "/",
1566 OFlags::DIRECTORY | OFlags::RDONLY | OFlags::CLOEXEC,
1567 Mode::empty(),
1568 )
1569 .unwrap();
1570 let err = mount_setattr_idmap(&dir, own_ns("user")).unwrap_err();
1571 assert!(matches!(err, Errno::PERM | Errno::INVAL), "{err}");
1572 }
1573
1574 #[test]
1575 fn the_peer_groups_of_a_socket_pair_are_the_groups_of_the_process() {
1576 let (a, _b) = std::os::unix::net::UnixStream::pair().unwrap();
1577 let mut got: Vec<u32> = peer_groups(&a, 4096).unwrap();
1578 got.sort_unstable();
1579 let status = std::fs::read_to_string("/proc/self/status").unwrap();
1580 let mut want: Vec<u32> = status
1581 .lines()
1582 .find_map(|line| line.strip_prefix("Groups:"))
1583 .unwrap()
1584 .split_whitespace()
1585 .map(|g| g.parse().unwrap())
1586 .collect();
1587 want.sort_unstable();
1588 assert_eq!(got, want);
1589 if !want.is_empty() {
1590 assert_eq!(peer_groups(&a, want.len() - 1).unwrap_err(), Errno::RANGE);
1591 }
1592
1593 let file = std::fs::File::open("/proc/self/status").unwrap();
1594 assert_eq!(peer_groups(&file, 4096).unwrap_err(), Errno::NOTSOCK);
1595 }
1596
1597 #[test]
1598 fn the_listen_variables_must_name_this_process_and_one_socket() {
1599 let s = |v: &'static str| Some(OsStr::new(v));
1600 assert_eq!(listen_vars_match(None, None, 42), Ok(false));
1601 assert_eq!(listen_vars_match(s("42"), s("1"), 42), Ok(true));
1602 assert_eq!(listen_vars_match(s("41"), s("1"), 42), Err(Errno::INVAL));
1603 assert_eq!(listen_vars_match(s("42"), s("2"), 42), Err(Errno::INVAL));
1604 assert_eq!(listen_vars_match(s("42"), s("0"), 42), Err(Errno::INVAL));
1605 assert_eq!(listen_vars_match(s("x"), s("1"), 42), Err(Errno::INVAL));
1606 assert_eq!(listen_vars_match(s("42"), None, 42), Err(Errno::INVAL));
1607 assert_eq!(listen_vars_match(None, s("1"), 42), Err(Errno::INVAL));
1608 }
1609
1610 /// A child process with the systemd variables and an open descriptor 3
1611 /// takes the descriptor once.
1612 #[test]
1613 fn a_passed_descriptor_is_taken_once() {
1614 let exe = std::env::current_exe().unwrap();
1615 let out = Command::new("/bin/sh")
1616 .arg("-c")
1617 .arg(r#"export LISTEN_PID=$$ LISTEN_FDS=1; exec "$0" "$@" 3</dev/null"#)
1618 .arg(&exe)
1619 .args([LISTEN_CHILD, "--exact", "--ignored", "--nocapture"])
1620 .output()
1621 .unwrap();
1622 let stdout = String::from_utf8_lossy(&out.stdout);
1623 assert!(
1624 out.status.success() && stdout.contains("1 passed"),
1625 "{}\n{stdout}\n{}",
1626 out.status,
1627 String::from_utf8_lossy(&out.stderr)
1628 );
1629 }
1630
1631 /// The body of the child process of [`a_passed_descriptor_is_taken_once`].
1632 /// Outside that child, the test does nothing.
1633 #[test]
1634 #[ignore = "runs in a child process with LISTEN_PID and LISTEN_FDS"]
1635 fn listen_fd_child() {
1636 if std::env::var_os("LISTEN_PID").is_none() {
1637 return;
1638 }
1639 let fd = systemd_listen_fd().unwrap().unwrap();
1640 assert_eq!(fd.as_raw_fd(), 3);
1641 let flags = rustix::io::fcntl_getfd(&fd).unwrap();
1642 assert!(flags.contains(FdFlags::CLOEXEC));
1643 assert_eq!(systemd_listen_fd().unwrap_err(), Errno::ALREADY);
1644 }
1645}