xref: /linux/security/loadpin/loadpin.c (revision d30aca3eeffc18452e5cc5c4e59f1a4da2bd2f12)
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/hex.h>
15 #include <linux/kernel_read_file.h>
16 #include <linux/lsm_hooks.h>
17 #include <linux/mount.h>
18 #include <linux/blkdev.h>
19 #include <linux/path.h>
20 #include <linux/sched.h>	/* current */
21 #include <linux/string_helpers.h>
22 #include <linux/dm-verity-loadpin.h>
23 #include <uapi/linux/loadpin.h>
24 #include <uapi/linux/lsm.h>
25 
26 #define VERITY_DIGEST_FILE_HEADER "# LOADPIN_TRUSTED_VERITY_ROOT_DIGESTS"
27 
28 static void report_load(const char *origin, struct file *file, char *operation)
29 {
30 	char *cmdline, *pathname;
31 
32 	pathname = kstrdup_quotable_file(file, GFP_KERNEL);
33 	cmdline = kstrdup_quotable_cmdline(current, GFP_KERNEL);
34 
35 	pr_notice("%s %s obj=%s%s%s pid=%d cmdline=%s%s%s\n",
36 		  origin, operation,
37 		  (pathname && pathname[0] != '<') ? "\"" : "",
38 		  pathname,
39 		  (pathname && pathname[0] != '<') ? "\"" : "",
40 		  task_pid_nr(current),
41 		  cmdline ? "\"" : "", cmdline, cmdline ? "\"" : "");
42 
43 	kfree(cmdline);
44 	kfree(pathname);
45 }
46 
47 static int enforce = IS_ENABLED(CONFIG_SECURITY_LOADPIN_ENFORCE);
48 static char *exclude_read_files[READING_MAX_ID];
49 static int ignore_read_file_id[READING_MAX_ID] __ro_after_init;
50 static struct super_block *pinned_root;
51 static DEFINE_SPINLOCK(pinned_root_spinlock);
52 #ifdef CONFIG_SECURITY_LOADPIN_VERITY
53 static bool deny_reading_verity_digests;
54 #endif
55 
56 #ifdef CONFIG_SYSCTL
57 static struct ctl_table loadpin_sysctl_table[] = {
58 	{
59 		.procname       = "enforce",
60 		.data           = &enforce,
61 		.maxlen         = sizeof(int),
62 		.mode           = 0644,
63 		.proc_handler   = proc_dointvec_minmax,
64 		.extra1         = SYSCTL_ONE,
65 		.extra2         = SYSCTL_ONE,
66 	},
67 };
68 
69 static void set_sysctl(bool is_writable)
70 {
71 	/*
72 	 * If load pinning is not enforced via a read-only block
73 	 * device, allow sysctl to change modes for testing.
74 	 */
75 	if (is_writable)
76 		loadpin_sysctl_table[0].extra1 = SYSCTL_ZERO;
77 	else
78 		loadpin_sysctl_table[0].extra1 = SYSCTL_ONE;
79 }
80 #else
81 static inline void set_sysctl(bool is_writable) { }
82 #endif
83 
84 static void report_writable(struct super_block *mnt_sb, bool writable)
85 {
86 	if (mnt_sb->s_bdev) {
87 		pr_info("%pg (%u:%u): %s\n", mnt_sb->s_bdev,
88 			MAJOR(mnt_sb->s_bdev->bd_dev),
89 			MINOR(mnt_sb->s_bdev->bd_dev),
90 			writable ? "writable" : "read-only");
91 	} else
92 		pr_info("mnt_sb lacks block device, treating as: writable\n");
93 
94 	if (!writable)
95 		pr_info("load pinning engaged.\n");
96 }
97 
98 /*
99  * This must be called after early kernel init, since then the rootdev
100  * is available.
101  */
102 static bool sb_is_writable(struct super_block *mnt_sb)
103 {
104 	bool writable = true;
105 
106 	if (mnt_sb->s_bdev)
107 		writable = !bdev_read_only(mnt_sb->s_bdev);
108 
109 	return writable;
110 }
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 when we are in
118 	 * enforcing mode. Otherwise, allow the root to be reestablished.
119 	 */
120 	if (!IS_ERR_OR_NULL(pinned_root) && mnt_sb == pinned_root) {
121 		if (enforce) {
122 			pinned_root = ERR_PTR(-EIO);
123 			pr_info("umount pinned fs: refusing further loads\n");
124 		} else {
125 			pinned_root = NULL;
126 		}
127 	}
128 }
129 
130 static int loadpin_check(struct file *file, enum kernel_read_file_id id)
131 {
132 	struct super_block *load_root;
133 	const char *origin = kernel_read_file_id_str(id);
134 	bool first_root_pin = false;
135 	bool load_root_writable;
136 
137 	/* If the file id is excluded, ignore the pinning. */
138 	if ((unsigned int)id < ARRAY_SIZE(ignore_read_file_id) &&
139 	    ignore_read_file_id[id]) {
140 		report_load(origin, file, "pinning-excluded");
141 		return 0;
142 	}
143 
144 	/* This handles the older init_module API that has a NULL file. */
145 	if (!file) {
146 		if (!enforce) {
147 			report_load(origin, NULL, "old-api-pinning-ignored");
148 			return 0;
149 		}
150 
151 		report_load(origin, NULL, "old-api-denied");
152 		return -EPERM;
153 	}
154 
155 	load_root = file->f_path.mnt->mnt_sb;
156 	load_root_writable = sb_is_writable(load_root);
157 
158 	/* First loaded module/firmware defines the root for all others. */
159 	spin_lock(&pinned_root_spinlock);
160 	/*
161 	 * pinned_root is only NULL at startup or when the pinned root has
162 	 * been unmounted while we are not in enforcing mode. Otherwise, it
163 	 * is either a valid reference, or an ERR_PTR.
164 	 */
165 	if (!pinned_root) {
166 		pinned_root = load_root;
167 		first_root_pin = true;
168 	}
169 	spin_unlock(&pinned_root_spinlock);
170 
171 	if (first_root_pin) {
172 		report_writable(pinned_root, load_root_writable);
173 		set_sysctl(load_root_writable);
174 		report_load(origin, file, "pinned");
175 	}
176 
177 	if (IS_ERR_OR_NULL(pinned_root) ||
178 	    ((load_root != pinned_root) && !dm_verity_loadpin_is_bdev_trusted(load_root->s_bdev))) {
179 		if (unlikely(!enforce)) {
180 			report_load(origin, file, "pinning-ignored");
181 			return 0;
182 		}
183 
184 		report_load(origin, file, "denied");
185 		return -EPERM;
186 	}
187 
188 	return 0;
189 }
190 
191 static int loadpin_read_file(struct file *file, enum kernel_read_file_id id,
192 			     bool contents)
193 {
194 	/*
195 	 * LoadPin only cares about the _origin_ of a file, not its
196 	 * contents, so we can ignore the "are full contents available"
197 	 * argument here.
198 	 */
199 	return loadpin_check(file, id);
200 }
201 
202 static int loadpin_load_data(enum kernel_load_data_id id, bool contents)
203 {
204 	/*
205 	 * LoadPin only cares about the _origin_ of a file, not its
206 	 * contents, so a NULL file is passed, and we can ignore the
207 	 * state of "contents".
208 	 */
209 	return loadpin_check(NULL, (enum kernel_read_file_id) id);
210 }
211 
212 static const struct lsm_id loadpin_lsmid = {
213 	.name = "loadpin",
214 	.id = LSM_ID_LOADPIN,
215 };
216 
217 static struct security_hook_list loadpin_hooks[] __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("kernel/loadpin", loadpin_sysctl_table))
266 		pr_notice("sysctl registration failed!\n");
267 #endif
268 	security_add_hooks(loadpin_hooks, ARRAY_SIZE(loadpin_hooks),
269 			   &loadpin_lsmid);
270 
271 	return 0;
272 }
273 
274 #ifdef CONFIG_SECURITY_LOADPIN_VERITY
275 
276 enum loadpin_securityfs_interface_index {
277 	LOADPIN_DM_VERITY,
278 };
279 
280 static int read_trusted_verity_root_digests(unsigned int fd)
281 {
282 	void *data;
283 	int rc;
284 	char *p, *d;
285 
286 	if (deny_reading_verity_digests)
287 		return -EPERM;
288 
289 	/* The list of trusted root digests can only be set up once */
290 	if (!list_empty(&dm_verity_loadpin_trusted_root_digests))
291 		return -EPERM;
292 
293 	CLASS(fd, f)(fd);
294 	if (fd_empty(f))
295 		return -EINVAL;
296 
297 	data = kzalloc(SZ_4K, GFP_KERNEL);
298 	if (!data) {
299 		rc = -ENOMEM;
300 		goto err;
301 	}
302 
303 	rc = kernel_read_file(fd_file(f), 0, (void **)&data, SZ_4K - 1, NULL, READING_POLICY);
304 	if (rc < 0)
305 		goto err;
306 
307 	p = data;
308 	p[rc] = '\0';
309 	p = strim(p);
310 
311 	p = strim(data);
312 	while ((d = strsep(&p, "\n")) != NULL) {
313 		int len;
314 		struct dm_verity_loadpin_trusted_root_digest *trd;
315 
316 		if (d == data) {
317 			/* first line, validate header */
318 			if (strcmp(d, VERITY_DIGEST_FILE_HEADER)) {
319 				rc = -EPROTO;
320 				goto err;
321 			}
322 
323 			continue;
324 		}
325 
326 		len = strlen(d);
327 
328 		if (len % 2) {
329 			rc = -EPROTO;
330 			goto err;
331 		}
332 
333 		len /= 2;
334 
335 		trd = kzalloc(struct_size(trd, data, len), GFP_KERNEL);
336 		if (!trd) {
337 			rc = -ENOMEM;
338 			goto err;
339 		}
340 		trd->len = len;
341 
342 		if (hex2bin(trd->data, d, len)) {
343 			kfree(trd);
344 			rc = -EPROTO;
345 			goto err;
346 		}
347 
348 		list_add_tail(&trd->node, &dm_verity_loadpin_trusted_root_digests);
349 	}
350 
351 	if (list_empty(&dm_verity_loadpin_trusted_root_digests)) {
352 		rc = -EPROTO;
353 		goto err;
354 	}
355 
356 	kfree(data);
357 
358 	return 0;
359 
360 err:
361 	kfree(data);
362 
363 	/* any failure in loading/parsing invalidates the entire list */
364 	{
365 		struct dm_verity_loadpin_trusted_root_digest *trd, *tmp;
366 
367 		list_for_each_entry_safe(trd, tmp, &dm_verity_loadpin_trusted_root_digests, node) {
368 			list_del(&trd->node);
369 			kfree(trd);
370 		}
371 	}
372 
373 	/* disallow further attempts after reading a corrupt/invalid file */
374 	deny_reading_verity_digests = true;
375 
376 	return rc;
377 }
378 
379 /******************************** securityfs ********************************/
380 
381 static long dm_verity_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
382 {
383 	void __user *uarg = (void __user *)arg;
384 	unsigned int fd;
385 
386 	switch (cmd) {
387 	case LOADPIN_IOC_SET_TRUSTED_VERITY_DIGESTS:
388 		if (copy_from_user(&fd, uarg, sizeof(fd)))
389 			return -EFAULT;
390 
391 		return read_trusted_verity_root_digests(fd);
392 
393 	default:
394 		return -EINVAL;
395 	}
396 }
397 
398 static const struct file_operations loadpin_dm_verity_ops = {
399 	.unlocked_ioctl = dm_verity_ioctl,
400 	.compat_ioctl = compat_ptr_ioctl,
401 };
402 
403 /**
404  * init_loadpin_securityfs - create the securityfs directory for LoadPin
405  *
406  * We can not put this method normally under the loadpin_init() code path since
407  * the security subsystem gets initialized before the vfs caches.
408  *
409  * Returns 0 if the securityfs directory creation was successful.
410  */
411 static int __init init_loadpin_securityfs(void)
412 {
413 	struct dentry *loadpin_dir, *dentry;
414 
415 	loadpin_dir = securityfs_create_dir("loadpin", NULL);
416 	if (IS_ERR(loadpin_dir)) {
417 		pr_err("LoadPin: could not create securityfs dir: %ld\n",
418 		       PTR_ERR(loadpin_dir));
419 		return PTR_ERR(loadpin_dir);
420 	}
421 
422 	dentry = securityfs_create_file("dm-verity", 0600, loadpin_dir,
423 					(void *)LOADPIN_DM_VERITY, &loadpin_dm_verity_ops);
424 	if (IS_ERR(dentry)) {
425 		pr_err("LoadPin: could not create securityfs entry 'dm-verity': %ld\n",
426 		       PTR_ERR(dentry));
427 		return PTR_ERR(dentry);
428 	}
429 
430 	return 0;
431 }
432 
433 #endif /* CONFIG_SECURITY_LOADPIN_VERITY */
434 
435 DEFINE_LSM(loadpin) = {
436 	.id = &loadpin_lsmid,
437 	.init = loadpin_init,
438 #ifdef CONFIG_SECURITY_LOADPIN_VERITY
439 	.initcall_fs = init_loadpin_securityfs,
440 #endif /* CONFIG_SECURITY_LOADPIN_VERITY */
441 };
442 
443 /* Should not be mutable after boot, so not listed in sysfs (perm == 0). */
444 module_param(enforce, int, 0);
445 MODULE_PARM_DESC(enforce, "Enforce module/firmware pinning");
446 module_param_array_named(exclude, exclude_read_files, charp, NULL, 0);
447 MODULE_PARM_DESC(exclude, "Exclude pinning specific read file types");
448