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