xref: /linux/security/loadpin/loadpin.c (revision a2564d0688db20a1ee1660f45d7823075feb12a7)
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 #include <uapi/linux/lsm.h>
24 
25 #define VERITY_DIGEST_FILE_HEADER "# LOADPIN_TRUSTED_VERITY_ROOT_DIGESTS"
26 
27 static void report_load(const char *origin, struct file *file, char *operation)
28 {
29 	char *cmdline, *pathname;
30 
31 	pathname = kstrdup_quotable_file(file, GFP_KERNEL);
32 	cmdline = kstrdup_quotable_cmdline(current, GFP_KERNEL);
33 
34 	pr_notice("%s %s obj=%s%s%s pid=%d cmdline=%s%s%s\n",
35 		  origin, operation,
36 		  (pathname && pathname[0] != '<') ? "\"" : "",
37 		  pathname,
38 		  (pathname && pathname[0] != '<') ? "\"" : "",
39 		  task_pid_nr(current),
40 		  cmdline ? "\"" : "", cmdline, cmdline ? "\"" : "");
41 
42 	kfree(cmdline);
43 	kfree(pathname);
44 }
45 
46 static int enforce = IS_ENABLED(CONFIG_SECURITY_LOADPIN_ENFORCE);
47 static char *exclude_read_files[READING_MAX_ID];
48 static int ignore_read_file_id[READING_MAX_ID] __ro_after_init;
49 static struct super_block *pinned_root;
50 static DEFINE_SPINLOCK(pinned_root_spinlock);
51 #ifdef CONFIG_SECURITY_LOADPIN_VERITY
52 static bool deny_reading_verity_digests;
53 #endif
54 
55 // initialized to false
56 static bool loadpin_root_writable;
57 #ifdef CONFIG_SYSCTL
58 
59 static int proc_handler_loadpin(const struct ctl_table *table, int dir,
60 				void *buffer, size_t *lenp, loff_t *ppos)
61 {
62 	if (!loadpin_root_writable && SYSCTL_USER_TO_KERN(dir))
63 		return -EINVAL;
64 	return proc_dointvec_minmax(table, dir, buffer, lenp, ppos);
65 }
66 
67 static const struct ctl_table loadpin_sysctl_table[] = {
68 	{
69 		.procname       = "enforce",
70 		.data           = &enforce,
71 		.maxlen         = sizeof(int),
72 		.mode           = 0644,
73 		.proc_handler   = proc_handler_loadpin,
74 		.extra1         = SYSCTL_ZERO,
75 		.extra2         = SYSCTL_ONE,
76 	},
77 };
78 #endif
79 
80 static void report_writable(struct super_block *mnt_sb, bool writable)
81 {
82 	if (mnt_sb->s_bdev) {
83 		pr_info("%pg (%u:%u): %s\n", mnt_sb->s_bdev,
84 			MAJOR(mnt_sb->s_bdev->bd_dev),
85 			MINOR(mnt_sb->s_bdev->bd_dev),
86 			writable ? "writable" : "read-only");
87 	} else
88 		pr_info("mnt_sb lacks block device, treating as: writable\n");
89 
90 	if (!writable)
91 		pr_info("load pinning engaged.\n");
92 }
93 
94 /*
95  * This must be called after early kernel init, since then the rootdev
96  * is available.
97  */
98 static bool sb_is_writable(struct super_block *mnt_sb)
99 {
100 	bool writable = true;
101 
102 	if (mnt_sb->s_bdev)
103 		writable = !bdev_read_only(mnt_sb->s_bdev);
104 
105 	return writable;
106 }
107 
108 static void loadpin_sb_free_security(struct super_block *mnt_sb)
109 {
110 	/*
111 	 * When unmounting the filesystem we were using for load
112 	 * pinning, we acknowledge the superblock release, but make sure
113 	 * no other modules or firmware can be loaded when we are in
114 	 * enforcing mode. Otherwise, allow the root to be reestablished.
115 	 */
116 	if (!IS_ERR_OR_NULL(pinned_root) && mnt_sb == pinned_root) {
117 		if (enforce) {
118 			pinned_root = ERR_PTR(-EIO);
119 			pr_info("umount pinned fs: refusing further loads\n");
120 		} else {
121 			pinned_root = NULL;
122 		}
123 	}
124 }
125 
126 static int loadpin_check(struct file *file, enum kernel_read_file_id id)
127 {
128 	struct super_block *load_root;
129 	const char *origin = kernel_read_file_id_str(id);
130 	bool first_root_pin = false;
131 
132 	/* If the file id is excluded, ignore the pinning. */
133 	if ((unsigned int)id < ARRAY_SIZE(ignore_read_file_id) &&
134 	    ignore_read_file_id[id]) {
135 		report_load(origin, file, "pinning-excluded");
136 		return 0;
137 	}
138 
139 	/* This handles the older init_module API that has a NULL file. */
140 	if (!file) {
141 		if (!enforce) {
142 			report_load(origin, NULL, "old-api-pinning-ignored");
143 			return 0;
144 		}
145 
146 		report_load(origin, NULL, "old-api-denied");
147 		return -EPERM;
148 	}
149 
150 	load_root = file->f_path.mnt->mnt_sb;
151 
152 	/* First loaded module/firmware defines the root for all others. */
153 	spin_lock(&pinned_root_spinlock);
154 	/*
155 	 * pinned_root is only NULL at startup or when the pinned root has
156 	 * been unmounted while we are not in enforcing mode. Otherwise, it
157 	 * is either a valid reference, or an ERR_PTR.
158 	 */
159 	if (!pinned_root) {
160 		pinned_root = load_root;
161 		first_root_pin = true;
162 	}
163 	spin_unlock(&pinned_root_spinlock);
164 
165 	if (first_root_pin) {
166 		loadpin_root_writable = sb_is_writable(pinned_root);
167 		report_writable(pinned_root, loadpin_root_writable);
168 		report_load(origin, file, "pinned");
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 
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 
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 const struct lsm_id loadpin_lsmid = {
207 	.name = "loadpin",
208 	.id = LSM_ID_LOADPIN,
209 };
210 
211 static struct security_hook_list loadpin_hooks[] __ro_after_init = {
212 	LSM_HOOK_INIT(sb_free_security, loadpin_sb_free_security),
213 	LSM_HOOK_INIT(kernel_read_file, loadpin_read_file),
214 	LSM_HOOK_INIT(kernel_load_data, loadpin_load_data),
215 };
216 
217 static void __init parse_exclude(void)
218 {
219 	int i, j;
220 	char *cur;
221 
222 	/*
223 	 * Make sure all the arrays stay within expected sizes. This
224 	 * is slightly weird because kernel_read_file_str[] includes
225 	 * READING_MAX_ID, which isn't actually meaningful here.
226 	 */
227 	BUILD_BUG_ON(ARRAY_SIZE(exclude_read_files) !=
228 		     ARRAY_SIZE(ignore_read_file_id));
229 	BUILD_BUG_ON(ARRAY_SIZE(kernel_read_file_str) <
230 		     ARRAY_SIZE(ignore_read_file_id));
231 
232 	for (i = 0; i < ARRAY_SIZE(exclude_read_files); i++) {
233 		cur = exclude_read_files[i];
234 		if (!cur)
235 			break;
236 		if (*cur == '\0')
237 			continue;
238 
239 		for (j = 0; j < ARRAY_SIZE(ignore_read_file_id); j++) {
240 			if (strcmp(cur, kernel_read_file_str[j]) == 0) {
241 				pr_info("excluding: %s\n",
242 					kernel_read_file_str[j]);
243 				ignore_read_file_id[j] = 1;
244 				/*
245 				 * Can not break, because one read_file_str
246 				 * may map to more than on read_file_id.
247 				 */
248 			}
249 		}
250 	}
251 }
252 
253 static int __init loadpin_init(void)
254 {
255 	pr_info("ready to pin (currently %senforcing)\n",
256 		enforce ? "" : "not ");
257 	parse_exclude();
258 #ifdef CONFIG_SYSCTL
259 	if (!register_sysctl("kernel/loadpin", loadpin_sysctl_table))
260 		pr_notice("sysctl registration failed!\n");
261 #endif
262 	security_add_hooks(loadpin_hooks, ARRAY_SIZE(loadpin_hooks),
263 			   &loadpin_lsmid);
264 
265 	return 0;
266 }
267 
268 #ifdef CONFIG_SECURITY_LOADPIN_VERITY
269 
270 enum loadpin_securityfs_interface_index {
271 	LOADPIN_DM_VERITY,
272 };
273 
274 static int read_trusted_verity_root_digests(unsigned int fd)
275 {
276 	void *data;
277 	int rc;
278 	char *p, *d;
279 
280 	if (deny_reading_verity_digests)
281 		return -EPERM;
282 
283 	/* The list of trusted root digests can only be set up once */
284 	if (!list_empty(&dm_verity_loadpin_trusted_root_digests))
285 		return -EPERM;
286 
287 	CLASS(fd, f)(fd);
288 	if (fd_empty(f))
289 		return -EINVAL;
290 
291 	data = kzalloc(SZ_4K, GFP_KERNEL);
292 	if (!data) {
293 		rc = -ENOMEM;
294 		goto err;
295 	}
296 
297 	rc = kernel_read_file(fd_file(f), 0, (void **)&data, SZ_4K - 1, NULL, READING_POLICY);
298 	if (rc < 0)
299 		goto err;
300 
301 	p = data;
302 	p[rc] = '\0';
303 	p = strim(p);
304 
305 	p = strim(data);
306 	while ((d = strsep(&p, "\n")) != NULL) {
307 		int len;
308 		struct dm_verity_loadpin_trusted_root_digest *trd;
309 
310 		if (d == data) {
311 			/* first line, validate header */
312 			if (strcmp(d, VERITY_DIGEST_FILE_HEADER)) {
313 				rc = -EPROTO;
314 				goto err;
315 			}
316 
317 			continue;
318 		}
319 
320 		len = strlen(d);
321 
322 		if (len % 2) {
323 			rc = -EPROTO;
324 			goto err;
325 		}
326 
327 		len /= 2;
328 
329 		trd = kzalloc(struct_size(trd, data, len), GFP_KERNEL);
330 		if (!trd) {
331 			rc = -ENOMEM;
332 			goto err;
333 		}
334 		trd->len = len;
335 
336 		if (hex2bin(trd->data, d, len)) {
337 			kfree(trd);
338 			rc = -EPROTO;
339 			goto err;
340 		}
341 
342 		list_add_tail(&trd->node, &dm_verity_loadpin_trusted_root_digests);
343 	}
344 
345 	if (list_empty(&dm_verity_loadpin_trusted_root_digests)) {
346 		rc = -EPROTO;
347 		goto err;
348 	}
349 
350 	kfree(data);
351 
352 	return 0;
353 
354 err:
355 	kfree(data);
356 
357 	/* any failure in loading/parsing invalidates the entire list */
358 	{
359 		struct dm_verity_loadpin_trusted_root_digest *trd, *tmp;
360 
361 		list_for_each_entry_safe(trd, tmp, &dm_verity_loadpin_trusted_root_digests, node) {
362 			list_del(&trd->node);
363 			kfree(trd);
364 		}
365 	}
366 
367 	/* disallow further attempts after reading a corrupt/invalid file */
368 	deny_reading_verity_digests = true;
369 
370 	return rc;
371 }
372 
373 /******************************** securityfs ********************************/
374 
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  */
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 #endif /* CONFIG_SECURITY_LOADPIN_VERITY */
428 
429 DEFINE_LSM(loadpin) = {
430 	.id = &loadpin_lsmid,
431 	.init = loadpin_init,
432 #ifdef CONFIG_SECURITY_LOADPIN_VERITY
433 	.initcall_fs = init_loadpin_securityfs,
434 #endif /* CONFIG_SECURITY_LOADPIN_VERITY */
435 };
436 
437 /* Should not be mutable after boot, so not listed in sysfs (perm == 0). */
438 module_param(enforce, int, 0);
439 MODULE_PARM_DESC(enforce, "Enforce module/firmware pinning");
440 module_param_array_named(exclude, exclude_read_files, charp, NULL, 0);
441 MODULE_PARM_DESC(exclude, "Exclude pinning specific read file types");
442