blob: 86c4969f8a6c54f2ad233cbadb935e654c4f2222 [file] [log] [blame]
Victor Hsiehdde17902021-02-26 12:35:31 -08001/*
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 super::common::{build_fsverity_digest, merkle_tree_height, FsverityError};
18use crate::common::CHUNK_SIZE;
19use crate::crypto::{CryptoError, Sha256Hash, Sha256Hasher};
20
21const HASH_SIZE: usize = Sha256Hasher::HASH_SIZE;
22const HASH_PER_PAGE: usize = CHUNK_SIZE as usize / HASH_SIZE;
23
24/// MerkleLeaves can be used by the class' customer for bookkeeping integrity data for their bytes.
25/// It can also be used to generate the standard fs-verity digest for the source data.
26///
27/// It's in-memory because for the initial use cases, we don't need to read back an existing file,
28/// and only need to deal with new files. Also, considering that the output file won't be large at
29/// the moment, it is sufficient to simply keep the Merkle tree in memory in the trusted world. To
30/// further simplify the initial implementation, we only need to keep the leaf nodes in memory, and
31/// generate the tree / root hash when requested.
32pub struct MerkleLeaves {
33 leaves: Vec<Sha256Hash>,
34 file_size: u64,
35}
36
37fn hash_all_pages(source: &[Sha256Hash]) -> Result<Vec<Sha256Hash>, CryptoError> {
38 source
39 .chunks(HASH_PER_PAGE)
40 .map(|chunk| {
41 let padding_bytes = (HASH_PER_PAGE - chunk.len()) * HASH_SIZE;
42 Ok(Sha256Hasher::new()?
43 .update_from(chunk)?
44 .update(&vec![0u8; padding_bytes])?
45 .finalize()?)
46 })
47 .collect()
48}
49
Victor Hsiehdde17902021-02-26 12:35:31 -080050impl MerkleLeaves {
51 /// Creates a `MerkleLeaves` instance with empty data.
52 pub fn new() -> Self {
53 Self { leaves: Vec::new(), file_size: 0 }
54 }
55
56 /// Updates the hash of the `index`-th leaf, and increase the size to `size_at_least` if the
57 /// current size is smaller.
58 pub fn update_hash(&mut self, index: usize, hash: &Sha256Hash, size_at_least: u64) {
59 // +1 since index is zero-based.
60 if self.leaves.len() < index + 1 {
61 // When resizing, fill in hash of zeros by default. This makes it easy to handle holes
62 // in a file.
63 self.leaves.resize(index + 1, Sha256Hasher::HASH_OF_4096_ZEROS);
64 }
65 self.leaves[index].clone_from_slice(hash);
66
67 if size_at_least > self.file_size {
68 self.file_size = size_at_least;
69 }
70 }
71
72 /// Returns whether `index` is within the bound of leaves.
73 pub fn is_index_valid(&self, index: usize) -> bool {
74 index < self.leaves.len()
75 }
76
77 /// Returns whether the `index`-th hash is consistent to `hash`.
78 pub fn is_consistent(&self, index: usize, hash: &Sha256Hash) -> bool {
79 if let Some(element) = self.leaves.get(index) {
80 element == hash
81 } else {
82 false
83 }
84 }
85
86 fn calculate_root_hash(&self) -> Result<Sha256Hash, FsverityError> {
87 match self.leaves.len() {
88 // Special cases per fs-verity digest definition.
89 0 => {
90 debug_assert_eq!(self.file_size, 0);
91 Ok([0u8; HASH_SIZE])
92 }
93 1 => {
94 debug_assert!(self.file_size <= CHUNK_SIZE && self.file_size > 0);
95 Ok(self.leaves[0])
96 }
97 n => {
98 debug_assert_eq!((self.file_size - 1) / CHUNK_SIZE, n as u64);
99 let size_for_equivalent = n as u64 * CHUNK_SIZE;
100 let level = merkle_tree_height(size_for_equivalent).unwrap(); // safe since n > 0
101
102 // `leaves` is owned and can't be the initial state below. Here we manually hash it
103 // first to avoid a copy and to get the type right.
104 let second_level = hash_all_pages(&self.leaves)?;
105 let hashes =
106 (1..=level).try_fold(second_level, |source, _| hash_all_pages(&source))?;
107 if hashes.len() != 1 {
108 Err(FsverityError::InvalidState)
109 } else {
110 Ok(hashes.into_iter().next().unwrap())
111 }
112 }
113 }
114 }
115
116 /// Returns the fs-verity digest based on the current tree and file size.
117 pub fn calculate_fsverity_digest(&self) -> Result<Sha256Hash, FsverityError> {
118 let root_hash = self.calculate_root_hash()?;
119 Ok(build_fsverity_digest(&root_hash, self.file_size)?)
120 }
121}
122
123#[cfg(test)]
124mod tests {
125 // Test data below can be generated by:
126 // $ perl -e 'print "\x{00}" x 6000' > foo
127 // $ perl -e 'print "\x{01}" x 5000' >> foo
128 // $ fsverity digest foo
129 use super::*;
130 use anyhow::Result;
131
132 #[test]
133 fn merkle_tree_empty_file() -> Result<()> {
134 assert_eq!(
135 to_u8_vec("3d248ca542a24fc62d1c43b916eae5016878e2533c88238480b26128a1f1af95"),
136 generate_fsverity_digest_sequentially(&Vec::new())?
137 );
138 Ok(())
139 }
140
141 #[test]
142 fn merkle_tree_file_size_less_than_or_equal_to_4k() -> Result<()> {
143 // Test a file that contains 4096 '\01's.
144 assert_eq!(
145 to_u8_vec("cd0875ca59c7d37e962c5e8f5acd3770750ac80225e2df652ce5672fd34500af"),
146 generate_fsverity_digest_sequentially(&vec![1; 4096])?
147 );
148 Ok(())
149 }
150
151 #[test]
152 fn merkle_tree_more_sizes() -> Result<()> {
153 // Test files that contains >4096 '\01's.
154
155 assert_eq!(
156 to_u8_vec("2901b849fda2d91e3929524561c4a47e77bb64734319759507b2029f18b9cc52"),
157 generate_fsverity_digest_sequentially(&vec![1; 4097])?
158 );
159
160 assert_eq!(
161 to_u8_vec("2a476d58eb80394052a3a783111e1458ac3ecf68a7878183fed86ca0ff47ec0d"),
162 generate_fsverity_digest_sequentially(&vec![1; 8192])?
163 );
164
165 // Test with max size that still fits in 2 levels.
166 assert_eq!(
167 to_u8_vec("26b7c190a34e19f420808ee7ec233b09fa6c34543b5a9d2950530114c205d14f"),
168 generate_fsverity_digest_sequentially(&vec![1; 524288])?
169 );
170
171 // Test with data that requires 3 levels.
172 assert_eq!(
173 to_u8_vec("316835d9be1c95b5cd55d07ae7965d651689efad186e26cbf680e40b683a3262"),
174 generate_fsverity_digest_sequentially(&vec![1; 524289])?
175 );
176 Ok(())
177 }
178
179 #[test]
180 fn merkle_tree_non_sequential() -> Result<()> {
181 let mut tree = MerkleLeaves::new();
182 let hash = Sha256Hasher::new()?.update(&vec![1u8; CHUNK_SIZE as usize])?.finalize()?;
183
184 // Update hashes of 4 1-blocks.
185 tree.update_hash(1, &hash, CHUNK_SIZE * 2);
186 tree.update_hash(3, &hash, CHUNK_SIZE * 4);
187 tree.update_hash(0, &hash, CHUNK_SIZE);
188 tree.update_hash(2, &hash, CHUNK_SIZE * 3);
189
190 assert_eq!(
191 to_u8_vec("7d3c0d2e1dc54230b20ed875f5f3a4bd3f9873df601936b3ca8127d4db3548f3"),
192 tree.calculate_fsverity_digest()?
193 );
194 Ok(())
195 }
196
197 fn generate_fsverity_digest_sequentially(test_data: &[u8]) -> Result<Sha256Hash> {
198 let mut tree = MerkleLeaves::new();
199 for (index, chunk) in test_data.chunks(CHUNK_SIZE as usize).enumerate() {
200 let hash = Sha256Hasher::new()?
201 .update(&chunk)?
202 .update(&vec![0u8; CHUNK_SIZE as usize - chunk.len()])?
203 .finalize()?;
204
205 tree.update_hash(index, &hash, CHUNK_SIZE * index as u64 + chunk.len() as u64);
206 }
207 Ok(tree.calculate_fsverity_digest()?)
208 }
209
210 fn to_u8_vec(hex_str: &str) -> Vec<u8> {
211 assert!(hex_str.len() % 2 == 0);
212 (0..hex_str.len())
213 .step_by(2)
214 .map(|i| u8::from_str_radix(&hex_str[i..i + 2], 16).unwrap())
215 .collect()
216 }
217}