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