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 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 
80 /* 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)81 static int mmap_violation_check(enum ima_hooks func, struct file *file,
82 				char **pathbuf, const char **pathname,
83 				char *filename)
84 {
85 	struct inode *inode;
86 	int rc = 0;
87 
88 	if ((func == MMAP_CHECK) && mapping_writably_mapped(file->f_mapping)) {
89 		rc = -ETXTBSY;
90 		inode = file_inode(file);
91 
92 		if (!*pathbuf)	/* ima_rdwr_violation possibly pre-fetched */
93 			*pathname = ima_d_path(&file->f_path, pathbuf,
94 					       filename);
95 		integrity_audit_msg(AUDIT_INTEGRITY_DATA, inode, *pathname,
96 				    "mmap_file", "mmapped_writers", rc, 0);
97 	}
98 	return rc;
99 }
100 
101 /*
102  * ima_rdwr_violation_check
103  *
104  * Only invalidate the PCR for measured files:
105  *	- Opening a file for write when already open for read,
106  *	  results in a time of measure, time of use (ToMToU) error.
107  *	- Opening a file for read when already open for write,
108  *	  could result in a file measurement error.
109  *
110  */
ima_rdwr_violation_check(struct file *file, struct integrity_iint_cache *iint, int must_measure, char **pathbuf, const char **pathname, char *filename)111 static void ima_rdwr_violation_check(struct file *file,
112 				     struct integrity_iint_cache *iint,
113 				     int must_measure,
114 				     char **pathbuf,
115 				     const char **pathname,
116 				     char *filename)
117 {
118 	struct inode *inode = file_inode(file);
119 	fmode_t mode = file->f_mode;
120 	bool send_tomtou = false, send_writers = false;
121 
122 	if (mode & FMODE_WRITE) {
123 		if (atomic_read(&inode->i_readcount) && IS_IMA(inode)) {
124 			if (!iint)
125 				iint = integrity_iint_find(inode);
126 			/* IMA_MEASURE is set from reader side */
127 			if (iint && test_bit(IMA_MUST_MEASURE,
128 						&iint->atomic_flags))
129 				send_tomtou = true;
130 		}
131 	} else {
132 		if (must_measure)
133 			set_bit(IMA_MUST_MEASURE, &iint->atomic_flags);
134 		if (inode_is_open_for_write(inode) && must_measure)
135 			send_writers = true;
136 	}
137 
138 	if (!send_tomtou && !send_writers)
139 		return;
140 
141 	*pathname = ima_d_path(&file->f_path, pathbuf, filename);
142 
143 	if (send_tomtou)
144 		ima_add_violation(file, *pathname, iint,
145 				  "invalid_pcr", "ToMToU");
146 	if (send_writers)
147 		ima_add_violation(file, *pathname, iint,
148 				  "invalid_pcr", "open_writers");
149 }
150 
ima_check_last_writer(struct integrity_iint_cache *iint, struct inode *inode, struct file *file)151 static void ima_check_last_writer(struct integrity_iint_cache *iint,
152 				  struct inode *inode, struct file *file)
153 {
154 	fmode_t mode = file->f_mode;
155 	bool update;
156 
157 	if (!(mode & FMODE_WRITE))
158 		return;
159 
160 	mutex_lock(&iint->mutex);
161 	if (atomic_read(&inode->i_writecount) == 1) {
162 		update = test_and_clear_bit(IMA_UPDATE_XATTR,
163 					    &iint->atomic_flags);
164 		if (!IS_I_VERSION(inode) ||
165 		    !inode_eq_iversion(inode, iint->version) ||
166 		    (iint->flags & IMA_NEW_FILE)) {
167 			iint->flags &= ~(IMA_DONE_MASK | IMA_NEW_FILE);
168 			iint->measured_pcrs = 0;
169 			if (update)
170 				ima_update_xattr(iint, file);
171 		}
172 	}
173 	mutex_unlock(&iint->mutex);
174 }
175 
176 /**
177  * ima_file_free - called on __fput()
178  * @file: pointer to file structure being freed
179  *
180  * Flag files that changed, based on i_version
181  */
ima_file_free(struct file *file)182 void ima_file_free(struct file *file)
183 {
184 	struct inode *inode = file_inode(file);
185 	struct integrity_iint_cache *iint;
186 
187 	if (!ima_policy_flag || !S_ISREG(inode->i_mode))
188 		return;
189 
190 	iint = integrity_iint_find(inode);
191 	if (!iint)
192 		return;
193 
194 	ima_check_last_writer(iint, inode, file);
195 }
196 
process_measurement(struct file *file, const struct cred *cred, u32 secid, char *buf, loff_t size, int mask, enum ima_hooks func)197 static int process_measurement(struct file *file, const struct cred *cred,
198 			       u32 secid, char *buf, loff_t size, int mask,
199 			       enum ima_hooks func)
200 {
201 	struct inode *backing_inode, *inode = file_inode(file);
202 	struct integrity_iint_cache *iint = NULL;
203 	struct ima_template_desc *template_desc = NULL;
204 	char *pathbuf = NULL;
205 	char filename[NAME_MAX];
206 	const char *pathname = NULL;
207 	int rc = 0, action, must_appraise = 0;
208 	int pcr = CONFIG_IMA_MEASURE_PCR_IDX;
209 	struct evm_ima_xattr_data *xattr_value = NULL;
210 	struct modsig *modsig = NULL;
211 	int xattr_len = 0;
212 	bool violation_check;
213 	enum hash_algo hash_algo;
214 
215 	if (!ima_policy_flag || !S_ISREG(inode->i_mode))
216 		return 0;
217 
218 	/* Return an IMA_MEASURE, IMA_APPRAISE, IMA_AUDIT action
219 	 * bitmask based on the appraise/audit/measurement policy.
220 	 * Included is the appraise submask.
221 	 */
222 	action = ima_get_action(inode, cred, secid, mask, func, &pcr,
223 				&template_desc, NULL);
224 	violation_check = ((func == FILE_CHECK || func == MMAP_CHECK) &&
225 			   (ima_policy_flag & IMA_MEASURE));
226 	if (!action && !violation_check)
227 		return 0;
228 
229 	must_appraise = action & IMA_APPRAISE;
230 
231 	/*  Is the appraise rule hook specific?  */
232 	if (action & IMA_FILE_APPRAISE)
233 		func = FILE_CHECK;
234 
235 	inode_lock(inode);
236 
237 	if (action) {
238 		iint = integrity_inode_get(inode);
239 		if (!iint)
240 			rc = -ENOMEM;
241 	}
242 
243 	if (!rc && violation_check)
244 		ima_rdwr_violation_check(file, iint, action & IMA_MEASURE,
245 					 &pathbuf, &pathname, filename);
246 
247 	inode_unlock(inode);
248 
249 	if (rc)
250 		goto out;
251 	if (!action)
252 		goto out;
253 
254 	mutex_lock(&iint->mutex);
255 
256 	if (test_and_clear_bit(IMA_CHANGE_ATTR, &iint->atomic_flags))
257 		/* reset appraisal flags if ima_inode_post_setattr was called */
258 		iint->flags &= ~(IMA_APPRAISE | IMA_APPRAISED |
259 				 IMA_APPRAISE_SUBMASK | IMA_APPRAISED_SUBMASK |
260 				 IMA_ACTION_FLAGS);
261 
262 	/*
263 	 * Re-evaulate the file if either the xattr has changed or the
264 	 * kernel has no way of detecting file change on the filesystem.
265 	 * (Limited to privileged mounted filesystems.)
266 	 */
267 	if (test_and_clear_bit(IMA_CHANGE_XATTR, &iint->atomic_flags) ||
268 	    ((inode->i_sb->s_iflags & SB_I_IMA_UNVERIFIABLE_SIGNATURE) &&
269 	     !(inode->i_sb->s_iflags & SB_I_UNTRUSTED_MOUNTER) &&
270 	     !(action & IMA_FAIL_UNVERIFIABLE_SIGS))) {
271 		iint->flags &= ~IMA_DONE_MASK;
272 		iint->measured_pcrs = 0;
273 	}
274 
275 	/* Detect and re-evaluate changes made to the backing file. */
276 	backing_inode = d_real_inode(file_dentry(file));
277 	if (backing_inode != inode &&
278 	    (action & IMA_DO_MASK) && (iint->flags & IMA_DONE_MASK)) {
279 		if (!IS_I_VERSION(backing_inode) ||
280 		    backing_inode->i_sb->s_dev != iint->real_dev ||
281 		    backing_inode->i_ino != iint->real_ino ||
282 		    !inode_eq_iversion(backing_inode, iint->version)) {
283 			iint->flags &= ~IMA_DONE_MASK;
284 			iint->measured_pcrs = 0;
285 		}
286 	}
287 
288 	/* Determine if already appraised/measured based on bitmask
289 	 * (IMA_MEASURE, IMA_MEASURED, IMA_XXXX_APPRAISE, IMA_XXXX_APPRAISED,
290 	 *  IMA_AUDIT, IMA_AUDITED)
291 	 */
292 	iint->flags |= action;
293 	action &= IMA_DO_MASK;
294 	action &= ~((iint->flags & (IMA_DONE_MASK ^ IMA_MEASURED)) >> 1);
295 
296 	/* If target pcr is already measured, unset IMA_MEASURE action */
297 	if ((action & IMA_MEASURE) && (iint->measured_pcrs & (0x1 << pcr)))
298 		action ^= IMA_MEASURE;
299 
300 	/* HASH sets the digital signature and update flags, nothing else */
301 	if ((action & IMA_HASH) &&
302 	    !(test_bit(IMA_DIGSIG, &iint->atomic_flags))) {
303 		xattr_len = ima_read_xattr(file_dentry(file), &xattr_value);
304 		if ((xattr_value && xattr_len > 2) &&
305 		    (xattr_value->type == EVM_IMA_XATTR_DIGSIG))
306 			set_bit(IMA_DIGSIG, &iint->atomic_flags);
307 		iint->flags |= IMA_HASHED;
308 		action ^= IMA_HASH;
309 		set_bit(IMA_UPDATE_XATTR, &iint->atomic_flags);
310 	}
311 
312 	/* Nothing to do, just return existing appraised status */
313 	if (!action) {
314 		if (must_appraise) {
315 			rc = mmap_violation_check(func, file, &pathbuf,
316 						  &pathname, filename);
317 			if (!rc)
318 				rc = ima_get_cache_status(iint, func);
319 		}
320 		goto out_locked;
321 	}
322 
323 	if ((action & IMA_APPRAISE_SUBMASK) ||
324 	    strcmp(template_desc->name, IMA_TEMPLATE_IMA_NAME) != 0) {
325 		/* read 'security.ima' */
326 		xattr_len = ima_read_xattr(file_dentry(file), &xattr_value);
327 
328 		/*
329 		 * Read the appended modsig if allowed by the policy, and allow
330 		 * an additional measurement list entry, if needed, based on the
331 		 * template format and whether the file was already measured.
332 		 */
333 		if (iint->flags & IMA_MODSIG_ALLOWED) {
334 			rc = ima_read_modsig(func, buf, size, &modsig);
335 
336 			if (!rc && ima_template_has_modsig(template_desc) &&
337 			    iint->flags & IMA_MEASURED)
338 				action |= IMA_MEASURE;
339 		}
340 	}
341 
342 	hash_algo = ima_get_hash_algo(xattr_value, xattr_len);
343 
344 	rc = ima_collect_measurement(iint, file, buf, size, hash_algo, modsig);
345 	if (rc != 0 && rc != -EBADF && rc != -EINVAL)
346 		goto out_locked;
347 
348 	if (!pathbuf)	/* ima_rdwr_violation possibly pre-fetched */
349 		pathname = ima_d_path(&file->f_path, &pathbuf, filename);
350 
351 	if (action & IMA_MEASURE)
352 		ima_store_measurement(iint, file, pathname,
353 				      xattr_value, xattr_len, modsig, pcr,
354 				      template_desc);
355 	if (rc == 0 && (action & IMA_APPRAISE_SUBMASK)) {
356 		rc = ima_check_blacklist(iint, modsig, pcr);
357 		if (rc != -EPERM) {
358 			inode_lock(inode);
359 			rc = ima_appraise_measurement(func, iint, file,
360 						      pathname, xattr_value,
361 						      xattr_len, modsig);
362 			inode_unlock(inode);
363 		}
364 		if (!rc)
365 			rc = mmap_violation_check(func, file, &pathbuf,
366 						  &pathname, filename);
367 	}
368 	if (action & IMA_AUDIT)
369 		ima_audit_measurement(iint, pathname);
370 
371 	if ((file->f_flags & O_DIRECT) && (iint->flags & IMA_PERMIT_DIRECTIO))
372 		rc = 0;
373 out_locked:
374 	if ((mask & MAY_WRITE) && test_bit(IMA_DIGSIG, &iint->atomic_flags) &&
375 	     !(iint->flags & IMA_NEW_FILE))
376 		rc = -EACCES;
377 	mutex_unlock(&iint->mutex);
378 	kfree(xattr_value);
379 	ima_free_modsig(modsig);
380 out:
381 	if (pathbuf)
382 		__putname(pathbuf);
383 	if (must_appraise) {
384 		if (rc && (ima_appraise & IMA_APPRAISE_ENFORCE))
385 			return -EACCES;
386 		if (file->f_mode & FMODE_WRITE)
387 			set_bit(IMA_UPDATE_XATTR, &iint->atomic_flags);
388 	}
389 	return 0;
390 }
391 
392 /**
393  * ima_file_mmap - based on policy, collect/store measurement.
394  * @file: pointer to the file to be measured (May be NULL)
395  * @reqprot: protection requested by the application
396  * @prot: protection that will be applied by the kernel
397  * @flags: operational flags
398  *
399  * Measure files being mmapped executable based on the ima_must_measure()
400  * policy decision.
401  *
402  * On success return 0.  On integrity appraisal error, assuming the file
403  * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
404  */
ima_file_mmap(struct file *file, unsigned long reqprot, unsigned long prot, unsigned long flags)405 int ima_file_mmap(struct file *file, unsigned long reqprot,
406 		  unsigned long prot, unsigned long flags)
407 {
408 	u32 secid;
409 
410 	if (file && (prot & PROT_EXEC)) {
411 		security_task_getsecid(current, &secid);
412 		return process_measurement(file, current_cred(), secid, NULL,
413 					   0, MAY_EXEC, MMAP_CHECK);
414 	}
415 
416 	return 0;
417 }
418 
419 /**
420  * ima_file_mprotect - based on policy, limit mprotect change
421  * @prot: contains the protection that will be applied by the kernel.
422  *
423  * Files can be mmap'ed read/write and later changed to execute to circumvent
424  * IMA's mmap appraisal policy rules.  Due to locking issues (mmap semaphore
425  * would be taken before i_mutex), files can not be measured or appraised at
426  * this point.  Eliminate this integrity gap by denying the mprotect
427  * PROT_EXECUTE change, if an mmap appraise policy rule exists.
428  *
429  * On mprotect change success, return 0.  On failure, return -EACESS.
430  */
ima_file_mprotect(struct vm_area_struct *vma, unsigned long prot)431 int ima_file_mprotect(struct vm_area_struct *vma, unsigned long prot)
432 {
433 	struct ima_template_desc *template;
434 	struct file *file = vma->vm_file;
435 	char filename[NAME_MAX];
436 	char *pathbuf = NULL;
437 	const char *pathname = NULL;
438 	struct inode *inode;
439 	int result = 0;
440 	int action;
441 	u32 secid;
442 	int pcr;
443 
444 	/* Is mprotect making an mmap'ed file executable? */
445 	if (!(ima_policy_flag & IMA_APPRAISE) || !vma->vm_file ||
446 	    !(prot & PROT_EXEC) || (vma->vm_flags & VM_EXEC))
447 		return 0;
448 
449 	security_task_getsecid(current, &secid);
450 	inode = file_inode(vma->vm_file);
451 	action = ima_get_action(inode, current_cred(), secid, MAY_EXEC,
452 				MMAP_CHECK, &pcr, &template, 0);
453 
454 	/* Is the mmap'ed file in policy? */
455 	if (!(action & (IMA_MEASURE | IMA_APPRAISE_SUBMASK)))
456 		return 0;
457 
458 	if (action & IMA_APPRAISE_SUBMASK)
459 		result = -EPERM;
460 
461 	file = vma->vm_file;
462 	pathname = ima_d_path(&file->f_path, &pathbuf, filename);
463 	integrity_audit_msg(AUDIT_INTEGRITY_DATA, inode, pathname,
464 			    "collect_data", "failed-mprotect", result, 0);
465 	if (pathbuf)
466 		__putname(pathbuf);
467 
468 	return result;
469 }
470 
471 /**
472  * ima_bprm_check - based on policy, collect/store measurement.
473  * @bprm: contains the linux_binprm structure
474  *
475  * The OS protects against an executable file, already open for write,
476  * from being executed in deny_write_access() and an executable file,
477  * already open for execute, from being modified in get_write_access().
478  * So we can be certain that what we verify and measure here is actually
479  * what is being executed.
480  *
481  * On success return 0.  On integrity appraisal error, assuming the file
482  * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
483  */
ima_bprm_check(struct linux_binprm *bprm)484 int ima_bprm_check(struct linux_binprm *bprm)
485 {
486 	int ret;
487 	u32 secid;
488 
489 	security_task_getsecid(current, &secid);
490 	ret = process_measurement(bprm->file, current_cred(), secid, NULL, 0,
491 				  MAY_EXEC, BPRM_CHECK);
492 	if (ret)
493 		return ret;
494 
495 	security_cred_getsecid(bprm->cred, &secid);
496 	return process_measurement(bprm->file, bprm->cred, secid, NULL, 0,
497 				   MAY_EXEC, CREDS_CHECK);
498 }
499 
500 /**
501  * ima_path_check - based on policy, collect/store measurement.
502  * @file: pointer to the file to be measured
503  * @mask: contains MAY_READ, MAY_WRITE, MAY_EXEC or MAY_APPEND
504  *
505  * Measure files based on the ima_must_measure() policy decision.
506  *
507  * On success return 0.  On integrity appraisal error, assuming the file
508  * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
509  */
ima_file_check(struct file *file, int mask)510 int ima_file_check(struct file *file, int mask)
511 {
512 	u32 secid;
513 
514 	security_task_getsecid(current, &secid);
515 	return process_measurement(file, current_cred(), secid, NULL, 0,
516 				   mask & (MAY_READ | MAY_WRITE | MAY_EXEC |
517 					   MAY_APPEND), FILE_CHECK);
518 }
519 EXPORT_SYMBOL_GPL(ima_file_check);
520 
521 /**
522  * ima_file_hash - return the stored measurement if a file has been hashed and
523  * is in the iint cache.
524  * @file: pointer to the file
525  * @buf: buffer in which to store the hash
526  * @buf_size: length of the buffer
527  *
528  * On success, return the hash algorithm (as defined in the enum hash_algo).
529  * If buf is not NULL, this function also outputs the hash into buf.
530  * If the hash is larger than buf_size, then only buf_size bytes will be copied.
531  * It generally just makes sense to pass a buffer capable of holding the largest
532  * possible hash: IMA_MAX_DIGEST_SIZE.
533  * The file hash returned is based on the entire file, including the appended
534  * signature.
535  *
536  * If IMA is disabled or if no measurement is available, return -EOPNOTSUPP.
537  * If the parameters are incorrect, return -EINVAL.
538  */
ima_file_hash(struct file *file, char *buf, size_t buf_size)539 int ima_file_hash(struct file *file, char *buf, size_t buf_size)
540 {
541 	struct inode *inode;
542 	struct integrity_iint_cache *iint;
543 	int hash_algo;
544 
545 	if (!file)
546 		return -EINVAL;
547 
548 	if (!ima_policy_flag)
549 		return -EOPNOTSUPP;
550 
551 	inode = file_inode(file);
552 	iint = integrity_iint_find(inode);
553 	if (!iint)
554 		return -EOPNOTSUPP;
555 
556 	mutex_lock(&iint->mutex);
557 
558 	/*
559 	 * ima_file_hash can be called when ima_collect_measurement has still
560 	 * not been called, we might not always have a hash.
561 	 */
562 	if (!iint->ima_hash) {
563 		mutex_unlock(&iint->mutex);
564 		return -EOPNOTSUPP;
565 	}
566 
567 	if (buf) {
568 		size_t copied_size;
569 
570 		copied_size = min_t(size_t, iint->ima_hash->length, buf_size);
571 		memcpy(buf, iint->ima_hash->digest, copied_size);
572 	}
573 	hash_algo = iint->ima_hash->algo;
574 	mutex_unlock(&iint->mutex);
575 
576 	return hash_algo;
577 }
578 EXPORT_SYMBOL_GPL(ima_file_hash);
579 
580 /**
581  * ima_post_create_tmpfile - mark newly created tmpfile as new
582  * @file : newly created tmpfile
583  *
584  * No measuring, appraising or auditing of newly created tmpfiles is needed.
585  * Skip calling process_measurement(), but indicate which newly, created
586  * tmpfiles are in policy.
587  */
ima_post_create_tmpfile(struct inode *inode)588 void ima_post_create_tmpfile(struct inode *inode)
589 {
590 	struct integrity_iint_cache *iint;
591 	int must_appraise;
592 
593 	must_appraise = ima_must_appraise(inode, MAY_ACCESS, FILE_CHECK);
594 	if (!must_appraise)
595 		return;
596 
597 	/* Nothing to do if we can't allocate memory */
598 	iint = integrity_inode_get(inode);
599 	if (!iint)
600 		return;
601 
602 	/* needed for writing the security xattrs */
603 	set_bit(IMA_UPDATE_XATTR, &iint->atomic_flags);
604 	iint->ima_file_status = INTEGRITY_PASS;
605 }
606 
607 /**
608  * ima_post_path_mknod - mark as a new inode
609  * @dentry: newly created dentry
610  *
611  * Mark files created via the mknodat syscall as new, so that the
612  * file data can be written later.
613  */
ima_post_path_mknod(struct dentry *dentry)614 void ima_post_path_mknod(struct dentry *dentry)
615 {
616 	struct integrity_iint_cache *iint;
617 	struct inode *inode = dentry->d_inode;
618 	int must_appraise;
619 
620 	must_appraise = ima_must_appraise(inode, MAY_ACCESS, FILE_CHECK);
621 	if (!must_appraise)
622 		return;
623 
624 	/* Nothing to do if we can't allocate memory */
625 	iint = integrity_inode_get(inode);
626 	if (!iint)
627 		return;
628 
629 	/* needed for re-opening empty files */
630 	iint->flags |= IMA_NEW_FILE;
631 }
632 
633 /**
634  * ima_read_file - pre-measure/appraise hook decision based on policy
635  * @file: pointer to the file to be measured/appraised/audit
636  * @read_id: caller identifier
637  * @contents: whether a subsequent call will be made to ima_post_read_file()
638  *
639  * Permit reading a file based on policy. The policy rules are written
640  * in terms of the policy identifier.  Appraising the integrity of
641  * a file requires a file descriptor.
642  *
643  * For permission return 0, otherwise return -EACCES.
644  */
ima_read_file(struct file *file, enum kernel_read_file_id read_id, bool contents)645 int ima_read_file(struct file *file, enum kernel_read_file_id read_id,
646 		  bool contents)
647 {
648 	enum ima_hooks func;
649 	u32 secid;
650 
651 	/*
652 	 * Do devices using pre-allocated memory run the risk of the
653 	 * firmware being accessible to the device prior to the completion
654 	 * of IMA's signature verification any more than when using two
655 	 * buffers? It may be desirable to include the buffer address
656 	 * in this API and walk all the dma_map_single() mappings to check.
657 	 */
658 
659 	/*
660 	 * There will be a call made to ima_post_read_file() with
661 	 * a filled buffer, so we don't need to perform an extra
662 	 * read early here.
663 	 */
664 	if (contents)
665 		return 0;
666 
667 	/* Read entire file for all partial reads. */
668 	func = read_idmap[read_id] ?: FILE_CHECK;
669 	security_task_getsecid(current, &secid);
670 	return process_measurement(file, current_cred(), secid, NULL,
671 				   0, MAY_READ, func);
672 }
673 
674 const int read_idmap[READING_MAX_ID] = {
675 	[READING_FIRMWARE] = FIRMWARE_CHECK,
676 	[READING_MODULE] = MODULE_CHECK,
677 	[READING_KEXEC_IMAGE] = KEXEC_KERNEL_CHECK,
678 	[READING_KEXEC_INITRAMFS] = KEXEC_INITRAMFS_CHECK,
679 	[READING_POLICY] = POLICY_CHECK
680 };
681 
682 /**
683  * ima_post_read_file - in memory collect/appraise/audit measurement
684  * @file: pointer to the file to be measured/appraised/audit
685  * @buf: pointer to in memory file contents
686  * @size: size of in memory file contents
687  * @read_id: caller identifier
688  *
689  * Measure/appraise/audit in memory file based on policy.  Policy rules
690  * are written in terms of a policy identifier.
691  *
692  * On success return 0.  On integrity appraisal error, assuming the file
693  * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
694  */
ima_post_read_file(struct file *file, void *buf, loff_t size, enum kernel_read_file_id read_id)695 int ima_post_read_file(struct file *file, void *buf, loff_t size,
696 		       enum kernel_read_file_id read_id)
697 {
698 	enum ima_hooks func;
699 	u32 secid;
700 
701 	/* permit signed certs */
702 	if (!file && read_id == READING_X509_CERTIFICATE)
703 		return 0;
704 
705 	if (!file || !buf || size == 0) { /* should never happen */
706 		if (ima_appraise & IMA_APPRAISE_ENFORCE)
707 			return -EACCES;
708 		return 0;
709 	}
710 
711 	func = read_idmap[read_id] ?: FILE_CHECK;
712 	security_task_getsecid(current, &secid);
713 	return process_measurement(file, current_cred(), secid, buf, size,
714 				   MAY_READ, func);
715 }
716 
717 /**
718  * ima_load_data - appraise decision based on policy
719  * @id: kernel load data caller identifier
720  * @contents: whether the full contents will be available in a later
721  *	      call to ima_post_load_data().
722  *
723  * Callers of this LSM hook can not measure, appraise, or audit the
724  * data provided by userspace.  Enforce policy rules requring a file
725  * signature (eg. kexec'ed kernel image).
726  *
727  * For permission return 0, otherwise return -EACCES.
728  */
ima_load_data(enum kernel_load_data_id id, bool contents)729 int ima_load_data(enum kernel_load_data_id id, bool contents)
730 {
731 	bool ima_enforce, sig_enforce;
732 
733 	ima_enforce =
734 		(ima_appraise & IMA_APPRAISE_ENFORCE) == IMA_APPRAISE_ENFORCE;
735 
736 	switch (id) {
737 	case LOADING_KEXEC_IMAGE:
738 		if (IS_ENABLED(CONFIG_KEXEC_SIG)
739 		    && arch_ima_get_secureboot()) {
740 			pr_err("impossible to appraise a kernel image without a file descriptor; try using kexec_file_load syscall.\n");
741 			return -EACCES;
742 		}
743 
744 		if (ima_enforce && (ima_appraise & IMA_APPRAISE_KEXEC)) {
745 			pr_err("impossible to appraise a kernel image without a file descriptor; try using kexec_file_load syscall.\n");
746 			return -EACCES;	/* INTEGRITY_UNKNOWN */
747 		}
748 		break;
749 	case LOADING_FIRMWARE:
750 		if (ima_enforce && (ima_appraise & IMA_APPRAISE_FIRMWARE) && !contents) {
751 			pr_err("Prevent firmware sysfs fallback loading.\n");
752 			return -EACCES;	/* INTEGRITY_UNKNOWN */
753 		}
754 		break;
755 	case LOADING_MODULE:
756 		sig_enforce = is_module_sig_enforced();
757 
758 		if (ima_enforce && (!sig_enforce
759 				    && (ima_appraise & IMA_APPRAISE_MODULES))) {
760 			pr_err("impossible to appraise a module without a file descriptor. sig_enforce kernel parameter might help\n");
761 			return -EACCES;	/* INTEGRITY_UNKNOWN */
762 		}
763 		break;
764 	default:
765 		break;
766 	}
767 	return 0;
768 }
769 
770 /**
771  * ima_post_load_data - appraise decision based on policy
772  * @buf: pointer to in memory file contents
773  * @size: size of in memory file contents
774  * @id: kernel load data caller identifier
775  * @description: @id-specific description of contents
776  *
777  * Measure/appraise/audit in memory buffer based on policy.  Policy rules
778  * are written in terms of a policy identifier.
779  *
780  * On success return 0.  On integrity appraisal error, assuming the file
781  * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
782  */
ima_post_load_data(char *buf, loff_t size, enum kernel_load_data_id load_id, char *description)783 int ima_post_load_data(char *buf, loff_t size,
784 		       enum kernel_load_data_id load_id,
785 		       char *description)
786 {
787 	if (load_id == LOADING_FIRMWARE) {
788 		if ((ima_appraise & IMA_APPRAISE_FIRMWARE) &&
789 		    (ima_appraise & IMA_APPRAISE_ENFORCE)) {
790 			pr_err("Prevent firmware loading_store.\n");
791 			return -EACCES; /* INTEGRITY_UNKNOWN */
792 		}
793 		return 0;
794 	}
795 
796 	return 0;
797 }
798 
799 /*
800  * process_buffer_measurement - Measure the buffer to ima log.
801  * @inode: inode associated with the object being measured (NULL for KEY_CHECK)
802  * @buf: pointer to the buffer that needs to be added to the log.
803  * @size: size of buffer(in bytes).
804  * @eventname: event name to be used for the buffer entry.
805  * @func: IMA hook
806  * @pcr: pcr to extend the measurement
807  * @keyring: keyring name to determine the action to be performed
808  *
809  * Based on policy, the buffer is measured into the ima log.
810  */
process_buffer_measurement(struct inode *inode, const void *buf, int size, const char *eventname, enum ima_hooks func, int pcr, const char *keyring)811 void process_buffer_measurement(struct inode *inode, const void *buf, int size,
812 				const char *eventname, enum ima_hooks func,
813 				int pcr, const char *keyring)
814 {
815 	int ret = 0;
816 	const char *audit_cause = "ENOMEM";
817 	struct ima_template_entry *entry = NULL;
818 	struct integrity_iint_cache iint = {};
819 	struct ima_event_data event_data = {.iint = &iint,
820 					    .filename = eventname,
821 					    .buf = buf,
822 					    .buf_len = size};
823 	struct ima_template_desc *template = NULL;
824 	struct {
825 		struct ima_digest_data hdr;
826 		char digest[IMA_MAX_DIGEST_SIZE];
827 	} hash = {};
828 	int violation = 0;
829 	int action = 0;
830 	u32 secid;
831 
832 	if (!ima_policy_flag)
833 		return;
834 
835 	/*
836 	 * Both LSM hooks and auxilary based buffer measurements are
837 	 * based on policy.  To avoid code duplication, differentiate
838 	 * between the LSM hooks and auxilary buffer measurements,
839 	 * retrieving the policy rule information only for the LSM hook
840 	 * buffer measurements.
841 	 */
842 	if (func) {
843 		security_task_getsecid(current, &secid);
844 		action = ima_get_action(inode, current_cred(), secid, 0, func,
845 					&pcr, &template, keyring);
846 		if (!(action & IMA_MEASURE))
847 			return;
848 	}
849 
850 	if (!pcr)
851 		pcr = CONFIG_IMA_MEASURE_PCR_IDX;
852 
853 	if (!template) {
854 		template = lookup_template_desc("ima-buf");
855 		ret = template_desc_init_fields(template->fmt,
856 						&(template->fields),
857 						&(template->num_fields));
858 		if (ret < 0) {
859 			pr_err("template %s init failed, result: %d\n",
860 			       (strlen(template->name) ?
861 				template->name : template->fmt), ret);
862 			return;
863 		}
864 	}
865 
866 	iint.ima_hash = &hash.hdr;
867 	iint.ima_hash->algo = ima_hash_algo;
868 	iint.ima_hash->length = hash_digest_size[ima_hash_algo];
869 
870 	ret = ima_calc_buffer_hash(buf, size, iint.ima_hash);
871 	if (ret < 0) {
872 		audit_cause = "hashing_error";
873 		goto out;
874 	}
875 
876 	ret = ima_alloc_init_template(&event_data, &entry, template);
877 	if (ret < 0) {
878 		audit_cause = "alloc_entry";
879 		goto out;
880 	}
881 
882 	ret = ima_store_template(entry, violation, NULL, buf, pcr);
883 	if (ret < 0) {
884 		audit_cause = "store_entry";
885 		ima_free_template_entry(entry);
886 	}
887 
888 out:
889 	if (ret < 0)
890 		integrity_audit_message(AUDIT_INTEGRITY_PCR, NULL, eventname,
891 					func_measure_str(func),
892 					audit_cause, ret, 0, ret);
893 
894 	return;
895 }
896 
897 /**
898  * ima_kexec_cmdline - measure kexec cmdline boot args
899  * @kernel_fd: file descriptor of the kexec kernel being loaded
900  * @buf: pointer to buffer
901  * @size: size of buffer
902  *
903  * Buffers can only be measured, not appraised.
904  */
ima_kexec_cmdline(int kernel_fd, const void *buf, int size)905 void ima_kexec_cmdline(int kernel_fd, const void *buf, int size)
906 {
907 	struct fd f;
908 
909 	if (!buf || !size)
910 		return;
911 
912 	f = fdget(kernel_fd);
913 	if (!f.file)
914 		return;
915 
916 	process_buffer_measurement(file_inode(f.file), buf, size,
917 				   "kexec-cmdline", KEXEC_CMDLINE, 0, NULL);
918 	fdput(f);
919 }
920 
init_ima(void)921 static int __init init_ima(void)
922 {
923 	int error;
924 
925 	ima_init_template_list();
926 	hash_setup(CONFIG_IMA_DEFAULT_HASH);
927 	error = ima_init();
928 
929 	if (error && strcmp(hash_algo_name[ima_hash_algo],
930 			    CONFIG_IMA_DEFAULT_HASH) != 0) {
931 		pr_info("Allocating %s failed, going to use default hash algorithm %s\n",
932 			hash_algo_name[ima_hash_algo], CONFIG_IMA_DEFAULT_HASH);
933 		hash_setup_done = 0;
934 		hash_setup(CONFIG_IMA_DEFAULT_HASH);
935 		error = ima_init();
936 	}
937 
938 	if (error)
939 		return error;
940 
941 	error = register_blocking_lsm_notifier(&ima_lsm_policy_notifier);
942 	if (error)
943 		pr_warn("Couldn't register LSM notifier, error %d\n", error);
944 
945 	if (!error)
946 		ima_update_policy_flag();
947 
948 	return error;
949 }
950 
951 late_initcall(init_ima);	/* Start IMA after the TPM is available */
952