2 * ima-evm-utils - IMA/EVM support utilities
4 * Copyright (C) 2011 Nokia Corporation
5 * Copyright (C) 2011,2012,2013 Intel Corporation
6 * Copyright (C) 2013,2014 Samsung Electronics
9 * Dmitry Kasatkin <dmitry.kasatkin@nokia.com>
10 * <dmitry.kasatkin@intel.com>
11 * <d.kasatkin@samsung.com>
12 * Pawel Polawski <p.polawski@samsung.com>
14 * This program is free software; you can redistribute it and/or
15 * modify it under the terms of the GNU General Public License
16 * version 2 as published by the Free Software Foundation.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License
24 * along with this program. If not, see <http://www.gnu.org/licenses/>.
26 * As a special exception, the copyright holders give permission to link the
27 * code of portions of this program with the OpenSSL library under certain
28 * conditions as described in each individual source file and distribute
29 * linked combinations including the program with the OpenSSL library. You
30 * must comply with the GNU General Public License in all respects
31 * for all of the code used other than as permitted herein. If you modify
32 * file(s) with this exception, you may extend this exception to your
33 * version of the file(s), but you are not obligated to do so. If you do not
34 * wish to do so, delete this exception statement from your version. If you
35 * delete this exception statement from all source files in the program,
36 * then also delete it in the license file.
42 /* should we use logger instead for library? */
45 #include <sys/types.h>
46 #include <sys/param.h>
48 #include <asm/byteorder.h>
49 #include <attr/xattr.h>
57 #include <openssl/pem.h>
58 #include <openssl/evp.h>
59 #include <openssl/x509.h>
63 const char *const pkey_hash_algo[PKEY_HASH__LAST] = {
64 [PKEY_HASH_MD4] = "md4",
65 [PKEY_HASH_MD5] = "md5",
66 [PKEY_HASH_SHA1] = "sha1",
67 [PKEY_HASH_RIPE_MD_160] = "rmd160",
68 [PKEY_HASH_SHA256] = "sha256",
69 [PKEY_HASH_SHA384] = "sha384",
70 [PKEY_HASH_SHA512] = "sha512",
71 [PKEY_HASH_SHA224] = "sha224",
75 * Hash algorithm OIDs plus ASN.1 DER wrappings [RFC4880 sec 5.2.2].
77 static const uint8_t RSA_digest_info_MD5[] = {
78 0x30, 0x20, 0x30, 0x0C, 0x06, 0x08,
79 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x05, /* OID */
80 0x05, 0x00, 0x04, 0x10
83 static const uint8_t RSA_digest_info_SHA1[] = {
84 0x30, 0x21, 0x30, 0x09, 0x06, 0x05,
85 0x2B, 0x0E, 0x03, 0x02, 0x1A,
86 0x05, 0x00, 0x04, 0x14
89 static const uint8_t RSA_digest_info_RIPE_MD_160[] = {
90 0x30, 0x21, 0x30, 0x09, 0x06, 0x05,
91 0x2B, 0x24, 0x03, 0x02, 0x01,
92 0x05, 0x00, 0x04, 0x14
95 static const uint8_t RSA_digest_info_SHA224[] = {
96 0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09,
97 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04,
98 0x05, 0x00, 0x04, 0x1C
101 static const uint8_t RSA_digest_info_SHA256[] = {
102 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09,
103 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01,
104 0x05, 0x00, 0x04, 0x20
107 static const uint8_t RSA_digest_info_SHA384[] = {
108 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09,
109 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02,
110 0x05, 0x00, 0x04, 0x30
113 static const uint8_t RSA_digest_info_SHA512[] = {
114 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09,
115 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03,
116 0x05, 0x00, 0x04, 0x40
119 const struct RSA_ASN1_template RSA_ASN1_templates[PKEY_HASH__LAST] = {
120 #define _(X) { RSA_digest_info_##X, sizeof(RSA_digest_info_##X) }
121 [PKEY_HASH_MD5] = _(MD5),
122 [PKEY_HASH_SHA1] = _(SHA1),
123 [PKEY_HASH_RIPE_MD_160] = _(RIPE_MD_160),
124 [PKEY_HASH_SHA256] = _(SHA256),
125 [PKEY_HASH_SHA384] = _(SHA384),
126 [PKEY_HASH_SHA512] = _(SHA512),
127 [PKEY_HASH_SHA224] = _(SHA224),
131 struct libevm_params params = {
132 .verbose = LOG_INFO - 1,
137 void do_dump(FILE *fp, const void *ptr, int len, bool cr)
140 uint8_t *data = (uint8_t *) ptr;
142 for (i = 0; i < len; i++)
143 fprintf(fp, "%02x", data[i]);
148 void dump(const void *ptr, int len)
150 do_dump(stdout, ptr, len, true);
153 int get_filesize(const char *filename)
156 /* Need to know the file length */
157 stat(filename, &stats);
158 return (int)stats.st_size;
161 static inline off_t get_fdsize(int fd)
164 /* Need to know the file length */
166 return stats.st_size;
169 static int add_file_hash(const char *file, EVP_MD_CTX *ctx)
172 int err = -1, bs = DATA_SIZE;
176 fp = fopen(file, "r");
178 log_err("Failed to open: %s\n", file);
184 log_err("malloc failed\n");
188 for (size = get_fdsize(fileno(fp)); size; size -= len) {
190 if (!fread(data, len, 1, fp)) {
192 log_err("fread() failed\n\n");
197 if (!EVP_DigestUpdate(ctx, data, len)) {
198 log_err("EVP_DigestUpdate() failed\n");
211 static int add_dir_hash(const char *file, EVP_MD_CTX *ctx)
216 unsigned long long ino, off;
221 log_err("Failed to open: %s\n", file);
225 while ((de = readdir(dir))) {
229 log_debug("entry: %s, ino: %llu, type: %u, off: %llu, reclen: %hu\n",
230 de->d_name, ino, type, off, de->d_reclen);
231 err = EVP_DigestUpdate(ctx, de->d_name, strlen(de->d_name));
232 /*err |= EVP_DigestUpdate(ctx, &off, sizeof(off));*/
233 err |= EVP_DigestUpdate(ctx, &ino, sizeof(ino));
234 err |= EVP_DigestUpdate(ctx, &type, sizeof(type));
236 log_err("EVP_DigestUpdate() failed\n");
246 static int add_link_hash(const char *path, EVP_MD_CTX *ctx)
251 err = readlink(path, buf, sizeof(buf));
255 log_info("link: %s -> %.*s\n", path, err, buf);
256 return !EVP_DigestUpdate(ctx, buf, err);
259 static int add_dev_hash(struct stat *st, EVP_MD_CTX *ctx)
261 uint32_t dev = st->st_rdev;
262 unsigned major = (dev & 0xfff00) >> 8;
263 unsigned minor = (dev & 0xff) | ((dev >> 12) & 0xfff00);
265 log_info("device: %u:%u\n", major, minor);
266 return !EVP_DigestUpdate(ctx, &dev, sizeof(dev));
269 int ima_calc_hash(const char *file, uint8_t *hash)
277 /* Need to know the file length */
278 err = lstat(file, &st);
280 log_err("Failed to stat: %s\n", file);
284 md = EVP_get_digestbyname(params.hash_algo);
286 log_err("EVP_get_digestbyname() failed\n");
290 err = EVP_DigestInit(&ctx, md);
292 log_err("EVP_DigestInit() failed\n");
296 switch (st.st_mode & S_IFMT) {
298 err = add_file_hash(file, &ctx);
301 err = add_dir_hash(file, &ctx);
304 err = add_link_hash(file, &ctx);
306 case S_IFIFO: case S_IFSOCK:
307 case S_IFCHR: case S_IFBLK:
308 err = add_dev_hash(&st, &ctx);
311 log_errno("Unsupported file type");
318 err = EVP_DigestFinal(&ctx, hash, &mdlen);
320 log_err("EVP_DigestFinal() failed\n");
327 RSA *read_pub_key(const char *keyfile, int x509)
332 EVP_PKEY *pkey = NULL;
334 fp = fopen(keyfile, "r");
336 log_err("Failed to open keyfile: %s\n", keyfile);
341 crt = d2i_X509_fp(fp, NULL);
343 log_err("d2i_X509_fp() failed\n");
346 pkey = X509_extract_key(crt);
348 log_err("X509_extract_key() failed\n");
351 key = EVP_PKEY_get1_RSA(pkey);
353 key = PEM_read_RSA_PUBKEY(fp, NULL, NULL, NULL);
357 log_err("PEM_read_RSA_PUBKEY() failed\n");
368 int verify_hash_v1(const unsigned char *hash, int size, unsigned char *sig, int siglen, const char *keyfile)
372 unsigned char out[1024];
374 unsigned char sighash[20];
375 struct signature_hdr *hdr = (struct signature_hdr *)sig;
378 log_dump(hash, size);
380 key = read_pub_key(keyfile, 0);
385 SHA1_Update(&ctx, hash, size);
386 SHA1_Update(&ctx, hdr, sizeof(*hdr));
387 SHA1_Final(sighash, &ctx);
388 log_info("sighash: ");
389 log_dump(sighash, sizeof(sighash));
391 err = RSA_public_decrypt(siglen - sizeof(*hdr) - 2, sig + sizeof(*hdr) + 2, out, key, RSA_PKCS1_PADDING);
394 log_err("RSA_public_decrypt() failed: %d\n", err);
400 if (len != sizeof(sighash) || memcmp(out, sighash, len) != 0) {
401 log_err("Verification failed: %d\n", err);
404 /*log_info("Verification is OK\n");*/
405 printf("Verification is OK\n");
411 int verify_hash_v2(const unsigned char *hash, int size, unsigned char *sig, int siglen, const char *keyfile)
414 unsigned char out[1024];
416 struct signature_v2_hdr *hdr = (struct signature_v2_hdr *)sig;
417 const struct RSA_ASN1_template *asn1;
420 log_dump(hash, size);
422 key = read_pub_key(keyfile, 1);
426 err = RSA_public_decrypt(siglen - sizeof(*hdr), sig + sizeof(*hdr), out, key, RSA_PKCS1_PADDING);
429 log_err("RSA_public_decrypt() failed: %d\n", err);
435 asn1 = &RSA_ASN1_templates[hdr->hash_algo];
437 if (len < asn1->size || memcmp(out, asn1->data, asn1->size)) {
438 log_err("Verification failed: %d\n", err);
444 if (len != size || memcmp(out + asn1->size, hash, len)) {
445 log_err("Verification failed: %d\n", err);
449 /*log_info("Verification is OK\n");*/
450 printf("Verification is OK\n");
455 int get_hash_algo(const char *algo)
459 for (i = 0; i < PKEY_HASH__LAST; i++)
460 if (!strcmp(algo, pkey_hash_algo[i]))
463 return PKEY_HASH_SHA1;
466 static int get_hash_algo_from_sig(unsigned char *sig)
471 hashalgo = ((struct signature_hdr *)sig)->hash;
473 if (hashalgo >= DIGEST_ALGO_MAX)
477 case DIGEST_ALGO_SHA1:
478 return PKEY_HASH_SHA1;
479 case DIGEST_ALGO_SHA256:
480 return PKEY_HASH_SHA256;
484 } else if (sig[0] == 2) {
485 hashalgo = ((struct signature_v2_hdr *)sig)->hash_algo;
486 if (hashalgo >= PKEY_HASH__LAST)
493 int verify_hash(const unsigned char *hash, int size, unsigned char *sig, int siglen)
497 verify_hash_fn_t verify_hash;
499 /* Get signature type from sig header */
500 if (sig[0] == DIGSIG_VERSION_1) {
501 verify_hash = verify_hash_v1;
502 /* Read pubkey from RSA key */
504 } else if (sig[0] == DIGSIG_VERSION_2) {
505 verify_hash = verify_hash_v2;
506 /* Read pubkey from x509 cert */
511 /* Determine what key to use for verification*/
512 key = params.keyfile ? : x509 ?
513 "/etc/keys/x509_evm.der" :
514 "/etc/keys/pubkey_evm.pem";
516 return verify_hash(hash, size, sig, siglen, key);
519 int ima_verify_signature(const char *file, unsigned char *sig, int siglen)
521 unsigned char hash[64];
522 int hashlen, sig_hash_algo;
524 if (sig[0] != 0x03) {
525 log_err("security.ima has no signature\n");
529 sig_hash_algo = get_hash_algo_from_sig(sig + 1);
530 if (sig_hash_algo < 0) {
531 log_err("Invalid signature\n");
534 /* Use hash algorithm as retrieved from signature */
535 params.hash_algo = pkey_hash_algo[sig_hash_algo];
537 hashlen = ima_calc_hash(file, hash);
541 return verify_hash(hash, hashlen, sig + 1, siglen - 1);
545 * Create binary key representation suitable for kernel
547 int key2bin(RSA *key, unsigned char *pub)
549 int len, b, offset = 0;
550 struct pubkey_hdr *pkh = (struct pubkey_hdr *)pub;
554 pkh->timestamp = 0; /* PEM has no timestamp?? */
555 pkh->algo = PUBKEY_ALGO_RSA;
558 offset += sizeof(*pkh);
560 len = BN_num_bytes(key->n);
561 b = BN_num_bits(key->n);
562 pub[offset++] = b >> 8;
563 pub[offset++] = b & 0xff;
564 BN_bn2bin(key->n, &pub[offset]);
567 len = BN_num_bytes(key->e);
568 b = BN_num_bits(key->e);
569 pub[offset++] = b >> 8;
570 pub[offset++] = b & 0xff;
571 BN_bn2bin(key->e, &pub[offset]);
577 void calc_keyid_v1(uint8_t *keyid, char *str, const unsigned char *pkey, int len)
579 uint8_t sha1[SHA_DIGEST_LENGTH];
582 SHA1(pkey, len, sha1);
584 /* sha1[12 - 19] is exactly keyid from gpg file */
585 memcpy(keyid, sha1 + 12, 8);
586 log_debug("keyid: ");
587 log_debug_dump(keyid, 8);
589 id = __be64_to_cpup((__be64 *) keyid);
590 sprintf(str, "%llX", (unsigned long long)id);
591 log_info("keyid: %s\n", str);
594 void calc_keyid_v2(uint32_t *keyid, char *str, RSA *key)
596 uint8_t sha1[SHA_DIGEST_LENGTH];
597 unsigned char *pkey = NULL;
600 len = i2d_RSAPublicKey(key, &pkey);
602 SHA1(pkey, len, sha1);
604 /* sha1[12 - 19] is exactly keyid from gpg file */
605 memcpy(keyid, sha1 + 16, 4);
606 log_debug("keyid: ");
607 log_debug_dump(keyid, 4);
609 sprintf(str, "%x", __be32_to_cpup(keyid));
610 log_info("keyid: %s\n", str);
615 static RSA *read_priv_key(const char *keyfile, char *keypass)
620 fp = fopen(keyfile, "r");
622 log_err("Failed to open keyfile: %s\n", keyfile);
625 key = PEM_read_RSAPrivateKey(fp, NULL, NULL, keypass);
627 log_err("PEM_read_RSAPrivateKey() failed\n");
633 static int get_hash_algo_v1(const char *algo)
636 if (!strcmp(algo, "sha1"))
637 return DIGEST_ALGO_SHA1;
638 else if (!strcmp(algo, "sha256"))
639 return DIGEST_ALGO_SHA256;
644 int sign_hash_v1(const char *hashalgo, const unsigned char *hash, int size, const char *keyfile, unsigned char *sig)
646 int len = -1, hashalgo_idx;
648 unsigned char pub[1024];
651 unsigned char sighash[20];
652 struct signature_hdr *hdr;
656 log_err("sign_hash_v1: hash is null\n");
661 log_err("sign_hash_v1: size is negative: %d\n", size);
666 log_err("sign_hash_v1: hashalgo is null\n");
671 log_err("sign_hash_v1: sig is null\n");
676 log_dump(hash, size);
678 key = read_priv_key(keyfile, params.keypass);
682 hdr = (struct signature_hdr *)sig;
684 /* now create a new hash */
685 hdr->version = (uint8_t) DIGSIG_VERSION_1;
686 hdr->timestamp = time(NULL);
687 hdr->algo = PUBKEY_ALGO_RSA;
688 hashalgo_idx = get_hash_algo_v1(hashalgo);
689 if (hashalgo_idx < 0) {
690 log_err("Signature version 1 does not support hash algo %s\n",
694 hdr->hash = (uint8_t) hashalgo_idx;
696 len = key2bin(key, pub);
697 calc_keyid_v1(hdr->keyid, name, pub, len);
702 SHA1_Update(&ctx, hash, size);
703 SHA1_Update(&ctx, hdr, sizeof(*hdr));
704 SHA1_Final(sighash, &ctx);
705 log_info("sighash: ");
706 log_dump(sighash, sizeof(sighash));
708 len = RSA_private_encrypt(sizeof(sighash), sighash, sig + sizeof(*hdr) + 2, key, RSA_PKCS1_PADDING);
710 log_err("RSA_private_encrypt() failed: %d\n", len);
714 /* we add bit length of the signature to make it gnupg compatible */
715 blen = (uint16_t *) (sig + sizeof(*hdr));
716 *blen = __cpu_to_be16(len << 3);
717 len += sizeof(*hdr) + 2;
718 log_info("evm/ima signature: %d bytes\n", len);
724 int sign_hash_v2(const char *algo, const unsigned char *hash, int size, const char *keyfile, unsigned char *sig)
726 struct signature_v2_hdr *hdr;
731 const struct RSA_ASN1_template *asn1;
734 log_err("sign_hash_v2: hash is null\n");
739 log_err("sign_hash_v2: size is negative: %d\n", size);
744 log_err("sign_hash_v2: sig is null\n");
749 log_err("sign_hash_v2: algo is null\n");
754 log_dump(hash, size);
756 key = read_priv_key(keyfile, params.keypass);
760 hdr = (struct signature_v2_hdr *)sig;
761 hdr->version = (uint8_t) DIGSIG_VERSION_2;
763 hdr->hash_algo = get_hash_algo(algo);
765 calc_keyid_v2(&hdr->keyid, name, key);
767 asn1 = &RSA_ASN1_templates[hdr->hash_algo];
769 buf = malloc(size + asn1->size);
773 memcpy(buf, asn1->data, asn1->size);
774 memcpy(buf + asn1->size, hash, size);
775 len = RSA_private_encrypt(size + asn1->size, buf, hdr->sig,
776 key, RSA_PKCS1_PADDING);
778 log_err("RSA_private_encrypt() failed: %d\n", len);
782 /* we add bit length of the signature to make it gnupg compatible */
783 hdr->sig_size = __cpu_to_be16(len);
785 log_info("evm/ima signature: %d bytes\n", len);
793 int sign_hash(const char *hashalgo, const unsigned char *hash, int size, const char *keyfile, unsigned char *sig)
795 return params.x509 ? sign_hash_v2(hashalgo, hash, size, keyfile, sig) :
796 sign_hash_v1(hashalgo, hash, size, keyfile, sig);
799 #define IMA_STATE_PATH "/sys/kernel/security/ima/ima_state"
800 #define IMA_XATTR "security.ima"
802 #define EVM_STATE_PATH "/sys/kernel/security/evm"
803 #define EVM_XATTR "security.evm"
805 #define IMA_POLICY_INTERFACE "/sys/kernel/security/ima/policy"
806 #define IMA_POLICY_TMP_DIR "/tmp/"
807 #define IMA_POLICY_TMP_FILE_PREFIX "ima_"
808 #define IMA_POLICY_SIGNATRURE_EXTENSION ".sig"
810 int ima_get_state(int *state)
816 log_err("Error input param\n");
817 return LIB_ERROR_INPUT_PARAM;
820 fd = open(IMA_STATE_PATH, O_RDONLY);
822 log_err("Unable to open file\n");
823 return LIB_ERROR_SYSCALL;
826 if (read(fd, &buff, sizeof(buff)) < 0) {
827 log_err("Unable to read file\n");
829 return LIB_ERROR_SYSCALL;
836 *state = IMA_STATE_DISABLED;
839 *state = IMA_STATE_IGNORE;
842 *state = IMA_STATE_ENFORCE;
845 *state = IMA_STATE_FIX;
848 log_err("Unknown IMA state\n");
849 return LIB_ERROR_UNKNOWN;
853 int ima_set_state(int state)
857 int fd = open(IMA_STATE_PATH, O_RDWR);
859 log_err("Unable to open file\n");
860 return LIB_ERROR_SYSCALL;
864 case IMA_STATE_DISABLED:
867 case IMA_STATE_IGNORE:
870 case IMA_STATE_ENFORCE:
877 log_err("Wrong IMA state\n");
879 return LIB_ERROR_INPUT_PARAM;
882 if (write(fd, &buff, sizeof(buff)) < 0) {
883 log_err("Unable to write file\n");
885 return LIB_ERROR_SYSCALL;
892 int evm_get_state(int *state)
898 log_err("Error input param\n");
899 return LIB_ERROR_INPUT_PARAM;
902 fd = open(EVM_STATE_PATH, O_RDONLY);
904 log_err("Unable to open file\n");
905 return LIB_ERROR_SYSCALL;
908 if (read(fd, &buff, sizeof(buff)) < 0) {
909 log_err("Unable to read file\n");
911 return LIB_ERROR_SYSCALL;
918 *state = EVM_STATE_DISABLED;
921 *state = EVM_STATE_ENABLED;
924 *state = EVM_STATE_FIX;
927 log_err("Unknown EVM state\n");
928 return LIB_ERROR_UNKNOWN;
932 int evm_set_state(int state)
936 int fd = open(EVM_STATE_PATH, O_RDWR);
938 log_err("Unable to open file\n");
939 return LIB_ERROR_SYSCALL;
943 case EVM_STATE_DISABLED:
946 case EVM_STATE_ENABLED:
953 log_err("Wrong EVM state\n");
955 return LIB_ERROR_UNKNOWN;
958 if (write(fd, &buff, sizeof(buff)) < 0) {
959 log_err("Unable to write file\n");
961 return LIB_ERROR_SYSCALL;
968 int ima_set_xattr(const char *path)
973 log_err("Error input param\n");
974 return LIB_ERROR_INPUT_PARAM;
977 ret = setxattr(path, IMA_XATTR, hash, strlen(hash), 0);
979 log_err("Unable to set xattr\n");
980 return LIB_ERROR_SYSCALL;
986 int ima_get_xattr(const char *path, char **hash)
990 if (!path || !hash) {
991 log_err("Error input param\n");
992 return LIB_ERROR_INPUT_PARAM;
995 //read xattr size only
996 ret = getxattr(path, IMA_XATTR, NULL, 0);
998 if (errno == ENOATTR) {
999 log_err("Missing attribute or no access\n");
1000 return LIB_ERROR_ATTRIBUTE;
1002 log_err("Error in read xattr\n");
1003 return LIB_ERROR_SYSCALL;
1006 *hash = calloc(ret + 1, sizeof(char));
1008 log_err("Allocation error\n");
1009 return LIB_ERROR_MEMORY;
1012 ret = getxattr(path, IMA_XATTR, *hash, ret);
1014 if (errno == ENOATTR) {
1015 log_err("Missing attribute or no access\n");
1016 return LIB_ERROR_ATTRIBUTE;
1018 log_err("Error in read xattr\n");
1020 return LIB_ERROR_SYSCALL;
1026 int evm_set_xattr(const char *path, const char *evm)
1030 if (!path || !evm) {
1031 log_err("Error input param\n");
1032 return LIB_ERROR_INPUT_PARAM;
1035 ret = setxattr(path, EVM_XATTR, evm, strlen(evm), 0);
1037 log_err("Unable to set xattr\n");
1038 return LIB_ERROR_SYSCALL;
1044 int evm_get_xattr(const char *path, char **hash)
1048 if (!path || !hash) {
1049 log_err("Error input param\n");
1050 return LIB_ERROR_INPUT_PARAM;
1053 //read xattr size only
1054 ret = getxattr(path, EVM_XATTR, NULL, 0);
1056 if (errno == ENOATTR) {
1057 log_err("Missing attribute or no access\n");
1058 return LIB_ERROR_ATTRIBUTE;
1060 log_err("Error in read xattr\n");
1061 return LIB_ERROR_SYSCALL;
1064 *hash = calloc(ret + 1, sizeof(char));
1066 log_err("Allocation error\n");
1067 return LIB_ERROR_MEMORY;
1070 ret = getxattr(path, EVM_XATTR, *hash, ret);
1072 if (errno == ENOATTR) {
1073 log_err("Missing attribute or no access\n");
1074 return LIB_ERROR_ATTRIBUTE;
1076 log_err("Error in read xattr\n");
1078 return LIB_ERROR_SYSCALL;
1084 int ima_get_policy(char*** policy)
1087 char *policy_tmp = NULL;
1093 int ret_code = LIB_SUCCESS;
1097 return LIB_ERROR_INPUT_PARAM;
1099 int fd = open(IMA_POLICY_INTERFACE, O_RDONLY);
1101 log_err("Unable to open %s file\n", IMA_POLICY_INTERFACE);
1102 return LIB_ERROR_SYSCALL;
1105 // Read policy from fd to policy_tmp;
1107 ret = read(fd, &buff, sizeof(buff));
1109 log_err("Unable to read %s file\n", IMA_POLICY_INTERFACE);
1110 ret_code = LIB_ERROR_SYSCALL;
1113 last = realloc(policy_tmp, length + ret + 1);
1114 if (!last) { // realloc error
1115 ret_code = LIB_ERROR_MEMORY;
1119 memcpy(&(policy_tmp[length]), buff, ret);
1121 } while (ret == (int) sizeof(buff)); // If not whole buffer was filled then it means that the
1122 // whole policy was read. Exit the while loop.
1123 policy_tmp[length] = '\0';
1125 if (length <= 1) { // Empty policy;
1126 *policy = malloc(sizeof(char*));
1128 ret_code = LIB_ERROR_MEMORY;
1131 (*policy)[0] = NULL;
1137 rules_count = 1; // Start counting from 1 because there can be one more rule then new line sign
1138 while ((last = strchr(last, '\n'))) {
1139 last += sizeof(char);
1143 *policy = malloc(sizeof(char*) * (rules_count + 1)); // +1 because this is null terminated list
1145 ret_code = LIB_ERROR_MEMORY;
1148 (*policy)[rules_count] = NULL;
1151 // Re-write rules as a list of strings - every rule in different string.
1152 for (i = 0; i < rules_count; ++i) {
1153 last2 = strchr(last, '\n');
1155 (*policy)[i] = malloc(sizeof(char*) * (last2 - last) + 1);
1156 if (!((*policy)[i])) {
1161 ret_code = LIB_ERROR_MEMORY;
1164 memcpy((*policy)[i], last, (last2 - last));
1165 (*policy)[i][last2 - last] = '\0';
1166 } else { // This should be the last run of FOR loop
1167 (*policy)[i] = malloc(sizeof(char*) * strlen(last) + 1);
1168 if (!((*policy)[i])) {
1173 ret_code = LIB_ERROR_MEMORY;
1176 memcpy((*policy)[i], last, strlen(last));
1177 (*policy)[i][strlen(last)] = '\0';
1179 last = last2 + sizeof(char);
1188 int ima_free_policy(char **policy)
1193 return LIB_ERROR_INPUT_PARAM;
1205 static int _ima_write_rule(int fd, const char *rule)
1211 return LIB_ERROR_SYSCALL;
1215 int len = strlen(rule);
1218 while (counter < len) {
1219 ret = write(fd, &(rule[counter]), len-counter);
1220 if (ret < 0) { /* Write error. Return with error code */
1221 return LIB_ERROR_SYSCALL;
1226 /* writing new line sign */
1228 ret = write(fd, "\n", sizeof("\n"));
1230 return LIB_ERROR_SYSCALL;
1232 if (ret != sizeof("\n"))
1233 return LIB_ERROR_SYSCALL;
1238 int ima_set_policy_file(const char *policy_path)
1240 int ret_code = LIB_SUCCESS;
1246 if (!policy_path || policy_path[0] == '\0')
1247 return LIB_ERROR_INPUT_PARAM;
1249 /* open and write to kernel interface */
1250 fd = open(IMA_POLICY_INTERFACE, O_WRONLY);
1252 log_err("Cannot open kernel interface\n");
1253 ret_code = LIB_ERROR_SYSCALL;
1258 len = strlen(policy_path);
1259 while (counter < len) {
1260 ret = write(fd, &(policy_path[counter]), len - counter);
1262 log_err("Error while writing to the kernel interface (%s)\n", strerror(errno));
1263 ret_code = LIB_ERROR_SYSCALL;
1275 int ima_set_policy(const char **policy, const char *policy_sig)
1277 int ret_code = LIB_SUCCESS;
1278 char *policy_file_name = NULL;
1279 char *sig_file_name = NULL;
1283 int i, counter, len;
1286 if (!policy || !policy_sig) {
1287 log_err("Error input param\n");
1288 return LIB_ERROR_INPUT_PARAM;
1291 /* Generate random filename */
1292 policy_file_name = tempnam(IMA_POLICY_TMP_DIR, IMA_POLICY_TMP_FILE_PREFIX);
1293 if (!policy_file_name) {
1294 log_err("Cannot generate unique file name\n");
1295 return LIB_ERROR_SYSCALL;
1298 /* write policy to temporary file */
1299 /* We need to be sure that we create a new file. */
1300 /* No one should have any right to this file - except write for us */
1301 fd_policy = open(policy_file_name, O_WRONLY | O_CREAT | O_EXCL, S_IWUSR);
1302 if (fd_policy < 0) {
1303 log_err("Cannot open policy temporary file\n");
1304 ret_code = LIB_ERROR_SYSCALL;
1310 ret = _ima_write_rule(fd_policy, policy[i]);
1311 if (ret != LIB_SUCCESS) {
1312 log_err("Error while writing policy rule to temporary file\n");
1318 /* We keep this file locked */
1320 /* generate signature file name */
1321 sig_file_name = malloc(sizeof(char) * (strlen(policy_file_name) + sizeof(IMA_POLICY_SIGNATRURE_EXTENSION) + 1));
1322 if (!sig_file_name) {
1323 ret_code = LIB_ERROR_MEMORY;
1326 len = strlen(policy_file_name);
1327 memcpy(sig_file_name, policy_file_name, len);
1328 memcpy(&(sig_file_name[len]),
1329 IMA_POLICY_SIGNATRURE_EXTENSION,
1330 sizeof(IMA_POLICY_SIGNATRURE_EXTENSION));
1331 sig_file_name[len + sizeof(IMA_POLICY_SIGNATRURE_EXTENSION)] = '\0';
1333 /* write signature to temporary file - the same conditions as for the policy file */
1334 fd_sig = open(sig_file_name, O_WRONLY | O_CREAT | O_EXCL, S_IWUSR);
1336 log_err("Cannot open signature temporary file\n");
1337 ret_code = LIB_ERROR_SYSCALL;
1342 len = strlen(policy_sig);
1343 while (counter < len) {
1344 ret = write(fd_sig, &(policy_sig[counter]), len-counter);
1346 log_err("Error while writing signature to temporary file\n");
1347 ret_code = LIB_ERROR_SYSCALL;
1353 /* unlocked policy and signature file */
1359 /* open and write to kernel interface */
1360 fd = open(IMA_POLICY_INTERFACE, O_WRONLY);
1362 log_err("Cannot open kernel interface\n");
1363 ret_code = LIB_ERROR_SYSCALL;
1368 len = strlen(policy_file_name);
1369 while (counter < len) {
1370 ret = write(fd, &(policy_file_name[counter]), len-counter);
1372 log_err("Error while writing to the kernel interface\n");
1373 ret_code = LIB_ERROR_SYSCALL;
1386 if (policy_file_name) {
1387 unlink(policy_file_name);
1388 free(policy_file_name);
1390 if (sig_file_name) {
1391 unlink(sig_file_name);
1392 free(sig_file_name);
1397 #define IMA_MEASURE_PATH "/sys/kernel/security/ima/ascii_runtime_measurements"
1398 #define IMA_TAMPERED_STATE 0x0001
1400 int get_file_state(const char *path, int *state)
1404 char *fileState = NULL;
1407 *state = FILE_STATE_UNKNOWN;
1409 if (!path || !state) {
1410 log_err("Error input param\n");
1411 return LIB_ERROR_INPUT_PARAM;
1414 fp = fopen(path, "r");
1416 if (errno != EACCES && errno != EPERM) {
1417 *state = FILE_STATE_UNKNOWN;
1420 fp = fopen(IMA_MEASURE_PATH, "r");
1422 log_err("Unable to open file\n");
1423 return LIB_ERROR_SYSCALL;
1425 while (fgets(line, sizeof line, fp) != NULL) {
1426 token = strtok(line, " ");
1427 while ((token = strtok(NULL, " "))) {
1428 if (!strcmp(path, token)) {
1434 token = strtok(NULL, " ");
1435 while (NULL != token) {
1437 token = strtok(NULL, " ");
1439 if (atoi(fileState) & IMA_TAMPERED_STATE) {
1440 *state = FILE_STATE_TAMPERED;
1447 *state = FILE_STATE_OK;