1 // SPDX-License-Identifier: GPL-2.0-only
3 #include <linux/fs_struct.h>
4 #include <linux/kernel_read_file.h>
5 #include <linux/security.h>
6 #include <linux/vmalloc.h>
9 * kernel_read_file() - read file contents into a kernel buffer
11 * @file file to read from
12 * @buf pointer to a "void *" buffer for reading into (if
13 * *@buf is NULL, a buffer will be allocated, and
14 * @buf_size will be ignored)
15 * @buf_size size of buf, if already allocated. If @buf not
16 * allocated, this is the largest size to allocate.
17 * @file_size if non-NULL, the full size of @file will be
19 * @id the kernel_read_file_id identifying the type of
20 * file contents being read (for LSMs to examine)
22 * Returns number of bytes read (no single read will be bigger
23 * than INT_MAX), or negative on error.
26 int kernel_read_file(struct file *file, void **buf,
27 size_t buf_size, size_t *file_size,
28 enum kernel_read_file_id id)
32 void *allocated = NULL;
35 if (!S_ISREG(file_inode(file)->i_mode))
38 ret = deny_write_access(file);
42 ret = security_kernel_read_file(file, id);
46 i_size = i_size_read(file_inode(file));
51 if (i_size > INT_MAX || i_size > buf_size) {
59 *buf = allocated = vmalloc(i_size);
66 while (pos < i_size) {
67 bytes = kernel_read(file, *buf + pos, i_size - pos, &pos);
82 ret = security_kernel_post_read_file(file, *buf, i_size, id);
93 allow_write_access(file);
94 return ret == 0 ? pos : ret;
96 EXPORT_SYMBOL_GPL(kernel_read_file);
98 int kernel_read_file_from_path(const char *path, void **buf,
99 size_t buf_size, size_t *file_size,
100 enum kernel_read_file_id id)
108 file = filp_open(path, O_RDONLY, 0);
110 return PTR_ERR(file);
112 ret = kernel_read_file(file, buf, buf_size, file_size, id);
116 EXPORT_SYMBOL_GPL(kernel_read_file_from_path);
118 int kernel_read_file_from_path_initns(const char *path, void **buf,
119 size_t buf_size, size_t *file_size,
120 enum kernel_read_file_id id)
129 task_lock(&init_task);
130 get_fs_root(init_task.fs, &root);
131 task_unlock(&init_task);
133 file = file_open_root(root.dentry, root.mnt, path, O_RDONLY, 0);
136 return PTR_ERR(file);
138 ret = kernel_read_file(file, buf, buf_size, file_size, id);
142 EXPORT_SYMBOL_GPL(kernel_read_file_from_path_initns);
144 int kernel_read_file_from_fd(int fd, void **buf, size_t buf_size,
146 enum kernel_read_file_id id)
148 struct fd f = fdget(fd);
154 ret = kernel_read_file(f.file, buf, buf_size, file_size, id);
159 EXPORT_SYMBOL_GPL(kernel_read_file_from_fd);