test/lib: Add OpenSSL verify and decrypt tests
[petitboot] / test / lib / test-security-openssl-decrypt.c
1 #include <stdlib.h>
2 #include <unistd.h>
3 #include <string.h>
4 #include <assert.h>
5 #include <fcntl.h>
6 #include <sys/stat.h>
7
8 #include <log/log.h>
9 #include <talloc/talloc.h>
10 #include <file/file.h>
11 #include <security/security.h>
12
13 #define SECURITY_TEST_DATA_DIR  TEST_LIB_DATA_BASE "/security/"
14
15 int main(void)
16 {
17         char *verify_data = NULL;
18         char *compare_data = NULL;
19         char *filename = NULL;
20         FILE *keyfile = NULL;
21         int ret = EXIT_FAILURE;
22         int verify_len;
23         int compare_len;
24
25         pb_log_init(stdout);
26
27         keyfile = fopen(SECURITY_TEST_DATA_DIR "cert.p12", "r");
28         if (!keyfile)
29                 return EXIT_FAILURE;
30
31         if (read_file(NULL, SECURITY_TEST_DATA_DIR "rootdata.txt", &verify_data, &verify_len))
32                 goto out;
33
34         /* first basic CMS decrypt case */
35
36         /*
37          * these calls overwrite so need a temp file
38          * copy_file_secure_dest is having some permission issues
39          */
40         if (copy_file_secure_dest(NULL,
41                                   SECURITY_TEST_DATA_DIR "rootdata.cmsencver",
42                                   &filename))
43                 goto out;
44
45         if (decrypt_file(filename, keyfile, NULL))
46                 goto out;
47
48         if (read_file(verify_data, filename, &compare_data, &compare_len))
49                 goto out;
50
51         if (verify_len != compare_len)
52                 goto out;
53
54         if (memcmp(verify_data, compare_data, verify_len))
55                 goto out;
56
57         /* check an encrypted but unverified message fails */
58         unlink(filename);
59         talloc_free(filename);
60
61         if (copy_file_secure_dest(NULL,
62                                   SECURITY_TEST_DATA_DIR "rootdata.cmsenc",
63                                   &filename))
64                 goto out;
65
66
67         if (!decrypt_file(filename, keyfile, NULL))
68                 goto out;
69
70         /* got here, all fine */
71         ret = EXIT_SUCCESS;
72
73 out:
74         if (keyfile)
75                 fclose(keyfile);
76         if (filename) {
77                 unlink(filename);
78                 talloc_free(filename);
79         }
80         talloc_free(verify_data);
81         return ret;
82 }