xref: /linux/fs/ecryptfs/mmap.c (revision 7f71507851fc7764b36a3221839607d3a45c2025)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * eCryptfs: Linux filesystem encryption layer
4  * This is where eCryptfs coordinates the symmetric encryption and
5  * decryption of the file data as it passes between the lower
6  * encrypted file and the upper decrypted file.
7  *
8  * Copyright (C) 1997-2003 Erez Zadok
9  * Copyright (C) 2001-2003 Stony Brook University
10  * Copyright (C) 2004-2007 International Business Machines Corp.
11  *   Author(s): Michael A. Halcrow <mahalcro@us.ibm.com>
12  */
13 
14 #include <linux/pagemap.h>
15 #include <linux/writeback.h>
16 #include <linux/page-flags.h>
17 #include <linux/mount.h>
18 #include <linux/file.h>
19 #include <linux/scatterlist.h>
20 #include <linux/slab.h>
21 #include <linux/xattr.h>
22 #include <linux/unaligned.h>
23 #include "ecryptfs_kernel.h"
24 
25 /*
26  * This is where we encrypt the data and pass the encrypted data to
27  * the lower filesystem.  In OpenPGP-compatible mode, we operate on
28  * entire underlying packets.
29  */
30 static int ecryptfs_writepages(struct address_space *mapping,
31 		struct writeback_control *wbc)
32 {
33 	struct folio *folio = NULL;
34 	int error;
35 
36 	while ((folio = writeback_iter(mapping, wbc, folio, &error))) {
37 		error = ecryptfs_encrypt_page(folio);
38 		if (error) {
39 			ecryptfs_printk(KERN_WARNING,
40 				"Error encrypting folio (index [0x%.16lx])\n",
41 				folio->index);
42 			folio_clear_uptodate(folio);
43 			mapping_set_error(mapping, error);
44 		}
45 		folio_unlock(folio);
46 	}
47 
48 	return error;
49 }
50 
51 static void strip_xattr_flag(char *page_virt,
52 			     struct ecryptfs_crypt_stat *crypt_stat)
53 {
54 	if (crypt_stat->flags & ECRYPTFS_METADATA_IN_XATTR) {
55 		size_t written;
56 
57 		crypt_stat->flags &= ~ECRYPTFS_METADATA_IN_XATTR;
58 		ecryptfs_write_crypt_stat_flags(page_virt, crypt_stat,
59 						&written);
60 		crypt_stat->flags |= ECRYPTFS_METADATA_IN_XATTR;
61 	}
62 }
63 
64 /*
65  *   Header Extent:
66  *     Octets 0-7:        Unencrypted file size (big-endian)
67  *     Octets 8-15:       eCryptfs special marker
68  *     Octets 16-19:      Flags
69  *      Octet 16:         File format version number (between 0 and 255)
70  *      Octets 17-18:     Reserved
71  *      Octet 19:         Bit 1 (lsb): Reserved
72  *                        Bit 2: Encrypted?
73  *                        Bits 3-8: Reserved
74  *     Octets 20-23:      Header extent size (big-endian)
75  *     Octets 24-25:      Number of header extents at front of file
76  *                        (big-endian)
77  *     Octet  26:         Begin RFC 2440 authentication token packet set
78  */
79 
80 /**
81  * ecryptfs_copy_up_encrypted_with_header
82  * @folio: Sort of a ``virtual'' representation of the encrypted lower
83  *        file. The actual lower file does not have the metadata in
84  *        the header. This is locked.
85  * @crypt_stat: The eCryptfs inode's cryptographic context
86  *
87  * The ``view'' is the version of the file that userspace winds up
88  * seeing, with the header information inserted.
89  */
90 static int
91 ecryptfs_copy_up_encrypted_with_header(struct folio *folio,
92 				       struct ecryptfs_crypt_stat *crypt_stat)
93 {
94 	loff_t extent_num_in_page = 0;
95 	loff_t num_extents_per_page = (PAGE_SIZE
96 				       / crypt_stat->extent_size);
97 	int rc = 0;
98 
99 	while (extent_num_in_page < num_extents_per_page) {
100 		loff_t view_extent_num = ((loff_t)folio->index
101 					   * num_extents_per_page)
102 					  + extent_num_in_page;
103 		size_t num_header_extents_at_front =
104 			(crypt_stat->metadata_size / crypt_stat->extent_size);
105 
106 		if (view_extent_num < num_header_extents_at_front) {
107 			/* This is a header extent */
108 			char *page_virt;
109 
110 			page_virt = kmap_local_folio(folio, 0);
111 			memset(page_virt, 0, PAGE_SIZE);
112 			/* TODO: Support more than one header extent */
113 			if (view_extent_num == 0) {
114 				size_t written;
115 
116 				rc = ecryptfs_read_xattr_region(
117 					page_virt, folio->mapping->host);
118 				strip_xattr_flag(page_virt + 16, crypt_stat);
119 				ecryptfs_write_header_metadata(page_virt + 20,
120 							       crypt_stat,
121 							       &written);
122 			}
123 			kunmap_local(page_virt);
124 			flush_dcache_folio(folio);
125 			if (rc) {
126 				printk(KERN_ERR "%s: Error reading xattr "
127 				       "region; rc = [%d]\n", __func__, rc);
128 				goto out;
129 			}
130 		} else {
131 			/* This is an encrypted data extent */
132 			loff_t lower_offset =
133 				((view_extent_num * crypt_stat->extent_size)
134 				 - crypt_stat->metadata_size);
135 
136 			rc = ecryptfs_read_lower_page_segment(
137 				folio, (lower_offset >> PAGE_SHIFT),
138 				(lower_offset & ~PAGE_MASK),
139 				crypt_stat->extent_size, folio->mapping->host);
140 			if (rc) {
141 				printk(KERN_ERR "%s: Error attempting to read "
142 				       "extent at offset [%lld] in the lower "
143 				       "file; rc = [%d]\n", __func__,
144 				       lower_offset, rc);
145 				goto out;
146 			}
147 		}
148 		extent_num_in_page++;
149 	}
150 out:
151 	return rc;
152 }
153 
154 /**
155  * ecryptfs_read_folio
156  * @file: An eCryptfs file
157  * @folio: Folio from eCryptfs inode mapping into which to stick the read data
158  *
159  * Read in a folio, decrypting if necessary.
160  *
161  * Returns zero on success; non-zero on error.
162  */
163 static int ecryptfs_read_folio(struct file *file, struct folio *folio)
164 {
165 	struct inode *inode = folio->mapping->host;
166 	struct ecryptfs_crypt_stat *crypt_stat =
167 		&ecryptfs_inode_to_private(inode)->crypt_stat;
168 	int err = 0;
169 
170 	if (!crypt_stat || !(crypt_stat->flags & ECRYPTFS_ENCRYPTED)) {
171 		err = ecryptfs_read_lower_page_segment(folio, folio->index, 0,
172 				folio_size(folio), inode);
173 	} else if (crypt_stat->flags & ECRYPTFS_VIEW_AS_ENCRYPTED) {
174 		if (crypt_stat->flags & ECRYPTFS_METADATA_IN_XATTR) {
175 			err = ecryptfs_copy_up_encrypted_with_header(folio,
176 					crypt_stat);
177 			if (err) {
178 				printk(KERN_ERR "%s: Error attempting to copy "
179 				       "the encrypted content from the lower "
180 				       "file whilst inserting the metadata "
181 				       "from the xattr into the header; err = "
182 				       "[%d]\n", __func__, err);
183 				goto out;
184 			}
185 
186 		} else {
187 			err = ecryptfs_read_lower_page_segment(folio,
188 					folio->index, 0, folio_size(folio),
189 					inode);
190 			if (err) {
191 				printk(KERN_ERR "Error reading page; err = "
192 				       "[%d]\n", err);
193 				goto out;
194 			}
195 		}
196 	} else {
197 		err = ecryptfs_decrypt_page(folio);
198 		if (err) {
199 			ecryptfs_printk(KERN_ERR, "Error decrypting page; "
200 					"err = [%d]\n", err);
201 			goto out;
202 		}
203 	}
204 out:
205 	ecryptfs_printk(KERN_DEBUG, "Unlocking folio with index = [0x%.16lx]\n",
206 			folio->index);
207 	folio_end_read(folio, err == 0);
208 	return err;
209 }
210 
211 /*
212  * Called with lower inode mutex held.
213  */
214 static int fill_zeros_to_end_of_page(struct folio *folio, unsigned int to)
215 {
216 	struct inode *inode = folio->mapping->host;
217 	int end_byte_in_page;
218 
219 	if ((i_size_read(inode) / PAGE_SIZE) != folio->index)
220 		goto out;
221 	end_byte_in_page = i_size_read(inode) % PAGE_SIZE;
222 	if (to > end_byte_in_page)
223 		end_byte_in_page = to;
224 	folio_zero_segment(folio, end_byte_in_page, PAGE_SIZE);
225 out:
226 	return 0;
227 }
228 
229 /**
230  * ecryptfs_write_begin
231  * @file: The eCryptfs file
232  * @mapping: The eCryptfs object
233  * @pos: The file offset at which to start writing
234  * @len: Length of the write
235  * @foliop: Pointer to return the folio
236  * @fsdata: Pointer to return fs data (unused)
237  *
238  * This function must zero any hole we create
239  *
240  * Returns zero on success; non-zero otherwise
241  */
242 static int ecryptfs_write_begin(struct file *file,
243 			struct address_space *mapping,
244 			loff_t pos, unsigned len,
245 			struct folio **foliop, void **fsdata)
246 {
247 	pgoff_t index = pos >> PAGE_SHIFT;
248 	struct folio *folio;
249 	loff_t prev_page_end_size;
250 	int rc = 0;
251 
252 	folio = __filemap_get_folio(mapping, index, FGP_WRITEBEGIN,
253 			mapping_gfp_mask(mapping));
254 	if (IS_ERR(folio))
255 		return PTR_ERR(folio);
256 	*foliop = folio;
257 
258 	prev_page_end_size = ((loff_t)index << PAGE_SHIFT);
259 	if (!folio_test_uptodate(folio)) {
260 		struct ecryptfs_crypt_stat *crypt_stat =
261 			&ecryptfs_inode_to_private(mapping->host)->crypt_stat;
262 
263 		if (!(crypt_stat->flags & ECRYPTFS_ENCRYPTED)) {
264 			rc = ecryptfs_read_lower_page_segment(
265 				folio, index, 0, PAGE_SIZE, mapping->host);
266 			if (rc) {
267 				printk(KERN_ERR "%s: Error attempting to read "
268 				       "lower page segment; rc = [%d]\n",
269 				       __func__, rc);
270 				folio_clear_uptodate(folio);
271 				goto out;
272 			} else
273 				folio_mark_uptodate(folio);
274 		} else if (crypt_stat->flags & ECRYPTFS_VIEW_AS_ENCRYPTED) {
275 			if (crypt_stat->flags & ECRYPTFS_METADATA_IN_XATTR) {
276 				rc = ecryptfs_copy_up_encrypted_with_header(
277 					folio, crypt_stat);
278 				if (rc) {
279 					printk(KERN_ERR "%s: Error attempting "
280 					       "to copy the encrypted content "
281 					       "from the lower file whilst "
282 					       "inserting the metadata from "
283 					       "the xattr into the header; rc "
284 					       "= [%d]\n", __func__, rc);
285 					folio_clear_uptodate(folio);
286 					goto out;
287 				}
288 				folio_mark_uptodate(folio);
289 			} else {
290 				rc = ecryptfs_read_lower_page_segment(
291 					folio, index, 0, PAGE_SIZE,
292 					mapping->host);
293 				if (rc) {
294 					printk(KERN_ERR "%s: Error reading "
295 					       "page; rc = [%d]\n",
296 					       __func__, rc);
297 					folio_clear_uptodate(folio);
298 					goto out;
299 				}
300 				folio_mark_uptodate(folio);
301 			}
302 		} else {
303 			if (prev_page_end_size
304 			    >= i_size_read(mapping->host)) {
305 				folio_zero_range(folio, 0, PAGE_SIZE);
306 				folio_mark_uptodate(folio);
307 			} else if (len < PAGE_SIZE) {
308 				rc = ecryptfs_decrypt_page(folio);
309 				if (rc) {
310 					printk(KERN_ERR "%s: Error decrypting "
311 					       "page at index [%ld]; "
312 					       "rc = [%d]\n",
313 					       __func__, folio->index, rc);
314 					folio_clear_uptodate(folio);
315 					goto out;
316 				}
317 				folio_mark_uptodate(folio);
318 			}
319 		}
320 	}
321 	/* If creating a page or more of holes, zero them out via truncate.
322 	 * Note, this will increase i_size. */
323 	if (index != 0) {
324 		if (prev_page_end_size > i_size_read(mapping->host)) {
325 			rc = ecryptfs_truncate(file->f_path.dentry,
326 					       prev_page_end_size);
327 			if (rc) {
328 				printk(KERN_ERR "%s: Error on attempt to "
329 				       "truncate to (higher) offset [%lld];"
330 				       " rc = [%d]\n", __func__,
331 				       prev_page_end_size, rc);
332 				goto out;
333 			}
334 		}
335 	}
336 	/* Writing to a new page, and creating a small hole from start
337 	 * of page?  Zero it out. */
338 	if ((i_size_read(mapping->host) == prev_page_end_size)
339 	    && (pos != 0))
340 		folio_zero_range(folio, 0, PAGE_SIZE);
341 out:
342 	if (unlikely(rc)) {
343 		folio_unlock(folio);
344 		folio_put(folio);
345 	}
346 	return rc;
347 }
348 
349 /*
350  * ecryptfs_write_inode_size_to_header
351  *
352  * Writes the lower file size to the first 8 bytes of the header.
353  *
354  * Returns zero on success; non-zero on error.
355  */
356 static int ecryptfs_write_inode_size_to_header(struct inode *ecryptfs_inode)
357 {
358 	char *file_size_virt;
359 	int rc;
360 
361 	file_size_virt = kmalloc(sizeof(u64), GFP_KERNEL);
362 	if (!file_size_virt) {
363 		rc = -ENOMEM;
364 		goto out;
365 	}
366 	put_unaligned_be64(i_size_read(ecryptfs_inode), file_size_virt);
367 	rc = ecryptfs_write_lower(ecryptfs_inode, file_size_virt, 0,
368 				  sizeof(u64));
369 	kfree(file_size_virt);
370 	if (rc < 0)
371 		printk(KERN_ERR "%s: Error writing file size to header; "
372 		       "rc = [%d]\n", __func__, rc);
373 	else
374 		rc = 0;
375 out:
376 	return rc;
377 }
378 
379 struct kmem_cache *ecryptfs_xattr_cache;
380 
381 static int ecryptfs_write_inode_size_to_xattr(struct inode *ecryptfs_inode)
382 {
383 	ssize_t size;
384 	void *xattr_virt;
385 	struct dentry *lower_dentry =
386 		ecryptfs_inode_to_private(ecryptfs_inode)->lower_file->f_path.dentry;
387 	struct inode *lower_inode = d_inode(lower_dentry);
388 	int rc;
389 
390 	if (!(lower_inode->i_opflags & IOP_XATTR)) {
391 		printk(KERN_WARNING
392 		       "No support for setting xattr in lower filesystem\n");
393 		rc = -ENOSYS;
394 		goto out;
395 	}
396 	xattr_virt = kmem_cache_alloc(ecryptfs_xattr_cache, GFP_KERNEL);
397 	if (!xattr_virt) {
398 		rc = -ENOMEM;
399 		goto out;
400 	}
401 	inode_lock(lower_inode);
402 	size = __vfs_getxattr(lower_dentry, lower_inode, ECRYPTFS_XATTR_NAME,
403 			      xattr_virt, PAGE_SIZE);
404 	if (size < 0)
405 		size = 8;
406 	put_unaligned_be64(i_size_read(ecryptfs_inode), xattr_virt);
407 	rc = __vfs_setxattr(&nop_mnt_idmap, lower_dentry, lower_inode,
408 			    ECRYPTFS_XATTR_NAME, xattr_virt, size, 0);
409 	inode_unlock(lower_inode);
410 	if (rc)
411 		printk(KERN_ERR "Error whilst attempting to write inode size "
412 		       "to lower file xattr; rc = [%d]\n", rc);
413 	kmem_cache_free(ecryptfs_xattr_cache, xattr_virt);
414 out:
415 	return rc;
416 }
417 
418 int ecryptfs_write_inode_size_to_metadata(struct inode *ecryptfs_inode)
419 {
420 	struct ecryptfs_crypt_stat *crypt_stat;
421 
422 	crypt_stat = &ecryptfs_inode_to_private(ecryptfs_inode)->crypt_stat;
423 	BUG_ON(!(crypt_stat->flags & ECRYPTFS_ENCRYPTED));
424 	if (crypt_stat->flags & ECRYPTFS_METADATA_IN_XATTR)
425 		return ecryptfs_write_inode_size_to_xattr(ecryptfs_inode);
426 	else
427 		return ecryptfs_write_inode_size_to_header(ecryptfs_inode);
428 }
429 
430 /**
431  * ecryptfs_write_end
432  * @file: The eCryptfs file object
433  * @mapping: The eCryptfs object
434  * @pos: The file position
435  * @len: The length of the data (unused)
436  * @copied: The amount of data copied
437  * @folio: The eCryptfs folio
438  * @fsdata: The fsdata (unused)
439  */
440 static int ecryptfs_write_end(struct file *file,
441 			struct address_space *mapping,
442 			loff_t pos, unsigned len, unsigned copied,
443 			struct folio *folio, void *fsdata)
444 {
445 	pgoff_t index = pos >> PAGE_SHIFT;
446 	unsigned from = pos & (PAGE_SIZE - 1);
447 	unsigned to = from + copied;
448 	struct inode *ecryptfs_inode = mapping->host;
449 	struct ecryptfs_crypt_stat *crypt_stat =
450 		&ecryptfs_inode_to_private(ecryptfs_inode)->crypt_stat;
451 	int rc;
452 
453 	ecryptfs_printk(KERN_DEBUG, "Calling fill_zeros_to_end_of_page"
454 			"(page w/ index = [0x%.16lx], to = [%d])\n", index, to);
455 	if (!(crypt_stat->flags & ECRYPTFS_ENCRYPTED)) {
456 		rc = ecryptfs_write_lower_page_segment(ecryptfs_inode,
457 				folio, 0, to);
458 		if (!rc) {
459 			rc = copied;
460 			fsstack_copy_inode_size(ecryptfs_inode,
461 				ecryptfs_inode_to_lower(ecryptfs_inode));
462 		}
463 		goto out;
464 	}
465 	if (!folio_test_uptodate(folio)) {
466 		if (copied < PAGE_SIZE) {
467 			rc = 0;
468 			goto out;
469 		}
470 		folio_mark_uptodate(folio);
471 	}
472 	/* Fills in zeros if 'to' goes beyond inode size */
473 	rc = fill_zeros_to_end_of_page(folio, to);
474 	if (rc) {
475 		ecryptfs_printk(KERN_WARNING, "Error attempting to fill "
476 			"zeros in page with index = [0x%.16lx]\n", index);
477 		goto out;
478 	}
479 	rc = ecryptfs_encrypt_page(folio);
480 	if (rc) {
481 		ecryptfs_printk(KERN_WARNING, "Error encrypting page (upper "
482 				"index [0x%.16lx])\n", index);
483 		goto out;
484 	}
485 	if (pos + copied > i_size_read(ecryptfs_inode)) {
486 		i_size_write(ecryptfs_inode, pos + copied);
487 		ecryptfs_printk(KERN_DEBUG, "Expanded file size to "
488 			"[0x%.16llx]\n",
489 			(unsigned long long)i_size_read(ecryptfs_inode));
490 	}
491 	rc = ecryptfs_write_inode_size_to_metadata(ecryptfs_inode);
492 	if (rc)
493 		printk(KERN_ERR "Error writing inode size to metadata; "
494 		       "rc = [%d]\n", rc);
495 	else
496 		rc = copied;
497 out:
498 	folio_unlock(folio);
499 	folio_put(folio);
500 	return rc;
501 }
502 
503 static sector_t ecryptfs_bmap(struct address_space *mapping, sector_t block)
504 {
505 	struct inode *lower_inode = ecryptfs_inode_to_lower(mapping->host);
506 	int ret = bmap(lower_inode, &block);
507 
508 	if (ret)
509 		return 0;
510 	return block;
511 }
512 
513 #include <linux/buffer_head.h>
514 
515 const struct address_space_operations ecryptfs_aops = {
516 	/*
517 	 * XXX: This is pretty broken for multiple reasons: ecryptfs does not
518 	 * actually use buffer_heads, and ecryptfs will crash without
519 	 * CONFIG_BLOCK.  But it matches the behavior before the default for
520 	 * address_space_operations without the ->dirty_folio method was
521 	 * cleaned up, so this is the best we can do without maintainer
522 	 * feedback.
523 	 */
524 #ifdef CONFIG_BLOCK
525 	.dirty_folio	= block_dirty_folio,
526 	.invalidate_folio = block_invalidate_folio,
527 #endif
528 	.writepages = ecryptfs_writepages,
529 	.read_folio = ecryptfs_read_folio,
530 	.write_begin = ecryptfs_write_begin,
531 	.write_end = ecryptfs_write_end,
532 	.migrate_folio = filemap_migrate_folio,
533 	.bmap = ecryptfs_bmap,
534 };
535