blob: 547fa47824bce7f0b228378522876915e8423131 [file] [log] [blame]
Jiyong Parkbf9673a2021-08-11 15:58:07 +09001/*
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 */
16use ring::digest::{self, Algorithm};
17use std::io::{Cursor, Read, Result, Seek, SeekFrom, Write};
18
19/// `HashTree` is a merkle tree (and its root hash) that is compatible with fs-verity.
20pub struct HashTree {
21 pub tree: Vec<u8>,
22 pub root_hash: Vec<u8>,
23}
24
25impl HashTree {
26 /// Creates merkle tree from `input`, using the given `salt` and hashing `algorithm`. `input`
27 /// is divided into `block_size` chunks.
28 pub fn from<R: Read>(
29 input: &mut R,
30 input_size: usize,
31 salt: &[u8],
32 block_size: usize,
33 algorithm: &'static Algorithm,
34 ) -> Result<Self> {
35 let salt = zero_pad_salt(&salt, algorithm);
36 let tree = generate_hash_tree(input, input_size, &salt, block_size, algorithm)?;
37
38 // Root hash is from the first block of the hash or the input data if there is no hash tree
39 // generate which can happen when input data is smaller than block size
40 let root_hash = if tree.is_empty() {
41 hash_one_level(input, input_size, &salt, block_size, algorithm)?
42 } else {
43 let mut ctx = digest::Context::new(algorithm);
44 ctx.update(&salt);
45 ctx.update(&tree[0..block_size]);
46 ctx.finish().as_ref().to_vec()
47 };
48 Ok(HashTree { tree, root_hash })
49 }
50}
51
52/// Calculate hash tree for the blocks in `input`.
53///
54/// This function implements: https://www.kernel.org/doc/html/latest/filesystems/fsverity.html#merkle-tree
55///
56/// The file contents is divided into blocks, where the block size is configurable but is usually
57/// 4096 bytes. The end of the last block is zero-padded if needed. Each block is then hashed,
58/// producing the first level of hashes. Then, the hashes in this first level are grouped into
59/// blocksize-byte blocks (zero-padding the ends as needed) and these blocks are hashed,
60/// producing the second level of hashes. This proceeds up the tree until only a single block
61/// remains.
62fn generate_hash_tree<R: Read>(
63 input: &mut R,
64 input_size: usize,
65 salt: &[u8],
66 block_size: usize,
67 algorithm: &'static Algorithm,
68) -> Result<Vec<u8>> {
69 let digest_size = algorithm.output_len;
70 let (hash_level_offsets, tree_size) =
71 calc_hash_level_offsets(input_size, block_size, digest_size);
72
73 let mut hash_tree = Cursor::new(vec![0; tree_size]);
74 let mut input_size = input_size;
75 for (level, offset) in hash_level_offsets.iter().enumerate() {
76 let hashes = if level == 0 {
77 hash_one_level(input, input_size, salt, block_size, algorithm)?
78 } else {
79 // For the intermediate levels, input is the output from the previous level
80 hash_tree.seek(SeekFrom::Start(hash_level_offsets[level - 1] as u64)).unwrap();
81 hash_one_level(&mut hash_tree, input_size, salt, block_size, algorithm)?
82 };
83 hash_tree.seek(SeekFrom::Start(*offset as u64)).unwrap();
84 hash_tree.write_all(hashes.as_ref()).unwrap();
85 // Output from this level becomes input for the next level
86 input_size = hashes.len();
87 }
88 Ok(hash_tree.into_inner())
89}
90
91/// Calculate hashes for the blocks in `input`. The end of the last block is zero-padded if needed.
92/// Each block is then hashed, producing a stream of hashes for a level.
93fn hash_one_level<R: Read>(
94 input: &mut R,
95 input_size: usize,
96 salt: &[u8],
97 block_size: usize,
98 algorithm: &'static Algorithm,
99) -> Result<Vec<u8>> {
100 // Input is zero padded when it's not multiple of blocks. Note that `take()` is also needed to
101 // not read more than `input_size` from the `input` reader. This is required because `input`
102 // can be from the in-memory hashtree. We need to read only the part of hashtree that is for
103 // the current level.
104 let pad_size = round_to_multiple(input_size, block_size) - input_size;
105 let mut input = input.take(input_size as u64).chain(Cursor::new(vec![0; pad_size]));
106
107 // Read one block from input, write the hash of it to the output. Repeat that for all input
108 // blocks.
109 let mut hashes = Cursor::new(Vec::new());
110 let mut buf = vec![0; block_size];
111 let mut num_blocks = (input_size + block_size - 1) / block_size;
112 while num_blocks > 0 {
113 input.read_exact(&mut buf)?;
114 let mut ctx = digest::Context::new(algorithm);
115 ctx.update(salt);
116 ctx.update(&buf);
117 let hash = ctx.finish();
118 hashes.write_all(hash.as_ref())?;
119 num_blocks -= 1;
120 }
121 Ok(hashes.into_inner())
122}
123
124/// Calculate the size of hashes for each level, and also returns the total size of the hash tree.
125/// This function is needed because hash tree is stored upside down; hashes for level N is stored
126/// "after" hashes for level N + 1.
127fn calc_hash_level_offsets(
128 input_size: usize,
129 block_size: usize,
130 digest_size: usize,
131) -> (Vec<usize>, usize) {
132 // The input is split into multiple blocks and each block is hashed, which becomes the input
133 // for the next level. Size of a single hash is `digest_size`.
134 let mut level_sizes = Vec::new();
135 loop {
136 // Input for this level is from either the last level (if exists), or the input parameter.
137 let input_size = *level_sizes.last().unwrap_or(&input_size);
138 if input_size <= block_size {
139 break;
140 }
141 let num_blocks = (input_size + block_size - 1) / block_size;
142 let hashes_size = round_to_multiple(num_blocks * digest_size, block_size);
143 level_sizes.push(hashes_size);
144 }
145 if level_sizes.is_empty() {
146 return ([].to_vec(), 0);
147 }
148
149 // The hash tree is stored upside down. The top level is at offset 0. The second level comes
150 // next, and so on. Level 0 is located at the end.
151 //
152 // Given level_sizes [10, 3, 1], the offsets for each label are ...
153 //
154 // Level 2 is at offset 0
155 // Level 1 is at offset 1 (because Level 2 is of size 1)
156 // Level 0 is at offset 4 (because Level 1 is of size 3)
157 //
158 // This is done by accumulating the sizes in reverse order (i.e. from the highest level to the
159 // level 1 (not level 0)
160 let mut offsets = level_sizes.iter().rev().take(level_sizes.len() - 1).fold(
161 vec![0; 1], // offset for the top level
162 |mut offsets, size| {
163 offsets.push(offsets.last().unwrap() + size);
164 offsets
165 },
166 );
167 offsets.reverse(); // reverse the offsets again so that index N is for level N
168 let tree_size = level_sizes.iter().sum();
169 (offsets, tree_size)
170}
171
172/// Round `n` up to the nearest multiple of `unit`
173fn round_to_multiple(n: usize, unit: usize) -> usize {
174 (n + unit - 1) & !(unit - 1)
175}
176
177/// Pad zero to salt if necessary.
178///
179/// According to https://www.kernel.org/doc/html/latest/filesystems/fsverity.html:
180///
181/// If a salt was specified, then it’s zero-padded to the closest multiple of the input size of the
182/// hash algorithm’s compression function, e.g. 64 bytes for SHA-256 or 128 bytes for SHA-512. The
183/// padded salt is prepended to every data or Merkle tree block that is hashed.
184fn zero_pad_salt(salt: &[u8], algorithm: &Algorithm) -> Vec<u8> {
185 if salt.is_empty() {
186 salt.to_vec()
187 } else {
188 let padded_len = round_to_multiple(salt.len(), algorithm.block_len);
189 let mut salt = salt.to_vec();
190 salt.resize(padded_len, 0);
191 salt
192 }
193}
194
195#[cfg(test)]
196mod tests {
197 use crate::*;
198 use ring::digest;
199 use std::fs::{self, File};
200
201 #[test]
202 fn compare_with_golden_output() -> Result<()> {
203 // The golden outputs are generated by using the `fsverity` utility.
204 let sizes = ["512", "4K", "1M", "10000000"];
205 for size in sizes.iter() {
206 let input_name = format!("testdata/input.{}", size);
207 let mut input = File::open(&input_name)?;
208 let golden_hash_tree = fs::read(format!("testdata/input.{}.hash", size))?;
209 let golden_descriptor = fs::read(format!("testdata/input.{}.descriptor", size))?;
210 let golden_root_hash = &golden_descriptor[16..16 + 32];
211
212 let size = std::fs::metadata(&input_name)?.len() as usize;
213 let salt = vec![1, 2, 3, 4, 5, 6];
214 let ht = HashTree::from(&mut input, size, &salt, 4096, &digest::SHA256)?;
215
216 assert_eq!(golden_hash_tree.as_slice(), ht.tree.as_slice());
217 assert_eq!(golden_root_hash, ht.root_hash.as_slice());
218 }
219 Ok(())
220 }
221}