1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * fs/verity/enable.c: ioctl to enable verity on a file
4 *
5 * Copyright 2019 Google LLC
6 */
7
8 #include "fsverity_private.h"
9
10 #include <crypto/hash.h>
11 #include <linux/backing-dev.h>
12 #include <linux/mount.h>
13 #include <linux/pagemap.h>
14 #include <linux/sched/signal.h>
15 #include <linux/uaccess.h>
16
17 static int check_file_and_enable_verity(struct file *filp,
18 const struct fsverity_enable_arg *arg);
19
20 #ifdef CONFIG_SECURITY_CODE_SIGN
21
22 static int code_sign_init_descriptor(struct inode *inode,
23 const struct fsverity_enable_arg *_arg, struct fsverity_descriptor *_desc);
24
25 static int code_sign_copy_merkle_tree(struct file *filp, const void *_desc,
26 const struct merkle_tree_params *params);
27
28 #else /* !CONFIG_SECURITY_CODE_SIGN */
29
code_sign_init_descriptor(struct inode * inode,const struct fsverity_enable_arg * _arg,struct fsverity_descriptor * _desc)30 static inline int code_sign_init_descriptor(struct inode *inode,
31 const struct fsverity_enable_arg *_arg, struct fsverity_descriptor *_desc)
32 {
33 return 0;
34 }
35
code_sign_copy_merkle_tree(struct file * filp,const void * _desc,const struct merkle_tree_params * params)36 static int code_sign_copy_merkle_tree(struct file *filp,
37 const void *_desc,
38 const struct merkle_tree_params *params)
39 {
40 return 0;
41 }
42 #endif /* !CONFIG_SECURITY_CODE_SIGN */
43
44 /*
45 * Read a file data page for Merkle tree construction. Do aggressive readahead,
46 * since we're sequentially reading the entire file.
47 */
read_file_data_page(struct file * filp,pgoff_t index,struct file_ra_state * ra,unsigned long remaining_pages)48 static struct page *read_file_data_page(struct file *filp, pgoff_t index,
49 struct file_ra_state *ra,
50 unsigned long remaining_pages)
51 {
52 struct page *page;
53
54 page = find_get_page_flags(filp->f_mapping, index, FGP_ACCESSED);
55 if (!page || !PageUptodate(page)) {
56 if (page)
57 put_page(page);
58 else
59 page_cache_sync_readahead(filp->f_mapping, ra, filp,
60 index, remaining_pages);
61 page = read_mapping_page(filp->f_mapping, index, NULL);
62 if (IS_ERR(page))
63 return page;
64 }
65 if (PageReadahead(page))
66 page_cache_async_readahead(filp->f_mapping, ra, filp, page,
67 index, remaining_pages);
68 return page;
69 }
70
build_merkle_tree_level(struct file * filp,unsigned int level,u64 num_blocks_to_hash,const struct merkle_tree_params * params,u8 * pending_hashes,struct ahash_request * req)71 static int build_merkle_tree_level(struct file *filp, unsigned int level,
72 u64 num_blocks_to_hash,
73 const struct merkle_tree_params *params,
74 u8 *pending_hashes,
75 struct ahash_request *req)
76 {
77 struct inode *inode = file_inode(filp);
78 const struct fsverity_operations *vops = inode->i_sb->s_vop;
79 struct file_ra_state ra = { 0 };
80 unsigned int pending_size = 0;
81 u64 dst_block_num;
82 u64 i;
83 int err;
84
85 if (WARN_ON(params->block_size != PAGE_SIZE)) /* checked earlier too */
86 return -EINVAL;
87
88 if (level < params->num_levels) {
89 dst_block_num = params->level_start[level];
90 } else {
91 if (WARN_ON(num_blocks_to_hash != 1))
92 return -EINVAL;
93 dst_block_num = 0; /* unused */
94 }
95
96 file_ra_state_init(&ra, filp->f_mapping);
97
98 for (i = 0; i < num_blocks_to_hash; i++) {
99 struct page *src_page;
100
101 if ((pgoff_t)i % 10000 == 0 || i + 1 == num_blocks_to_hash)
102 pr_debug("Hashing block %llu of %llu for level %u\n",
103 i + 1, num_blocks_to_hash, level);
104
105 if (level == 0) {
106 /* Leaf: hashing a data block */
107 src_page = read_file_data_page(filp, i, &ra,
108 num_blocks_to_hash - i);
109 if (IS_ERR(src_page)) {
110 err = PTR_ERR(src_page);
111 fsverity_err(inode,
112 "Error %d reading data page %llu",
113 err, i);
114 return err;
115 }
116 } else {
117 unsigned long num_ra_pages =
118 min_t(unsigned long, num_blocks_to_hash - i,
119 inode->i_sb->s_bdi->io_pages);
120
121 /* Non-leaf: hashing hash block from level below */
122 src_page = vops->read_merkle_tree_page(inode,
123 params->level_start[level - 1] + i,
124 num_ra_pages);
125 if (IS_ERR(src_page)) {
126 err = PTR_ERR(src_page);
127 fsverity_err(inode,
128 "Error %d reading Merkle tree page %llu",
129 err, params->level_start[level - 1] + i);
130 return err;
131 }
132 }
133
134 err = fsverity_hash_page(params, inode, req, src_page,
135 &pending_hashes[pending_size]);
136 put_page(src_page);
137 if (err)
138 return err;
139 pending_size += params->digest_size;
140
141 if (level == params->num_levels) /* Root hash? */
142 return 0;
143
144 if (pending_size + params->digest_size > params->block_size ||
145 i + 1 == num_blocks_to_hash) {
146 /* Flush the pending hash block */
147 memset(&pending_hashes[pending_size], 0,
148 params->block_size - pending_size);
149 err = vops->write_merkle_tree_block(inode,
150 pending_hashes,
151 dst_block_num,
152 params->log_blocksize);
153 if (err) {
154 fsverity_err(inode,
155 "Error %d writing Merkle tree block %llu",
156 err, dst_block_num);
157 return err;
158 }
159 dst_block_num++;
160 pending_size = 0;
161 }
162
163 if (fatal_signal_pending(current))
164 return -EINTR;
165 cond_resched();
166 }
167 return 0;
168 }
169
170 /*
171 * Build the Merkle tree for the given file using the given parameters, and
172 * return the root hash in @root_hash.
173 *
174 * The tree is written to a filesystem-specific location as determined by the
175 * ->write_merkle_tree_block() method. However, the blocks that comprise the
176 * tree are the same for all filesystems.
177 */
build_merkle_tree(struct file * filp,const struct merkle_tree_params * params,u8 * root_hash,size_t data_size)178 static int build_merkle_tree(struct file *filp,
179 const struct merkle_tree_params *params,
180 u8 *root_hash,
181 size_t data_size)
182 {
183 struct inode *inode = file_inode(filp);
184 u8 *pending_hashes;
185 struct ahash_request *req;
186 u64 blocks;
187 unsigned int level;
188 int err = -ENOMEM;
189
190 if (data_size == 0) {
191 /* Empty file is a special case; root hash is all 0's */
192 memset(root_hash, 0, params->digest_size);
193 return 0;
194 }
195
196 /* This allocation never fails, since it's mempool-backed. */
197 req = fsverity_alloc_hash_request(params->hash_alg, GFP_KERNEL);
198
199 pending_hashes = kmalloc(params->block_size, GFP_KERNEL);
200 if (!pending_hashes)
201 goto out;
202
203 /*
204 * Build each level of the Merkle tree, starting at the leaf level
205 * (level 0) and ascending to the root node (level 'num_levels - 1').
206 * Then at the end (level 'num_levels'), calculate the root hash.
207 */
208 blocks = ((u64)data_size + params->block_size - 1) >>
209 params->log_blocksize;
210 for (level = 0; level <= params->num_levels; level++) {
211 err = build_merkle_tree_level(filp, level, blocks, params,
212 pending_hashes, req);
213 if (err)
214 goto out;
215 blocks = (blocks + params->hashes_per_block - 1) >>
216 params->log_arity;
217 }
218 memcpy(root_hash, pending_hashes, params->digest_size);
219 err = 0;
220 out:
221 kfree(pending_hashes);
222 fsverity_free_hash_request(params->hash_alg, req);
223 return err;
224 }
225
enable_verity(struct file * filp,const struct fsverity_enable_arg * arg)226 static int enable_verity(struct file *filp,
227 const struct fsverity_enable_arg *arg)
228 {
229 struct inode *inode = file_inode(filp);
230 struct fsverity_descriptor *desc;
231 size_t desc_size = sizeof(*desc) + arg->sig_size;
232 int err;
233
234 /* Start initializing the fsverity_descriptor */
235 desc = kzalloc(desc_size, GFP_KERNEL);
236 if (!desc)
237 return -ENOMEM;
238 desc->version = 1;
239 desc->hash_algorithm = arg->hash_algorithm;
240 desc->log_blocksize = ilog2(arg->block_size);
241
242 /* Get the salt if the user provided one */
243 if (arg->salt_size &&
244 copy_from_user(desc->salt, u64_to_user_ptr(arg->salt_ptr),
245 arg->salt_size)) {
246 err = -EFAULT;
247 goto out;
248 }
249 desc->salt_size = arg->salt_size;
250
251 /* Get the signature if the user provided one */
252 if (arg->sig_size &&
253 copy_from_user(desc->signature, u64_to_user_ptr(arg->sig_ptr),
254 arg->sig_size)) {
255 err = -EFAULT;
256 goto out;
257 }
258 desc->sig_size = cpu_to_le32(arg->sig_size);
259
260 desc->data_size = cpu_to_le64(inode->i_size);
261
262 err = code_sign_init_descriptor(inode, arg, desc);
263 if (err) {
264 fsverity_err(inode, "Init code sign descriptor err: %u", err);
265 goto out;
266 }
267
268 err = fsverity_enable_with_descriptor(filp, (void *)desc, desc_size);
269 out:
270 kfree(desc);
271 return err;
272 }
273
fsverity_enable_with_descriptor(struct file * filp,void * _desc,size_t desc_size)274 int fsverity_enable_with_descriptor(struct file *filp,
275 void *_desc, size_t desc_size)
276 {
277 struct inode *inode = file_inode(filp);
278 const struct fsverity_operations *vops = inode->i_sb->s_vop;
279 struct merkle_tree_params params = { };
280 struct fsverity_descriptor *desc = (struct fsverity_descriptor *)_desc;
281 struct fsverity_info *vi;
282 int err;
283
284 /* Prepare the Merkle tree parameters */
285 err = fsverity_init_merkle_tree_params(¶ms, inode,
286 desc->hash_algorithm,
287 desc->log_blocksize,
288 desc->salt, desc->salt_size,
289 desc->data_size);
290 if (err)
291 goto out;
292
293 /*
294 * Start enabling verity on this file, serialized by the inode lock.
295 * Fail if verity is already enabled or is already being enabled.
296 */
297 inode_lock(inode);
298 if (IS_VERITY(inode))
299 err = -EEXIST;
300 else
301 err = vops->begin_enable_verity(filp);
302 inode_unlock(inode);
303 if (err)
304 goto out;
305
306 err = code_sign_copy_merkle_tree(filp, _desc, ¶ms);
307 if (err < 0) {
308 fsverity_err(inode, "Error %d copying Merkle tree", err);
309 goto rollback;
310 } else if (err == 1) /* already copy merkle tree */
311 goto skip_build;
312
313 /*
314 * Build the Merkle tree. Don't hold the inode lock during this, since
315 * on huge files this may take a very long time and we don't want to
316 * force unrelated syscalls like chown() to block forever. We don't
317 * need the inode lock here because deny_write_access() already prevents
318 * the file from being written to or truncated, and we still serialize
319 * ->begin_enable_verity() and ->end_enable_verity() using the inode
320 * lock and only allow one process to be here at a time on a given file.
321 */
322 pr_debug("Building Merkle tree...\n");
323 BUILD_BUG_ON(sizeof(desc->root_hash) < FS_VERITY_MAX_DIGEST_SIZE);
324 err = build_merkle_tree(filp, ¶ms, desc->root_hash, desc->data_size);
325 if (err) {
326 fsverity_err(inode, "Error %d building Merkle tree", err);
327 goto rollback;
328 }
329
330 skip_build:
331 pr_debug("Done building Merkle tree. Root hash is %s:%*phN\n",
332 params.hash_alg->name, params.digest_size, desc->root_hash);
333
334 /*
335 * Create the fsverity_info. Don't bother trying to save work by
336 * reusing the merkle_tree_params from above. Instead, just create the
337 * fsverity_info from the fsverity_descriptor as if it were just loaded
338 * from disk. This is simpler, and it serves as an extra check that the
339 * metadata we're writing is valid before actually enabling verity.
340 */
341 vi = fsverity_create_info(inode, desc, desc_size);
342 if (IS_ERR(vi)) {
343 err = PTR_ERR(vi);
344 goto rollback;
345 }
346
347 if (desc->sig_size)
348 pr_debug("Storing a %u-byte PKCS#7 signature alongside the file\n",
349 desc->sig_size);
350
351 /*
352 * Tell the filesystem to finish enabling verity on the file.
353 * Serialized with ->begin_enable_verity() by the inode lock.
354 */
355 inode_lock(inode);
356 err = vops->end_enable_verity(filp, desc, desc_size, params.tree_size);
357 inode_unlock(inode);
358 if (err) {
359 fsverity_err(inode, "%ps() failed with err %d",
360 vops->end_enable_verity, err);
361 fsverity_free_info(vi);
362 } else if (WARN_ON(!IS_VERITY(inode))) {
363 err = -EINVAL;
364 fsverity_free_info(vi);
365 } else {
366 /* Successfully enabled verity */
367
368 /*
369 * Readers can start using ->i_verity_info immediately, so it
370 * can't be rolled back once set. So don't set it until just
371 * after the filesystem has successfully enabled verity.
372 */
373 fsverity_set_info(inode, vi);
374 }
375 out:
376 kfree(params.hashstate);
377 return err;
378
379 rollback:
380 inode_lock(inode);
381 (void)vops->end_enable_verity(filp, NULL, 0, params.tree_size);
382 inode_unlock(inode);
383 goto out;
384 }
385 EXPORT_SYMBOL_GPL(fsverity_enable_with_descriptor);
386
387 /**
388 * fsverity_ioctl_enable() - enable verity on a file
389 * @filp: file to enable verity on
390 * @uarg: user pointer to fsverity_enable_arg
391 *
392 * Enable fs-verity on a file. See the "FS_IOC_ENABLE_VERITY" section of
393 * Documentation/filesystems/fsverity.rst for the documentation.
394 *
395 * Return: 0 on success, -errno on failure
396 */
fsverity_ioctl_enable(struct file * filp,const void __user * uarg)397 int fsverity_ioctl_enable(struct file *filp, const void __user *uarg)
398 {
399 struct inode *inode = file_inode(filp);
400 struct fsverity_enable_arg arg;
401
402 if (copy_from_user(&arg, uarg, sizeof(arg)))
403 return -EFAULT;
404
405 if (arg.version != 1)
406 return -EINVAL;
407
408 if (arg.__reserved1 ||
409 memchr_inv(arg.__reserved2, 0, sizeof(arg.__reserved2)))
410 return -EINVAL;
411
412 if (arg.block_size != PAGE_SIZE)
413 return -EINVAL;
414
415 if (arg.salt_size > sizeof_field(struct fsverity_descriptor, salt))
416 return -EMSGSIZE;
417
418 if (arg.sig_size > FS_VERITY_MAX_SIGNATURE_SIZE)
419 return -EMSGSIZE;
420
421 return check_file_and_enable_verity(filp, &arg);
422 }
423 EXPORT_SYMBOL_GPL(fsverity_ioctl_enable);
424
check_file_and_enable_verity(struct file * filp,const struct fsverity_enable_arg * arg)425 static int check_file_and_enable_verity(struct file *filp,
426 const struct fsverity_enable_arg *arg)
427 {
428 struct inode *inode = file_inode(filp);
429 int err;
430 /*
431 * Require a regular file with write access. But the actual fd must
432 * still be readonly so that we can lock out all writers. This is
433 * needed to guarantee that no writable fds exist to the file once it
434 * has verity enabled, and to stabilize the data being hashed.
435 */
436
437 err = inode_permission(inode, MAY_WRITE);
438 if (err)
439 return err;
440
441 if (IS_APPEND(inode))
442 return -EPERM;
443
444 if (S_ISDIR(inode->i_mode))
445 return -EISDIR;
446
447 if (!S_ISREG(inode->i_mode))
448 return -EINVAL;
449
450 err = mnt_want_write_file(filp);
451 if (err) /* -EROFS */
452 return err;
453
454 err = deny_write_access(filp);
455 if (err) /* -ETXTBSY */
456 goto out_drop_write;
457
458 err = enable_verity(filp, arg);
459
460 /*
461 * We no longer drop the inode's pagecache after enabling verity. This
462 * used to be done to try to avoid a race condition where pages could be
463 * evicted after being used in the Merkle tree construction, then
464 * re-instantiated by a concurrent read. Such pages are unverified, and
465 * the backing storage could have filled them with different content, so
466 * they shouldn't be used to fulfill reads once verity is enabled.
467 *
468 * But, dropping the pagecache has a big performance impact, and it
469 * doesn't fully solve the race condition anyway. So for those reasons,
470 * and also because this race condition isn't very important relatively
471 * speaking (especially for small-ish files, where the chance of a page
472 * being used, evicted, *and* re-instantiated all while enabling verity
473 * is quite small), we no longer drop the inode's pagecache.
474 */
475
476 /*
477 * allow_write_access() is needed to pair with deny_write_access().
478 * Regardless, the filesystem won't allow writing to verity files.
479 */
480 allow_write_access(filp);
481 out_drop_write:
482 mnt_drop_write_file(filp);
483 return err;
484 }
485
486 #ifdef CONFIG_SECURITY_CODE_SIGN
code_sign_copy_merkle_tree(struct file * filp,const void * _desc,const struct merkle_tree_params * params)487 static int code_sign_copy_merkle_tree(struct file *filp,
488 const void *_desc,
489 const struct merkle_tree_params *params)
490 {
491 struct inode *inode = file_inode(filp);
492 const struct fsverity_operations *vops = inode->i_sb->s_vop;
493 u8 *tree_data;
494 u64 blocks, i;
495 int err = -ENOMEM;
496 struct file_ra_state ra = { 0 };
497 struct page *src_page;
498 void *addr;
499 u64 tree_offset, tree_start_index;
500
501 if (!is_inside_tree_compact(_desc))
502 return 0;
503
504 tree_offset = get_tree_offset_compact(_desc);
505
506 if (inode->i_size < tree_offset + params->tree_size) {
507 fsverity_err(inode, "File is too small to contain Merkle tree.");
508 return -EFAULT;
509 }
510
511 tree_data = kmalloc(PAGE_SIZE, GFP_KERNEL);
512 if (!tree_data)
513 goto out;
514
515 file_ra_state_init(&ra, filp->f_mapping);
516
517 tree_start_index = tree_offset >> PAGE_SHIFT;
518 blocks = params->tree_size >> PAGE_SHIFT;
519 for (i = 0; i < blocks; i++) {
520 pr_debug("Copy Merkle tree page at %d\n", tree_start_index + i);
521 src_page = read_file_data_page(filp, tree_start_index + i, &ra,
522 blocks - i);
523 if (IS_ERR(src_page)) {
524 err = PTR_ERR(src_page);
525 fsverity_err(inode,
526 "Error %d reading Merkle tree page %llu",
527 err, tree_start_index + i);
528 goto out;
529 }
530
531 addr = kmap_atomic(src_page);
532 memcpy(tree_data, addr, PAGE_SIZE);
533 kunmap_atomic(addr);
534 put_page(src_page);
535 err = vops->write_merkle_tree_block(inode, tree_data, i,
536 params->log_blocksize);
537 if (err) {
538 fsverity_err(inode,
539 "Error %d writing Merkle tree block %llu",
540 err, i);
541 goto out;
542 }
543 }
544 /* already copy merkle tree */
545 err = 1;
546 out:
547 kfree(tree_data);
548 return err;
549 }
550
code_sign_init_descriptor(struct inode * inode,const struct fsverity_enable_arg * _arg,struct fsverity_descriptor * _desc)551 static int code_sign_init_descriptor(struct inode *inode,
552 const struct fsverity_enable_arg *_arg,
553 struct fsverity_descriptor *_desc)
554 {
555 struct code_sign_descriptor *desc = CAST_CODE_SIGN_DESC(_desc);
556 const struct code_sign_enable_arg *arg = (const struct code_sign_enable_arg *)_arg;
557 int algo_index;
558
559 if (!arg->cs_version)
560 return 0;
561
562 /* init extended fields */
563 desc->flags = cpu_to_le32(arg->flags);
564 desc->data_size = cpu_to_le64(arg->data_size);
565 desc->tree_offset = cpu_to_le64(arg->tree_offset);
566 desc->cs_version = arg->cs_version;
567
568 /* Get root hash if a Merkle tree carried in file */
569 if (!IS_INSIDE_TREE(desc))
570 return 0;
571
572 /* Get size of root hash */
573 algo_index = desc->hash_algorithm;
574 if (algo_index >= g_fsverity_hash_algs_num ||
575 !fsverity_hash_algs[algo_index].name) {
576 fsverity_err(inode, "Unknown hash algorithm: %u", algo_index);
577 return -EINVAL;
578 }
579
580 if (copy_from_user(desc->root_hash, u64_to_user_ptr(arg->root_hash_ptr),
581 fsverity_hash_algs[algo_index].digest_size)) {
582 return -EFAULT;
583 }
584
585 return 0;
586 }
587
588 /**
589 * fsverity_ioctl_enable_code_sign() - enable code signing on a file
590 * @filp: file to enable code signing on
591 * @uarg: user pointer to code_sign_enable_arg
592 *
593 * Enable fs-verity on a file with code signing features.
594 *
595 * Return: 0 on success, -errno on failure
596 */
fsverity_ioctl_enable_code_sign(struct file * filp,const void __user * uarg)597 int fsverity_ioctl_enable_code_sign(struct file *filp, const void __user *uarg)
598 {
599 struct inode *inode = file_inode(filp);
600 struct code_sign_enable_arg arg;
601
602 if (copy_from_user(&arg, uarg, sizeof(arg)))
603 return -EFAULT;
604
605 if (arg.version != 1)
606 return -EINVAL;
607
608 if (arg.cs_version != 1)
609 return -EINVAL;
610
611 if (arg.__reserved1 ||
612 memchr_inv(arg.__reserved2, 0, sizeof(arg.__reserved2)))
613 return -EINVAL;
614
615 if (arg.data_size > inode->i_size)
616 return -EINVAL;
617
618 if (arg.tree_offset % PAGE_SIZE != 0)
619 return -EINVAL;
620
621 if (arg.block_size != PAGE_SIZE)
622 return -EINVAL;
623
624 if (arg.salt_size > sizeof_field(struct code_sign_descriptor, salt))
625 return -EMSGSIZE;
626
627 if (arg.sig_size > FS_VERITY_MAX_SIGNATURE_SIZE)
628 return -EMSGSIZE;
629
630 return check_file_and_enable_verity(filp, (struct fsverity_enable_arg *)&arg);
631 }
632 EXPORT_SYMBOL_GPL(fsverity_ioctl_enable_code_sign);
633 #endif /* CONFIG_SECURITY_CODE_SIGN */
634