clang on Linux x86_64 complains about unreachable code.
[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 }
130
131 /* Test copying of contexts */
132 static void test_ctx_replace(EVP_CIPHER_CTX **pctx)
133 {
134     /* Make copy of context and replace original */
135     EVP_CIPHER_CTX *ctx_copy;
136     ctx_copy = EVP_CIPHER_CTX_new();
137     EVP_CIPHER_CTX_copy(ctx_copy, *pctx);
138     EVP_CIPHER_CTX_free(*pctx);
139     *pctx = ctx_copy;
140 }
141
142 static void test1(const EVP_CIPHER *c, const unsigned char *key, int kn,
143                   const unsigned char *iv, int in,
144                   const unsigned char *plaintext, int pn,
145                   const unsigned char *ciphertext, int cn,
146                   const unsigned char *aad, int an,
147                   const unsigned char *tag, int tn, int encdec)
148 {
149     EVP_CIPHER_CTX *ctx = NULL;
150     unsigned char out[4096];
151     int outl, outl2, mode;
152
153     printf("Testing cipher %s%s\n", EVP_CIPHER_name(c),
154            (encdec ==
155             1 ? "(encrypt)" : (encdec ==
156                                0 ? "(decrypt)" : "(encrypt/decrypt)")));
157     hexdump(stdout, "Key", key, kn);
158     if (in)
159         hexdump(stdout, "IV", iv, in);
160     hexdump(stdout, "Plaintext", plaintext, pn);
161     hexdump(stdout, "Ciphertext", ciphertext, cn);
162     if (an)
163         hexdump(stdout, "AAD", aad, an);
164     if (tn)
165         hexdump(stdout, "Tag", tag, tn);
166     mode = EVP_CIPHER_mode(c);
167     if (kn != EVP_CIPHER_key_length(c)) {
168         fprintf(stderr, "Key length doesn't match, got %d expected %lu\n", kn,
169                 (unsigned long)EVP_CIPHER_key_length(c));
170         test1_exit(5);
171     }
172     ctx = EVP_CIPHER_CTX_new();
173     EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
174     if (encdec != 0) {
175         if ((mode == EVP_CIPH_GCM_MODE) || (mode == EVP_CIPH_OCB_MODE)
176             || (mode == EVP_CIPH_CCM_MODE)) {
177             if (!EVP_EncryptInit_ex(ctx, c, NULL, NULL, NULL)) {
178                 fprintf(stderr, "EncryptInit failed\n");
179                 ERR_print_errors_fp(stderr);
180                 test1_exit(10);
181             }
182             if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, in, NULL)) {
183                 fprintf(stderr, "IV length set failed\n");
184                 ERR_print_errors_fp(stderr);
185                 test1_exit(11);
186             }
187             if ((mode != EVP_CIPH_GCM_MODE) &&
188                 !EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, tn, NULL)) {
189                 fprintf(stderr, "Tag length set failed\n");
190                 ERR_print_errors_fp(stderr);
191                 test1_exit(15);
192             }
193             if (!EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv)) {
194                 fprintf(stderr, "Key/IV set failed\n");
195                 ERR_print_errors_fp(stderr);
196                 test1_exit(12);
197             }
198             if ((mode == EVP_CIPH_CCM_MODE) &&
199                 !EVP_EncryptUpdate(ctx, NULL, &outl, NULL, pn)) {
200                 fprintf(stderr, "Plaintext length set failed\n");
201                 ERR_print_errors_fp(stderr);
202                 test1_exit(12);
203             }
204             if (an && !EVP_EncryptUpdate(ctx, NULL, &outl, aad, an)) {
205                 fprintf(stderr, "AAD set failed\n");
206                 ERR_print_errors_fp(stderr);
207                 test1_exit(13);
208             }
209         } else if (mode == EVP_CIPH_WRAP_MODE) {
210             if (!EVP_EncryptInit_ex(ctx, c, NULL, key, in ? iv : NULL)) {
211                 fprintf(stderr, "EncryptInit failed\n");
212                 ERR_print_errors_fp(stderr);
213                 test1_exit(10);
214             }
215         } else if (!EVP_EncryptInit_ex(ctx, c, NULL, key, iv)) {
216             fprintf(stderr, "EncryptInit failed\n");
217             ERR_print_errors_fp(stderr);
218             test1_exit(10);
219         }
220         EVP_CIPHER_CTX_set_padding(ctx, 0);
221
222         test_ctx_replace(&ctx);
223
224         if (!EVP_EncryptUpdate(ctx, out, &outl, plaintext, pn)) {
225             fprintf(stderr, "Encrypt failed\n");
226             ERR_print_errors_fp(stderr);
227             test1_exit(6);
228         }
229         if (!EVP_EncryptFinal_ex(ctx, out + outl, &outl2)) {
230             fprintf(stderr, "EncryptFinal failed\n");
231             ERR_print_errors_fp(stderr);
232             test1_exit(7);
233         }
234
235         if (outl + outl2 != cn) {
236             fprintf(stderr, "Ciphertext length mismatch got %d expected %d\n",
237                     outl + outl2, cn);
238             test1_exit(8);
239         }
240
241         if (memcmp(out, ciphertext, cn)) {
242             fprintf(stderr, "Ciphertext mismatch\n");
243             hexdump(stderr, "Got", out, cn);
244             hexdump(stderr, "Expected", ciphertext, cn);
245             test1_exit(9);
246         }
247         if ((mode == EVP_CIPH_GCM_MODE) || (mode == EVP_CIPH_OCB_MODE)
248             || (mode == EVP_CIPH_CCM_MODE)) {
249             unsigned char rtag[16];
250
251             if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, tn, rtag)) {
252                 fprintf(stderr, "Get tag failed\n");
253                 ERR_print_errors_fp(stderr);
254                 test1_exit(14);
255             }
256             if (memcmp(rtag, tag, tn)) {
257                 fprintf(stderr, "Tag mismatch\n");
258                 hexdump(stderr, "Got", rtag, tn);
259                 hexdump(stderr, "Expected", tag, tn);
260                 test1_exit(9);
261             }
262         }
263     }
264
265     if (encdec <= 0) {
266         if ((mode == EVP_CIPH_GCM_MODE) || (mode == EVP_CIPH_OCB_MODE)) {
267             if (!EVP_DecryptInit_ex(ctx, c, NULL, NULL, NULL)) {
268                 fprintf(stderr, "DecryptInit failed\n");
269                 ERR_print_errors_fp(stderr);
270                 test1_exit(10);
271             }
272             if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, in, NULL)) {
273                 fprintf(stderr, "IV length set failed\n");
274                 ERR_print_errors_fp(stderr);
275                 test1_exit(11);
276             }
277             if ((mode == EVP_CIPH_OCB_MODE) &&
278                 !EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, tn, NULL)) {
279                 fprintf(stderr, "Tag length set failed\n");
280                 ERR_print_errors_fp(stderr);
281                 test1_exit(15);
282             }
283             if (!EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv)) {
284                 fprintf(stderr, "Key/IV set failed\n");
285                 ERR_print_errors_fp(stderr);
286                 test1_exit(12);
287             }
288             if (!EVP_CIPHER_CTX_ctrl
289                 (ctx, EVP_CTRL_AEAD_SET_TAG, tn, (void *)tag)) {
290                 fprintf(stderr, "Set tag failed\n");
291                 ERR_print_errors_fp(stderr);
292                 test1_exit(14);
293             }
294             if (an && !EVP_DecryptUpdate(ctx, NULL, &outl, aad, an)) {
295                 fprintf(stderr, "AAD set failed\n");
296                 ERR_print_errors_fp(stderr);
297                 test1_exit(13);
298             }
299         } else if (mode == EVP_CIPH_CCM_MODE) {
300             if (!EVP_DecryptInit_ex(ctx, c, NULL, NULL, NULL)) {
301                 fprintf(stderr, "DecryptInit failed\n");
302                 ERR_print_errors_fp(stderr);
303                 test1_exit(10);
304             }
305             if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, in, NULL)) {
306                 fprintf(stderr, "IV length set failed\n");
307                 ERR_print_errors_fp(stderr);
308                 test1_exit(11);
309             }
310             if (!EVP_CIPHER_CTX_ctrl
311                 (ctx, EVP_CTRL_AEAD_SET_TAG, tn, (void *)tag)) {
312                 fprintf(stderr, "Tag length set failed\n");
313                 ERR_print_errors_fp(stderr);
314                 test1_exit(11);
315             }
316             if (!EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv)) {
317                 fprintf(stderr, "Key/Nonce set failed\n");
318                 ERR_print_errors_fp(stderr);
319                 test1_exit(12);
320             }
321             if (!EVP_DecryptUpdate(ctx, NULL, &outl, NULL, pn)) {
322                 fprintf(stderr, "Plaintext length set failed\n");
323                 ERR_print_errors_fp(stderr);
324                 test1_exit(12);
325             }
326             if (an && !EVP_EncryptUpdate(ctx, NULL, &outl, aad, an)) {
327                 fprintf(stderr, "AAD set failed\n");
328                 ERR_print_errors_fp(stderr);
329                 test1_exit(13);
330             }
331         } else if (mode == EVP_CIPH_WRAP_MODE) {
332             if (!EVP_DecryptInit_ex(ctx, c, NULL, key, in ? iv : NULL)) {
333                 fprintf(stderr, "EncryptInit failed\n");
334                 ERR_print_errors_fp(stderr);
335                 test1_exit(10);
336             }
337         } else if (!EVP_DecryptInit_ex(ctx, c, NULL, key, iv)) {
338             fprintf(stderr, "DecryptInit failed\n");
339             ERR_print_errors_fp(stderr);
340             test1_exit(11);
341         }
342         EVP_CIPHER_CTX_set_padding(ctx, 0);
343
344         test_ctx_replace(&ctx);
345
346         if (!EVP_DecryptUpdate(ctx, out, &outl, ciphertext, cn)) {
347             fprintf(stderr, "Decrypt failed\n");
348             ERR_print_errors_fp(stderr);
349             test1_exit(6);
350         }
351         if (mode != EVP_CIPH_CCM_MODE
352             && !EVP_DecryptFinal_ex(ctx, out + outl, &outl2)) {
353             fprintf(stderr, "DecryptFinal failed\n");
354             ERR_print_errors_fp(stderr);
355             test1_exit(7);
356         }
357
358         if (outl + outl2 != pn) {
359             fprintf(stderr, "Plaintext length mismatch got %d expected %d\n",
360                     outl + outl2, pn);
361             test1_exit(8);
362         }
363
364         if (memcmp(out, plaintext, pn)) {
365             fprintf(stderr, "Plaintext mismatch\n");
366             hexdump(stderr, "Got", out, pn);
367             hexdump(stderr, "Expected", plaintext, pn);
368             test1_exit(9);
369         }
370     }
371
372     EVP_CIPHER_CTX_free(ctx);
373
374     printf("\n");
375 }
376
377 static int test_cipher(const char *cipher, const unsigned char *key, int kn,
378                        const unsigned char *iv, int in,
379                        const unsigned char *plaintext, int pn,
380                        const unsigned char *ciphertext, int cn,
381                        const unsigned char *aad, int an,
382                        const unsigned char *tag, int tn, int encdec)
383 {
384     const EVP_CIPHER *c;
385
386 #ifdef OPENSSL_NO_OCB
387     if (strstr(cipher, "ocb") != NULL)
388         return 1;
389 #endif
390     c = EVP_get_cipherbyname(cipher);
391     if (!c)
392         return 0;
393
394     test1(c, key, kn, iv, in, plaintext, pn, ciphertext, cn, aad, an, tag, tn,
395           encdec);
396
397     return 1;
398 }
399
400 static int test_digest(const char *digest,
401                        const unsigned char *plaintext, int pn,
402                        const unsigned char *ciphertext, unsigned int cn)
403 {
404     const EVP_MD *d;
405     EVP_MD_CTX ctx;
406     unsigned char md[EVP_MAX_MD_SIZE];
407     unsigned int mdn;
408
409     d = EVP_get_digestbyname(digest);
410     if (!d)
411         return 0;
412
413     printf("Testing digest %s\n", EVP_MD_name(d));
414     hexdump(stdout, "Plaintext", plaintext, pn);
415     hexdump(stdout, "Digest", ciphertext, cn);
416
417     EVP_MD_CTX_init(&ctx);
418     if (!EVP_DigestInit_ex(&ctx, d, NULL)) {
419         fprintf(stderr, "DigestInit failed\n");
420         ERR_print_errors_fp(stderr);
421         EXIT(100);
422     }
423     if (!EVP_DigestUpdate(&ctx, plaintext, pn)) {
424         fprintf(stderr, "DigestUpdate failed\n");
425         ERR_print_errors_fp(stderr);
426         EXIT(101);
427     }
428     if (!EVP_DigestFinal_ex(&ctx, md, &mdn)) {
429         fprintf(stderr, "DigestFinal failed\n");
430         ERR_print_errors_fp(stderr);
431         EXIT(101);
432     }
433     EVP_MD_CTX_cleanup(&ctx);
434
435     if (mdn != cn) {
436         fprintf(stderr, "Digest length mismatch, got %d expected %d\n", mdn,
437                 cn);
438         EXIT(102);
439     }
440
441     if (memcmp(md, ciphertext, cn)) {
442         fprintf(stderr, "Digest mismatch\n");
443         hexdump(stderr, "Got", md, cn);
444         hexdump(stderr, "Expected", ciphertext, cn);
445         EXIT(103);
446     }
447
448     printf("\n");
449
450     EVP_MD_CTX_cleanup(&ctx);
451
452     return 1;
453 }
454
455 int main(int argc, char **argv)
456 {
457     const char *szTestFile;
458     FILE *f;
459
460     if (argc != 2) {
461         fprintf(stderr, "%s <test file>\n", argv[0]);
462         EXIT(1);
463     }
464     CRYPTO_malloc_debug_init();
465     CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
466     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
467
468     szTestFile = argv[1];
469
470     f = fopen(szTestFile, "r");
471     if (!f) {
472         perror(szTestFile);
473         EXIT(2);
474     }
475     ERR_load_crypto_strings();
476     /* Load up the software EVP_CIPHER and EVP_MD definitions */
477     OpenSSL_add_all_ciphers();
478     OpenSSL_add_all_digests();
479 #ifndef OPENSSL_NO_ENGINE
480     /* Load all compiled-in ENGINEs */
481     ENGINE_load_builtin_engines();
482 #endif
483 #if 0
484     OPENSSL_config();
485 #endif
486 #ifndef OPENSSL_NO_ENGINE
487     /*
488      * Register all available ENGINE implementations of ciphers and digests.
489      * This could perhaps be changed to "ENGINE_register_all_complete()"?
490      */
491     ENGINE_register_all_ciphers();
492     ENGINE_register_all_digests();
493     /*
494      * If we add command-line options, this statement should be switchable.
495      * It'll prevent ENGINEs being ENGINE_init()ialised for cipher/digest use
496      * if they weren't already initialised.
497      */
498     /* ENGINE_set_cipher_flags(ENGINE_CIPHER_FLAG_NOINIT); */
499 #endif
500
501     for (;;) {
502         char line[4096];
503         char *p;
504         char *cipher;
505         unsigned char *iv, *key, *plaintext, *ciphertext, *aad, *tag;
506         int encdec;
507         int kn, in, pn, cn;
508         int an = 0;
509         int tn = 0;
510
511         if (!fgets((char *)line, sizeof line, f))
512             break;
513         if (line[0] == '#' || line[0] == '\n')
514             continue;
515         p = line;
516         cipher = sstrsep(&p, ":");
517         key = ustrsep(&p, ":");
518         iv = ustrsep(&p, ":");
519         plaintext = ustrsep(&p, ":");
520         ciphertext = ustrsep(&p, ":");
521         if (p[-1] == '\n') {
522             encdec = -1;
523             p[-1] = '\0';
524             tag = aad = NULL;
525             an = tn = 0;
526         } else {
527             aad = ustrsep(&p, ":");
528             tag = ustrsep(&p, ":");
529             if (tag == NULL) {
530                 p = (char *)aad;
531                 tag = aad = NULL;
532                 an = tn = 0;
533             }
534             if (p[-1] == '\n') {
535                 encdec = -1;
536                 p[-1] = '\0';
537             } else
538                 encdec = atoi(sstrsep(&p, "\n"));
539         }
540
541         kn = convert(key);
542         in = convert(iv);
543         pn = convert(plaintext);
544         cn = convert(ciphertext);
545         if (aad) {
546             an = convert(aad);
547             tn = convert(tag);
548         }
549
550         if (!test_cipher
551             (cipher, key, kn, iv, in, plaintext, pn, ciphertext, cn, aad, an,
552              tag, tn, encdec)
553             && !test_digest(cipher, plaintext, pn, ciphertext, cn)) {
554 #ifdef OPENSSL_NO_AES
555             if (strstr(cipher, "AES") == cipher) {
556                 fprintf(stdout, "Cipher disabled, skipping %s\n", cipher);
557                 continue;
558             }
559 #endif
560 #ifdef OPENSSL_NO_DES
561             if (strstr(cipher, "DES") == cipher) {
562                 fprintf(stdout, "Cipher disabled, skipping %s\n", cipher);
563                 continue;
564             }
565 #endif
566 #ifdef OPENSSL_NO_RC4
567             if (strstr(cipher, "RC4") == cipher) {
568                 fprintf(stdout, "Cipher disabled, skipping %s\n", cipher);
569                 continue;
570             }
571 #endif
572 #ifdef OPENSSL_NO_CAMELLIA
573             if (strstr(cipher, "CAMELLIA") == cipher) {
574                 fprintf(stdout, "Cipher disabled, skipping %s\n", cipher);
575                 continue;
576             }
577 #endif
578 #ifdef OPENSSL_NO_SEED
579             if (strstr(cipher, "SEED") == cipher) {
580                 fprintf(stdout, "Cipher disabled, skipping %s\n", cipher);
581                 continue;
582             }
583 #endif
584             fprintf(stderr, "Can't find %s\n", cipher);
585             EXIT(3);
586         }
587     }
588     fclose(f);
589
590 #ifndef OPENSSL_NO_ENGINE
591     ENGINE_cleanup();
592 #endif
593     EVP_cleanup();
594     CRYPTO_cleanup_all_ex_data();
595     ERR_remove_thread_state(NULL);
596     ERR_free_strings();
597     CRYPTO_mem_leaks_fp(stderr);
598
599     return 0;
600 }