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