1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Opening fs-verity files
4  *
5  * Copyright 2019 Google LLC
6  */
7 
8 #include "fsverity_private.h"
9 
10 #include <linux/mm.h>
11 #include <linux/slab.h>
12 
13 static struct kmem_cache *fsverity_info_cachep;
14 
15 /**
16  * fsverity_init_merkle_tree_params() - initialize Merkle tree parameters
17  * @params: the parameters struct to initialize
18  * @inode: the inode for which the Merkle tree is being built
19  * @hash_algorithm: number of hash algorithm to use
20  * @log_blocksize: log base 2 of block size to use
21  * @salt: pointer to salt (optional)
22  * @salt_size: size of salt, possibly 0
23  * @data_size: verified data size
24  *
25  * Validate the hash algorithm and block size, then compute the tree topology
26  * (num levels, num blocks in each level, etc.) and initialize @params.
27  *
28  * Return: 0 on success, -errno on failure
29  */
fsverity_init_merkle_tree_params(struct merkle_tree_params *params, const struct inode *inode, unsigned int hash_algorithm, unsigned int log_blocksize, const u8 *salt, size_t salt_size, u64 data_size)30 int fsverity_init_merkle_tree_params(struct merkle_tree_params *params,
31 				     const struct inode *inode,
32 				     unsigned int hash_algorithm,
33 				     unsigned int log_blocksize,
34 				     const u8 *salt, size_t salt_size,
35 				     u64 data_size)
36 {
37 	const struct fsverity_hash_alg *hash_alg;
38 	int err;
39 	u64 blocks;
40 	u64 blocks_in_level[FS_VERITY_MAX_LEVELS];
41 	u64 offset;
42 	int level;
43 
44 	memset(params, 0, sizeof(*params));
45 
46 	hash_alg = fsverity_get_hash_alg(inode, hash_algorithm);
47 	if (IS_ERR(hash_alg))
48 		return PTR_ERR(hash_alg);
49 	params->hash_alg = hash_alg;
50 	params->digest_size = hash_alg->digest_size;
51 
52 	params->hashstate = fsverity_prepare_hash_state(hash_alg, salt,
53 							salt_size);
54 	if (IS_ERR(params->hashstate)) {
55 		err = PTR_ERR(params->hashstate);
56 		params->hashstate = NULL;
57 		fsverity_err(inode, "Error %d preparing hash state", err);
58 		goto out_err;
59 	}
60 
61 	/*
62 	 * fs/verity/ directly assumes that the Merkle tree block size is a
63 	 * power of 2 less than or equal to PAGE_SIZE.  Another restriction
64 	 * arises from the interaction between fs/verity/ and the filesystems
65 	 * themselves: filesystems expect to be able to verify a single
66 	 * filesystem block of data at a time.  Therefore, the Merkle tree block
67 	 * size must also be less than or equal to the filesystem block size.
68 	 *
69 	 * The above are the only hard limitations, so in theory the Merkle tree
70 	 * block size could be as small as twice the digest size.  However,
71 	 * that's not useful, and it would result in some unusually deep and
72 	 * large Merkle trees.  So we currently require that the Merkle tree
73 	 * block size be at least 1024 bytes.  That's small enough to test the
74 	 * sub-page block case on systems with 4K pages, but not too small.
75 	 */
76 	if (log_blocksize < 10 || log_blocksize > PAGE_SHIFT ||
77 	    log_blocksize > inode->i_blkbits) {
78 		fsverity_warn(inode, "Unsupported log_blocksize: %u",
79 			      log_blocksize);
80 		err = -EINVAL;
81 		goto out_err;
82 	}
83 	params->log_blocksize = log_blocksize;
84 	params->block_size = 1 << log_blocksize;
85 	params->log_blocks_per_page = PAGE_SHIFT - log_blocksize;
86 	params->blocks_per_page = 1 << params->log_blocks_per_page;
87 
88 	if (WARN_ON_ONCE(!is_power_of_2(params->digest_size))) {
89 		err = -EINVAL;
90 		goto out_err;
91 	}
92 	if (params->block_size < 2 * params->digest_size) {
93 		fsverity_warn(inode,
94 			      "Merkle tree block size (%u) too small for hash algorithm \"%s\"",
95 			      params->block_size, hash_alg->name);
96 		err = -EINVAL;
97 		goto out_err;
98 	}
99 	params->log_digestsize = ilog2(params->digest_size);
100 	params->log_arity = log_blocksize - params->log_digestsize;
101 	params->hashes_per_block = 1 << params->log_arity;
102 
103 	/*
104 	 * Compute the number of levels in the Merkle tree and create a map from
105 	 * level to the starting block of that level.  Level 'num_levels - 1' is
106 	 * the root and is stored first.  Level 0 is the level directly "above"
107 	 * the data blocks and is stored last.
108 	 */
109 
110 	/* Compute number of levels and the number of blocks in each level */
111 	blocks = ((u64)data_size + params->block_size - 1) >> params->log_blocksize;
112 	while (blocks > 1) {
113 		if (params->num_levels >= FS_VERITY_MAX_LEVELS) {
114 			fsverity_err(inode, "Too many levels in Merkle tree");
115 			err = -EFBIG;
116 			goto out_err;
117 		}
118 		blocks = (blocks + params->hashes_per_block - 1) >>
119 			 params->log_arity;
120 		blocks_in_level[params->num_levels++] = blocks;
121 	}
122 
123 	/* Compute the starting block of each level */
124 	offset = 0;
125 	for (level = (int)params->num_levels - 1; level >= 0; level--) {
126 		params->level_start[level] = offset;
127 		offset += blocks_in_level[level];
128 	}
129 
130 	/*
131 	 * With block_size != PAGE_SIZE, an in-memory bitmap will need to be
132 	 * allocated to track the "verified" status of hash blocks.  Don't allow
133 	 * this bitmap to get too large.  For now, limit it to 1 MiB, which
134 	 * limits the file size to about 4.4 TB with SHA-256 and 4K blocks.
135 	 *
136 	 * Together with the fact that the data, and thus also the Merkle tree,
137 	 * cannot have more than ULONG_MAX pages, this implies that hash block
138 	 * indices can always fit in an 'unsigned long'.  But to be safe, we
139 	 * explicitly check for that too.  Note, this is only for hash block
140 	 * indices; data block indices might not fit in an 'unsigned long'.
141 	 */
142 	if ((params->block_size != PAGE_SIZE && offset > 1 << 23) ||
143 	    offset > ULONG_MAX) {
144 		fsverity_err(inode, "Too many blocks in Merkle tree");
145 		err = -EFBIG;
146 		goto out_err;
147 	}
148 
149 	params->tree_size = offset << log_blocksize;
150 	params->tree_pages = PAGE_ALIGN(params->tree_size) >> PAGE_SHIFT;
151 	return 0;
152 
153 out_err:
154 	kfree(params->hashstate);
155 	memset(params, 0, sizeof(*params));
156 	return err;
157 }
158 
159 /*
160  * Compute the file digest by hashing the fsverity_descriptor excluding the
161  * builtin signature and with the sig_size field set to 0.
162  */
compute_file_digest(const struct fsverity_hash_alg *hash_alg, struct fsverity_descriptor *desc, u8 *file_digest)163 static int compute_file_digest(const struct fsverity_hash_alg *hash_alg,
164 			       struct fsverity_descriptor *desc,
165 			       u8 *file_digest)
166 {
167 	__le32 sig_size = desc->sig_size;
168 	int err, cs_version;
169 
170 	cs_version = code_sign_before_measurement_hook(desc);
171 	desc->sig_size = 0;
172 	err = fsverity_hash_buffer(hash_alg, desc, sizeof(*desc), file_digest);
173 	desc->sig_size = sig_size;
174 	code_sign_after_measurement_hook(desc, cs_version);
175 
176 	return err;
177 }
178 
179 /*
180  * Create a new fsverity_info from the given fsverity_descriptor (with optional
181  * appended builtin signature), and check the signature if present.  The
182  * fsverity_descriptor must have already undergone basic validation.
183  */
fsverity_create_info(const struct inode *inode, struct fsverity_descriptor *desc)184 struct fsverity_info *fsverity_create_info(const struct inode *inode,
185 					   struct fsverity_descriptor *desc)
186 {
187 	struct fsverity_info *vi;
188 	int err;
189 
190 	err = code_sign_check_descriptor_hook(inode, desc);
191 	if (err < 0) {
192 		fsverity_err(inode, "Invalid code sign descriptor.");
193 		return ERR_PTR(err);
194 	} else if (err == 1)
195 		goto skip_part_check;
196 
197 skip_part_check:
198 	vi = kmem_cache_zalloc(fsverity_info_cachep, GFP_KERNEL);
199 	if (!vi)
200 		return ERR_PTR(-ENOMEM);
201 	vi->inode = inode;
202 
203 	err = fsverity_init_merkle_tree_params(&vi->tree_params, inode,
204 					       desc->hash_algorithm,
205 					       desc->log_blocksize,
206 					       desc->salt, desc->salt_size,
207 						   le64_to_cpu(desc->data_size));
208 	if (err) {
209 		fsverity_err(inode,
210 			     "Error %d initializing Merkle tree parameters",
211 			     err);
212 		goto fail;
213 	}
214 
215 	memcpy(vi->root_hash, desc->root_hash, vi->tree_params.digest_size);
216 
217 	err = compute_file_digest(vi->tree_params.hash_alg, desc,
218 				  vi->file_digest);
219 	if (err) {
220 		fsverity_err(inode, "Error %d computing file digest", err);
221 		goto fail;
222 	}
223 
224 #ifdef CONFIG_SECURITY_CODE_SIGN
225 	vi->verified_data_size = le64_to_cpu(desc->data_size);
226 #endif
227 	err = fsverity_verify_signature(vi, desc->signature,
228 					le32_to_cpu(desc->sig_size));
229 	if (err)
230 		goto fail;
231 
232 	if (vi->tree_params.block_size != PAGE_SIZE) {
233 		/*
234 		 * When the Merkle tree block size and page size differ, we use
235 		 * a bitmap to keep track of which hash blocks have been
236 		 * verified.  This bitmap must contain one bit per hash block,
237 		 * including alignment to a page boundary at the end.
238 		 *
239 		 * Eventually, to support extremely large files in an efficient
240 		 * way, it might be necessary to make pages of this bitmap
241 		 * reclaimable.  But for now, simply allocating the whole bitmap
242 		 * is a simple solution that works well on the files on which
243 		 * fsverity is realistically used.  E.g., with SHA-256 and 4K
244 		 * blocks, a 100MB file only needs a 24-byte bitmap, and the
245 		 * bitmap for any file under 17GB fits in a 4K page.
246 		 */
247 		unsigned long num_bits =
248 			vi->tree_params.tree_pages <<
249 			vi->tree_params.log_blocks_per_page;
250 
251 		vi->hash_block_verified = kvcalloc(BITS_TO_LONGS(num_bits),
252 						   sizeof(unsigned long),
253 						   GFP_KERNEL);
254 		if (!vi->hash_block_verified) {
255 			err = -ENOMEM;
256 			goto fail;
257 		}
258 		spin_lock_init(&vi->hash_page_init_lock);
259 	}
260 
261 	return vi;
262 
263 fail:
264 	fsverity_free_info(vi);
265 	return ERR_PTR(err);
266 }
267 
fsverity_set_info(struct inode *inode, struct fsverity_info *vi)268 void fsverity_set_info(struct inode *inode, struct fsverity_info *vi)
269 {
270 	/*
271 	 * Multiple tasks may race to set ->i_verity_info, so use
272 	 * cmpxchg_release().  This pairs with the smp_load_acquire() in
273 	 * fsverity_get_info().  I.e., here we publish ->i_verity_info with a
274 	 * RELEASE barrier so that other tasks can ACQUIRE it.
275 	 */
276 	if (cmpxchg_release(&inode->i_verity_info, NULL, vi) != NULL) {
277 		/* Lost the race, so free the fsverity_info we allocated. */
278 		fsverity_free_info(vi);
279 		/*
280 		 * Afterwards, the caller may access ->i_verity_info directly,
281 		 * so make sure to ACQUIRE the winning fsverity_info.
282 		 */
283 		(void)fsverity_get_info(inode);
284 	}
285 }
286 
fsverity_free_info(struct fsverity_info *vi)287 void fsverity_free_info(struct fsverity_info *vi)
288 {
289 	if (!vi)
290 		return;
291 	kfree(vi->tree_params.hashstate);
292 	kvfree(vi->hash_block_verified);
293 	kmem_cache_free(fsverity_info_cachep, vi);
294 }
295 
validate_fsverity_descriptor(struct inode *inode, const struct fsverity_descriptor *desc, size_t desc_size)296 static bool validate_fsverity_descriptor(struct inode *inode,
297 					 const struct fsverity_descriptor *desc,
298 					 size_t desc_size)
299 {
300 	if (desc_size < sizeof(*desc)) {
301 		fsverity_err(inode, "Unrecognized descriptor size: %zu bytes",
302 			     desc_size);
303 		return false;
304 	}
305 
306 	if (desc->version != 1) {
307 		fsverity_err(inode, "Unrecognized descriptor version: %u",
308 			     desc->version);
309 		return false;
310 	}
311 
312 	if (memchr_inv(desc->__reserved, 0, sizeof(desc->__reserved))) {
313 		fsverity_err(inode, "Reserved bits set in descriptor");
314 		return false;
315 	}
316 
317 	if (desc->salt_size > sizeof(desc->salt)) {
318 		fsverity_err(inode, "Invalid salt_size: %u", desc->salt_size);
319 		return false;
320 	}
321 
322 	if (le64_to_cpu(desc->data_size) != inode->i_size) {
323 		fsverity_err(inode,
324 			     "Wrong data_size: %llu (desc) != %lld (inode)",
325 			     le64_to_cpu(desc->data_size), inode->i_size);
326 		return false;
327 	}
328 
329 	if (le32_to_cpu(desc->sig_size) > desc_size - sizeof(*desc)) {
330 		fsverity_err(inode, "Signature overflows verity descriptor");
331 		return false;
332 	}
333 
334 	return true;
335 }
336 
337 /*
338  * Read the inode's fsverity_descriptor (with optional appended builtin
339  * signature) from the filesystem, and do basic validation of it.
340  */
fsverity_get_descriptor(struct inode *inode, struct fsverity_descriptor **desc_ret)341 int fsverity_get_descriptor(struct inode *inode,
342 			    struct fsverity_descriptor **desc_ret)
343 {
344 	int res;
345 	struct fsverity_descriptor *desc;
346 
347 	res = inode->i_sb->s_vop->get_verity_descriptor(inode, NULL, 0);
348 	if (res < 0) {
349 		fsverity_err(inode,
350 			     "Error %d getting verity descriptor size", res);
351 		return res;
352 	}
353 	if (res > FS_VERITY_MAX_DESCRIPTOR_SIZE) {
354 		fsverity_err(inode, "Verity descriptor is too large (%d bytes)",
355 			     res);
356 		return -EMSGSIZE;
357 	}
358 	desc = kmalloc(res, GFP_KERNEL);
359 	if (!desc)
360 		return -ENOMEM;
361 	res = inode->i_sb->s_vop->get_verity_descriptor(inode, desc, res);
362 	if (res < 0) {
363 		fsverity_err(inode, "Error %d reading verity descriptor", res);
364 		kfree(desc);
365 		return res;
366 	}
367 
368 	if (!validate_fsverity_descriptor(inode, desc, res)) {
369 		kfree(desc);
370 		return -EINVAL;
371 	}
372 
373 	*desc_ret = desc;
374 	return 0;
375 }
376 
377 /* Ensure the inode has an ->i_verity_info */
ensure_verity_info(struct inode *inode)378 static int ensure_verity_info(struct inode *inode)
379 {
380 	struct fsverity_info *vi = fsverity_get_info(inode);
381 	struct fsverity_descriptor *desc;
382 	int err;
383 
384 	if (vi)
385 		return 0;
386 
387 	err = fsverity_get_descriptor(inode, &desc);
388 	if (err)
389 		return err;
390 
391 	vi = fsverity_create_info(inode, desc);
392 	if (IS_ERR(vi)) {
393 		err = PTR_ERR(vi);
394 		goto out_free_desc;
395 	}
396 
397 	fsverity_set_info(inode, vi);
398 	err = 0;
399 out_free_desc:
400 	kfree(desc);
401 	return err;
402 }
403 
__fsverity_file_open(struct inode *inode, struct file *filp)404 int __fsverity_file_open(struct inode *inode, struct file *filp)
405 {
406 	if (filp->f_mode & FMODE_WRITE)
407 		return -EPERM;
408 	return ensure_verity_info(inode);
409 }
410 EXPORT_SYMBOL_GPL(__fsverity_file_open);
411 
__fsverity_prepare_setattr(struct dentry *dentry, struct iattr *attr)412 int __fsverity_prepare_setattr(struct dentry *dentry, struct iattr *attr)
413 {
414 	if (attr->ia_valid & ATTR_SIZE)
415 		return -EPERM;
416 	return 0;
417 }
418 EXPORT_SYMBOL_GPL(__fsverity_prepare_setattr);
419 
__fsverity_cleanup_inode(struct inode *inode)420 void __fsverity_cleanup_inode(struct inode *inode)
421 {
422 	fsverity_free_info(inode->i_verity_info);
423 	inode->i_verity_info = NULL;
424 }
425 EXPORT_SYMBOL_GPL(__fsverity_cleanup_inode);
426 
fsverity_init_info_cache(void)427 void __init fsverity_init_info_cache(void)
428 {
429 	fsverity_info_cachep = KMEM_CACHE_USERCOPY(
430 					fsverity_info,
431 					SLAB_RECLAIM_ACCOUNT | SLAB_PANIC,
432 					file_digest);
433 }
434