xref: /kernel/linux/linux-6.6/fs/verity/enable.c (revision 62306a36)
1// SPDX-License-Identifier: GPL-2.0
2/*
3 * Ioctl to enable verity on a file
4 *
5 * Copyright 2019 Google LLC
6 */
7
8#include "fsverity_private.h"
9
10#include <crypto/hash.h>
11#include <linux/mount.h>
12#include <linux/sched/signal.h>
13#include <linux/uaccess.h>
14
15struct block_buffer {
16	u32 filled;
17	bool is_root_hash;
18	u8 *data;
19};
20
21/* Hash a block, writing the result to the next level's pending block buffer. */
22static int hash_one_block(struct inode *inode,
23			  const struct merkle_tree_params *params,
24			  struct block_buffer *cur)
25{
26	struct block_buffer *next = cur + 1;
27	int err;
28
29	/*
30	 * Safety check to prevent a buffer overflow in case of a filesystem bug
31	 * that allows the file size to change despite deny_write_access(), or a
32	 * bug in the Merkle tree logic itself
33	 */
34	if (WARN_ON_ONCE(next->is_root_hash && next->filled != 0))
35		return -EINVAL;
36
37	/* Zero-pad the block if it's shorter than the block size. */
38	memset(&cur->data[cur->filled], 0, params->block_size - cur->filled);
39
40	err = fsverity_hash_block(params, inode, cur->data,
41				  &next->data[next->filled]);
42	if (err)
43		return err;
44	next->filled += params->digest_size;
45	cur->filled = 0;
46	return 0;
47}
48
49static int write_merkle_tree_block(struct inode *inode, const u8 *buf,
50				   unsigned long index,
51				   const struct merkle_tree_params *params)
52{
53	u64 pos = (u64)index << params->log_blocksize;
54	int err;
55
56	err = inode->i_sb->s_vop->write_merkle_tree_block(inode, buf, pos,
57							  params->block_size);
58	if (err)
59		fsverity_err(inode, "Error %d writing Merkle tree block %lu",
60			     err, index);
61	return err;
62}
63
64static int check_file_and_enable_verity(struct file *filp,
65	const struct fsverity_enable_arg *arg);
66
67#ifdef CONFIG_SECURITY_CODE_SIGN
68
69static int code_sign_init_descriptor(struct inode *inode,
70	const struct fsverity_enable_arg *_arg, struct fsverity_descriptor *_desc);
71
72static int code_sign_copy_merkle_tree(struct file *filp, const void *_desc,
73	const struct merkle_tree_params *params);
74
75#else /* !CONFIG_SECURITY_CODE_SIGN */
76
77static inline int code_sign_init_descriptor(struct inode *inode,
78	const struct fsverity_enable_arg *_arg, struct fsverity_descriptor *_desc)
79{
80	return 0;
81}
82
83static int code_sign_copy_merkle_tree(struct file *filp,
84	const void *_desc,
85	const struct merkle_tree_params *params)
86{
87	return 0;
88}
89#endif /* !CONFIG_SECURITY_CODE_SIGN */
90
91/*
92 * Build the Merkle tree for the given file using the given parameters, and
93 * return the root hash in @root_hash.
94 *
95 * The tree is written to a filesystem-specific location as determined by the
96 * ->write_merkle_tree_block() method.  However, the blocks that comprise the
97 * tree are the same for all filesystems.
98 */
99static int build_merkle_tree(struct file *filp,
100			     const struct merkle_tree_params *params,
101			     u8 *root_hash,
102			     size_t data_size)
103{
104	struct inode *inode = file_inode(filp);
105	const int num_levels = params->num_levels;
106	struct block_buffer _buffers[1 + FS_VERITY_MAX_LEVELS + 1] = {};
107	struct block_buffer *buffers = &_buffers[1];
108	unsigned long level_offset[FS_VERITY_MAX_LEVELS];
109	int level;
110	u64 offset;
111	int err;
112
113	if (data_size == 0) {
114		/* Empty file is a special case; root hash is all 0's */
115		memset(root_hash, 0, params->digest_size);
116		return 0;
117	}
118
119	/*
120	 * Allocate the block buffers.  Buffer "-1" is for data blocks.
121	 * Buffers 0 <= level < num_levels are for the actual tree levels.
122	 * Buffer 'num_levels' is for the root hash.
123	 */
124	for (level = -1; level < num_levels; level++) {
125		buffers[level].data = kzalloc(params->block_size, GFP_KERNEL);
126		if (!buffers[level].data) {
127			err = -ENOMEM;
128			goto out;
129		}
130	}
131	buffers[num_levels].data = root_hash;
132	buffers[num_levels].is_root_hash = true;
133
134	BUILD_BUG_ON(sizeof(level_offset) != sizeof(params->level_start));
135	memcpy(level_offset, params->level_start, sizeof(level_offset));
136
137	/* Hash each data block, also hashing the tree blocks as they fill up */
138	for (offset = 0; offset < data_size; offset += params->block_size) {
139		ssize_t bytes_read;
140		loff_t pos = offset;
141
142		buffers[-1].filled = min_t(u64, params->block_size,
143					   data_size - offset);
144		bytes_read = __kernel_read(filp, buffers[-1].data,
145					   buffers[-1].filled, &pos);
146		if (bytes_read < 0) {
147			err = bytes_read;
148			fsverity_err(inode, "Error %d reading file data", err);
149			goto out;
150		}
151		if (bytes_read != buffers[-1].filled) {
152			err = -EINVAL;
153			fsverity_err(inode, "Short read of file data");
154			goto out;
155		}
156		err = hash_one_block(inode, params, &buffers[-1]);
157		if (err)
158			goto out;
159		for (level = 0; level < num_levels; level++) {
160			if (buffers[level].filled + params->digest_size <=
161			    params->block_size) {
162				/* Next block at @level isn't full yet */
163				break;
164			}
165			/* Next block at @level is full */
166
167			err = hash_one_block(inode, params, &buffers[level]);
168			if (err)
169				goto out;
170			err = write_merkle_tree_block(inode,
171						      buffers[level].data,
172						      level_offset[level],
173						      params);
174			if (err)
175				goto out;
176			level_offset[level]++;
177		}
178		if (fatal_signal_pending(current)) {
179			err = -EINTR;
180			goto out;
181		}
182		cond_resched();
183	}
184	/* Finish all nonempty pending tree blocks. */
185	for (level = 0; level < num_levels; level++) {
186		if (buffers[level].filled != 0) {
187			err = hash_one_block(inode, params, &buffers[level]);
188			if (err)
189				goto out;
190			err = write_merkle_tree_block(inode,
191						      buffers[level].data,
192						      level_offset[level],
193						      params);
194			if (err)
195				goto out;
196		}
197	}
198	/* The root hash was filled by the last call to hash_one_block(). */
199	if (WARN_ON_ONCE(buffers[num_levels].filled != params->digest_size)) {
200		err = -EINVAL;
201		goto out;
202	}
203	err = 0;
204out:
205	for (level = -1; level < num_levels; level++)
206		kfree(buffers[level].data);
207	return err;
208}
209
210static int enable_verity(struct file *filp,
211			 const struct fsverity_enable_arg *arg)
212{
213	struct inode *inode = file_inode(filp);
214	struct fsverity_descriptor *desc;
215	size_t desc_size = struct_size(desc, signature, arg->sig_size);
216	int err;
217
218	/* Start initializing the fsverity_descriptor */
219	desc = kzalloc(desc_size, GFP_KERNEL);
220	if (!desc)
221		return -ENOMEM;
222	desc->version = 1;
223	desc->hash_algorithm = arg->hash_algorithm;
224	desc->log_blocksize = ilog2(arg->block_size);
225
226	/* Get the salt if the user provided one */
227	if (arg->salt_size &&
228	    copy_from_user(desc->salt, u64_to_user_ptr(arg->salt_ptr),
229			   arg->salt_size)) {
230		err = -EFAULT;
231		goto out;
232	}
233	desc->salt_size = arg->salt_size;
234
235	/* Get the builtin signature if the user provided one */
236	if (arg->sig_size &&
237	    copy_from_user(desc->signature, u64_to_user_ptr(arg->sig_ptr),
238			   arg->sig_size)) {
239		err = -EFAULT;
240		goto out;
241	}
242	desc->sig_size = cpu_to_le32(arg->sig_size);
243
244	desc->data_size = cpu_to_le64(inode->i_size);
245
246	err = code_sign_init_descriptor(inode, arg, desc);
247	if (err) {
248		fsverity_err(inode, "Init code sign descriptor err: %u", err);
249		goto out;
250	}
251
252	err = fsverity_enable_with_descriptor(filp, (void *)desc, desc_size);
253out:
254	kfree(desc);
255	return err;
256}
257
258int fsverity_enable_with_descriptor(struct file *filp,
259	void *_desc, size_t desc_size)
260{
261	struct inode *inode = file_inode(filp);
262	const struct fsverity_operations *vops = inode->i_sb->s_vop;
263	struct merkle_tree_params params = { };
264	struct fsverity_descriptor *desc = (struct fsverity_descriptor *)_desc;
265	struct fsverity_info *vi;
266	int err;
267
268	if (vops == NULL) {
269		fsverity_err(inode, "current filesystem doesn't support fs-verity.");
270		return -ENOTTY;
271	}
272
273	/* Prepare the Merkle tree parameters */
274	err = fsverity_init_merkle_tree_params(&params, inode,
275					       desc->hash_algorithm,
276					       desc->log_blocksize,
277					       desc->salt, desc->salt_size,
278					       desc->data_size);
279	if (err)
280		goto out;
281
282	/*
283	 * Start enabling verity on this file, serialized by the inode lock.
284	 * Fail if verity is already enabled or is already being enabled.
285	 */
286	inode_lock(inode);
287	if (IS_VERITY(inode))
288		err = -EEXIST;
289	else
290		err = vops->begin_enable_verity(filp);
291	inode_unlock(inode);
292	if (err)
293		goto out;
294
295	err = code_sign_copy_merkle_tree(filp, _desc, &params);
296	if (err < 0) {
297		fsverity_err(inode, "Error %d copying Merkle tree", err);
298		goto rollback;
299	} else if (err == 1) /* already copy merkle tree */
300		goto skip_build;
301
302	/*
303	 * Build the Merkle tree.  Don't hold the inode lock during this, since
304	 * on huge files this may take a very long time and we don't want to
305	 * force unrelated syscalls like chown() to block forever.  We don't
306	 * need the inode lock here because deny_write_access() already prevents
307	 * the file from being written to or truncated, and we still serialize
308	 * ->begin_enable_verity() and ->end_enable_verity() using the inode
309	 * lock and only allow one process to be here at a time on a given file.
310	 */
311	BUILD_BUG_ON(sizeof(desc->root_hash) < FS_VERITY_MAX_DIGEST_SIZE);
312	err = build_merkle_tree(filp, &params, desc->root_hash, desc->data_size);
313	if (err) {
314		fsverity_err(inode, "Error %d building Merkle tree", err);
315		goto rollback;
316	}
317
318skip_build:
319	pr_debug("Done building Merkle tree.  Root hash is %s:%*phN\n",
320		 params.hash_alg->name, params.digest_size, desc->root_hash);
321
322	/*
323	 * Create the fsverity_info.  Don't bother trying to save work by
324	 * reusing the merkle_tree_params from above.  Instead, just create the
325	 * fsverity_info from the fsverity_descriptor as if it were just loaded
326	 * from disk.  This is simpler, and it serves as an extra check that the
327	 * metadata we're writing is valid before actually enabling verity.
328	 */
329	vi = fsverity_create_info(inode, desc);
330	if (IS_ERR(vi)) {
331		err = PTR_ERR(vi);
332		goto rollback;
333	}
334
335	/*
336	 * Tell the filesystem to finish enabling verity on the file.
337	 * Serialized with ->begin_enable_verity() by the inode lock.
338	 */
339	inode_lock(inode);
340	err = vops->end_enable_verity(filp, desc, desc_size, params.tree_size);
341	inode_unlock(inode);
342	if (err) {
343		fsverity_err(inode, "%ps() failed with err %d",
344			     vops->end_enable_verity, err);
345		fsverity_free_info(vi);
346	} else if (WARN_ON_ONCE(!IS_VERITY(inode))) {
347		err = -EINVAL;
348		fsverity_free_info(vi);
349	} else {
350		/* Successfully enabled verity */
351
352		/*
353		 * Readers can start using ->i_verity_info immediately, so it
354		 * can't be rolled back once set.  So don't set it until just
355		 * after the filesystem has successfully enabled verity.
356		 */
357		fsverity_set_info(inode, vi);
358	}
359out:
360	kfree(params.hashstate);
361	return err;
362
363rollback:
364	inode_lock(inode);
365	(void)vops->end_enable_verity(filp, NULL, 0, params.tree_size);
366	inode_unlock(inode);
367	goto out;
368}
369EXPORT_SYMBOL_GPL(fsverity_enable_with_descriptor);
370
371/**
372 * fsverity_ioctl_enable() - enable verity on a file
373 * @filp: file to enable verity on
374 * @uarg: user pointer to fsverity_enable_arg
375 *
376 * Enable fs-verity on a file.  See the "FS_IOC_ENABLE_VERITY" section of
377 * Documentation/filesystems/fsverity.rst for the documentation.
378 *
379 * Return: 0 on success, -errno on failure
380 */
381int fsverity_ioctl_enable(struct file *filp, const void __user *uarg)
382{
383	struct inode *inode = file_inode(filp);
384	struct fsverity_enable_arg arg;
385
386	if (copy_from_user(&arg, uarg, sizeof(arg)))
387		return -EFAULT;
388
389	if (arg.version != 1)
390		return -EINVAL;
391
392	if (arg.__reserved1 ||
393	    memchr_inv(arg.__reserved2, 0, sizeof(arg.__reserved2)))
394		return -EINVAL;
395
396	if (!is_power_of_2(arg.block_size))
397		return -EINVAL;
398
399	if (arg.salt_size > sizeof_field(struct fsverity_descriptor, salt))
400		return -EMSGSIZE;
401
402	if (arg.sig_size > FS_VERITY_MAX_SIGNATURE_SIZE)
403		return -EMSGSIZE;
404
405	return check_file_and_enable_verity(filp, &arg);
406}
407EXPORT_SYMBOL_GPL(fsverity_ioctl_enable);
408
409static int check_file_and_enable_verity(struct file *filp,
410	const struct fsverity_enable_arg *arg)
411{
412	struct inode *inode = file_inode(filp);
413	int err;
414	/*
415	 * Require a regular file with write access.  But the actual fd must
416	 * still be readonly so that we can lock out all writers.  This is
417	 * needed to guarantee that no writable fds exist to the file once it
418	 * has verity enabled, and to stabilize the data being hashed.
419	 */
420
421	err = file_permission(filp, MAY_WRITE);
422	if (err)
423		return err;
424	/*
425	 * __kernel_read() is used while building the Merkle tree.  So, we can't
426	 * allow file descriptors that were opened for ioctl access only, using
427	 * the special nonstandard access mode 3.  O_RDONLY only, please!
428	 */
429	if (!(filp->f_mode & FMODE_READ))
430		return -EBADF;
431
432	if (IS_APPEND(inode))
433		return -EPERM;
434
435	if (S_ISDIR(inode->i_mode))
436		return -EISDIR;
437
438	if (!S_ISREG(inode->i_mode))
439		return -EINVAL;
440
441	err = mnt_want_write_file(filp);
442	if (err) /* -EROFS */
443		return err;
444
445	err = deny_write_access(filp);
446	if (err) /* -ETXTBSY */
447		goto out_drop_write;
448
449	err = enable_verity(filp, arg);
450
451	/*
452	 * We no longer drop the inode's pagecache after enabling verity.  This
453	 * used to be done to try to avoid a race condition where pages could be
454	 * evicted after being used in the Merkle tree construction, then
455	 * re-instantiated by a concurrent read.  Such pages are unverified, and
456	 * the backing storage could have filled them with different content, so
457	 * they shouldn't be used to fulfill reads once verity is enabled.
458	 *
459	 * But, dropping the pagecache has a big performance impact, and it
460	 * doesn't fully solve the race condition anyway.  So for those reasons,
461	 * and also because this race condition isn't very important relatively
462	 * speaking (especially for small-ish files, where the chance of a page
463	 * being used, evicted, *and* re-instantiated all while enabling verity
464	 * is quite small), we no longer drop the inode's pagecache.
465	 */
466
467	/*
468	 * allow_write_access() is needed to pair with deny_write_access().
469	 * Regardless, the filesystem won't allow writing to verity files.
470	 */
471	allow_write_access(filp);
472out_drop_write:
473	mnt_drop_write_file(filp);
474	return err;
475}
476
477#ifdef CONFIG_SECURITY_CODE_SIGN
478static int code_sign_copy_merkle_tree(struct file *filp,
479				 const void *_desc,
480				 const struct merkle_tree_params *params)
481{
482	struct inode *inode = file_inode(filp);
483	struct block_buffer buffer = {};
484	int err = -ENOMEM;
485	u64 offset;
486	u64 tree_offset;
487
488	if (!is_inside_tree_compact(_desc))
489		return 0;
490
491	tree_offset = get_tree_offset_compact(_desc);
492
493	if (inode->i_size < tree_offset + params->tree_size) {
494		fsverity_err(inode, "File is too small to contain Merkle tree.");
495		return -EFAULT;
496	}
497
498	buffer.data = kzalloc(params->block_size, GFP_KERNEL);
499	if (!buffer.data)
500		goto out;
501
502	for (offset = tree_offset; offset < tree_offset + params->tree_size; offset += params->block_size) {
503		ssize_t bytes_read;
504		loff_t pos = offset;
505
506		bytes_read = __kernel_read(filp, buffer.data,
507						params->block_size, &pos);
508		if (bytes_read < 0) {
509			err = bytes_read;
510			fsverity_err(inode, "Error %d reading Merkle tree block %llu",
511						err, offset / params->block_size);
512			goto out;
513		}
514		if (bytes_read != params->block_size) {
515			err = -EINVAL;
516			fsverity_err(inode, "Short read of Merkle tree block %llu",
517						offset / params->block_size);
518			goto out;
519		}
520
521		err = write_merkle_tree_block(inode, buffer.data,
522				(offset - tree_offset) / params->block_size,
523				params);
524		if (err)
525			goto out;
526	}
527
528	/* already copy merkle tree */
529	err = 1;
530out:
531	kfree(buffer.data);
532	return err;
533}
534
535static int code_sign_init_descriptor(struct inode *inode,
536	const struct fsverity_enable_arg *_arg,
537	struct fsverity_descriptor *_desc)
538{
539	struct code_sign_descriptor *desc = CAST_CODE_SIGN_DESC(_desc);
540	const struct code_sign_enable_arg *arg = (const struct code_sign_enable_arg *)_arg;
541	int algo_index;
542
543	if (!arg->cs_version)
544		return 0;
545
546	/* init extended fields */
547	desc->flags = cpu_to_le32(arg->flags);
548	desc->data_size = cpu_to_le64(arg->data_size);
549	desc->tree_offset = cpu_to_le64(arg->tree_offset);
550	desc->cs_version = arg->cs_version;
551	desc->pgtypeinfo_size = cpu_to_le32(arg->pgtypeinfo_size);
552	desc->pgtypeinfo_off = cpu_to_le64(arg->pgtypeinfo_off);
553
554	/* Get root hash if a Merkle tree carried in file */
555	if (!IS_INSIDE_TREE(desc))
556		return 0;
557
558	/* Get size of root hash */
559	algo_index = desc->hash_algorithm;
560	if (algo_index >= g_fsverity_hash_algs_num ||
561			!fsverity_hash_algs[algo_index].name) {
562		fsverity_err(inode, "Unknown hash algorithm: %u", algo_index);
563		return -EINVAL;
564	}
565
566	if (copy_from_user(desc->root_hash, u64_to_user_ptr(arg->root_hash_ptr),
567			fsverity_hash_algs[algo_index].digest_size)) {
568		return -EFAULT;
569	}
570
571	return 0;
572}
573
574/**
575 * fsverity_ioctl_enable_code_sign() - enable code signing on a file
576 * @filp: file to enable code signing on
577 * @uarg: user pointer to code_sign_enable_arg
578 *
579 * Enable fs-verity on a file with code signing features.
580 *
581 * Return: 0 on success, -errno on failure
582 */
583int fsverity_ioctl_enable_code_sign(struct file *filp, const void __user *uarg)
584{
585	struct inode *inode = file_inode(filp);
586	struct code_sign_enable_arg arg;
587
588	if (copy_from_user(&arg, uarg, sizeof(arg)))
589		return -EFAULT;
590
591	if (arg.version != 1)
592		return -EINVAL;
593
594	if (arg.__reserved1 ||
595	    memchr_inv(arg.__reserved2, 0, sizeof(arg.__reserved2)))
596		return -EINVAL;
597
598	if (arg.data_size > inode->i_size)
599		return -EINVAL;
600
601	if (arg.tree_offset % arg.block_size != 0)
602		return -EINVAL;
603
604	if (!is_power_of_2(arg.block_size))
605		return -EINVAL;
606
607	if (arg.salt_size > sizeof_field(struct code_sign_descriptor, salt))
608		return -EMSGSIZE;
609
610	if (arg.sig_size > FS_VERITY_MAX_SIGNATURE_SIZE)
611		return -EMSGSIZE;
612
613	if (arg.pgtypeinfo_off > arg.data_size - arg.pgtypeinfo_size / 8)
614		return -EINVAL;
615
616	return check_file_and_enable_verity(filp, (struct fsverity_enable_arg *)&arg);
617}
618EXPORT_SYMBOL_GPL(fsverity_ioctl_enable_code_sign);
619#endif /* CONFIG_SECURITY_CODE_SIGN */
620