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 time_t timestamp; /* key made, always 0 for now */
115 } __attribute__ ((packed));
118 struct signature_hdr {
119 uint8_t version; /* signature format version */
120 time_t timestamp; /* signature made */
126 } __attribute__ ((packed));
129 static char *evm_config_xattrnames[] = {
133 "security.capability",
139 int (*func)(struct command *cmd);
142 char *msg; /* extra info message */
145 static int verbose = LOG_INFO - 1;
147 static char **g_argv;
148 static int set_xattr = 1;
149 static int digest = 0;
150 static int digsig = 0;
151 static char *hash_algo = "sha1";
152 static int binkey = 0;
153 static char *keypass;
155 extern struct command cmds[];
156 static void print_usage(struct command *cmd);
158 static void do_dump(FILE *fp, const void *ptr, int len)
161 uint8_t *data = (uint8_t *)ptr;
163 for (i = 0; i < len; i++) {
164 fprintf(fp, "%02x", data[i]);
169 static void dump(const void *ptr, int len)
171 do_dump(stdout, ptr, len);
174 static inline int get_filesize(const char *filename)
177 /* Need to know the file length */
178 stat(filename, &stats);
179 return (int) stats.st_size;
182 static inline int get_fdsize(int fd)
185 /* Need to know the file length */
187 return (int) stats.st_size;
190 static int bin2file(const char *file, const char *ext, const unsigned char *data, int len)
193 char name[strlen(file) + (ext ? strlen(ext) : 0) + 2];
197 sprintf(name, "%s.%s", file, ext);
199 sprintf(name, "%s", file);
201 log_info("Writing to %s\n", name);
203 fp = fopen(name, "w");
205 log_errno("Unable to open %s for writing", name);
208 err = fwrite(data, len, 1, fp);
213 static char *file2bin(const char *file, int *size)
219 len = get_filesize(file);
220 fp = fopen(file, "r");
222 log_errno("Unable to open %s", file);
226 if (!fread(data, len, 1, fp))
235 * Create binary key representation suitable for kernel
237 static int key2bin(RSA *key, unsigned char *pub)
239 int len, b, offset = 0;
240 struct pubkey_hdr *pkh = (struct pubkey_hdr *)pub;
244 pkh->timestamp = 0; /* PEM has no timestamp?? */
245 pkh->algo = PUBKEY_ALGO_RSA;
248 offset += sizeof(*pkh);
251 len = BN_num_bytes(key->n);
252 b = BN_num_bits(key->n);
253 pub[offset++] = b >> 8;
254 pub[offset++] = b & 0xff;
255 BN_bn2bin(key->n, &pub[offset]);
258 len = BN_num_bytes(key->e);
259 b = BN_num_bits(key->e);
260 pub[offset++] = b >> 8;
261 pub[offset++] = b & 0xff;
262 BN_bn2bin(key->e, &pub[offset]);
268 static int read_key(const char *inkey, unsigned char *pub)
271 RSA *key = NULL, *key1;
274 fp = fopen(inkey, "r");
276 log_errno("read key failed from file %s", inkey);
280 key1 = PEM_read_RSA_PUBKEY(fp, &key, NULL, NULL);
283 log_errno("PEM_read_RSA_PUBKEY() failed");
287 len = key2bin(key, pub);
295 static void calc_keyid(uint8_t *keyid, char *str, const unsigned char *pkey, int len)
297 uint8_t sha1[SHA_DIGEST_LENGTH];
300 log_debug("pkey:\n");
301 log_debug_dump(pkey, len);
302 SHA1(pkey, len, sha1);
304 //sha1[12 - 19] is exactly keyid from gpg file
305 memcpy(keyid, sha1 + 12, 8);
306 log_debug("keyid:\n");
307 log_debug_dump(keyid, 8);
309 id = __be64_to_cpup((__be64 *)keyid);
310 sprintf(str, "%llX", (unsigned long long)id);
311 log_info("keyid: %s\n", str);
314 static int sign_hash(const unsigned char *hash, int size, const char *keyfile, unsigned char *sig)
318 unsigned char pub[1024];
319 RSA *key = NULL, *key1;
322 unsigned char sighash[20];
323 struct signature_hdr *hdr = (struct signature_hdr *)sig;
327 log_dump(hash, size);
329 fp = fopen(keyfile, "r");
331 log_errno("Unable to open keyfile %s", keyfile);
334 key1 = PEM_read_RSAPrivateKey(fp, &key, NULL, keypass);
337 log_errno("RSAPrivateKey() failed");
341 /* now create a new hash */
343 time(&hdr->timestamp);
344 hdr->algo = PUBKEY_ALGO_RSA;
345 hdr->hash = DIGEST_ALGO_SHA1;
347 len = key2bin(key, pub);
348 calc_keyid(hdr->keyid, name, pub, len);
353 SHA1_Update(&ctx, hash, size);
354 SHA1_Update(&ctx, hdr, sizeof(*hdr));
355 SHA1_Final(sighash, &ctx);
356 log_info("sighash: ");
357 log_dump(sighash, sizeof(sighash));
359 err = RSA_private_encrypt(sizeof(sighash), sighash, sig + sizeof(*hdr) + 2, key, RSA_PKCS1_PADDING);
362 log_errno("RSA_private_encrypt() failed: %d", err);
368 /* we add bit length of the signature to make it gnupg compatible */
369 blen = (uint16_t *)(sig + sizeof(*hdr));
370 *blen = __cpu_to_be16(len << 3);
371 len += sizeof(*hdr) + 2;
372 log_info("evm/ima signature: %d bytes\n", len);
373 if (!set_xattr || verbose >= LOG_INFO)
379 static int calc_evm_hash(const char *file, const char *keyfile, unsigned char *hash)
388 char xattr_value[1024];
392 log_errno("Unable to open %s", file);
396 if (fstat(fd, &st)) {
397 log_errno("fstat() failed");
401 if (ioctl(fd, EXT34_IOC_GETVERSION, &generation)) {
402 log_errno("ioctl() failed");
408 log_info("generation: %u\n", generation);
410 md = EVP_get_digestbyname("sha1");
412 log_errno("EVP_get_digestbyname() failed");
416 err = EVP_DigestInit(&ctx, md);
418 log_errno("EVP_DigestInit() failed");
422 for (xattrname = evm_config_xattrnames; *xattrname != NULL; xattrname++) {
423 err = getxattr(file, *xattrname, xattr_value, sizeof(xattr_value));
425 log_info("no attr: %s\n", *xattrname);
428 //log_debug("name: %s, value: %s, size: %d\n", *xattrname, xattr_value, err);
429 log_info("name: %s, size: %d\n", *xattrname, err);
430 log_debug_dump(xattr_value, err);
431 err = EVP_DigestUpdate(&ctx, xattr_value, err);
433 log_errno("EVP_DigestUpdate() failed");
438 memset(&hmac_misc, 0, sizeof(hmac_misc));
439 hmac_misc.ino = st.st_ino;
440 hmac_misc.generation = generation;
441 hmac_misc.uid = st.st_uid;
442 hmac_misc.gid = st.st_gid;
443 hmac_misc.mode = st.st_mode;
445 err = EVP_DigestUpdate(&ctx, (const unsigned char*)&hmac_misc, sizeof(hmac_misc));
447 log_errno("EVP_DigestUpdate() failed");
450 err = EVP_DigestFinal(&ctx, hash, &mdlen);
452 log_errno("EVP_DigestFinal() failed");
459 static int sign_evm(const char *file, const char *key)
461 unsigned char hash[20];
462 unsigned char sig[1024] = "\x03";
465 calc_evm_hash(file, key, hash);
467 err = sign_hash(hash, sizeof(hash), key, sig + 1);
472 err = setxattr(file, "security.evm", sig, err + 1, 0);
474 log_errno("setxattr failed: %s", file);
482 static int calc_file_hash(const char *file, uint8_t *hash)
487 int err, size, bs = DATA_SIZE;
494 log_errno("malloc failed");
498 fp = fopen(file, "r");
500 log_errno("Unable to open %s", file);
504 md = EVP_get_digestbyname(hash_algo);
506 log_errno("EVP_get_digestbyname() failed");
510 err = EVP_DigestInit(&ctx, md);
512 log_errno("EVP_DigestInit() failed");
516 for (size = get_fdsize(fileno(fp)); size; size -= len) {
518 err = fread(data, len, 1, fp);
521 log_errno("fread() error\n");
526 err = EVP_DigestUpdate(&ctx, data, len);
528 log_errno("EVP_DigestUpdate() failed");
533 err = EVP_DigestFinal(&ctx, hash, &mdlen);
535 log_errno("EVP_DigestFinal() failed");
547 struct dirent_list *next;
551 static int calc_dir_hash(const char *file, uint8_t *hash)
559 struct dirent_list *head = NULL, *pos, *prev, *cur;
564 log_errno("Unable to open %s", file);
568 md = EVP_get_digestbyname(hash_algo);
570 log_errno("EVP_get_digestbyname() failed");
574 err = EVP_DigestInit(&ctx, md);
576 log_errno("EVP_DigestInit() failed");
580 while ((de = readdir(dir))) {
581 //printf("entry: ino: %lu, %s\n", de->d_ino, de->d_name);
582 for (prev = NULL, pos = head; pos; prev = pos, pos = pos->next) {
583 if (de->d_ino < pos->de.d_ino)
586 cur = malloc(sizeof(*cur));
595 for (cur = head; cur; cur = pos) {
598 log_debug("entry: ino: %llu, %s\n", (unsigned long long)ino, cur->de.d_name);
599 err = EVP_DigestUpdate(&ctx, cur->de.d_name, strlen(cur->de.d_name));
601 log_errno("EVP_DigestUpdate() failed");
604 err = EVP_DigestUpdate(&ctx, &ino, sizeof(ino));
606 log_errno("EVP_DigestUpdate() failed");
612 err = EVP_DigestFinal(&ctx, hash, &mdlen);
614 log_errno("EVP_DigestFinal() failed");
623 static int hash_ima(const char *file)
625 unsigned char hash[65] = "\x01";// MAX hash size + 1
629 /* Need to know the file length */
630 err = stat(file, &st);
632 log_errno("stat() failed");
636 if (S_ISDIR(st.st_mode))
637 err = calc_dir_hash(file, hash + 1);
639 err = calc_file_hash(file, hash + 1);
643 if (verbose >= LOG_INFO)
646 if (!set_xattr || verbose >= LOG_INFO)
650 err = setxattr(file, "security.ima", hash, err + 1, 0);
652 log_errno("setxattr failed: %s", file);
660 static int cmd_hash_ima(struct command *cmd)
662 char *file = g_argv[optind++];
665 log_err("Parameters missing\n");
670 return hash_ima(file);
673 static int sign_ima(const char *file, const char *key)
675 unsigned char hash[64];
676 unsigned char sig[1024] = "\x03";
679 err = calc_file_hash(file, hash);
683 err = sign_hash(hash, err, key, sig + 1);
688 err = setxattr(file, "security.ima", sig, err + 1, 0);
690 log_errno("setxattr failed: %s", file);
698 static int cmd_sign_ima(struct command *cmd)
700 char *key, *file = g_argv[optind++];
703 log_err("Parameters missing\n");
708 key = g_argv[optind++];
710 key = "/etc/keys/privkey_evm.pem";
712 return sign_ima(file, key);
716 static int cmd_sign_evm(struct command *cmd)
718 char *key, *file = g_argv[optind++];
722 log_err("Parameters missing\n");
727 key = g_argv[optind++];
729 key = "/etc/keys/privkey_evm.pem";
732 err = sign_ima(file, key);
738 err = hash_ima(file);
743 return sign_evm(file, key);
746 static int verify_hash(const unsigned char *hash, int size, unsigned char *sig, int siglen, const char *keyfile)
750 unsigned char out[1024];
751 RSA *key = NULL, *key1;
753 unsigned char sighash[20];
754 struct signature_hdr *hdr = (struct signature_hdr *)sig;
757 log_dump(hash, size);
759 fp = fopen(keyfile, "r");
761 log_errno("Unable to open keyfile %s", keyfile);
764 key1 = PEM_read_RSA_PUBKEY(fp, &key, NULL, NULL);
767 log_errno("PEM_read_RSA_PUBKEY() failed");
772 SHA1_Update(&ctx, hash, size);
773 SHA1_Update(&ctx, hdr, sizeof(*hdr));
774 SHA1_Final(sighash, &ctx);
775 log_info("sighash: ");
776 log_dump(sighash, sizeof(sighash));
778 err = RSA_public_decrypt(siglen - sizeof(*hdr) - 2, sig + sizeof(*hdr) + 2, out, key, RSA_PKCS1_PADDING);
781 log_errno("RSA_public_decrypt() failed: %d", err);
787 if (len != sizeof(sighash) || memcmp(out, sighash, len) != 0) {
788 log_errno("Verification failed: %d", err);
791 //log_info("Verification is OK\n");
792 printf("Verification is OK\n");
798 static int verify_evm(const char *file, const char *key)
800 unsigned char hash[20];
801 unsigned char sig[1024];
804 calc_evm_hash(file, key, hash);
806 err = getxattr(file, "security.evm", sig, sizeof(sig));
808 log_errno("getxattr failed");
812 if (sig[0] != 0x03) {
813 log_errno("security.evm has not signature");
817 return verify_hash(hash, sizeof(hash), sig + 1, err - 1, key);
820 static int cmd_verify_evm(struct command *cmd)
822 char *key, *file = g_argv[optind++];
825 log_err("Parameters missing\n");
830 key = g_argv[optind++];
832 key = "/etc/keys/pubkey_evm.pem";
834 return verify_evm(file, key);
837 static int cmd_convert(struct command *cmd)
839 char *inkey, *outkey = NULL;
840 unsigned char pub[1024];
845 inkey = g_argv[optind++];
847 inkey = "/etc/keys/pubkey_evm.pem";
849 outkey = g_argv[optind++];
852 outkey = "pubkey_evm.bin";
854 log_info("Convert public key %s to %s\n", inkey, outkey);
856 len = read_key(inkey, pub);
860 calc_keyid(keyid, name, pub, len);
862 bin2file(outkey, name, pub, len);
867 static int cmd_import_bin(struct command *cmd)
870 char *inkey, *ring = NULL;
875 inkey = g_argv[optind++];
877 inkey = "/etc/keys/pubkey_evm.bin";
879 ring = g_argv[optind++];
882 id = KEY_SPEC_USER_KEYRING;
886 key = file2bin(inkey, &len);
890 calc_keyid(keyid, name, (unsigned char *)key, len);
892 log_info("Importing public key %s from file %s into keyring %d\n", name, inkey, id);
894 id = add_key("user", name, key, len, id);
896 log_errno("add_key failed");
900 log_info("keyid: %d\n", id);
908 static int cmd_import(struct command *cmd)
910 char *inkey, *ring = NULL;
911 unsigned char key[1024];
917 return cmd_import_bin(cmd);
919 inkey = g_argv[optind++];
921 inkey = "/etc/keys/pubkey_evm.pem";
923 ring = g_argv[optind++];
926 id = KEY_SPEC_USER_KEYRING;
930 len = read_key(inkey, key);
934 calc_keyid(keyid, name, key, len);
936 log_info("Importing public key %s from file %s into keyring %d\n", name, inkey, id);
938 id = add_key("user", name, key, len, id);
940 log_errno("add_key failed");
944 log_info("keyid: %d\n", id);
950 #define MAX_KEY_SIZE 128
952 static int calc_evm_hmac(const char *file, const char *keyfile, unsigned char *hash)
960 unsigned char xattr_value[1024];
963 unsigned char evmkey[MAX_KEY_SIZE];
965 key = file2bin(keyfile, &keylen);
967 log_errno("Unable to read a key: %s\n", keyfile);
971 if (keylen > sizeof(evmkey)) {
972 log_errno("key is too long\n");
976 /* EVM key is 128 bytes */
977 memcpy(evmkey, key, keylen);
978 memset(evmkey + keylen, 0, sizeof(evmkey) - keylen);
982 log_errno("Unable to open %s", file);
986 if (fstat(fd, &st)) {
987 log_errno("fstat() failed");
991 if (ioctl(fd, EXT34_IOC_GETVERSION, &generation)) {
992 log_errno("ioctl() failed");
998 log_info("generation: %u\n", generation);
1000 HMAC_Init(&ctx, evmkey, sizeof(evmkey), EVP_sha1());
1002 for (xattrname = evm_config_xattrnames; *xattrname != NULL; xattrname++) {
1003 err = getxattr(file, *xattrname, xattr_value, sizeof(xattr_value));
1005 log_info("no attr: %s\n", *xattrname);
1008 //log_debug("name: %s, value: %s, size: %d\n", *xattrname, xattr_value, err);
1009 log_info("name: %s, size: %d\n", *xattrname, err);
1010 log_debug_dump(xattr_value, err);
1011 HMAC_Update(&ctx, xattr_value, err);
1014 memset(&hmac_misc, 0, sizeof(hmac_misc));
1015 hmac_misc.ino = st.st_ino;
1016 hmac_misc.generation = generation;
1017 hmac_misc.uid = st.st_uid;
1018 hmac_misc.gid = st.st_gid;
1019 hmac_misc.mode = st.st_mode;
1021 HMAC_Update(&ctx, (const unsigned char*)&hmac_misc, sizeof(hmac_misc));
1022 HMAC_Final(&ctx, hash, &mdlen);
1023 HMAC_CTX_cleanup(&ctx);
1030 static int hmac_evm(const char *file, const char *key)
1032 unsigned char hash[20];
1033 unsigned char sig[1024] = "\x02";
1036 calc_evm_hmac(file, key, hash);
1039 log_dump(hash, sizeof(hash));
1040 memcpy(sig + 1, hash, sizeof(hash));
1044 err = setxattr(file, "security.evm", sig, err + 1, 0);
1046 log_errno("setxattr failed: %s", file);
1054 static int cmd_hmac_evm(struct command *cmd)
1056 char *key, *file = g_argv[optind++];
1060 log_err("Parameters missing\n");
1065 key = g_argv[optind++];
1067 key = "/etc/keys/privkey_evm.pem";
1070 err = sign_ima(file, key);
1076 err = hash_ima(file);
1081 return hmac_evm(file, "/etc/keys/evm-key-plain");
1084 static void print_usage(struct command *cmd)
1086 printf("usage: %s %s\n", cmd->name, cmd->arg ? cmd->arg : "");
1089 static void print_full_usage(struct command *cmd)
1092 printf("usage: %s %s\n", cmd->name, cmd->arg ? cmd->arg : "");
1094 printf("description:\n%s", cmd->msg);
1098 static int print_command_usage(struct command *cmds, char *command)
1100 struct command *cmd;
1102 for (cmd = cmds; cmd->name; cmd++) {
1103 if (strcmp(cmd->name, command) == 0) {
1104 print_full_usage(cmd);
1108 printf("invalid command: %s\n", command);
1112 static void print_all_usage(struct command *cmds)
1114 struct command *cmd;
1116 for (cmd = cmds; cmd->name; cmd++) {
1118 printf("%s %s\n", cmd->name, cmd->arg);
1120 printf("%s", cmd->msg);
1124 static int call_command(struct command *cmds, char *command)
1126 struct command *cmd;
1128 for (cmd = cmds; cmd->name; cmd++) {
1129 if (strcasecmp(cmd->name, command) == 0)
1130 return cmd->func(cmd);
1132 printf("Invalid command: %s\n", command);
1136 static int cmd_help(struct command *cmd)
1138 if (!g_argv[optind]) {
1142 return print_command_usage(cmds, g_argv[optind]);
1145 static void usage(void)
1147 printf("Usage: evmctl <command> [parameters..]\n");
1149 print_all_usage(cmds);
1152 struct command cmds[] = {
1153 {"help", cmd_help, 0, "<command>"},
1154 {"import", cmd_import, 0, "[--bin] inkey keyring", "Import public key (PEM/bin) into the keyring.\n" },
1155 {"convert", cmd_convert, 0, "inkey outkey", "Convert PEM public key into IMA/EVM kernel friendly format.\n" },
1156 {"sign", cmd_sign_evm, 0, "[--imahash | --imasig ] file [key]", "Sign file metadata.\n" },
1157 {"verify", cmd_verify_evm, 0, "file", "Verify EVM signature (for debugging).\n" },
1158 {"ima_sign", cmd_sign_ima, 0, "file [key]", "Sign file content.\n" },
1159 {"ima_hash", cmd_hash_ima, 0, "file", "Hash file content.\n" },
1160 {"hmac", cmd_hmac_evm, 0, "[--imahash | --imasig ] file [key]", "Sign file metadata with HMAC (for debugging).\n" },
1164 static struct option opts[] = {
1165 {"help", 0, 0, 'h'},
1166 {"inkey", 1, 0, 'k'},
1167 {"imasig", 0, 0, 's'},
1168 {"imahash", 0, 0, 'd'},
1169 {"hashalgo", 1, 0, 'a'},
1171 {"pass", 1, 0, 'p'},
1176 int main(int argc, char *argv[])
1178 int err = 0, c, lind;
1184 c = getopt_long(argc, argv, "hk:vnsda:bp:", opts, &lind);
1194 printf("inkey: %s\n", optarg);
1206 set_xattr = 0; // do not set Extended Attributes... just print signature
1221 log_err("getopt() returned: %d (%c)\n", c, c);
1225 OpenSSL_add_all_algorithms();
1226 ERR_load_crypto_strings();
1228 if (argv[optind] == NULL)
1231 err = call_command(cmds, argv[optind++]);
1234 log_err("error: %s\n", ERR_error_string(ERR_get_error(), NULL));