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