xref: /openbmc/linux/security/loadpin/loadpin.c (revision 6c8c1406)
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 
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  */
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
106 static void check_pinning_enforcement(struct super_block *mnt_sb)
107 {
108 	pr_info("load pinning engaged.\n");
109 }
110 #endif
111 
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 
125 static int loadpin_read_file(struct file *file, enum kernel_read_file_id id,
126 			     bool contents)
127 {
128 	struct super_block *load_root;
129 	const char *origin = kernel_read_file_id_str(id);
130 
131 	/*
132 	 * If we will not know that we'll be seeing the full contents
133 	 * then we cannot trust a load will be complete and unchanged
134 	 * off disk. Treat all contents=false hooks as if there were
135 	 * no associated file struct.
136 	 */
137 	if (!contents)
138 		file = NULL;
139 
140 	/* If the file id is excluded, ignore the pinning. */
141 	if ((unsigned int)id < ARRAY_SIZE(ignore_read_file_id) &&
142 	    ignore_read_file_id[id]) {
143 		report_load(origin, file, "pinning-excluded");
144 		return 0;
145 	}
146 
147 	/* This handles the older init_module API that has a NULL file. */
148 	if (!file) {
149 		if (!enforce) {
150 			report_load(origin, NULL, "old-api-pinning-ignored");
151 			return 0;
152 		}
153 
154 		report_load(origin, NULL, "old-api-denied");
155 		return -EPERM;
156 	}
157 
158 	load_root = file->f_path.mnt->mnt_sb;
159 
160 	/* First loaded module/firmware defines the root for all others. */
161 	spin_lock(&pinned_root_spinlock);
162 	/*
163 	 * pinned_root is only NULL at startup. Otherwise, it is either
164 	 * a valid reference, or an ERR_PTR.
165 	 */
166 	if (!pinned_root) {
167 		pinned_root = load_root;
168 		/*
169 		 * Unlock now since it's only pinned_root we care about.
170 		 * In the worst case, we will (correctly) report pinning
171 		 * failures before we have announced that pinning is
172 		 * enforcing. This would be purely cosmetic.
173 		 */
174 		spin_unlock(&pinned_root_spinlock);
175 		check_pinning_enforcement(pinned_root);
176 		report_load(origin, file, "pinned");
177 	} else {
178 		spin_unlock(&pinned_root_spinlock);
179 	}
180 
181 	if (IS_ERR_OR_NULL(pinned_root) ||
182 	    ((load_root != pinned_root) && !dm_verity_loadpin_is_bdev_trusted(load_root->s_bdev))) {
183 		if (unlikely(!enforce)) {
184 			report_load(origin, file, "pinning-ignored");
185 			return 0;
186 		}
187 
188 		report_load(origin, file, "denied");
189 		return -EPERM;
190 	}
191 
192 	return 0;
193 }
194 
195 static int loadpin_load_data(enum kernel_load_data_id id, bool contents)
196 {
197 	return loadpin_read_file(NULL, (enum kernel_read_file_id) id, contents);
198 }
199 
200 static struct security_hook_list loadpin_hooks[] __lsm_ro_after_init = {
201 	LSM_HOOK_INIT(sb_free_security, loadpin_sb_free_security),
202 	LSM_HOOK_INIT(kernel_read_file, loadpin_read_file),
203 	LSM_HOOK_INIT(kernel_load_data, loadpin_load_data),
204 };
205 
206 static void __init parse_exclude(void)
207 {
208 	int i, j;
209 	char *cur;
210 
211 	/*
212 	 * Make sure all the arrays stay within expected sizes. This
213 	 * is slightly weird because kernel_read_file_str[] includes
214 	 * READING_MAX_ID, which isn't actually meaningful here.
215 	 */
216 	BUILD_BUG_ON(ARRAY_SIZE(exclude_read_files) !=
217 		     ARRAY_SIZE(ignore_read_file_id));
218 	BUILD_BUG_ON(ARRAY_SIZE(kernel_read_file_str) <
219 		     ARRAY_SIZE(ignore_read_file_id));
220 
221 	for (i = 0; i < ARRAY_SIZE(exclude_read_files); i++) {
222 		cur = exclude_read_files[i];
223 		if (!cur)
224 			break;
225 		if (*cur == '\0')
226 			continue;
227 
228 		for (j = 0; j < ARRAY_SIZE(ignore_read_file_id); j++) {
229 			if (strcmp(cur, kernel_read_file_str[j]) == 0) {
230 				pr_info("excluding: %s\n",
231 					kernel_read_file_str[j]);
232 				ignore_read_file_id[j] = 1;
233 				/*
234 				 * Can not break, because one read_file_str
235 				 * may map to more than on read_file_id.
236 				 */
237 			}
238 		}
239 	}
240 }
241 
242 static int __init loadpin_init(void)
243 {
244 	pr_info("ready to pin (currently %senforcing)\n",
245 		enforce ? "" : "not ");
246 	parse_exclude();
247 	security_add_hooks(loadpin_hooks, ARRAY_SIZE(loadpin_hooks), "loadpin");
248 
249 	return 0;
250 }
251 
252 DEFINE_LSM(loadpin) = {
253 	.name = "loadpin",
254 	.init = loadpin_init,
255 };
256 
257 #ifdef CONFIG_SECURITY_LOADPIN_VERITY
258 
259 enum loadpin_securityfs_interface_index {
260 	LOADPIN_DM_VERITY,
261 };
262 
263 static int read_trusted_verity_root_digests(unsigned int fd)
264 {
265 	struct fd f;
266 	void *data;
267 	int rc;
268 	char *p, *d;
269 
270 	if (deny_reading_verity_digests)
271 		return -EPERM;
272 
273 	/* The list of trusted root digests can only be set up once */
274 	if (!list_empty(&dm_verity_loadpin_trusted_root_digests))
275 		return -EPERM;
276 
277 	f = fdget(fd);
278 	if (!f.file)
279 		return -EINVAL;
280 
281 	data = kzalloc(SZ_4K, GFP_KERNEL);
282 	if (!data) {
283 		rc = -ENOMEM;
284 		goto err;
285 	}
286 
287 	rc = kernel_read_file(f.file, 0, (void **)&data, SZ_4K - 1, NULL, READING_POLICY);
288 	if (rc < 0)
289 		goto err;
290 
291 	p = data;
292 	p[rc] = '\0';
293 	p = strim(p);
294 
295 	p = strim(data);
296 	while ((d = strsep(&p, "\n")) != NULL) {
297 		int len;
298 		struct dm_verity_loadpin_trusted_root_digest *trd;
299 
300 		if (d == data) {
301 			/* first line, validate header */
302 			if (strcmp(d, VERITY_DIGEST_FILE_HEADER)) {
303 				rc = -EPROTO;
304 				goto err;
305 			}
306 
307 			continue;
308 		}
309 
310 		len = strlen(d);
311 
312 		if (len % 2) {
313 			rc = -EPROTO;
314 			goto err;
315 		}
316 
317 		len /= 2;
318 
319 		trd = kzalloc(struct_size(trd, data, len), GFP_KERNEL);
320 		if (!trd) {
321 			rc = -ENOMEM;
322 			goto err;
323 		}
324 
325 		if (hex2bin(trd->data, d, len)) {
326 			kfree(trd);
327 			rc = -EPROTO;
328 			goto err;
329 		}
330 
331 		trd->len = len;
332 
333 		list_add_tail(&trd->node, &dm_verity_loadpin_trusted_root_digests);
334 	}
335 
336 	if (list_empty(&dm_verity_loadpin_trusted_root_digests)) {
337 		rc = -EPROTO;
338 		goto err;
339 	}
340 
341 	kfree(data);
342 	fdput(f);
343 
344 	return 0;
345 
346 err:
347 	kfree(data);
348 
349 	/* any failure in loading/parsing invalidates the entire list */
350 	{
351 		struct dm_verity_loadpin_trusted_root_digest *trd, *tmp;
352 
353 		list_for_each_entry_safe(trd, tmp, &dm_verity_loadpin_trusted_root_digests, node) {
354 			list_del(&trd->node);
355 			kfree(trd);
356 		}
357 	}
358 
359 	/* disallow further attempts after reading a corrupt/invalid file */
360 	deny_reading_verity_digests = true;
361 
362 	fdput(f);
363 
364 	return rc;
365 }
366 
367 /******************************** securityfs ********************************/
368 
369 static long dm_verity_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
370 {
371 	void __user *uarg = (void __user *)arg;
372 	unsigned int fd;
373 
374 	switch (cmd) {
375 	case LOADPIN_IOC_SET_TRUSTED_VERITY_DIGESTS:
376 		if (copy_from_user(&fd, uarg, sizeof(fd)))
377 			return -EFAULT;
378 
379 		return read_trusted_verity_root_digests(fd);
380 
381 	default:
382 		return -EINVAL;
383 	}
384 }
385 
386 static const struct file_operations loadpin_dm_verity_ops = {
387 	.unlocked_ioctl = dm_verity_ioctl,
388 	.compat_ioctl = compat_ptr_ioctl,
389 };
390 
391 /**
392  * init_loadpin_securityfs - create the securityfs directory for LoadPin
393  *
394  * We can not put this method normally under the loadpin_init() code path since
395  * the security subsystem gets initialized before the vfs caches.
396  *
397  * Returns 0 if the securityfs directory creation was successful.
398  */
399 static int __init init_loadpin_securityfs(void)
400 {
401 	struct dentry *loadpin_dir, *dentry;
402 
403 	loadpin_dir = securityfs_create_dir("loadpin", NULL);
404 	if (IS_ERR(loadpin_dir)) {
405 		pr_err("LoadPin: could not create securityfs dir: %ld\n",
406 		       PTR_ERR(loadpin_dir));
407 		return PTR_ERR(loadpin_dir);
408 	}
409 
410 	dentry = securityfs_create_file("dm-verity", 0600, loadpin_dir,
411 					(void *)LOADPIN_DM_VERITY, &loadpin_dm_verity_ops);
412 	if (IS_ERR(dentry)) {
413 		pr_err("LoadPin: could not create securityfs entry 'dm-verity': %ld\n",
414 		       PTR_ERR(dentry));
415 		return PTR_ERR(dentry);
416 	}
417 
418 	return 0;
419 }
420 
421 fs_initcall(init_loadpin_securityfs);
422 
423 #endif /* CONFIG_SECURITY_LOADPIN_VERITY */
424 
425 /* Should not be mutable after boot, so not listed in sysfs (perm == 0). */
426 module_param(enforce, int, 0);
427 MODULE_PARM_DESC(enforce, "Enforce module/firmware pinning");
428 module_param_array_named(exclude, exclude_read_files, charp, NULL, 0);
429 MODULE_PARM_DESC(exclude, "Exclude pinning specific read file types");
430