xref: /linux/security/integrity/ima/ima_fs.c (revision d7bd8cf0b348d3edae7bee33e74a32b21668b181)
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 /* print format:
120  *       32bit-le=pcr#
121  *       char[n]=template digest
122  *       32bit-le=template name size
123  *       char[n]=template name
124  *       [eventdata length]
125  *       eventdata[n]=template specific data
126  */
127 int ima_measurements_show(struct seq_file *m, void *v)
128 {
129 	/* the list never shrinks, so we don't need a lock here */
130 	struct ima_queue_entry *qe = v;
131 	struct ima_template_entry *e;
132 	char *template_name;
133 	u32 pcr, namelen, template_data_len; /* temporary fields */
134 	bool is_ima_template = false;
135 	int i, algo_idx;
136 
137 	algo_idx = ima_sha1_idx;
138 
139 	if (m->file != NULL)
140 		algo_idx = (unsigned long)file_inode(m->file)->i_private;
141 
142 	/* get entry */
143 	e = qe->entry;
144 	if (e == NULL)
145 		return -1;
146 
147 	template_name = (e->template_desc->name[0] != '\0') ?
148 	    e->template_desc->name : e->template_desc->fmt;
149 
150 	/*
151 	 * 1st: PCRIndex
152 	 * PCR used defaults to the same (config option) in
153 	 * little-endian format, unless set in policy
154 	 */
155 	pcr = !ima_canonical_fmt ? e->pcr : (__force u32)cpu_to_le32(e->pcr);
156 	ima_putc(m, &pcr, sizeof(e->pcr));
157 
158 	/* 2nd: template digest */
159 	ima_putc(m, e->digests[algo_idx].digest,
160 		 ima_algo_array[algo_idx].digest_size);
161 
162 	/* 3rd: template name size */
163 	namelen = !ima_canonical_fmt ? strlen(template_name) :
164 		(__force u32)cpu_to_le32(strlen(template_name));
165 	ima_putc(m, &namelen, sizeof(namelen));
166 
167 	/* 4th:  template name */
168 	ima_putc(m, template_name, strlen(template_name));
169 
170 	/* 5th:  template length (except for 'ima' template) */
171 	if (strcmp(template_name, IMA_TEMPLATE_IMA_NAME) == 0)
172 		is_ima_template = true;
173 
174 	if (!is_ima_template) {
175 		template_data_len = !ima_canonical_fmt ? e->template_data_len :
176 			(__force u32)cpu_to_le32(e->template_data_len);
177 		ima_putc(m, &template_data_len, sizeof(e->template_data_len));
178 	}
179 
180 	/* 6th:  template specific data */
181 	for (i = 0; i < e->template_desc->num_fields; i++) {
182 		enum ima_show_type show = IMA_SHOW_BINARY;
183 		const struct ima_template_field *field =
184 			e->template_desc->fields[i];
185 
186 		if (is_ima_template && strcmp(field->field_id, "d") == 0)
187 			show = IMA_SHOW_BINARY_NO_FIELD_LEN;
188 		if (is_ima_template && strcmp(field->field_id, "n") == 0)
189 			show = IMA_SHOW_BINARY_OLD_STRING_FMT;
190 		field->field_show(m, show, &e->template_data[i]);
191 	}
192 	return 0;
193 }
194 
195 static const struct seq_operations ima_measurments_seqops = {
196 	.start = ima_measurements_start,
197 	.next = ima_measurements_next,
198 	.stop = ima_measurements_stop,
199 	.show = ima_measurements_show
200 };
201 
202 static int ima_measurements_open(struct inode *inode, struct file *file)
203 {
204 	return seq_open(file, &ima_measurments_seqops);
205 }
206 
207 static const struct file_operations ima_measurements_ops = {
208 	.open = ima_measurements_open,
209 	.read = seq_read,
210 	.llseek = seq_lseek,
211 	.release = seq_release,
212 };
213 
214 void ima_print_digest(struct seq_file *m, u8 *digest, u32 size)
215 {
216 	u32 i;
217 
218 	for (i = 0; i < size; i++)
219 		seq_printf(m, "%02x", *(digest + i));
220 }
221 
222 /* print in ascii */
223 static int ima_ascii_measurements_show(struct seq_file *m, void *v)
224 {
225 	/* the list never shrinks, so we don't need a lock here */
226 	struct ima_queue_entry *qe = v;
227 	struct ima_template_entry *e;
228 	char *template_name;
229 	int i, algo_idx;
230 
231 	algo_idx = ima_sha1_idx;
232 
233 	if (m->file != NULL)
234 		algo_idx = (unsigned long)file_inode(m->file)->i_private;
235 
236 	/* get entry */
237 	e = qe->entry;
238 	if (e == NULL)
239 		return -1;
240 
241 	template_name = (e->template_desc->name[0] != '\0') ?
242 	    e->template_desc->name : e->template_desc->fmt;
243 
244 	/* 1st: PCR used (config option) */
245 	seq_printf(m, "%2d ", e->pcr);
246 
247 	/* 2nd: template hash */
248 	ima_print_digest(m, e->digests[algo_idx].digest,
249 			 ima_algo_array[algo_idx].digest_size);
250 
251 	/* 3th:  template name */
252 	seq_printf(m, " %s", template_name);
253 
254 	/* 4th:  template specific data */
255 	for (i = 0; i < e->template_desc->num_fields; i++) {
256 		seq_puts(m, " ");
257 		if (e->template_data[i].len == 0)
258 			continue;
259 
260 		e->template_desc->fields[i]->field_show(m, IMA_SHOW_ASCII,
261 							&e->template_data[i]);
262 	}
263 	seq_puts(m, "\n");
264 	return 0;
265 }
266 
267 static const struct seq_operations ima_ascii_measurements_seqops = {
268 	.start = ima_measurements_start,
269 	.next = ima_measurements_next,
270 	.stop = ima_measurements_stop,
271 	.show = ima_ascii_measurements_show
272 };
273 
274 static int ima_ascii_measurements_open(struct inode *inode, struct file *file)
275 {
276 	return seq_open(file, &ima_ascii_measurements_seqops);
277 }
278 
279 static const struct file_operations ima_ascii_measurements_ops = {
280 	.open = ima_ascii_measurements_open,
281 	.read = seq_read,
282 	.llseek = seq_lseek,
283 	.release = seq_release,
284 };
285 
286 static ssize_t ima_read_policy(char *path)
287 {
288 	void *data = NULL;
289 	char *datap;
290 	size_t size;
291 	int rc, pathlen = strlen(path);
292 
293 	char *p;
294 
295 	/* remove \n */
296 	datap = path;
297 	strsep(&datap, "\n");
298 
299 	rc = kernel_read_file_from_path(path, 0, &data, INT_MAX, NULL,
300 					READING_POLICY);
301 	if (rc < 0) {
302 		pr_err("Unable to open file: %s (%d)", path, rc);
303 		return rc;
304 	}
305 	size = rc;
306 	rc = 0;
307 
308 	datap = data;
309 	while (size > 0 && (p = strsep(&datap, "\n"))) {
310 		pr_debug("rule: %s\n", p);
311 		rc = ima_parse_add_rule(p);
312 		if (rc < 0)
313 			break;
314 		size -= rc;
315 	}
316 
317 	vfree(data);
318 	if (rc < 0)
319 		return rc;
320 	else if (size)
321 		return -EINVAL;
322 	else
323 		return pathlen;
324 }
325 
326 static ssize_t ima_write_policy(struct file *file, const char __user *buf,
327 				size_t datalen, loff_t *ppos)
328 {
329 	char *data;
330 	ssize_t result;
331 
332 	if (datalen >= PAGE_SIZE)
333 		datalen = PAGE_SIZE - 1;
334 
335 	/* No partial writes. */
336 	result = -EINVAL;
337 	if (*ppos != 0)
338 		goto out;
339 
340 	data = memdup_user_nul(buf, datalen);
341 	if (IS_ERR(data)) {
342 		result = PTR_ERR(data);
343 		goto out;
344 	}
345 
346 	result = mutex_lock_interruptible(&ima_write_mutex);
347 	if (result < 0)
348 		goto out_free;
349 
350 	if (data[0] == '/') {
351 		result = ima_read_policy(data);
352 	} else if (ima_appraise & IMA_APPRAISE_POLICY) {
353 		pr_err("signed policy file (specified as an absolute pathname) required\n");
354 		integrity_audit_msg(AUDIT_INTEGRITY_STATUS, NULL, NULL,
355 				    "policy_update", "signed policy required",
356 				    1, 0);
357 		result = -EACCES;
358 	} else {
359 		result = ima_parse_add_rule(data);
360 	}
361 	mutex_unlock(&ima_write_mutex);
362 out_free:
363 	kfree(data);
364 out:
365 	if (result < 0)
366 		valid_policy = 0;
367 
368 	return result;
369 }
370 
371 static struct dentry *ima_dir;
372 static struct dentry *ima_symlink;
373 
374 enum ima_fs_flags {
375 	IMA_FS_BUSY,
376 };
377 
378 static unsigned long ima_fs_flags;
379 
380 #ifdef	CONFIG_IMA_READ_POLICY
381 static const struct seq_operations ima_policy_seqops = {
382 		.start = ima_policy_start,
383 		.next = ima_policy_next,
384 		.stop = ima_policy_stop,
385 		.show = ima_policy_show,
386 };
387 #endif
388 
389 static int __init create_securityfs_measurement_lists(void)
390 {
391 	int count = NR_BANKS(ima_tpm_chip);
392 
393 	if (ima_sha1_idx >= NR_BANKS(ima_tpm_chip))
394 		count++;
395 
396 	for (int i = 0; i < count; i++) {
397 		u16 algo = ima_algo_array[i].algo;
398 		char file_name[NAME_MAX + 1];
399 		struct dentry *dentry;
400 
401 		if (algo == HASH_ALGO__LAST)
402 			sprintf(file_name, "ascii_runtime_measurements_tpm_alg_%x",
403 				ima_tpm_chip->allocated_banks[i].alg_id);
404 		else
405 			sprintf(file_name, "ascii_runtime_measurements_%s",
406 				hash_algo_name[algo]);
407 		dentry = securityfs_create_file(file_name, S_IRUSR | S_IRGRP,
408 						ima_dir, (void *)(uintptr_t)i,
409 						&ima_ascii_measurements_ops);
410 		if (IS_ERR(dentry))
411 			return PTR_ERR(dentry);
412 
413 		if (algo == HASH_ALGO__LAST)
414 			sprintf(file_name, "binary_runtime_measurements_tpm_alg_%x",
415 				ima_tpm_chip->allocated_banks[i].alg_id);
416 		else
417 			sprintf(file_name, "binary_runtime_measurements_%s",
418 				hash_algo_name[algo]);
419 		dentry = securityfs_create_file(file_name, S_IRUSR | S_IRGRP,
420 						ima_dir, (void *)(uintptr_t)i,
421 						&ima_measurements_ops);
422 		if (IS_ERR(dentry))
423 			return PTR_ERR(dentry);
424 	}
425 
426 	return 0;
427 }
428 
429 /*
430  * ima_open_policy: sequentialize access to the policy file
431  */
432 static int ima_open_policy(struct inode *inode, struct file *filp)
433 {
434 	if (!(filp->f_flags & O_WRONLY)) {
435 #ifndef	CONFIG_IMA_READ_POLICY
436 		return -EACCES;
437 #else
438 		if ((filp->f_flags & O_ACCMODE) != O_RDONLY)
439 			return -EACCES;
440 		if (!capable(CAP_SYS_ADMIN))
441 			return -EPERM;
442 		return seq_open(filp, &ima_policy_seqops);
443 #endif
444 	}
445 	if (test_and_set_bit(IMA_FS_BUSY, &ima_fs_flags))
446 		return -EBUSY;
447 	return 0;
448 }
449 
450 /*
451  * ima_release_policy - start using the new measure policy rules.
452  *
453  * Initially, ima_measure points to the default policy rules, now
454  * point to the new policy rules, and remove the securityfs policy file,
455  * assuming a valid policy.
456  */
457 static int ima_release_policy(struct inode *inode, struct file *file)
458 {
459 	const char *cause = valid_policy ? "completed" : "failed";
460 
461 	if ((file->f_flags & O_ACCMODE) == O_RDONLY)
462 		return seq_release(inode, file);
463 
464 	if (valid_policy && ima_check_policy() < 0) {
465 		cause = "failed";
466 		valid_policy = 0;
467 	}
468 
469 	pr_info("policy update %s\n", cause);
470 	integrity_audit_msg(AUDIT_INTEGRITY_STATUS, NULL, NULL,
471 			    "policy_update", cause, !valid_policy, 0);
472 
473 	if (!valid_policy) {
474 		ima_delete_rules();
475 		valid_policy = 1;
476 		clear_bit(IMA_FS_BUSY, &ima_fs_flags);
477 		return 0;
478 	}
479 
480 	ima_update_policy();
481 #if !defined(CONFIG_IMA_WRITE_POLICY) && !defined(CONFIG_IMA_READ_POLICY)
482 	securityfs_remove(file->f_path.dentry);
483 #elif defined(CONFIG_IMA_WRITE_POLICY)
484 	clear_bit(IMA_FS_BUSY, &ima_fs_flags);
485 #elif defined(CONFIG_IMA_READ_POLICY)
486 	inode->i_mode &= ~S_IWUSR;
487 #endif
488 	return 0;
489 }
490 
491 static const struct file_operations ima_measure_policy_ops = {
492 	.open = ima_open_policy,
493 	.write = ima_write_policy,
494 	.read = seq_read,
495 	.release = ima_release_policy,
496 	.llseek = generic_file_llseek,
497 };
498 
499 int __init ima_fs_init(void)
500 {
501 	struct dentry *dentry;
502 	int ret;
503 
504 	ret = integrity_fs_init();
505 	if (ret < 0)
506 		return ret;
507 
508 	ima_dir = securityfs_create_dir("ima", integrity_dir);
509 	if (IS_ERR(ima_dir)) {
510 		ret = PTR_ERR(ima_dir);
511 		goto out;
512 	}
513 
514 	ima_symlink = securityfs_create_symlink("ima", NULL, "integrity/ima",
515 						NULL);
516 	if (IS_ERR(ima_symlink)) {
517 		ret = PTR_ERR(ima_symlink);
518 		goto out;
519 	}
520 
521 	ret = create_securityfs_measurement_lists();
522 	if (ret != 0)
523 		goto out;
524 
525 	dentry = securityfs_create_symlink("binary_runtime_measurements", ima_dir,
526 				      "binary_runtime_measurements_sha1", NULL);
527 	if (IS_ERR(dentry)) {
528 		ret = PTR_ERR(dentry);
529 		goto out;
530 	}
531 
532 	dentry = securityfs_create_symlink("ascii_runtime_measurements", ima_dir,
533 				      "ascii_runtime_measurements_sha1", NULL);
534 	if (IS_ERR(dentry)) {
535 		ret = PTR_ERR(dentry);
536 		goto out;
537 	}
538 
539 	dentry = securityfs_create_file("runtime_measurements_count",
540 				   S_IRUSR | S_IRGRP, ima_dir, NULL,
541 				   &ima_measurements_count_ops);
542 	if (IS_ERR(dentry)) {
543 		ret = PTR_ERR(dentry);
544 		goto out;
545 	}
546 
547 	dentry = securityfs_create_file("violations", S_IRUSR | S_IRGRP,
548 				   ima_dir, NULL, &ima_htable_violations_ops);
549 	if (IS_ERR(dentry)) {
550 		ret = PTR_ERR(dentry);
551 		goto out;
552 	}
553 
554 	dentry = securityfs_create_file("policy", POLICY_FILE_FLAGS,
555 					    ima_dir, NULL,
556 					    &ima_measure_policy_ops);
557 	if (IS_ERR(dentry)) {
558 		ret = PTR_ERR(dentry);
559 		goto out;
560 	}
561 
562 	return 0;
563 out:
564 	securityfs_remove(ima_symlink);
565 	securityfs_remove(ima_dir);
566 	integrity_fs_fini();
567 
568 	return ret;
569 }
570