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>
23 static int init_desc(struct hash_desc *desc)
27 desc->tfm = crypto_alloc_hash(ima_hash, 0, CRYPTO_ALG_ASYNC);
28 if (IS_ERR(desc->tfm)) {
29 pr_info("failed to load %s transform: %ld\n",
30 ima_hash, PTR_ERR(desc->tfm));
31 rc = PTR_ERR(desc->tfm);
35 rc = crypto_hash_init(desc);
37 crypto_free_hash(desc->tfm);
42 * Calculate the MD5/SHA1 file digest
44 int ima_calc_hash(struct file *file, char *digest)
46 struct hash_desc desc;
47 struct scatterlist sg[1];
52 rc = init_desc(&desc);
56 rbuf = kzalloc(PAGE_SIZE, GFP_KERNEL);
61 i_size = i_size_read(file->f_dentry->d_inode);
62 while (offset < i_size) {
65 rbuf_len = kernel_read(file, offset, rbuf, PAGE_SIZE);
71 sg_init_one(sg, rbuf, rbuf_len);
73 rc = crypto_hash_update(&desc, sg, rbuf_len);
79 rc = crypto_hash_final(&desc, digest);
81 crypto_free_hash(desc.tfm);
86 * Calculate the hash of a given template
88 int ima_calc_template_hash(int template_len, void *template, char *digest)
90 struct hash_desc desc;
91 struct scatterlist sg[1];
94 rc = init_desc(&desc);
98 sg_init_one(sg, template, template_len);
99 rc = crypto_hash_update(&desc, sg, template_len);
101 rc = crypto_hash_final(&desc, digest);
102 crypto_free_hash(desc.tfm);
106 static void ima_pcrread(int idx, u8 *pcr)
111 if (tpm_pcr_read(TPM_ANY_NUM, idx, pcr) != 0)
112 pr_err("Error Communicating to TPM chip\n");
116 * Calculate the boot aggregate hash
118 int ima_calc_boot_aggregate(char *digest)
120 struct hash_desc desc;
121 struct scatterlist sg;
122 u8 pcr_i[IMA_DIGEST_SIZE];
125 rc = init_desc(&desc);
129 /* cumulative sha1 over tpm registers 0-7 */
130 for (i = TPM_PCR0; i < TPM_PCR8; i++) {
131 ima_pcrread(i, pcr_i);
132 /* now accumulate with current aggregate */
133 sg_init_one(&sg, pcr_i, IMA_DIGEST_SIZE);
134 rc = crypto_hash_update(&desc, &sg, IMA_DIGEST_SIZE);
137 crypto_hash_final(&desc, digest);
138 crypto_free_hash(desc.tfm);