Merge tag 'for-linus-5.2-rc1' of ssh://gitolite.kernel.org/pub/scm/linux/kernel/git...
[linux-2.6-microblaze.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
28 #include "ima.h"
29
30 /* minimum file size for ahash use */
31 static unsigned long ima_ahash_minsize;
32 module_param_named(ahash_minsize, ima_ahash_minsize, ulong, 0644);
33 MODULE_PARM_DESC(ahash_minsize, "Minimum file size for ahash use");
34
35 /* default is 0 - 1 page. */
36 static int ima_maxorder;
37 static unsigned int ima_bufsize = PAGE_SIZE;
38
39 static int param_set_bufsize(const char *val, const struct kernel_param *kp)
40 {
41         unsigned long long size;
42         int order;
43
44         size = memparse(val, NULL);
45         order = get_order(size);
46         if (order >= MAX_ORDER)
47                 return -EINVAL;
48         ima_maxorder = order;
49         ima_bufsize = PAGE_SIZE << order;
50         return 0;
51 }
52
53 static const struct kernel_param_ops param_ops_bufsize = {
54         .set = param_set_bufsize,
55         .get = param_get_uint,
56 };
57 #define param_check_bufsize(name, p) __param_check(name, p, unsigned int)
58
59 module_param_named(ahash_bufsize, ima_bufsize, bufsize, 0644);
60 MODULE_PARM_DESC(ahash_bufsize, "Maximum ahash buffer size");
61
62 static struct crypto_shash *ima_shash_tfm;
63 static struct crypto_ahash *ima_ahash_tfm;
64
65 int __init ima_init_crypto(void)
66 {
67         long rc;
68
69         ima_shash_tfm = crypto_alloc_shash(hash_algo_name[ima_hash_algo], 0, 0);
70         if (IS_ERR(ima_shash_tfm)) {
71                 rc = PTR_ERR(ima_shash_tfm);
72                 pr_err("Can not allocate %s (reason: %ld)\n",
73                        hash_algo_name[ima_hash_algo], rc);
74                 return rc;
75         }
76         pr_info("Allocated hash algorithm: %s\n",
77                 hash_algo_name[ima_hash_algo]);
78         return 0;
79 }
80
81 static struct crypto_shash *ima_alloc_tfm(enum hash_algo algo)
82 {
83         struct crypto_shash *tfm = ima_shash_tfm;
84         int rc;
85
86         if (algo < 0 || algo >= HASH_ALGO__LAST)
87                 algo = ima_hash_algo;
88
89         if (algo != ima_hash_algo) {
90                 tfm = crypto_alloc_shash(hash_algo_name[algo], 0, 0);
91                 if (IS_ERR(tfm)) {
92                         rc = PTR_ERR(tfm);
93                         pr_err("Can not allocate %s (reason: %d)\n",
94                                hash_algo_name[algo], rc);
95                 }
96         }
97         return tfm;
98 }
99
100 static void ima_free_tfm(struct crypto_shash *tfm)
101 {
102         if (tfm != ima_shash_tfm)
103                 crypto_free_shash(tfm);
104 }
105
106 /**
107  * ima_alloc_pages() - Allocate contiguous pages.
108  * @max_size:       Maximum amount of memory to allocate.
109  * @allocated_size: Returned size of actual allocation.
110  * @last_warn:      Should the min_size allocation warn or not.
111  *
112  * Tries to do opportunistic allocation for memory first trying to allocate
113  * max_size amount of memory and then splitting that until zero order is
114  * reached. Allocation is tried without generating allocation warnings unless
115  * last_warn is set. Last_warn set affects only last allocation of zero order.
116  *
117  * By default, ima_maxorder is 0 and it is equivalent to kmalloc(GFP_KERNEL)
118  *
119  * Return pointer to allocated memory, or NULL on failure.
120  */
121 static void *ima_alloc_pages(loff_t max_size, size_t *allocated_size,
122                              int last_warn)
123 {
124         void *ptr;
125         int order = ima_maxorder;
126         gfp_t gfp_mask = __GFP_RECLAIM | __GFP_NOWARN | __GFP_NORETRY;
127
128         if (order)
129                 order = min(get_order(max_size), order);
130
131         for (; order; order--) {
132                 ptr = (void *)__get_free_pages(gfp_mask, order);
133                 if (ptr) {
134                         *allocated_size = PAGE_SIZE << order;
135                         return ptr;
136                 }
137         }
138
139         /* order is zero - one page */
140
141         gfp_mask = GFP_KERNEL;
142
143         if (!last_warn)
144                 gfp_mask |= __GFP_NOWARN;
145
146         ptr = (void *)__get_free_pages(gfp_mask, 0);
147         if (ptr) {
148                 *allocated_size = PAGE_SIZE;
149                 return ptr;
150         }
151
152         *allocated_size = 0;
153         return NULL;
154 }
155
156 /**
157  * ima_free_pages() - Free pages allocated by ima_alloc_pages().
158  * @ptr:  Pointer to allocated pages.
159  * @size: Size of allocated buffer.
160  */
161 static void ima_free_pages(void *ptr, size_t size)
162 {
163         if (!ptr)
164                 return;
165         free_pages((unsigned long)ptr, get_order(size));
166 }
167
168 static struct crypto_ahash *ima_alloc_atfm(enum hash_algo algo)
169 {
170         struct crypto_ahash *tfm = ima_ahash_tfm;
171         int rc;
172
173         if (algo < 0 || algo >= HASH_ALGO__LAST)
174                 algo = ima_hash_algo;
175
176         if (algo != ima_hash_algo || !tfm) {
177                 tfm = crypto_alloc_ahash(hash_algo_name[algo], 0, 0);
178                 if (!IS_ERR(tfm)) {
179                         if (algo == ima_hash_algo)
180                                 ima_ahash_tfm = tfm;
181                 } else {
182                         rc = PTR_ERR(tfm);
183                         pr_err("Can not allocate %s (reason: %d)\n",
184                                hash_algo_name[algo], rc);
185                 }
186         }
187         return tfm;
188 }
189
190 static void ima_free_atfm(struct crypto_ahash *tfm)
191 {
192         if (tfm != ima_ahash_tfm)
193                 crypto_free_ahash(tfm);
194 }
195
196 static inline int ahash_wait(int err, struct crypto_wait *wait)
197 {
198
199         err = crypto_wait_req(err, wait);
200
201         if (err)
202                 pr_crit_ratelimited("ahash calculation failed: err: %d\n", err);
203
204         return err;
205 }
206
207 static int ima_calc_file_hash_atfm(struct file *file,
208                                    struct ima_digest_data *hash,
209                                    struct crypto_ahash *tfm)
210 {
211         loff_t i_size, offset;
212         char *rbuf[2] = { NULL, };
213         int rc, rbuf_len, active = 0, ahash_rc = 0;
214         struct ahash_request *req;
215         struct scatterlist sg[1];
216         struct crypto_wait wait;
217         size_t rbuf_size[2];
218
219         hash->length = crypto_ahash_digestsize(tfm);
220
221         req = ahash_request_alloc(tfm, GFP_KERNEL);
222         if (!req)
223                 return -ENOMEM;
224
225         crypto_init_wait(&wait);
226         ahash_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG |
227                                    CRYPTO_TFM_REQ_MAY_SLEEP,
228                                    crypto_req_done, &wait);
229
230         rc = ahash_wait(crypto_ahash_init(req), &wait);
231         if (rc)
232                 goto out1;
233
234         i_size = i_size_read(file_inode(file));
235
236         if (i_size == 0)
237                 goto out2;
238
239         /*
240          * Try to allocate maximum size of memory.
241          * Fail if even a single page cannot be allocated.
242          */
243         rbuf[0] = ima_alloc_pages(i_size, &rbuf_size[0], 1);
244         if (!rbuf[0]) {
245                 rc = -ENOMEM;
246                 goto out1;
247         }
248
249         /* Only allocate one buffer if that is enough. */
250         if (i_size > rbuf_size[0]) {
251                 /*
252                  * Try to allocate secondary buffer. If that fails fallback to
253                  * using single buffering. Use previous memory allocation size
254                  * as baseline for possible allocation size.
255                  */
256                 rbuf[1] = ima_alloc_pages(i_size - rbuf_size[0],
257                                           &rbuf_size[1], 0);
258         }
259
260         for (offset = 0; offset < i_size; offset += rbuf_len) {
261                 if (!rbuf[1] && offset) {
262                         /* Not using two buffers, and it is not the first
263                          * read/request, wait for the completion of the
264                          * previous ahash_update() request.
265                          */
266                         rc = ahash_wait(ahash_rc, &wait);
267                         if (rc)
268                                 goto out3;
269                 }
270                 /* read buffer */
271                 rbuf_len = min_t(loff_t, i_size - offset, rbuf_size[active]);
272                 rc = integrity_kernel_read(file, offset, rbuf[active],
273                                            rbuf_len);
274                 if (rc != rbuf_len)
275                         goto out3;
276
277                 if (rbuf[1] && offset) {
278                         /* Using two buffers, and it is not the first
279                          * read/request, wait for the completion of the
280                          * previous ahash_update() request.
281                          */
282                         rc = ahash_wait(ahash_rc, &wait);
283                         if (rc)
284                                 goto out3;
285                 }
286
287                 sg_init_one(&sg[0], rbuf[active], rbuf_len);
288                 ahash_request_set_crypt(req, sg, NULL, rbuf_len);
289
290                 ahash_rc = crypto_ahash_update(req);
291
292                 if (rbuf[1])
293                         active = !active; /* swap buffers, if we use two */
294         }
295         /* wait for the last update request to complete */
296         rc = ahash_wait(ahash_rc, &wait);
297 out3:
298         ima_free_pages(rbuf[0], rbuf_size[0]);
299         ima_free_pages(rbuf[1], rbuf_size[1]);
300 out2:
301         if (!rc) {
302                 ahash_request_set_crypt(req, NULL, hash->digest, 0);
303                 rc = ahash_wait(crypto_ahash_final(req), &wait);
304         }
305 out1:
306         ahash_request_free(req);
307         return rc;
308 }
309
310 static int ima_calc_file_ahash(struct file *file, struct ima_digest_data *hash)
311 {
312         struct crypto_ahash *tfm;
313         int rc;
314
315         tfm = ima_alloc_atfm(hash->algo);
316         if (IS_ERR(tfm))
317                 return PTR_ERR(tfm);
318
319         rc = ima_calc_file_hash_atfm(file, hash, tfm);
320
321         ima_free_atfm(tfm);
322
323         return rc;
324 }
325
326 static int ima_calc_file_hash_tfm(struct file *file,
327                                   struct ima_digest_data *hash,
328                                   struct crypto_shash *tfm)
329 {
330         loff_t i_size, offset = 0;
331         char *rbuf;
332         int rc;
333         SHASH_DESC_ON_STACK(shash, tfm);
334
335         shash->tfm = tfm;
336
337         hash->length = crypto_shash_digestsize(tfm);
338
339         rc = crypto_shash_init(shash);
340         if (rc != 0)
341                 return rc;
342
343         i_size = i_size_read(file_inode(file));
344
345         if (i_size == 0)
346                 goto out;
347
348         rbuf = kzalloc(PAGE_SIZE, GFP_KERNEL);
349         if (!rbuf)
350                 return -ENOMEM;
351
352         while (offset < i_size) {
353                 int rbuf_len;
354
355                 rbuf_len = integrity_kernel_read(file, offset, rbuf, PAGE_SIZE);
356                 if (rbuf_len < 0) {
357                         rc = rbuf_len;
358                         break;
359                 }
360                 if (rbuf_len == 0)
361                         break;
362                 offset += rbuf_len;
363
364                 rc = crypto_shash_update(shash, rbuf, rbuf_len);
365                 if (rc)
366                         break;
367         }
368         kfree(rbuf);
369 out:
370         if (!rc)
371                 rc = crypto_shash_final(shash, hash->digest);
372         return rc;
373 }
374
375 static int ima_calc_file_shash(struct file *file, struct ima_digest_data *hash)
376 {
377         struct crypto_shash *tfm;
378         int rc;
379
380         tfm = ima_alloc_tfm(hash->algo);
381         if (IS_ERR(tfm))
382                 return PTR_ERR(tfm);
383
384         rc = ima_calc_file_hash_tfm(file, hash, tfm);
385
386         ima_free_tfm(tfm);
387
388         return rc;
389 }
390
391 /*
392  * ima_calc_file_hash - calculate file hash
393  *
394  * Asynchronous hash (ahash) allows using HW acceleration for calculating
395  * a hash. ahash performance varies for different data sizes on different
396  * crypto accelerators. shash performance might be better for smaller files.
397  * The 'ima.ahash_minsize' module parameter allows specifying the best
398  * minimum file size for using ahash on the system.
399  *
400  * If the ima.ahash_minsize parameter is not specified, this function uses
401  * shash for the hash calculation.  If ahash fails, it falls back to using
402  * shash.
403  */
404 int ima_calc_file_hash(struct file *file, struct ima_digest_data *hash)
405 {
406         loff_t i_size;
407         int rc;
408         struct file *f = file;
409         bool new_file_instance = false, modified_flags = false;
410
411         /*
412          * For consistency, fail file's opened with the O_DIRECT flag on
413          * filesystems mounted with/without DAX option.
414          */
415         if (file->f_flags & O_DIRECT) {
416                 hash->length = hash_digest_size[ima_hash_algo];
417                 hash->algo = ima_hash_algo;
418                 return -EINVAL;
419         }
420
421         /* Open a new file instance in O_RDONLY if we cannot read */
422         if (!(file->f_mode & FMODE_READ)) {
423                 int flags = file->f_flags & ~(O_WRONLY | O_APPEND |
424                                 O_TRUNC | O_CREAT | O_NOCTTY | O_EXCL);
425                 flags |= O_RDONLY;
426                 f = dentry_open(&file->f_path, flags, file->f_cred);
427                 if (IS_ERR(f)) {
428                         /*
429                          * Cannot open the file again, lets modify f_flags
430                          * of original and continue
431                          */
432                         pr_info_ratelimited("Unable to reopen file for reading.\n");
433                         f = file;
434                         f->f_flags |= FMODE_READ;
435                         modified_flags = true;
436                 } else {
437                         new_file_instance = true;
438                 }
439         }
440
441         i_size = i_size_read(file_inode(f));
442
443         if (ima_ahash_minsize && i_size >= ima_ahash_minsize) {
444                 rc = ima_calc_file_ahash(f, hash);
445                 if (!rc)
446                         goto out;
447         }
448
449         rc = ima_calc_file_shash(f, hash);
450 out:
451         if (new_file_instance)
452                 fput(f);
453         else if (modified_flags)
454                 f->f_flags &= ~FMODE_READ;
455         return rc;
456 }
457
458 /*
459  * Calculate the hash of template data
460  */
461 static int ima_calc_field_array_hash_tfm(struct ima_field_data *field_data,
462                                          struct ima_template_desc *td,
463                                          int num_fields,
464                                          struct ima_digest_data *hash,
465                                          struct crypto_shash *tfm)
466 {
467         SHASH_DESC_ON_STACK(shash, tfm);
468         int rc, i;
469
470         shash->tfm = tfm;
471
472         hash->length = crypto_shash_digestsize(tfm);
473
474         rc = crypto_shash_init(shash);
475         if (rc != 0)
476                 return rc;
477
478         for (i = 0; i < num_fields; i++) {
479                 u8 buffer[IMA_EVENT_NAME_LEN_MAX + 1] = { 0 };
480                 u8 *data_to_hash = field_data[i].data;
481                 u32 datalen = field_data[i].len;
482                 u32 datalen_to_hash =
483                     !ima_canonical_fmt ? datalen : cpu_to_le32(datalen);
484
485                 if (strcmp(td->name, IMA_TEMPLATE_IMA_NAME) != 0) {
486                         rc = crypto_shash_update(shash,
487                                                 (const u8 *) &datalen_to_hash,
488                                                 sizeof(datalen_to_hash));
489                         if (rc)
490                                 break;
491                 } else if (strcmp(td->fields[i]->field_id, "n") == 0) {
492                         memcpy(buffer, data_to_hash, datalen);
493                         data_to_hash = buffer;
494                         datalen = IMA_EVENT_NAME_LEN_MAX + 1;
495                 }
496                 rc = crypto_shash_update(shash, data_to_hash, datalen);
497                 if (rc)
498                         break;
499         }
500
501         if (!rc)
502                 rc = crypto_shash_final(shash, hash->digest);
503
504         return rc;
505 }
506
507 int ima_calc_field_array_hash(struct ima_field_data *field_data,
508                               struct ima_template_desc *desc, int num_fields,
509                               struct ima_digest_data *hash)
510 {
511         struct crypto_shash *tfm;
512         int rc;
513
514         tfm = ima_alloc_tfm(hash->algo);
515         if (IS_ERR(tfm))
516                 return PTR_ERR(tfm);
517
518         rc = ima_calc_field_array_hash_tfm(field_data, desc, num_fields,
519                                            hash, tfm);
520
521         ima_free_tfm(tfm);
522
523         return rc;
524 }
525
526 static int calc_buffer_ahash_atfm(const void *buf, loff_t len,
527                                   struct ima_digest_data *hash,
528                                   struct crypto_ahash *tfm)
529 {
530         struct ahash_request *req;
531         struct scatterlist sg;
532         struct crypto_wait wait;
533         int rc, ahash_rc = 0;
534
535         hash->length = crypto_ahash_digestsize(tfm);
536
537         req = ahash_request_alloc(tfm, GFP_KERNEL);
538         if (!req)
539                 return -ENOMEM;
540
541         crypto_init_wait(&wait);
542         ahash_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG |
543                                    CRYPTO_TFM_REQ_MAY_SLEEP,
544                                    crypto_req_done, &wait);
545
546         rc = ahash_wait(crypto_ahash_init(req), &wait);
547         if (rc)
548                 goto out;
549
550         sg_init_one(&sg, buf, len);
551         ahash_request_set_crypt(req, &sg, NULL, len);
552
553         ahash_rc = crypto_ahash_update(req);
554
555         /* wait for the update request to complete */
556         rc = ahash_wait(ahash_rc, &wait);
557         if (!rc) {
558                 ahash_request_set_crypt(req, NULL, hash->digest, 0);
559                 rc = ahash_wait(crypto_ahash_final(req), &wait);
560         }
561 out:
562         ahash_request_free(req);
563         return rc;
564 }
565
566 static int calc_buffer_ahash(const void *buf, loff_t len,
567                              struct ima_digest_data *hash)
568 {
569         struct crypto_ahash *tfm;
570         int rc;
571
572         tfm = ima_alloc_atfm(hash->algo);
573         if (IS_ERR(tfm))
574                 return PTR_ERR(tfm);
575
576         rc = calc_buffer_ahash_atfm(buf, len, hash, tfm);
577
578         ima_free_atfm(tfm);
579
580         return rc;
581 }
582
583 static int calc_buffer_shash_tfm(const void *buf, loff_t size,
584                                 struct ima_digest_data *hash,
585                                 struct crypto_shash *tfm)
586 {
587         SHASH_DESC_ON_STACK(shash, tfm);
588         unsigned int len;
589         int rc;
590
591         shash->tfm = tfm;
592
593         hash->length = crypto_shash_digestsize(tfm);
594
595         rc = crypto_shash_init(shash);
596         if (rc != 0)
597                 return rc;
598
599         while (size) {
600                 len = size < PAGE_SIZE ? size : PAGE_SIZE;
601                 rc = crypto_shash_update(shash, buf, len);
602                 if (rc)
603                         break;
604                 buf += len;
605                 size -= len;
606         }
607
608         if (!rc)
609                 rc = crypto_shash_final(shash, hash->digest);
610         return rc;
611 }
612
613 static int calc_buffer_shash(const void *buf, loff_t len,
614                              struct ima_digest_data *hash)
615 {
616         struct crypto_shash *tfm;
617         int rc;
618
619         tfm = ima_alloc_tfm(hash->algo);
620         if (IS_ERR(tfm))
621                 return PTR_ERR(tfm);
622
623         rc = calc_buffer_shash_tfm(buf, len, hash, tfm);
624
625         ima_free_tfm(tfm);
626         return rc;
627 }
628
629 int ima_calc_buffer_hash(const void *buf, loff_t len,
630                          struct ima_digest_data *hash)
631 {
632         int rc;
633
634         if (ima_ahash_minsize && len >= ima_ahash_minsize) {
635                 rc = calc_buffer_ahash(buf, len, hash);
636                 if (!rc)
637                         return 0;
638         }
639
640         return calc_buffer_shash(buf, len, hash);
641 }
642
643 static void __init ima_pcrread(u32 idx, struct tpm_digest *d)
644 {
645         if (!ima_tpm_chip)
646                 return;
647
648         if (tpm_pcr_read(ima_tpm_chip, idx, d) != 0)
649                 pr_err("Error Communicating to TPM chip\n");
650 }
651
652 /*
653  * Calculate the boot aggregate hash
654  */
655 static int __init ima_calc_boot_aggregate_tfm(char *digest,
656                                               struct crypto_shash *tfm)
657 {
658         struct tpm_digest d = { .alg_id = TPM_ALG_SHA1, .digest = {0} };
659         int rc;
660         u32 i;
661         SHASH_DESC_ON_STACK(shash, tfm);
662
663         shash->tfm = tfm;
664
665         rc = crypto_shash_init(shash);
666         if (rc != 0)
667                 return rc;
668
669         /* cumulative sha1 over tpm registers 0-7 */
670         for (i = TPM_PCR0; i < TPM_PCR8; i++) {
671                 ima_pcrread(i, &d);
672                 /* now accumulate with current aggregate */
673                 rc = crypto_shash_update(shash, d.digest, TPM_DIGEST_SIZE);
674         }
675         if (!rc)
676                 crypto_shash_final(shash, digest);
677         return rc;
678 }
679
680 int __init ima_calc_boot_aggregate(struct ima_digest_data *hash)
681 {
682         struct crypto_shash *tfm;
683         int rc;
684
685         tfm = ima_alloc_tfm(hash->algo);
686         if (IS_ERR(tfm))
687                 return PTR_ERR(tfm);
688
689         hash->length = crypto_shash_digestsize(tfm);
690         rc = ima_calc_boot_aggregate_tfm(hash->digest, tfm);
691
692         ima_free_tfm(tfm);
693
694         return rc;
695 }