xref: /linux/fs/verity/enable.c (revision 376b1446153ca67e7028e6b9555d9b17477f568b)
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/pagemap.h>
12 #include <linux/sched/signal.h>
13 #include <linux/uaccess.h>
14 
15 struct block_buffer {
16 	u32 filled;
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 	/* Zero-pad the block if it's shorter than the block size. */
29 	memset(&cur->data[cur->filled], 0, params->block_size - cur->filled);
30 
31 	err = fsverity_hash_block(params, inode, req, virt_to_page(cur->data),
32 				  offset_in_page(cur->data),
33 				  &next->data[next->filled]);
34 	if (err)
35 		return err;
36 	next->filled += params->digest_size;
37 	cur->filled = 0;
38 	return 0;
39 }
40 
41 static int write_merkle_tree_block(struct inode *inode, const u8 *buf,
42 				   unsigned long index,
43 				   const struct merkle_tree_params *params)
44 {
45 	u64 pos = (u64)index << params->log_blocksize;
46 	int err;
47 
48 	err = inode->i_sb->s_vop->write_merkle_tree_block(inode, buf, pos,
49 							  params->block_size);
50 	if (err)
51 		fsverity_err(inode, "Error %d writing Merkle tree block %lu",
52 			     err, index);
53 	return err;
54 }
55 
56 /*
57  * Build the Merkle tree for the given file using the given parameters, and
58  * return the root hash in @root_hash.
59  *
60  * The tree is written to a filesystem-specific location as determined by the
61  * ->write_merkle_tree_block() method.  However, the blocks that comprise the
62  * tree are the same for all filesystems.
63  */
64 static int build_merkle_tree(struct file *filp,
65 			     const struct merkle_tree_params *params,
66 			     u8 *root_hash)
67 {
68 	struct inode *inode = file_inode(filp);
69 	const u64 data_size = inode->i_size;
70 	const int num_levels = params->num_levels;
71 	struct ahash_request *req;
72 	struct block_buffer _buffers[1 + FS_VERITY_MAX_LEVELS + 1] = {};
73 	struct block_buffer *buffers = &_buffers[1];
74 	unsigned long level_offset[FS_VERITY_MAX_LEVELS];
75 	int level;
76 	u64 offset;
77 	int err;
78 
79 	if (data_size == 0) {
80 		/* Empty file is a special case; root hash is all 0's */
81 		memset(root_hash, 0, params->digest_size);
82 		return 0;
83 	}
84 
85 	/* This allocation never fails, since it's mempool-backed. */
86 	req = fsverity_alloc_hash_request(params->hash_alg, GFP_KERNEL);
87 
88 	/*
89 	 * Allocate the block buffers.  Buffer "-1" is for data blocks.
90 	 * Buffers 0 <= level < num_levels are for the actual tree levels.
91 	 * Buffer 'num_levels' is for the root hash.
92 	 */
93 	for (level = -1; level < num_levels; level++) {
94 		buffers[level].data = kzalloc(params->block_size, GFP_KERNEL);
95 		if (!buffers[level].data) {
96 			err = -ENOMEM;
97 			goto out;
98 		}
99 	}
100 	buffers[num_levels].data = root_hash;
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(inode, params, req, &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(inode, params, req,
136 					     &buffers[level]);
137 			if (err)
138 				goto out;
139 			err = write_merkle_tree_block(inode,
140 						      buffers[level].data,
141 						      level_offset[level],
142 						      params);
143 			if (err)
144 				goto out;
145 			level_offset[level]++;
146 		}
147 		if (fatal_signal_pending(current)) {
148 			err = -EINTR;
149 			goto out;
150 		}
151 		cond_resched();
152 	}
153 	/* Finish all nonempty pending tree blocks. */
154 	for (level = 0; level < num_levels; level++) {
155 		if (buffers[level].filled != 0) {
156 			err = hash_one_block(inode, params, req,
157 					     &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(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 	fsverity_free_hash_request(params->hash_alg, req);
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 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 	/*
229 	 * Start enabling verity on this file, serialized by the inode lock.
230 	 * Fail if verity is already enabled or is already being enabled.
231 	 */
232 	inode_lock(inode);
233 	if (IS_VERITY(inode))
234 		err = -EEXIST;
235 	else
236 		err = vops->begin_enable_verity(filp);
237 	inode_unlock(inode);
238 	if (err)
239 		goto out;
240 
241 	/*
242 	 * Build the Merkle tree.  Don't hold the inode lock during this, since
243 	 * on huge files this may take a very long time and we don't want to
244 	 * force unrelated syscalls like chown() to block forever.  We don't
245 	 * need the inode lock here because deny_write_access() already prevents
246 	 * the file from being written to or truncated, and we still serialize
247 	 * ->begin_enable_verity() and ->end_enable_verity() using the inode
248 	 * lock and only allow one process to be here at a time on a given file.
249 	 */
250 	BUILD_BUG_ON(sizeof(desc->root_hash) < FS_VERITY_MAX_DIGEST_SIZE);
251 	err = build_merkle_tree(filp, &params, desc->root_hash);
252 	if (err) {
253 		fsverity_err(inode, "Error %d building Merkle tree", err);
254 		goto rollback;
255 	}
256 
257 	/*
258 	 * Create the fsverity_info.  Don't bother trying to save work by
259 	 * reusing the merkle_tree_params from above.  Instead, just create the
260 	 * fsverity_info from the fsverity_descriptor as if it were just loaded
261 	 * from disk.  This is simpler, and it serves as an extra check that the
262 	 * metadata we're writing is valid before actually enabling verity.
263 	 */
264 	vi = fsverity_create_info(inode, desc);
265 	if (IS_ERR(vi)) {
266 		err = PTR_ERR(vi);
267 		goto rollback;
268 	}
269 
270 	/*
271 	 * Tell the filesystem to finish enabling verity on the file.
272 	 * Serialized with ->begin_enable_verity() by the inode lock.
273 	 */
274 	inode_lock(inode);
275 	err = vops->end_enable_verity(filp, desc, desc_size, params.tree_size);
276 	inode_unlock(inode);
277 	if (err) {
278 		fsverity_err(inode, "%ps() failed with err %d",
279 			     vops->end_enable_verity, err);
280 		fsverity_free_info(vi);
281 	} else if (WARN_ON(!IS_VERITY(inode))) {
282 		err = -EINVAL;
283 		fsverity_free_info(vi);
284 	} else {
285 		/* Successfully enabled verity */
286 
287 		/*
288 		 * Readers can start using ->i_verity_info immediately, so it
289 		 * can't be rolled back once set.  So don't set it until just
290 		 * after the filesystem has successfully enabled verity.
291 		 */
292 		fsverity_set_info(inode, vi);
293 	}
294 out:
295 	kfree(params.hashstate);
296 	kfree(desc);
297 	return err;
298 
299 rollback:
300 	inode_lock(inode);
301 	(void)vops->end_enable_verity(filp, NULL, 0, params.tree_size);
302 	inode_unlock(inode);
303 	goto out;
304 }
305 
306 /**
307  * fsverity_ioctl_enable() - enable verity on a file
308  * @filp: file to enable verity on
309  * @uarg: user pointer to fsverity_enable_arg
310  *
311  * Enable fs-verity on a file.  See the "FS_IOC_ENABLE_VERITY" section of
312  * Documentation/filesystems/fsverity.rst for the documentation.
313  *
314  * Return: 0 on success, -errno on failure
315  */
316 int fsverity_ioctl_enable(struct file *filp, const void __user *uarg)
317 {
318 	struct inode *inode = file_inode(filp);
319 	struct fsverity_enable_arg arg;
320 	int err;
321 
322 	if (copy_from_user(&arg, uarg, sizeof(arg)))
323 		return -EFAULT;
324 
325 	if (arg.version != 1)
326 		return -EINVAL;
327 
328 	if (arg.__reserved1 ||
329 	    memchr_inv(arg.__reserved2, 0, sizeof(arg.__reserved2)))
330 		return -EINVAL;
331 
332 	if (!is_power_of_2(arg.block_size))
333 		return -EINVAL;
334 
335 	if (arg.salt_size > sizeof_field(struct fsverity_descriptor, salt))
336 		return -EMSGSIZE;
337 
338 	if (arg.sig_size > FS_VERITY_MAX_SIGNATURE_SIZE)
339 		return -EMSGSIZE;
340 
341 	/*
342 	 * Require a regular file with write access.  But the actual fd must
343 	 * still be readonly so that we can lock out all writers.  This is
344 	 * needed to guarantee that no writable fds exist to the file once it
345 	 * has verity enabled, and to stabilize the data being hashed.
346 	 */
347 
348 	err = file_permission(filp, MAY_WRITE);
349 	if (err)
350 		return err;
351 
352 	if (IS_APPEND(inode))
353 		return -EPERM;
354 
355 	if (S_ISDIR(inode->i_mode))
356 		return -EISDIR;
357 
358 	if (!S_ISREG(inode->i_mode))
359 		return -EINVAL;
360 
361 	err = mnt_want_write_file(filp);
362 	if (err) /* -EROFS */
363 		return err;
364 
365 	err = deny_write_access(filp);
366 	if (err) /* -ETXTBSY */
367 		goto out_drop_write;
368 
369 	err = enable_verity(filp, &arg);
370 	if (err)
371 		goto out_allow_write_access;
372 
373 	/*
374 	 * Some pages of the file may have been evicted from pagecache after
375 	 * being used in the Merkle tree construction, then read into pagecache
376 	 * again by another process reading from the file concurrently.  Since
377 	 * these pages didn't undergo verification against the file digest which
378 	 * fs-verity now claims to be enforcing, we have to wipe the pagecache
379 	 * to ensure that all future reads are verified.
380 	 */
381 	filemap_write_and_wait(inode->i_mapping);
382 	invalidate_inode_pages2(inode->i_mapping);
383 
384 	/*
385 	 * allow_write_access() is needed to pair with deny_write_access().
386 	 * Regardless, the filesystem won't allow writing to verity files.
387 	 */
388 out_allow_write_access:
389 	allow_write_access(filp);
390 out_drop_write:
391 	mnt_drop_write_file(filp);
392 	return err;
393 }
394 EXPORT_SYMBOL_GPL(fsverity_ioctl_enable);
395