1 /*
2  * Copyright (C) 2023 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 //! A wrapper library to use fs-verity
18 
19 mod sys;
20 
21 use crate::sys::*;
22 use std::io;
23 use std::os::fd::AsRawFd;
24 use std::os::unix::io::BorrowedFd;
25 
read_metadata(fd: i32, metadata_type: u64, offset: u64, buf: &mut [u8]) -> io::Result<usize>26 fn read_metadata(fd: i32, metadata_type: u64, offset: u64, buf: &mut [u8]) -> io::Result<usize> {
27     let mut arg = fsverity_read_metadata_arg {
28         metadata_type,
29         offset,
30         length: buf.len() as u64,
31         buf_ptr: buf.as_mut_ptr() as u64,
32         __reserved: 0,
33     };
34     // SAFETY: the ioctl doesn't change the sematics in the current process
35     Ok(unsafe { read_verity_metadata(fd, &mut arg) }? as usize)
36 }
37 
38 /// Read the raw Merkle tree from the fd, if it exists. The API semantics is similar to a regular
39 /// pread(2), and may not return full requested buffer.
read_merkle_tree(fd: i32, offset: u64, buf: &mut [u8]) -> io::Result<usize>40 pub fn read_merkle_tree(fd: i32, offset: u64, buf: &mut [u8]) -> io::Result<usize> {
41     read_metadata(fd, FS_VERITY_METADATA_TYPE_MERKLE_TREE, offset, buf)
42 }
43 
44 /// Read the fs-verity signature from the fd (if exists). The returned signature should be complete.
read_signature(fd: i32, buf: &mut [u8]) -> io::Result<usize>45 pub fn read_signature(fd: i32, buf: &mut [u8]) -> io::Result<usize> {
46     read_metadata(fd, FS_VERITY_METADATA_TYPE_SIGNATURE, 0 /* offset */, buf)
47 }
48 
49 /// Enable fs-verity to the `fd`, with sha256 hash algorithm and 4KB block size.
enable(fd: BorrowedFd) -> io::Result<()>50 pub fn enable(fd: BorrowedFd) -> io::Result<()> {
51     let arg = fsverity_enable_arg {
52         version: 1,
53         hash_algorithm: FS_VERITY_HASH_ALG_SHA256,
54         block_size: 4096,
55         salt_size: 0,
56         salt_ptr: 0,
57         sig_size: 0,
58         __reserved1: 0,
59         sig_ptr: 0,
60         __reserved2: [0; 11],
61     };
62     // SAFETY: the ioctl doesn't change the sematics in the current process
63     if unsafe { enable_verity(fd.as_raw_fd(), &arg) } == Ok(0) {
64         Ok(())
65     } else {
66         Err(io::Error::last_os_error())
67     }
68 }
69