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