xref: /linux/security/integrity/ima/ima_fs.c (revision 5a558f369ef89c6fd8170ee1137274fcc08517ae)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2005,2006,2007,2008 IBM Corporation
4  *
5  * Authors:
6  * Kylene Hall <kjhall@us.ibm.com>
7  * Reiner Sailer <sailer@us.ibm.com>
8  * Mimi Zohar <zohar@us.ibm.com>
9  *
10  * File: ima_fs.c
11  *	implemenents security file system for reporting
12  *	current measurement list and IMA statistics
13  */
14 
15 #include <linux/fcntl.h>
16 #include <linux/kernel_read_file.h>
17 #include <linux/slab.h>
18 #include <linux/init.h>
19 #include <linux/seq_file.h>
20 #include <linux/rculist.h>
21 #include <linux/rcupdate.h>
22 #include <linux/parser.h>
23 #include <linux/vmalloc.h>
24 
25 #include "ima.h"
26 
27 static DEFINE_MUTEX(ima_write_mutex);
28 
29 bool ima_canonical_fmt;
30 static int __init default_canonical_fmt_setup(char *str)
31 {
32 #ifdef __BIG_ENDIAN
33 	ima_canonical_fmt = true;
34 #endif
35 	return 1;
36 }
37 __setup("ima_canonical_fmt", default_canonical_fmt_setup);
38 
39 static int valid_policy = 1;
40 
41 static ssize_t ima_show_htable_value(char __user *buf, size_t count,
42 				     loff_t *ppos, atomic_long_t *val)
43 {
44 	char tmpbuf[32];	/* greater than largest 'long' string value */
45 	ssize_t len;
46 
47 	len = scnprintf(tmpbuf, sizeof(tmpbuf), "%li\n", atomic_long_read(val));
48 	return simple_read_from_buffer(buf, count, ppos, tmpbuf, len);
49 }
50 
51 static ssize_t ima_show_htable_violations(struct file *filp,
52 					  char __user *buf,
53 					  size_t count, loff_t *ppos)
54 {
55 	return ima_show_htable_value(buf, count, ppos, &ima_htable.violations);
56 }
57 
58 static const struct file_operations ima_htable_violations_ops = {
59 	.read = ima_show_htable_violations,
60 	.llseek = generic_file_llseek,
61 };
62 
63 static ssize_t ima_show_measurements_count(struct file *filp,
64 					   char __user *buf,
65 					   size_t count, loff_t *ppos)
66 {
67 	return ima_show_htable_value(buf, count, ppos, &ima_htable.len);
68 
69 }
70 
71 static const struct file_operations ima_measurements_count_ops = {
72 	.read = ima_show_measurements_count,
73 	.llseek = generic_file_llseek,
74 };
75 
76 /* returns pointer to hlist_node */
77 static void *ima_measurements_start(struct seq_file *m, loff_t *pos)
78 {
79 	loff_t l = *pos;
80 	struct ima_queue_entry *qe;
81 
82 	/* we need a lock since pos could point beyond last element */
83 	rcu_read_lock();
84 	list_for_each_entry_rcu(qe, &ima_measurements, later) {
85 		if (!l--) {
86 			rcu_read_unlock();
87 			return qe;
88 		}
89 	}
90 	rcu_read_unlock();
91 	return NULL;
92 }
93 
94 static void *ima_measurements_next(struct seq_file *m, void *v, loff_t *pos)
95 {
96 	struct ima_queue_entry *qe = v;
97 
98 	/* lock protects when reading beyond last element
99 	 * against concurrent list-extension
100 	 */
101 	rcu_read_lock();
102 	qe = list_entry_rcu(qe->later.next, struct ima_queue_entry, later);
103 	rcu_read_unlock();
104 	(*pos)++;
105 
106 	return (&qe->later == &ima_measurements) ? NULL : qe;
107 }
108 
109 static void ima_measurements_stop(struct seq_file *m, void *v)
110 {
111 }
112 
113 void ima_putc(struct seq_file *m, void *data, int datalen)
114 {
115 	while (datalen--)
116 		seq_putc(m, *(char *)data++);
117 }
118 
119 static struct dentry **ascii_securityfs_measurement_lists __ro_after_init;
120 static struct dentry **binary_securityfs_measurement_lists __ro_after_init;
121 static int securityfs_measurement_list_count __ro_after_init;
122 
123 static void lookup_template_data_hash_algo(int *algo_idx, enum hash_algo *algo,
124 					   struct seq_file *m,
125 					   struct dentry **lists)
126 {
127 	struct dentry *dentry;
128 	int i;
129 
130 	dentry = file_dentry(m->file);
131 
132 	for (i = 0; i < securityfs_measurement_list_count; i++) {
133 		if (dentry == lists[i]) {
134 			*algo_idx = i;
135 			*algo = ima_algo_array[i].algo;
136 			break;
137 		}
138 	}
139 }
140 
141 /* print format:
142  *       32bit-le=pcr#
143  *       char[n]=template digest
144  *       32bit-le=template name size
145  *       char[n]=template name
146  *       [eventdata length]
147  *       eventdata[n]=template specific data
148  */
149 int ima_measurements_show(struct seq_file *m, void *v)
150 {
151 	/* the list never shrinks, so we don't need a lock here */
152 	struct ima_queue_entry *qe = v;
153 	struct ima_template_entry *e;
154 	char *template_name;
155 	u32 pcr, namelen, template_data_len; /* temporary fields */
156 	bool is_ima_template = false;
157 	enum hash_algo algo;
158 	int i, algo_idx;
159 
160 	algo_idx = ima_sha1_idx;
161 	algo = HASH_ALGO_SHA1;
162 
163 	if (m->file != NULL)
164 		lookup_template_data_hash_algo(&algo_idx, &algo, m,
165 					       binary_securityfs_measurement_lists);
166 
167 	/* get entry */
168 	e = qe->entry;
169 	if (e == NULL)
170 		return -1;
171 
172 	template_name = (e->template_desc->name[0] != '\0') ?
173 	    e->template_desc->name : e->template_desc->fmt;
174 
175 	/*
176 	 * 1st: PCRIndex
177 	 * PCR used defaults to the same (config option) in
178 	 * little-endian format, unless set in policy
179 	 */
180 	pcr = !ima_canonical_fmt ? e->pcr : (__force u32)cpu_to_le32(e->pcr);
181 	ima_putc(m, &pcr, sizeof(e->pcr));
182 
183 	/* 2nd: template digest */
184 	ima_putc(m, e->digests[algo_idx].digest, hash_digest_size[algo]);
185 
186 	/* 3rd: template name size */
187 	namelen = !ima_canonical_fmt ? strlen(template_name) :
188 		(__force u32)cpu_to_le32(strlen(template_name));
189 	ima_putc(m, &namelen, sizeof(namelen));
190 
191 	/* 4th:  template name */
192 	ima_putc(m, template_name, strlen(template_name));
193 
194 	/* 5th:  template length (except for 'ima' template) */
195 	if (strcmp(template_name, IMA_TEMPLATE_IMA_NAME) == 0)
196 		is_ima_template = true;
197 
198 	if (!is_ima_template) {
199 		template_data_len = !ima_canonical_fmt ? e->template_data_len :
200 			(__force u32)cpu_to_le32(e->template_data_len);
201 		ima_putc(m, &template_data_len, sizeof(e->template_data_len));
202 	}
203 
204 	/* 6th:  template specific data */
205 	for (i = 0; i < e->template_desc->num_fields; i++) {
206 		enum ima_show_type show = IMA_SHOW_BINARY;
207 		const struct ima_template_field *field =
208 			e->template_desc->fields[i];
209 
210 		if (is_ima_template && strcmp(field->field_id, "d") == 0)
211 			show = IMA_SHOW_BINARY_NO_FIELD_LEN;
212 		if (is_ima_template && strcmp(field->field_id, "n") == 0)
213 			show = IMA_SHOW_BINARY_OLD_STRING_FMT;
214 		field->field_show(m, show, &e->template_data[i]);
215 	}
216 	return 0;
217 }
218 
219 static const struct seq_operations ima_measurments_seqops = {
220 	.start = ima_measurements_start,
221 	.next = ima_measurements_next,
222 	.stop = ima_measurements_stop,
223 	.show = ima_measurements_show
224 };
225 
226 static int ima_measurements_open(struct inode *inode, struct file *file)
227 {
228 	return seq_open(file, &ima_measurments_seqops);
229 }
230 
231 static const struct file_operations ima_measurements_ops = {
232 	.open = ima_measurements_open,
233 	.read = seq_read,
234 	.llseek = seq_lseek,
235 	.release = seq_release,
236 };
237 
238 void ima_print_digest(struct seq_file *m, u8 *digest, u32 size)
239 {
240 	u32 i;
241 
242 	for (i = 0; i < size; i++)
243 		seq_printf(m, "%02x", *(digest + i));
244 }
245 
246 /* print in ascii */
247 static int ima_ascii_measurements_show(struct seq_file *m, void *v)
248 {
249 	/* the list never shrinks, so we don't need a lock here */
250 	struct ima_queue_entry *qe = v;
251 	struct ima_template_entry *e;
252 	char *template_name;
253 	enum hash_algo algo;
254 	int i, algo_idx;
255 
256 	algo_idx = ima_sha1_idx;
257 	algo = HASH_ALGO_SHA1;
258 
259 	if (m->file != NULL)
260 		lookup_template_data_hash_algo(&algo_idx, &algo, m,
261 					       ascii_securityfs_measurement_lists);
262 
263 	/* get entry */
264 	e = qe->entry;
265 	if (e == NULL)
266 		return -1;
267 
268 	template_name = (e->template_desc->name[0] != '\0') ?
269 	    e->template_desc->name : e->template_desc->fmt;
270 
271 	/* 1st: PCR used (config option) */
272 	seq_printf(m, "%2d ", e->pcr);
273 
274 	/* 2nd: template hash */
275 	ima_print_digest(m, e->digests[algo_idx].digest, hash_digest_size[algo]);
276 
277 	/* 3th:  template name */
278 	seq_printf(m, " %s", template_name);
279 
280 	/* 4th:  template specific data */
281 	for (i = 0; i < e->template_desc->num_fields; i++) {
282 		seq_puts(m, " ");
283 		if (e->template_data[i].len == 0)
284 			continue;
285 
286 		e->template_desc->fields[i]->field_show(m, IMA_SHOW_ASCII,
287 							&e->template_data[i]);
288 	}
289 	seq_puts(m, "\n");
290 	return 0;
291 }
292 
293 static const struct seq_operations ima_ascii_measurements_seqops = {
294 	.start = ima_measurements_start,
295 	.next = ima_measurements_next,
296 	.stop = ima_measurements_stop,
297 	.show = ima_ascii_measurements_show
298 };
299 
300 static int ima_ascii_measurements_open(struct inode *inode, struct file *file)
301 {
302 	return seq_open(file, &ima_ascii_measurements_seqops);
303 }
304 
305 static const struct file_operations ima_ascii_measurements_ops = {
306 	.open = ima_ascii_measurements_open,
307 	.read = seq_read,
308 	.llseek = seq_lseek,
309 	.release = seq_release,
310 };
311 
312 static ssize_t ima_read_policy(char *path)
313 {
314 	void *data = NULL;
315 	char *datap;
316 	size_t size;
317 	int rc, pathlen = strlen(path);
318 
319 	char *p;
320 
321 	/* remove \n */
322 	datap = path;
323 	strsep(&datap, "\n");
324 
325 	rc = kernel_read_file_from_path(path, 0, &data, INT_MAX, NULL,
326 					READING_POLICY);
327 	if (rc < 0) {
328 		pr_err("Unable to open file: %s (%d)", path, rc);
329 		return rc;
330 	}
331 	size = rc;
332 	rc = 0;
333 
334 	datap = data;
335 	while (size > 0 && (p = strsep(&datap, "\n"))) {
336 		pr_debug("rule: %s\n", p);
337 		rc = ima_parse_add_rule(p);
338 		if (rc < 0)
339 			break;
340 		size -= rc;
341 	}
342 
343 	vfree(data);
344 	if (rc < 0)
345 		return rc;
346 	else if (size)
347 		return -EINVAL;
348 	else
349 		return pathlen;
350 }
351 
352 static ssize_t ima_write_policy(struct file *file, const char __user *buf,
353 				size_t datalen, loff_t *ppos)
354 {
355 	char *data;
356 	ssize_t result;
357 
358 	if (datalen >= PAGE_SIZE)
359 		datalen = PAGE_SIZE - 1;
360 
361 	/* No partial writes. */
362 	result = -EINVAL;
363 	if (*ppos != 0)
364 		goto out;
365 
366 	data = memdup_user_nul(buf, datalen);
367 	if (IS_ERR(data)) {
368 		result = PTR_ERR(data);
369 		goto out;
370 	}
371 
372 	result = mutex_lock_interruptible(&ima_write_mutex);
373 	if (result < 0)
374 		goto out_free;
375 
376 	if (data[0] == '/') {
377 		result = ima_read_policy(data);
378 	} else if (ima_appraise & IMA_APPRAISE_POLICY) {
379 		pr_err("signed policy file (specified as an absolute pathname) required\n");
380 		integrity_audit_msg(AUDIT_INTEGRITY_STATUS, NULL, NULL,
381 				    "policy_update", "signed policy required",
382 				    1, 0);
383 		result = -EACCES;
384 	} else {
385 		result = ima_parse_add_rule(data);
386 	}
387 	mutex_unlock(&ima_write_mutex);
388 out_free:
389 	kfree(data);
390 out:
391 	if (result < 0)
392 		valid_policy = 0;
393 
394 	return result;
395 }
396 
397 static struct dentry *ima_dir;
398 static struct dentry *ima_symlink;
399 static struct dentry *binary_runtime_measurements;
400 static struct dentry *ascii_runtime_measurements;
401 static struct dentry *runtime_measurements_count;
402 static struct dentry *violations;
403 static struct dentry *ima_policy;
404 
405 enum ima_fs_flags {
406 	IMA_FS_BUSY,
407 };
408 
409 static unsigned long ima_fs_flags;
410 
411 #ifdef	CONFIG_IMA_READ_POLICY
412 static const struct seq_operations ima_policy_seqops = {
413 		.start = ima_policy_start,
414 		.next = ima_policy_next,
415 		.stop = ima_policy_stop,
416 		.show = ima_policy_show,
417 };
418 #endif
419 
420 static void __init remove_securityfs_measurement_lists(struct dentry **lists)
421 {
422 	int i;
423 
424 	if (lists) {
425 		for (i = 0; i < securityfs_measurement_list_count; i++)
426 			securityfs_remove(lists[i]);
427 
428 		kfree(lists);
429 	}
430 
431 	securityfs_measurement_list_count = 0;
432 }
433 
434 static int __init create_securityfs_measurement_lists(void)
435 {
436 	char file_name[NAME_MAX + 1];
437 	struct dentry *dentry;
438 	u16 algo;
439 	int i;
440 
441 	securityfs_measurement_list_count = NR_BANKS(ima_tpm_chip);
442 
443 	if (ima_sha1_idx >= NR_BANKS(ima_tpm_chip))
444 		securityfs_measurement_list_count++;
445 
446 	ascii_securityfs_measurement_lists =
447 	    kcalloc(securityfs_measurement_list_count, sizeof(struct dentry *),
448 		    GFP_KERNEL);
449 	if (!ascii_securityfs_measurement_lists)
450 		return -ENOMEM;
451 
452 	binary_securityfs_measurement_lists =
453 	    kcalloc(securityfs_measurement_list_count, sizeof(struct dentry *),
454 		    GFP_KERNEL);
455 	if (!binary_securityfs_measurement_lists)
456 		return -ENOMEM;
457 
458 	for (i = 0; i < securityfs_measurement_list_count; i++) {
459 		algo = ima_algo_array[i].algo;
460 
461 		sprintf(file_name, "ascii_runtime_measurements_%s",
462 			hash_algo_name[algo]);
463 		dentry = securityfs_create_file(file_name, S_IRUSR | S_IRGRP,
464 						ima_dir, NULL,
465 						&ima_ascii_measurements_ops);
466 		if (IS_ERR(dentry))
467 			return PTR_ERR(dentry);
468 
469 		ascii_securityfs_measurement_lists[i] = dentry;
470 
471 		sprintf(file_name, "binary_runtime_measurements_%s",
472 			hash_algo_name[algo]);
473 		dentry = securityfs_create_file(file_name, S_IRUSR | S_IRGRP,
474 						ima_dir, NULL,
475 						&ima_measurements_ops);
476 		if (IS_ERR(dentry))
477 			return PTR_ERR(dentry);
478 
479 		binary_securityfs_measurement_lists[i] = dentry;
480 	}
481 
482 	return 0;
483 }
484 
485 /*
486  * ima_open_policy: sequentialize access to the policy file
487  */
488 static int ima_open_policy(struct inode *inode, struct file *filp)
489 {
490 	if (!(filp->f_flags & O_WRONLY)) {
491 #ifndef	CONFIG_IMA_READ_POLICY
492 		return -EACCES;
493 #else
494 		if ((filp->f_flags & O_ACCMODE) != O_RDONLY)
495 			return -EACCES;
496 		if (!capable(CAP_SYS_ADMIN))
497 			return -EPERM;
498 		return seq_open(filp, &ima_policy_seqops);
499 #endif
500 	}
501 	if (test_and_set_bit(IMA_FS_BUSY, &ima_fs_flags))
502 		return -EBUSY;
503 	return 0;
504 }
505 
506 /*
507  * ima_release_policy - start using the new measure policy rules.
508  *
509  * Initially, ima_measure points to the default policy rules, now
510  * point to the new policy rules, and remove the securityfs policy file,
511  * assuming a valid policy.
512  */
513 static int ima_release_policy(struct inode *inode, struct file *file)
514 {
515 	const char *cause = valid_policy ? "completed" : "failed";
516 
517 	if ((file->f_flags & O_ACCMODE) == O_RDONLY)
518 		return seq_release(inode, file);
519 
520 	if (valid_policy && ima_check_policy() < 0) {
521 		cause = "failed";
522 		valid_policy = 0;
523 	}
524 
525 	pr_info("policy update %s\n", cause);
526 	integrity_audit_msg(AUDIT_INTEGRITY_STATUS, NULL, NULL,
527 			    "policy_update", cause, !valid_policy, 0);
528 
529 	if (!valid_policy) {
530 		ima_delete_rules();
531 		valid_policy = 1;
532 		clear_bit(IMA_FS_BUSY, &ima_fs_flags);
533 		return 0;
534 	}
535 
536 	ima_update_policy();
537 #if !defined(CONFIG_IMA_WRITE_POLICY) && !defined(CONFIG_IMA_READ_POLICY)
538 	securityfs_remove(ima_policy);
539 	ima_policy = NULL;
540 #elif defined(CONFIG_IMA_WRITE_POLICY)
541 	clear_bit(IMA_FS_BUSY, &ima_fs_flags);
542 #elif defined(CONFIG_IMA_READ_POLICY)
543 	inode->i_mode &= ~S_IWUSR;
544 #endif
545 	return 0;
546 }
547 
548 static const struct file_operations ima_measure_policy_ops = {
549 	.open = ima_open_policy,
550 	.write = ima_write_policy,
551 	.read = seq_read,
552 	.release = ima_release_policy,
553 	.llseek = generic_file_llseek,
554 };
555 
556 int __init ima_fs_init(void)
557 {
558 	int ret;
559 
560 	ascii_securityfs_measurement_lists = NULL;
561 	binary_securityfs_measurement_lists = NULL;
562 
563 	ima_dir = securityfs_create_dir("ima", integrity_dir);
564 	if (IS_ERR(ima_dir))
565 		return PTR_ERR(ima_dir);
566 
567 	ima_symlink = securityfs_create_symlink("ima", NULL, "integrity/ima",
568 						NULL);
569 	if (IS_ERR(ima_symlink)) {
570 		ret = PTR_ERR(ima_symlink);
571 		goto out;
572 	}
573 
574 	ret = create_securityfs_measurement_lists();
575 	if (ret != 0)
576 		goto out;
577 
578 	binary_runtime_measurements =
579 	    securityfs_create_symlink("binary_runtime_measurements", ima_dir,
580 				      "binary_runtime_measurements_sha1", NULL);
581 	if (IS_ERR(binary_runtime_measurements)) {
582 		ret = PTR_ERR(binary_runtime_measurements);
583 		goto out;
584 	}
585 
586 	ascii_runtime_measurements =
587 	    securityfs_create_symlink("ascii_runtime_measurements", ima_dir,
588 				      "ascii_runtime_measurements_sha1", NULL);
589 	if (IS_ERR(ascii_runtime_measurements)) {
590 		ret = PTR_ERR(ascii_runtime_measurements);
591 		goto out;
592 	}
593 
594 	runtime_measurements_count =
595 	    securityfs_create_file("runtime_measurements_count",
596 				   S_IRUSR | S_IRGRP, ima_dir, NULL,
597 				   &ima_measurements_count_ops);
598 	if (IS_ERR(runtime_measurements_count)) {
599 		ret = PTR_ERR(runtime_measurements_count);
600 		goto out;
601 	}
602 
603 	violations =
604 	    securityfs_create_file("violations", S_IRUSR | S_IRGRP,
605 				   ima_dir, NULL, &ima_htable_violations_ops);
606 	if (IS_ERR(violations)) {
607 		ret = PTR_ERR(violations);
608 		goto out;
609 	}
610 
611 	ima_policy = securityfs_create_file("policy", POLICY_FILE_FLAGS,
612 					    ima_dir, NULL,
613 					    &ima_measure_policy_ops);
614 	if (IS_ERR(ima_policy)) {
615 		ret = PTR_ERR(ima_policy);
616 		goto out;
617 	}
618 
619 	return 0;
620 out:
621 	securityfs_remove(ima_policy);
622 	securityfs_remove(violations);
623 	securityfs_remove(runtime_measurements_count);
624 	securityfs_remove(ascii_runtime_measurements);
625 	securityfs_remove(binary_runtime_measurements);
626 	remove_securityfs_measurement_lists(ascii_securityfs_measurement_lists);
627 	remove_securityfs_measurement_lists(binary_securityfs_measurement_lists);
628 	securityfs_remove(ima_symlink);
629 	securityfs_remove(ima_dir);
630 
631 	return ret;
632 }
633