2 * evm-utils - IMA/EVM support utilities
4 * Copyright (C) 2011 Nokia Corporation
5 * Copyright (C) 2011 Intel Corporation
8 * Dmitry Kasatkin <dmitry.kasatkin@nokia.com>
9 * <dmitry.kasatkin@intel.com>
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public License
13 * version 2.1 as published by the Free Software Foundation.
15 * This library is distributed in the hope that it will be useful, but
16 * WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
26 * IMA/EVM control program
29 #include <sys/types.h>
31 #include <sys/ioctl.h>
32 #include <sys/param.h>
39 #include <attr/xattr.h>
43 #include <asm/byteorder.h>
45 #include <attr/xattr.h>
48 #include <openssl/sha.h>
49 #include <openssl/rsa.h>
50 #include <openssl/pem.h>
51 #include <openssl/hmac.h>
52 #include <openssl/engine.h>
53 #include <openssl/evp.h>
54 #include <openssl/err.h>
59 #define do_log(level, fmt, args...) ({ if (level <= verbose) fprintf(stderr, fmt, ##args); })
60 #define do_log_dump(level, p, len) ({ if (level <= verbose) do_dump(stderr, p, len); })
62 #define do_log(level, fmt, args...) syslog(level, fmt, ##args)
63 #define do_log_dump(p, len)
67 #define log_debug(fmt, args...) do_log(LOG_DEBUG, "%s:%d " fmt, __func__ , __LINE__ , ##args)
68 #define log_debug_dump(p, len) do_log_dump(LOG_DEBUG, p, len)
70 #define log_debug(fmt, args...)
71 #define log_debug_dump(p, len)
74 #define log_dump(p, len) do_log_dump(LOG_INFO, p, len)
75 #define log_info(fmt, args...) do_log(LOG_INFO, fmt, ##args)
76 #define log_err(fmt, args...) do_log(LOG_ERR, fmt, ##args)
77 #define log_errno(fmt, args...) do_log(LOG_ERR, fmt ": %s (%d)\n", ##args, strerror(errno), errno)
79 #define DATA_SIZE 4096
80 #define SHA1_HASH_LEN 20
82 #define EXT2_IOC_GETVERSION _IOR('v', 1, long)
83 #define EXT34_IOC_GETVERSION _IOR('f', 3, long)
85 #define FS_IOC_GETFLAGS _IOR('f', 1, long)
86 #define FS_IOC_SETFLAGS _IOW('f', 2, long)
87 #define FS_IOC32_GETFLAGS _IOR('f', 1, int)
88 #define FS_IOC32_SETFLAGS _IOW('f', 2, int)
110 uint8_t version; /* key format version */
111 uint32_t timestamp; /* key made, always 0 for now */
115 } __attribute__ ((packed));
117 struct signature_hdr {
118 uint8_t version; /* signature format version */
119 uint32_t timestamp; /* signature made */
125 } __attribute__ ((packed));
127 static char *evm_config_xattrnames[] = {
131 "security.capability",
137 int (*func)(struct command *cmd);
140 char *msg; /* extra info message */
143 static int verbose = LOG_INFO - 1;
145 static char **g_argv;
146 static int xattr = 1;
149 static char *hash_algo = "sha1";
151 static char *keypass;
154 struct command cmds[];
155 static void print_usage(struct command *cmd);
157 static void do_dump(FILE *fp, const void *ptr, int len)
160 uint8_t *data = (uint8_t *) ptr;
162 for (i = 0; i < len; i++)
163 fprintf(fp, "%02x", data[i]);
167 static void dump(const void *ptr, int len)
169 do_dump(stdout, ptr, len);
172 static inline int get_filesize(const char *filename)
175 /* Need to know the file length */
176 stat(filename, &stats);
177 return (int)stats.st_size;
180 static inline int get_fdsize(int fd)
183 /* Need to know the file length */
185 return (int)stats.st_size;
188 static int bin2file(const char *file, const char *ext, const unsigned char *data, int len)
191 char name[strlen(file) + (ext ? strlen(ext) : 0) + 2];
195 sprintf(name, "%s.%s", file, ext);
197 sprintf(name, "%s", file);
199 log_info("Writing to %s\n", name);
201 fp = fopen(name, "w");
203 log_errno("Unable to open %s for writing", name);
206 err = fwrite(data, len, 1, fp);
211 static char *file2bin(const char *file, int *size)
217 len = get_filesize(file);
218 fp = fopen(file, "r");
220 log_errno("Unable to open %s", file);
224 if (!fread(data, len, 1, fp))
233 * Create binary key representation suitable for kernel
235 static int key2bin(RSA *key, unsigned char *pub)
237 int len, b, offset = 0;
238 struct pubkey_hdr *pkh = (struct pubkey_hdr *)pub;
242 pkh->timestamp = 0; /* PEM has no timestamp?? */
243 pkh->algo = PUBKEY_ALGO_RSA;
246 offset += sizeof(*pkh);
248 len = BN_num_bytes(key->n);
249 b = BN_num_bits(key->n);
250 pub[offset++] = b >> 8;
251 pub[offset++] = b & 0xff;
252 BN_bn2bin(key->n, &pub[offset]);
255 len = BN_num_bytes(key->e);
256 b = BN_num_bits(key->e);
257 pub[offset++] = b >> 8;
258 pub[offset++] = b & 0xff;
259 BN_bn2bin(key->e, &pub[offset]);
265 static int read_key(const char *inkey, unsigned char *pub)
268 RSA *key = NULL, *key1;
271 fp = fopen(inkey, "r");
273 log_errno("read key failed from file %s", inkey);
277 key1 = PEM_read_RSA_PUBKEY(fp, &key, NULL, NULL);
280 log_errno("PEM_read_RSA_PUBKEY() failed");
284 len = key2bin(key, pub);
291 static void calc_keyid(uint8_t *keyid, char *str, const unsigned char *pkey, int len)
293 uint8_t sha1[SHA_DIGEST_LENGTH];
296 log_debug("pkey:\n");
297 log_debug_dump(pkey, len);
298 SHA1(pkey, len, sha1);
300 /* sha1[12 - 19] is exactly keyid from gpg file */
301 memcpy(keyid, sha1 + 12, 8);
302 log_debug("keyid:\n");
303 log_debug_dump(keyid, 8);
305 id = __be64_to_cpup((__be64 *) keyid);
306 sprintf(str, "%llX", (unsigned long long)id);
307 log_info("keyid: %s\n", str);
310 static int sign_hash(const unsigned char *hash, int size, const char *keyfile, unsigned char *sig)
314 unsigned char pub[1024];
315 RSA *key = NULL, *key1;
318 unsigned char sighash[20];
319 struct signature_hdr *hdr = (struct signature_hdr *)sig;
323 log_dump(hash, size);
325 fp = fopen(keyfile, "r");
327 log_errno("Unable to open keyfile %s", keyfile);
330 key1 = PEM_read_RSAPrivateKey(fp, &key, NULL, keypass);
333 log_errno("RSAPrivateKey() failed");
337 /* now create a new hash */
339 hdr->timestamp = time(NULL);
340 hdr->algo = PUBKEY_ALGO_RSA;
341 hdr->hash = DIGEST_ALGO_SHA1;
343 len = key2bin(key, pub);
344 calc_keyid(hdr->keyid, name, pub, len);
349 SHA1_Update(&ctx, hash, size);
350 SHA1_Update(&ctx, hdr, sizeof(*hdr));
351 SHA1_Final(sighash, &ctx);
352 log_info("sighash: ");
353 log_dump(sighash, sizeof(sighash));
355 err = RSA_private_encrypt(sizeof(sighash), sighash, sig + sizeof(*hdr) + 2, key, RSA_PKCS1_PADDING);
358 log_errno("RSA_private_encrypt() failed: %d", err);
364 /* we add bit length of the signature to make it gnupg compatible */
365 blen = (uint16_t *) (sig + sizeof(*hdr));
366 *blen = __cpu_to_be16(len << 3);
367 len += sizeof(*hdr) + 2;
368 log_info("evm/ima signature: %d bytes\n", len);
369 if (!xattr || verbose >= LOG_INFO)
375 static int calc_evm_hash(const char *file, unsigned char *hash)
384 char xattr_value[1024];
388 log_errno("Unable to open %s", file);
392 if (fstat(fd, &st)) {
393 log_errno("fstat() failed");
397 if (ioctl(fd, EXT34_IOC_GETVERSION, &generation)) {
398 log_errno("ioctl() failed");
404 log_info("generation: %u\n", generation);
406 md = EVP_get_digestbyname("sha1");
408 log_errno("EVP_get_digestbyname() failed");
412 err = EVP_DigestInit(&ctx, md);
414 log_errno("EVP_DigestInit() failed");
418 for (xattrname = evm_config_xattrnames; *xattrname != NULL; xattrname++) {
419 err = getxattr(file, *xattrname, xattr_value, sizeof(xattr_value));
421 log_info("no attr: %s\n", *xattrname);
424 /*log_debug("name: %s, value: %s, size: %d\n", *xattrname, xattr_value, err);*/
425 log_info("name: %s, size: %d\n", *xattrname, err);
426 log_debug_dump(xattr_value, err);
427 err = EVP_DigestUpdate(&ctx, xattr_value, err);
429 log_errno("EVP_DigestUpdate() failed");
434 memset(&hmac_misc, 0, sizeof(hmac_misc));
435 hmac_misc.ino = st.st_ino;
436 hmac_misc.generation = generation;
437 hmac_misc.uid = st.st_uid;
438 hmac_misc.gid = st.st_gid;
439 hmac_misc.mode = st.st_mode;
441 err = EVP_DigestUpdate(&ctx, (const unsigned char *)&hmac_misc, sizeof(hmac_misc));
443 log_errno("EVP_DigestUpdate() failed");
446 err = EVP_DigestFinal(&ctx, hash, &mdlen);
448 log_errno("EVP_DigestFinal() failed");
455 static int sign_evm(const char *file, const char *key)
457 unsigned char hash[20];
458 unsigned char sig[1024] = "\x03";
461 calc_evm_hash(file, hash);
463 err = sign_hash(hash, sizeof(hash), key, sig + 1);
468 err = setxattr(file, "security.evm", sig, err + 1, 0);
470 log_errno("setxattr failed: %s", file);
478 static int calc_file_hash(const char *file, uint8_t *hash)
483 int err, size, bs = DATA_SIZE;
490 log_errno("malloc failed");
494 fp = fopen(file, "r");
496 log_errno("Unable to open %s", file);
500 md = EVP_get_digestbyname(hash_algo);
502 log_errno("EVP_get_digestbyname() failed");
506 err = EVP_DigestInit(&ctx, md);
508 log_errno("EVP_DigestInit() failed");
512 for (size = get_fdsize(fileno(fp)); size; size -= len) {
514 err = fread(data, len, 1, fp);
517 log_errno("fread() error\n");
522 err = EVP_DigestUpdate(&ctx, data, len);
524 log_errno("EVP_DigestUpdate() failed");
529 err = EVP_DigestFinal(&ctx, hash, &mdlen);
531 log_errno("EVP_DigestFinal() failed");
543 struct dirent_list *next;
547 static int calc_dir_hash(const char *file, uint8_t *hash)
555 struct dirent_list *head = NULL, *pos, *prev, *cur;
560 log_errno("Unable to open %s", file);
564 md = EVP_get_digestbyname(hash_algo);
566 log_errno("EVP_get_digestbyname() failed");
570 err = EVP_DigestInit(&ctx, md);
572 log_errno("EVP_DigestInit() failed");
576 while ((de = readdir(dir))) {
577 /*log_debug("entry: ino: %lu, %s\n", de->d_ino, de->d_name);*/
578 for (prev = NULL, pos = head; pos; prev = pos, pos = pos->next) {
579 if (de->d_ino < pos->de.d_ino)
582 cur = malloc(sizeof(*cur));
591 for (cur = head; cur; cur = pos) {
594 log_debug("entry: ino: %llu, %s\n", (unsigned long long)ino, cur->de.d_name);
595 err = EVP_DigestUpdate(&ctx, cur->de.d_name, strlen(cur->de.d_name));
597 log_errno("EVP_DigestUpdate() failed");
600 err = EVP_DigestUpdate(&ctx, &ino, sizeof(ino));
602 log_errno("EVP_DigestUpdate() failed");
608 err = EVP_DigestFinal(&ctx, hash, &mdlen);
610 log_errno("EVP_DigestFinal() failed");
619 static int hash_ima(const char *file)
621 unsigned char hash[65] = "\x01"; /* MAX hash size + 1 */
625 /* Need to know the file length */
626 err = stat(file, &st);
628 log_errno("stat() failed");
632 if (S_ISDIR(st.st_mode))
633 err = calc_dir_hash(file, hash + 1);
635 err = calc_file_hash(file, hash + 1);
639 if (verbose >= LOG_INFO)
642 if (!xattr || verbose >= LOG_INFO)
646 err = setxattr(file, "security.ima", hash, err + 1, 0);
648 log_errno("setxattr failed: %s", file);
656 static int cmd_hash_ima(struct command *cmd)
658 char *file = g_argv[optind++];
661 log_err("Parameters missing\n");
666 return hash_ima(file);
669 static int sign_ima(const char *file, const char *key)
671 unsigned char hash[64];
672 unsigned char sig[1024] = "\x03";
675 err = calc_file_hash(file, hash);
679 err = sign_hash(hash, err, key, sig + 1);
684 bin2file(file, "sig", sig, err + 1);
687 err = setxattr(file, "security.ima", sig, err + 1, 0);
689 log_errno("setxattr failed: %s", file);
697 static int cmd_sign_ima(struct command *cmd)
699 char *key, *file = g_argv[optind++];
702 log_err("Parameters missing\n");
707 key = g_argv[optind++];
709 key = "/etc/keys/privkey_evm.pem";
711 return sign_ima(file, key);
715 static int cmd_sign_evm(struct command *cmd)
717 char *key, *file = g_argv[optind++];
721 log_err("Parameters missing\n");
726 key = g_argv[optind++];
728 key = "/etc/keys/privkey_evm.pem";
731 err = sign_ima(file, key);
737 err = hash_ima(file);
742 return sign_evm(file, key);
745 static int verify_hash(const unsigned char *hash, int size, unsigned char *sig, int siglen, const char *keyfile)
749 unsigned char out[1024];
750 RSA *key = NULL, *key1;
752 unsigned char sighash[20];
753 struct signature_hdr *hdr = (struct signature_hdr *)sig;
756 log_dump(hash, size);
758 fp = fopen(keyfile, "r");
760 log_errno("Unable to open keyfile %s", keyfile);
763 key1 = PEM_read_RSA_PUBKEY(fp, &key, NULL, NULL);
766 log_errno("PEM_read_RSA_PUBKEY() failed");
771 SHA1_Update(&ctx, hash, size);
772 SHA1_Update(&ctx, hdr, sizeof(*hdr));
773 SHA1_Final(sighash, &ctx);
774 log_info("sighash: ");
775 log_dump(sighash, sizeof(sighash));
777 err = RSA_public_decrypt(siglen - sizeof(*hdr) - 2, sig + sizeof(*hdr) + 2, out, key, RSA_PKCS1_PADDING);
780 log_errno("RSA_public_decrypt() failed: %d", err);
786 if (len != sizeof(sighash) || memcmp(out, sighash, len) != 0) {
787 log_errno("Verification failed: %d", err);
790 /*log_info("Verification is OK\n");*/
791 printf("Verification is OK\n");
797 static int verify_evm(const char *file, const char *key)
799 unsigned char hash[20];
800 unsigned char sig[1024];
803 calc_evm_hash(file, hash);
805 err = getxattr(file, "security.evm", sig, sizeof(sig));
807 log_errno("getxattr failed");
811 if (sig[0] != 0x03) {
812 log_errno("security.evm has not signature");
816 return verify_hash(hash, sizeof(hash), sig + 1, err - 1, key);
819 static int cmd_verify_evm(struct command *cmd)
821 char *key, *file = g_argv[optind++];
824 log_err("Parameters missing\n");
829 key = g_argv[optind++];
831 key = "/etc/keys/pubkey_evm.pem";
833 return verify_evm(file, key);
836 static int cmd_convert(struct command *cmd)
838 char *inkey, *outkey = NULL;
839 unsigned char pub[1024];
844 inkey = g_argv[optind++];
846 inkey = "/etc/keys/pubkey_evm.pem";
848 outkey = g_argv[optind++];
851 outkey = "pubkey_evm.bin";
853 log_info("Convert public key %s to %s\n", inkey, outkey);
855 len = read_key(inkey, pub);
859 calc_keyid(keyid, name, pub, len);
861 bin2file(outkey, name, pub, len);
866 static int cmd_import_bin(struct command *cmd)
869 char *inkey, *ring = NULL;
874 inkey = g_argv[optind++];
876 inkey = "/etc/keys/pubkey_evm.bin";
878 ring = g_argv[optind++];
881 id = KEY_SPEC_USER_KEYRING;
885 key = file2bin(inkey, &len);
889 calc_keyid(keyid, name, (unsigned char *)key, len);
891 log_info("Importing public key %s from file %s into keyring %d\n", name, inkey, id);
893 id = add_key("user", name, key, len, id);
895 log_errno("add_key failed");
899 log_info("keyid: %d\n", id);
907 static int cmd_import(struct command *cmd)
909 char *inkey, *ring = NULL;
910 unsigned char key[1024];
916 return cmd_import_bin(cmd);
918 inkey = g_argv[optind++];
920 inkey = "/etc/keys/pubkey_evm.pem";
922 ring = g_argv[optind++];
925 id = KEY_SPEC_USER_KEYRING;
929 len = read_key(inkey, key);
933 calc_keyid(keyid, name, key, len);
935 log_info("Importing public key %s from file %s into keyring %d\n", name, inkey, id);
937 id = add_key("user", name, key, len, id);
939 log_errno("add_key failed");
943 log_info("keyid: %d\n", id);
949 #define MAX_KEY_SIZE 128
951 static int calc_evm_hmac(const char *file, const char *keyfile, unsigned char *hash)
959 unsigned char xattr_value[1024];
962 unsigned char evmkey[MAX_KEY_SIZE];
964 key = file2bin(keyfile, &keylen);
966 log_errno("Unable to read a key: %s\n", keyfile);
970 if (keylen > sizeof(evmkey)) {
971 log_errno("key is too long\n");
975 /* EVM key is 128 bytes */
976 memcpy(evmkey, key, keylen);
977 memset(evmkey + keylen, 0, sizeof(evmkey) - keylen);
981 log_errno("Unable to open %s", file);
985 if (fstat(fd, &st)) {
986 log_errno("fstat() failed");
990 if (ioctl(fd, EXT34_IOC_GETVERSION, &generation)) {
991 log_errno("ioctl() failed");
997 log_info("generation: %u\n", generation);
999 HMAC_Init(&ctx, evmkey, sizeof(evmkey), EVP_sha1());
1001 for (xattrname = evm_config_xattrnames; *xattrname != NULL; xattrname++) {
1002 err = getxattr(file, *xattrname, xattr_value, sizeof(xattr_value));
1004 log_info("no attr: %s\n", *xattrname);
1007 /*log_debug("name: %s, value: %s, size: %d\n", *xattrname, xattr_value, err);*/
1008 log_info("name: %s, size: %d\n", *xattrname, err);
1009 log_debug_dump(xattr_value, err);
1010 HMAC_Update(&ctx, xattr_value, err);
1013 memset(&hmac_misc, 0, sizeof(hmac_misc));
1014 hmac_misc.ino = st.st_ino;
1015 hmac_misc.generation = generation;
1016 hmac_misc.uid = st.st_uid;
1017 hmac_misc.gid = st.st_gid;
1018 hmac_misc.mode = st.st_mode;
1020 HMAC_Update(&ctx, (const unsigned char *)&hmac_misc, sizeof(hmac_misc));
1021 HMAC_Final(&ctx, hash, &mdlen);
1022 HMAC_CTX_cleanup(&ctx);
1029 static int hmac_evm(const char *file, const char *key)
1031 unsigned char hash[20];
1032 unsigned char sig[1024] = "\x02";
1035 calc_evm_hmac(file, key, hash);
1038 log_dump(hash, sizeof(hash));
1039 memcpy(sig + 1, hash, sizeof(hash));
1043 err = setxattr(file, "security.evm", sig, err + 1, 0);
1045 log_errno("setxattr failed: %s", file);
1053 static int cmd_hmac_evm(struct command *cmd)
1055 char *key, *file = g_argv[optind++];
1059 log_err("Parameters missing\n");
1064 key = g_argv[optind++];
1066 key = "/etc/keys/privkey_evm.pem";
1069 err = sign_ima(file, key);
1075 err = hash_ima(file);
1080 return hmac_evm(file, "/etc/keys/evm-key-plain");
1083 static void print_usage(struct command *cmd)
1085 printf("usage: %s %s\n", cmd->name, cmd->arg ? cmd->arg : "");
1088 static void print_full_usage(struct command *cmd)
1091 printf("usage: %s %s\n", cmd->name, cmd->arg ? cmd->arg : "");
1093 printf("description:\n%s", cmd->msg);
1097 static int print_command_usage(struct command *cmds, char *command)
1099 struct command *cmd;
1101 for (cmd = cmds; cmd->name; cmd++) {
1102 if (strcmp(cmd->name, command) == 0) {
1103 print_full_usage(cmd);
1107 printf("invalid command: %s\n", command);
1111 static void print_all_usage(struct command *cmds)
1113 struct command *cmd;
1115 for (cmd = cmds; cmd->name; cmd++) {
1117 printf("%s %s\n", cmd->name, cmd->arg);
1119 printf("%s", cmd->msg);
1123 static int call_command(struct command *cmds, char *command)
1125 struct command *cmd;
1127 for (cmd = cmds; cmd->name; cmd++) {
1128 if (strcasecmp(cmd->name, command) == 0)
1129 return cmd->func(cmd);
1131 printf("Invalid command: %s\n", command);
1135 static int cmd_help(struct command *cmd)
1137 if (!g_argv[optind]) {
1141 return print_command_usage(cmds, g_argv[optind]);
1144 static void usage(void)
1146 printf("Usage: evmctl <command> [parameters..]\n");
1148 print_all_usage(cmds);
1151 struct command cmds[] = {
1152 {"help", cmd_help, 0, "<command>"},
1153 {"import", cmd_import, 0, "[--bin] inkey keyring", "Import public key (PEM/bin) into the keyring.\n"},
1154 {"convert", cmd_convert, 0, "inkey outkey", "Convert PEM public key into IMA/EVM kernel friendly format.\n"},
1155 {"sign", cmd_sign_evm, 0, "[--imahash | --imasig ] file [key]", "Sign file metadata.\n"},
1156 {"verify", cmd_verify_evm, 0, "file", "Verify EVM signature (for debugging).\n"},
1157 {"ima_sign", cmd_sign_ima, 0, "[--sigfile] file [key]", "Sign file content.\n"},
1158 {"ima_hash", cmd_hash_ima, 0, "file", "Hash file content.\n"},
1159 {"hmac", cmd_hmac_evm, 0, "[--imahash | --imasig ] file [key]", "Sign file metadata with HMAC (for debugging).\n"},
1163 static struct option opts[] = {
1164 {"help", 0, 0, 'h'},
1165 {"inkey", 1, 0, 'k'},
1166 {"imasig", 0, 0, 's'},
1167 {"imahash", 0, 0, 'd'},
1168 {"hashalgo", 1, 0, 'a'},
1170 {"pass", 1, 0, 'p'},
1171 {"sigfile", 0, 0, 'f'},
1176 int main(int argc, char *argv[])
1178 int err = 0, c, lind;
1184 c = getopt_long(argc, argv, "hk:vnsda:bp:f", opts, &lind);
1194 printf("inkey: %s\n", optarg);
1206 /* do not set Extended Attributes... just print signature */
1225 log_err("getopt() returned: %d (%c)\n", c, c);
1229 OpenSSL_add_all_algorithms();
1230 ERR_load_crypto_strings();
1232 if (argv[optind] == NULL)
1235 err = call_command(cmds, argv[optind++]);
1238 log_err("error: %s\n", ERR_error_string(ERR_get_error(), NULL));