2 * Copyright (C) 2005,2006,2007,2008 IBM Corporation
5 * Mimi Zohar <zohar@us.ibm.com>
6 * Kylene Hall <kjhall@us.ibm.com>
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, version 2 of the License.
13 * Calculates md5/sha1 file hash, template hash, boot-aggreate hash
16 #include <linux/kernel.h>
17 #include <linux/file.h>
18 #include <linux/crypto.h>
19 #include <linux/scatterlist.h>
20 #include <linux/err.h>
21 #include <linux/slab.h>
22 #include <crypto/hash.h>
25 static struct crypto_shash *ima_shash_tfm;
27 int ima_init_crypto(void)
31 ima_shash_tfm = crypto_alloc_shash(ima_hash, 0, 0);
32 if (IS_ERR(ima_shash_tfm)) {
33 rc = PTR_ERR(ima_shash_tfm);
34 pr_err("Can not allocate %s (reason: %ld)\n", ima_hash, rc);
41 * Calculate the MD5/SHA1 file digest
43 int ima_calc_file_hash(struct file *file, char *digest)
45 loff_t i_size, offset = 0;
49 struct shash_desc shash;
50 char ctx[crypto_shash_descsize(ima_shash_tfm)];
53 desc.shash.tfm = ima_shash_tfm;
56 rc = crypto_shash_init(&desc.shash);
60 rbuf = kzalloc(PAGE_SIZE, GFP_KERNEL);
65 if (!(file->f_mode & FMODE_READ)) {
66 file->f_mode |= FMODE_READ;
69 i_size = i_size_read(file->f_dentry->d_inode);
70 while (offset < i_size) {
73 rbuf_len = kernel_read(file, offset, rbuf, PAGE_SIZE);
82 rc = crypto_shash_update(&desc.shash, rbuf, rbuf_len);
88 rc = crypto_shash_final(&desc.shash, digest);
90 file->f_mode &= ~FMODE_READ;
96 * Calculate the hash of a given buffer
98 int ima_calc_buffer_hash(const void *data, int len, char *digest)
101 struct shash_desc shash;
102 char ctx[crypto_shash_descsize(ima_shash_tfm)];
105 desc.shash.tfm = ima_shash_tfm;
106 desc.shash.flags = 0;
108 return crypto_shash_digest(&desc.shash, data, len, digest);
111 static void __init ima_pcrread(int idx, u8 *pcr)
116 if (tpm_pcr_read(TPM_ANY_NUM, idx, pcr) != 0)
117 pr_err("IMA: Error Communicating to TPM chip\n");
121 * Calculate the boot aggregate hash
123 int __init ima_calc_boot_aggregate(char *digest)
125 u8 pcr_i[IMA_DIGEST_SIZE];
128 struct shash_desc shash;
129 char ctx[crypto_shash_descsize(ima_shash_tfm)];
132 desc.shash.tfm = ima_shash_tfm;
133 desc.shash.flags = 0;
135 rc = crypto_shash_init(&desc.shash);
139 /* cumulative sha1 over tpm registers 0-7 */
140 for (i = TPM_PCR0; i < TPM_PCR8; i++) {
141 ima_pcrread(i, pcr_i);
142 /* now accumulate with current aggregate */
143 rc = crypto_shash_update(&desc.shash, pcr_i, IMA_DIGEST_SIZE);
146 crypto_shash_final(&desc.shash, digest);