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