99c5ac8d7daeb0b0a7fb76d87b1b72b14a12fc3e
[platform/upstream/ima-evm-utils.git] / src / libimaevm.c
1 /*
2  * ima-evm-utils - IMA/EVM support utilities
3  *
4  * Copyright (C) 2011 Nokia Corporation
5  * Copyright (C) 2011,2012,2013 Intel Corporation
6  * Copyright (C) 2013,2014 Samsung Electronics
7  *
8  * Authors:
9  * Dmitry Kasatkin <dmitry.kasatkin@nokia.com>
10  *                 <dmitry.kasatkin@intel.com>
11  *                 <d.kasatkin@samsung.com>
12  * Pawel Polawski  <p.polawski@samsung.com>
13  *
14  * This program is free software; you can redistribute it and/or
15  * modify it under the terms of the GNU General Public License
16  * version 2 as published by the Free Software Foundation.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
25  *
26  * As a special exception, the copyright holders give permission to link the
27  * code of portions of this program with the OpenSSL library under certain
28  * conditions as described in each individual source file and distribute
29  * linked combinations including the program with the OpenSSL library. You
30  * must comply with the GNU General Public License in all respects
31  * for all of the code used other than as permitted herein. If you modify
32  * file(s) with this exception, you may extend this exception to your
33  * version of the file(s), but you are not obligated to do so. If you do not
34  * wish to do so, delete this exception statement from your version. If you
35  * delete this exception statement from all source files in the program,
36  * then also delete it in the license file.
37  *
38  * File: libimaevm.c
39  * IMA/EVM library
40  */
41
42 /* should we use logger instead for library? */
43 #define USE_FPRINTF
44
45 #include <sys/types.h>
46 #include <sys/param.h>
47 #include <sys/stat.h>
48 #include <asm/byteorder.h>
49 #include <attr/xattr.h>
50 #include <unistd.h>
51 #include <dirent.h>
52 #include <string.h>
53 #include <stdio.h>
54 #include <fcntl.h>
55 #include <errno.h>
56
57 #include <openssl/pem.h>
58 #include <openssl/evp.h>
59 #include <openssl/x509.h>
60
61 #include "imaevm.h"
62
63 const char *const pkey_hash_algo[PKEY_HASH__LAST] = {
64         [PKEY_HASH_MD4]         = "md4",
65         [PKEY_HASH_MD5]         = "md5",
66         [PKEY_HASH_SHA1]        = "sha1",
67         [PKEY_HASH_RIPE_MD_160] = "rmd160",
68         [PKEY_HASH_SHA256]      = "sha256",
69         [PKEY_HASH_SHA384]      = "sha384",
70         [PKEY_HASH_SHA512]      = "sha512",
71         [PKEY_HASH_SHA224]      = "sha224",
72 };
73
74 /*
75  * Hash algorithm OIDs plus ASN.1 DER wrappings [RFC4880 sec 5.2.2].
76  */
77 static const uint8_t RSA_digest_info_MD5[] = {
78         0x30, 0x20, 0x30, 0x0C, 0x06, 0x08,
79         0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x05, /* OID */
80         0x05, 0x00, 0x04, 0x10
81 };
82
83 static const uint8_t RSA_digest_info_SHA1[] = {
84         0x30, 0x21, 0x30, 0x09, 0x06, 0x05,
85         0x2B, 0x0E, 0x03, 0x02, 0x1A,
86         0x05, 0x00, 0x04, 0x14
87 };
88
89 static const uint8_t RSA_digest_info_RIPE_MD_160[] = {
90         0x30, 0x21, 0x30, 0x09, 0x06, 0x05,
91         0x2B, 0x24, 0x03, 0x02, 0x01,
92         0x05, 0x00, 0x04, 0x14
93 };
94
95 static const uint8_t RSA_digest_info_SHA224[] = {
96         0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09,
97         0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04,
98         0x05, 0x00, 0x04, 0x1C
99 };
100
101 static const uint8_t RSA_digest_info_SHA256[] = {
102         0x30, 0x31, 0x30, 0x0d, 0x06, 0x09,
103         0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01,
104         0x05, 0x00, 0x04, 0x20
105 };
106
107 static const uint8_t RSA_digest_info_SHA384[] = {
108         0x30, 0x41, 0x30, 0x0d, 0x06, 0x09,
109         0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02,
110         0x05, 0x00, 0x04, 0x30
111 };
112
113 static const uint8_t RSA_digest_info_SHA512[] = {
114         0x30, 0x51, 0x30, 0x0d, 0x06, 0x09,
115         0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03,
116         0x05, 0x00, 0x04, 0x40
117 };
118
119 const struct RSA_ASN1_template RSA_ASN1_templates[PKEY_HASH__LAST] = {
120 #define _(X) { RSA_digest_info_##X, sizeof(RSA_digest_info_##X) }
121         [PKEY_HASH_MD5]         = _(MD5),
122         [PKEY_HASH_SHA1]        = _(SHA1),
123         [PKEY_HASH_RIPE_MD_160] = _(RIPE_MD_160),
124         [PKEY_HASH_SHA256]      = _(SHA256),
125         [PKEY_HASH_SHA384]      = _(SHA384),
126         [PKEY_HASH_SHA512]      = _(SHA512),
127         [PKEY_HASH_SHA224]      = _(SHA224),
128 #undef _
129 };
130
131 struct libevm_params params = {
132         .verbose = LOG_INFO - 1,
133         .x509 = 1,
134         .hash_algo = "sha1",
135 };
136
137 void do_dump(FILE *fp, const void *ptr, int len, bool cr)
138 {
139         int i;
140         uint8_t *data = (uint8_t *) ptr;
141
142         for (i = 0; i < len; i++)
143                 fprintf(fp, "%02x", data[i]);
144         if (cr)
145                 fprintf(fp, "\n");
146 }
147
148 void dump(const void *ptr, int len)
149 {
150         do_dump(stdout, ptr, len, true);
151 }
152
153 int get_filesize(const char *filename)
154 {
155         struct stat stats;
156         /*  Need to know the file length */
157         stat(filename, &stats);
158         return (int)stats.st_size;
159 }
160
161 static inline off_t get_fdsize(int fd)
162 {
163         struct stat stats;
164         /*  Need to know the file length */
165         fstat(fd, &stats);
166         return stats.st_size;
167 }
168
169 static int add_file_hash(const char *file, EVP_MD_CTX *ctx)
170 {
171         uint8_t *data;
172         int err = -1, bs = DATA_SIZE;
173         off_t size, len;
174         FILE *fp;
175
176         fp = fopen(file, "r");
177         if (!fp) {
178                 log_err("Failed to open: %s\n", file);
179                 return -1;
180         }
181
182         data = malloc(bs);
183         if (!data) {
184                 log_err("malloc failed\n");
185                 goto out;
186         }
187
188         for (size = get_fdsize(fileno(fp)); size; size -= len) {
189                 len = MIN(size, bs);
190                 if (!fread(data, len, 1, fp)) {
191                         if (ferror(fp)) {
192                                 log_err("fread() failed\n\n");
193                                 goto out;
194                         }
195                         break;
196                 }
197                 if (!EVP_DigestUpdate(ctx, data, len)) {
198                         log_err("EVP_DigestUpdate() failed\n");
199                         err = 1;
200                         goto out;
201                 }
202         }
203         err = 0;
204 out:
205         fclose(fp);
206         free(data);
207
208         return err;
209 }
210
211 static int add_dir_hash(const char *file, EVP_MD_CTX *ctx)
212 {
213         int err;
214         struct dirent *de;
215         DIR *dir;
216         unsigned long long ino, off;
217         unsigned int type;
218
219         dir = opendir(file);
220         if (!dir) {
221                 log_err("Failed to open: %s\n", file);
222                 return -1;
223         }
224
225         while ((de = readdir(dir))) {
226                 ino = de->d_ino;
227                 off = de->d_off;
228                 type = de->d_type;
229                 log_debug("entry: %s, ino: %llu, type: %u, off: %llu, reclen: %hu\n",
230                           de->d_name, ino, type, off, de->d_reclen);
231                 err = EVP_DigestUpdate(ctx, de->d_name, strlen(de->d_name));
232                 /*err |= EVP_DigestUpdate(ctx, &off, sizeof(off));*/
233                 err |= EVP_DigestUpdate(ctx, &ino, sizeof(ino));
234                 err |= EVP_DigestUpdate(ctx, &type, sizeof(type));
235                 if (!err) {
236                         log_err("EVP_DigestUpdate() failed\n");
237                         return 1;
238                 }
239         }
240
241         closedir(dir);
242
243         return 0;
244 }
245
246 static int add_link_hash(const char *path, EVP_MD_CTX *ctx)
247 {
248         int err;
249         char buf[1024];
250
251         err = readlink(path, buf, sizeof(buf));
252         if (err <= 0)
253                 return -1;
254
255         log_info("link: %s -> %.*s\n", path, err, buf);
256         return !EVP_DigestUpdate(ctx, buf, err);
257 }
258
259 static int add_dev_hash(struct stat *st, EVP_MD_CTX *ctx)
260 {
261         uint32_t dev = st->st_rdev;
262         unsigned major = (dev & 0xfff00) >> 8;
263         unsigned minor = (dev & 0xff) | ((dev >> 12) & 0xfff00);
264
265         log_info("device: %u:%u\n", major, minor);
266         return !EVP_DigestUpdate(ctx, &dev, sizeof(dev));
267 }
268
269 int ima_calc_hash(const char *file, uint8_t *hash)
270 {
271         const EVP_MD *md;
272         struct stat st;
273         EVP_MD_CTX ctx;
274         unsigned int mdlen;
275         int err;
276
277         /*  Need to know the file length */
278         err = lstat(file, &st);
279         if (err < 0) {
280                 log_err("Failed to stat: %s\n", file);
281                 return err;
282         }
283
284         md = EVP_get_digestbyname(params.hash_algo);
285         if (!md) {
286                 log_err("EVP_get_digestbyname() failed\n");
287                 return 1;
288         }
289
290         err = EVP_DigestInit(&ctx, md);
291         if (!err) {
292                 log_err("EVP_DigestInit() failed\n");
293                 return 1;
294         }
295
296         switch (st.st_mode & S_IFMT) {
297         case S_IFREG:
298                 err = add_file_hash(file, &ctx);
299                 break;
300         case S_IFDIR:
301                 err = add_dir_hash(file, &ctx);
302                 break;
303         case S_IFLNK:
304                 err = add_link_hash(file, &ctx);
305                 break;
306         case S_IFIFO: case S_IFSOCK:
307         case S_IFCHR: case S_IFBLK:
308                 err = add_dev_hash(&st, &ctx);
309                 break;
310         default:
311                 log_errno("Unsupported file type");
312                 return -1;
313         }
314
315         if (err)
316                 return err;
317
318         err = EVP_DigestFinal(&ctx, hash, &mdlen);
319         if (!err) {
320                 log_err("EVP_DigestFinal() failed\n");
321                 return 1;
322         }
323
324         return mdlen;
325 }
326
327 RSA *read_pub_key(const char *keyfile, int x509)
328 {
329         FILE *fp;
330         RSA *key = NULL;
331         X509 *crt = NULL;
332         EVP_PKEY *pkey = NULL;
333
334         fp = fopen(keyfile, "r");
335         if (!fp) {
336                 log_err("Failed to open keyfile: %s\n", keyfile);
337                 return NULL;
338         }
339
340         if (x509) {
341                 crt = d2i_X509_fp(fp, NULL);
342                 if (!crt) {
343                         log_err("d2i_X509_fp() failed\n");
344                         goto out;
345                 }
346                 pkey = X509_extract_key(crt);
347                 if (!pkey) {
348                         log_err("X509_extract_key() failed\n");
349                         goto out;
350                 }
351                 key = EVP_PKEY_get1_RSA(pkey);
352         } else {
353                 key = PEM_read_RSA_PUBKEY(fp, NULL, NULL, NULL);
354         }
355
356         if (!key)
357                 log_err("PEM_read_RSA_PUBKEY() failed\n");
358
359 out:
360         if (pkey)
361                 EVP_PKEY_free(pkey);
362         if (crt)
363                 X509_free(crt);
364         fclose(fp);
365         return key;
366 }
367
368 int verify_hash_v1(const unsigned char *hash, int size, unsigned char *sig, int siglen, const char *keyfile)
369 {
370         int err, len;
371         SHA_CTX ctx;
372         unsigned char out[1024];
373         RSA *key;
374         unsigned char sighash[20];
375         struct signature_hdr *hdr = (struct signature_hdr *)sig;
376
377         log_info("hash: ");
378         log_dump(hash, size);
379
380         key = read_pub_key(keyfile, 0);
381         if (!key)
382                 return 1;
383
384         SHA1_Init(&ctx);
385         SHA1_Update(&ctx, hash, size);
386         SHA1_Update(&ctx, hdr, sizeof(*hdr));
387         SHA1_Final(sighash, &ctx);
388         log_info("sighash: ");
389         log_dump(sighash, sizeof(sighash));
390
391         err = RSA_public_decrypt(siglen - sizeof(*hdr) - 2, sig + sizeof(*hdr) + 2, out, key, RSA_PKCS1_PADDING);
392         RSA_free(key);
393         if (err < 0) {
394                 log_err("RSA_public_decrypt() failed: %d\n", err);
395                 return 1;
396         }
397
398         len = err;
399
400         if (len != sizeof(sighash) || memcmp(out, sighash, len) != 0) {
401                 log_err("Verification failed: %d\n", err);
402                 return -1;
403         } else {
404                 /*log_info("Verification is OK\n");*/
405                 printf("Verification is OK\n");
406         }
407
408         return 0;
409 }
410
411 int verify_hash_v2(const unsigned char *hash, int size, unsigned char *sig, int siglen, const char *keyfile)
412 {
413         int err, len;
414         unsigned char out[1024];
415         RSA *key;
416         struct signature_v2_hdr *hdr = (struct signature_v2_hdr *)sig;
417         const struct RSA_ASN1_template *asn1;
418
419         log_info("hash: ");
420         log_dump(hash, size);
421
422         key = read_pub_key(keyfile, 1);
423         if (!key)
424                 return 1;
425
426         err = RSA_public_decrypt(siglen - sizeof(*hdr), sig + sizeof(*hdr), out, key, RSA_PKCS1_PADDING);
427         RSA_free(key);
428         if (err < 0) {
429                 log_err("RSA_public_decrypt() failed: %d\n", err);
430                 return 1;
431         }
432
433         len = err;
434
435         asn1 = &RSA_ASN1_templates[hdr->hash_algo];
436
437         if (len < asn1->size || memcmp(out, asn1->data, asn1->size)) {
438                 log_err("Verification failed: %d\n", err);
439                 return -1;
440         }
441
442         len -= asn1->size;
443
444         if (len != size || memcmp(out + asn1->size, hash, len)) {
445                 log_err("Verification failed: %d\n", err);
446                 return -1;
447         }
448
449         /*log_info("Verification is OK\n");*/
450         printf("Verification is OK\n");
451
452         return 0;
453 }
454
455 int get_hash_algo(const char *algo)
456 {
457         int i;
458
459         for (i = 0; i < PKEY_HASH__LAST; i++)
460                 if (!strcmp(algo, pkey_hash_algo[i]))
461                         return i;
462
463         return PKEY_HASH_SHA1;
464 }
465
466 static int get_hash_algo_from_sig(unsigned char *sig)
467 {
468         uint8_t hashalgo;
469
470         if (sig[0] == 1) {
471                 hashalgo = ((struct signature_hdr *)sig)->hash;
472
473                 if (hashalgo >= DIGEST_ALGO_MAX)
474                         return -1;
475
476                 switch (hashalgo) {
477                 case DIGEST_ALGO_SHA1:
478                         return PKEY_HASH_SHA1;
479                 case DIGEST_ALGO_SHA256:
480                         return PKEY_HASH_SHA256;
481                 default:
482                         return -1;
483                 }
484         } else if (sig[0] == 2) {
485                 hashalgo = ((struct signature_v2_hdr *)sig)->hash_algo;
486                 if (hashalgo >= PKEY_HASH__LAST)
487                         return -1;
488                 return hashalgo;
489         } else
490                 return -1;
491 }
492
493 int verify_hash(const unsigned char *hash, int size, unsigned char *sig, int siglen)
494 {
495         char *key;
496         int x509;
497         verify_hash_fn_t verify_hash;
498
499         /* Get signature type from sig header */
500         if (sig[0] == DIGSIG_VERSION_1) {
501                 verify_hash = verify_hash_v1;
502                 /* Read pubkey from RSA key */
503                 x509 = 0;
504         } else if (sig[0] == DIGSIG_VERSION_2) {
505                 verify_hash = verify_hash_v2;
506                 /* Read pubkey from x509 cert */
507                 x509 = 1;
508         } else
509                 return -1;
510
511         /* Determine what key to use for verification*/
512         key = params.keyfile ? : x509 ?
513                         "/etc/keys/x509_evm.der" :
514                         "/etc/keys/pubkey_evm.pem";
515
516         return verify_hash(hash, size, sig, siglen, key);
517 }
518
519 int ima_verify_signature(const char *file, unsigned char *sig, int siglen)
520 {
521         unsigned char hash[64];
522         int hashlen, sig_hash_algo;
523
524         if (sig[0] != 0x03) {
525                 log_err("security.ima has no signature\n");
526                 return -1;
527         }
528
529         sig_hash_algo = get_hash_algo_from_sig(sig + 1);
530         if (sig_hash_algo < 0) {
531                 log_err("Invalid signature\n");
532                 return -1;
533         }
534         /* Use hash algorithm as retrieved from signature */
535         params.hash_algo = pkey_hash_algo[sig_hash_algo];
536
537         hashlen = ima_calc_hash(file, hash);
538         if (hashlen <= 1)
539                 return hashlen;
540
541         return verify_hash(hash, hashlen, sig + 1, siglen - 1);
542 }
543
544 /*
545  * Create binary key representation suitable for kernel
546  */
547 int key2bin(RSA *key, unsigned char *pub)
548 {
549         int len, b, offset = 0;
550         struct pubkey_hdr *pkh = (struct pubkey_hdr *)pub;
551
552         /* add key header */
553         pkh->version = 1;
554         pkh->timestamp = 0;     /* PEM has no timestamp?? */
555         pkh->algo = PUBKEY_ALGO_RSA;
556         pkh->nmpi = 2;
557
558         offset += sizeof(*pkh);
559
560         len = BN_num_bytes(key->n);
561         b = BN_num_bits(key->n);
562         pub[offset++] = b >> 8;
563         pub[offset++] = b & 0xff;
564         BN_bn2bin(key->n, &pub[offset]);
565         offset += len;
566
567         len = BN_num_bytes(key->e);
568         b = BN_num_bits(key->e);
569         pub[offset++] = b >> 8;
570         pub[offset++] = b & 0xff;
571         BN_bn2bin(key->e, &pub[offset]);
572         offset += len;
573
574         return offset;
575 }
576
577 void calc_keyid_v1(uint8_t *keyid, char *str, const unsigned char *pkey, int len)
578 {
579         uint8_t sha1[SHA_DIGEST_LENGTH];
580         uint64_t id;
581
582         SHA1(pkey, len, sha1);
583
584         /* sha1[12 - 19] is exactly keyid from gpg file */
585         memcpy(keyid, sha1 + 12, 8);
586         log_debug("keyid: ");
587         log_debug_dump(keyid, 8);
588
589         id = __be64_to_cpup((__be64 *) keyid);
590         sprintf(str, "%llX", (unsigned long long)id);
591         log_info("keyid: %s\n", str);
592 }
593
594 void calc_keyid_v2(uint32_t *keyid, char *str, RSA *key)
595 {
596         uint8_t sha1[SHA_DIGEST_LENGTH];
597         unsigned char *pkey = NULL;
598         int len;
599
600         len = i2d_RSAPublicKey(key, &pkey);
601
602         SHA1(pkey, len, sha1);
603
604         /* sha1[12 - 19] is exactly keyid from gpg file */
605         memcpy(keyid, sha1 + 16, 4);
606         log_debug("keyid: ");
607         log_debug_dump(keyid, 4);
608
609         sprintf(str, "%x", __be32_to_cpup(keyid));
610         log_info("keyid: %s\n", str);
611
612         free(pkey);
613 }
614
615 static RSA *read_priv_key(const char *keyfile, char *keypass)
616 {
617         FILE *fp;
618         RSA *key;
619
620         fp = fopen(keyfile, "r");
621         if (!fp) {
622                 log_err("Failed to open keyfile: %s\n", keyfile);
623                 return NULL;
624         }
625         key = PEM_read_RSAPrivateKey(fp, NULL, NULL, keypass);
626         if (!key)
627                 log_err("PEM_read_RSAPrivateKey() failed\n");
628
629         fclose(fp);
630         return key;
631 }
632
633 static int get_hash_algo_v1(const char *algo)
634 {
635
636         if (!strcmp(algo, "sha1"))
637                 return DIGEST_ALGO_SHA1;
638         else if (!strcmp(algo, "sha256"))
639                 return DIGEST_ALGO_SHA256;
640
641         return -1;
642 }
643
644 int sign_hash_v1(const char *hashalgo, const unsigned char *hash, int size, const char *keyfile, unsigned char *sig)
645 {
646         int len = -1, hashalgo_idx;
647         SHA_CTX ctx;
648         unsigned char pub[1024];
649         RSA *key;
650         char name[20];
651         unsigned char sighash[20];
652         struct signature_hdr *hdr;
653         uint16_t *blen;
654
655         if (!hash) {
656                 log_err("sign_hash_v1: hash is null\n");
657                 return -1;
658         }
659
660         if (size < 0) {
661                 log_err("sign_hash_v1: size is negative: %d\n", size);
662                 return -1;
663         }
664
665         if (!hashalgo) {
666                 log_err("sign_hash_v1: hashalgo is null\n");
667                 return -1;
668         }
669
670         if (!sig) {
671                 log_err("sign_hash_v1: sig is null\n");
672                 return -1;
673         }
674
675         log_info("hash: ");
676         log_dump(hash, size);
677
678         key = read_priv_key(keyfile, params.keypass);
679         if (!key)
680                 return -1;
681
682         hdr = (struct signature_hdr *)sig;
683
684         /* now create a new hash */
685         hdr->version = (uint8_t) DIGSIG_VERSION_1;
686         hdr->timestamp = time(NULL);
687         hdr->algo = PUBKEY_ALGO_RSA;
688         hashalgo_idx = get_hash_algo_v1(hashalgo);
689         if (hashalgo_idx < 0) {
690                 log_err("Signature version 1 does not support hash algo %s\n",
691                         hashalgo);
692                 goto out;
693         }
694         hdr->hash = (uint8_t) hashalgo_idx;
695
696         len = key2bin(key, pub);
697         calc_keyid_v1(hdr->keyid, name, pub, len);
698
699         hdr->nmpi = 1;
700
701         SHA1_Init(&ctx);
702         SHA1_Update(&ctx, hash, size);
703         SHA1_Update(&ctx, hdr, sizeof(*hdr));
704         SHA1_Final(sighash, &ctx);
705         log_info("sighash: ");
706         log_dump(sighash, sizeof(sighash));
707
708         len = RSA_private_encrypt(sizeof(sighash), sighash, sig + sizeof(*hdr) + 2, key, RSA_PKCS1_PADDING);
709         if (len < 0) {
710                 log_err("RSA_private_encrypt() failed: %d\n", len);
711                 goto out;
712         }
713
714         /* we add bit length of the signature to make it gnupg compatible */
715         blen = (uint16_t *) (sig + sizeof(*hdr));
716         *blen = __cpu_to_be16(len << 3);
717         len += sizeof(*hdr) + 2;
718         log_info("evm/ima signature: %d bytes\n", len);
719 out:
720         RSA_free(key);
721         return len;
722 }
723
724 int sign_hash_v2(const char *algo, const unsigned char *hash, int size, const char *keyfile, unsigned char *sig)
725 {
726         struct signature_v2_hdr *hdr;
727         int len = -1;
728         RSA *key;
729         char name[20];
730         unsigned char *buf;
731         const struct RSA_ASN1_template *asn1;
732
733         if (!hash) {
734                 log_err("sign_hash_v2: hash is null\n");
735                 return -1;
736         }
737
738         if (size < 0) {
739                 log_err("sign_hash_v2: size is negative: %d\n", size);
740                 return -1;
741         }
742
743         if (!sig) {
744                 log_err("sign_hash_v2: sig is null\n");
745                 return -1;
746         }
747
748         if (!algo) {
749                 log_err("sign_hash_v2: algo is null\n");
750                 return -1;
751         }
752
753         log_info("hash: ");
754         log_dump(hash, size);
755
756         key = read_priv_key(keyfile, params.keypass);
757         if (!key)
758                 return -1;
759
760         hdr = (struct signature_v2_hdr *)sig;
761         hdr->version = (uint8_t) DIGSIG_VERSION_2;
762
763         hdr->hash_algo = get_hash_algo(algo);
764
765         calc_keyid_v2(&hdr->keyid, name, key);
766
767         asn1 = &RSA_ASN1_templates[hdr->hash_algo];
768
769         buf = malloc(size + asn1->size);
770         if (!buf)
771                 goto out;
772
773         memcpy(buf, asn1->data, asn1->size);
774         memcpy(buf + asn1->size, hash, size);
775         len = RSA_private_encrypt(size + asn1->size, buf, hdr->sig,
776                                   key, RSA_PKCS1_PADDING);
777         if (len < 0) {
778                 log_err("RSA_private_encrypt() failed: %d\n", len);
779                 goto out;
780         }
781
782         /* we add bit length of the signature to make it gnupg compatible */
783         hdr->sig_size = __cpu_to_be16(len);
784         len += sizeof(*hdr);
785         log_info("evm/ima signature: %d bytes\n", len);
786 out:
787         if (buf)
788                 free(buf);
789         RSA_free(key);
790         return len;
791 }
792
793 int sign_hash(const char *hashalgo, const unsigned char *hash, int size, const char *keyfile, unsigned char *sig)
794 {
795         return params.x509 ? sign_hash_v2(hashalgo, hash, size, keyfile, sig) :
796                              sign_hash_v1(hashalgo, hash, size, keyfile, sig);
797 }
798
799 #define IMA_STATE_PATH  "/sys/kernel/security/ima/ima_state"
800 #define IMA_XATTR   "security.ima"
801
802 #define EVM_STATE_PATH  "/sys/kernel/security/evm"
803 #define EVM_XATTR   "security.evm"
804
805 #define IMA_POLICY_INTERFACE             "/sys/kernel/security/ima/policy"
806 #define IMA_POLICY_TMP_DIR               "/tmp/"
807 #define IMA_POLICY_TMP_FILE_PREFIX       "ima_"
808 #define IMA_POLICY_SIGNATRURE_EXTENSION  ".sig"
809
810 int ima_get_state(int *state)
811 {
812         int fd;
813         char buff;
814
815         if (!state) {
816                 log_err("Error input param\n");
817                 return LIB_ERROR_INPUT_PARAM;
818         }
819
820         fd = open(IMA_STATE_PATH, O_RDONLY);
821         if (fd < 0) {
822                 log_err("Unable to open file\n");
823                 return LIB_ERROR_SYSCALL;
824         }
825
826         if (read(fd, &buff, sizeof(buff)) < 0) {
827                 log_err("Unable to read file\n");
828                 close(fd);
829                 return LIB_ERROR_SYSCALL;
830         }
831
832         close(fd);
833
834         switch (buff) {
835         case '0':
836                 *state = IMA_STATE_DISABLED;
837                 return LIB_SUCCESS;
838         case '1':
839                 *state = IMA_STATE_IGNORE;
840                 return LIB_SUCCESS;
841         case '2':
842                 *state = IMA_STATE_ENFORCE;
843                 return LIB_SUCCESS;
844         case '4':
845                 *state = IMA_STATE_FIX;
846                 return LIB_SUCCESS;
847         default:
848                 log_err("Unknown IMA state\n");
849                 return LIB_ERROR_UNKNOWN;
850         }
851 }
852
853 int ima_set_state(int state)
854 {
855         char buff;
856
857         int fd = open(IMA_STATE_PATH, O_RDWR);
858         if (fd < 0) {
859                 log_err("Unable to open file\n");
860                 return LIB_ERROR_SYSCALL;
861         }
862
863         switch (state) {
864         case IMA_STATE_DISABLED:
865                 buff = '0';
866                 break;
867         case IMA_STATE_IGNORE:
868                 buff = '1';
869                 break;
870         case IMA_STATE_ENFORCE:
871                 buff = '2';
872                 break;
873         case IMA_STATE_FIX:
874                 buff = '4';
875                 break;
876         default:
877                 log_err("Wrong IMA state\n");
878                 close(fd);
879                 return LIB_ERROR_INPUT_PARAM;
880         }
881
882         if (write(fd, &buff, sizeof(buff)) < 0) {
883                 log_err("Unable to write file\n");
884                 close(fd);
885                 return LIB_ERROR_SYSCALL;
886         }
887
888         close(fd);
889         return LIB_SUCCESS;
890 }
891
892 int evm_get_state(int *state)
893 {
894         int fd;
895         char buff;
896
897         if (!state) {
898                 log_err("Error input param\n");
899                 return LIB_ERROR_INPUT_PARAM;
900         }
901
902         fd = open(EVM_STATE_PATH, O_RDONLY);
903         if (fd < 0) {
904                 log_err("Unable to open file\n");
905                 return LIB_ERROR_SYSCALL;
906         }
907
908         if (read(fd, &buff, sizeof(buff)) < 0) {
909                 log_err("Unable to read file\n");
910                 close(fd);
911                 return LIB_ERROR_SYSCALL;
912         }
913
914         close(fd);
915
916         switch (buff) {
917         case '0':
918                 *state = EVM_STATE_DISABLED;
919                 return LIB_SUCCESS;
920         case '1':
921                 *state = EVM_STATE_ENABLED;
922                 return LIB_SUCCESS;
923         case '2':
924                 *state = EVM_STATE_FIX;
925                 return LIB_SUCCESS;
926         default:
927                 log_err("Unknown EVM state\n");
928                 return LIB_ERROR_UNKNOWN;
929         }
930 }
931
932 int evm_set_state(int state)
933 {
934         char buff;
935
936         int fd = open(EVM_STATE_PATH, O_RDWR);
937         if (fd < 0) {
938                 log_err("Unable to open file\n");
939                 return LIB_ERROR_SYSCALL;
940         }
941
942         switch (state) {
943         case EVM_STATE_DISABLED:
944                 buff = '0';
945                 break;
946         case EVM_STATE_ENABLED:
947                 buff = '1';
948                 break;
949         case EVM_STATE_FIX:
950                 buff = '2';
951                 break;
952         default:
953                 log_err("Wrong EVM state\n");
954                 close(fd);
955                 return LIB_ERROR_UNKNOWN;
956         }
957
958         if (write(fd, &buff, sizeof(buff)) < 0) {
959                 log_err("Unable to write file\n");
960                 close(fd);
961                 return LIB_ERROR_SYSCALL;
962         }
963
964         close(fd);
965         return LIB_SUCCESS;
966 }
967
968 int ima_set_xattr(const char *path)
969 {
970         int ret;
971
972         if (!path) {
973                 log_err("Error input param\n");
974                 return LIB_ERROR_INPUT_PARAM;
975         }
976
977         ret = setxattr(path, IMA_XATTR, hash, strlen(hash), 0);
978         if (ret < 0) {
979                 log_err("Unable to set xattr\n");
980                 return LIB_ERROR_SYSCALL;
981         }
982
983         return LIB_SUCCESS;
984 }
985
986 int ima_get_xattr(const char *path, char **hash)
987 {
988         int ret;
989
990         if (!path || !hash) {
991                 log_err("Error input param\n");
992                 return LIB_ERROR_INPUT_PARAM;
993         }
994
995         //read xattr size only
996         ret = getxattr(path, IMA_XATTR, NULL, 0);
997         if (ret < 0) {
998                 if (errno == ENOATTR) {
999                         log_err("Missing attribute or no access\n");
1000                         return LIB_ERROR_ATTRIBUTE;
1001                 }
1002                 log_err("Error in read xattr\n");
1003                 return LIB_ERROR_SYSCALL;
1004         }
1005
1006         *hash = calloc(ret + 1, sizeof(char));
1007         if (!(*hash)) {
1008                 log_err("Allocation error\n");
1009                 return LIB_ERROR_MEMORY;
1010         }
1011
1012         ret = getxattr(path, IMA_XATTR, *hash, ret);
1013         if (ret < 0) {
1014                 if (errno == ENOATTR) {
1015                         log_err("Missing attribute or no access\n");
1016                         return LIB_ERROR_ATTRIBUTE;
1017                 }
1018                 log_err("Error in read xattr\n");
1019                 free(*hash);
1020                 return LIB_ERROR_SYSCALL;
1021         }
1022
1023         return LIB_SUCCESS;
1024 }
1025
1026 int evm_set_xattr(const char *path, const char *evm)
1027 {
1028         int ret;
1029
1030         if (!path || !evm) {
1031                 log_err("Error input param\n");
1032                 return LIB_ERROR_INPUT_PARAM;
1033         }
1034
1035         ret = setxattr(path, EVM_XATTR, evm, strlen(evm), 0);
1036         if (ret < 0) {
1037                 log_err("Unable to set xattr\n");
1038                 return LIB_ERROR_SYSCALL;
1039         }
1040
1041         return LIB_SUCCESS;
1042 }
1043
1044 int evm_get_xattr(const char *path, char **hash)
1045 {
1046         int ret;
1047
1048         if (!path || !hash) {
1049                 log_err("Error input param\n");
1050                 return LIB_ERROR_INPUT_PARAM;
1051         }
1052
1053         //read xattr size only
1054         ret = getxattr(path, EVM_XATTR, NULL, 0);
1055         if (ret < 0) {
1056                 if (errno == ENOATTR) {
1057                         log_err("Missing attribute or no access\n");
1058                         return LIB_ERROR_ATTRIBUTE;
1059                 }
1060                 log_err("Error in read xattr\n");
1061                 return LIB_ERROR_SYSCALL;
1062         }
1063
1064         *hash = calloc(ret + 1, sizeof(char));
1065         if (!(*hash)) {
1066                 log_err("Allocation error\n");
1067                 return LIB_ERROR_MEMORY;
1068         }
1069
1070         ret = getxattr(path, EVM_XATTR, *hash, ret);
1071         if (ret < 0) {
1072                 if (errno == ENOATTR) {
1073                         log_err("Missing attribute or no access\n");
1074                         return LIB_ERROR_ATTRIBUTE;
1075                 }
1076                 log_err("Error in read xattr\n");
1077                 free(*hash);
1078                 return LIB_ERROR_SYSCALL;
1079         }
1080
1081         return LIB_SUCCESS;
1082 }
1083
1084 int ima_get_policy(char*** policy)
1085 {
1086         char buff[100];
1087         char *policy_tmp = NULL;
1088         char *last;
1089         char *last2;
1090         int length = 0;
1091         int rules_count;
1092         int ret;
1093         int ret_code = LIB_SUCCESS;
1094         int i;
1095
1096         if (!policy)
1097                 return LIB_ERROR_INPUT_PARAM;
1098
1099         int fd = open(IMA_POLICY_INTERFACE, O_RDONLY);
1100         if (fd < 0) {
1101                 log_err("Unable to open %s file\n", IMA_POLICY_INTERFACE);
1102                 return LIB_ERROR_SYSCALL;
1103         }
1104
1105         // Read policy from fd to policy_tmp;
1106         do {
1107                 ret = read(fd, &buff, sizeof(buff));
1108                 if (ret < 0) {
1109                         log_err("Unable to read %s file\n", IMA_POLICY_INTERFACE);
1110                         ret_code = LIB_ERROR_SYSCALL;
1111                         goto out;
1112                 }
1113                 last = realloc(policy_tmp, length + ret + 1);
1114                 if (!last) { // realloc error
1115                         ret_code = LIB_ERROR_MEMORY;
1116                         goto out;
1117                 }
1118                 policy_tmp = last;
1119                 memcpy(&(policy_tmp[length]), buff, ret);
1120                 length += ret;
1121         } while (ret == (int) sizeof(buff)); // If not whole buffer was filled then it means that the
1122                                              // whole policy was read. Exit the while loop.
1123         policy_tmp[length] = '\0';
1124
1125         if (length <= 1) { // Empty policy;
1126                 *policy = malloc(sizeof(char*));
1127                 if (!(*policy)) {
1128                         ret_code = LIB_ERROR_MEMORY;
1129                         goto out;
1130                 }
1131                 (*policy)[0] = NULL;
1132                 goto out;
1133         }
1134
1135         // Counting rules
1136         last = policy_tmp;
1137         rules_count = 1; // Start counting from 1 because there can be one more rule then new line sign
1138         while ((last = strchr(last, '\n'))) {
1139                 last += sizeof(char);
1140                 rules_count++;
1141         }
1142
1143         *policy = malloc(sizeof(char*) * (rules_count + 1)); // +1 because this is null terminated list
1144         if (!(*policy)) {
1145                 ret_code = LIB_ERROR_MEMORY;
1146                 goto out;
1147         }
1148         (*policy)[rules_count] = NULL;
1149         last = policy_tmp;
1150
1151         // Re-write rules as a list of strings - every rule in different string.
1152         for (i = 0; i < rules_count; ++i) {
1153                 last2 = strchr(last, '\n');
1154                 if (last2) {
1155                         (*policy)[i] = malloc(sizeof(char*) * (last2 - last) + 1);
1156                         if (!((*policy)[i])) {
1157                                 for (; i >= 0; --i)
1158                                         free((*policy)[i]);
1159                                 free(*policy);
1160                                 *policy = NULL;
1161                                 ret_code = LIB_ERROR_MEMORY;
1162                                 goto out;
1163                         }
1164                         memcpy((*policy)[i], last, (last2 - last));
1165                         (*policy)[i][last2 - last] = '\0';
1166                 } else { // This should be the last run of FOR loop
1167                         (*policy)[i] = malloc(sizeof(char*) * strlen(last) + 1);
1168                         if (!((*policy)[i])) {
1169                                 for (; i >= 0; --i)
1170                                         free((*policy)[i]);
1171                                 free(*policy);
1172                                 *policy = NULL;
1173                                 ret_code = LIB_ERROR_MEMORY;
1174                                 goto out;
1175                         }
1176                         memcpy((*policy)[i], last, strlen(last));
1177                         (*policy)[i][strlen(last)] = '\0';
1178                 }
1179                 last = last2 + sizeof(char);
1180         }
1181
1182 out:
1183         close(fd);
1184         free(policy_tmp);
1185         return ret_code;
1186 }
1187
1188 int ima_free_policy(char **policy)
1189 {
1190         int i = 0;
1191
1192         if (!policy)
1193                 return LIB_ERROR_INPUT_PARAM;
1194
1195         while (policy[i]) {
1196                 free(policy[i]);
1197                 policy[i] = NULL;
1198                 ++i;
1199         }
1200         free(policy);
1201
1202         return LIB_SUCCESS;
1203 }
1204
1205 static int _ima_write_rule(int fd, const char *rule)
1206 {
1207         int counter = 0;
1208         int ret;
1209
1210         if (fd < 0)
1211                 return LIB_ERROR_SYSCALL;
1212         if (!rule)
1213                 return LIB_SUCCESS;
1214
1215         int len = strlen(rule);
1216
1217         /* writing rule */
1218         while (counter < len) {
1219                 ret = write(fd, &(rule[counter]), len-counter);
1220                 if (ret < 0) { /* Write error. Return with error code */
1221                         return LIB_ERROR_SYSCALL;
1222                 }
1223                 counter += ret;
1224         }
1225
1226         /* writing new line sign */
1227         do {
1228                 ret = write(fd, "\n", sizeof("\n"));
1229                 if (ret < 0)
1230                         return LIB_ERROR_SYSCALL;
1231         } while (!ret);
1232         if (ret != sizeof("\n"))
1233                 return LIB_ERROR_SYSCALL;
1234
1235         return LIB_SUCCESS;
1236 }
1237
1238 int ima_set_policy_file(const char *policy_path)
1239 {
1240         int ret_code = LIB_SUCCESS;
1241         int counter;
1242         int len;
1243         int ret;
1244         int fd = -1;
1245
1246         if (!policy_path || policy_path[0] == '\0')
1247                 return LIB_ERROR_INPUT_PARAM;
1248
1249         /* open and write to kernel interface */
1250         fd = open(IMA_POLICY_INTERFACE, O_WRONLY);
1251         if (fd < 0) {
1252                 log_err("Cannot open kernel interface\n");
1253                 ret_code = LIB_ERROR_SYSCALL;
1254                 goto out;
1255         }
1256
1257         counter = 0;
1258         len = strlen(policy_path);
1259         while (counter < len) {
1260                 ret = write(fd, &(policy_path[counter]), len - counter);
1261                 if (ret < 0) {
1262                         log_err("Error while writing to the kernel interface (%s)\n", strerror(errno));
1263                         ret_code = LIB_ERROR_SYSCALL;
1264                         goto out;
1265                 }
1266                 counter += ret;
1267         }
1268
1269 out:
1270         if (fd > -1)
1271                 close(fd);
1272         return ret_code;
1273 }
1274
1275 int ima_set_policy(const char **policy, const char *policy_sig)
1276 {
1277         int ret_code = LIB_SUCCESS;
1278         char *policy_file_name = NULL;
1279         char *sig_file_name = NULL;
1280         int fd_policy = -1;
1281         int fd_sig = -1;
1282         int fd = -1;
1283         int i, counter, len;
1284         int ret;
1285
1286         if (!policy || !policy_sig) {
1287                 log_err("Error input param\n");
1288                 return LIB_ERROR_INPUT_PARAM;
1289         }
1290
1291         /* Generate random filename */
1292         policy_file_name = tempnam(IMA_POLICY_TMP_DIR, IMA_POLICY_TMP_FILE_PREFIX);
1293         if (!policy_file_name) {
1294                 log_err("Cannot generate unique file name\n");
1295                 return LIB_ERROR_SYSCALL;
1296         }
1297
1298         /* write policy to temporary file */
1299         /* We need to be sure that we create a new file. */
1300         /* No one should have any right to this file - except write for us */
1301         fd_policy = open(policy_file_name, O_WRONLY | O_CREAT | O_EXCL, S_IWUSR);
1302         if (fd_policy < 0) {
1303                 log_err("Cannot open policy temporary file\n");
1304                 ret_code = LIB_ERROR_SYSCALL;
1305                 goto out;
1306         }
1307
1308         i = 0;
1309         while (policy[i]) {
1310                 ret = _ima_write_rule(fd_policy, policy[i]);
1311                 if (ret != LIB_SUCCESS) {
1312                         log_err("Error while writing policy rule to temporary file\n");
1313                         ret_code = ret;
1314                         goto out;
1315                 }
1316                 ++i;
1317         }
1318         /* We keep this file locked */
1319
1320         /* generate signature file name */
1321         sig_file_name = malloc(sizeof(char) * (strlen(policy_file_name) + sizeof(IMA_POLICY_SIGNATRURE_EXTENSION) + 1));
1322         if (!sig_file_name) {
1323                 ret_code = LIB_ERROR_MEMORY;
1324                 goto out;
1325         }
1326         len = strlen(policy_file_name);
1327         memcpy(sig_file_name, policy_file_name, len);
1328         memcpy(&(sig_file_name[len]),
1329                         IMA_POLICY_SIGNATRURE_EXTENSION,
1330                         sizeof(IMA_POLICY_SIGNATRURE_EXTENSION));
1331         sig_file_name[len + sizeof(IMA_POLICY_SIGNATRURE_EXTENSION)] = '\0';
1332
1333         /* write signature to temporary file - the same conditions as for the policy file */
1334         fd_sig = open(sig_file_name, O_WRONLY | O_CREAT | O_EXCL, S_IWUSR);
1335         if (fd_sig < 0) {
1336                 log_err("Cannot open signature temporary file\n");
1337                 ret_code = LIB_ERROR_SYSCALL;
1338                 goto out;
1339         }
1340
1341         counter = 0;
1342         len = strlen(policy_sig);
1343         while (counter < len) {
1344                 ret = write(fd_sig, &(policy_sig[counter]), len-counter);
1345                 if (ret < 0) {
1346                         log_err("Error while writing signature to temporary file\n");
1347                         ret_code = LIB_ERROR_SYSCALL;
1348                         goto out;
1349                 }
1350                 counter += ret;
1351         }
1352
1353         /* unlocked policy and signature file */
1354         if (fd_policy > -1)
1355                 close(fd_policy);
1356         if (fd_sig > -1)
1357                 close(fd_sig);
1358
1359         /* open and write to kernel interface */
1360         fd = open(IMA_POLICY_INTERFACE, O_WRONLY);
1361         if (fd < 0) {
1362                 log_err("Cannot open kernel interface\n");
1363                 ret_code = LIB_ERROR_SYSCALL;
1364                 goto out;
1365         }
1366
1367         counter = 0;
1368         len = strlen(policy_file_name);
1369         while (counter < len) {
1370                 ret = write(fd, &(policy_file_name[counter]), len-counter);
1371                 if (ret < 0) {
1372                         log_err("Error while writing to the kernel interface\n");
1373                         ret_code = LIB_ERROR_SYSCALL;
1374                         goto out;
1375                 }
1376                 counter += ret;
1377         }
1378
1379 out:
1380         if (fd_policy > -1)
1381                 close(fd_policy);
1382         if (fd_sig > -1)
1383                 close(fd_sig);
1384         if (fd > -1)
1385                 close(fd);
1386         if (policy_file_name) {
1387                 unlink(policy_file_name);
1388                 free(policy_file_name);
1389         }
1390         if (sig_file_name) {
1391                 unlink(sig_file_name);
1392                 free(sig_file_name);
1393         }
1394         return ret_code;
1395 }
1396
1397 #define IMA_MEASURE_PATH        "/sys/kernel/security/ima/ascii_runtime_measurements"
1398 #define IMA_TAMPERED_STATE      0x0001
1399
1400  int get_file_state(const char *path, int *state)
1401 {
1402         char line[256];
1403         FILE *fp;
1404         char *fileState = NULL;
1405         char *token = NULL;
1406         int found = 0;
1407         *state = FILE_STATE_UNKNOWN;
1408
1409         if (!path || !state) {
1410                 log_err("Error input param\n");
1411                 return LIB_ERROR_INPUT_PARAM;
1412         }
1413
1414         fp = fopen(path, "r");
1415         if (NULL == fp) {
1416                 if (errno != EACCES && errno != EPERM) {
1417                         *state = FILE_STATE_UNKNOWN;
1418                         goto out;
1419                 }
1420                 fp = fopen(IMA_MEASURE_PATH, "r");
1421                 if (NULL == fp) {
1422                         log_err("Unable to open file\n");
1423                         return LIB_ERROR_SYSCALL;
1424                 }
1425                 while (fgets(line, sizeof line, fp) != NULL) {
1426                         token = strtok(line, " ");
1427                         while ((token = strtok(NULL, " "))) {
1428                                 if (!strcmp(path, token)) {
1429                                         found = 1;
1430                                         break;
1431                                 }
1432                         }
1433                         if (found) {
1434                                 token = strtok(NULL, " ");
1435                                 while (NULL != token) {
1436                                         fileState = token;
1437                                         token = strtok(NULL, " ");
1438                                 }
1439                                 if (atoi(fileState) & IMA_TAMPERED_STATE) {
1440                                         *state = FILE_STATE_TAMPERED;
1441                                         goto out;
1442                                 }
1443                         }
1444                 }
1445         }
1446         else
1447                 *state = FILE_STATE_OK;
1448
1449 out:
1450         if (fp)
1451                 fclose(fp);
1452         return LIB_SUCCESS;
1453 }