Use --m32 and --m64 parameters also in HMAC signing code
[platform/upstream/ima-evm-utils.git] / src / evmctl.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  *
13  * This program is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU General Public License
15  * version 2 as published by the Free Software Foundation.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
24  *
25  * File: evmctl.c
26  *       IMA/EVM control program
27  */
28
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <sys/ioctl.h>
32 #include <sys/param.h>
33 #include <fcntl.h>
34 #include <unistd.h>
35 #include <stdlib.h>
36 #include <stdio.h>
37 #include <stdint.h>
38 #include <string.h>
39 #include <attr/xattr.h>
40 #include <getopt.h>
41 #include <signal.h>
42 #include <keyutils.h>
43 #include <asm/byteorder.h>
44 #include <ctype.h>
45
46 #define USE_FPRINTF
47
48 #include <libevm.h>
49
50 static char *evm_config_xattrnames[] = {
51         "security.selinux",
52         "security.SMACK64",
53         "security.ima",
54         "security.capability",
55         NULL
56 };
57
58 struct command {
59         char *name;
60         int (*func)(struct command *cmd);
61         int cmd;
62         char *arg;
63         char *msg;              /* extra info message */
64 };
65
66 static int g_argc;
67 static char **g_argv;
68 static int xattr = 1;
69 static int sigdump;
70 static int digest;
71 static int digsig;
72 static char *keypass;
73 static int sigfile;
74 static int x509 = 1;
75 static char *uuid_str = "+";
76 static char *search_type;
77 static int recursive;
78 static int msize;
79 static dev_t fs_dev;
80
81 typedef int (*find_cb_t)(const char *path);
82 static int find(const char *path, int dts, find_cb_t func);
83
84 #define REG_MASK        (1 << DT_REG)
85 #define DIR_MASK        (1 << DT_DIR)
86 #define LNK_MASK        (1 << DT_LNK)
87 #define CHR_MASK        (1 << DT_CHR)
88 #define BLK_MASK        (1 << DT_BLK)
89
90 typedef int (*sign_hash_fn_t)(const char *algo, const unsigned char *hash, int size, const char *keyfile, unsigned char *sig);
91
92 static sign_hash_fn_t sign_hash;
93
94 struct command cmds[];
95 static void print_usage(struct command *cmd);
96
97 static int bin2file(const char *file, const char *ext, const unsigned char *data, int len)
98 {
99         FILE *fp;
100         char name[strlen(file) + (ext ? strlen(ext) : 0) + 2];
101         int err;
102
103         if (ext)
104                 sprintf(name, "%s.%s", file, ext);
105         else
106                 sprintf(name, "%s", file);
107
108         log_info("Writing to %s\n", name);
109
110         fp = fopen(name, "w");
111         if (!fp) {
112                 log_err("Unable to open %s for writing\n", name);
113                 return -1;
114         }
115         err = fwrite(data, len, 1, fp);
116         fclose(fp);
117         return err;
118 }
119
120 static unsigned char *file2bin(const char *file, const char *ext, int *size)
121 {
122         FILE *fp;
123         int len;
124         unsigned char *data;
125         char name[strlen(file) + (ext ? strlen(ext) : 0) + 2];
126
127         if (ext)
128                 sprintf(name, "%s.%s", file, ext);
129         else
130                 sprintf(name, "%s", file);
131
132         log_info("Reading to %s\n", name);
133
134         len = get_filesize(name);
135         fp = fopen(name, "r");
136         if (!fp) {
137                 log_err("Unable to open %s\n", name);
138                 return NULL;
139         }
140         data = malloc(len);
141         if (!fread(data, len, 1, fp))
142                 len = 0;
143         fclose(fp);
144
145         *size = len;
146         return data;
147 }
148
149 /*
150  * Create binary key representation suitable for kernel
151  */
152 static int key2bin(RSA *key, unsigned char *pub)
153 {
154         int len, b, offset = 0;
155         struct pubkey_hdr *pkh = (struct pubkey_hdr *)pub;
156
157         /* add key header */
158         pkh->version = 1;
159         pkh->timestamp = 0;     /* PEM has no timestamp?? */
160         pkh->algo = PUBKEY_ALGO_RSA;
161         pkh->nmpi = 2;
162
163         offset += sizeof(*pkh);
164
165         len = BN_num_bytes(key->n);
166         b = BN_num_bits(key->n);
167         pub[offset++] = b >> 8;
168         pub[offset++] = b & 0xff;
169         BN_bn2bin(key->n, &pub[offset]);
170         offset += len;
171
172         len = BN_num_bytes(key->e);
173         b = BN_num_bits(key->e);
174         pub[offset++] = b >> 8;
175         pub[offset++] = b & 0xff;
176         BN_bn2bin(key->e, &pub[offset]);
177         offset += len;
178
179         return offset;
180 }
181
182 static void calc_keyid_v1(uint8_t *keyid, char *str, const unsigned char *pkey, int len)
183 {
184         uint8_t sha1[SHA_DIGEST_LENGTH];
185         uint64_t id;
186
187         SHA1(pkey, len, sha1);
188
189         /* sha1[12 - 19] is exactly keyid from gpg file */
190         memcpy(keyid, sha1 + 12, 8);
191         log_debug("keyid: ");
192         log_debug_dump(keyid, 8);
193
194         id = __be64_to_cpup((__be64 *) keyid);
195         sprintf(str, "%llX", (unsigned long long)id);
196         log_info("keyid: %s\n", str);
197 }
198
199 static void calc_keyid_v2(uint32_t *keyid, char *str, RSA *key)
200 {
201         uint8_t sha1[SHA_DIGEST_LENGTH];
202         unsigned char *pkey = NULL;
203         int len;
204
205         len = i2d_RSAPublicKey(key, &pkey);
206
207         SHA1(pkey, len, sha1);
208
209         /* sha1[12 - 19] is exactly keyid from gpg file */
210         memcpy(keyid, sha1 + 16, 4);
211         log_debug("keyid: ");
212         log_debug_dump(keyid, 4);
213
214         sprintf(str, "%x", __be32_to_cpup(keyid));
215         log_info("keyid: %s\n", str);
216
217         free(pkey);
218 }
219
220 static RSA *read_priv_key(const char *keyfile)
221 {
222         FILE *fp;
223         RSA *key;
224
225         fp = fopen(keyfile, "r");
226         if (!fp) {
227                 log_err("Unable to open keyfile %s\n", keyfile);
228                 return NULL;
229         }
230         key = PEM_read_RSAPrivateKey(fp, NULL, NULL, keypass);
231         if (!key)
232                 log_err("PEM_read_RSAPrivateKey() failed\n");
233
234         fclose(fp);
235         return key;
236 }
237
238 static int get_hash_algo_v1(const char *algo)
239 {
240
241         if (!strcmp(algo, "sha1"))
242                 return DIGEST_ALGO_SHA1;
243         else if (!strcmp(algo, "sha256"))
244                 return DIGEST_ALGO_SHA256;
245
246         return -1;
247 }
248
249 static int sign_hash_v1(const char *hashalgo, const unsigned char *hash, int size, const char *keyfile, unsigned char *sig)
250 {
251         int len = -1, hashalgo_idx;
252         SHA_CTX ctx;
253         unsigned char pub[1024];
254         RSA *key;
255         char name[20];
256         unsigned char sighash[20];
257         struct signature_hdr *hdr = (struct signature_hdr *)sig;
258         uint16_t *blen;
259
260         log_info("hash: ");
261         log_dump(hash, size);
262
263         key = read_priv_key(keyfile);
264         if (!key)
265                 return -1;
266
267         /* now create a new hash */
268         hdr->version = (uint8_t) DIGSIG_VERSION_1;
269         hdr->timestamp = time(NULL);
270         hdr->algo = PUBKEY_ALGO_RSA;
271         hashalgo_idx = get_hash_algo_v1(hashalgo);
272         if (hashalgo_idx < 0) {
273                 log_err("Signature version 1 does not support hash algo %s\n",
274                         hashalgo);
275                 goto out;
276         }
277         hdr->hash = (uint8_t) hashalgo_idx;
278
279         len = key2bin(key, pub);
280         calc_keyid_v1(hdr->keyid, name, pub, len);
281
282         hdr->nmpi = 1;
283
284         SHA1_Init(&ctx);
285         SHA1_Update(&ctx, hash, size);
286         SHA1_Update(&ctx, hdr, sizeof(*hdr));
287         SHA1_Final(sighash, &ctx);
288         log_info("sighash: ");
289         log_dump(sighash, sizeof(sighash));
290
291         len = RSA_private_encrypt(sizeof(sighash), sighash, sig + sizeof(*hdr) + 2, key, RSA_PKCS1_PADDING);
292         if (len < 0) {
293                 log_err("RSA_private_encrypt() failed: %d\n", len);
294                 goto out;
295         }
296
297         /* we add bit length of the signature to make it gnupg compatible */
298         blen = (uint16_t *) (sig + sizeof(*hdr));
299         *blen = __cpu_to_be16(len << 3);
300         len += sizeof(*hdr) + 2;
301         log_info("evm/ima signature: %d bytes\n", len);
302         if (sigdump || params.verbose >= LOG_INFO)
303                 dump(sig, len);
304 out:
305         RSA_free(key);
306         return len;
307 }
308
309 static int sign_hash_v2(const char *algo, const unsigned char *hash, int size, const char *keyfile, unsigned char *sig)
310 {
311         struct signature_v2_hdr *hdr = (struct signature_v2_hdr *)sig;
312         int len = -1;
313         RSA *key;
314         char name[20];
315         unsigned char *buf;
316         const struct RSA_ASN1_template *asn1;
317
318         log_info("hash: ");
319         log_dump(hash, size);
320
321         key = read_priv_key(keyfile);
322         if (!key)
323                 return -1;
324
325         hdr->version = (uint8_t) DIGSIG_VERSION_2;
326         hdr->hash_algo = get_hash_algo(algo);
327
328         calc_keyid_v2(&hdr->keyid, name, key);
329
330         asn1 = &RSA_ASN1_templates[hdr->hash_algo];
331
332         buf = malloc(size + asn1->size);
333         if (!buf)
334                 goto out;
335
336         memcpy(buf, asn1->data, asn1->size);
337         memcpy(buf + asn1->size, hash, size);
338         len = RSA_private_encrypt(size + asn1->size, buf, hdr->sig,
339                                   key, RSA_PKCS1_PADDING);
340         if (len < 0) {
341                 log_err("RSA_private_encrypt() failed: %d\n", len);
342                 goto out;
343         }
344
345         /* we add bit length of the signature to make it gnupg compatible */
346         hdr->sig_size = __cpu_to_be16(len);
347         len += sizeof(*hdr);
348         log_info("evm/ima signature: %d bytes\n", len);
349         if (sigdump || params.verbose >= LOG_INFO)
350                 dump(sig, len);
351 out:
352         if (buf)
353                 free(buf);
354         RSA_free(key);
355         return len;
356 }
357
358 static int find_xattr(const char *list, int list_size, const char *xattr)
359 {
360         int len;
361
362         for (; list_size > 0; len++, list_size -= len, list += len) {
363                 len = strlen(list);
364                 if (!strcmp(list, xattr))
365                         return 1;
366         }
367         return 0;
368 }
369
370 static int hex_to_bin(char ch)
371 {
372         if ((ch >= '0') && (ch <= '9'))
373                 return ch - '0';
374         ch = tolower(ch);
375         if ((ch >= 'a') && (ch <= 'f'))
376                 return ch - 'a' + 10;
377         return -1;
378 }
379
380 static int hex2bin(uint8_t *dst, const char *src, size_t count)
381 {
382         int hi, lo;
383
384         while (count--) {
385                 if (*src == ' ')
386                         src++;
387
388                 hi = hex_to_bin(*src++);
389                 lo = hex_to_bin(*src++);
390
391                 if ((hi < 0) || (lo < 0))
392                         return -1;
393
394                 *dst++ = (hi << 4) | lo;
395         }
396         return 0;
397 }
398
399 static int pack_uuid(const char *uuid_str, char *uuid)
400 {
401         int i;
402         char *to = uuid;
403
404         for (i = 0; i < 16; ++i) {
405                 if (!uuid_str[0] || !uuid_str[1]) {
406                         log_err("wrong UUID format\n");
407                         return -1;
408                 }
409                 *to++ = (hex_to_bin(*uuid_str) << 4) |
410                         (hex_to_bin(*(uuid_str + 1)));
411                 uuid_str += 2;
412                 switch (i) {
413                 case 3:
414                 case 5:
415                 case 7:
416                 case 9:
417                         if (*uuid_str != '-') {
418                                 log_err("wrong UUID format\n");
419                                 return -1;
420                         }
421                         uuid_str++;
422                         continue;
423                 }
424         }
425         log_info("uuid: ");
426         log_dump(uuid, 16);
427         return 0;
428 }
429
430 static int get_uuid(struct stat *st, char *uuid)
431 {
432         uint32_t dev;
433         unsigned minor, major;
434         char path[PATH_MAX], _uuid[37];
435         FILE *fp;
436         size_t len;
437
438         if (uuid_str[0] != '+')
439                 return pack_uuid(uuid_str, uuid);
440
441         dev = st->st_dev;
442         major = (dev & 0xfff00) >> 8;
443         minor = (dev & 0xff) | ((dev >> 12) & 0xfff00);
444
445         log_debug("dev: %u:%u\n", major, minor);
446         sprintf(path, "blkid -s UUID -o value /dev/block/%u:%u", major, minor);
447
448         fp = popen(path, "r");
449         if (!fp) {
450                 log_err("popen() failed\n");
451                 return -1;
452         }
453
454         len = fread(_uuid, 1, sizeof(_uuid), fp);
455         pclose(fp);
456         if (len != sizeof(_uuid)) {
457                 log_err("fread() failed\n");
458                 return -1;
459         }
460
461         return pack_uuid(_uuid, uuid);
462 }
463
464 static int calc_evm_hash(const char *file, unsigned char *hash)
465 {
466         struct stat st;
467         int err;
468         uint32_t generation = 0;
469         EVP_MD_CTX ctx;
470         unsigned int mdlen;
471         char **xattrname;
472         char xattr_value[1024];
473         char list[1024];
474         ssize_t list_size;
475         char uuid[16];
476         struct h_misc_64 hmac_misc;
477         int hmac_size;
478
479         if (lstat(file, &st)) {
480                 log_err("lstat() failed\n");
481                 return -1;
482         }
483
484         if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode)) {
485                 /* we cannot at the momement to get generation of special files..
486                  * kernel API does not support it */
487                 int fd = open(file, 0);
488                 if (fd < 0) {
489                         log_err("Unable to open %s\n", file);
490                         return -1;
491                 }
492                 if (ioctl(fd, EXT34_IOC_GETVERSION, &generation)) {
493                         log_err("ioctl() failed\n");
494                         return -1;
495                 }
496                 close(fd);
497         }
498
499         log_info("generation: %u\n", generation);
500
501         list_size = llistxattr(file, list, sizeof(list));
502         if (list_size < 0) {
503                 log_err("llistxattr() failed\n");
504                 return -1;
505         }
506
507         err = EVP_DigestInit(&ctx, EVP_sha1());
508         if (!err) {
509                 log_err("EVP_DigestInit() failed\n");
510                 return 1;
511         }
512
513         for (xattrname = evm_config_xattrnames; *xattrname != NULL; xattrname++) {
514                 err = lgetxattr(file, *xattrname, xattr_value, sizeof(xattr_value));
515                 if (err < 0) {
516                         log_info("no xattr: %s\n", *xattrname);
517                         continue;
518                 }
519                 if (!find_xattr(list, list_size, *xattrname)) {
520                         log_info("skipping xattr: %s\n", *xattrname);
521                         continue;
522                 }
523                 /*log_debug("name: %s, value: %s, size: %d\n", *xattrname, xattr_value, err);*/
524                 log_info("name: %s, size: %d\n", *xattrname, err);
525                 log_debug_dump(xattr_value, err);
526                 err = EVP_DigestUpdate(&ctx, xattr_value, err);
527                 if (!err) {
528                         log_err("EVP_DigestUpdate() failed\n");
529                         return 1;
530                 }
531         }
532
533         memset(&hmac_misc, 0, sizeof(hmac_misc));
534
535         if (msize == 0) {
536                 struct h_misc *hmac = (struct h_misc *)&hmac_misc;
537                 hmac_size = sizeof(*hmac);
538                 hmac->ino = st.st_ino;
539                 hmac->generation = generation;
540                 hmac->uid = st.st_uid;
541                 hmac->gid = st.st_gid;
542                 hmac->mode = st.st_mode;
543         } else if (msize == 64) {
544                 struct h_misc_64 *hmac = (struct h_misc_64 *)&hmac_misc;
545                 hmac_size = sizeof(*hmac);
546                 hmac->ino = st.st_ino;
547                 hmac->generation = generation;
548                 hmac->uid = st.st_uid;
549                 hmac->gid = st.st_gid;
550                 hmac->mode = st.st_mode;
551         } else {
552                 struct h_misc_32 *hmac = (struct h_misc_32 *)&hmac_misc;
553                 hmac_size = sizeof(*hmac);
554                 hmac->ino = st.st_ino;
555                 hmac->generation = generation;
556                 hmac->uid = st.st_uid;
557                 hmac->gid = st.st_gid;
558                 hmac->mode = st.st_mode;
559         }
560
561         log_debug("hmac_misc (%d): ", hmac_size);
562         log_debug_dump(&hmac_misc, hmac_size);
563
564         err = EVP_DigestUpdate(&ctx, &hmac_misc, hmac_size);
565         if (!err) {
566                 log_err("EVP_DigestUpdate() failed\n");
567                 return 1;
568         }
569
570         if (*uuid_str != '-') {
571                 err = get_uuid(&st, uuid);
572                 if (err)
573                         return -1;
574
575                 err = EVP_DigestUpdate(&ctx, (const unsigned char *)uuid, sizeof(uuid));
576                 if (!err) {
577                         log_err("EVP_DigestUpdate() failed\n");
578                         return 1;
579                 }
580         }
581
582         err = EVP_DigestFinal(&ctx, hash, &mdlen);
583         if (!err) {
584                 log_err("EVP_DigestFinal() failed\n");
585                 return 1;
586         }
587
588         return mdlen;
589 }
590
591 static int sign_evm(const char *file, const char *key)
592 {
593         unsigned char hash[20];
594         unsigned char sig[1024] = "\x03";
595         int len, err;
596
597         len = calc_evm_hash(file, hash);
598         if (len <= 1)
599                 return len;
600
601         len = sign_hash("sha1", hash, len, key, sig + 1);
602         if (len <= 1)
603                 return len;
604
605         if (xattr) {
606                 err = lsetxattr(file, "security.evm", sig, len + 1, 0);
607                 if (err < 0) {
608                         log_err("setxattr failed: %s\n", file);
609                         return err;
610                 }
611         }
612
613         return 0;
614 }
615
616 static int hash_ima(const char *file)
617 {
618         unsigned char hash[65] = "\x01"; /* MAX hash size + 1 */
619         int len, err;
620
621         len = ima_calc_hash(file, hash + 1);
622         if (len <= 1)
623                 return len;
624
625         if (params.verbose >= LOG_INFO)
626                 log_info("hash: ");
627
628         if (sigdump || params.verbose >= LOG_INFO)
629                 dump(hash, len + 1);
630
631         if (xattr) {
632                 err = lsetxattr(file, "security.ima", hash, len + 1, 0);
633                 if (err < 0) {
634                         log_err("setxattr failed: %s\n", file);
635                         return err;
636                 }
637         }
638
639         return 0;
640 }
641
642 static int cmd_hash_ima(struct command *cmd)
643 {
644         char *file = g_argv[optind++];
645
646         if (!file) {
647                 log_err("Parameters missing\n");
648                 print_usage(cmd);
649                 return -1;
650         }
651
652         return hash_ima(file);
653 }
654
655 static int sign_ima(const char *file, const char *key)
656 {
657         unsigned char hash[64];
658         unsigned char sig[1024] = "\x03";
659         int len, err;
660
661         len = ima_calc_hash(file, hash);
662         if (len <= 1)
663                 return len;
664
665         len = sign_hash(params.hash_algo, hash, len, key, sig + 1);
666         if (len <= 1)
667                 return len;
668
669         /* add header */
670         len++;
671
672         if (sigfile)
673                 bin2file(file, "sig", sig, len);
674
675         if (xattr) {
676                 err = lsetxattr(file, "security.ima", sig, len, 0);
677                 if (err < 0) {
678                         log_err("setxattr failed: %s\n", file);
679                         return err;
680                 }
681         }
682
683         return 0;
684 }
685
686 static int get_file_type(const char *path, const char *search_type)
687 {
688         int err, dts = 0, i;
689         struct stat st;
690
691         for (i = 0; search_type[i]; i++) {
692                 switch (search_type[i]) {
693                 case 'f':
694                         dts |= REG_MASK; break;
695                 case 'd':
696                         dts |= DIR_MASK; break;
697                 case 's':
698                         dts |= BLK_MASK | CHR_MASK | LNK_MASK; break;
699                 case 'm':
700                         /* stay within the same filesystem*/
701                         err = lstat(path, &st);
702                         if (err < 0) {
703                                 log_err("stat() failed\n");
704                                 return err;
705                         }
706                         fs_dev = st.st_dev; /* filesystem to start from */
707                         break;
708                 }
709         }
710
711         return dts;
712 }
713
714 static int sign_ima_file(const char *file)
715 {
716         char *key;
717
718         key = params.keyfile ? : "/etc/keys/privkey_evm.pem";
719
720         return sign_ima(file, key);
721 }
722
723 static int cmd_sign_ima(struct command *cmd)
724 {
725         char *file = g_argv[optind++];
726         int err, dts = REG_MASK; /* only regular files by default */
727
728         if (!file) {
729                 log_err("Parameters missing\n");
730                 print_usage(cmd);
731                 return -1;
732         }
733
734         if (recursive) {
735                 if (search_type) {
736                         dts = get_file_type(file, search_type);
737                         if (dts < 0)
738                                 return dts;
739                 }
740                 err = find(file, dts, sign_ima_file);
741         } else {
742                 err = sign_ima_file(file);
743         }
744
745         return err;
746 }
747
748 static int sign_evm_path(const char *file)
749 {
750         char *key;
751         int err;
752
753         key = params.keyfile ? : "/etc/keys/privkey_evm.pem";
754
755         if (digsig) {
756                 err = sign_ima(file, key);
757                 if (err)
758                         return err;
759         }
760
761         if (digest) {
762                 err = hash_ima(file);
763                 if (err)
764                         return err;
765         }
766
767         return sign_evm(file, key);
768 }
769
770 static int cmd_sign_evm(struct command *cmd)
771 {
772         char *path = g_argv[optind++];
773         int err, dts = REG_MASK; /* only regular files by default */
774
775         if (!path) {
776                 log_err("Parameters missing\n");
777                 print_usage(cmd);
778                 return -1;
779         }
780
781         if (recursive) {
782                 if (search_type) {
783                         dts = get_file_type(path, search_type);
784                         if (dts < 0)
785                                 return dts;
786                 }
787                 err = find(path, dts, sign_evm_path);
788         } else {
789                 err = sign_evm_path(path);
790         }
791
792         return err;
793 }
794
795 static int verify_evm(const char *file)
796 {
797         unsigned char hash[20];
798         unsigned char sig[1024];
799         int len;
800
801         len = calc_evm_hash(file, hash);
802         if (len <= 1)
803                 return len;
804
805         len = lgetxattr(file, "security.evm", sig, sizeof(sig));
806         if (len < 0) {
807                 log_err("getxattr failed\n");
808                 return len;
809         }
810
811         if (sig[0] != 0x03) {
812                 log_err("security.evm has not signature\n");
813                 return -1;
814         }
815
816         return verify_hash(hash, sizeof(hash), sig + 1, len - 1);
817 }
818
819 static int cmd_verify_evm(struct command *cmd)
820 {
821         char *file = g_argv[optind++];
822
823         if (!file) {
824                 log_err("Parameters missing\n");
825                 print_usage(cmd);
826                 return -1;
827         }
828
829         return verify_evm(file);
830 }
831
832 static int verify_ima(const char *file)
833 {
834         unsigned char sig[1024];
835         int len;
836
837         if (xattr) {
838                 len = lgetxattr(file, "security.ima", sig, sizeof(sig));
839                 if (len < 0) {
840                         log_err("getxattr failed\n");
841                         return len;
842                 }
843         }
844
845         if (sigfile) {
846                 void *tmp;
847                 tmp = file2bin(file, "sig", &len);
848                 memcpy(sig, tmp, len);
849                 free(tmp);
850         }
851
852         return ima_verify_signature(file, sig, len);
853 }
854
855 static int cmd_verify_ima(struct command *cmd)
856 {
857         char *file = g_argv[optind++];
858
859         if (!file) {
860                 log_err("Parameters missing\n");
861                 print_usage(cmd);
862                 return -1;
863         }
864
865         return verify_ima(file);
866 }
867
868 static int cmd_import(struct command *cmd)
869 {
870         char *inkey, *ring = NULL;
871         unsigned char _pub[1024], *pub = _pub;
872         int id, len, err = 0;
873         char name[20];
874         uint8_t keyid[8];
875         RSA *key;
876
877         inkey = g_argv[optind++];
878         if (!inkey) {
879                 inkey = x509 ? "/etc/keys/x509_evm.der" :
880                                "/etc/keys/pubkey_evm.pem";
881         } else
882                 ring = g_argv[optind++];
883
884         if (!ring)
885                 id = KEY_SPEC_USER_KEYRING;
886         else
887                 id = atoi(ring);
888
889         key = read_pub_key(inkey, x509);
890         if (!key)
891                 return 1;
892
893         if (x509) {
894                 pub = file2bin(inkey, NULL, &len);
895                 if (!pub)
896                         goto out;
897                 calc_keyid_v2((uint32_t *)keyid, name, key);
898         } else {
899                 len = key2bin(key, pub);
900                 calc_keyid_v1(keyid, name, pub, len);
901         }
902
903         log_info("Importing public key %s from file %s into keyring %d\n", name, inkey, id);
904
905         id = add_key(x509 ? "asymmetric" : "user", x509 ? NULL : name, pub, len, id);
906         if (id < 0) {
907                 log_err("add_key failed\n");
908                 err = id;
909         } else {
910                 log_info("keyid: %d\n", id);
911                 printf("%d\n", id);
912         }
913         if (x509)
914                 free(pub);
915 out:
916         RSA_free(key);
917         return err;
918 }
919
920 #define MAX_KEY_SIZE 128
921
922 static int calc_evm_hmac(const char *file, const char *keyfile, unsigned char *hash)
923 {
924         struct stat st;
925         int err = -1;
926         uint32_t generation = 0;
927         HMAC_CTX ctx;
928         unsigned int mdlen;
929         char **xattrname;
930         unsigned char xattr_value[1024];
931         unsigned char *key;
932         int keylen;
933         unsigned char evmkey[MAX_KEY_SIZE];
934         char list[1024];
935         ssize_t list_size;
936         struct h_misc_64 hmac_misc;
937         int hmac_size;
938
939         key = file2bin(keyfile, NULL, &keylen);
940         if (!key) {
941                 log_err("Unable to read a key: %s\n\n", keyfile);
942                 return -1;
943         }
944
945         if (keylen > sizeof(evmkey)) {
946                 log_err("key is too long\n");
947                 goto out;
948         }
949
950         /* EVM key is 128 bytes */
951         memcpy(evmkey, key, keylen);
952         memset(evmkey + keylen, 0, sizeof(evmkey) - keylen);
953
954         if (lstat(file, &st)) {
955                 log_err("lstat() failed\n");
956                 goto out;
957         }
958
959         if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode)) {
960                 /* we cannot at the momement to get generation of special files..
961                  * kernel API does not support it */
962                 int fd = open(file, 0);
963                 if (fd < 0) {
964                         log_err("Unable to open %s\n", file);
965                         goto out;
966                 }
967                 if (ioctl(fd, EXT34_IOC_GETVERSION, &generation)) {
968                         log_err("ioctl() failed\n");
969                         goto out;
970                 }
971                 close(fd);
972         }
973
974         log_info("generation: %u\n", generation);
975
976         list_size = llistxattr(file, list, sizeof(list));
977         if (list_size <= 0) {
978                 log_err("llistxattr() failed\n");
979                 goto out;
980         }
981
982         err = !HMAC_Init(&ctx, evmkey, sizeof(evmkey), EVP_sha1());
983         if (err) {
984                 log_err("HMAC_Init() failed\n");
985                 goto out;
986         }
987
988         for (xattrname = evm_config_xattrnames; *xattrname != NULL; xattrname++) {
989                 err = lgetxattr(file, *xattrname, xattr_value, sizeof(xattr_value));
990                 if (err < 0) {
991                         log_info("no xattr: %s\n", *xattrname);
992                         continue;
993                 }
994                 if (!find_xattr(list, list_size, *xattrname)) {
995                         log_info("skipping xattr: %s\n", *xattrname);
996                         continue;
997                 }
998                 /*log_debug("name: %s, value: %s, size: %d\n", *xattrname, xattr_value, err);*/
999                 log_info("name: %s, size: %d\n", *xattrname, err);
1000                 log_debug_dump(xattr_value, err);
1001                 err = !HMAC_Update(&ctx, xattr_value, err);
1002                 if (err) {
1003                         log_err("HMAC_Update() failed\n");
1004                         goto out_ctx_cleanup;
1005                 }
1006         }
1007
1008         memset(&hmac_misc, 0, sizeof(hmac_misc));
1009
1010         if (msize == 0) {
1011                 struct h_misc *hmac = (struct h_misc *)&hmac_misc;
1012                 hmac_size = sizeof(*hmac);
1013                 hmac->ino = st.st_ino;
1014                 hmac->generation = generation;
1015                 hmac->uid = st.st_uid;
1016                 hmac->gid = st.st_gid;
1017                 hmac->mode = st.st_mode;
1018         } else if (msize == 64) {
1019                 struct h_misc_64 *hmac = (struct h_misc_64 *)&hmac_misc;
1020                 hmac_size = sizeof(*hmac);
1021                 hmac->ino = st.st_ino;
1022                 hmac->generation = generation;
1023                 hmac->uid = st.st_uid;
1024                 hmac->gid = st.st_gid;
1025                 hmac->mode = st.st_mode;
1026         } else {
1027                 struct h_misc_32 *hmac = (struct h_misc_32 *)&hmac_misc;
1028                 hmac_size = sizeof(*hmac);
1029                 hmac->ino = st.st_ino;
1030                 hmac->generation = generation;
1031                 hmac->uid = st.st_uid;
1032                 hmac->gid = st.st_gid;
1033                 hmac->mode = st.st_mode;
1034         }
1035
1036         log_debug("hmac_misc (%d): ", hmac_size);
1037         log_debug_dump(&hmac_misc, hmac_size);
1038
1039         err = !HMAC_Update(&ctx, (const unsigned char *)&hmac_misc, hmac_size);
1040         if (err) {
1041                 log_err("HMAC_Update() failed\n");
1042                 goto out_ctx_cleanup;
1043         }
1044         err = !HMAC_Final(&ctx, hash, &mdlen);
1045         if (err)
1046                 log_err("HMAC_Final() failed\n");
1047 out_ctx_cleanup:
1048         HMAC_CTX_cleanup(&ctx);
1049 out:
1050         free(key);
1051         return err ?: mdlen;
1052 }
1053
1054 static int hmac_evm(const char *file, const char *key)
1055 {
1056         unsigned char hash[20];
1057         unsigned char sig[1024] = "\x02";
1058         int len, err;
1059
1060         len = calc_evm_hmac(file, key, hash);
1061         if (len <= 1)
1062                 return len;
1063
1064         log_info("hmac: ");
1065         log_dump(hash, len);
1066         memcpy(sig + 1, hash, len);
1067
1068         if (xattr) {
1069                 err = lsetxattr(file, "security.evm", sig, len + 1, 0);
1070                 if (err < 0) {
1071                         log_err("setxattr failed: %s\n", file);
1072                         return err;
1073                 }
1074         }
1075
1076         return 0;
1077 }
1078
1079 static int cmd_hmac_evm(struct command *cmd)
1080 {
1081         char *key, *file = g_argv[optind++];
1082         int err;
1083
1084         if (!file) {
1085                 log_err("Parameters missing\n");
1086                 print_usage(cmd);
1087                 return -1;
1088         }
1089
1090         key = params.keyfile ? : "/etc/keys/privkey_evm.pem";
1091
1092         if (digsig) {
1093                 err = sign_ima(file, key);
1094                 if (err)
1095                         return err;
1096         }
1097
1098         if (digest) {
1099                 err = hash_ima(file);
1100                 if (err)
1101                         return err;
1102         }
1103
1104         return hmac_evm(file, "/etc/keys/evm-key-plain");
1105 }
1106
1107 static int ima_fix(const char *path)
1108 {
1109         int fd, size, len, ima = 0, evm = 0;
1110         char buf[1024], *list = buf;
1111
1112         log_info("%s\n", path);
1113
1114         if (xattr) {
1115                 /* re-measuring takes a time
1116                  * in some cases we can skip labeling if xattrs exists
1117                  */
1118                 size = llistxattr(path, list, sizeof(buf));
1119                 if (size < 0) {
1120                         log_errno("llistxattr() failed: %s\n", path);
1121                         return -1;
1122                 }
1123                 for (; size > 0; len++, size -= len, list += len) {
1124                         len = strlen(list);
1125                         if (!strcmp(list, "security.ima"))
1126                                 ima = 1;
1127                         else if (!strcmp(list, "security.evm"))
1128                                 evm = 1;
1129                 }
1130                 if (ima && evm)
1131                         return 0;
1132         }
1133
1134         fd = open(path, O_RDONLY);
1135         if (fd < 0) {
1136                 log_errno("%s open failed", path);
1137                 return -1;
1138         }
1139
1140         close(fd);
1141
1142         return 0;
1143 }
1144
1145 static int find(const char *path, int dts, find_cb_t func)
1146 {
1147         struct dirent *de;
1148         DIR *dir;
1149
1150         if (fs_dev) {
1151                 struct stat st;
1152                 int err = lstat(path, &st);
1153                 if (err < 0) {
1154                         log_err("stat() failed\n");
1155                         return err;
1156                 }
1157                 if (st.st_dev != fs_dev)
1158                         return 0;
1159         }
1160
1161         dir = opendir(path);
1162         if (!dir) {
1163                 log_err("Unable to open %s\n", path);
1164                 return -1;
1165         }
1166
1167         if (fchdir(dirfd(dir))) {
1168                 log_err("Unable to chdir %s\n", path);
1169                 return -1;
1170         }
1171
1172         while ((de = readdir(dir))) {
1173                 if (!strcmp(de->d_name, "..") || !strcmp(de->d_name, "."))
1174                         continue;
1175                 log_debug("path: %s, type: %u\n", de->d_name, de->d_type);
1176                 if (de->d_type == DT_DIR)
1177                         find(de->d_name, dts, func);
1178                 else if (dts & (1 << de->d_type))
1179                         func(de->d_name);
1180         }
1181
1182         if (chdir("..")) {
1183                 log_err("Unable to chdir %s\n", path);
1184                 return -1;
1185         }
1186
1187         if (dts & DIR_MASK)
1188                 func(path);
1189
1190         closedir(dir);
1191
1192         return 0;
1193 }
1194
1195 static int cmd_ima_fix(struct command *cmd)
1196 {
1197         char *path = g_argv[optind++];
1198         int err, dts = REG_MASK; /* only regular files by default */
1199         struct stat st;
1200
1201         if (!path) {
1202                 log_err("Parameters missing\n");
1203                 print_usage(cmd);
1204                 return -1;
1205         }
1206
1207         xattr = 0; /* do not check xattrs, fix everything */
1208
1209         if (search_type) {
1210                 int i;
1211
1212                 dts = 0;
1213                 for (i = 0; search_type[i]; i++) {
1214                         switch (search_type[i]) {
1215                         case 'f':
1216                                 dts |= REG_MASK; break;
1217                         case 'd':
1218                                 dts |= DIR_MASK; break;
1219                         case 's':
1220                                 dts |= BLK_MASK | CHR_MASK | LNK_MASK; break;
1221                         case 'x':
1222                                 /* check xattrs */
1223                                 xattr = 1; break;
1224                         case 'm':
1225                                 /* stay within the same filesystem*/
1226                                 err = lstat(path, &st);
1227                                 if (err < 0) {
1228                                         log_err("stat() failed\n");
1229                                         return err;
1230                                 }
1231                                 fs_dev = st.st_dev; /* filesystem to start from */
1232                                 break;
1233                         }
1234                 }
1235         }
1236
1237         err = find(path, dts, ima_fix);
1238         if (err)
1239                 return err;
1240
1241         return 0;
1242 }
1243
1244
1245 static char *pcrs = "/sys/class/misc/tpm0/device/pcrs";
1246
1247 static int tpm_pcr_read(int idx, uint8_t *pcr, int len)
1248 {
1249         FILE *fp;
1250         char *p, pcr_str[7], buf[70]; /* length of the TPM string */
1251
1252         sprintf(pcr_str, "PCR-%d", idx);
1253
1254         fp = fopen(pcrs, "r");
1255         if (!fp) {
1256                 log_err("Unable to open %s\n", pcrs);
1257                 return -1;
1258         }
1259
1260         for (;;) {
1261                 p = fgets(buf, sizeof(buf), fp);
1262                 if (!p)
1263                         break;
1264                 if (!strncmp(p, pcr_str, 6)) {
1265                         hex2bin(pcr, p + 7, len);
1266                         return 0;
1267                 }
1268         }
1269         fclose(fp);
1270         return -1;
1271 }
1272
1273 #define TCG_EVENT_NAME_LEN_MAX  255
1274
1275 struct template_entry {
1276         struct {
1277                 uint32_t pcr;
1278                 uint8_t digest[SHA_DIGEST_LENGTH];
1279                 uint32_t name_len;
1280         } header  __packed;
1281         char name[TCG_EVENT_NAME_LEN_MAX + 1];
1282         int template_len;
1283         uint8_t *template;
1284         int template_buf_len;
1285 };
1286
1287 static uint8_t zero[SHA_DIGEST_LENGTH];
1288 static uint8_t fox[SHA_DIGEST_LENGTH];
1289
1290 int validate = 1;
1291
1292 void ima_extend_pcr(uint8_t *pcr, uint8_t *digest, int length)
1293 {
1294         SHA_CTX ctx;
1295
1296         SHA1_Init(&ctx);
1297         SHA1_Update(&ctx, pcr, length);
1298         if (validate && !memcmp(digest, zero, length))
1299                 SHA1_Update(&ctx, fox, length);
1300         else
1301                 SHA1_Update(&ctx, digest, length);
1302         SHA1_Final(pcr, &ctx);
1303 }
1304
1305 static int ima_verify_tamplate_hash(struct template_entry *entry)
1306 {
1307         uint8_t digest[SHA_DIGEST_LENGTH];
1308
1309         if (!memcmp(zero, entry->header.digest, sizeof(zero)))
1310                 return 0;
1311
1312         SHA1(entry->template, entry->template_len, digest);
1313
1314         if (memcmp(digest, entry->header.digest, sizeof(digest))) {
1315                 log_err("template hash error\n");
1316                 return 1;
1317         }
1318
1319         return 0;
1320 }
1321
1322 void ima_show(struct template_entry *entry)
1323 {
1324         log_debug("ima, digest: ");
1325         log_debug_dump(entry->header.digest, sizeof(entry->header.digest));
1326 }
1327
1328 void ima_ng_show(struct template_entry *entry)
1329 {
1330         uint8_t *fieldp = entry->template;
1331         uint32_t field_len;
1332         int total_len = entry->template_len, digest_len, len, sig_len;
1333         uint8_t *digest, *sig = NULL;
1334         char *algo, *path;
1335
1336         /* get binary digest */
1337         field_len = *(uint8_t *)fieldp;
1338         fieldp += sizeof(field_len);
1339         total_len -= sizeof(field_len);
1340
1341         algo = (char *)fieldp;
1342         len = strlen(algo) + 1;
1343         digest_len = field_len - len;
1344         digest = fieldp + len;
1345
1346         /* move to next field */
1347         fieldp += field_len;
1348         total_len -= field_len;
1349
1350         /* get path */
1351         field_len = *(uint8_t *)fieldp;
1352         fieldp += sizeof(field_len);
1353         total_len -= sizeof(field_len);
1354
1355         path = (char *)fieldp;
1356
1357         /* move to next field */
1358         fieldp += field_len;
1359         total_len -= field_len;
1360
1361         if (!strcmp(entry->name, "ima-sig")) {
1362                 /* get signature */
1363                 field_len = *(uint8_t *)fieldp;
1364                 fieldp += sizeof(field_len);
1365                 total_len -= sizeof(field_len);
1366
1367                 if (field_len) {
1368                         sig = fieldp;
1369                         sig_len = field_len;
1370
1371                         /* move to next field */
1372                         fieldp += field_len;
1373                         total_len -= field_len;
1374                 }
1375         }
1376
1377         /* ascii_runtime_measurements */
1378         log_info("%d ", entry->header.pcr);
1379         log_dump_n(entry->header.digest, sizeof(entry->header.digest));
1380         log_info(" %s %s", entry->name, algo);
1381         log_dump_n(digest, digest_len);
1382         log_info(" %s", path);
1383
1384         if (sig) {
1385                 log_info(" ");
1386                 log_dump(sig, sig_len);
1387                 ima_verify_signature(path, sig, sig_len);
1388         } else
1389                 log_info("\n");
1390
1391         if (total_len)
1392                 log_err("Remain unprocessed data: %d\n", total_len);
1393 }
1394
1395 static int ima_measurement(const char *file)
1396 {
1397         uint8_t pcr[SHA_DIGEST_LENGTH] = {0,};
1398         uint8_t pcr10[SHA_DIGEST_LENGTH];
1399         struct template_entry entry = { .template = 0 };
1400         FILE *fp;
1401         int err;
1402
1403         memset(fox, 0xff, SHA_DIGEST_LENGTH);
1404
1405         log_debug("Initial PCR value: ");
1406         log_debug_dump(pcr, sizeof(pcr));
1407
1408         fp = fopen(file, "rb");
1409         if (!fp) {
1410                 log_err("Unable to open measurement file\n");
1411                 return -1;
1412         }
1413
1414         while ((err = fread(&entry.header, sizeof(entry.header), 1, fp))) {
1415                 ima_extend_pcr(pcr, entry.header.digest, SHA_DIGEST_LENGTH);
1416
1417                 if (!fread(entry.name, entry.header.name_len, 1, fp)) {
1418                         log_err("Unable to read template name\n");
1419                         return -1;
1420                 }
1421
1422                 entry.name[entry.header.name_len] = '\0';
1423
1424                 if (!fread(&entry.template_len, sizeof(entry.template_len), 1, fp)) {
1425                         log_err("Unable to read template length\n");
1426                         return -1;
1427                 }
1428
1429                 if (entry.template_buf_len < entry.template_len) {
1430                         free(entry.template);
1431                         entry.template_buf_len = entry.template_len;
1432                         entry.template = malloc(entry.template_len);
1433                 }
1434
1435                 if (!fread(entry.template, entry.template_len, 1, fp)) {
1436                         log_err("Unable to read template\n");
1437                         return -1;
1438                 }
1439
1440                 if (validate)
1441                         ima_verify_tamplate_hash(&entry);
1442
1443                 if (!strcmp(entry.name, "ima"))
1444                         ima_show(&entry);
1445                 else
1446                         ima_ng_show(&entry);
1447         }
1448
1449         fclose(fp);
1450
1451         tpm_pcr_read(10, pcr10, sizeof(pcr10));
1452
1453         log_info("PCRAgg: ");
1454         log_dump(pcr, sizeof(pcr));
1455
1456         log_info("PCR-10: ");
1457         log_dump(pcr10, sizeof(pcr10));
1458
1459         if (memcmp(pcr, pcr10, sizeof(pcr))) {
1460                 log_err("PCRAgg does not match PCR-10\n");
1461                 return -1;
1462         }
1463
1464         return 0;
1465 }
1466
1467 static int cmd_ima_measurement(struct command *cmd)
1468 {
1469         char *file = g_argv[optind++];
1470
1471         if (!file) {
1472                 log_err("Parameters missing\n");
1473                 print_usage(cmd);
1474                 return -1;
1475         }
1476
1477         return ima_measurement(file);
1478 }
1479
1480 static void print_usage(struct command *cmd)
1481 {
1482         printf("usage: %s %s\n", cmd->name, cmd->arg ? cmd->arg : "");
1483 }
1484
1485 static void print_full_usage(struct command *cmd)
1486 {
1487         if (cmd->name)
1488                 printf("usage: %s %s\n", cmd->name, cmd->arg ? cmd->arg : "");
1489         if (cmd->msg)
1490                 printf("%s", cmd->msg);
1491 }
1492
1493 static int print_command_usage(struct command *cmds, char *command)
1494 {
1495         struct command *cmd;
1496
1497         for (cmd = cmds; cmd->name; cmd++) {
1498                 if (strcmp(cmd->name, command) == 0) {
1499                         print_full_usage(cmd);
1500                         return 0;
1501                 }
1502         }
1503         printf("invalid command: %s\n", command);
1504         return -1;
1505 }
1506
1507 static void print_all_usage(struct command *cmds)
1508 {
1509         struct command *cmd;
1510
1511         printf("commands:\n");
1512
1513         for (cmd = cmds; cmd->name; cmd++) {
1514                 if (cmd->arg)
1515                         printf(" %s %s\n", cmd->name, cmd->arg);
1516                 else if (cmd->msg)
1517                         printf(" %s", cmd->msg);
1518         }
1519 }
1520
1521 static int call_command(struct command *cmds, char *command)
1522 {
1523         struct command *cmd;
1524
1525         for (cmd = cmds; cmd->name; cmd++) {
1526                 if (strcasecmp(cmd->name, command) == 0)
1527                         return cmd->func(cmd);
1528         }
1529         printf("Invalid command: %s\n", command);
1530         return -1;
1531 }
1532
1533 static int cmd_help(struct command *cmd)
1534 {
1535         if (!g_argv[optind]) {
1536                 print_usage(cmd);
1537                 return 0;
1538         } else
1539                 return print_command_usage(cmds, g_argv[optind]);
1540 }
1541
1542 static void usage(void)
1543 {
1544         printf("Usage: evmctl [-v] <command> [OPTIONS]\n");
1545
1546         print_all_usage(cmds);
1547
1548         printf(
1549                 "\n"
1550                 "  -a, --hashalgo     sha1 (default), sha224, sha256, sha384, sha512\n"
1551                 "  -s, --imasig       also make IMA signature\n"
1552                 "  -d, --imahash      also make IMA hash\n"
1553                 "  -f, --sigfile      store IMA signature in .sig file instead of xattr\n"
1554                 "  -1, --rsa          signing key is in RSA DER format (signing v1)\n"
1555                 "  -k, --key          path to signing key (default keys are /etc/keys/{privkey,pubkey}_evm.pem)\n"
1556                 "  -p, --pass         password for encrypted signing key\n"
1557                 "  -u, --uuid         use file system UUID in HMAC calculation (EVM v2)\n"
1558                 "  -t, --type         file types to fix 'fdsxm' (f - file, d - directory, s - block/char/symlink)\n"
1559                 "                     x - skip fixing if both ima and evm xattrs exist (caution: they may be wrong)\n"
1560                 "                     m - stay on the same filesystem (like 'find -xdev')\n"
1561                 "  -n                 print result to stdout instead of setting xattr\n"
1562                 "  -r, --recursive    recurse into directories (sign)\n"
1563                 "  --x32              force signature for 32 bit target system\n"
1564                 "  --x64              force signature for 32 bit target system\n"
1565                 "  -v                 increase verbosity level\n"
1566                 "  -h, --help         display this help and exit\n"
1567                 "\n");
1568 }
1569
1570 struct command cmds[] = {
1571         {"help", cmd_help, 0, "<command>"},
1572         {"import", cmd_import, 0, "[--rsa] pubkey keyring", "Import public key into the keyring.\n"},
1573         {"sign", cmd_sign_evm, 0, "[-r] [--imahash | --imasig ] [--key key] [--pass password] file", "Sign file metadata.\n"},
1574         {"verify", cmd_verify_evm, 0, "file", "Verify EVM signature (for debugging).\n"},
1575         {"ima_sign", cmd_sign_ima, 0, "[--sigfile] [--key key] [--pass password] file", "Make file content signature.\n"},
1576         {"ima_verify", cmd_verify_ima, 0, "file", "Verify IMA signature (for debugging).\n"},
1577         {"ima_hash", cmd_hash_ima, 0, "file", "Make file content hash.\n"},
1578         {"ima_measurement", cmd_ima_measurement, 0, "file", "Verify measurement list (experimental).\n"},
1579         {"ima_fix", cmd_ima_fix, 0, "[-t fdsxm] path", "Recursively fix IMA/EVM xattrs in fix mode.\n"},
1580 #ifdef DEBUG
1581         {"hmac", cmd_hmac_evm, 0, "[--imahash | --imasig ] file", "Sign file metadata with HMAC using symmetric key (for testing purpose).\n"},
1582 #endif
1583         {0, 0, 0, NULL}
1584 };
1585
1586 static struct option opts[] = {
1587         {"help", 0, 0, 'h'},
1588         {"imasig", 0, 0, 's'},
1589         {"imahash", 0, 0, 'd'},
1590         {"hashalgo", 1, 0, 'a'},
1591         {"pass", 1, 0, 'p'},
1592         {"sigfile", 0, 0, 'f'},
1593         {"uuid", 2, 0, 'u'},
1594         {"rsa", 0, 0, '1'},
1595         {"key", 1, 0, 'k'},
1596         {"type", 1, 0, 't'},
1597         {"recursive", 0, 0, 'r'},
1598         {"m32", 0, 0, '3'},
1599         {"m64", 0, 0, '6'},
1600         {}
1601
1602 };
1603
1604 int main(int argc, char *argv[])
1605 {
1606         int err = 0, c, lind;
1607
1608         g_argv = argv;
1609         g_argc = argc;
1610
1611         while (1) {
1612                 c = getopt_long(argc, argv, "hvnsda:p:fu::xk:t:r", opts, &lind);
1613                 if (c == -1)
1614                         break;
1615
1616                 switch (c) {
1617                 case 'h':
1618                         usage();
1619                         exit(0);
1620                         break;
1621                 case 'v':
1622                         params.verbose++;
1623                         break;
1624                 case 'd':
1625                         digest = 1;
1626                         break;
1627                 case 's':
1628                         digsig = 1;
1629                         break;
1630                 case 'n':
1631                         /* do not set Extended Attributes... just print signature */
1632                         xattr = 0;
1633                         sigdump = 1;
1634                         break;
1635                 case 'a':
1636                         params.hash_algo = optarg;
1637                         break;
1638                 case 'p':
1639                         keypass = optarg;
1640                         break;
1641                 case 'f':
1642                         sigfile = 1;
1643                         xattr = 0;
1644                         break;
1645                 case 'u':
1646                         uuid_str = optarg ?: "+";
1647                         break;
1648                 case '1':
1649                         x509 = 0;
1650                         break;
1651                 case 'k':
1652                         params.keyfile = optarg;
1653                         break;
1654                 case 't':
1655                         search_type = optarg;
1656                         break;
1657                 case 'r':
1658                         recursive = 1;
1659                         break;
1660                 case '3':
1661                         msize = 32;
1662                         break;
1663                 case '6':
1664                         msize = 64;
1665                         break;
1666                 case '?':
1667                         exit(1);
1668                         break;
1669                 default:
1670                         log_err("getopt() returned: %d (%c)\n", c, c);
1671                 }
1672         }
1673
1674         if (x509)
1675                 sign_hash = sign_hash_v2;
1676         else
1677                 sign_hash = sign_hash_v1;
1678
1679         OpenSSL_add_all_algorithms();
1680         ERR_load_crypto_strings();
1681
1682         if (argv[optind] == NULL)
1683                 usage();
1684         else
1685                 err = call_command(cmds, argv[optind++]);
1686
1687         if (err) {
1688                 unsigned long error;
1689                 if (errno)
1690                         log_err("errno: %s (%d)\n", strerror(errno), errno);
1691                 for (;;) {
1692                         error = ERR_get_error();
1693                         if (!error)
1694                                 break;
1695                         log_err("%s\n", ERR_error_string(error, NULL));
1696                 }
1697         }
1698
1699         ERR_free_strings();
1700         EVP_cleanup();
1701
1702         return err;
1703 }