GNU Linux-libre 4.4.284-gnu1
[releases.git] / security / integrity / ima / ima_crypto.c
1 /*
2  * Copyright (C) 2005,2006,2007,2008 IBM Corporation
3  *
4  * Authors:
5  * Mimi Zohar <zohar@us.ibm.com>
6  * Kylene Hall <kjhall@us.ibm.com>
7  *
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.
11  *
12  * File: ima_crypto.c
13  *      Calculates md5/sha1 file hash, template hash, boot-aggreate hash
14  */
15
16 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
17
18 #include <linux/kernel.h>
19 #include <linux/moduleparam.h>
20 #include <linux/ratelimit.h>
21 #include <linux/file.h>
22 #include <linux/crypto.h>
23 #include <linux/scatterlist.h>
24 #include <linux/err.h>
25 #include <linux/slab.h>
26 #include <crypto/hash.h>
27 #include <crypto/hash_info.h>
28 #include "ima.h"
29
30 struct ahash_completion {
31         struct completion completion;
32         int err;
33 };
34
35 /* minimum file size for ahash use */
36 static unsigned long ima_ahash_minsize;
37 module_param_named(ahash_minsize, ima_ahash_minsize, ulong, 0644);
38 MODULE_PARM_DESC(ahash_minsize, "Minimum file size for ahash use");
39
40 /* default is 0 - 1 page. */
41 static int ima_maxorder;
42 static unsigned int ima_bufsize = PAGE_SIZE;
43
44 static int param_set_bufsize(const char *val, const struct kernel_param *kp)
45 {
46         unsigned long long size;
47         int order;
48
49         size = memparse(val, NULL);
50         order = get_order(size);
51         if (order >= MAX_ORDER)
52                 return -EINVAL;
53         ima_maxorder = order;
54         ima_bufsize = PAGE_SIZE << order;
55         return 0;
56 }
57
58 static const struct kernel_param_ops param_ops_bufsize = {
59         .set = param_set_bufsize,
60         .get = param_get_uint,
61 };
62 #define param_check_bufsize(name, p) __param_check(name, p, unsigned int)
63
64 module_param_named(ahash_bufsize, ima_bufsize, bufsize, 0644);
65 MODULE_PARM_DESC(ahash_bufsize, "Maximum ahash buffer size");
66
67 static struct crypto_shash *ima_shash_tfm;
68 static struct crypto_ahash *ima_ahash_tfm;
69
70 int __init ima_init_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;
90
91         if (algo < 0 || algo >= HASH_ALGO__LAST)
92                 algo = ima_hash_algo;
93
94         if (algo != ima_hash_algo) {
95                 tfm = crypto_alloc_shash(hash_algo_name[algo], 0, 0);
96                 if (IS_ERR(tfm)) {
97                         rc = PTR_ERR(tfm);
98                         pr_err("Can not allocate %s (reason: %d)\n",
99                                hash_algo_name[algo], rc);
100                 }
101         }
102         return tfm;
103 }
104
105 static void ima_free_tfm(struct crypto_shash *tfm)
106 {
107         if (tfm != ima_shash_tfm)
108                 crypto_free_shash(tfm);
109 }
110
111 /**
112  * ima_alloc_pages() - Allocate contiguous pages.
113  * @max_size:       Maximum amount of memory to allocate.
114  * @allocated_size: Returned size of actual allocation.
115  * @last_warn:      Should the min_size allocation warn or not.
116  *
117  * Tries to do opportunistic allocation for memory first trying to allocate
118  * max_size amount of memory and then splitting that until zero order is
119  * reached. Allocation is tried without generating allocation warnings unless
120  * last_warn is set. Last_warn set affects only last allocation of zero order.
121  *
122  * By default, ima_maxorder is 0 and it is equivalent to kmalloc(GFP_KERNEL)
123  *
124  * Return pointer to allocated memory, or NULL on failure.
125  */
126 static void *ima_alloc_pages(loff_t max_size, size_t *allocated_size,
127                              int last_warn)
128 {
129         void *ptr;
130         int order = ima_maxorder;
131         gfp_t gfp_mask = __GFP_RECLAIM | __GFP_NOWARN | __GFP_NORETRY;
132
133         if (order)
134                 order = min(get_order(max_size), order);
135
136         for (; order; order--) {
137                 ptr = (void *)__get_free_pages(gfp_mask, order);
138                 if (ptr) {
139                         *allocated_size = PAGE_SIZE << order;
140                         return ptr;
141                 }
142         }
143
144         /* order is zero - one page */
145
146         gfp_mask = GFP_KERNEL;
147
148         if (!last_warn)
149                 gfp_mask |= __GFP_NOWARN;
150
151         ptr = (void *)__get_free_pages(gfp_mask, 0);
152         if (ptr) {
153                 *allocated_size = PAGE_SIZE;
154                 return ptr;
155         }
156
157         *allocated_size = 0;
158         return NULL;
159 }
160
161 /**
162  * ima_free_pages() - Free pages allocated by ima_alloc_pages().
163  * @ptr:  Pointer to allocated pages.
164  * @size: Size of allocated buffer.
165  */
166 static void ima_free_pages(void *ptr, size_t size)
167 {
168         if (!ptr)
169                 return;
170         free_pages((unsigned long)ptr, get_order(size));
171 }
172
173 static struct crypto_ahash *ima_alloc_atfm(enum hash_algo algo)
174 {
175         struct crypto_ahash *tfm = ima_ahash_tfm;
176         int rc;
177
178         if (algo < 0 || algo >= HASH_ALGO__LAST)
179                 algo = ima_hash_algo;
180
181         if (algo != ima_hash_algo || !tfm) {
182                 tfm = crypto_alloc_ahash(hash_algo_name[algo], 0, 0);
183                 if (!IS_ERR(tfm)) {
184                         if (algo == ima_hash_algo)
185                                 ima_ahash_tfm = tfm;
186                 } else {
187                         rc = PTR_ERR(tfm);
188                         pr_err("Can not allocate %s (reason: %d)\n",
189                                hash_algo_name[algo], rc);
190                 }
191         }
192         return tfm;
193 }
194
195 static void ima_free_atfm(struct crypto_ahash *tfm)
196 {
197         if (tfm != ima_ahash_tfm)
198                 crypto_free_ahash(tfm);
199 }
200
201 static void ahash_complete(struct crypto_async_request *req, int err)
202 {
203         struct ahash_completion *res = req->data;
204
205         if (err == -EINPROGRESS)
206                 return;
207         res->err = err;
208         complete(&res->completion);
209 }
210
211 static int ahash_wait(int err, struct ahash_completion *res)
212 {
213         switch (err) {
214         case 0:
215                 break;
216         case -EINPROGRESS:
217         case -EBUSY:
218                 wait_for_completion(&res->completion);
219                 reinit_completion(&res->completion);
220                 err = res->err;
221                 /* fall through */
222         default:
223                 pr_crit_ratelimited("ahash calculation failed: err: %d\n", err);
224         }
225
226         return err;
227 }
228
229 static int ima_calc_file_hash_atfm(struct file *file,
230                                    struct ima_digest_data *hash,
231                                    struct crypto_ahash *tfm)
232 {
233         loff_t i_size, offset;
234         char *rbuf[2] = { NULL, };
235         int rc, read = 0, rbuf_len, active = 0, ahash_rc = 0;
236         struct ahash_request *req;
237         struct scatterlist sg[1];
238         struct ahash_completion res;
239         size_t rbuf_size[2];
240
241         hash->length = crypto_ahash_digestsize(tfm);
242
243         req = ahash_request_alloc(tfm, GFP_KERNEL);
244         if (!req)
245                 return -ENOMEM;
246
247         init_completion(&res.completion);
248         ahash_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG |
249                                    CRYPTO_TFM_REQ_MAY_SLEEP,
250                                    ahash_complete, &res);
251
252         rc = ahash_wait(crypto_ahash_init(req), &res);
253         if (rc)
254                 goto out1;
255
256         i_size = i_size_read(file_inode(file));
257
258         if (i_size == 0)
259                 goto out2;
260
261         /*
262          * Try to allocate maximum size of memory.
263          * Fail if even a single page cannot be allocated.
264          */
265         rbuf[0] = ima_alloc_pages(i_size, &rbuf_size[0], 1);
266         if (!rbuf[0]) {
267                 rc = -ENOMEM;
268                 goto out1;
269         }
270
271         /* Only allocate one buffer if that is enough. */
272         if (i_size > rbuf_size[0]) {
273                 /*
274                  * Try to allocate secondary buffer. If that fails fallback to
275                  * using single buffering. Use previous memory allocation size
276                  * as baseline for possible allocation size.
277                  */
278                 rbuf[1] = ima_alloc_pages(i_size - rbuf_size[0],
279                                           &rbuf_size[1], 0);
280         }
281
282         if (!(file->f_mode & FMODE_READ)) {
283                 file->f_mode |= FMODE_READ;
284                 read = 1;
285         }
286
287         for (offset = 0; offset < i_size; offset += rbuf_len) {
288                 if (!rbuf[1] && offset) {
289                         /* Not using two buffers, and it is not the first
290                          * read/request, wait for the completion of the
291                          * previous ahash_update() request.
292                          */
293                         rc = ahash_wait(ahash_rc, &res);
294                         if (rc)
295                                 goto out3;
296                 }
297                 /* read buffer */
298                 rbuf_len = min_t(loff_t, i_size - offset, rbuf_size[active]);
299                 rc = integrity_kernel_read(file, offset, rbuf[active],
300                                            rbuf_len);
301                 if (rc != rbuf_len) {
302                         if (rc >= 0)
303                                 rc = -EINVAL;
304                         goto out3;
305                 }
306
307                 if (rbuf[1] && offset) {
308                         /* Using two buffers, and it is not the first
309                          * read/request, wait for the completion of the
310                          * previous ahash_update() request.
311                          */
312                         rc = ahash_wait(ahash_rc, &res);
313                         if (rc)
314                                 goto out3;
315                 }
316
317                 sg_init_one(&sg[0], rbuf[active], rbuf_len);
318                 ahash_request_set_crypt(req, sg, NULL, rbuf_len);
319
320                 ahash_rc = crypto_ahash_update(req);
321
322                 if (rbuf[1])
323                         active = !active; /* swap buffers, if we use two */
324         }
325         /* wait for the last update request to complete */
326         rc = ahash_wait(ahash_rc, &res);
327 out3:
328         if (read)
329                 file->f_mode &= ~FMODE_READ;
330         ima_free_pages(rbuf[0], rbuf_size[0]);
331         ima_free_pages(rbuf[1], rbuf_size[1]);
332 out2:
333         if (!rc) {
334                 ahash_request_set_crypt(req, NULL, hash->digest, 0);
335                 rc = ahash_wait(crypto_ahash_final(req), &res);
336         }
337 out1:
338         ahash_request_free(req);
339         return rc;
340 }
341
342 static int ima_calc_file_ahash(struct file *file, struct ima_digest_data *hash)
343 {
344         struct crypto_ahash *tfm;
345         int rc;
346
347         tfm = ima_alloc_atfm(hash->algo);
348         if (IS_ERR(tfm))
349                 return PTR_ERR(tfm);
350
351         rc = ima_calc_file_hash_atfm(file, hash, tfm);
352
353         ima_free_atfm(tfm);
354
355         return rc;
356 }
357
358 static int ima_calc_file_hash_tfm(struct file *file,
359                                   struct ima_digest_data *hash,
360                                   struct crypto_shash *tfm)
361 {
362         loff_t i_size, offset = 0;
363         char *rbuf;
364         int rc, read = 0;
365         SHASH_DESC_ON_STACK(shash, tfm);
366
367         shash->tfm = tfm;
368         shash->flags = 0;
369
370         hash->length = crypto_shash_digestsize(tfm);
371
372         rc = crypto_shash_init(shash);
373         if (rc != 0)
374                 return rc;
375
376         i_size = i_size_read(file_inode(file));
377
378         if (i_size == 0)
379                 goto out;
380
381         rbuf = kzalloc(PAGE_SIZE, GFP_KERNEL);
382         if (!rbuf)
383                 return -ENOMEM;
384
385         if (!(file->f_mode & FMODE_READ)) {
386                 file->f_mode |= FMODE_READ;
387                 read = 1;
388         }
389
390         while (offset < i_size) {
391                 int rbuf_len;
392
393                 rbuf_len = integrity_kernel_read(file, offset, rbuf, PAGE_SIZE);
394                 if (rbuf_len < 0) {
395                         rc = rbuf_len;
396                         break;
397                 }
398                 if (rbuf_len == 0)
399                         break;
400                 offset += rbuf_len;
401
402                 rc = crypto_shash_update(shash, rbuf, rbuf_len);
403                 if (rc)
404                         break;
405         }
406         if (read)
407                 file->f_mode &= ~FMODE_READ;
408         kfree(rbuf);
409 out:
410         if (!rc)
411                 rc = crypto_shash_final(shash, hash->digest);
412         return rc;
413 }
414
415 static int ima_calc_file_shash(struct file *file, struct ima_digest_data *hash)
416 {
417         struct crypto_shash *tfm;
418         int rc;
419
420         tfm = ima_alloc_tfm(hash->algo);
421         if (IS_ERR(tfm))
422                 return PTR_ERR(tfm);
423
424         rc = ima_calc_file_hash_tfm(file, hash, tfm);
425
426         ima_free_tfm(tfm);
427
428         return rc;
429 }
430
431 /*
432  * ima_calc_file_hash - calculate file hash
433  *
434  * Asynchronous hash (ahash) allows using HW acceleration for calculating
435  * a hash. ahash performance varies for different data sizes on different
436  * crypto accelerators. shash performance might be better for smaller files.
437  * The 'ima.ahash_minsize' module parameter allows specifying the best
438  * minimum file size for using ahash on the system.
439  *
440  * If the ima.ahash_minsize parameter is not specified, this function uses
441  * shash for the hash calculation.  If ahash fails, it falls back to using
442  * shash.
443  */
444 int ima_calc_file_hash(struct file *file, struct ima_digest_data *hash)
445 {
446         loff_t i_size;
447         int rc;
448
449         i_size = i_size_read(file_inode(file));
450
451         if (ima_ahash_minsize && i_size >= ima_ahash_minsize) {
452                 rc = ima_calc_file_ahash(file, hash);
453                 if (!rc)
454                         return 0;
455         }
456
457         return ima_calc_file_shash(file, hash);
458 }
459
460 /*
461  * Calculate the hash of template data
462  */
463 static int ima_calc_field_array_hash_tfm(struct ima_field_data *field_data,
464                                          struct ima_template_desc *td,
465                                          int num_fields,
466                                          struct ima_digest_data *hash,
467                                          struct crypto_shash *tfm)
468 {
469         SHASH_DESC_ON_STACK(shash, tfm);
470         int rc, i;
471
472         shash->tfm = tfm;
473         shash->flags = 0;
474
475         hash->length = crypto_shash_digestsize(tfm);
476
477         rc = crypto_shash_init(shash);
478         if (rc != 0)
479                 return rc;
480
481         for (i = 0; i < num_fields; i++) {
482                 u8 buffer[IMA_EVENT_NAME_LEN_MAX + 1] = { 0 };
483                 u8 *data_to_hash = field_data[i].data;
484                 u32 datalen = field_data[i].len;
485
486                 if (strcmp(td->name, IMA_TEMPLATE_IMA_NAME) != 0) {
487                         rc = crypto_shash_update(shash,
488                                                 (const u8 *) &field_data[i].len,
489                                                 sizeof(field_data[i].len));
490                         if (rc)
491                                 break;
492                 } else if (strcmp(td->fields[i]->field_id, "n") == 0) {
493                         memcpy(buffer, data_to_hash, datalen);
494                         data_to_hash = buffer;
495                         datalen = IMA_EVENT_NAME_LEN_MAX + 1;
496                 }
497                 rc = crypto_shash_update(shash, data_to_hash, datalen);
498                 if (rc)
499                         break;
500         }
501
502         if (!rc)
503                 rc = crypto_shash_final(shash, hash->digest);
504
505         return rc;
506 }
507
508 int ima_calc_field_array_hash(struct ima_field_data *field_data,
509                               struct ima_template_desc *desc, int num_fields,
510                               struct ima_digest_data *hash)
511 {
512         struct crypto_shash *tfm;
513         int rc;
514
515         tfm = ima_alloc_tfm(hash->algo);
516         if (IS_ERR(tfm))
517                 return PTR_ERR(tfm);
518
519         rc = ima_calc_field_array_hash_tfm(field_data, desc, num_fields,
520                                            hash, tfm);
521
522         ima_free_tfm(tfm);
523
524         return rc;
525 }
526
527 static void __init ima_pcrread(int idx, u8 *pcr)
528 {
529         if (!ima_used_chip)
530                 return;
531
532         if (tpm_pcr_read(TPM_ANY_NUM, idx, pcr) != 0)
533                 pr_err("Error Communicating to TPM chip\n");
534 }
535
536 /*
537  * Calculate the boot aggregate hash
538  */
539 static int __init ima_calc_boot_aggregate_tfm(char *digest,
540                                               struct crypto_shash *tfm)
541 {
542         u8 pcr_i[TPM_DIGEST_SIZE];
543         int rc, i;
544         SHASH_DESC_ON_STACK(shash, tfm);
545
546         shash->tfm = tfm;
547         shash->flags = 0;
548
549         rc = crypto_shash_init(shash);
550         if (rc != 0)
551                 return rc;
552
553         /* cumulative sha1 over tpm registers 0-7 */
554         for (i = TPM_PCR0; i < TPM_PCR8; i++) {
555                 ima_pcrread(i, pcr_i);
556                 /* now accumulate with current aggregate */
557                 rc = crypto_shash_update(shash, pcr_i, TPM_DIGEST_SIZE);
558                 if (rc != 0)
559                         return rc;
560         }
561         if (!rc)
562                 crypto_shash_final(shash, digest);
563         return rc;
564 }
565
566 int __init ima_calc_boot_aggregate(struct ima_digest_data *hash)
567 {
568         struct crypto_shash *tfm;
569         int rc;
570
571         tfm = ima_alloc_tfm(hash->algo);
572         if (IS_ERR(tfm))
573                 return PTR_ERR(tfm);
574
575         hash->length = crypto_shash_digestsize(tfm);
576         rc = ima_calc_boot_aggregate_tfm(hash->digest, tfm);
577
578         ima_free_tfm(tfm);
579
580         return rc;
581 }