GNU Linux-libre 4.14.254-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
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, 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         for (offset = 0; offset < i_size; offset += rbuf_len) {
283                 if (!rbuf[1] && offset) {
284                         /* Not using two buffers, and it is not the first
285                          * read/request, wait for the completion of the
286                          * previous ahash_update() request.
287                          */
288                         rc = ahash_wait(ahash_rc, &res);
289                         if (rc)
290                                 goto out3;
291                 }
292                 /* read buffer */
293                 rbuf_len = min_t(loff_t, i_size - offset, rbuf_size[active]);
294                 rc = integrity_kernel_read(file, offset, rbuf[active],
295                                            rbuf_len);
296                 if (rc != rbuf_len) {
297                         if (rc >= 0)
298                                 rc = -EINVAL;
299                         goto out3;
300                 }
301
302                 if (rbuf[1] && offset) {
303                         /* Using two buffers, and it is not the first
304                          * read/request, wait for the completion of the
305                          * previous ahash_update() request.
306                          */
307                         rc = ahash_wait(ahash_rc, &res);
308                         if (rc)
309                                 goto out3;
310                 }
311
312                 sg_init_one(&sg[0], rbuf[active], rbuf_len);
313                 ahash_request_set_crypt(req, sg, NULL, rbuf_len);
314
315                 ahash_rc = crypto_ahash_update(req);
316
317                 if (rbuf[1])
318                         active = !active; /* swap buffers, if we use two */
319         }
320         /* wait for the last update request to complete */
321         rc = ahash_wait(ahash_rc, &res);
322 out3:
323         ima_free_pages(rbuf[0], rbuf_size[0]);
324         ima_free_pages(rbuf[1], rbuf_size[1]);
325 out2:
326         if (!rc) {
327                 ahash_request_set_crypt(req, NULL, hash->digest, 0);
328                 rc = ahash_wait(crypto_ahash_final(req), &res);
329         }
330 out1:
331         ahash_request_free(req);
332         return rc;
333 }
334
335 static int ima_calc_file_ahash(struct file *file, struct ima_digest_data *hash)
336 {
337         struct crypto_ahash *tfm;
338         int rc;
339
340         tfm = ima_alloc_atfm(hash->algo);
341         if (IS_ERR(tfm))
342                 return PTR_ERR(tfm);
343
344         rc = ima_calc_file_hash_atfm(file, hash, tfm);
345
346         ima_free_atfm(tfm);
347
348         return rc;
349 }
350
351 static int ima_calc_file_hash_tfm(struct file *file,
352                                   struct ima_digest_data *hash,
353                                   struct crypto_shash *tfm)
354 {
355         loff_t i_size, offset = 0;
356         char *rbuf;
357         int rc;
358         SHASH_DESC_ON_STACK(shash, tfm);
359
360         shash->tfm = tfm;
361         shash->flags = 0;
362
363         hash->length = crypto_shash_digestsize(tfm);
364
365         rc = crypto_shash_init(shash);
366         if (rc != 0)
367                 return rc;
368
369         i_size = i_size_read(file_inode(file));
370
371         if (i_size == 0)
372                 goto out;
373
374         rbuf = kzalloc(PAGE_SIZE, GFP_KERNEL);
375         if (!rbuf)
376                 return -ENOMEM;
377
378         while (offset < i_size) {
379                 int rbuf_len;
380
381                 rbuf_len = integrity_kernel_read(file, offset, rbuf, PAGE_SIZE);
382                 if (rbuf_len < 0) {
383                         rc = rbuf_len;
384                         break;
385                 }
386                 if (rbuf_len == 0)
387                         break;
388                 offset += rbuf_len;
389
390                 rc = crypto_shash_update(shash, rbuf, rbuf_len);
391                 if (rc)
392                         break;
393         }
394         kfree(rbuf);
395 out:
396         if (!rc)
397                 rc = crypto_shash_final(shash, hash->digest);
398         return rc;
399 }
400
401 static int ima_calc_file_shash(struct file *file, struct ima_digest_data *hash)
402 {
403         struct crypto_shash *tfm;
404         int rc;
405
406         tfm = ima_alloc_tfm(hash->algo);
407         if (IS_ERR(tfm))
408                 return PTR_ERR(tfm);
409
410         rc = ima_calc_file_hash_tfm(file, hash, tfm);
411
412         ima_free_tfm(tfm);
413
414         return rc;
415 }
416
417 /*
418  * ima_calc_file_hash - calculate file hash
419  *
420  * Asynchronous hash (ahash) allows using HW acceleration for calculating
421  * a hash. ahash performance varies for different data sizes on different
422  * crypto accelerators. shash performance might be better for smaller files.
423  * The 'ima.ahash_minsize' module parameter allows specifying the best
424  * minimum file size for using ahash on the system.
425  *
426  * If the ima.ahash_minsize parameter is not specified, this function uses
427  * shash for the hash calculation.  If ahash fails, it falls back to using
428  * shash.
429  */
430 int ima_calc_file_hash(struct file *file, struct ima_digest_data *hash)
431 {
432         loff_t i_size;
433         int rc;
434         struct file *f = file;
435         bool new_file_instance = false;
436
437         /*
438          * For consistency, fail file's opened with the O_DIRECT flag on
439          * filesystems mounted with/without DAX option.
440          */
441         if (file->f_flags & O_DIRECT) {
442                 hash->length = hash_digest_size[ima_hash_algo];
443                 hash->algo = ima_hash_algo;
444                 return -EINVAL;
445         }
446
447         /* Open a new file instance in O_RDONLY if we cannot read */
448         if (!(file->f_mode & FMODE_READ)) {
449                 int flags = file->f_flags & ~(O_WRONLY | O_APPEND |
450                                 O_TRUNC | O_CREAT | O_NOCTTY | O_EXCL);
451                 flags |= O_RDONLY;
452                 f = dentry_open(&file->f_path, flags, file->f_cred);
453                 if (IS_ERR(f))
454                         return PTR_ERR(f);
455
456                 new_file_instance = true;
457         }
458
459         i_size = i_size_read(file_inode(f));
460
461         if (ima_ahash_minsize && i_size >= ima_ahash_minsize) {
462                 rc = ima_calc_file_ahash(f, hash);
463                 if (!rc)
464                         goto out;
465         }
466
467         rc = ima_calc_file_shash(f, hash);
468 out:
469         if (new_file_instance)
470                 fput(f);
471         return rc;
472 }
473
474 /*
475  * Calculate the hash of template data
476  */
477 static int ima_calc_field_array_hash_tfm(struct ima_field_data *field_data,
478                                          struct ima_template_desc *td,
479                                          int num_fields,
480                                          struct ima_digest_data *hash,
481                                          struct crypto_shash *tfm)
482 {
483         SHASH_DESC_ON_STACK(shash, tfm);
484         int rc, i;
485
486         shash->tfm = tfm;
487         shash->flags = 0;
488
489         hash->length = crypto_shash_digestsize(tfm);
490
491         rc = crypto_shash_init(shash);
492         if (rc != 0)
493                 return rc;
494
495         for (i = 0; i < num_fields; i++) {
496                 u8 buffer[IMA_EVENT_NAME_LEN_MAX + 1] = { 0 };
497                 u8 *data_to_hash = field_data[i].data;
498                 u32 datalen = field_data[i].len;
499                 u32 datalen_to_hash =
500                     !ima_canonical_fmt ? datalen : cpu_to_le32(datalen);
501
502                 if (strcmp(td->name, IMA_TEMPLATE_IMA_NAME) != 0) {
503                         rc = crypto_shash_update(shash,
504                                                 (const u8 *) &datalen_to_hash,
505                                                 sizeof(datalen_to_hash));
506                         if (rc)
507                                 break;
508                 } else if (strcmp(td->fields[i]->field_id, "n") == 0) {
509                         memcpy(buffer, data_to_hash, datalen);
510                         data_to_hash = buffer;
511                         datalen = IMA_EVENT_NAME_LEN_MAX + 1;
512                 }
513                 rc = crypto_shash_update(shash, data_to_hash, datalen);
514                 if (rc)
515                         break;
516         }
517
518         if (!rc)
519                 rc = crypto_shash_final(shash, hash->digest);
520
521         return rc;
522 }
523
524 int ima_calc_field_array_hash(struct ima_field_data *field_data,
525                               struct ima_template_desc *desc, int num_fields,
526                               struct ima_digest_data *hash)
527 {
528         struct crypto_shash *tfm;
529         int rc;
530
531         tfm = ima_alloc_tfm(hash->algo);
532         if (IS_ERR(tfm))
533                 return PTR_ERR(tfm);
534
535         rc = ima_calc_field_array_hash_tfm(field_data, desc, num_fields,
536                                            hash, tfm);
537
538         ima_free_tfm(tfm);
539
540         return rc;
541 }
542
543 static int calc_buffer_ahash_atfm(const void *buf, loff_t len,
544                                   struct ima_digest_data *hash,
545                                   struct crypto_ahash *tfm)
546 {
547         struct ahash_request *req;
548         struct scatterlist sg;
549         struct ahash_completion res;
550         int rc, ahash_rc = 0;
551
552         hash->length = crypto_ahash_digestsize(tfm);
553
554         req = ahash_request_alloc(tfm, GFP_KERNEL);
555         if (!req)
556                 return -ENOMEM;
557
558         init_completion(&res.completion);
559         ahash_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG |
560                                    CRYPTO_TFM_REQ_MAY_SLEEP,
561                                    ahash_complete, &res);
562
563         rc = ahash_wait(crypto_ahash_init(req), &res);
564         if (rc)
565                 goto out;
566
567         sg_init_one(&sg, buf, len);
568         ahash_request_set_crypt(req, &sg, NULL, len);
569
570         ahash_rc = crypto_ahash_update(req);
571
572         /* wait for the update request to complete */
573         rc = ahash_wait(ahash_rc, &res);
574         if (!rc) {
575                 ahash_request_set_crypt(req, NULL, hash->digest, 0);
576                 rc = ahash_wait(crypto_ahash_final(req), &res);
577         }
578 out:
579         ahash_request_free(req);
580         return rc;
581 }
582
583 static int calc_buffer_ahash(const void *buf, loff_t len,
584                              struct ima_digest_data *hash)
585 {
586         struct crypto_ahash *tfm;
587         int rc;
588
589         tfm = ima_alloc_atfm(hash->algo);
590         if (IS_ERR(tfm))
591                 return PTR_ERR(tfm);
592
593         rc = calc_buffer_ahash_atfm(buf, len, hash, tfm);
594
595         ima_free_atfm(tfm);
596
597         return rc;
598 }
599
600 static int calc_buffer_shash_tfm(const void *buf, loff_t size,
601                                 struct ima_digest_data *hash,
602                                 struct crypto_shash *tfm)
603 {
604         SHASH_DESC_ON_STACK(shash, tfm);
605         unsigned int len;
606         int rc;
607
608         shash->tfm = tfm;
609         shash->flags = 0;
610
611         hash->length = crypto_shash_digestsize(tfm);
612
613         rc = crypto_shash_init(shash);
614         if (rc != 0)
615                 return rc;
616
617         while (size) {
618                 len = size < PAGE_SIZE ? size : PAGE_SIZE;
619                 rc = crypto_shash_update(shash, buf, len);
620                 if (rc)
621                         break;
622                 buf += len;
623                 size -= len;
624         }
625
626         if (!rc)
627                 rc = crypto_shash_final(shash, hash->digest);
628         return rc;
629 }
630
631 static int calc_buffer_shash(const void *buf, loff_t len,
632                              struct ima_digest_data *hash)
633 {
634         struct crypto_shash *tfm;
635         int rc;
636
637         tfm = ima_alloc_tfm(hash->algo);
638         if (IS_ERR(tfm))
639                 return PTR_ERR(tfm);
640
641         rc = calc_buffer_shash_tfm(buf, len, hash, tfm);
642
643         ima_free_tfm(tfm);
644         return rc;
645 }
646
647 int ima_calc_buffer_hash(const void *buf, loff_t len,
648                          struct ima_digest_data *hash)
649 {
650         int rc;
651
652         if (ima_ahash_minsize && len >= ima_ahash_minsize) {
653                 rc = calc_buffer_ahash(buf, len, hash);
654                 if (!rc)
655                         return 0;
656         }
657
658         return calc_buffer_shash(buf, len, hash);
659 }
660
661 static void __init ima_pcrread(int idx, u8 *pcr)
662 {
663         if (!ima_used_chip)
664                 return;
665
666         if (tpm_pcr_read(TPM_ANY_NUM, idx, pcr) != 0)
667                 pr_err("Error Communicating to TPM chip\n");
668 }
669
670 /*
671  * Calculate the boot aggregate hash
672  */
673 static int __init ima_calc_boot_aggregate_tfm(char *digest,
674                                               struct crypto_shash *tfm)
675 {
676         u8 pcr_i[TPM_DIGEST_SIZE];
677         int rc, i;
678         SHASH_DESC_ON_STACK(shash, tfm);
679
680         shash->tfm = tfm;
681         shash->flags = 0;
682
683         rc = crypto_shash_init(shash);
684         if (rc != 0)
685                 return rc;
686
687         /* cumulative sha1 over tpm registers 0-7 */
688         for (i = TPM_PCR0; i < TPM_PCR8; i++) {
689                 ima_pcrread(i, pcr_i);
690                 /* now accumulate with current aggregate */
691                 rc = crypto_shash_update(shash, pcr_i, TPM_DIGEST_SIZE);
692                 if (rc != 0)
693                         return rc;
694         }
695         if (!rc)
696                 crypto_shash_final(shash, digest);
697         return rc;
698 }
699
700 int __init ima_calc_boot_aggregate(struct ima_digest_data *hash)
701 {
702         struct crypto_shash *tfm;
703         int rc;
704
705         tfm = ima_alloc_tfm(hash->algo);
706         if (IS_ERR(tfm))
707                 return PTR_ERR(tfm);
708
709         hash->length = crypto_shash_digestsize(tfm);
710         rc = ima_calc_boot_aggregate_tfm(hash->digest, tfm);
711
712         ima_free_tfm(tfm);
713
714         return rc;
715 }