xref: /linux/security/integrity/ima/ima_crypto.c (revision 69050f8d6d075dc01af7a5f2f550a8067510366f)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2005,2006,2007,2008 IBM Corporation
4  *
5  * Authors:
6  * Mimi Zohar <zohar@us.ibm.com>
7  * Kylene Hall <kjhall@us.ibm.com>
8  *
9  * File: ima_crypto.c
10  *	Calculates md5/sha1 file hash, template hash, boot-aggreate hash
11  */
12 
13 #include <linux/kernel.h>
14 #include <linux/moduleparam.h>
15 #include <linux/ratelimit.h>
16 #include <linux/file.h>
17 #include <linux/crypto.h>
18 #include <linux/scatterlist.h>
19 #include <linux/err.h>
20 #include <linux/slab.h>
21 #include <crypto/hash.h>
22 
23 #include "ima.h"
24 
25 /* minimum file size for ahash use */
26 static unsigned long ima_ahash_minsize;
27 module_param_named(ahash_minsize, ima_ahash_minsize, ulong, 0644);
28 MODULE_PARM_DESC(ahash_minsize, "Minimum file size for ahash use");
29 
30 /* default is 0 - 1 page. */
31 static int ima_maxorder;
32 static unsigned int ima_bufsize = PAGE_SIZE;
33 
34 static int param_set_bufsize(const char *val, const struct kernel_param *kp)
35 {
36 	unsigned long long size;
37 	int order;
38 
39 	size = memparse(val, NULL);
40 	order = get_order(size);
41 	if (order > MAX_PAGE_ORDER)
42 		return -EINVAL;
43 	ima_maxorder = order;
44 	ima_bufsize = PAGE_SIZE << order;
45 	return 0;
46 }
47 
48 static const struct kernel_param_ops param_ops_bufsize = {
49 	.set = param_set_bufsize,
50 	.get = param_get_uint,
51 };
52 #define param_check_bufsize(name, p) __param_check(name, p, unsigned int)
53 
54 module_param_named(ahash_bufsize, ima_bufsize, bufsize, 0644);
55 MODULE_PARM_DESC(ahash_bufsize, "Maximum ahash buffer size");
56 
57 static struct crypto_shash *ima_shash_tfm;
58 static struct crypto_ahash *ima_ahash_tfm;
59 
60 int ima_sha1_idx __ro_after_init;
61 int ima_hash_algo_idx __ro_after_init;
62 /*
63  * Additional number of slots reserved, as needed, for SHA1
64  * and IMA default algo.
65  */
66 int ima_extra_slots __ro_after_init;
67 
68 struct ima_algo_desc *ima_algo_array __ro_after_init;
69 
70 static int __init ima_init_ima_crypto(void)
71 {
72 	long rc;
73 
74 	ima_shash_tfm = crypto_alloc_shash(hash_algo_name[ima_hash_algo], 0, 0);
75 	if (IS_ERR(ima_shash_tfm)) {
76 		rc = PTR_ERR(ima_shash_tfm);
77 		pr_err("Can not allocate %s (reason: %ld)\n",
78 		       hash_algo_name[ima_hash_algo], rc);
79 		return rc;
80 	}
81 	pr_info("Allocated hash algorithm: %s\n",
82 		hash_algo_name[ima_hash_algo]);
83 	return 0;
84 }
85 
86 static struct crypto_shash *ima_alloc_tfm(enum hash_algo algo)
87 {
88 	struct crypto_shash *tfm = ima_shash_tfm;
89 	int rc, i;
90 
91 	if (algo < 0 || algo >= HASH_ALGO__LAST)
92 		algo = ima_hash_algo;
93 
94 	if (algo == ima_hash_algo)
95 		return tfm;
96 
97 	for (i = 0; i < NR_BANKS(ima_tpm_chip) + ima_extra_slots; i++)
98 		if (ima_algo_array[i].tfm && ima_algo_array[i].algo == algo)
99 			return ima_algo_array[i].tfm;
100 
101 	tfm = crypto_alloc_shash(hash_algo_name[algo], 0, 0);
102 	if (IS_ERR(tfm)) {
103 		rc = PTR_ERR(tfm);
104 		pr_err("Can not allocate %s (reason: %d)\n",
105 		       hash_algo_name[algo], rc);
106 	}
107 	return tfm;
108 }
109 
110 int __init ima_init_crypto(void)
111 {
112 	enum hash_algo algo;
113 	long rc;
114 	int i;
115 
116 	rc = ima_init_ima_crypto();
117 	if (rc)
118 		return rc;
119 
120 	ima_sha1_idx = -1;
121 	ima_hash_algo_idx = -1;
122 
123 	for (i = 0; i < NR_BANKS(ima_tpm_chip); i++) {
124 		algo = ima_tpm_chip->allocated_banks[i].crypto_id;
125 		if (algo == HASH_ALGO_SHA1)
126 			ima_sha1_idx = i;
127 
128 		if (algo == ima_hash_algo)
129 			ima_hash_algo_idx = i;
130 	}
131 
132 	if (ima_sha1_idx < 0) {
133 		ima_sha1_idx = NR_BANKS(ima_tpm_chip) + ima_extra_slots++;
134 		if (ima_hash_algo == HASH_ALGO_SHA1)
135 			ima_hash_algo_idx = ima_sha1_idx;
136 	}
137 
138 	if (ima_hash_algo_idx < 0)
139 		ima_hash_algo_idx = NR_BANKS(ima_tpm_chip) + ima_extra_slots++;
140 
141 	ima_algo_array = kzalloc_objs(*ima_algo_array,
142 				      NR_BANKS(ima_tpm_chip) + ima_extra_slots,
143 				      GFP_KERNEL);
144 	if (!ima_algo_array) {
145 		rc = -ENOMEM;
146 		goto out;
147 	}
148 
149 	for (i = 0; i < NR_BANKS(ima_tpm_chip); i++) {
150 		algo = ima_tpm_chip->allocated_banks[i].crypto_id;
151 		ima_algo_array[i].algo = algo;
152 
153 		/* unknown TPM algorithm */
154 		if (algo == HASH_ALGO__LAST)
155 			continue;
156 
157 		if (algo == ima_hash_algo) {
158 			ima_algo_array[i].tfm = ima_shash_tfm;
159 			continue;
160 		}
161 
162 		ima_algo_array[i].tfm = ima_alloc_tfm(algo);
163 		if (IS_ERR(ima_algo_array[i].tfm)) {
164 			if (algo == HASH_ALGO_SHA1) {
165 				rc = PTR_ERR(ima_algo_array[i].tfm);
166 				ima_algo_array[i].tfm = NULL;
167 				goto out_array;
168 			}
169 
170 			ima_algo_array[i].tfm = NULL;
171 		}
172 	}
173 
174 	if (ima_sha1_idx >= NR_BANKS(ima_tpm_chip)) {
175 		if (ima_hash_algo == HASH_ALGO_SHA1) {
176 			ima_algo_array[ima_sha1_idx].tfm = ima_shash_tfm;
177 		} else {
178 			ima_algo_array[ima_sha1_idx].tfm =
179 						ima_alloc_tfm(HASH_ALGO_SHA1);
180 			if (IS_ERR(ima_algo_array[ima_sha1_idx].tfm)) {
181 				rc = PTR_ERR(ima_algo_array[ima_sha1_idx].tfm);
182 				goto out_array;
183 			}
184 		}
185 
186 		ima_algo_array[ima_sha1_idx].algo = HASH_ALGO_SHA1;
187 	}
188 
189 	if (ima_hash_algo_idx >= NR_BANKS(ima_tpm_chip) &&
190 	    ima_hash_algo_idx != ima_sha1_idx) {
191 		ima_algo_array[ima_hash_algo_idx].tfm = ima_shash_tfm;
192 		ima_algo_array[ima_hash_algo_idx].algo = ima_hash_algo;
193 	}
194 
195 	return 0;
196 out_array:
197 	for (i = 0; i < NR_BANKS(ima_tpm_chip) + ima_extra_slots; i++) {
198 		if (!ima_algo_array[i].tfm ||
199 		    ima_algo_array[i].tfm == ima_shash_tfm)
200 			continue;
201 
202 		crypto_free_shash(ima_algo_array[i].tfm);
203 	}
204 	kfree(ima_algo_array);
205 out:
206 	crypto_free_shash(ima_shash_tfm);
207 	return rc;
208 }
209 
210 static void ima_free_tfm(struct crypto_shash *tfm)
211 {
212 	int i;
213 
214 	if (tfm == ima_shash_tfm)
215 		return;
216 
217 	for (i = 0; i < NR_BANKS(ima_tpm_chip) + ima_extra_slots; i++)
218 		if (ima_algo_array[i].tfm == tfm)
219 			return;
220 
221 	crypto_free_shash(tfm);
222 }
223 
224 /**
225  * ima_alloc_pages() - Allocate contiguous pages.
226  * @max_size:       Maximum amount of memory to allocate.
227  * @allocated_size: Returned size of actual allocation.
228  * @last_warn:      Should the min_size allocation warn or not.
229  *
230  * Tries to do opportunistic allocation for memory first trying to allocate
231  * max_size amount of memory and then splitting that until zero order is
232  * reached. Allocation is tried without generating allocation warnings unless
233  * last_warn is set. Last_warn set affects only last allocation of zero order.
234  *
235  * By default, ima_maxorder is 0 and it is equivalent to kmalloc(GFP_KERNEL)
236  *
237  * Return pointer to allocated memory, or NULL on failure.
238  */
239 static void *ima_alloc_pages(loff_t max_size, size_t *allocated_size,
240 			     int last_warn)
241 {
242 	void *ptr;
243 	int order = ima_maxorder;
244 	gfp_t gfp_mask = __GFP_RECLAIM | __GFP_NOWARN | __GFP_NORETRY;
245 
246 	if (order)
247 		order = min(get_order(max_size), order);
248 
249 	for (; order; order--) {
250 		ptr = (void *)__get_free_pages(gfp_mask, order);
251 		if (ptr) {
252 			*allocated_size = PAGE_SIZE << order;
253 			return ptr;
254 		}
255 	}
256 
257 	/* order is zero - one page */
258 
259 	gfp_mask = GFP_KERNEL;
260 
261 	if (!last_warn)
262 		gfp_mask |= __GFP_NOWARN;
263 
264 	ptr = (void *)__get_free_pages(gfp_mask, 0);
265 	if (ptr) {
266 		*allocated_size = PAGE_SIZE;
267 		return ptr;
268 	}
269 
270 	*allocated_size = 0;
271 	return NULL;
272 }
273 
274 /**
275  * ima_free_pages() - Free pages allocated by ima_alloc_pages().
276  * @ptr:  Pointer to allocated pages.
277  * @size: Size of allocated buffer.
278  */
279 static void ima_free_pages(void *ptr, size_t size)
280 {
281 	if (!ptr)
282 		return;
283 	free_pages((unsigned long)ptr, get_order(size));
284 }
285 
286 static struct crypto_ahash *ima_alloc_atfm(enum hash_algo algo)
287 {
288 	struct crypto_ahash *tfm = ima_ahash_tfm;
289 	int rc;
290 
291 	if (algo < 0 || algo >= HASH_ALGO__LAST)
292 		algo = ima_hash_algo;
293 
294 	if (algo != ima_hash_algo || !tfm) {
295 		tfm = crypto_alloc_ahash(hash_algo_name[algo], 0, 0);
296 		if (!IS_ERR(tfm)) {
297 			if (algo == ima_hash_algo)
298 				ima_ahash_tfm = tfm;
299 		} else {
300 			rc = PTR_ERR(tfm);
301 			pr_err("Can not allocate %s (reason: %d)\n",
302 			       hash_algo_name[algo], rc);
303 		}
304 	}
305 	return tfm;
306 }
307 
308 static void ima_free_atfm(struct crypto_ahash *tfm)
309 {
310 	if (tfm != ima_ahash_tfm)
311 		crypto_free_ahash(tfm);
312 }
313 
314 static inline int ahash_wait(int err, struct crypto_wait *wait)
315 {
316 
317 	err = crypto_wait_req(err, wait);
318 
319 	if (err)
320 		pr_crit_ratelimited("ahash calculation failed: err: %d\n", err);
321 
322 	return err;
323 }
324 
325 static int ima_calc_file_hash_atfm(struct file *file,
326 				   struct ima_digest_data *hash,
327 				   struct crypto_ahash *tfm)
328 {
329 	loff_t i_size, offset;
330 	char *rbuf[2] = { NULL, };
331 	int rc, rbuf_len, active = 0, ahash_rc = 0;
332 	struct ahash_request *req;
333 	struct scatterlist sg[1];
334 	struct crypto_wait wait;
335 	size_t rbuf_size[2];
336 
337 	hash->length = crypto_ahash_digestsize(tfm);
338 
339 	req = ahash_request_alloc(tfm, GFP_KERNEL);
340 	if (!req)
341 		return -ENOMEM;
342 
343 	crypto_init_wait(&wait);
344 	ahash_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG |
345 				   CRYPTO_TFM_REQ_MAY_SLEEP,
346 				   crypto_req_done, &wait);
347 
348 	rc = ahash_wait(crypto_ahash_init(req), &wait);
349 	if (rc)
350 		goto out1;
351 
352 	i_size = i_size_read(file_inode(file));
353 
354 	if (i_size == 0)
355 		goto out2;
356 
357 	/*
358 	 * Try to allocate maximum size of memory.
359 	 * Fail if even a single page cannot be allocated.
360 	 */
361 	rbuf[0] = ima_alloc_pages(i_size, &rbuf_size[0], 1);
362 	if (!rbuf[0]) {
363 		rc = -ENOMEM;
364 		goto out1;
365 	}
366 
367 	/* Only allocate one buffer if that is enough. */
368 	if (i_size > rbuf_size[0]) {
369 		/*
370 		 * Try to allocate secondary buffer. If that fails fallback to
371 		 * using single buffering. Use previous memory allocation size
372 		 * as baseline for possible allocation size.
373 		 */
374 		rbuf[1] = ima_alloc_pages(i_size - rbuf_size[0],
375 					  &rbuf_size[1], 0);
376 	}
377 
378 	for (offset = 0; offset < i_size; offset += rbuf_len) {
379 		if (!rbuf[1] && offset) {
380 			/* Not using two buffers, and it is not the first
381 			 * read/request, wait for the completion of the
382 			 * previous ahash_update() request.
383 			 */
384 			rc = ahash_wait(ahash_rc, &wait);
385 			if (rc)
386 				goto out3;
387 		}
388 		/* read buffer */
389 		rbuf_len = min_t(loff_t, i_size - offset, rbuf_size[active]);
390 		rc = integrity_kernel_read(file, offset, rbuf[active],
391 					   rbuf_len);
392 		if (rc != rbuf_len) {
393 			if (rc >= 0)
394 				rc = -EINVAL;
395 			/*
396 			 * Forward current rc, do not overwrite with return value
397 			 * from ahash_wait()
398 			 */
399 			ahash_wait(ahash_rc, &wait);
400 			goto out3;
401 		}
402 
403 		if (rbuf[1] && offset) {
404 			/* Using two buffers, and it is not the first
405 			 * read/request, wait for the completion of the
406 			 * previous ahash_update() request.
407 			 */
408 			rc = ahash_wait(ahash_rc, &wait);
409 			if (rc)
410 				goto out3;
411 		}
412 
413 		sg_init_one(&sg[0], rbuf[active], rbuf_len);
414 		ahash_request_set_crypt(req, sg, NULL, rbuf_len);
415 
416 		ahash_rc = crypto_ahash_update(req);
417 
418 		if (rbuf[1])
419 			active = !active; /* swap buffers, if we use two */
420 	}
421 	/* wait for the last update request to complete */
422 	rc = ahash_wait(ahash_rc, &wait);
423 out3:
424 	ima_free_pages(rbuf[0], rbuf_size[0]);
425 	ima_free_pages(rbuf[1], rbuf_size[1]);
426 out2:
427 	if (!rc) {
428 		ahash_request_set_crypt(req, NULL, hash->digest, 0);
429 		rc = ahash_wait(crypto_ahash_final(req), &wait);
430 	}
431 out1:
432 	ahash_request_free(req);
433 	return rc;
434 }
435 
436 static int ima_calc_file_ahash(struct file *file, struct ima_digest_data *hash)
437 {
438 	struct crypto_ahash *tfm;
439 	int rc;
440 
441 	tfm = ima_alloc_atfm(hash->algo);
442 	if (IS_ERR(tfm))
443 		return PTR_ERR(tfm);
444 
445 	rc = ima_calc_file_hash_atfm(file, hash, tfm);
446 
447 	ima_free_atfm(tfm);
448 
449 	return rc;
450 }
451 
452 static int ima_calc_file_hash_tfm(struct file *file,
453 				  struct ima_digest_data *hash,
454 				  struct crypto_shash *tfm)
455 {
456 	loff_t i_size, offset = 0;
457 	char *rbuf;
458 	int rc;
459 	SHASH_DESC_ON_STACK(shash, tfm);
460 
461 	shash->tfm = tfm;
462 
463 	hash->length = crypto_shash_digestsize(tfm);
464 
465 	rc = crypto_shash_init(shash);
466 	if (rc != 0)
467 		return rc;
468 
469 	i_size = i_size_read(file_inode(file));
470 
471 	if (i_size == 0)
472 		goto out;
473 
474 	rbuf = kzalloc(PAGE_SIZE, GFP_KERNEL);
475 	if (!rbuf)
476 		return -ENOMEM;
477 
478 	while (offset < i_size) {
479 		int rbuf_len;
480 
481 		rbuf_len = integrity_kernel_read(file, offset, rbuf, PAGE_SIZE);
482 		if (rbuf_len < 0) {
483 			rc = rbuf_len;
484 			break;
485 		}
486 		if (rbuf_len == 0) {	/* unexpected EOF */
487 			rc = -EINVAL;
488 			break;
489 		}
490 		offset += rbuf_len;
491 
492 		rc = crypto_shash_update(shash, rbuf, rbuf_len);
493 		if (rc)
494 			break;
495 	}
496 	kfree(rbuf);
497 out:
498 	if (!rc)
499 		rc = crypto_shash_final(shash, hash->digest);
500 	return rc;
501 }
502 
503 static int ima_calc_file_shash(struct file *file, struct ima_digest_data *hash)
504 {
505 	struct crypto_shash *tfm;
506 	int rc;
507 
508 	tfm = ima_alloc_tfm(hash->algo);
509 	if (IS_ERR(tfm))
510 		return PTR_ERR(tfm);
511 
512 	rc = ima_calc_file_hash_tfm(file, hash, tfm);
513 
514 	ima_free_tfm(tfm);
515 
516 	return rc;
517 }
518 
519 /*
520  * ima_calc_file_hash - calculate file hash
521  *
522  * Asynchronous hash (ahash) allows using HW acceleration for calculating
523  * a hash. ahash performance varies for different data sizes on different
524  * crypto accelerators. shash performance might be better for smaller files.
525  * The 'ima.ahash_minsize' module parameter allows specifying the best
526  * minimum file size for using ahash on the system.
527  *
528  * If the ima.ahash_minsize parameter is not specified, this function uses
529  * shash for the hash calculation.  If ahash fails, it falls back to using
530  * shash.
531  */
532 int ima_calc_file_hash(struct file *file, struct ima_digest_data *hash)
533 {
534 	loff_t i_size;
535 	int rc;
536 	struct file *f = file;
537 	bool new_file_instance = false;
538 
539 	/*
540 	 * For consistency, fail file's opened with the O_DIRECT flag on
541 	 * filesystems mounted with/without DAX option.
542 	 */
543 	if (file->f_flags & O_DIRECT) {
544 		hash->length = hash_digest_size[ima_hash_algo];
545 		hash->algo = ima_hash_algo;
546 		return -EINVAL;
547 	}
548 
549 	/* Open a new file instance in O_RDONLY if we cannot read */
550 	if (!(file->f_mode & FMODE_READ)) {
551 		int flags = file->f_flags & ~(O_WRONLY | O_APPEND |
552 				O_TRUNC | O_CREAT | O_NOCTTY | O_EXCL);
553 		flags |= O_RDONLY;
554 		f = dentry_open(&file->f_path, flags, file->f_cred);
555 		if (IS_ERR(f))
556 			return PTR_ERR(f);
557 
558 		new_file_instance = true;
559 	}
560 
561 	i_size = i_size_read(file_inode(f));
562 
563 	if (ima_ahash_minsize && i_size >= ima_ahash_minsize) {
564 		rc = ima_calc_file_ahash(f, hash);
565 		if (!rc)
566 			goto out;
567 	}
568 
569 	rc = ima_calc_file_shash(f, hash);
570 out:
571 	if (new_file_instance)
572 		fput(f);
573 	return rc;
574 }
575 
576 /*
577  * Calculate the hash of template data
578  */
579 static int ima_calc_field_array_hash_tfm(struct ima_field_data *field_data,
580 					 struct ima_template_entry *entry,
581 					 int tfm_idx)
582 {
583 	SHASH_DESC_ON_STACK(shash, ima_algo_array[tfm_idx].tfm);
584 	struct ima_template_desc *td = entry->template_desc;
585 	int num_fields = entry->template_desc->num_fields;
586 	int rc, i;
587 
588 	shash->tfm = ima_algo_array[tfm_idx].tfm;
589 
590 	rc = crypto_shash_init(shash);
591 	if (rc != 0)
592 		return rc;
593 
594 	for (i = 0; i < num_fields; i++) {
595 		u8 buffer[IMA_EVENT_NAME_LEN_MAX + 1] = { 0 };
596 		u8 *data_to_hash = field_data[i].data;
597 		u32 datalen = field_data[i].len;
598 		u32 datalen_to_hash = !ima_canonical_fmt ?
599 				datalen : (__force u32)cpu_to_le32(datalen);
600 
601 		if (strcmp(td->name, IMA_TEMPLATE_IMA_NAME) != 0) {
602 			rc = crypto_shash_update(shash,
603 						(const u8 *) &datalen_to_hash,
604 						sizeof(datalen_to_hash));
605 			if (rc)
606 				break;
607 		} else if (strcmp(td->fields[i]->field_id, "n") == 0) {
608 			memcpy(buffer, data_to_hash, datalen);
609 			data_to_hash = buffer;
610 			datalen = IMA_EVENT_NAME_LEN_MAX + 1;
611 		}
612 		rc = crypto_shash_update(shash, data_to_hash, datalen);
613 		if (rc)
614 			break;
615 	}
616 
617 	if (!rc)
618 		rc = crypto_shash_final(shash, entry->digests[tfm_idx].digest);
619 
620 	return rc;
621 }
622 
623 int ima_calc_field_array_hash(struct ima_field_data *field_data,
624 			      struct ima_template_entry *entry)
625 {
626 	u16 alg_id;
627 	int rc, i;
628 
629 	rc = ima_calc_field_array_hash_tfm(field_data, entry, ima_sha1_idx);
630 	if (rc)
631 		return rc;
632 
633 	entry->digests[ima_sha1_idx].alg_id = TPM_ALG_SHA1;
634 
635 	for (i = 0; i < NR_BANKS(ima_tpm_chip) + ima_extra_slots; i++) {
636 		if (i == ima_sha1_idx)
637 			continue;
638 
639 		if (i < NR_BANKS(ima_tpm_chip)) {
640 			alg_id = ima_tpm_chip->allocated_banks[i].alg_id;
641 			entry->digests[i].alg_id = alg_id;
642 		}
643 
644 		/* for unmapped TPM algorithms digest is still a padded SHA1 */
645 		if (!ima_algo_array[i].tfm) {
646 			memcpy(entry->digests[i].digest,
647 			       entry->digests[ima_sha1_idx].digest,
648 			       TPM_DIGEST_SIZE);
649 			continue;
650 		}
651 
652 		rc = ima_calc_field_array_hash_tfm(field_data, entry, i);
653 		if (rc)
654 			return rc;
655 	}
656 	return rc;
657 }
658 
659 static int calc_buffer_ahash_atfm(const void *buf, loff_t len,
660 				  struct ima_digest_data *hash,
661 				  struct crypto_ahash *tfm)
662 {
663 	struct ahash_request *req;
664 	struct scatterlist sg;
665 	struct crypto_wait wait;
666 	int rc, ahash_rc = 0;
667 
668 	hash->length = crypto_ahash_digestsize(tfm);
669 
670 	req = ahash_request_alloc(tfm, GFP_KERNEL);
671 	if (!req)
672 		return -ENOMEM;
673 
674 	crypto_init_wait(&wait);
675 	ahash_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG |
676 				   CRYPTO_TFM_REQ_MAY_SLEEP,
677 				   crypto_req_done, &wait);
678 
679 	rc = ahash_wait(crypto_ahash_init(req), &wait);
680 	if (rc)
681 		goto out;
682 
683 	sg_init_one(&sg, buf, len);
684 	ahash_request_set_crypt(req, &sg, NULL, len);
685 
686 	ahash_rc = crypto_ahash_update(req);
687 
688 	/* wait for the update request to complete */
689 	rc = ahash_wait(ahash_rc, &wait);
690 	if (!rc) {
691 		ahash_request_set_crypt(req, NULL, hash->digest, 0);
692 		rc = ahash_wait(crypto_ahash_final(req), &wait);
693 	}
694 out:
695 	ahash_request_free(req);
696 	return rc;
697 }
698 
699 static int calc_buffer_ahash(const void *buf, loff_t len,
700 			     struct ima_digest_data *hash)
701 {
702 	struct crypto_ahash *tfm;
703 	int rc;
704 
705 	tfm = ima_alloc_atfm(hash->algo);
706 	if (IS_ERR(tfm))
707 		return PTR_ERR(tfm);
708 
709 	rc = calc_buffer_ahash_atfm(buf, len, hash, tfm);
710 
711 	ima_free_atfm(tfm);
712 
713 	return rc;
714 }
715 
716 static int calc_buffer_shash_tfm(const void *buf, loff_t size,
717 				struct ima_digest_data *hash,
718 				struct crypto_shash *tfm)
719 {
720 	SHASH_DESC_ON_STACK(shash, tfm);
721 	unsigned int len;
722 	int rc;
723 
724 	shash->tfm = tfm;
725 
726 	hash->length = crypto_shash_digestsize(tfm);
727 
728 	rc = crypto_shash_init(shash);
729 	if (rc != 0)
730 		return rc;
731 
732 	while (size) {
733 		len = size < PAGE_SIZE ? size : PAGE_SIZE;
734 		rc = crypto_shash_update(shash, buf, len);
735 		if (rc)
736 			break;
737 		buf += len;
738 		size -= len;
739 	}
740 
741 	if (!rc)
742 		rc = crypto_shash_final(shash, hash->digest);
743 	return rc;
744 }
745 
746 static int calc_buffer_shash(const void *buf, loff_t len,
747 			     struct ima_digest_data *hash)
748 {
749 	struct crypto_shash *tfm;
750 	int rc;
751 
752 	tfm = ima_alloc_tfm(hash->algo);
753 	if (IS_ERR(tfm))
754 		return PTR_ERR(tfm);
755 
756 	rc = calc_buffer_shash_tfm(buf, len, hash, tfm);
757 
758 	ima_free_tfm(tfm);
759 	return rc;
760 }
761 
762 int ima_calc_buffer_hash(const void *buf, loff_t len,
763 			 struct ima_digest_data *hash)
764 {
765 	int rc;
766 
767 	if (ima_ahash_minsize && len >= ima_ahash_minsize) {
768 		rc = calc_buffer_ahash(buf, len, hash);
769 		if (!rc)
770 			return 0;
771 	}
772 
773 	return calc_buffer_shash(buf, len, hash);
774 }
775 
776 static void ima_pcrread(u32 idx, struct tpm_digest *d)
777 {
778 	if (!ima_tpm_chip)
779 		return;
780 
781 	if (tpm_pcr_read(ima_tpm_chip, idx, d) != 0)
782 		pr_err("Error Communicating to TPM chip\n");
783 }
784 
785 /*
786  * The boot_aggregate is a cumulative hash over TPM registers 0 - 7.  With
787  * TPM 1.2 the boot_aggregate was based on reading the SHA1 PCRs, but with
788  * TPM 2.0 hash agility, TPM chips could support multiple TPM PCR banks,
789  * allowing firmware to configure and enable different banks.
790  *
791  * Knowing which TPM bank is read to calculate the boot_aggregate digest
792  * needs to be conveyed to a verifier.  For this reason, use the same
793  * hash algorithm for reading the TPM PCRs as for calculating the boot
794  * aggregate digest as stored in the measurement list.
795  */
796 static int ima_calc_boot_aggregate_tfm(char *digest, u16 alg_id,
797 				       struct crypto_shash *tfm)
798 {
799 	struct tpm_digest d = { .alg_id = alg_id, .digest = {0} };
800 	int rc;
801 	u32 i;
802 	SHASH_DESC_ON_STACK(shash, tfm);
803 
804 	shash->tfm = tfm;
805 
806 	pr_devel("calculating the boot-aggregate based on TPM bank: %04x\n",
807 		 d.alg_id);
808 
809 	rc = crypto_shash_init(shash);
810 	if (rc != 0)
811 		return rc;
812 
813 	/* cumulative digest over TPM registers 0-7 */
814 	for (i = TPM_PCR0; i < TPM_PCR8; i++) {
815 		ima_pcrread(i, &d);
816 		/* now accumulate with current aggregate */
817 		rc = crypto_shash_update(shash, d.digest,
818 					 crypto_shash_digestsize(tfm));
819 		if (rc != 0)
820 			return rc;
821 	}
822 	/*
823 	 * Extend cumulative digest over TPM registers 8-9, which contain
824 	 * measurement for the kernel command line (reg. 8) and image (reg. 9)
825 	 * in a typical PCR allocation. Registers 8-9 are only included in
826 	 * non-SHA1 boot_aggregate digests to avoid ambiguity.
827 	 */
828 	if (alg_id != TPM_ALG_SHA1) {
829 		for (i = TPM_PCR8; i < TPM_PCR10; i++) {
830 			ima_pcrread(i, &d);
831 			rc = crypto_shash_update(shash, d.digest,
832 						crypto_shash_digestsize(tfm));
833 		}
834 	}
835 	if (!rc)
836 		crypto_shash_final(shash, digest);
837 	return rc;
838 }
839 
840 int ima_calc_boot_aggregate(struct ima_digest_data *hash)
841 {
842 	struct crypto_shash *tfm;
843 	u16 crypto_id, alg_id;
844 	int rc, i, bank_idx = -1;
845 
846 	for (i = 0; i < ima_tpm_chip->nr_allocated_banks; i++) {
847 		crypto_id = ima_tpm_chip->allocated_banks[i].crypto_id;
848 		if (crypto_id == hash->algo) {
849 			bank_idx = i;
850 			break;
851 		}
852 
853 		if (crypto_id == HASH_ALGO_SHA256)
854 			bank_idx = i;
855 
856 		if (bank_idx == -1 && crypto_id == HASH_ALGO_SHA1)
857 			bank_idx = i;
858 	}
859 
860 	if (bank_idx == -1) {
861 		pr_err("No suitable TPM algorithm for boot aggregate\n");
862 		return 0;
863 	}
864 
865 	hash->algo = ima_tpm_chip->allocated_banks[bank_idx].crypto_id;
866 
867 	tfm = ima_alloc_tfm(hash->algo);
868 	if (IS_ERR(tfm))
869 		return PTR_ERR(tfm);
870 
871 	hash->length = crypto_shash_digestsize(tfm);
872 	alg_id = ima_tpm_chip->allocated_banks[bank_idx].alg_id;
873 	rc = ima_calc_boot_aggregate_tfm(hash->digest, alg_id, tfm);
874 
875 	ima_free_tfm(tfm);
876 
877 	return rc;
878 }
879