1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Module and Firmware Pinning Security Module
4  *
5  * Copyright 2011-2016 Google Inc.
6  *
7  * Author: Kees Cook <keescook@chromium.org>
8  */
9 
10 #define pr_fmt(fmt) "LoadPin: " fmt
11 
12 #include <linux/module.h>
13 #include <linux/fs.h>
14 #include <linux/kernel_read_file.h>
15 #include <linux/lsm_hooks.h>
16 #include <linux/mount.h>
17 #include <linux/blkdev.h>
18 #include <linux/path.h>
19 #include <linux/sched.h>	/* current */
20 #include <linux/string_helpers.h>
21 #include <linux/dm-verity-loadpin.h>
22 #include <uapi/linux/loadpin.h>
23 
24 #define VERITY_DIGEST_FILE_HEADER "# LOADPIN_TRUSTED_VERITY_ROOT_DIGESTS"
25 
report_load(const char * origin,struct file * file,char * operation)26 static void report_load(const char *origin, struct file *file, char *operation)
27 {
28 	char *cmdline, *pathname;
29 
30 	pathname = kstrdup_quotable_file(file, GFP_KERNEL);
31 	cmdline = kstrdup_quotable_cmdline(current, GFP_KERNEL);
32 
33 	pr_notice("%s %s obj=%s%s%s pid=%d cmdline=%s%s%s\n",
34 		  origin, operation,
35 		  (pathname && pathname[0] != '<') ? "\"" : "",
36 		  pathname,
37 		  (pathname && pathname[0] != '<') ? "\"" : "",
38 		  task_pid_nr(current),
39 		  cmdline ? "\"" : "", cmdline, cmdline ? "\"" : "");
40 
41 	kfree(cmdline);
42 	kfree(pathname);
43 }
44 
45 static int enforce = IS_ENABLED(CONFIG_SECURITY_LOADPIN_ENFORCE);
46 static char *exclude_read_files[READING_MAX_ID];
47 static int ignore_read_file_id[READING_MAX_ID] __ro_after_init;
48 static struct super_block *pinned_root;
49 static DEFINE_SPINLOCK(pinned_root_spinlock);
50 #ifdef CONFIG_SECURITY_LOADPIN_VERITY
51 static bool deny_reading_verity_digests;
52 #endif
53 
54 #ifdef CONFIG_SYSCTL
55 
56 static struct ctl_path loadpin_sysctl_path[] = {
57 	{ .procname = "kernel", },
58 	{ .procname = "loadpin", },
59 	{ }
60 };
61 
62 static struct ctl_table loadpin_sysctl_table[] = {
63 	{
64 		.procname       = "enforce",
65 		.data           = &enforce,
66 		.maxlen         = sizeof(int),
67 		.mode           = 0644,
68 		.proc_handler   = proc_dointvec_minmax,
69 		.extra1         = SYSCTL_ZERO,
70 		.extra2         = SYSCTL_ONE,
71 	},
72 	{ }
73 };
74 
75 /*
76  * This must be called after early kernel init, since then the rootdev
77  * is available.
78  */
check_pinning_enforcement(struct super_block * mnt_sb)79 static void check_pinning_enforcement(struct super_block *mnt_sb)
80 {
81 	bool ro = false;
82 
83 	/*
84 	 * If load pinning is not enforced via a read-only block
85 	 * device, allow sysctl to change modes for testing.
86 	 */
87 	if (mnt_sb->s_bdev) {
88 		ro = bdev_read_only(mnt_sb->s_bdev);
89 		pr_info("%pg (%u:%u): %s\n", mnt_sb->s_bdev,
90 			MAJOR(mnt_sb->s_bdev->bd_dev),
91 			MINOR(mnt_sb->s_bdev->bd_dev),
92 			ro ? "read-only" : "writable");
93 	} else
94 		pr_info("mnt_sb lacks block device, treating as: writable\n");
95 
96 	if (!ro) {
97 		if (!register_sysctl_paths(loadpin_sysctl_path,
98 					   loadpin_sysctl_table))
99 			pr_notice("sysctl registration failed!\n");
100 		else
101 			pr_info("enforcement can be disabled.\n");
102 	} else
103 		pr_info("load pinning engaged.\n");
104 }
105 #else
check_pinning_enforcement(struct super_block * mnt_sb)106 static void check_pinning_enforcement(struct super_block *mnt_sb)
107 {
108 	pr_info("load pinning engaged.\n");
109 }
110 #endif
111 
loadpin_sb_free_security(struct super_block * mnt_sb)112 static void loadpin_sb_free_security(struct super_block *mnt_sb)
113 {
114 	/*
115 	 * When unmounting the filesystem we were using for load
116 	 * pinning, we acknowledge the superblock release, but make sure
117 	 * no other modules or firmware can be loaded.
118 	 */
119 	if (!IS_ERR_OR_NULL(pinned_root) && mnt_sb == pinned_root) {
120 		pinned_root = ERR_PTR(-EIO);
121 		pr_info("umount pinned fs: refusing further loads\n");
122 	}
123 }
124 
loadpin_check(struct file * file,enum kernel_read_file_id id)125 static int loadpin_check(struct file *file, enum kernel_read_file_id id)
126 {
127 	struct super_block *load_root;
128 	const char *origin = kernel_read_file_id_str(id);
129 
130 	/* If the file id is excluded, ignore the pinning. */
131 	if ((unsigned int)id < ARRAY_SIZE(ignore_read_file_id) &&
132 	    ignore_read_file_id[id]) {
133 		report_load(origin, file, "pinning-excluded");
134 		return 0;
135 	}
136 
137 	/* This handles the older init_module API that has a NULL file. */
138 	if (!file) {
139 		if (!enforce) {
140 			report_load(origin, NULL, "old-api-pinning-ignored");
141 			return 0;
142 		}
143 
144 		report_load(origin, NULL, "old-api-denied");
145 		return -EPERM;
146 	}
147 
148 	load_root = file->f_path.mnt->mnt_sb;
149 
150 	/* First loaded module/firmware defines the root for all others. */
151 	spin_lock(&pinned_root_spinlock);
152 	/*
153 	 * pinned_root is only NULL at startup. Otherwise, it is either
154 	 * a valid reference, or an ERR_PTR.
155 	 */
156 	if (!pinned_root) {
157 		pinned_root = load_root;
158 		/*
159 		 * Unlock now since it's only pinned_root we care about.
160 		 * In the worst case, we will (correctly) report pinning
161 		 * failures before we have announced that pinning is
162 		 * enforcing. This would be purely cosmetic.
163 		 */
164 		spin_unlock(&pinned_root_spinlock);
165 		check_pinning_enforcement(pinned_root);
166 		report_load(origin, file, "pinned");
167 	} else {
168 		spin_unlock(&pinned_root_spinlock);
169 	}
170 
171 	if (IS_ERR_OR_NULL(pinned_root) ||
172 	    ((load_root != pinned_root) && !dm_verity_loadpin_is_bdev_trusted(load_root->s_bdev))) {
173 		if (unlikely(!enforce)) {
174 			report_load(origin, file, "pinning-ignored");
175 			return 0;
176 		}
177 
178 		report_load(origin, file, "denied");
179 		return -EPERM;
180 	}
181 
182 	return 0;
183 }
184 
loadpin_read_file(struct file * file,enum kernel_read_file_id id,bool contents)185 static int loadpin_read_file(struct file *file, enum kernel_read_file_id id,
186 			     bool contents)
187 {
188 	/*
189 	 * LoadPin only cares about the _origin_ of a file, not its
190 	 * contents, so we can ignore the "are full contents available"
191 	 * argument here.
192 	 */
193 	return loadpin_check(file, id);
194 }
195 
loadpin_load_data(enum kernel_load_data_id id,bool contents)196 static int loadpin_load_data(enum kernel_load_data_id id, bool contents)
197 {
198 	/*
199 	 * LoadPin only cares about the _origin_ of a file, not its
200 	 * contents, so a NULL file is passed, and we can ignore the
201 	 * state of "contents".
202 	 */
203 	return loadpin_check(NULL, (enum kernel_read_file_id) id);
204 }
205 
206 static struct security_hook_list loadpin_hooks[] __lsm_ro_after_init = {
207 	LSM_HOOK_INIT(sb_free_security, loadpin_sb_free_security),
208 	LSM_HOOK_INIT(kernel_read_file, loadpin_read_file),
209 	LSM_HOOK_INIT(kernel_load_data, loadpin_load_data),
210 };
211 
parse_exclude(void)212 static void __init parse_exclude(void)
213 {
214 	int i, j;
215 	char *cur;
216 
217 	/*
218 	 * Make sure all the arrays stay within expected sizes. This
219 	 * is slightly weird because kernel_read_file_str[] includes
220 	 * READING_MAX_ID, which isn't actually meaningful here.
221 	 */
222 	BUILD_BUG_ON(ARRAY_SIZE(exclude_read_files) !=
223 		     ARRAY_SIZE(ignore_read_file_id));
224 	BUILD_BUG_ON(ARRAY_SIZE(kernel_read_file_str) <
225 		     ARRAY_SIZE(ignore_read_file_id));
226 
227 	for (i = 0; i < ARRAY_SIZE(exclude_read_files); i++) {
228 		cur = exclude_read_files[i];
229 		if (!cur)
230 			break;
231 		if (*cur == '\0')
232 			continue;
233 
234 		for (j = 0; j < ARRAY_SIZE(ignore_read_file_id); j++) {
235 			if (strcmp(cur, kernel_read_file_str[j]) == 0) {
236 				pr_info("excluding: %s\n",
237 					kernel_read_file_str[j]);
238 				ignore_read_file_id[j] = 1;
239 				/*
240 				 * Can not break, because one read_file_str
241 				 * may map to more than on read_file_id.
242 				 */
243 			}
244 		}
245 	}
246 }
247 
loadpin_init(void)248 static int __init loadpin_init(void)
249 {
250 	pr_info("ready to pin (currently %senforcing)\n",
251 		enforce ? "" : "not ");
252 	parse_exclude();
253 	security_add_hooks(loadpin_hooks, ARRAY_SIZE(loadpin_hooks), "loadpin");
254 
255 	return 0;
256 }
257 
258 DEFINE_LSM(loadpin) = {
259 	.name = "loadpin",
260 	.init = loadpin_init,
261 };
262 
263 #ifdef CONFIG_SECURITY_LOADPIN_VERITY
264 
265 enum loadpin_securityfs_interface_index {
266 	LOADPIN_DM_VERITY,
267 };
268 
read_trusted_verity_root_digests(unsigned int fd)269 static int read_trusted_verity_root_digests(unsigned int fd)
270 {
271 	struct fd f;
272 	void *data;
273 	int rc;
274 	char *p, *d;
275 
276 	if (deny_reading_verity_digests)
277 		return -EPERM;
278 
279 	/* The list of trusted root digests can only be set up once */
280 	if (!list_empty(&dm_verity_loadpin_trusted_root_digests))
281 		return -EPERM;
282 
283 	f = fdget(fd);
284 	if (!f.file)
285 		return -EINVAL;
286 
287 	data = kzalloc(SZ_4K, GFP_KERNEL);
288 	if (!data) {
289 		rc = -ENOMEM;
290 		goto err;
291 	}
292 
293 	rc = kernel_read_file(f.file, 0, (void **)&data, SZ_4K - 1, NULL, READING_POLICY);
294 	if (rc < 0)
295 		goto err;
296 
297 	p = data;
298 	p[rc] = '\0';
299 	p = strim(p);
300 
301 	p = strim(data);
302 	while ((d = strsep(&p, "\n")) != NULL) {
303 		int len;
304 		struct dm_verity_loadpin_trusted_root_digest *trd;
305 
306 		if (d == data) {
307 			/* first line, validate header */
308 			if (strcmp(d, VERITY_DIGEST_FILE_HEADER)) {
309 				rc = -EPROTO;
310 				goto err;
311 			}
312 
313 			continue;
314 		}
315 
316 		len = strlen(d);
317 
318 		if (len % 2) {
319 			rc = -EPROTO;
320 			goto err;
321 		}
322 
323 		len /= 2;
324 
325 		trd = kzalloc(struct_size(trd, data, len), GFP_KERNEL);
326 		if (!trd) {
327 			rc = -ENOMEM;
328 			goto err;
329 		}
330 
331 		if (hex2bin(trd->data, d, len)) {
332 			kfree(trd);
333 			rc = -EPROTO;
334 			goto err;
335 		}
336 
337 		trd->len = len;
338 
339 		list_add_tail(&trd->node, &dm_verity_loadpin_trusted_root_digests);
340 	}
341 
342 	if (list_empty(&dm_verity_loadpin_trusted_root_digests)) {
343 		rc = -EPROTO;
344 		goto err;
345 	}
346 
347 	kfree(data);
348 	fdput(f);
349 
350 	return 0;
351 
352 err:
353 	kfree(data);
354 
355 	/* any failure in loading/parsing invalidates the entire list */
356 	{
357 		struct dm_verity_loadpin_trusted_root_digest *trd, *tmp;
358 
359 		list_for_each_entry_safe(trd, tmp, &dm_verity_loadpin_trusted_root_digests, node) {
360 			list_del(&trd->node);
361 			kfree(trd);
362 		}
363 	}
364 
365 	/* disallow further attempts after reading a corrupt/invalid file */
366 	deny_reading_verity_digests = true;
367 
368 	fdput(f);
369 
370 	return rc;
371 }
372 
373 /******************************** securityfs ********************************/
374 
dm_verity_ioctl(struct file * filp,unsigned int cmd,unsigned long arg)375 static long dm_verity_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
376 {
377 	void __user *uarg = (void __user *)arg;
378 	unsigned int fd;
379 
380 	switch (cmd) {
381 	case LOADPIN_IOC_SET_TRUSTED_VERITY_DIGESTS:
382 		if (copy_from_user(&fd, uarg, sizeof(fd)))
383 			return -EFAULT;
384 
385 		return read_trusted_verity_root_digests(fd);
386 
387 	default:
388 		return -EINVAL;
389 	}
390 }
391 
392 static const struct file_operations loadpin_dm_verity_ops = {
393 	.unlocked_ioctl = dm_verity_ioctl,
394 	.compat_ioctl = compat_ptr_ioctl,
395 };
396 
397 /**
398  * init_loadpin_securityfs - create the securityfs directory for LoadPin
399  *
400  * We can not put this method normally under the loadpin_init() code path since
401  * the security subsystem gets initialized before the vfs caches.
402  *
403  * Returns 0 if the securityfs directory creation was successful.
404  */
init_loadpin_securityfs(void)405 static int __init init_loadpin_securityfs(void)
406 {
407 	struct dentry *loadpin_dir, *dentry;
408 
409 	loadpin_dir = securityfs_create_dir("loadpin", NULL);
410 	if (IS_ERR(loadpin_dir)) {
411 		pr_err("LoadPin: could not create securityfs dir: %ld\n",
412 		       PTR_ERR(loadpin_dir));
413 		return PTR_ERR(loadpin_dir);
414 	}
415 
416 	dentry = securityfs_create_file("dm-verity", 0600, loadpin_dir,
417 					(void *)LOADPIN_DM_VERITY, &loadpin_dm_verity_ops);
418 	if (IS_ERR(dentry)) {
419 		pr_err("LoadPin: could not create securityfs entry 'dm-verity': %ld\n",
420 		       PTR_ERR(dentry));
421 		return PTR_ERR(dentry);
422 	}
423 
424 	return 0;
425 }
426 
427 fs_initcall(init_loadpin_securityfs);
428 
429 #endif /* CONFIG_SECURITY_LOADPIN_VERITY */
430 
431 /* Should not be mutable after boot, so not listed in sysfs (perm == 0). */
432 module_param(enforce, int, 0);
433 MODULE_PARM_DESC(enforce, "Enforce module/firmware pinning");
434 module_param_array_named(exclude, exclude_read_files, charp, NULL, 0);
435 MODULE_PARM_DESC(exclude, "Exclude pinning specific read file types");
436