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