xref: /openbmc/linux/security/integrity/ima/ima_main.c (revision 8ebc80a25f9d9bf7a8e368b266d5b740c485c362)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Integrity Measurement Architecture
4  *
5  * Copyright (C) 2005,2006,2007,2008 IBM Corporation
6  *
7  * Authors:
8  * Reiner Sailer <sailer@watson.ibm.com>
9  * Serge Hallyn <serue@us.ibm.com>
10  * Kylene Hall <kylene@us.ibm.com>
11  * Mimi Zohar <zohar@us.ibm.com>
12  *
13  * File: ima_main.c
14  *	implements the IMA hooks: ima_bprm_check, ima_file_mmap,
15  *	and ima_file_check.
16  */
17 
18 #include <linux/module.h>
19 #include <linux/file.h>
20 #include <linux/binfmts.h>
21 #include <linux/kernel_read_file.h>
22 #include <linux/mount.h>
23 #include <linux/mman.h>
24 #include <linux/slab.h>
25 #include <linux/xattr.h>
26 #include <linux/ima.h>
27 #include <linux/fs.h>
28 #include <linux/iversion.h>
29 
30 #include "ima.h"
31 
32 #ifdef CONFIG_IMA_APPRAISE
33 int ima_appraise = IMA_APPRAISE_ENFORCE;
34 #else
35 int ima_appraise;
36 #endif
37 
38 int __ro_after_init ima_hash_algo = HASH_ALGO_SHA1;
39 static int hash_setup_done;
40 
41 static struct notifier_block ima_lsm_policy_notifier = {
42 	.notifier_call = ima_lsm_policy_change,
43 };
44 
hash_setup(char * str)45 static int __init hash_setup(char *str)
46 {
47 	struct ima_template_desc *template_desc = ima_template_desc_current();
48 	int i;
49 
50 	if (hash_setup_done)
51 		return 1;
52 
53 	if (strcmp(template_desc->name, IMA_TEMPLATE_IMA_NAME) == 0) {
54 		if (strncmp(str, "sha1", 4) == 0) {
55 			ima_hash_algo = HASH_ALGO_SHA1;
56 		} else if (strncmp(str, "md5", 3) == 0) {
57 			ima_hash_algo = HASH_ALGO_MD5;
58 		} else {
59 			pr_err("invalid hash algorithm \"%s\" for template \"%s\"",
60 				str, IMA_TEMPLATE_IMA_NAME);
61 			return 1;
62 		}
63 		goto out;
64 	}
65 
66 	i = match_string(hash_algo_name, HASH_ALGO__LAST, str);
67 	if (i < 0) {
68 		pr_err("invalid hash algorithm \"%s\"", str);
69 		return 1;
70 	}
71 
72 	ima_hash_algo = i;
73 out:
74 	hash_setup_done = 1;
75 	return 1;
76 }
77 __setup("ima_hash=", hash_setup);
78 
ima_get_current_hash_algo(void)79 enum hash_algo ima_get_current_hash_algo(void)
80 {
81 	return ima_hash_algo;
82 }
83 
84 /* Prevent mmap'ing a file execute that is already mmap'ed write */
mmap_violation_check(enum ima_hooks func,struct file * file,char ** pathbuf,const char ** pathname,char * filename)85 static int mmap_violation_check(enum ima_hooks func, struct file *file,
86 				char **pathbuf, const char **pathname,
87 				char *filename)
88 {
89 	struct inode *inode;
90 	int rc = 0;
91 
92 	if ((func == MMAP_CHECK || func == MMAP_CHECK_REQPROT) &&
93 	    mapping_writably_mapped(file->f_mapping)) {
94 		rc = -ETXTBSY;
95 		inode = file_inode(file);
96 
97 		if (!*pathbuf)	/* ima_rdwr_violation possibly pre-fetched */
98 			*pathname = ima_d_path(&file->f_path, pathbuf,
99 					       filename);
100 		integrity_audit_msg(AUDIT_INTEGRITY_DATA, inode, *pathname,
101 				    "mmap_file", "mmapped_writers", rc, 0);
102 	}
103 	return rc;
104 }
105 
106 /*
107  * ima_rdwr_violation_check
108  *
109  * Only invalidate the PCR for measured files:
110  *	- Opening a file for write when already open for read,
111  *	  results in a time of measure, time of use (ToMToU) error.
112  *	- Opening a file for read when already open for write,
113  *	  could result in a file measurement error.
114  *
115  */
ima_rdwr_violation_check(struct file * file,struct integrity_iint_cache * iint,int must_measure,char ** pathbuf,const char ** pathname,char * filename)116 static void ima_rdwr_violation_check(struct file *file,
117 				     struct integrity_iint_cache *iint,
118 				     int must_measure,
119 				     char **pathbuf,
120 				     const char **pathname,
121 				     char *filename)
122 {
123 	struct inode *inode = file_inode(file);
124 	fmode_t mode = file->f_mode;
125 	bool send_tomtou = false, send_writers = false;
126 
127 	if (mode & FMODE_WRITE) {
128 		if (atomic_read(&inode->i_readcount) && IS_IMA(inode)) {
129 			if (!iint)
130 				iint = integrity_iint_find(inode);
131 			/* IMA_MEASURE is set from reader side */
132 			if (iint && test_bit(IMA_MUST_MEASURE,
133 						&iint->atomic_flags))
134 				send_tomtou = true;
135 		}
136 	} else {
137 		if (must_measure)
138 			set_bit(IMA_MUST_MEASURE, &iint->atomic_flags);
139 		if (inode_is_open_for_write(inode) && must_measure)
140 			send_writers = true;
141 	}
142 
143 	if (!send_tomtou && !send_writers)
144 		return;
145 
146 	*pathname = ima_d_path(&file->f_path, pathbuf, filename);
147 
148 	if (send_tomtou)
149 		ima_add_violation(file, *pathname, iint,
150 				  "invalid_pcr", "ToMToU");
151 	if (send_writers)
152 		ima_add_violation(file, *pathname, iint,
153 				  "invalid_pcr", "open_writers");
154 }
155 
ima_check_last_writer(struct integrity_iint_cache * iint,struct inode * inode,struct file * file)156 static void ima_check_last_writer(struct integrity_iint_cache *iint,
157 				  struct inode *inode, struct file *file)
158 {
159 	fmode_t mode = file->f_mode;
160 	bool update;
161 
162 	if (!(mode & FMODE_WRITE))
163 		return;
164 
165 	mutex_lock(&iint->mutex);
166 	if (atomic_read(&inode->i_writecount) == 1) {
167 		struct kstat stat;
168 
169 		update = test_and_clear_bit(IMA_UPDATE_XATTR,
170 					    &iint->atomic_flags);
171 		if ((iint->flags & IMA_NEW_FILE) ||
172 		    vfs_getattr_nosec(&file->f_path, &stat,
173 				      STATX_CHANGE_COOKIE,
174 				      AT_STATX_SYNC_AS_STAT) ||
175 		    !(stat.result_mask & STATX_CHANGE_COOKIE) ||
176 		    stat.change_cookie != iint->version) {
177 			iint->flags &= ~(IMA_DONE_MASK | IMA_NEW_FILE);
178 			iint->measured_pcrs = 0;
179 			if (update)
180 				ima_update_xattr(iint, file);
181 		}
182 	}
183 	mutex_unlock(&iint->mutex);
184 }
185 
186 /**
187  * ima_file_free - called on __fput()
188  * @file: pointer to file structure being freed
189  *
190  * Flag files that changed, based on i_version
191  */
ima_file_free(struct file * file)192 void ima_file_free(struct file *file)
193 {
194 	struct inode *inode = file_inode(file);
195 	struct integrity_iint_cache *iint;
196 
197 	if (!ima_policy_flag || !S_ISREG(inode->i_mode))
198 		return;
199 
200 	iint = integrity_iint_find(inode);
201 	if (!iint)
202 		return;
203 
204 	ima_check_last_writer(iint, inode, file);
205 }
206 
process_measurement(struct file * file,const struct cred * cred,u32 secid,char * buf,loff_t size,int mask,enum ima_hooks func)207 static int process_measurement(struct file *file, const struct cred *cred,
208 			       u32 secid, char *buf, loff_t size, int mask,
209 			       enum ima_hooks func)
210 {
211 	struct inode *backing_inode, *inode = file_inode(file);
212 	struct integrity_iint_cache *iint = NULL;
213 	struct ima_template_desc *template_desc = NULL;
214 	char *pathbuf = NULL;
215 	char filename[NAME_MAX];
216 	const char *pathname = NULL;
217 	int rc = 0, action, must_appraise = 0;
218 	int pcr = CONFIG_IMA_MEASURE_PCR_IDX;
219 	struct evm_ima_xattr_data *xattr_value = NULL;
220 	struct modsig *modsig = NULL;
221 	int xattr_len = 0;
222 	bool violation_check;
223 	enum hash_algo hash_algo;
224 	unsigned int allowed_algos = 0;
225 
226 	if (!ima_policy_flag || !S_ISREG(inode->i_mode))
227 		return 0;
228 
229 	/* Return an IMA_MEASURE, IMA_APPRAISE, IMA_AUDIT action
230 	 * bitmask based on the appraise/audit/measurement policy.
231 	 * Included is the appraise submask.
232 	 */
233 	action = ima_get_action(file_mnt_idmap(file), inode, cred, secid,
234 				mask, func, &pcr, &template_desc, NULL,
235 				&allowed_algos);
236 	violation_check = ((func == FILE_CHECK || func == MMAP_CHECK ||
237 			    func == MMAP_CHECK_REQPROT) &&
238 			   (ima_policy_flag & IMA_MEASURE));
239 	if (!action && !violation_check)
240 		return 0;
241 
242 	must_appraise = action & IMA_APPRAISE;
243 
244 	/*  Is the appraise rule hook specific?  */
245 	if (action & IMA_FILE_APPRAISE)
246 		func = FILE_CHECK;
247 
248 	inode_lock(inode);
249 
250 	if (action) {
251 		iint = integrity_inode_get(inode);
252 		if (!iint)
253 			rc = -ENOMEM;
254 	}
255 
256 	if (!rc && violation_check)
257 		ima_rdwr_violation_check(file, iint, action & IMA_MEASURE,
258 					 &pathbuf, &pathname, filename);
259 
260 	inode_unlock(inode);
261 
262 	if (rc)
263 		goto out;
264 	if (!action)
265 		goto out;
266 
267 	mutex_lock(&iint->mutex);
268 
269 	if (test_and_clear_bit(IMA_CHANGE_ATTR, &iint->atomic_flags))
270 		/*
271 		 * Reset appraisal flags (action and non-action rule-specific)
272 		 * if ima_inode_post_setattr was called.
273 		 */
274 		iint->flags &= ~(IMA_APPRAISE | IMA_APPRAISED |
275 				 IMA_APPRAISE_SUBMASK | IMA_APPRAISED_SUBMASK |
276 				 IMA_NONACTION_RULE_FLAGS);
277 
278 	/*
279 	 * Re-evaulate the file if either the xattr has changed or the
280 	 * kernel has no way of detecting file change on the filesystem.
281 	 * (Limited to privileged mounted filesystems.)
282 	 */
283 	if (test_and_clear_bit(IMA_CHANGE_XATTR, &iint->atomic_flags) ||
284 	    ((inode->i_sb->s_iflags & SB_I_IMA_UNVERIFIABLE_SIGNATURE) &&
285 	     !(inode->i_sb->s_iflags & SB_I_UNTRUSTED_MOUNTER) &&
286 	     !(action & IMA_FAIL_UNVERIFIABLE_SIGS))) {
287 		iint->flags &= ~IMA_DONE_MASK;
288 		iint->measured_pcrs = 0;
289 	}
290 
291 	/* Detect and re-evaluate changes made to the backing file. */
292 	backing_inode = d_real_inode(file_dentry(file));
293 	if (backing_inode != inode &&
294 	    (action & IMA_DO_MASK) && (iint->flags & IMA_DONE_MASK)) {
295 		if (!IS_I_VERSION(backing_inode) ||
296 		    backing_inode->i_sb->s_dev != iint->real_dev ||
297 		    backing_inode->i_ino != iint->real_ino ||
298 		    !inode_eq_iversion(backing_inode, iint->version)) {
299 			iint->flags &= ~IMA_DONE_MASK;
300 			iint->measured_pcrs = 0;
301 		}
302 	}
303 
304 	/* Determine if already appraised/measured based on bitmask
305 	 * (IMA_MEASURE, IMA_MEASURED, IMA_XXXX_APPRAISE, IMA_XXXX_APPRAISED,
306 	 *  IMA_AUDIT, IMA_AUDITED)
307 	 */
308 	iint->flags |= action;
309 	action &= IMA_DO_MASK;
310 	action &= ~((iint->flags & (IMA_DONE_MASK ^ IMA_MEASURED)) >> 1);
311 
312 	/* If target pcr is already measured, unset IMA_MEASURE action */
313 	if ((action & IMA_MEASURE) && (iint->measured_pcrs & (0x1 << pcr)))
314 		action ^= IMA_MEASURE;
315 
316 	/* HASH sets the digital signature and update flags, nothing else */
317 	if ((action & IMA_HASH) &&
318 	    !(test_bit(IMA_DIGSIG, &iint->atomic_flags))) {
319 		xattr_len = ima_read_xattr(file_dentry(file),
320 					   &xattr_value, xattr_len);
321 		if ((xattr_value && xattr_len > 2) &&
322 		    (xattr_value->type == EVM_IMA_XATTR_DIGSIG))
323 			set_bit(IMA_DIGSIG, &iint->atomic_flags);
324 		iint->flags |= IMA_HASHED;
325 		action ^= IMA_HASH;
326 		set_bit(IMA_UPDATE_XATTR, &iint->atomic_flags);
327 	}
328 
329 	/* Nothing to do, just return existing appraised status */
330 	if (!action) {
331 		if (must_appraise) {
332 			rc = mmap_violation_check(func, file, &pathbuf,
333 						  &pathname, filename);
334 			if (!rc)
335 				rc = ima_get_cache_status(iint, func);
336 		}
337 		goto out_locked;
338 	}
339 
340 	if ((action & IMA_APPRAISE_SUBMASK) ||
341 	    strcmp(template_desc->name, IMA_TEMPLATE_IMA_NAME) != 0) {
342 		/* read 'security.ima' */
343 		xattr_len = ima_read_xattr(file_dentry(file),
344 					   &xattr_value, xattr_len);
345 
346 		/*
347 		 * Read the appended modsig if allowed by the policy, and allow
348 		 * an additional measurement list entry, if needed, based on the
349 		 * template format and whether the file was already measured.
350 		 */
351 		if (iint->flags & IMA_MODSIG_ALLOWED) {
352 			rc = ima_read_modsig(func, buf, size, &modsig);
353 
354 			if (!rc && ima_template_has_modsig(template_desc) &&
355 			    iint->flags & IMA_MEASURED)
356 				action |= IMA_MEASURE;
357 		}
358 	}
359 
360 	hash_algo = ima_get_hash_algo(xattr_value, xattr_len);
361 
362 	rc = ima_collect_measurement(iint, file, buf, size, hash_algo, modsig);
363 	if (rc != 0 && rc != -EBADF && rc != -EINVAL)
364 		goto out_locked;
365 
366 	if (!pathbuf)	/* ima_rdwr_violation possibly pre-fetched */
367 		pathname = ima_d_path(&file->f_path, &pathbuf, filename);
368 
369 	if (action & IMA_MEASURE)
370 		ima_store_measurement(iint, file, pathname,
371 				      xattr_value, xattr_len, modsig, pcr,
372 				      template_desc);
373 	if (rc == 0 && (action & IMA_APPRAISE_SUBMASK)) {
374 		rc = ima_check_blacklist(iint, modsig, pcr);
375 		if (rc != -EPERM) {
376 			inode_lock(inode);
377 			rc = ima_appraise_measurement(func, iint, file,
378 						      pathname, xattr_value,
379 						      xattr_len, modsig);
380 			inode_unlock(inode);
381 		}
382 		if (!rc)
383 			rc = mmap_violation_check(func, file, &pathbuf,
384 						  &pathname, filename);
385 	}
386 	if (action & IMA_AUDIT)
387 		ima_audit_measurement(iint, pathname);
388 
389 	if ((file->f_flags & O_DIRECT) && (iint->flags & IMA_PERMIT_DIRECTIO))
390 		rc = 0;
391 
392 	/* Ensure the digest was generated using an allowed algorithm */
393 	if (rc == 0 && must_appraise && allowed_algos != 0 &&
394 	    (allowed_algos & (1U << hash_algo)) == 0) {
395 		rc = -EACCES;
396 
397 		integrity_audit_msg(AUDIT_INTEGRITY_DATA, file_inode(file),
398 				    pathname, "collect_data",
399 				    "denied-hash-algorithm", rc, 0);
400 	}
401 out_locked:
402 	if ((mask & MAY_WRITE) && test_bit(IMA_DIGSIG, &iint->atomic_flags) &&
403 	     !(iint->flags & IMA_NEW_FILE))
404 		rc = -EACCES;
405 	mutex_unlock(&iint->mutex);
406 	kfree(xattr_value);
407 	ima_free_modsig(modsig);
408 out:
409 	if (pathbuf)
410 		__putname(pathbuf);
411 	if (must_appraise) {
412 		if (rc && (ima_appraise & IMA_APPRAISE_ENFORCE))
413 			return -EACCES;
414 		if (file->f_mode & FMODE_WRITE)
415 			set_bit(IMA_UPDATE_XATTR, &iint->atomic_flags);
416 	}
417 	return 0;
418 }
419 
420 /**
421  * ima_file_mmap - based on policy, collect/store measurement.
422  * @file: pointer to the file to be measured (May be NULL)
423  * @reqprot: protection requested by the application
424  * @prot: protection that will be applied by the kernel
425  * @flags: operational flags
426  *
427  * Measure files being mmapped executable based on the ima_must_measure()
428  * policy decision.
429  *
430  * On success return 0.  On integrity appraisal error, assuming the file
431  * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
432  */
ima_file_mmap(struct file * file,unsigned long reqprot,unsigned long prot,unsigned long flags)433 int ima_file_mmap(struct file *file, unsigned long reqprot,
434 		  unsigned long prot, unsigned long flags)
435 {
436 	u32 secid;
437 	int ret;
438 
439 	if (!file)
440 		return 0;
441 
442 	security_current_getsecid_subj(&secid);
443 
444 	if (reqprot & PROT_EXEC) {
445 		ret = process_measurement(file, current_cred(), secid, NULL,
446 					  0, MAY_EXEC, MMAP_CHECK_REQPROT);
447 		if (ret)
448 			return ret;
449 	}
450 
451 	if (prot & PROT_EXEC)
452 		return process_measurement(file, current_cred(), secid, NULL,
453 					   0, MAY_EXEC, MMAP_CHECK);
454 
455 	return 0;
456 }
457 
458 /**
459  * ima_file_mprotect - based on policy, limit mprotect change
460  * @vma: vm_area_struct protection is set to
461  * @prot: contains the protection that will be applied by the kernel.
462  *
463  * Files can be mmap'ed read/write and later changed to execute to circumvent
464  * IMA's mmap appraisal policy rules.  Due to locking issues (mmap semaphore
465  * would be taken before i_mutex), files can not be measured or appraised at
466  * this point.  Eliminate this integrity gap by denying the mprotect
467  * PROT_EXECUTE change, if an mmap appraise policy rule exists.
468  *
469  * On mprotect change success, return 0.  On failure, return -EACESS.
470  */
ima_file_mprotect(struct vm_area_struct * vma,unsigned long prot)471 int ima_file_mprotect(struct vm_area_struct *vma, unsigned long prot)
472 {
473 	struct ima_template_desc *template = NULL;
474 	struct file *file;
475 	char filename[NAME_MAX];
476 	char *pathbuf = NULL;
477 	const char *pathname = NULL;
478 	struct inode *inode;
479 	int result = 0;
480 	int action;
481 	u32 secid;
482 	int pcr;
483 
484 	/* Is mprotect making an mmap'ed file executable? */
485 	if (!(ima_policy_flag & IMA_APPRAISE) || !vma->vm_file ||
486 	    !(prot & PROT_EXEC) || (vma->vm_flags & VM_EXEC))
487 		return 0;
488 
489 	security_current_getsecid_subj(&secid);
490 	inode = file_inode(vma->vm_file);
491 	action = ima_get_action(file_mnt_idmap(vma->vm_file), inode,
492 				current_cred(), secid, MAY_EXEC, MMAP_CHECK,
493 				&pcr, &template, NULL, NULL);
494 	action |= ima_get_action(file_mnt_idmap(vma->vm_file), inode,
495 				 current_cred(), secid, MAY_EXEC,
496 				 MMAP_CHECK_REQPROT, &pcr, &template, NULL,
497 				 NULL);
498 
499 	/* Is the mmap'ed file in policy? */
500 	if (!(action & (IMA_MEASURE | IMA_APPRAISE_SUBMASK)))
501 		return 0;
502 
503 	if (action & IMA_APPRAISE_SUBMASK)
504 		result = -EPERM;
505 
506 	file = vma->vm_file;
507 	pathname = ima_d_path(&file->f_path, &pathbuf, filename);
508 	integrity_audit_msg(AUDIT_INTEGRITY_DATA, inode, pathname,
509 			    "collect_data", "failed-mprotect", result, 0);
510 	if (pathbuf)
511 		__putname(pathbuf);
512 
513 	return result;
514 }
515 
516 /**
517  * ima_bprm_check - based on policy, collect/store measurement.
518  * @bprm: contains the linux_binprm structure
519  *
520  * The OS protects against an executable file, already open for write,
521  * from being executed in deny_write_access() and an executable file,
522  * already open for execute, from being modified in get_write_access().
523  * So we can be certain that what we verify and measure here is actually
524  * what is being executed.
525  *
526  * On success return 0.  On integrity appraisal error, assuming the file
527  * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
528  */
ima_bprm_check(struct linux_binprm * bprm)529 int ima_bprm_check(struct linux_binprm *bprm)
530 {
531 	int ret;
532 	u32 secid;
533 
534 	security_current_getsecid_subj(&secid);
535 	ret = process_measurement(bprm->file, current_cred(), secid, NULL, 0,
536 				  MAY_EXEC, BPRM_CHECK);
537 	if (ret)
538 		return ret;
539 
540 	security_cred_getsecid(bprm->cred, &secid);
541 	return process_measurement(bprm->file, bprm->cred, secid, NULL, 0,
542 				   MAY_EXEC, CREDS_CHECK);
543 }
544 
545 /**
546  * ima_file_check - based on policy, collect/store measurement.
547  * @file: pointer to the file to be measured
548  * @mask: contains MAY_READ, MAY_WRITE, MAY_EXEC or MAY_APPEND
549  *
550  * Measure files based on the ima_must_measure() policy decision.
551  *
552  * On success return 0.  On integrity appraisal error, assuming the file
553  * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
554  */
ima_file_check(struct file * file,int mask)555 int ima_file_check(struct file *file, int mask)
556 {
557 	u32 secid;
558 
559 	security_current_getsecid_subj(&secid);
560 	return process_measurement(file, current_cred(), secid, NULL, 0,
561 				   mask & (MAY_READ | MAY_WRITE | MAY_EXEC |
562 					   MAY_APPEND), FILE_CHECK);
563 }
564 EXPORT_SYMBOL_GPL(ima_file_check);
565 
__ima_inode_hash(struct inode * inode,struct file * file,char * buf,size_t buf_size)566 static int __ima_inode_hash(struct inode *inode, struct file *file, char *buf,
567 			    size_t buf_size)
568 {
569 	struct integrity_iint_cache *iint = NULL, tmp_iint;
570 	int rc, hash_algo;
571 
572 	if (ima_policy_flag) {
573 		iint = integrity_iint_find(inode);
574 		if (iint)
575 			mutex_lock(&iint->mutex);
576 	}
577 
578 	if ((!iint || !(iint->flags & IMA_COLLECTED)) && file) {
579 		if (iint)
580 			mutex_unlock(&iint->mutex);
581 
582 		memset(&tmp_iint, 0, sizeof(tmp_iint));
583 		tmp_iint.inode = inode;
584 		mutex_init(&tmp_iint.mutex);
585 
586 		rc = ima_collect_measurement(&tmp_iint, file, NULL, 0,
587 					     ima_hash_algo, NULL);
588 		if (rc < 0) {
589 			/* ima_hash could be allocated in case of failure. */
590 			if (rc != -ENOMEM)
591 				kfree(tmp_iint.ima_hash);
592 
593 			return -EOPNOTSUPP;
594 		}
595 
596 		iint = &tmp_iint;
597 		mutex_lock(&iint->mutex);
598 	}
599 
600 	if (!iint)
601 		return -EOPNOTSUPP;
602 
603 	/*
604 	 * ima_file_hash can be called when ima_collect_measurement has still
605 	 * not been called, we might not always have a hash.
606 	 */
607 	if (!iint->ima_hash || !(iint->flags & IMA_COLLECTED)) {
608 		mutex_unlock(&iint->mutex);
609 		return -EOPNOTSUPP;
610 	}
611 
612 	if (buf) {
613 		size_t copied_size;
614 
615 		copied_size = min_t(size_t, iint->ima_hash->length, buf_size);
616 		memcpy(buf, iint->ima_hash->digest, copied_size);
617 	}
618 	hash_algo = iint->ima_hash->algo;
619 	mutex_unlock(&iint->mutex);
620 
621 	if (iint == &tmp_iint)
622 		kfree(iint->ima_hash);
623 
624 	return hash_algo;
625 }
626 
627 /**
628  * ima_file_hash - return a measurement of the file
629  * @file: pointer to the file
630  * @buf: buffer in which to store the hash
631  * @buf_size: length of the buffer
632  *
633  * On success, return the hash algorithm (as defined in the enum hash_algo).
634  * If buf is not NULL, this function also outputs the hash into buf.
635  * If the hash is larger than buf_size, then only buf_size bytes will be copied.
636  * It generally just makes sense to pass a buffer capable of holding the largest
637  * possible hash: IMA_MAX_DIGEST_SIZE.
638  * The file hash returned is based on the entire file, including the appended
639  * signature.
640  *
641  * If the measurement cannot be performed, return -EOPNOTSUPP.
642  * If the parameters are incorrect, return -EINVAL.
643  */
ima_file_hash(struct file * file,char * buf,size_t buf_size)644 int ima_file_hash(struct file *file, char *buf, size_t buf_size)
645 {
646 	if (!file)
647 		return -EINVAL;
648 
649 	return __ima_inode_hash(file_inode(file), file, buf, buf_size);
650 }
651 EXPORT_SYMBOL_GPL(ima_file_hash);
652 
653 /**
654  * ima_inode_hash - return the stored measurement if the inode has been hashed
655  * and is in the iint cache.
656  * @inode: pointer to the inode
657  * @buf: buffer in which to store the hash
658  * @buf_size: length of the buffer
659  *
660  * On success, return the hash algorithm (as defined in the enum hash_algo).
661  * If buf is not NULL, this function also outputs the hash into buf.
662  * If the hash is larger than buf_size, then only buf_size bytes will be copied.
663  * It generally just makes sense to pass a buffer capable of holding the largest
664  * possible hash: IMA_MAX_DIGEST_SIZE.
665  * The hash returned is based on the entire contents, including the appended
666  * signature.
667  *
668  * If IMA is disabled or if no measurement is available, return -EOPNOTSUPP.
669  * If the parameters are incorrect, return -EINVAL.
670  */
ima_inode_hash(struct inode * inode,char * buf,size_t buf_size)671 int ima_inode_hash(struct inode *inode, char *buf, size_t buf_size)
672 {
673 	if (!inode)
674 		return -EINVAL;
675 
676 	return __ima_inode_hash(inode, NULL, buf, buf_size);
677 }
678 EXPORT_SYMBOL_GPL(ima_inode_hash);
679 
680 /**
681  * ima_post_create_tmpfile - mark newly created tmpfile as new
682  * @idmap: idmap of the mount the inode was found from
683  * @inode: inode of the newly created tmpfile
684  *
685  * No measuring, appraising or auditing of newly created tmpfiles is needed.
686  * Skip calling process_measurement(), but indicate which newly, created
687  * tmpfiles are in policy.
688  */
ima_post_create_tmpfile(struct mnt_idmap * idmap,struct inode * inode)689 void ima_post_create_tmpfile(struct mnt_idmap *idmap,
690 			     struct inode *inode)
691 {
692 	struct integrity_iint_cache *iint;
693 	int must_appraise;
694 
695 	if (!ima_policy_flag || !S_ISREG(inode->i_mode))
696 		return;
697 
698 	must_appraise = ima_must_appraise(idmap, inode, MAY_ACCESS,
699 					  FILE_CHECK);
700 	if (!must_appraise)
701 		return;
702 
703 	/* Nothing to do if we can't allocate memory */
704 	iint = integrity_inode_get(inode);
705 	if (!iint)
706 		return;
707 
708 	/* needed for writing the security xattrs */
709 	set_bit(IMA_UPDATE_XATTR, &iint->atomic_flags);
710 	iint->ima_file_status = INTEGRITY_PASS;
711 }
712 
713 /**
714  * ima_post_path_mknod - mark as a new inode
715  * @idmap: idmap of the mount the inode was found from
716  * @dentry: newly created dentry
717  *
718  * Mark files created via the mknodat syscall as new, so that the
719  * file data can be written later.
720  */
ima_post_path_mknod(struct mnt_idmap * idmap,struct dentry * dentry)721 void ima_post_path_mknod(struct mnt_idmap *idmap,
722 			 struct dentry *dentry)
723 {
724 	struct integrity_iint_cache *iint;
725 	struct inode *inode = dentry->d_inode;
726 	int must_appraise;
727 
728 	if (!ima_policy_flag || !S_ISREG(inode->i_mode))
729 		return;
730 
731 	must_appraise = ima_must_appraise(idmap, inode, MAY_ACCESS,
732 					  FILE_CHECK);
733 	if (!must_appraise)
734 		return;
735 
736 	/* Nothing to do if we can't allocate memory */
737 	iint = integrity_inode_get(inode);
738 	if (!iint)
739 		return;
740 
741 	/* needed for re-opening empty files */
742 	iint->flags |= IMA_NEW_FILE;
743 }
744 
745 /**
746  * ima_read_file - pre-measure/appraise hook decision based on policy
747  * @file: pointer to the file to be measured/appraised/audit
748  * @read_id: caller identifier
749  * @contents: whether a subsequent call will be made to ima_post_read_file()
750  *
751  * Permit reading a file based on policy. The policy rules are written
752  * in terms of the policy identifier.  Appraising the integrity of
753  * a file requires a file descriptor.
754  *
755  * For permission return 0, otherwise return -EACCES.
756  */
ima_read_file(struct file * file,enum kernel_read_file_id read_id,bool contents)757 int ima_read_file(struct file *file, enum kernel_read_file_id read_id,
758 		  bool contents)
759 {
760 	enum ima_hooks func;
761 	u32 secid;
762 
763 	/*
764 	 * Do devices using pre-allocated memory run the risk of the
765 	 * firmware being accessible to the device prior to the completion
766 	 * of IMA's signature verification any more than when using two
767 	 * buffers? It may be desirable to include the buffer address
768 	 * in this API and walk all the dma_map_single() mappings to check.
769 	 */
770 
771 	/*
772 	 * There will be a call made to ima_post_read_file() with
773 	 * a filled buffer, so we don't need to perform an extra
774 	 * read early here.
775 	 */
776 	if (contents)
777 		return 0;
778 
779 	/* Read entire file for all partial reads. */
780 	func = read_idmap[read_id] ?: FILE_CHECK;
781 	security_current_getsecid_subj(&secid);
782 	return process_measurement(file, current_cred(), secid, NULL,
783 				   0, MAY_READ, func);
784 }
785 
786 const int read_idmap[READING_MAX_ID] = {
787 	[READING_FIRMWARE] = FIRMWARE_CHECK,
788 	[READING_MODULE] = MODULE_CHECK,
789 	[READING_KEXEC_IMAGE] = KEXEC_KERNEL_CHECK,
790 	[READING_KEXEC_INITRAMFS] = KEXEC_INITRAMFS_CHECK,
791 	[READING_POLICY] = POLICY_CHECK
792 };
793 
794 /**
795  * ima_post_read_file - in memory collect/appraise/audit measurement
796  * @file: pointer to the file to be measured/appraised/audit
797  * @buf: pointer to in memory file contents
798  * @size: size of in memory file contents
799  * @read_id: caller identifier
800  *
801  * Measure/appraise/audit in memory file based on policy.  Policy rules
802  * are written in terms of a policy identifier.
803  *
804  * On success return 0.  On integrity appraisal error, assuming the file
805  * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
806  */
ima_post_read_file(struct file * file,void * buf,loff_t size,enum kernel_read_file_id read_id)807 int ima_post_read_file(struct file *file, void *buf, loff_t size,
808 		       enum kernel_read_file_id read_id)
809 {
810 	enum ima_hooks func;
811 	u32 secid;
812 
813 	/* permit signed certs */
814 	if (!file && read_id == READING_X509_CERTIFICATE)
815 		return 0;
816 
817 	if (!file || !buf || size == 0) { /* should never happen */
818 		if (ima_appraise & IMA_APPRAISE_ENFORCE)
819 			return -EACCES;
820 		return 0;
821 	}
822 
823 	func = read_idmap[read_id] ?: FILE_CHECK;
824 	security_current_getsecid_subj(&secid);
825 	return process_measurement(file, current_cred(), secid, buf, size,
826 				   MAY_READ, func);
827 }
828 
829 /**
830  * ima_load_data - appraise decision based on policy
831  * @id: kernel load data caller identifier
832  * @contents: whether the full contents will be available in a later
833  *	      call to ima_post_load_data().
834  *
835  * Callers of this LSM hook can not measure, appraise, or audit the
836  * data provided by userspace.  Enforce policy rules requiring a file
837  * signature (eg. kexec'ed kernel image).
838  *
839  * For permission return 0, otherwise return -EACCES.
840  */
ima_load_data(enum kernel_load_data_id id,bool contents)841 int ima_load_data(enum kernel_load_data_id id, bool contents)
842 {
843 	bool ima_enforce, sig_enforce;
844 
845 	ima_enforce =
846 		(ima_appraise & IMA_APPRAISE_ENFORCE) == IMA_APPRAISE_ENFORCE;
847 
848 	switch (id) {
849 	case LOADING_KEXEC_IMAGE:
850 		if (IS_ENABLED(CONFIG_KEXEC_SIG)
851 		    && arch_ima_get_secureboot()) {
852 			pr_err("impossible to appraise a kernel image without a file descriptor; try using kexec_file_load syscall.\n");
853 			return -EACCES;
854 		}
855 
856 		if (ima_enforce && (ima_appraise & IMA_APPRAISE_KEXEC)) {
857 			pr_err("impossible to appraise a kernel image without a file descriptor; try using kexec_file_load syscall.\n");
858 			return -EACCES;	/* INTEGRITY_UNKNOWN */
859 		}
860 		break;
861 	case LOADING_FIRMWARE:
862 		if (ima_enforce && (ima_appraise & IMA_APPRAISE_FIRMWARE) && !contents) {
863 			pr_err("Prevent firmware sysfs fallback loading.\n");
864 			return -EACCES;	/* INTEGRITY_UNKNOWN */
865 		}
866 		break;
867 	case LOADING_MODULE:
868 		sig_enforce = is_module_sig_enforced();
869 
870 		if (ima_enforce && (!sig_enforce
871 				    && (ima_appraise & IMA_APPRAISE_MODULES))) {
872 			pr_err("impossible to appraise a module without a file descriptor. sig_enforce kernel parameter might help\n");
873 			return -EACCES;	/* INTEGRITY_UNKNOWN */
874 		}
875 		break;
876 	default:
877 		break;
878 	}
879 	return 0;
880 }
881 
882 /**
883  * ima_post_load_data - appraise decision based on policy
884  * @buf: pointer to in memory file contents
885  * @size: size of in memory file contents
886  * @load_id: kernel load data caller identifier
887  * @description: @load_id-specific description of contents
888  *
889  * Measure/appraise/audit in memory buffer based on policy.  Policy rules
890  * are written in terms of a policy identifier.
891  *
892  * On success return 0.  On integrity appraisal error, assuming the file
893  * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
894  */
ima_post_load_data(char * buf,loff_t size,enum kernel_load_data_id load_id,char * description)895 int ima_post_load_data(char *buf, loff_t size,
896 		       enum kernel_load_data_id load_id,
897 		       char *description)
898 {
899 	if (load_id == LOADING_FIRMWARE) {
900 		if ((ima_appraise & IMA_APPRAISE_FIRMWARE) &&
901 		    (ima_appraise & IMA_APPRAISE_ENFORCE)) {
902 			pr_err("Prevent firmware loading_store.\n");
903 			return -EACCES; /* INTEGRITY_UNKNOWN */
904 		}
905 		return 0;
906 	}
907 
908 	return 0;
909 }
910 
911 /**
912  * process_buffer_measurement - Measure the buffer or the buffer data hash
913  * @idmap: idmap of the mount the inode was found from
914  * @inode: inode associated with the object being measured (NULL for KEY_CHECK)
915  * @buf: pointer to the buffer that needs to be added to the log.
916  * @size: size of buffer(in bytes).
917  * @eventname: event name to be used for the buffer entry.
918  * @func: IMA hook
919  * @pcr: pcr to extend the measurement
920  * @func_data: func specific data, may be NULL
921  * @buf_hash: measure buffer data hash
922  * @digest: buffer digest will be written to
923  * @digest_len: buffer length
924  *
925  * Based on policy, either the buffer data or buffer data hash is measured
926  *
927  * Return: 0 if the buffer has been successfully measured, 1 if the digest
928  * has been written to the passed location but not added to a measurement entry,
929  * a negative value otherwise.
930  */
process_buffer_measurement(struct mnt_idmap * idmap,struct inode * inode,const void * buf,int size,const char * eventname,enum ima_hooks func,int pcr,const char * func_data,bool buf_hash,u8 * digest,size_t digest_len)931 int process_buffer_measurement(struct mnt_idmap *idmap,
932 			       struct inode *inode, const void *buf, int size,
933 			       const char *eventname, enum ima_hooks func,
934 			       int pcr, const char *func_data,
935 			       bool buf_hash, u8 *digest, size_t digest_len)
936 {
937 	int ret = 0;
938 	const char *audit_cause = "ENOMEM";
939 	struct ima_template_entry *entry = NULL;
940 	struct integrity_iint_cache iint = {};
941 	struct ima_event_data event_data = {.iint = &iint,
942 					    .filename = eventname,
943 					    .buf = buf,
944 					    .buf_len = size};
945 	struct ima_template_desc *template;
946 	struct ima_max_digest_data hash;
947 	char digest_hash[IMA_MAX_DIGEST_SIZE];
948 	int digest_hash_len = hash_digest_size[ima_hash_algo];
949 	int violation = 0;
950 	int action = 0;
951 	u32 secid;
952 
953 	if (digest && digest_len < digest_hash_len)
954 		return -EINVAL;
955 
956 	if (!ima_policy_flag && !digest)
957 		return -ENOENT;
958 
959 	template = ima_template_desc_buf();
960 	if (!template) {
961 		ret = -EINVAL;
962 		audit_cause = "ima_template_desc_buf";
963 		goto out;
964 	}
965 
966 	/*
967 	 * Both LSM hooks and auxilary based buffer measurements are
968 	 * based on policy.  To avoid code duplication, differentiate
969 	 * between the LSM hooks and auxilary buffer measurements,
970 	 * retrieving the policy rule information only for the LSM hook
971 	 * buffer measurements.
972 	 */
973 	if (func) {
974 		security_current_getsecid_subj(&secid);
975 		action = ima_get_action(idmap, inode, current_cred(),
976 					secid, 0, func, &pcr, &template,
977 					func_data, NULL);
978 		if (!(action & IMA_MEASURE) && !digest)
979 			return -ENOENT;
980 	}
981 
982 	if (!pcr)
983 		pcr = CONFIG_IMA_MEASURE_PCR_IDX;
984 
985 	iint.ima_hash = &hash.hdr;
986 	iint.ima_hash->algo = ima_hash_algo;
987 	iint.ima_hash->length = hash_digest_size[ima_hash_algo];
988 
989 	ret = ima_calc_buffer_hash(buf, size, iint.ima_hash);
990 	if (ret < 0) {
991 		audit_cause = "hashing_error";
992 		goto out;
993 	}
994 
995 	if (buf_hash) {
996 		memcpy(digest_hash, hash.hdr.digest, digest_hash_len);
997 
998 		ret = ima_calc_buffer_hash(digest_hash, digest_hash_len,
999 					   iint.ima_hash);
1000 		if (ret < 0) {
1001 			audit_cause = "hashing_error";
1002 			goto out;
1003 		}
1004 
1005 		event_data.buf = digest_hash;
1006 		event_data.buf_len = digest_hash_len;
1007 	}
1008 
1009 	if (digest)
1010 		memcpy(digest, iint.ima_hash->digest, digest_hash_len);
1011 
1012 	if (!ima_policy_flag || (func && !(action & IMA_MEASURE)))
1013 		return 1;
1014 
1015 	ret = ima_alloc_init_template(&event_data, &entry, template);
1016 	if (ret < 0) {
1017 		audit_cause = "alloc_entry";
1018 		goto out;
1019 	}
1020 
1021 	ret = ima_store_template(entry, violation, NULL, event_data.buf, pcr);
1022 	if (ret < 0) {
1023 		audit_cause = "store_entry";
1024 		ima_free_template_entry(entry);
1025 	}
1026 
1027 out:
1028 	if (ret < 0)
1029 		integrity_audit_message(AUDIT_INTEGRITY_PCR, NULL, eventname,
1030 					func_measure_str(func),
1031 					audit_cause, ret, 0, ret);
1032 
1033 	return ret;
1034 }
1035 
1036 /**
1037  * ima_kexec_cmdline - measure kexec cmdline boot args
1038  * @kernel_fd: file descriptor of the kexec kernel being loaded
1039  * @buf: pointer to buffer
1040  * @size: size of buffer
1041  *
1042  * Buffers can only be measured, not appraised.
1043  */
ima_kexec_cmdline(int kernel_fd,const void * buf,int size)1044 void ima_kexec_cmdline(int kernel_fd, const void *buf, int size)
1045 {
1046 	struct fd f;
1047 
1048 	if (!buf || !size)
1049 		return;
1050 
1051 	f = fdget(kernel_fd);
1052 	if (!f.file)
1053 		return;
1054 
1055 	process_buffer_measurement(file_mnt_idmap(f.file), file_inode(f.file),
1056 				   buf, size, "kexec-cmdline", KEXEC_CMDLINE, 0,
1057 				   NULL, false, NULL, 0);
1058 	fdput(f);
1059 }
1060 
1061 /**
1062  * ima_measure_critical_data - measure kernel integrity critical data
1063  * @event_label: unique event label for grouping and limiting critical data
1064  * @event_name: event name for the record in the IMA measurement list
1065  * @buf: pointer to buffer data
1066  * @buf_len: length of buffer data (in bytes)
1067  * @hash: measure buffer data hash
1068  * @digest: buffer digest will be written to
1069  * @digest_len: buffer length
1070  *
1071  * Measure data critical to the integrity of the kernel into the IMA log
1072  * and extend the pcr.  Examples of critical data could be various data
1073  * structures, policies, and states stored in kernel memory that can
1074  * impact the integrity of the system.
1075  *
1076  * Return: 0 if the buffer has been successfully measured, 1 if the digest
1077  * has been written to the passed location but not added to a measurement entry,
1078  * a negative value otherwise.
1079  */
ima_measure_critical_data(const char * event_label,const char * event_name,const void * buf,size_t buf_len,bool hash,u8 * digest,size_t digest_len)1080 int ima_measure_critical_data(const char *event_label,
1081 			      const char *event_name,
1082 			      const void *buf, size_t buf_len,
1083 			      bool hash, u8 *digest, size_t digest_len)
1084 {
1085 	if (!event_name || !event_label || !buf || !buf_len)
1086 		return -ENOPARAM;
1087 
1088 	return process_buffer_measurement(&nop_mnt_idmap, NULL, buf, buf_len,
1089 					  event_name, CRITICAL_DATA, 0,
1090 					  event_label, hash, digest,
1091 					  digest_len);
1092 }
1093 EXPORT_SYMBOL_GPL(ima_measure_critical_data);
1094 
init_ima(void)1095 static int __init init_ima(void)
1096 {
1097 	int error;
1098 
1099 	ima_appraise_parse_cmdline();
1100 	ima_init_template_list();
1101 	hash_setup(CONFIG_IMA_DEFAULT_HASH);
1102 	error = ima_init();
1103 
1104 	if (error && strcmp(hash_algo_name[ima_hash_algo],
1105 			    CONFIG_IMA_DEFAULT_HASH) != 0) {
1106 		pr_info("Allocating %s failed, going to use default hash algorithm %s\n",
1107 			hash_algo_name[ima_hash_algo], CONFIG_IMA_DEFAULT_HASH);
1108 		hash_setup_done = 0;
1109 		hash_setup(CONFIG_IMA_DEFAULT_HASH);
1110 		error = ima_init();
1111 	}
1112 
1113 	if (error)
1114 		return error;
1115 
1116 	error = register_blocking_lsm_notifier(&ima_lsm_policy_notifier);
1117 	if (error)
1118 		pr_warn("Couldn't register LSM notifier, error %d\n", error);
1119 
1120 	if (!error)
1121 		ima_update_policy_flags();
1122 
1123 	return error;
1124 }
1125 
1126 late_initcall(init_ima);	/* Start IMA after the TPM is available */
1127