1// SPDX-License-Identifier: GPL-2.0-or-later
2/*
3 * eCryptfs: Linux filesystem encryption layer
4 *
5 * Copyright (C) 1997-2004 Erez Zadok
6 * Copyright (C) 2001-2004 Stony Brook University
7 * Copyright (C) 2004-2007 International Business Machines Corp.
8 *   Author(s): Michael A. Halcrow <mhalcrow@us.ibm.com>
9 *   		Michael C. Thompson <mcthomps@us.ibm.com>
10 */
11
12#include <linux/file.h>
13#include <linux/poll.h>
14#include <linux/slab.h>
15#include <linux/mount.h>
16#include <linux/pagemap.h>
17#include <linux/security.h>
18#include <linux/compat.h>
19#include <linux/fs_stack.h>
20#include "ecryptfs_kernel.h"
21
22/*
23 * ecryptfs_read_update_atime
24 *
25 * generic_file_read updates the atime of upper layer inode.  But, it
26 * doesn't give us a chance to update the atime of the lower layer
27 * inode.  This function is a wrapper to generic_file_read.  It
28 * updates the atime of the lower level inode if generic_file_read
29 * returns without any errors. This is to be used only for file reads.
30 * The function to be used for directory reads is ecryptfs_read.
31 */
32static ssize_t ecryptfs_read_update_atime(struct kiocb *iocb,
33				struct iov_iter *to)
34{
35	ssize_t rc;
36	const struct path *path;
37	struct file *file = iocb->ki_filp;
38
39	rc = generic_file_read_iter(iocb, to);
40	if (rc >= 0) {
41		path = ecryptfs_dentry_to_lower_path(file->f_path.dentry);
42		touch_atime(path);
43	}
44	return rc;
45}
46
47/*
48 * ecryptfs_splice_read_update_atime
49 *
50 * filemap_splice_read updates the atime of upper layer inode.  But, it
51 * doesn't give us a chance to update the atime of the lower layer inode.  This
52 * function is a wrapper to generic_file_read.  It updates the atime of the
53 * lower level inode if generic_file_read returns without any errors. This is
54 * to be used only for file reads.  The function to be used for directory reads
55 * is ecryptfs_read.
56 */
57static ssize_t ecryptfs_splice_read_update_atime(struct file *in, loff_t *ppos,
58						 struct pipe_inode_info *pipe,
59						 size_t len, unsigned int flags)
60{
61	ssize_t rc;
62	const struct path *path;
63
64	rc = filemap_splice_read(in, ppos, pipe, len, flags);
65	if (rc >= 0) {
66		path = ecryptfs_dentry_to_lower_path(in->f_path.dentry);
67		touch_atime(path);
68	}
69	return rc;
70}
71
72struct ecryptfs_getdents_callback {
73	struct dir_context ctx;
74	struct dir_context *caller;
75	struct super_block *sb;
76	int filldir_called;
77	int entries_written;
78};
79
80/* Inspired by generic filldir in fs/readdir.c */
81static bool
82ecryptfs_filldir(struct dir_context *ctx, const char *lower_name,
83		 int lower_namelen, loff_t offset, u64 ino, unsigned int d_type)
84{
85	struct ecryptfs_getdents_callback *buf =
86		container_of(ctx, struct ecryptfs_getdents_callback, ctx);
87	size_t name_size;
88	char *name;
89	int err;
90	bool res;
91
92	buf->filldir_called++;
93	err = ecryptfs_decode_and_decrypt_filename(&name, &name_size,
94						   buf->sb, lower_name,
95						   lower_namelen);
96	if (err) {
97		if (err != -EINVAL) {
98			ecryptfs_printk(KERN_DEBUG,
99					"%s: Error attempting to decode and decrypt filename [%s]; rc = [%d]\n",
100					__func__, lower_name, err);
101			return false;
102		}
103
104		/* Mask -EINVAL errors as these are most likely due a plaintext
105		 * filename present in the lower filesystem despite filename
106		 * encryption being enabled. One unavoidable example would be
107		 * the "lost+found" dentry in the root directory of an Ext4
108		 * filesystem.
109		 */
110		return true;
111	}
112
113	buf->caller->pos = buf->ctx.pos;
114	res = dir_emit(buf->caller, name, name_size, ino, d_type);
115	kfree(name);
116	if (res)
117		buf->entries_written++;
118	return res;
119}
120
121/**
122 * ecryptfs_readdir
123 * @file: The eCryptfs directory file
124 * @ctx: The actor to feed the entries to
125 */
126static int ecryptfs_readdir(struct file *file, struct dir_context *ctx)
127{
128	int rc;
129	struct file *lower_file;
130	struct inode *inode = file_inode(file);
131	struct ecryptfs_getdents_callback buf = {
132		.ctx.actor = ecryptfs_filldir,
133		.caller = ctx,
134		.sb = inode->i_sb,
135	};
136	lower_file = ecryptfs_file_to_lower(file);
137	rc = iterate_dir(lower_file, &buf.ctx);
138	ctx->pos = buf.ctx.pos;
139	if (rc >= 0 && (buf.entries_written || !buf.filldir_called))
140		fsstack_copy_attr_atime(inode, file_inode(lower_file));
141	return rc;
142}
143
144struct kmem_cache *ecryptfs_file_info_cache;
145
146static int read_or_initialize_metadata(struct dentry *dentry)
147{
148	struct inode *inode = d_inode(dentry);
149	struct ecryptfs_mount_crypt_stat *mount_crypt_stat;
150	struct ecryptfs_crypt_stat *crypt_stat;
151	int rc;
152
153	crypt_stat = &ecryptfs_inode_to_private(inode)->crypt_stat;
154	mount_crypt_stat = &ecryptfs_superblock_to_private(
155						inode->i_sb)->mount_crypt_stat;
156	mutex_lock(&crypt_stat->cs_mutex);
157
158	if (crypt_stat->flags & ECRYPTFS_POLICY_APPLIED &&
159	    crypt_stat->flags & ECRYPTFS_KEY_VALID) {
160		rc = 0;
161		goto out;
162	}
163
164	rc = ecryptfs_read_metadata(dentry);
165	if (!rc)
166		goto out;
167
168	if (mount_crypt_stat->flags & ECRYPTFS_PLAINTEXT_PASSTHROUGH_ENABLED) {
169		crypt_stat->flags &= ~(ECRYPTFS_I_SIZE_INITIALIZED
170				       | ECRYPTFS_ENCRYPTED);
171		rc = 0;
172		goto out;
173	}
174
175	if (!(mount_crypt_stat->flags & ECRYPTFS_XATTR_METADATA_ENABLED) &&
176	    !i_size_read(ecryptfs_inode_to_lower(inode))) {
177		rc = ecryptfs_initialize_file(dentry, inode);
178		if (!rc)
179			goto out;
180	}
181
182	rc = -EIO;
183out:
184	mutex_unlock(&crypt_stat->cs_mutex);
185	return rc;
186}
187
188static int ecryptfs_mmap(struct file *file, struct vm_area_struct *vma)
189{
190	struct file *lower_file = ecryptfs_file_to_lower(file);
191	/*
192	 * Don't allow mmap on top of file systems that don't support it
193	 * natively.  If FILESYSTEM_MAX_STACK_DEPTH > 2 or ecryptfs
194	 * allows recursive mounting, this will need to be extended.
195	 */
196	if (!lower_file->f_op->mmap)
197		return -ENODEV;
198	return generic_file_mmap(file, vma);
199}
200
201/**
202 * ecryptfs_open
203 * @inode: inode specifying file to open
204 * @file: Structure to return filled in
205 *
206 * Opens the file specified by inode.
207 *
208 * Returns zero on success; non-zero otherwise
209 */
210static int ecryptfs_open(struct inode *inode, struct file *file)
211{
212	int rc = 0;
213	struct ecryptfs_crypt_stat *crypt_stat = NULL;
214	struct dentry *ecryptfs_dentry = file->f_path.dentry;
215	/* Private value of ecryptfs_dentry allocated in
216	 * ecryptfs_lookup() */
217	struct ecryptfs_file_info *file_info;
218
219	/* Released in ecryptfs_release or end of function if failure */
220	file_info = kmem_cache_zalloc(ecryptfs_file_info_cache, GFP_KERNEL);
221	ecryptfs_set_file_private(file, file_info);
222	if (!file_info) {
223		ecryptfs_printk(KERN_ERR,
224				"Error attempting to allocate memory\n");
225		rc = -ENOMEM;
226		goto out;
227	}
228	crypt_stat = &ecryptfs_inode_to_private(inode)->crypt_stat;
229	mutex_lock(&crypt_stat->cs_mutex);
230	if (!(crypt_stat->flags & ECRYPTFS_POLICY_APPLIED)) {
231		ecryptfs_printk(KERN_DEBUG, "Setting flags for stat...\n");
232		/* Policy code enabled in future release */
233		crypt_stat->flags |= (ECRYPTFS_POLICY_APPLIED
234				      | ECRYPTFS_ENCRYPTED);
235	}
236	mutex_unlock(&crypt_stat->cs_mutex);
237	rc = ecryptfs_get_lower_file(ecryptfs_dentry, inode);
238	if (rc) {
239		printk(KERN_ERR "%s: Error attempting to initialize "
240			"the lower file for the dentry with name "
241			"[%pd]; rc = [%d]\n", __func__,
242			ecryptfs_dentry, rc);
243		goto out_free;
244	}
245	if ((ecryptfs_inode_to_private(inode)->lower_file->f_flags & O_ACCMODE)
246	    == O_RDONLY && (file->f_flags & O_ACCMODE) != O_RDONLY) {
247		rc = -EPERM;
248		printk(KERN_WARNING "%s: Lower file is RO; eCryptfs "
249		       "file must hence be opened RO\n", __func__);
250		goto out_put;
251	}
252	ecryptfs_set_file_lower(
253		file, ecryptfs_inode_to_private(inode)->lower_file);
254	rc = read_or_initialize_metadata(ecryptfs_dentry);
255	if (rc)
256		goto out_put;
257	ecryptfs_printk(KERN_DEBUG, "inode w/ addr = [0x%p], i_ino = "
258			"[0x%.16lx] size: [0x%.16llx]\n", inode, inode->i_ino,
259			(unsigned long long)i_size_read(inode));
260	goto out;
261out_put:
262	ecryptfs_put_lower_file(inode);
263out_free:
264	kmem_cache_free(ecryptfs_file_info_cache,
265			ecryptfs_file_to_private(file));
266out:
267	return rc;
268}
269
270/**
271 * ecryptfs_dir_open
272 * @inode: inode specifying file to open
273 * @file: Structure to return filled in
274 *
275 * Opens the file specified by inode.
276 *
277 * Returns zero on success; non-zero otherwise
278 */
279static int ecryptfs_dir_open(struct inode *inode, struct file *file)
280{
281	struct dentry *ecryptfs_dentry = file->f_path.dentry;
282	/* Private value of ecryptfs_dentry allocated in
283	 * ecryptfs_lookup() */
284	struct ecryptfs_file_info *file_info;
285	struct file *lower_file;
286
287	/* Released in ecryptfs_release or end of function if failure */
288	file_info = kmem_cache_zalloc(ecryptfs_file_info_cache, GFP_KERNEL);
289	ecryptfs_set_file_private(file, file_info);
290	if (unlikely(!file_info)) {
291		ecryptfs_printk(KERN_ERR,
292				"Error attempting to allocate memory\n");
293		return -ENOMEM;
294	}
295	lower_file = dentry_open(ecryptfs_dentry_to_lower_path(ecryptfs_dentry),
296				 file->f_flags, current_cred());
297	if (IS_ERR(lower_file)) {
298		printk(KERN_ERR "%s: Error attempting to initialize "
299			"the lower file for the dentry with name "
300			"[%pd]; rc = [%ld]\n", __func__,
301			ecryptfs_dentry, PTR_ERR(lower_file));
302		kmem_cache_free(ecryptfs_file_info_cache, file_info);
303		return PTR_ERR(lower_file);
304	}
305	ecryptfs_set_file_lower(file, lower_file);
306	return 0;
307}
308
309static int ecryptfs_flush(struct file *file, fl_owner_t td)
310{
311	struct file *lower_file = ecryptfs_file_to_lower(file);
312
313	if (lower_file->f_op->flush) {
314		filemap_write_and_wait(file->f_mapping);
315		return lower_file->f_op->flush(lower_file, td);
316	}
317
318	return 0;
319}
320
321static int ecryptfs_release(struct inode *inode, struct file *file)
322{
323	ecryptfs_put_lower_file(inode);
324	kmem_cache_free(ecryptfs_file_info_cache,
325			ecryptfs_file_to_private(file));
326	return 0;
327}
328
329static int ecryptfs_dir_release(struct inode *inode, struct file *file)
330{
331	fput(ecryptfs_file_to_lower(file));
332	kmem_cache_free(ecryptfs_file_info_cache,
333			ecryptfs_file_to_private(file));
334	return 0;
335}
336
337static loff_t ecryptfs_dir_llseek(struct file *file, loff_t offset, int whence)
338{
339	return vfs_llseek(ecryptfs_file_to_lower(file), offset, whence);
340}
341
342static int
343ecryptfs_fsync(struct file *file, loff_t start, loff_t end, int datasync)
344{
345	int rc;
346
347	rc = file_write_and_wait(file);
348	if (rc)
349		return rc;
350
351	return vfs_fsync(ecryptfs_file_to_lower(file), datasync);
352}
353
354static int ecryptfs_fasync(int fd, struct file *file, int flag)
355{
356	int rc = 0;
357	struct file *lower_file = NULL;
358
359	lower_file = ecryptfs_file_to_lower(file);
360	if (lower_file->f_op->fasync)
361		rc = lower_file->f_op->fasync(fd, lower_file, flag);
362	return rc;
363}
364
365static long
366ecryptfs_unlocked_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
367{
368	struct file *lower_file = ecryptfs_file_to_lower(file);
369	long rc = -ENOTTY;
370
371	if (!lower_file->f_op->unlocked_ioctl)
372		return rc;
373
374	switch (cmd) {
375	case FITRIM:
376	case FS_IOC_GETFLAGS:
377	case FS_IOC_SETFLAGS:
378	case FS_IOC_GETVERSION:
379	case FS_IOC_SETVERSION:
380		rc = lower_file->f_op->unlocked_ioctl(lower_file, cmd, arg);
381		fsstack_copy_attr_all(file_inode(file), file_inode(lower_file));
382
383		return rc;
384	default:
385		return rc;
386	}
387}
388
389#ifdef CONFIG_COMPAT
390static long
391ecryptfs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
392{
393	struct file *lower_file = ecryptfs_file_to_lower(file);
394	long rc = -ENOIOCTLCMD;
395
396	if (!lower_file->f_op->compat_ioctl)
397		return rc;
398
399	switch (cmd) {
400	case FITRIM:
401	case FS_IOC32_GETFLAGS:
402	case FS_IOC32_SETFLAGS:
403	case FS_IOC32_GETVERSION:
404	case FS_IOC32_SETVERSION:
405		rc = lower_file->f_op->compat_ioctl(lower_file, cmd, arg);
406		fsstack_copy_attr_all(file_inode(file), file_inode(lower_file));
407
408		return rc;
409	default:
410		return rc;
411	}
412}
413#endif
414
415const struct file_operations ecryptfs_dir_fops = {
416	.iterate_shared = ecryptfs_readdir,
417	.read = generic_read_dir,
418	.unlocked_ioctl = ecryptfs_unlocked_ioctl,
419#ifdef CONFIG_COMPAT
420	.compat_ioctl = ecryptfs_compat_ioctl,
421#endif
422	.open = ecryptfs_dir_open,
423	.release = ecryptfs_dir_release,
424	.fsync = ecryptfs_fsync,
425	.llseek = ecryptfs_dir_llseek,
426};
427
428const struct file_operations ecryptfs_main_fops = {
429	.llseek = generic_file_llseek,
430	.read_iter = ecryptfs_read_update_atime,
431	.write_iter = generic_file_write_iter,
432	.unlocked_ioctl = ecryptfs_unlocked_ioctl,
433#ifdef CONFIG_COMPAT
434	.compat_ioctl = ecryptfs_compat_ioctl,
435#endif
436	.mmap = ecryptfs_mmap,
437	.open = ecryptfs_open,
438	.flush = ecryptfs_flush,
439	.release = ecryptfs_release,
440	.fsync = ecryptfs_fsync,
441	.fasync = ecryptfs_fasync,
442	.splice_read = ecryptfs_splice_read_update_atime,
443};
444