597b9fe23ca05cba9a03670f1e01f13fd8d0f6e9
[openssl.git] / crypto / evp / evp_test.c
1 /* Written by Ben Laurie, 2001 */
2 /*
3  * Copyright (c) 2001 The OpenSSL Project.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in
14  *    the documentation and/or other materials provided with the
15  *    distribution.
16  *
17  * 3. All advertising materials mentioning features or use of this
18  *    software must display the following acknowledgment:
19  *    "This product includes software developed by the OpenSSL Project
20  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
21  *
22  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
23  *    endorse or promote products derived from this software without
24  *    prior written permission. For written permission, please contact
25  *    openssl-core@openssl.org.
26  *
27  * 5. Products derived from this software may not be called "OpenSSL"
28  *    nor may "OpenSSL" appear in their names without prior written
29  *    permission of the OpenSSL Project.
30  *
31  * 6. Redistributions of any form whatsoever must retain the following
32  *    acknowledgment:
33  *    "This product includes software developed by the OpenSSL Project
34  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
35  *
36  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
37  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
38  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
39  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
40  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
42  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
43  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
44  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
45  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
46  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
47  * OF THE POSSIBILITY OF SUCH DAMAGE.
48  */
49
50 #include <stdio.h>
51 #include <string.h>
52
53 #include "../e_os.h"
54
55 #include <openssl/opensslconf.h>
56 #include <openssl/evp.h>
57 #ifndef OPENSSL_NO_ENGINE
58 # include <openssl/engine.h>
59 #endif
60 #include <openssl/err.h>
61 #include <openssl/conf.h>
62
63 static void hexdump(FILE *f, const char *title, const unsigned char *s, int l)
64 {
65     int n = 0;
66
67     fprintf(f, "%s", title);
68     for (; n < l; ++n) {
69         if ((n % 16) == 0)
70             fprintf(f, "\n%04x", n);
71         fprintf(f, " %02x", s[n]);
72     }
73     fprintf(f, "\n");
74 }
75
76 static int convert(unsigned char *s)
77 {
78     unsigned char *d;
79
80     for (d = s; *s; s += 2, ++d) {
81         unsigned int n;
82
83         if (!s[1]) {
84             fprintf(stderr, "Odd number of hex digits!");
85             EXIT(4);
86         }
87         sscanf((char *)s, "%2x", &n);
88         *d = (unsigned char)n;
89     }
90     return s - d;
91 }
92
93 static char *sstrsep(char **string, const char *delim)
94 {
95     char isdelim[256];
96     char *token = *string;
97
98     if (**string == 0)
99         return NULL;
100
101     memset(isdelim, 0, 256);
102     isdelim[0] = 1;
103
104     while (*delim) {
105         isdelim[(unsigned char)(*delim)] = 1;
106         delim++;
107     }
108
109     while (!isdelim[(unsigned char)(**string)]) {
110         (*string)++;
111     }
112
113     if (**string) {
114         **string = 0;
115         (*string)++;
116     }
117
118     return token;
119 }
120
121 static unsigned char *ustrsep(char **p, const char *sep)
122 {
123     return (unsigned char *)sstrsep(p, sep);
124 }
125
126 static int test1_exit(int ec)
127 {
128     EXIT(ec);
129     return (0);                 /* To keep some compilers quiet */
130 }
131
132 /* Test copying of contexts */
133 static void test_ctx_replace(EVP_CIPHER_CTX **pctx)
134 {
135     /* Make copy of context and replace original */
136     EVP_CIPHER_CTX *ctx_copy;
137     ctx_copy = EVP_CIPHER_CTX_new();
138     EVP_CIPHER_CTX_copy(ctx_copy, *pctx);
139     EVP_CIPHER_CTX_free(*pctx);
140     *pctx = ctx_copy;
141 }
142
143 static void test1(const EVP_CIPHER *c, const unsigned char *key, int kn,
144                   const unsigned char *iv, int in,
145                   const unsigned char *plaintext, int pn,
146                   const unsigned char *ciphertext, int cn,
147                   const unsigned char *aad, int an,
148                   const unsigned char *tag, int tn, int encdec)
149 {
150     EVP_CIPHER_CTX *ctx = NULL;
151     unsigned char out[4096];
152     int outl, outl2, mode;
153
154     printf("Testing cipher %s%s\n", EVP_CIPHER_name(c),
155            (encdec ==
156             1 ? "(encrypt)" : (encdec ==
157                                0 ? "(decrypt)" : "(encrypt/decrypt)")));
158     hexdump(stdout, "Key", key, kn);
159     if (in)
160         hexdump(stdout, "IV", iv, in);
161     hexdump(stdout, "Plaintext", plaintext, pn);
162     hexdump(stdout, "Ciphertext", ciphertext, cn);
163     if (an)
164         hexdump(stdout, "AAD", aad, an);
165     if (tn)
166         hexdump(stdout, "Tag", tag, tn);
167     mode = EVP_CIPHER_mode(c);
168     if (kn != EVP_CIPHER_key_length(c)) {
169         fprintf(stderr, "Key length doesn't match, got %d expected %lu\n", kn,
170                 (unsigned long)EVP_CIPHER_key_length(c));
171         test1_exit(5);
172     }
173     ctx = EVP_CIPHER_CTX_new();
174     EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
175     if (encdec != 0) {
176         if ((mode == EVP_CIPH_GCM_MODE) || (mode == EVP_CIPH_OCB_MODE)
177             || (mode == EVP_CIPH_CCM_MODE)) {
178             if (!EVP_EncryptInit_ex(ctx, c, NULL, NULL, NULL)) {
179                 fprintf(stderr, "EncryptInit failed\n");
180                 ERR_print_errors_fp(stderr);
181                 test1_exit(10);
182             }
183             if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, in, NULL)) {
184                 fprintf(stderr, "IV length set failed\n");
185                 ERR_print_errors_fp(stderr);
186                 test1_exit(11);
187             }
188             if ((mode != EVP_CIPH_GCM_MODE) &&
189                 !EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, tn, NULL)) {
190                 fprintf(stderr, "Tag length set failed\n");
191                 ERR_print_errors_fp(stderr);
192                 test1_exit(15);
193             }
194             if (!EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv)) {
195                 fprintf(stderr, "Key/IV set failed\n");
196                 ERR_print_errors_fp(stderr);
197                 test1_exit(12);
198             }
199             if ((mode == EVP_CIPH_CCM_MODE) &&
200                 !EVP_EncryptUpdate(ctx, NULL, &outl, NULL, pn)) {
201                 fprintf(stderr, "Plaintext length set failed\n");
202                 ERR_print_errors_fp(stderr);
203                 test1_exit(12);
204             }
205             if (an && !EVP_EncryptUpdate(ctx, NULL, &outl, aad, an)) {
206                 fprintf(stderr, "AAD set failed\n");
207                 ERR_print_errors_fp(stderr);
208                 test1_exit(13);
209             }
210         } else if (mode == EVP_CIPH_WRAP_MODE) {
211             if (!EVP_EncryptInit_ex(ctx, c, NULL, key, in ? iv : NULL)) {
212                 fprintf(stderr, "EncryptInit failed\n");
213                 ERR_print_errors_fp(stderr);
214                 test1_exit(10);
215             }
216         } else if (!EVP_EncryptInit_ex(ctx, c, NULL, key, iv)) {
217             fprintf(stderr, "EncryptInit failed\n");
218             ERR_print_errors_fp(stderr);
219             test1_exit(10);
220         }
221         EVP_CIPHER_CTX_set_padding(ctx, 0);
222
223         test_ctx_replace(&ctx);
224
225         if (!EVP_EncryptUpdate(ctx, out, &outl, plaintext, pn)) {
226             fprintf(stderr, "Encrypt failed\n");
227             ERR_print_errors_fp(stderr);
228             test1_exit(6);
229         }
230         if (!EVP_EncryptFinal_ex(ctx, out + outl, &outl2)) {
231             fprintf(stderr, "EncryptFinal failed\n");
232             ERR_print_errors_fp(stderr);
233             test1_exit(7);
234         }
235
236         if (outl + outl2 != cn) {
237             fprintf(stderr, "Ciphertext length mismatch got %d expected %d\n",
238                     outl + outl2, cn);
239             test1_exit(8);
240         }
241
242         if (memcmp(out, ciphertext, cn)) {
243             fprintf(stderr, "Ciphertext mismatch\n");
244             hexdump(stderr, "Got", out, cn);
245             hexdump(stderr, "Expected", ciphertext, cn);
246             test1_exit(9);
247         }
248         if ((mode == EVP_CIPH_GCM_MODE) || (mode == EVP_CIPH_OCB_MODE)
249             || (mode == EVP_CIPH_CCM_MODE)) {
250             unsigned char rtag[16];
251
252             if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, tn, rtag)) {
253                 fprintf(stderr, "Get tag failed\n");
254                 ERR_print_errors_fp(stderr);
255                 test1_exit(14);
256             }
257             if (memcmp(rtag, tag, tn)) {
258                 fprintf(stderr, "Tag mismatch\n");
259                 hexdump(stderr, "Got", rtag, tn);
260                 hexdump(stderr, "Expected", tag, tn);
261                 test1_exit(9);
262             }
263         }
264     }
265
266     if (encdec <= 0) {
267         if ((mode == EVP_CIPH_GCM_MODE) || (mode == EVP_CIPH_OCB_MODE)) {
268             if (!EVP_DecryptInit_ex(ctx, c, NULL, NULL, NULL)) {
269                 fprintf(stderr, "DecryptInit failed\n");
270                 ERR_print_errors_fp(stderr);
271                 test1_exit(10);
272             }
273             if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, in, NULL)) {
274                 fprintf(stderr, "IV length set failed\n");
275                 ERR_print_errors_fp(stderr);
276                 test1_exit(11);
277             }
278             if ((mode == EVP_CIPH_OCB_MODE) &&
279                 !EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, tn, NULL)) {
280                 fprintf(stderr, "Tag length set failed\n");
281                 ERR_print_errors_fp(stderr);
282                 test1_exit(15);
283             }
284             if (!EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv)) {
285                 fprintf(stderr, "Key/IV set failed\n");
286                 ERR_print_errors_fp(stderr);
287                 test1_exit(12);
288             }
289             if (!EVP_CIPHER_CTX_ctrl
290                 (ctx, EVP_CTRL_AEAD_SET_TAG, tn, (void *)tag)) {
291                 fprintf(stderr, "Set tag failed\n");
292                 ERR_print_errors_fp(stderr);
293                 test1_exit(14);
294             }
295             if (an && !EVP_DecryptUpdate(ctx, NULL, &outl, aad, an)) {
296                 fprintf(stderr, "AAD set failed\n");
297                 ERR_print_errors_fp(stderr);
298                 test1_exit(13);
299             }
300         } else if (mode == EVP_CIPH_CCM_MODE) {
301             if (!EVP_DecryptInit_ex(ctx, c, NULL, NULL, NULL)) {
302                 fprintf(stderr, "DecryptInit failed\n");
303                 ERR_print_errors_fp(stderr);
304                 test1_exit(10);
305             }
306             if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, in, NULL)) {
307                 fprintf(stderr, "IV length set failed\n");
308                 ERR_print_errors_fp(stderr);
309                 test1_exit(11);
310             }
311             if (!EVP_CIPHER_CTX_ctrl
312                 (ctx, EVP_CTRL_AEAD_SET_TAG, tn, (void *)tag)) {
313                 fprintf(stderr, "Tag length set failed\n");
314                 ERR_print_errors_fp(stderr);
315                 test1_exit(11);
316             }
317             if (!EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv)) {
318                 fprintf(stderr, "Key/Nonce set failed\n");
319                 ERR_print_errors_fp(stderr);
320                 test1_exit(12);
321             }
322             if (!EVP_DecryptUpdate(ctx, NULL, &outl, NULL, pn)) {
323                 fprintf(stderr, "Plaintext length set failed\n");
324                 ERR_print_errors_fp(stderr);
325                 test1_exit(12);
326             }
327             if (an && !EVP_EncryptUpdate(ctx, NULL, &outl, aad, an)) {
328                 fprintf(stderr, "AAD set failed\n");
329                 ERR_print_errors_fp(stderr);
330                 test1_exit(13);
331             }
332         } else if (mode == EVP_CIPH_WRAP_MODE) {
333             if (!EVP_DecryptInit_ex(ctx, c, NULL, key, in ? iv : NULL)) {
334                 fprintf(stderr, "EncryptInit failed\n");
335                 ERR_print_errors_fp(stderr);
336                 test1_exit(10);
337             }
338         } else if (!EVP_DecryptInit_ex(ctx, c, NULL, key, iv)) {
339             fprintf(stderr, "DecryptInit failed\n");
340             ERR_print_errors_fp(stderr);
341             test1_exit(11);
342         }
343         EVP_CIPHER_CTX_set_padding(ctx, 0);
344
345         test_ctx_replace(&ctx);
346
347         if (!EVP_DecryptUpdate(ctx, out, &outl, ciphertext, cn)) {
348             fprintf(stderr, "Decrypt failed\n");
349             ERR_print_errors_fp(stderr);
350             test1_exit(6);
351         }
352         if (mode != EVP_CIPH_CCM_MODE
353             && !EVP_DecryptFinal_ex(ctx, out + outl, &outl2)) {
354             fprintf(stderr, "DecryptFinal failed\n");
355             ERR_print_errors_fp(stderr);
356             test1_exit(7);
357         }
358
359         if (outl + outl2 != pn) {
360             fprintf(stderr, "Plaintext length mismatch got %d expected %d\n",
361                     outl + outl2, pn);
362             test1_exit(8);
363         }
364
365         if (memcmp(out, plaintext, pn)) {
366             fprintf(stderr, "Plaintext mismatch\n");
367             hexdump(stderr, "Got", out, pn);
368             hexdump(stderr, "Expected", plaintext, pn);
369             test1_exit(9);
370         }
371     }
372
373     EVP_CIPHER_CTX_free(ctx);
374
375     printf("\n");
376 }
377
378 static int test_cipher(const char *cipher, const unsigned char *key, int kn,
379                        const unsigned char *iv, int in,
380                        const unsigned char *plaintext, int pn,
381                        const unsigned char *ciphertext, int cn,
382                        const unsigned char *aad, int an,
383                        const unsigned char *tag, int tn, int encdec)
384 {
385     const EVP_CIPHER *c;
386
387 #ifdef OPENSSL_NO_OCB
388     if (strstr(cipher, "ocb") != NULL)
389         return 1;
390 #endif
391     c = EVP_get_cipherbyname(cipher);
392     if (!c)
393         return 0;
394
395     test1(c, key, kn, iv, in, plaintext, pn, ciphertext, cn, aad, an, tag, tn,
396           encdec);
397
398     return 1;
399 }
400
401 static int test_digest(const char *digest,
402                        const unsigned char *plaintext, int pn,
403                        const unsigned char *ciphertext, unsigned int cn)
404 {
405     const EVP_MD *d;
406     EVP_MD_CTX ctx;
407     unsigned char md[EVP_MAX_MD_SIZE];
408     unsigned int mdn;
409
410     d = EVP_get_digestbyname(digest);
411     if (!d)
412         return 0;
413
414     printf("Testing digest %s\n", EVP_MD_name(d));
415     hexdump(stdout, "Plaintext", plaintext, pn);
416     hexdump(stdout, "Digest", ciphertext, cn);
417
418     EVP_MD_CTX_init(&ctx);
419     if (!EVP_DigestInit_ex(&ctx, d, NULL)) {
420         fprintf(stderr, "DigestInit failed\n");
421         ERR_print_errors_fp(stderr);
422         EXIT(100);
423     }
424     if (!EVP_DigestUpdate(&ctx, plaintext, pn)) {
425         fprintf(stderr, "DigestUpdate failed\n");
426         ERR_print_errors_fp(stderr);
427         EXIT(101);
428     }
429     if (!EVP_DigestFinal_ex(&ctx, md, &mdn)) {
430         fprintf(stderr, "DigestFinal failed\n");
431         ERR_print_errors_fp(stderr);
432         EXIT(101);
433     }
434     EVP_MD_CTX_cleanup(&ctx);
435
436     if (mdn != cn) {
437         fprintf(stderr, "Digest length mismatch, got %d expected %d\n", mdn,
438                 cn);
439         EXIT(102);
440     }
441
442     if (memcmp(md, ciphertext, cn)) {
443         fprintf(stderr, "Digest mismatch\n");
444         hexdump(stderr, "Got", md, cn);
445         hexdump(stderr, "Expected", ciphertext, cn);
446         EXIT(103);
447     }
448
449     printf("\n");
450
451     EVP_MD_CTX_cleanup(&ctx);
452
453     return 1;
454 }
455
456 int main(int argc, char **argv)
457 {
458     const char *szTestFile;
459     FILE *f;
460
461     if (argc != 2) {
462         fprintf(stderr, "%s <test file>\n", argv[0]);
463         EXIT(1);
464     }
465     CRYPTO_malloc_debug_init();
466     CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
467     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
468
469     szTestFile = argv[1];
470
471     f = fopen(szTestFile, "r");
472     if (!f) {
473         perror(szTestFile);
474         EXIT(2);
475     }
476     ERR_load_crypto_strings();
477     /* Load up the software EVP_CIPHER and EVP_MD definitions */
478     OpenSSL_add_all_ciphers();
479     OpenSSL_add_all_digests();
480 #ifndef OPENSSL_NO_ENGINE
481     /* Load all compiled-in ENGINEs */
482     ENGINE_load_builtin_engines();
483 #endif
484 #if 0
485     OPENSSL_config();
486 #endif
487 #ifndef OPENSSL_NO_ENGINE
488     /*
489      * Register all available ENGINE implementations of ciphers and digests.
490      * This could perhaps be changed to "ENGINE_register_all_complete()"?
491      */
492     ENGINE_register_all_ciphers();
493     ENGINE_register_all_digests();
494     /*
495      * If we add command-line options, this statement should be switchable.
496      * It'll prevent ENGINEs being ENGINE_init()ialised for cipher/digest use
497      * if they weren't already initialised.
498      */
499     /* ENGINE_set_cipher_flags(ENGINE_CIPHER_FLAG_NOINIT); */
500 #endif
501
502     for (;;) {
503         char line[4096];
504         char *p;
505         char *cipher;
506         unsigned char *iv, *key, *plaintext, *ciphertext, *aad, *tag;
507         int encdec;
508         int kn, in, pn, cn;
509         int an = 0;
510         int tn = 0;
511
512         if (!fgets((char *)line, sizeof line, f))
513             break;
514         if (line[0] == '#' || line[0] == '\n')
515             continue;
516         p = line;
517         cipher = sstrsep(&p, ":");
518         key = ustrsep(&p, ":");
519         iv = ustrsep(&p, ":");
520         plaintext = ustrsep(&p, ":");
521         ciphertext = ustrsep(&p, ":");
522         if (p[-1] == '\n') {
523             encdec = -1;
524             p[-1] = '\0';
525             tag = aad = NULL;
526             an = tn = 0;
527         } else {
528             aad = ustrsep(&p, ":");
529             tag = ustrsep(&p, ":");
530             if (tag == NULL) {
531                 p = (char *)aad;
532                 tag = aad = NULL;
533                 an = tn = 0;
534             }
535             if (p[-1] == '\n') {
536                 encdec = -1;
537                 p[-1] = '\0';
538             } else
539                 encdec = atoi(sstrsep(&p, "\n"));
540         }
541
542         kn = convert(key);
543         in = convert(iv);
544         pn = convert(plaintext);
545         cn = convert(ciphertext);
546         if (aad) {
547             an = convert(aad);
548             tn = convert(tag);
549         }
550
551         if (!test_cipher
552             (cipher, key, kn, iv, in, plaintext, pn, ciphertext, cn, aad, an,
553              tag, tn, encdec)
554             && !test_digest(cipher, plaintext, pn, ciphertext, cn)) {
555 #ifdef OPENSSL_NO_AES
556             if (strstr(cipher, "AES") == cipher) {
557                 fprintf(stdout, "Cipher disabled, skipping %s\n", cipher);
558                 continue;
559             }
560 #endif
561 #ifdef OPENSSL_NO_DES
562             if (strstr(cipher, "DES") == cipher) {
563                 fprintf(stdout, "Cipher disabled, skipping %s\n", cipher);
564                 continue;
565             }
566 #endif
567 #ifdef OPENSSL_NO_RC4
568             if (strstr(cipher, "RC4") == cipher) {
569                 fprintf(stdout, "Cipher disabled, skipping %s\n", cipher);
570                 continue;
571             }
572 #endif
573 #ifdef OPENSSL_NO_CAMELLIA
574             if (strstr(cipher, "CAMELLIA") == cipher) {
575                 fprintf(stdout, "Cipher disabled, skipping %s\n", cipher);
576                 continue;
577             }
578 #endif
579 #ifdef OPENSSL_NO_SEED
580             if (strstr(cipher, "SEED") == cipher) {
581                 fprintf(stdout, "Cipher disabled, skipping %s\n", cipher);
582                 continue;
583             }
584 #endif
585             fprintf(stderr, "Can't find %s\n", cipher);
586             EXIT(3);
587         }
588     }
589     fclose(f);
590
591 #ifndef OPENSSL_NO_ENGINE
592     ENGINE_cleanup();
593 #endif
594     EVP_cleanup();
595     CRYPTO_cleanup_all_ex_data();
596     ERR_remove_thread_state(NULL);
597     ERR_free_strings();
598     CRYPTO_mem_leaks_fp(stderr);
599
600     return 0;
601 }