xref: /linux/fs/verity/enable.c (revision 4b65b859f55b036649a4525f09fa7c5bbbab384e)
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 <linux/export.h>
11 #include <linux/mount.h>
12 #include <linux/sched/signal.h>
13 #include <linux/uaccess.h>
14 
15 struct 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. */
hash_one_block(struct inode * inode,const struct merkle_tree_params * params,struct block_buffer * cur)22 static 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 
28 	/*
29 	 * Safety check to prevent a buffer overflow in case of a filesystem bug
30 	 * that allows the file size to change despite deny_write_access(), or a
31 	 * bug in the Merkle tree logic itself
32 	 */
33 	if (WARN_ON_ONCE(next->is_root_hash && next->filled != 0))
34 		return -EINVAL;
35 
36 	/* Zero-pad the block if it's shorter than the block size. */
37 	memset(&cur->data[cur->filled], 0, params->block_size - cur->filled);
38 
39 	fsverity_hash_block(params, inode, cur->data,
40 			    &next->data[next->filled]);
41 	next->filled += params->digest_size;
42 	cur->filled = 0;
43 	return 0;
44 }
45 
write_merkle_tree_block(struct inode * inode,const u8 * buf,unsigned long index,const struct merkle_tree_params * params)46 static int write_merkle_tree_block(struct inode *inode, const u8 *buf,
47 				   unsigned long index,
48 				   const struct merkle_tree_params *params)
49 {
50 	u64 pos = (u64)index << params->log_blocksize;
51 	int err;
52 
53 	err = inode->i_sb->s_vop->write_merkle_tree_block(inode, buf, pos,
54 							  params->block_size);
55 	if (err)
56 		fsverity_err(inode, "Error %d writing Merkle tree block %lu",
57 			     err, index);
58 	return err;
59 }
60 
61 /*
62  * Build the Merkle tree for the given file using the given parameters, and
63  * return the root hash in @root_hash.
64  *
65  * The tree is written to a filesystem-specific location as determined by the
66  * ->write_merkle_tree_block() method.  However, the blocks that comprise the
67  * tree are the same for all filesystems.
68  */
build_merkle_tree(struct file * filp,const struct merkle_tree_params * params,u8 * root_hash)69 static int build_merkle_tree(struct file *filp,
70 			     const struct merkle_tree_params *params,
71 			     u8 *root_hash)
72 {
73 	struct inode *inode = file_inode(filp);
74 	const u64 data_size = inode->i_size;
75 	const int num_levels = params->num_levels;
76 	struct block_buffer _buffers[1 + FS_VERITY_MAX_LEVELS + 1] = {};
77 	struct block_buffer *buffers = &_buffers[1];
78 	unsigned long level_offset[FS_VERITY_MAX_LEVELS];
79 	int level;
80 	u64 offset;
81 	int err;
82 
83 	if (data_size == 0) {
84 		/* Empty file is a special case; root hash is all 0's */
85 		memset(root_hash, 0, params->digest_size);
86 		return 0;
87 	}
88 
89 	/*
90 	 * Allocate the block buffers.  Buffer "-1" is for data blocks.
91 	 * Buffers 0 <= level < num_levels are for the actual tree levels.
92 	 * Buffer 'num_levels' is for the root hash.
93 	 */
94 	for (level = -1; level < num_levels; level++) {
95 		buffers[level].data = kzalloc(params->block_size, GFP_KERNEL);
96 		if (!buffers[level].data) {
97 			err = -ENOMEM;
98 			goto out;
99 		}
100 	}
101 	buffers[num_levels].data = root_hash;
102 	buffers[num_levels].is_root_hash = true;
103 
104 	BUILD_BUG_ON(sizeof(level_offset) != sizeof(params->level_start));
105 	memcpy(level_offset, params->level_start, sizeof(level_offset));
106 
107 	/* Hash each data block, also hashing the tree blocks as they fill up */
108 	for (offset = 0; offset < data_size; offset += params->block_size) {
109 		ssize_t bytes_read;
110 		loff_t pos = offset;
111 
112 		buffers[-1].filled = min_t(u64, params->block_size,
113 					   data_size - offset);
114 		bytes_read = __kernel_read(filp, buffers[-1].data,
115 					   buffers[-1].filled, &pos);
116 		if (bytes_read < 0) {
117 			err = bytes_read;
118 			fsverity_err(inode, "Error %d reading file data", err);
119 			goto out;
120 		}
121 		if (bytes_read != buffers[-1].filled) {
122 			err = -EINVAL;
123 			fsverity_err(inode, "Short read of file data");
124 			goto out;
125 		}
126 		err = hash_one_block(inode, params, &buffers[-1]);
127 		if (err)
128 			goto out;
129 		for (level = 0; level < num_levels; level++) {
130 			if (buffers[level].filled + params->digest_size <=
131 			    params->block_size) {
132 				/* Next block at @level isn't full yet */
133 				break;
134 			}
135 			/* Next block at @level is full */
136 
137 			err = hash_one_block(inode, params, &buffers[level]);
138 			if (err)
139 				goto out;
140 			err = write_merkle_tree_block(inode,
141 						      buffers[level].data,
142 						      level_offset[level],
143 						      params);
144 			if (err)
145 				goto out;
146 			level_offset[level]++;
147 		}
148 		if (fatal_signal_pending(current)) {
149 			err = -EINTR;
150 			goto out;
151 		}
152 		cond_resched();
153 	}
154 	/* Finish all nonempty pending tree blocks. */
155 	for (level = 0; level < num_levels; level++) {
156 		if (buffers[level].filled != 0) {
157 			err = hash_one_block(inode, params, &buffers[level]);
158 			if (err)
159 				goto out;
160 			err = write_merkle_tree_block(inode,
161 						      buffers[level].data,
162 						      level_offset[level],
163 						      params);
164 			if (err)
165 				goto out;
166 		}
167 	}
168 	/* The root hash was filled by the last call to hash_one_block(). */
169 	if (WARN_ON_ONCE(buffers[num_levels].filled != params->digest_size)) {
170 		err = -EINVAL;
171 		goto out;
172 	}
173 	err = 0;
174 out:
175 	for (level = -1; level < num_levels; level++)
176 		kfree(buffers[level].data);
177 	return err;
178 }
179 
enable_verity(struct file * filp,const struct fsverity_enable_arg * arg)180 static int enable_verity(struct file *filp,
181 			 const struct fsverity_enable_arg *arg)
182 {
183 	struct inode *inode = file_inode(filp);
184 	const struct fsverity_operations *vops = inode->i_sb->s_vop;
185 	struct merkle_tree_params params = { };
186 	struct fsverity_descriptor *desc;
187 	size_t desc_size = struct_size(desc, signature, arg->sig_size);
188 	struct fsverity_info *vi;
189 	int err;
190 
191 	/* Start initializing the fsverity_descriptor */
192 	desc = kzalloc(desc_size, GFP_KERNEL);
193 	if (!desc)
194 		return -ENOMEM;
195 	desc->version = 1;
196 	desc->hash_algorithm = arg->hash_algorithm;
197 	desc->log_blocksize = ilog2(arg->block_size);
198 
199 	/* Get the salt if the user provided one */
200 	if (arg->salt_size &&
201 	    copy_from_user(desc->salt, u64_to_user_ptr(arg->salt_ptr),
202 			   arg->salt_size)) {
203 		err = -EFAULT;
204 		goto out;
205 	}
206 	desc->salt_size = arg->salt_size;
207 
208 	/* Get the builtin signature if the user provided one */
209 	if (arg->sig_size &&
210 	    copy_from_user(desc->signature, u64_to_user_ptr(arg->sig_ptr),
211 			   arg->sig_size)) {
212 		err = -EFAULT;
213 		goto out;
214 	}
215 	desc->sig_size = cpu_to_le32(arg->sig_size);
216 
217 	desc->data_size = cpu_to_le64(inode->i_size);
218 
219 	/* Prepare the Merkle tree parameters */
220 	err = fsverity_init_merkle_tree_params(&params, inode,
221 					       arg->hash_algorithm,
222 					       desc->log_blocksize,
223 					       desc->salt, desc->salt_size);
224 	if (err)
225 		goto out;
226 
227 	/*
228 	 * Start enabling verity on this file, serialized by the inode lock.
229 	 * Fail if verity is already enabled or is already being enabled.
230 	 */
231 	inode_lock(inode);
232 	if (IS_VERITY(inode))
233 		err = -EEXIST;
234 	else
235 		err = vops->begin_enable_verity(filp);
236 	inode_unlock(inode);
237 	if (err)
238 		goto out;
239 
240 	/*
241 	 * Build the Merkle tree.  Don't hold the inode lock during this, since
242 	 * on huge files this may take a very long time and we don't want to
243 	 * force unrelated syscalls like chown() to block forever.  We don't
244 	 * need the inode lock here because deny_write_access() already prevents
245 	 * the file from being written to or truncated, and we still serialize
246 	 * ->begin_enable_verity() and ->end_enable_verity() using the inode
247 	 * lock and only allow one process to be here at a time on a given file.
248 	 */
249 	BUILD_BUG_ON(sizeof(desc->root_hash) < FS_VERITY_MAX_DIGEST_SIZE);
250 	err = build_merkle_tree(filp, &params, desc->root_hash);
251 	if (err) {
252 		fsverity_err(inode, "Error %d building Merkle tree", err);
253 		goto rollback;
254 	}
255 
256 	/*
257 	 * Create the fsverity_info.  Don't bother trying to save work by
258 	 * reusing the merkle_tree_params from above.  Instead, just create the
259 	 * fsverity_info from the fsverity_descriptor as if it were just loaded
260 	 * from disk.  This is simpler, and it serves as an extra check that the
261 	 * metadata we're writing is valid before actually enabling verity.
262 	 */
263 	vi = fsverity_create_info(inode, desc);
264 	if (IS_ERR(vi)) {
265 		err = PTR_ERR(vi);
266 		goto rollback;
267 	}
268 
269 	/*
270 	 * Tell the filesystem to finish enabling verity on the file.
271 	 * Serialized with ->begin_enable_verity() by the inode lock.
272 	 */
273 	inode_lock(inode);
274 	err = vops->end_enable_verity(filp, desc, desc_size, params.tree_size);
275 	inode_unlock(inode);
276 	if (err) {
277 		fsverity_err(inode, "%ps() failed with err %d",
278 			     vops->end_enable_verity, err);
279 		fsverity_free_info(vi);
280 	} else if (WARN_ON_ONCE(!IS_VERITY(inode))) {
281 		err = -EINVAL;
282 		fsverity_free_info(vi);
283 	} else {
284 		/* Successfully enabled verity */
285 
286 		/*
287 		 * Readers can start using ->i_verity_info immediately, so it
288 		 * can't be rolled back once set.  So don't set it until just
289 		 * after the filesystem has successfully enabled verity.
290 		 */
291 		fsverity_set_info(inode, vi);
292 	}
293 out:
294 	kfree(params.hashstate);
295 	kfree(desc);
296 	return err;
297 
298 rollback:
299 	inode_lock(inode);
300 	(void)vops->end_enable_verity(filp, NULL, 0, params.tree_size);
301 	inode_unlock(inode);
302 	goto out;
303 }
304 
305 /**
306  * fsverity_ioctl_enable() - enable verity on a file
307  * @filp: file to enable verity on
308  * @uarg: user pointer to fsverity_enable_arg
309  *
310  * Enable fs-verity on a file.  See the "FS_IOC_ENABLE_VERITY" section of
311  * Documentation/filesystems/fsverity.rst for the documentation.
312  *
313  * Return: 0 on success, -errno on failure
314  */
fsverity_ioctl_enable(struct file * filp,const void __user * uarg)315 int fsverity_ioctl_enable(struct file *filp, const void __user *uarg)
316 {
317 	struct inode *inode = file_inode(filp);
318 	struct fsverity_enable_arg arg;
319 	int err;
320 
321 	if (copy_from_user(&arg, uarg, sizeof(arg)))
322 		return -EFAULT;
323 
324 	if (arg.version != 1)
325 		return -EINVAL;
326 
327 	if (arg.__reserved1 ||
328 	    memchr_inv(arg.__reserved2, 0, sizeof(arg.__reserved2)))
329 		return -EINVAL;
330 
331 	if (!is_power_of_2(arg.block_size))
332 		return -EINVAL;
333 
334 	if (arg.salt_size > sizeof_field(struct fsverity_descriptor, salt))
335 		return -EMSGSIZE;
336 
337 	if (arg.sig_size > FS_VERITY_MAX_SIGNATURE_SIZE)
338 		return -EMSGSIZE;
339 
340 	/*
341 	 * Require a regular file with write access.  But the actual fd must
342 	 * still be readonly so that we can lock out all writers.  This is
343 	 * needed to guarantee that no writable fds exist to the file once it
344 	 * has verity enabled, and to stabilize the data being hashed.
345 	 */
346 
347 	err = file_permission(filp, MAY_WRITE);
348 	if (err)
349 		return err;
350 	/*
351 	 * __kernel_read() is used while building the Merkle tree.  So, we can't
352 	 * allow file descriptors that were opened for ioctl access only, using
353 	 * the special nonstandard access mode 3.  O_RDONLY only, please!
354 	 */
355 	if (!(filp->f_mode & FMODE_READ))
356 		return -EBADF;
357 
358 	if (IS_APPEND(inode))
359 		return -EPERM;
360 
361 	if (S_ISDIR(inode->i_mode))
362 		return -EISDIR;
363 
364 	if (!S_ISREG(inode->i_mode))
365 		return -EINVAL;
366 
367 	err = mnt_want_write_file(filp);
368 	if (err) /* -EROFS */
369 		return err;
370 
371 	err = deny_write_access(filp);
372 	if (err) /* -ETXTBSY */
373 		goto out_drop_write;
374 
375 	err = enable_verity(filp, &arg);
376 
377 	/*
378 	 * We no longer drop the inode's pagecache after enabling verity.  This
379 	 * used to be done to try to avoid a race condition where pages could be
380 	 * evicted after being used in the Merkle tree construction, then
381 	 * re-instantiated by a concurrent read.  Such pages are unverified, and
382 	 * the backing storage could have filled them with different content, so
383 	 * they shouldn't be used to fulfill reads once verity is enabled.
384 	 *
385 	 * But, dropping the pagecache has a big performance impact, and it
386 	 * doesn't fully solve the race condition anyway.  So for those reasons,
387 	 * and also because this race condition isn't very important relatively
388 	 * speaking (especially for small-ish files, where the chance of a page
389 	 * being used, evicted, *and* re-instantiated all while enabling verity
390 	 * is quite small), we no longer drop the inode's pagecache.
391 	 */
392 
393 	/*
394 	 * allow_write_access() is needed to pair with deny_write_access().
395 	 * Regardless, the filesystem won't allow writing to verity files.
396 	 */
397 	allow_write_access(filp);
398 out_drop_write:
399 	mnt_drop_write_file(filp);
400 	return err;
401 }
402 EXPORT_SYMBOL_GPL(fsverity_ioctl_enable);
403