xref: /kernel/linux/linux-5.10/fs/verity/open.c (revision 8c2ecf20)
1// SPDX-License-Identifier: GPL-2.0
2/*
3 * fs/verity/open.c: opening fs-verity files
4 *
5 * Copyright 2019 Google LLC
6 */
7
8#include "fsverity_private.h"
9
10#include <linux/slab.h>
11
12static struct kmem_cache *fsverity_info_cachep;
13
14/**
15 * fsverity_init_merkle_tree_params() - initialize Merkle tree parameters
16 * @params: the parameters struct to initialize
17 * @inode: the inode for which the Merkle tree is being built
18 * @hash_algorithm: number of hash algorithm to use
19 * @log_blocksize: log base 2 of block size to use
20 * @salt: pointer to salt (optional)
21 * @salt_size: size of salt, possibly 0
22 * @data_size: verified data size
23 *
24 * Validate the hash algorithm and block size, then compute the tree topology
25 * (num levels, num blocks in each level, etc.) and initialize @params.
26 *
27 * Return: 0 on success, -errno on failure
28 */
29int fsverity_init_merkle_tree_params(struct merkle_tree_params *params,
30				     const struct inode *inode,
31				     unsigned int hash_algorithm,
32				     unsigned int log_blocksize,
33				     const u8 *salt, size_t salt_size,
34				     u64 data_size)
35{
36	struct fsverity_hash_alg *hash_alg;
37	int err;
38	u64 blocks;
39	u64 offset;
40	int level;
41
42	memset(params, 0, sizeof(*params));
43
44	hash_alg = fsverity_get_hash_alg(inode, hash_algorithm);
45	if (IS_ERR(hash_alg))
46		return PTR_ERR(hash_alg);
47	params->hash_alg = hash_alg;
48	params->digest_size = hash_alg->digest_size;
49
50	params->hashstate = fsverity_prepare_hash_state(hash_alg, salt,
51							salt_size);
52	if (IS_ERR(params->hashstate)) {
53		err = PTR_ERR(params->hashstate);
54		params->hashstate = NULL;
55		fsverity_err(inode, "Error %d preparing hash state", err);
56		goto out_err;
57	}
58
59	if (log_blocksize != PAGE_SHIFT) {
60		fsverity_warn(inode, "Unsupported log_blocksize: %u",
61			      log_blocksize);
62		err = -EINVAL;
63		goto out_err;
64	}
65	params->log_blocksize = log_blocksize;
66	params->block_size = 1 << log_blocksize;
67
68	if (WARN_ON(!is_power_of_2(params->digest_size))) {
69		err = -EINVAL;
70		goto out_err;
71	}
72	if (params->block_size < 2 * params->digest_size) {
73		fsverity_warn(inode,
74			      "Merkle tree block size (%u) too small for hash algorithm \"%s\"",
75			      params->block_size, hash_alg->name);
76		err = -EINVAL;
77		goto out_err;
78	}
79	params->log_arity = params->log_blocksize - ilog2(params->digest_size);
80	params->hashes_per_block = 1 << params->log_arity;
81
82	pr_debug("Merkle tree uses %s with %u-byte blocks (%u hashes/block), salt=%*phN\n",
83		 hash_alg->name, params->block_size, params->hashes_per_block,
84		 (int)salt_size, salt);
85
86	/*
87	 * Compute the number of levels in the Merkle tree and create a map from
88	 * level to the starting block of that level.  Level 'num_levels - 1' is
89	 * the root and is stored first.  Level 0 is the level directly "above"
90	 * the data blocks and is stored last.
91	 */
92
93	/* Compute number of levels and the number of blocks in each level */
94	blocks = ((u64)data_size + params->block_size - 1) >> params->log_blocksize;
95	pr_debug("Data is %lld bytes (%llu blocks)\n", data_size, blocks);
96	while (blocks > 1) {
97		if (params->num_levels >= FS_VERITY_MAX_LEVELS) {
98			fsverity_err(inode, "Too many levels in Merkle tree");
99			err = -EINVAL;
100			goto out_err;
101		}
102		blocks = (blocks + params->hashes_per_block - 1) >>
103			 params->log_arity;
104		/* temporarily using level_start[] to store blocks in level */
105		params->level_start[params->num_levels++] = blocks;
106	}
107	params->level0_blocks = params->level_start[0];
108
109	/* Compute the starting block of each level */
110	offset = 0;
111	for (level = (int)params->num_levels - 1; level >= 0; level--) {
112		blocks = params->level_start[level];
113		params->level_start[level] = offset;
114		pr_debug("Level %d is %llu blocks starting at index %llu\n",
115			 level, blocks, offset);
116		offset += blocks;
117	}
118
119	params->tree_size = offset << log_blocksize;
120	return 0;
121
122out_err:
123	kfree(params->hashstate);
124	memset(params, 0, sizeof(*params));
125	return err;
126}
127
128/*
129 * Compute the file measurement by hashing the fsverity_descriptor excluding the
130 * signature and with the sig_size field set to 0.
131 */
132static int compute_file_measurement(struct fsverity_hash_alg *hash_alg,
133				    struct fsverity_descriptor *desc,
134				    u8 *measurement)
135{
136	__le32 sig_size = desc->sig_size;
137	int err, cs_version;
138
139	cs_version = code_sign_before_measurement_hook(desc);
140	desc->sig_size = 0;
141	err = fsverity_hash_buffer(hash_alg, desc, sizeof(*desc), measurement);
142	desc->sig_size = sig_size;
143	code_sign_after_measurement_hook(desc, cs_version);
144
145	return err;
146}
147
148/*
149 * Validate the given fsverity_descriptor and create a new fsverity_info from
150 * it.  The signature (if present) is also checked.
151 */
152struct fsverity_info *fsverity_create_info(const struct inode *inode,
153					   void *_desc, size_t desc_size)
154{
155	struct fsverity_descriptor *desc = _desc;
156	struct fsverity_info *vi;
157	int err;
158
159	if (desc_size < sizeof(*desc)) {
160		fsverity_err(inode, "Unrecognized descriptor size: %zu bytes",
161			     desc_size);
162		return ERR_PTR(-EINVAL);
163	}
164
165	err = code_sign_check_descriptor_hook(inode, _desc);
166	if (err < 0) {
167		fsverity_err(inode, "Invalid code sign descriptor.");
168		return ERR_PTR(err);
169	} else if (err == 1)
170		goto skip_part_check;
171
172	if (desc->version != 1) {
173		fsverity_err(inode, "Unrecognized descriptor version: %u",
174			     desc->version);
175		return ERR_PTR(-EINVAL);
176	}
177
178	if (memchr_inv(desc->__reserved, 0, sizeof(desc->__reserved))) {
179		fsverity_err(inode, "Reserved bits set in descriptor");
180		return ERR_PTR(-EINVAL);
181	}
182
183	if (desc->salt_size > sizeof(desc->salt)) {
184		fsverity_err(inode, "Invalid salt_size: %u", desc->salt_size);
185		return ERR_PTR(-EINVAL);
186	}
187
188	if (le64_to_cpu(desc->data_size) != inode->i_size) {
189		fsverity_err(inode,
190			     "Wrong data_size: %llu (desc) != %lld (inode)",
191			     le64_to_cpu(desc->data_size), inode->i_size);
192		return ERR_PTR(-EINVAL);
193	}
194
195skip_part_check:
196	vi = kmem_cache_zalloc(fsverity_info_cachep, GFP_KERNEL);
197	if (!vi)
198		return ERR_PTR(-ENOMEM);
199	vi->inode = inode;
200
201#ifdef CONFIG_SECURITY_CODE_SIGN
202	vi->verified_data_size = le64_to_cpu(desc->data_size);
203#endif
204
205	err = fsverity_init_merkle_tree_params(&vi->tree_params, inode,
206					       desc->hash_algorithm,
207					       desc->log_blocksize,
208					       desc->salt, desc->salt_size,
209					       le64_to_cpu(desc->data_size));
210	if (err) {
211		fsverity_err(inode,
212			     "Error %d initializing Merkle tree parameters",
213			     err);
214		goto out;
215	}
216
217	memcpy(vi->root_hash, desc->root_hash, vi->tree_params.digest_size);
218
219	err = compute_file_measurement(vi->tree_params.hash_alg, desc,
220				       vi->measurement);
221	if (err) {
222		fsverity_err(inode, "Error %d computing file measurement", err);
223		goto out;
224	}
225	pr_debug("Computed file measurement: %s:%*phN\n",
226		 vi->tree_params.hash_alg->name,
227		 vi->tree_params.digest_size, vi->measurement);
228
229	err = fsverity_verify_signature(vi, desc, desc_size);
230out:
231	if (err) {
232		fsverity_free_info(vi);
233		vi = ERR_PTR(err);
234	}
235	return vi;
236}
237
238void fsverity_set_info(struct inode *inode, struct fsverity_info *vi)
239{
240	/*
241	 * Multiple tasks may race to set ->i_verity_info, so use
242	 * cmpxchg_release().  This pairs with the smp_load_acquire() in
243	 * fsverity_get_info().  I.e., here we publish ->i_verity_info with a
244	 * RELEASE barrier so that other tasks can ACQUIRE it.
245	 */
246	if (cmpxchg_release(&inode->i_verity_info, NULL, vi) != NULL) {
247		/* Lost the race, so free the fsverity_info we allocated. */
248		fsverity_free_info(vi);
249		/*
250		 * Afterwards, the caller may access ->i_verity_info directly,
251		 * so make sure to ACQUIRE the winning fsverity_info.
252		 */
253		(void)fsverity_get_info(inode);
254	}
255}
256
257void fsverity_free_info(struct fsverity_info *vi)
258{
259	if (!vi)
260		return;
261	kfree(vi->tree_params.hashstate);
262	kmem_cache_free(fsverity_info_cachep, vi);
263}
264
265/* Ensure the inode has an ->i_verity_info */
266static int ensure_verity_info(struct inode *inode)
267{
268	struct fsverity_info *vi = fsverity_get_info(inode);
269	struct fsverity_descriptor *desc;
270	int res;
271
272	if (vi)
273		return 0;
274
275	res = inode->i_sb->s_vop->get_verity_descriptor(inode, NULL, 0);
276	if (res < 0) {
277		fsverity_err(inode,
278			     "Error %d getting verity descriptor size", res);
279		return res;
280	}
281	if (res > FS_VERITY_MAX_DESCRIPTOR_SIZE) {
282		fsverity_err(inode, "Verity descriptor is too large (%d bytes)",
283			     res);
284		return -EMSGSIZE;
285	}
286	desc = kmalloc(res, GFP_KERNEL);
287	if (!desc)
288		return -ENOMEM;
289	res = inode->i_sb->s_vop->get_verity_descriptor(inode, desc, res);
290	if (res < 0) {
291		fsverity_err(inode, "Error %d reading verity descriptor", res);
292		goto out_free_desc;
293	}
294
295	vi = fsverity_create_info(inode, desc, res);
296	if (IS_ERR(vi)) {
297		res = PTR_ERR(vi);
298		goto out_free_desc;
299	}
300
301	fsverity_set_info(inode, vi);
302	res = 0;
303out_free_desc:
304	kfree(desc);
305	return res;
306}
307
308/**
309 * fsverity_file_open() - prepare to open a verity file
310 * @inode: the inode being opened
311 * @filp: the struct file being set up
312 *
313 * When opening a verity file, deny the open if it is for writing.  Otherwise,
314 * set up the inode's ->i_verity_info if not already done.
315 *
316 * When combined with fscrypt, this must be called after fscrypt_file_open().
317 * Otherwise, we won't have the key set up to decrypt the verity metadata.
318 *
319 * Return: 0 on success, -errno on failure
320 */
321int fsverity_file_open(struct inode *inode, struct file *filp)
322{
323	if (!IS_VERITY(inode))
324		return 0;
325
326	if (filp->f_mode & FMODE_WRITE) {
327		pr_debug("Denying opening verity file (ino %lu) for write\n",
328			 inode->i_ino);
329		return -EPERM;
330	}
331
332	return ensure_verity_info(inode);
333}
334EXPORT_SYMBOL_GPL(fsverity_file_open);
335
336/**
337 * fsverity_prepare_setattr() - prepare to change a verity inode's attributes
338 * @dentry: dentry through which the inode is being changed
339 * @attr: attributes to change
340 *
341 * Verity files are immutable, so deny truncates.  This isn't covered by the
342 * open-time check because sys_truncate() takes a path, not a file descriptor.
343 *
344 * Return: 0 on success, -errno on failure
345 */
346int fsverity_prepare_setattr(struct dentry *dentry, struct iattr *attr)
347{
348	if (IS_VERITY(d_inode(dentry)) && (attr->ia_valid & ATTR_SIZE)) {
349		pr_debug("Denying truncate of verity file (ino %lu)\n",
350			 d_inode(dentry)->i_ino);
351		return -EPERM;
352	}
353	return 0;
354}
355EXPORT_SYMBOL_GPL(fsverity_prepare_setattr);
356
357/**
358 * fsverity_cleanup_inode() - free the inode's verity info, if present
359 * @inode: an inode being evicted
360 *
361 * Filesystems must call this on inode eviction to free ->i_verity_info.
362 */
363void fsverity_cleanup_inode(struct inode *inode)
364{
365	fsverity_free_info(inode->i_verity_info);
366	inode->i_verity_info = NULL;
367}
368EXPORT_SYMBOL_GPL(fsverity_cleanup_inode);
369
370int __init fsverity_init_info_cache(void)
371{
372	fsverity_info_cachep = KMEM_CACHE_USERCOPY(fsverity_info,
373						   SLAB_RECLAIM_ACCOUNT,
374						   measurement);
375	if (!fsverity_info_cachep)
376		return -ENOMEM;
377	return 0;
378}
379
380void __init fsverity_exit_info_cache(void)
381{
382	kmem_cache_destroy(fsverity_info_cachep);
383	fsverity_info_cachep = NULL;
384}
385