blob: a1e23140f71f81c70ca51c57f71c4ae887fafef2 [file] [log] [blame]
Victor Hsieh9ed27182021-08-25 15:52:42 -07001/*
2 * Copyright (C) 2021 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
17use anyhow::{bail, Result};
18use libc::getxattr;
19use std::ffi::CString;
20use std::io;
21use std::os::unix::io::RawFd;
22
23/// Magic used in fs-verity digest
24const FS_VERITY_MAGIC: &[u8; 8] = b"FSVerity";
25
26/// Hash algorithm to use from linux/fsverity.h
27const FS_VERITY_HASH_ALG_SHA256: u8 = 1;
28
29const SHA256_HASH_SIZE: usize = 32;
30
31/// Size of `struct fsverity_formatted_digest` with SHA-256 in bytes.
32const FORMATTED_SHA256_DIGEST_SIZE: usize = 12 + SHA256_HASH_SIZE;
33
34/// Bytes of `struct fsverity_formatted_digest` in Linux with SHA-256.
35pub type FormattedSha256Digest = [u8; FORMATTED_SHA256_DIGEST_SIZE];
36
37/// Bytes of SHA256 digest
38pub type Sha256Digest = [u8; SHA256_HASH_SIZE];
39
40/// Returns the fs-verity measurement/digest. Currently only SHA256 is supported.
41pub fn measure(fd: RawFd) -> Result<Sha256Digest> {
42 // TODO(b/196635431): Unfortunately, the FUSE API doesn't allow authfs to implement the standard
43 // fs-verity ioctls. Until the kernel allows, use the alternative xattr that authfs provides.
44 let path = CString::new(format!("/proc/self/fd/{}", fd).as_str()).unwrap();
45 let name = CString::new("authfs.fsverity.digest").unwrap();
46 let mut buf = [0u8; SHA256_HASH_SIZE];
47 // SAFETY: getxattr should not write beyond the given buffer size.
48 let size = unsafe {
49 getxattr(path.as_ptr(), name.as_ptr(), buf.as_mut_ptr() as *mut libc::c_void, buf.len())
50 };
51 if size < 0 {
52 bail!("Failed to getxattr: {}", io::Error::last_os_error());
53 } else if size != SHA256_HASH_SIZE as isize {
54 bail!("Unexpected hash size: {}", size);
55 } else {
56 Ok(buf)
57 }
58}
59
60pub fn to_formatted_digest(digest: &Sha256Digest) -> FormattedSha256Digest {
61 let mut formatted_digest: FormattedSha256Digest = [0; FORMATTED_SHA256_DIGEST_SIZE];
62 formatted_digest[0..8].copy_from_slice(FS_VERITY_MAGIC);
63 formatted_digest[8..10].copy_from_slice(&(FS_VERITY_HASH_ALG_SHA256 as u16).to_le_bytes());
64 formatted_digest[10..12].copy_from_slice(&(SHA256_HASH_SIZE as u16).to_le_bytes());
65 formatted_digest[12..].copy_from_slice(digest);
66 formatted_digest
67}