Victor Hsieh | 9ed2718 | 2021-08-25 15:52:42 -0700 | [diff] [blame] | 1 | /* |
| 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 | |
| 17 | use anyhow::{bail, Result}; |
| 18 | use libc::getxattr; |
| 19 | use std::ffi::CString; |
| 20 | use std::io; |
| 21 | use std::os::unix::io::RawFd; |
| 22 | |
Victor Hsieh | 9ed2718 | 2021-08-25 15:52:42 -0700 | [diff] [blame] | 23 | const SHA256_HASH_SIZE: usize = 32; |
| 24 | |
Victor Hsieh | 9ed2718 | 2021-08-25 15:52:42 -0700 | [diff] [blame] | 25 | /// Bytes of SHA256 digest |
| 26 | pub type Sha256Digest = [u8; SHA256_HASH_SIZE]; |
| 27 | |
| 28 | /// Returns the fs-verity measurement/digest. Currently only SHA256 is supported. |
| 29 | pub fn measure(fd: RawFd) -> Result<Sha256Digest> { |
| 30 | // TODO(b/196635431): Unfortunately, the FUSE API doesn't allow authfs to implement the standard |
| 31 | // fs-verity ioctls. Until the kernel allows, use the alternative xattr that authfs provides. |
| 32 | let path = CString::new(format!("/proc/self/fd/{}", fd).as_str()).unwrap(); |
| 33 | let name = CString::new("authfs.fsverity.digest").unwrap(); |
| 34 | let mut buf = [0u8; SHA256_HASH_SIZE]; |
| 35 | // SAFETY: getxattr should not write beyond the given buffer size. |
| 36 | let size = unsafe { |
| 37 | getxattr(path.as_ptr(), name.as_ptr(), buf.as_mut_ptr() as *mut libc::c_void, buf.len()) |
| 38 | }; |
| 39 | if size < 0 { |
| 40 | bail!("Failed to getxattr: {}", io::Error::last_os_error()); |
| 41 | } else if size != SHA256_HASH_SIZE as isize { |
| 42 | bail!("Unexpected hash size: {}", size); |
| 43 | } else { |
| 44 | Ok(buf) |
| 45 | } |
| 46 | } |