Add axTLS sourcecode
[project/luci.git] / libs / nixio / axTLS / ssl / test / ssltest.c.bak
1 /*
2  * Copyright (c) 2007, Cameron Rich
3  * 
4  * All rights reserved.
5  * 
6  * Redistribution and use in source and binary forms, with or without 
7  * modification, are permitted provided that the following conditions are met:
8  *
9  * * Redistributions of source code must retain the above copyright notice, 
10  *   this list of conditions and the following disclaimer.
11  * * Redistributions in binary form must reproduce the above copyright notice, 
12  *   this list of conditions and the following disclaimer in the documentation 
13  *   and/or other materials provided with the distribution.
14  * * Neither the name of the axTLS project nor the names of its contributors 
15  *   may be used to endorse or promote products derived from this software 
16  *   without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
22  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
25  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
26  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 /*
32  * The testing of the crypto and ssl stuff goes here. Keeps the individual code
33  * modules from being uncluttered with test code.
34  *
35  * This is test code - I make no apologies for the quality!
36  */
37
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <signal.h>
41 #include <string.h>
42 #include <errno.h>
43 #include <sys/stat.h>
44 #include <fcntl.h>
45
46 #ifndef WIN32
47 #include <pthread.h>
48 #endif
49
50 #include "ssl.h"
51
52 #define DEFAULT_CERT            "../ssl/test/axTLS.x509_512.cer"
53 #define DEFAULT_KEY             "../ssl/test/axTLS.key_512"     
54 //#define DEFAULT_SVR_OPTION      SSL_DISPLAY_BYTES|SSL_DISPLAY_STATES
55 #define DEFAULT_SVR_OPTION      0
56 #define DEFAULT_CLNT_OPTION     0
57 //#define DEFAULT_CLNT_OPTION      SSL_DISPLAY_BYTES|SSL_DISPLAY_STATES
58
59 static int g_port = 19001;
60
61 /**************************************************************************
62  * AES tests 
63  * 
64  * Run through a couple of the RFC3602 tests to verify that AES is correct.
65  **************************************************************************/
66 #define TEST1_SIZE  16
67 #define TEST2_SIZE  32
68
69 static int AES_test(BI_CTX *bi_ctx)
70 {
71     AES_CTX aes_key;
72     int res = 1;
73     uint8_t key[TEST1_SIZE];
74     uint8_t iv[TEST1_SIZE];
75
76     {
77         /*
78             Case #1: Encrypting 16 bytes (1 block) using AES-CBC
79             Key       : 0x06a9214036b8a15b512e03d534120006
80             IV        : 0x3dafba429d9eb430b422da802c9fac41
81             Plaintext : "Single block msg"
82             Ciphertext: 0xe353779c1079aeb82708942dbe77181a
83
84         */
85         char *in_str =  "Single block msg";
86         uint8_t ct[TEST1_SIZE];
87         uint8_t enc_data[TEST1_SIZE];
88         uint8_t dec_data[TEST1_SIZE];
89
90         bigint *key_bi = bi_str_import(
91                 bi_ctx, "06A9214036B8A15B512E03D534120006");
92         bigint *iv_bi = bi_str_import(
93                 bi_ctx, "3DAFBA429D9EB430B422DA802C9FAC41");
94         bigint *ct_bi = bi_str_import(
95                 bi_ctx, "E353779C1079AEB82708942DBE77181A");
96         bi_export(bi_ctx, key_bi, key, TEST1_SIZE);
97         bi_export(bi_ctx, iv_bi, iv, TEST1_SIZE);
98         bi_export(bi_ctx, ct_bi, ct, TEST1_SIZE);
99
100         AES_set_key(&aes_key, key, iv, AES_MODE_128);
101         AES_cbc_encrypt(&aes_key, (const uint8_t *)in_str, 
102                 enc_data, sizeof(enc_data));
103         if (memcmp(enc_data, ct, sizeof(ct)))
104         {
105             printf("Error: AES ENCRYPT #1 failed\n");
106             goto end;
107         }
108
109         AES_set_key(&aes_key, key, iv, AES_MODE_128);
110         AES_convert_key(&aes_key);
111         AES_cbc_decrypt(&aes_key, enc_data, dec_data, sizeof(enc_data));
112
113         if (memcmp(dec_data, in_str, sizeof(dec_data)))
114         {
115             printf("Error: AES DECRYPT #1 failed\n");
116             goto end;
117         }
118     }
119
120     {
121         /*
122             Case #2: Encrypting 32 bytes (2 blocks) using AES-CBC 
123             Key       : 0xc286696d887c9aa0611bbb3e2025a45a
124             IV        : 0x562e17996d093d28ddb3ba695a2e6f58
125             Plaintext : 0x000102030405060708090a0b0c0d0e0f
126                           101112131415161718191a1b1c1d1e1f
127             Ciphertext: 0xd296cd94c2cccf8a3a863028b5e1dc0a
128                           7586602d253cfff91b8266bea6d61ab1
129         */
130         uint8_t in_data[TEST2_SIZE];
131         uint8_t ct[TEST2_SIZE];
132         uint8_t enc_data[TEST2_SIZE];
133         uint8_t dec_data[TEST2_SIZE];
134
135         bigint *in_bi = bi_str_import(bi_ctx,
136             "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F");
137         bigint *key_bi = bi_str_import(
138                 bi_ctx, "C286696D887C9AA0611BBB3E2025A45A");
139         bigint *iv_bi = bi_str_import(
140                 bi_ctx, "562E17996D093D28DDB3BA695A2E6F58");
141         bigint *ct_bi = bi_str_import(bi_ctx,
142             "D296CD94C2CCCF8A3A863028B5E1DC0A7586602D253CFFF91B8266BEA6D61AB1");
143         bi_export(bi_ctx, in_bi, in_data, TEST2_SIZE);
144         bi_export(bi_ctx, key_bi, key, TEST1_SIZE);
145         bi_export(bi_ctx, iv_bi, iv, TEST1_SIZE);
146         bi_export(bi_ctx, ct_bi, ct, TEST2_SIZE);
147
148         AES_set_key(&aes_key, key, iv, AES_MODE_128);
149         AES_cbc_encrypt(&aes_key, (const uint8_t *)in_data, 
150                 enc_data, sizeof(enc_data));
151
152         if (memcmp(enc_data, ct, sizeof(ct)))
153         {
154             printf("Error: ENCRYPT #2 failed\n");
155             goto end;
156         }
157
158         AES_set_key(&aes_key, key, iv, AES_MODE_128);
159         AES_convert_key(&aes_key);
160         AES_cbc_decrypt(&aes_key, enc_data, dec_data, sizeof(enc_data));
161         if (memcmp(dec_data, in_data, sizeof(dec_data)))
162         {
163             printf("Error: DECRYPT #2 failed\n");
164             goto end;
165         }
166     }
167
168     res = 0;
169     printf("All AES tests passed\n");
170
171 end:
172     return res;
173 }
174
175 /**************************************************************************
176  * RC4 tests 
177  *
178  * ARC4 tests vectors from OpenSSL (crypto/rc4/rc4test.c)
179  **************************************************************************/
180 static const uint8_t keys[7][30]=
181 {
182     {8,0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef},
183     {8,0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef},
184     {8,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
185     {4,0xef,0x01,0x23,0x45},
186     {8,0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef},
187     {4,0xef,0x01,0x23,0x45},
188 };
189
190 static const uint8_t data_len[7]={8,8,8,20,28,10};
191 static uint8_t data[7][30]=
192 {
193     {0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef,0xff},
194     {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff},
195     {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff},
196     {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
197         0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
198         0x00,0x00,0x00,0x00,0xff},
199         {0x12,0x34,0x56,0x78,0x9A,0xBC,0xDE,0xF0,
200             0x12,0x34,0x56,0x78,0x9A,0xBC,0xDE,0xF0,
201             0x12,0x34,0x56,0x78,0x9A,0xBC,0xDE,0xF0,
202             0x12,0x34,0x56,0x78,0xff},
203             {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff},
204             {0},
205 };
206
207 static const uint8_t output[7][30]=
208 {
209     {0x75,0xb7,0x87,0x80,0x99,0xe0,0xc5,0x96,0x00},
210     {0x74,0x94,0xc2,0xe7,0x10,0x4b,0x08,0x79,0x00},
211     {0xde,0x18,0x89,0x41,0xa3,0x37,0x5d,0x3a,0x00},
212     {0xd6,0xa1,0x41,0xa7,0xec,0x3c,0x38,0xdf,
213         0xbd,0x61,0x5a,0x11,0x62,0xe1,0xc7,0xba,
214         0x36,0xb6,0x78,0x58,0x00},
215         {0x66,0xa0,0x94,0x9f,0x8a,0xf7,0xd6,0x89,
216             0x1f,0x7f,0x83,0x2b,0xa8,0x33,0xc0,0x0c,
217             0x89,0x2e,0xbe,0x30,0x14,0x3c,0xe2,0x87,
218             0x40,0x01,0x1e,0xcf,0x00},
219             {0xd6,0xa1,0x41,0xa7,0xec,0x3c,0x38,0xdf,0xbd,0x61,0x00},
220             {0},
221 };
222
223 static int RC4_test(BI_CTX *bi_ctx)
224 {
225     int i, res = 1;
226     RC4_CTX s;
227
228     for (i = 0; i < 6; i++)
229     {
230         RC4_setup(&s, &keys[i][1], keys[i][0]);
231         RC4_crypt(&s, data[i], data[i], data_len[i]);
232
233         if (memcmp(data[i], output[i], data_len[i]))
234         {
235             printf("Error: RC4 CRYPT #%d failed\n", i);
236             goto end;
237         }
238     }
239
240     res = 0;
241     printf("All RC4 tests passed\n");
242
243 end:
244     return res;
245 }
246
247 /**************************************************************************
248  * SHA1 tests 
249  *
250  * Run through a couple of the RFC3174 tests to verify that SHA1 is correct.
251  **************************************************************************/
252 static int SHA1_test(BI_CTX *bi_ctx)
253 {
254     SHA1_CTX ctx;
255     uint8_t ct[SHA1_SIZE];
256     uint8_t digest[SHA1_SIZE];
257     int res = 1;
258
259     {
260         const char *in_str = "abc";
261         bigint *ct_bi = bi_str_import(bi_ctx,
262                 "A9993E364706816ABA3E25717850C26C9CD0D89D");
263         bi_export(bi_ctx, ct_bi, ct, SHA1_SIZE);
264
265         SHA1_Init(&ctx);
266         SHA1_Update(&ctx, (const uint8_t *)in_str, strlen(in_str));
267         SHA1_Final(digest, &ctx);
268
269         if (memcmp(digest, ct, sizeof(ct)))
270         {
271             printf("Error: SHA1 #1 failed\n");
272             goto end;
273         }
274     }
275
276     {
277         const char *in_str =
278             "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq";
279         bigint *ct_bi = bi_str_import(bi_ctx,
280                 "84983E441C3BD26EBAAE4AA1F95129E5E54670F1");
281         bi_export(bi_ctx, ct_bi, ct, SHA1_SIZE);
282
283         SHA1_Init(&ctx);
284         SHA1_Update(&ctx, (const uint8_t *)in_str, strlen(in_str));
285         SHA1_Final(digest, &ctx);
286
287         if (memcmp(digest, ct, sizeof(ct)))
288         {
289             printf("Error: SHA1 #2 failed\n");
290             goto end;
291         }
292     }
293
294     res = 0;
295     printf("All SHA1 tests passed\n");
296
297 end:
298     return res;
299 }
300
301 /**************************************************************************
302  * MD5 tests 
303  *
304  * Run through a couple of the RFC1321 tests to verify that MD5 is correct.
305  **************************************************************************/
306 static int MD5_test(BI_CTX *bi_ctx)
307 {
308     MD5_CTX ctx;
309     uint8_t ct[MD5_SIZE];
310     uint8_t digest[MD5_SIZE];
311     int res = 1;
312
313     {
314         const char *in_str =  "abc";
315         bigint *ct_bi = bi_str_import(bi_ctx, 
316                 "900150983CD24FB0D6963F7D28E17F72");
317         bi_export(bi_ctx, ct_bi, ct, MD5_SIZE);
318
319         MD5_Init(&ctx);
320         MD5_Update(&ctx, (const uint8_t *)in_str, strlen(in_str));
321         MD5_Final(digest, &ctx);
322
323         if (memcmp(digest, ct, sizeof(ct)))
324         {
325             printf("Error: MD5 #1 failed\n");
326             goto end;
327         }
328     }
329
330     {
331         const char *in_str =
332             "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
333         bigint *ct_bi = bi_str_import(
334                 bi_ctx, "D174AB98D277D9F5A5611C2C9F419D9F");
335         bi_export(bi_ctx, ct_bi, ct, MD5_SIZE);
336
337         MD5_Init(&ctx);
338         MD5_Update(&ctx, (const uint8_t *)in_str, strlen(in_str));
339         MD5_Final(digest, &ctx);
340
341         if (memcmp(digest, ct, sizeof(ct)))
342         {
343             printf("Error: MD5 #2 failed\n");
344             goto end;
345         }
346     }
347     res = 0;
348     printf("All MD5 tests passed\n");
349
350 end:
351     return res;
352 }
353
354 /**************************************************************************
355  * HMAC tests 
356  *
357  * Run through a couple of the RFC2202 tests to verify that HMAC is correct.
358  **************************************************************************/
359 static int HMAC_test(BI_CTX *bi_ctx)
360 {
361     uint8_t key[SHA1_SIZE];
362     uint8_t ct[SHA1_SIZE];
363     uint8_t dgst[SHA1_SIZE];
364     int res = 1;
365     const char *key_str;
366
367     const char *data_str = "Hi There";
368     bigint *key_bi = bi_str_import(bi_ctx, "0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B");
369     bigint *ct_bi = bi_str_import(bi_ctx, "9294727A3638BB1C13F48EF8158BFC9D");
370     bi_export(bi_ctx, key_bi, key, MD5_SIZE);
371     bi_export(bi_ctx, ct_bi, ct, MD5_SIZE);
372     hmac_md5((const uint8_t *)data_str, 8, key, MD5_SIZE, dgst);
373     if (memcmp(dgst, ct, MD5_SIZE))
374     {
375         printf("HMAC MD5 #1 failed\n");
376         goto end;
377     }
378
379     data_str = "what do ya want for nothing?";
380     key_str = "Jefe";
381     ct_bi = bi_str_import(bi_ctx, "750C783E6AB0B503EAA86E310A5DB738");
382     bi_export(bi_ctx, ct_bi, ct, MD5_SIZE);
383     hmac_md5((const uint8_t *)data_str, 28, (const uint8_t *)key_str, 4, dgst);
384     if (memcmp(dgst, ct, MD5_SIZE))
385     {
386         printf("HMAC MD5 #2 failed\n");
387         goto end;
388     }
389    
390     data_str = "Hi There";
391     key_bi = bi_str_import(bi_ctx, "0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B");
392     bi_export(bi_ctx, key_bi, key, SHA1_SIZE);
393     ct_bi = bi_str_import(bi_ctx, "B617318655057264E28BC0B6FB378C8EF146BE00");
394     bi_export(bi_ctx, ct_bi, ct, SHA1_SIZE);
395
396     hmac_sha1((const uint8_t *)data_str, 8, 
397             (const uint8_t *)key, SHA1_SIZE, dgst);
398     if (memcmp(dgst, ct, SHA1_SIZE))
399     {
400         printf("HMAC SHA1 #1 failed\n");
401         goto end;
402     }
403
404     data_str = "what do ya want for nothing?";
405     key_str = "Jefe";
406     ct_bi = bi_str_import(bi_ctx, "EFFCDF6AE5EB2FA2D27416D5F184DF9C259A7C79");
407     bi_export(bi_ctx, ct_bi, ct, SHA1_SIZE);
408
409     hmac_sha1((const uint8_t *)data_str, 28, (const uint8_t *)key_str, 5, dgst);
410     if (memcmp(dgst, ct, SHA1_SIZE))
411     {
412         printf("HMAC SHA1 failed\n");
413         exit(1);
414     }
415
416     res = 0;
417     printf("All HMAC tests passed\n");
418
419 end:
420     return res;
421 }
422
423 /**************************************************************************
424  * BIGINT tests 
425  *
426  **************************************************************************/
427 static int BIGINT_test(BI_CTX *ctx)
428 {
429     int res = 1;
430     bigint *bi_data, *bi_exp, *bi_res;
431     const char *expnt, *plaintext, *mod;
432     uint8_t compare[MAX_KEY_BYTE_SIZE];
433
434     /**
435      * 512 bit key
436      */
437     plaintext = /* 64 byte number */
438         "01aaaaaaaaaabbbbbbbbbbbbbbbccccccccccccccdddddddddddddeeeeeeeeee";
439
440     mod = "C30773C8ABE09FCC279EE0E5343370DE"
441           "8B2FFDB6059271E3005A7CEEF0D35E0A"
442           "1F9915D95E63560836CC2EB2C289270D"
443           "BCAE8CAF6F5E907FC2759EE220071E1B";
444
445     expnt = "A1E556CD1738E10DF539E35101334E97"
446           "BE8D391C57A5C89A7AD9A2EA2ACA1B3D"
447           "F3140F5091CC535CBAA47CEC4159EE1F"
448           "B6A3661AFF1AB758426EAB158452A9B9";
449
450     bi_data = bi_import(ctx, (uint8_t *)plaintext, strlen(plaintext));
451     bi_exp = int_to_bi(ctx, 0x10001);
452     bi_set_mod(ctx, bi_str_import(ctx, mod), 0);
453     bi_res = bi_mod_power(ctx, bi_data, bi_exp);
454
455     bi_data = bi_res;   /* resuse again - see if we get the original */
456
457     bi_exp = bi_str_import(ctx, expnt);
458     bi_res = bi_mod_power(ctx, bi_data, bi_exp);
459     bi_free_mod(ctx, 0);
460
461     bi_export(ctx, bi_res, compare, 64);
462     if (memcmp(plaintext, compare, 64) != 0)
463         goto end;
464
465     printf("All BIGINT tests passed\n");
466     res = 0;
467
468 end:
469     return res;
470 }
471
472 /**************************************************************************
473  * RSA tests 
474  *
475  * Use the results from openssl to verify PKCS1 etc 
476  **************************************************************************/
477 static int RSA_test(void)
478 {
479     int res = 1;
480     const char *plaintext = /* 128 byte hex number */
481         "1aaaaaaaaaabbbbbbbbbbbbbbbccccccccccccccdddddddddddddeeeeeeeeee2"
482         "1aaaaaaaaaabbbbbbbbbbbbbbbccccccccccccccdddddddddddddeeeeeeeee2\012";
483     uint8_t enc_data[128], dec_data[128];
484     RSA_CTX *rsa_ctx = NULL;
485     BI_CTX *bi_ctx;
486     bigint *plaintext_bi;
487     bigint *enc_data_bi, *dec_data_bi;
488     uint8_t enc_data2[128], dec_data2[128];
489     int size;
490     int len; 
491     uint8_t *buf;
492
493     /* extract the private key elements */
494     len = get_file("../ssl/test/axTLS.key_1024", &buf);
495     if (asn1_get_private_key(buf, len, &rsa_ctx) < 0)
496     {
497         goto end;
498     }
499
500     free(buf);
501     bi_ctx = rsa_ctx->bi_ctx;
502     plaintext_bi = bi_import(bi_ctx, 
503             (const uint8_t *)plaintext, strlen(plaintext));
504
505     /* basic rsa encrypt */
506     enc_data_bi = RSA_public(rsa_ctx, plaintext_bi);
507     bi_export(bi_ctx, bi_copy(enc_data_bi), enc_data, sizeof(enc_data));
508
509     /* basic rsa decrypt */
510     dec_data_bi = RSA_private(rsa_ctx, enc_data_bi);
511     bi_export(bi_ctx, dec_data_bi, dec_data, sizeof(dec_data));
512
513     if (memcmp(dec_data, plaintext, strlen(plaintext)))
514     {
515         printf("Error: DECRYPT #1 failed\n");
516         goto end;
517     }
518
519     RSA_encrypt(rsa_ctx, (const uint8_t *)"abc", 3, enc_data2, 0);
520     size = RSA_decrypt(rsa_ctx, enc_data2, dec_data2, 1);
521     if (memcmp("abc", dec_data2, 3))
522     {
523         printf("Error: ENCRYPT/DECRYPT #2 failed\n");
524         goto end;
525     }
526
527     RSA_free(rsa_ctx);
528     res = 0;
529     printf("All RSA tests passed\n");
530
531 end:
532     return res;
533 }
534
535 /**************************************************************************
536  * Cert Testing
537  *
538  **************************************************************************/
539 static int cert_tests(void)
540 {
541     int res = -1, len;
542     X509_CTX *x509_ctx;
543     SSL_CTX *ssl_ctx;
544     uint8_t *buf;
545
546     /* check a bunch of 3rd party certificates */
547     ssl_ctx = ssl_ctx_new(0, 0);
548     len = get_file("../ssl/test/microsoft.x509_ca", &buf);
549     if ((res = add_cert_auth(ssl_ctx, buf, len)) < 0)
550     {
551         printf("Cert #1\n");
552         ssl_display_error(res);
553         goto bad_cert;
554     }
555
556     ssl_ctx_free(ssl_ctx);
557     free(buf);
558
559     ssl_ctx = ssl_ctx_new(0, 0);
560     len = get_file("../ssl/test/thawte.x509_ca", &buf);
561     if ((res = add_cert_auth(ssl_ctx, buf, len)) < 0)
562     {
563         printf("Cert #2\n");
564         ssl_display_error(res);
565         goto bad_cert;
566     }
567
568     ssl_ctx_free(ssl_ctx);
569     free(buf);
570
571     ssl_ctx = ssl_ctx_new(0, 0);
572     len = get_file("../ssl/test/deutsche_telecom.x509_ca", &buf);
573     if ((res = add_cert_auth(ssl_ctx, buf, len)) < 0)
574     {
575         printf("Cert #3\n");
576         ssl_display_error(res);
577         goto bad_cert;
578     }
579
580     ssl_ctx_free(ssl_ctx);
581     free(buf);
582
583     ssl_ctx = ssl_ctx_new(0, 0);
584     len = get_file("../ssl/test/equifax.x509_ca", &buf);
585     if ((res = add_cert_auth(ssl_ctx, buf, len)) < 0)
586     {
587         printf("Cert #4\n");
588         ssl_display_error(res);
589         goto bad_cert;
590     }
591
592     ssl_ctx_free(ssl_ctx);
593     free(buf);
594
595     ssl_ctx = ssl_ctx_new(0, 0);
596     len = get_file("../ssl/test/gnutls.cer", &buf);
597     if ((res = add_cert(ssl_ctx, buf, len)) < 0)
598     {
599         printf("Cert #5\n");
600         ssl_display_error(res);
601         goto bad_cert;
602     }
603
604     ssl_ctx_free(ssl_ctx);
605     free(buf);
606
607     ssl_ctx = ssl_ctx_new(0, 0);
608     len = get_file("../ssl/test/socgen.cer", &buf);
609     if ((res = add_cert(ssl_ctx, buf, len)) < 0)
610     {
611         printf("Cert #6\n");
612         ssl_display_error(res);
613         goto bad_cert;
614     }
615
616     ssl_ctx_free(ssl_ctx);
617     free(buf);
618
619     ssl_ctx = ssl_ctx_new(0, 0);
620     len = get_file("../ssl/test/verisign.x509_ca", &buf);
621     if ((res = add_cert_auth(ssl_ctx, buf, len)) <0)
622     {
623         printf("Cert #7\n");
624         ssl_display_error(res);
625         goto bad_cert;
626     }
627
628     ssl_ctx_free(ssl_ctx);
629     free(buf);
630
631     if (get_file("../ssl/test/verisign.x509_my_cert", &buf) < 0 ||
632                                     x509_new(buf, &len, &x509_ctx))
633     {
634         printf("Cert #8\n");
635         ssl_display_error(res);
636         goto bad_cert;
637     }
638
639     x509_free(x509_ctx);
640     free(buf);
641
642     ssl_ctx = ssl_ctx_new(0, 0);
643     if ((res = ssl_obj_load(ssl_ctx, 
644               SSL_OBJ_X509_CERT, "../ssl/test/ms_iis.cer", NULL)) != SSL_OK)
645     {
646         ssl_display_error(res);
647         goto bad_cert;
648     }
649
650     ssl_ctx_free(ssl_ctx);
651     res = 0;        /* all ok */
652     printf("All Certificate tests passed\n");
653
654 bad_cert:
655     if (res)
656         printf("Error: A certificate test failed\n");
657     return res;
658 }
659
660 /**
661  * init a server socket.
662  */
663 static int server_socket_init(int *port)
664 {
665     struct sockaddr_in serv_addr;
666     int server_fd;
667     char yes = 1;
668
669     /* Create socket for incoming connections */
670     if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
671     {
672         return -1;
673     }
674       
675     setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
676
677 go_again:
678     /* Construct local address structure */
679     memset(&serv_addr, 0, sizeof(serv_addr));      /* Zero out structure */
680     serv_addr.sin_family = AF_INET;                /* Internet address family */
681     serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */
682     serv_addr.sin_port = htons(*port);              /* Local port */
683
684     /* Bind to the local address */
685     if (bind(server_fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
686     {
687         (*port)++;
688         goto go_again;
689     }
690     /* Mark the socket so it will listen for incoming connections */
691     if (listen(server_fd, 3000) < 0)
692     {
693         return -1;
694     }
695
696     return server_fd;
697 }
698
699 /**
700  * init a client socket.
701  */
702 static int client_socket_init(uint16_t port)
703 {
704     struct sockaddr_in address;
705     int client_fd;
706
707     address.sin_family = AF_INET;
708     address.sin_port = htons(port);
709     address.sin_addr.s_addr =  inet_addr("127.0.0.1");
710     client_fd = socket(AF_INET, SOCK_STREAM, 0);
711     if (connect(client_fd, (struct sockaddr *)&address, sizeof(address)) < 0)
712     {
713         perror("socket");
714         SOCKET_CLOSE(client_fd);
715         client_fd = -1;
716     }
717
718     return client_fd;
719 }
720
721 /**************************************************************************
722  * SSL Server Testing
723  *
724  **************************************************************************/
725 typedef struct
726 {
727     /* not used as yet */
728     int dummy;
729 } SVR_CTX;
730
731 typedef struct
732 {
733     const char *testname;
734     const char *openssl_option;
735 } client_t;
736
737 static void do_client(client_t *clnt)
738 {
739     char openssl_buf[2048];
740
741     /* make sure the main thread goes first */
742     sleep(0);
743
744     /* show the session ids in the reconnect test */
745     if (strcmp(clnt->testname, "Session Reuse") == 0)
746     {
747         sprintf(openssl_buf, "echo \"hello client\" | openssl s_client "
748             "-connect localhost:%d %s 2>&1 | grep \"Session-ID:\"", 
749             g_port, clnt->openssl_option);
750     }
751     else
752     {
753         sprintf(openssl_buf, "echo \"hello client\" | openssl s_client "
754 #ifdef WIN32
755             "-connect localhost:%d -quiet %s",
756 #else
757             "-connect localhost:%d -quiet %s > /dev/null 2>&1",
758 #endif
759         g_port, clnt->openssl_option);
760     }
761
762     system(openssl_buf);
763 }
764
765 static int SSL_server_test(
766         const char *testname, 
767         const char *openssl_option, 
768         const char *device_cert, 
769         const char *product_cert, 
770         const char *private_key,
771         const char *ca_cert,
772         const char *password,
773         int axolotls_option)
774 {
775     int server_fd, ret = 0;
776     SSL_CTX *ssl_ctx = NULL;
777     struct sockaddr_in client_addr;
778     uint8_t *read_buf;
779     socklen_t clnt_len = sizeof(client_addr);
780     client_t client_data;
781 #ifndef WIN32
782     pthread_t thread;
783 #endif
784     g_port++;
785
786     client_data.testname = testname;
787     client_data.openssl_option = openssl_option;
788
789     if ((server_fd = server_socket_init(&g_port)) < 0)
790         goto error;
791
792     if (private_key)
793     {
794         axolotls_option |= SSL_NO_DEFAULT_KEY;
795     }
796
797     if ((ssl_ctx = ssl_ctx_new(axolotls_option, SSL_DEFAULT_SVR_SESS)) == NULL)
798     {
799         ret = SSL_ERROR_INVALID_KEY;
800         goto error;
801     }
802
803     if (private_key)
804     {
805         int obj_type = SSL_OBJ_RSA_KEY;
806
807         if (strstr(private_key, ".p8"))
808             obj_type = SSL_OBJ_PKCS8;
809         else if (strstr(private_key, ".p12"))
810             obj_type = SSL_OBJ_PKCS12;
811
812         if (ssl_obj_load(ssl_ctx, obj_type, private_key, password))
813         {
814             ret = SSL_ERROR_INVALID_KEY;
815             goto error;
816         }
817     }
818
819     if (device_cert)             /* test chaining */
820     {
821         if ((ret = ssl_obj_load(ssl_ctx, 
822                         SSL_OBJ_X509_CERT, device_cert, NULL)) != SSL_OK)
823             goto error;
824     }
825
826     if (product_cert)             /* test chaining */
827     {
828         if ((ret = ssl_obj_load(ssl_ctx, 
829                         SSL_OBJ_X509_CERT, product_cert, NULL)) != SSL_OK)
830             goto error;
831     }
832
833     if (ca_cert)                  /* test adding certificate authorities */
834     {
835         if ((ret = ssl_obj_load(ssl_ctx, 
836                         SSL_OBJ_X509_CACERT, ca_cert, NULL)) != SSL_OK)
837             goto error;
838     }
839
840 #ifndef WIN32
841     pthread_create(&thread, NULL, 
842                 (void *(*)(void *))do_client, (void *)&client_data);
843     pthread_detach(thread);
844 #else
845     CreateThread(NULL, 1024, (LPTHREAD_START_ROUTINE)do_client, 
846             (LPVOID)&client_data, 0, NULL);
847 #endif
848
849     for (;;)
850     {
851         int client_fd, size = 0; 
852         SSL *ssl;
853
854         /* Wait for a client to connect */
855         if ((client_fd = accept(server_fd, 
856                         (struct sockaddr *)&client_addr, &clnt_len)) < 0)
857         {
858             ret = SSL_ERROR_SOCK_SETUP_FAILURE;
859             goto error;
860         }
861         
862         /* we are ready to go */
863         ssl = ssl_server_new(ssl_ctx, client_fd);
864         while ((size = ssl_read(ssl, &read_buf)) == SSL_OK);
865         SOCKET_CLOSE(client_fd);
866         
867         if (size < SSL_OK) /* got some alert or something nasty */
868         {
869             ret = size;
870
871             if (ret == SSL_ERROR_CONN_LOST)
872             {
873                 ret = SSL_OK;
874                 continue;
875             }
876
877             break;  /* we've got a problem */
878         }
879         else /* looks more promising */
880         {
881             if (strstr("hello client", (char *)read_buf) == NULL)
882             {
883                 printf("SSL server test \"%s\" passed\n", testname);
884                 TTY_FLUSH();
885                 ret = 0;
886                 break;
887             }
888         }
889
890         ssl_free(ssl);
891     }
892
893     SOCKET_CLOSE(server_fd);
894
895 error:
896     ssl_ctx_free(ssl_ctx);
897     return ret;
898 }
899
900 int SSL_server_tests(void)
901 {
902     int ret = -1;
903     struct stat stat_buf;
904     SVR_CTX svr_test_ctx;
905     memset(&svr_test_ctx, 0, sizeof(SVR_CTX));
906
907     printf("### starting server tests\n"); TTY_FLUSH();
908
909     /* Go through the algorithms */
910
911     /* 
912      * TLS1 client hello 
913      */
914     if ((ret = SSL_server_test("TLSv1", "-cipher RC4-SHA -tls1", 
915                     NULL, NULL, NULL, NULL, NULL, DEFAULT_SVR_OPTION)))
916         goto cleanup;
917
918     /*
919      * AES128-SHA
920      */
921     if ((ret = SSL_server_test("AES256-SHA", "-cipher AES128-SHA", 
922                     DEFAULT_CERT, NULL, DEFAULT_KEY, NULL, NULL,
923                     DEFAULT_SVR_OPTION)))
924         goto cleanup;
925
926     /*
927      * AES256-SHA
928      */
929     if ((ret = SSL_server_test("AES256-SHA", "-cipher AES128-SHA", 
930                     DEFAULT_CERT, NULL, DEFAULT_KEY, NULL, NULL,
931                     DEFAULT_SVR_OPTION)))
932         goto cleanup;
933
934     /*
935      * RC4-SHA
936      */
937     if ((ret = SSL_server_test("RC4-SHA", "-cipher RC4-SHA", 
938                 DEFAULT_CERT, NULL, DEFAULT_KEY, NULL, NULL,
939                 DEFAULT_SVR_OPTION)))
940         goto cleanup;
941
942     /*
943      * RC4-MD5
944      */
945     if ((ret = SSL_server_test("RC4-MD5", "-cipher RC4-MD5", 
946                 DEFAULT_CERT, NULL, DEFAULT_KEY, NULL, NULL,
947                 DEFAULT_SVR_OPTION)))
948         goto cleanup;
949
950     /*
951      * Session Reuse
952      * all the session id's should match for session resumption.
953      */
954     if ((ret = SSL_server_test("Session Reuse", 
955                     "-cipher RC4-SHA -reconnect", 
956                     DEFAULT_CERT, NULL, DEFAULT_KEY, NULL, NULL,
957                     DEFAULT_SVR_OPTION)))
958         goto cleanup;
959
960     /* 
961      * 512 bit RSA key 
962      */
963     if ((ret = SSL_server_test("512 bit key", "-cipher RC4-SHA", 
964                     "../ssl/test/axTLS.x509_512.cer", NULL, 
965                     "../ssl/test/axTLS.key_512",
966                     NULL, NULL, DEFAULT_SVR_OPTION)))
967         goto cleanup;
968
969     /* 
970      * 1024 bit RSA key (check certificate chaining)
971      */
972     if ((ret = SSL_server_test("1024 bit key", 
973                     "-cipher RC4-SHA", 
974                     "../ssl/test/axTLS.x509_device.cer", 
975                     "../ssl/test/axTLS.x509_512.cer", 
976                     "../ssl/test/axTLS.device_key",
977                     NULL, NULL, DEFAULT_SVR_OPTION)))
978         goto cleanup;
979
980     /* 
981      * 2048 bit RSA key 
982      */
983     if ((ret = SSL_server_test("2048 bit key", 
984                     "-cipher RC4-SHA",
985                     "../ssl/test/axTLS.x509_2048.cer", NULL, 
986                     "../ssl/test/axTLS.key_2048",
987                     NULL, NULL, DEFAULT_SVR_OPTION)))
988         goto cleanup;
989
990     /* 
991      * 4096 bit RSA key 
992      */
993     if ((ret = SSL_server_test("4096 bit key", 
994                     "-cipher RC4-SHA",
995                     "../ssl/test/axTLS.x509_4096.cer", NULL, 
996                     "../ssl/test/axTLS.key_4096",
997                     NULL, NULL, DEFAULT_SVR_OPTION)))
998         goto cleanup;
999
1000     /* 
1001      * Client Verification
1002      */
1003     if ((ret = SSL_server_test("Client Verification", 
1004                     "-cipher RC4-SHA -tls1 "
1005                     "-cert ../ssl/test/axTLS.x509_2048.pem "
1006                     "-key ../ssl/test/axTLS.key_2048.pem ",
1007                     NULL, NULL, NULL, 
1008                     "../ssl/test/axTLS.ca_x509.cer", NULL,
1009                     DEFAULT_SVR_OPTION|SSL_CLIENT_AUTHENTICATION)))
1010         goto cleanup;
1011
1012     /* this test should fail */
1013     if (stat("../ssl/test/axTLS.x509_bad_before.pem", &stat_buf) >= 0)
1014     {
1015         if ((ret = SSL_server_test("Bad Before Cert", 
1016                     "-cipher RC4-SHA -tls1 "
1017                     "-cert ../ssl/test/axTLS.x509_bad_before.pem "
1018                     "-key ../ssl/test/axTLS.key_512.pem ",
1019                     NULL, NULL, NULL, 
1020                     "../ssl/test/axTLS.ca_x509.cer", NULL,
1021                     DEFAULT_SVR_OPTION|SSL_CLIENT_AUTHENTICATION)) !=
1022                             SSL_X509_ERROR(X509_VFY_ERROR_NOT_YET_VALID))
1023             goto cleanup;
1024
1025         printf("SSL server test \"%s\" passed\n", "Bad Before Cert");
1026         TTY_FLUSH();
1027         ret = 0;    /* is ok */
1028     }
1029
1030     /* this test should fail */
1031     if ((ret = SSL_server_test("Bad After Cert", 
1032                     "-cipher RC4-SHA -tls1 "
1033                     "-cert ../ssl/test/axTLS.x509_bad_after.pem "
1034                     "-key ../ssl/test/axTLS.key_512.pem ",
1035                     NULL, NULL, NULL, 
1036                     "../ssl/test/axTLS.ca_x509.cer", NULL,
1037                     DEFAULT_SVR_OPTION|SSL_CLIENT_AUTHENTICATION)) !=
1038                             SSL_X509_ERROR(X509_VFY_ERROR_EXPIRED))
1039         goto cleanup;
1040
1041     printf("SSL server test \"%s\" passed\n", "Bad After Cert");
1042     TTY_FLUSH();
1043
1044     /* 
1045      * Key in PEM format
1046      */
1047     if ((ret = SSL_server_test("Key in PEM format",
1048                     "-cipher RC4-SHA", 
1049                     "../ssl/test/axTLS.x509_512.cer", NULL, 
1050                     "../ssl/test/axTLS.key_512.pem", NULL,
1051                     NULL, DEFAULT_SVR_OPTION)))
1052         goto cleanup;
1053
1054     /* 
1055      * Cert in PEM format
1056      */
1057     if ((ret = SSL_server_test("Cert in PEM format", 
1058                     "-cipher RC4-SHA", 
1059                     "../ssl/test/axTLS.x509_512.pem", NULL, 
1060                     "../ssl/test/axTLS.key_512.pem", NULL,
1061                     NULL, DEFAULT_SVR_OPTION)))
1062         goto cleanup;
1063
1064     /* 
1065      * Cert chain in PEM format
1066      */
1067     if ((ret = SSL_server_test("Cert chain in PEM format", 
1068                     "-cipher RC4-SHA", 
1069                     "../ssl/test/axTLS.x509_device.pem", 
1070                     NULL, "../ssl/test/axTLS.device_key.pem",
1071                     "../ssl/test/axTLS.ca_x509.pem", NULL, DEFAULT_SVR_OPTION)))
1072         goto cleanup;
1073
1074     /* 
1075      * AES128 Encrypted key 
1076      */
1077     if ((ret = SSL_server_test("AES128 encrypted key", 
1078                     "-cipher RC4-SHA", 
1079                     "../ssl/test/axTLS.x509_aes128.pem", NULL, 
1080                     "../ssl/test/axTLS.key_aes128.pem",
1081                     NULL, "abcd", DEFAULT_SVR_OPTION)))
1082         goto cleanup;
1083
1084     /* 
1085      * AES256 Encrypted key 
1086      */
1087     if ((ret = SSL_server_test("AES256 encrypted key", 
1088                     "-cipher RC4-SHA", 
1089                     "../ssl/test/axTLS.x509_aes256.pem", NULL, 
1090                     "../ssl/test/axTLS.key_aes256.pem",
1091                     NULL, "abcd", DEFAULT_SVR_OPTION)))
1092         goto cleanup;
1093
1094     /* 
1095      * AES128 Encrypted invalid key 
1096      */
1097     if ((ret = SSL_server_test("AES128 encrypted invalid key", 
1098                     "-cipher RC4-SHA", 
1099                     "../ssl/test/axTLS.x509_aes128.pem", NULL, 
1100                     "../ssl/test/axTLS.key_aes128.pem",
1101                     NULL, "xyz", DEFAULT_SVR_OPTION)) != SSL_ERROR_INVALID_KEY)
1102         goto cleanup;
1103
1104     printf("SSL server test \"%s\" passed\n", "AES128 encrypted invalid key");
1105     TTY_FLUSH();
1106
1107     /*
1108      * PKCS#8 key (encrypted)
1109      */
1110     if ((ret = SSL_server_test("pkcs#8 encrypted", "-cipher RC4-SHA", 
1111                 DEFAULT_CERT, NULL, "../ssl/test/axTLS.encrypted.p8", 
1112                 NULL, "abcd", DEFAULT_SVR_OPTION)))
1113         goto cleanup;
1114
1115     /*
1116      * PKCS#8 key (unencrypted)
1117      */
1118     if ((ret = SSL_server_test("pkcs#8 unencrypted", "-cipher RC4-SHA", 
1119                 DEFAULT_CERT, NULL, "../ssl/test/axTLS.unencrypted.p8", 
1120                 NULL, NULL, DEFAULT_SVR_OPTION)))
1121         goto cleanup;
1122
1123     /*
1124      * PKCS#12 key/certificate
1125      */
1126     if ((ret = SSL_server_test("pkcs#12 with CA", "-cipher RC4-SHA", 
1127                 NULL, NULL, "../ssl/test/axTLS.withCA.p12", 
1128                 NULL, "abcd", DEFAULT_SVR_OPTION)))
1129         goto cleanup;
1130
1131     if ((ret = SSL_server_test("pkcs#12 no CA", "-cipher RC4-SHA", 
1132                 DEFAULT_CERT, NULL, "../ssl/test/axTLS.withoutCA.p12", 
1133                 NULL, "abcd", DEFAULT_SVR_OPTION)))
1134         goto cleanup;
1135
1136     /*
1137      *
1138      */
1139
1140     ret = 0;
1141
1142 cleanup:
1143     if (ret)
1144     {
1145         printf("Error: A server test failed\n");
1146         ssl_display_error(ret);
1147         exit(1);
1148     }
1149     else
1150     {
1151         printf("All server tests passed\n"); TTY_FLUSH();
1152     }
1153
1154     return ret;
1155 }
1156
1157 /**************************************************************************
1158  * SSL Client Testing
1159  *
1160  **************************************************************************/
1161 typedef struct
1162 {
1163     uint8_t session_id[SSL_SESSION_ID_SIZE];
1164 #ifndef WIN32
1165     pthread_t server_thread;
1166 #endif
1167     int start_server;
1168     int stop_server;
1169     int do_reneg;
1170 } CLNT_SESSION_RESUME_CTX;
1171
1172 typedef struct
1173 {
1174     const char *testname;
1175     const char *openssl_option;
1176 } server_t;
1177
1178 static void do_server(server_t *svr)
1179 {
1180     char openssl_buf[2048];
1181 #ifndef WIN32
1182     pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
1183 #endif
1184     sprintf(openssl_buf, "openssl s_server -tls1 " 
1185             "-accept %d -quiet %s ", g_port, svr->openssl_option);
1186     system(openssl_buf);
1187 }
1188
1189 static int SSL_client_test(
1190         const char *test,
1191         SSL_CTX **ssl_ctx,
1192         const char *openssl_option, 
1193         CLNT_SESSION_RESUME_CTX *sess_resume,
1194         uint32_t client_options,
1195         const char *private_key,
1196         const char *password,
1197         const char *cert)
1198 {
1199     server_t server_data;
1200     SSL *ssl = NULL;
1201     int client_fd = -1;
1202     uint8_t *session_id = NULL;
1203     int ret = 1;
1204 #ifndef WIN32
1205     pthread_t thread;
1206 #endif
1207
1208     if (sess_resume == NULL || sess_resume->start_server)
1209     {
1210         g_port++;
1211         server_data.openssl_option = openssl_option;
1212
1213 #ifndef WIN32
1214         pthread_create(&thread, NULL, 
1215                 (void *(*)(void *))do_server, (void *)&server_data);
1216         pthread_detach(thread);
1217 #else
1218         CreateThread(NULL, 1024, (LPTHREAD_START_ROUTINE)do_server, 
1219             (LPVOID)&server_data, 0, NULL);
1220 #endif
1221     }
1222     
1223     usleep(200000);           /* allow server to start */
1224
1225     if (*ssl_ctx == NULL)
1226     {
1227         if (private_key)
1228         {
1229             client_options |= SSL_NO_DEFAULT_KEY;
1230         }
1231
1232         if ((*ssl_ctx = ssl_ctx_new(
1233                             client_options, SSL_DEFAULT_CLNT_SESS)) == NULL)
1234         {
1235             ret = SSL_ERROR_INVALID_KEY;
1236             goto client_test_exit;
1237         }
1238
1239         if (private_key)
1240         {
1241             int obj_type = SSL_OBJ_RSA_KEY;
1242
1243             if (strstr(private_key, ".p8"))
1244                 obj_type = SSL_OBJ_PKCS8;
1245             else if (strstr(private_key, ".p12"))
1246                 obj_type = SSL_OBJ_PKCS12;
1247
1248             if (ssl_obj_load(*ssl_ctx, obj_type, private_key, password))
1249             {
1250                 ret = SSL_ERROR_INVALID_KEY;
1251                 goto client_test_exit;
1252             }
1253         }
1254
1255         if (cert)                  
1256         {
1257             if ((ret = ssl_obj_load(*ssl_ctx, 
1258                             SSL_OBJ_X509_CERT, cert, NULL)) != SSL_OK)
1259             {
1260                 printf("could not add cert %s (%d)\n", cert, ret);
1261                 TTY_FLUSH();
1262                 goto client_test_exit;
1263             }
1264         }
1265
1266         if (ssl_obj_load(*ssl_ctx, SSL_OBJ_X509_CACERT, 
1267                                 "../ssl/test/axTLS.ca_x509.cer", NULL))
1268         {
1269             printf("could not add cert auth\n"); TTY_FLUSH();
1270             goto client_test_exit;
1271         }
1272     }
1273     
1274     if (sess_resume && !sess_resume->start_server) 
1275     {
1276         session_id = sess_resume->session_id;
1277     }
1278
1279     if ((client_fd = client_socket_init(g_port)) < 0)
1280     {
1281         printf("could not start socket on %d\n", g_port); TTY_FLUSH();
1282         goto client_test_exit;
1283     }
1284
1285     ssl = ssl_client_new(*ssl_ctx, client_fd, session_id, sizeof(session_id));
1286
1287     /* check the return status */
1288     if ((ret = ssl_handshake_status(ssl)))
1289         goto client_test_exit;
1290
1291     /* renegotiate client */
1292     if (sess_resume && sess_resume->do_reneg) 
1293     {
1294         if (ssl_renegotiate(ssl) < 0)
1295             goto client_test_exit;
1296     }
1297
1298     if (sess_resume)
1299     {
1300         memcpy(sess_resume->session_id, 
1301                 ssl_get_session_id(ssl), SSL_SESSION_ID_SIZE);
1302     }
1303
1304     if (IS_SET_SSL_FLAG(SSL_SERVER_VERIFY_LATER) && 
1305                                             (ret = ssl_verify_cert(ssl)))
1306     {
1307         goto client_test_exit;
1308     }
1309
1310     ssl_write(ssl, (uint8_t *)"hello world\n", 13);
1311     if (sess_resume)
1312     {
1313         const uint8_t *sess_id = ssl_get_session_id(ssl);
1314         int i;
1315
1316         printf("    Session-ID: ");
1317         for (i = 0; i < SSL_SESSION_ID_SIZE; i++)
1318         {
1319             printf("%02X", sess_id[i]);
1320         }
1321         printf("\n");
1322         TTY_FLUSH();
1323     }
1324
1325     ret = 0;
1326
1327 client_test_exit:
1328     ssl_free(ssl);
1329     SOCKET_CLOSE(client_fd);
1330     usleep(200000);           /* allow openssl to say something */
1331
1332     if (sess_resume)
1333     {
1334         if (sess_resume->stop_server)
1335         {
1336             ssl_ctx_free(*ssl_ctx);
1337             *ssl_ctx = NULL;
1338 #ifndef WIN32
1339             pthread_cancel(sess_resume->server_thread);
1340 #endif
1341         }
1342         else if (sess_resume->start_server)
1343         {
1344 #ifndef WIN32
1345            sess_resume->server_thread = thread;
1346 #endif
1347         }
1348     }
1349     else
1350     {
1351         ssl_ctx_free(*ssl_ctx);
1352         *ssl_ctx = NULL;
1353 #ifndef WIN32
1354         pthread_cancel(thread);
1355 #endif
1356     }
1357
1358     if (ret == 0)
1359     {
1360         printf("SSL client test \"%s\" passed\n", test);
1361         TTY_FLUSH();
1362     }
1363
1364     return ret;
1365 }
1366
1367 int SSL_client_tests(void)
1368 {
1369     int ret =  -1;
1370     SSL_CTX *ssl_ctx = NULL;
1371     CLNT_SESSION_RESUME_CTX sess_resume;
1372     memset(&sess_resume, 0, sizeof(CLNT_SESSION_RESUME_CTX));
1373
1374     sess_resume.start_server = 1;
1375     printf("### starting client tests\n");
1376    
1377     if ((ret = SSL_client_test("512 bit key", 
1378                     &ssl_ctx,
1379                     "-cert ../ssl/test/axTLS.x509_512.pem "
1380                     "-key ../ssl/test/axTLS.key_512.pem", &sess_resume, 
1381                     DEFAULT_CLNT_OPTION, NULL, NULL, NULL)))
1382         goto cleanup;
1383
1384     /* all the session id's should match for session resumption */
1385     sess_resume.start_server = 0;
1386     if ((ret = SSL_client_test("Client session resumption #1", 
1387                     &ssl_ctx, NULL, &sess_resume, 
1388                     DEFAULT_CLNT_OPTION, NULL, NULL, NULL)))
1389         goto cleanup;
1390
1391     sess_resume.do_reneg = 1;
1392     if ((ret = SSL_client_test("Client renegotiation", 
1393                     &ssl_ctx, NULL, &sess_resume, 
1394                     DEFAULT_CLNT_OPTION, NULL, NULL, NULL)))
1395         goto cleanup;
1396     sess_resume.do_reneg = 0;
1397
1398     sess_resume.stop_server = 1;
1399     if ((ret = SSL_client_test("Client session resumption #2", 
1400                     &ssl_ctx, NULL, &sess_resume, 
1401                     DEFAULT_CLNT_OPTION, NULL, NULL, NULL)))
1402         goto cleanup;
1403
1404     if ((ret = SSL_client_test("1024 bit key", 
1405                     &ssl_ctx,
1406                     "-cert ../ssl/test/axTLS.x509_1024.pem "
1407                     "-key ../ssl/test/axTLS.key_1024.pem", NULL,
1408                     DEFAULT_CLNT_OPTION, NULL, NULL, NULL)))
1409         goto cleanup;
1410
1411     if ((ret = SSL_client_test("2048 bit key", 
1412                     &ssl_ctx,
1413                     "-cert ../ssl/test/axTLS.x509_2048.pem "
1414                     "-key ../ssl/test/axTLS.key_2048.pem",  NULL,
1415                     DEFAULT_CLNT_OPTION, NULL, NULL, NULL)))
1416         goto cleanup;
1417
1418     if ((ret = SSL_client_test("4096 bit key", 
1419                     &ssl_ctx,
1420                     "-cert ../ssl/test/axTLS.x509_4096.pem "
1421                     "-key ../ssl/test/axTLS.key_4096.pem", NULL,
1422                     DEFAULT_CLNT_OPTION, NULL, NULL, NULL)))
1423         goto cleanup;
1424
1425     if ((ret = SSL_client_test("Server cert chaining", 
1426                     &ssl_ctx,
1427                     "-cert ../ssl/test/axTLS.x509_device.pem "
1428                     "-key ../ssl/test/axTLS.device_key.pem "
1429                     "-CAfile ../ssl/test/axTLS.x509_512.pem ", NULL,
1430                     DEFAULT_CLNT_OPTION, NULL, NULL, NULL)))
1431         goto cleanup;
1432
1433     /* Check the server can verify the client */
1434     if ((ret = SSL_client_test("Client peer authentication",
1435                     &ssl_ctx,
1436                     "-cert ../ssl/test/axTLS.x509_2048.pem "
1437                     "-key ../ssl/test/axTLS.key_2048.pem "
1438                     "-CAfile ../ssl/test/axTLS.ca_x509.pem "
1439                     "-verify 1 ", NULL, DEFAULT_CLNT_OPTION, 
1440                     "../ssl/test/axTLS.key_1024", NULL,
1441                     "../ssl/test/axTLS.x509_1024.cer")))
1442         goto cleanup;
1443
1444     /* Should get an "ERROR" from openssl (as the handshake fails as soon as
1445      * the certificate verification fails) */
1446     if ((ret = SSL_client_test("Error: Expired cert (verify now)",
1447                     &ssl_ctx,
1448                     "-cert ../ssl/test/axTLS.x509_bad_after.pem "
1449                     "-key ../ssl/test/axTLS.key_512.pem", NULL,
1450                     DEFAULT_CLNT_OPTION, NULL, NULL, NULL)) != 
1451                             SSL_X509_ERROR(X509_VFY_ERROR_EXPIRED))
1452     {
1453         printf("*** Error: %d\n", ret);
1454         goto cleanup;
1455     }
1456
1457     printf("SSL client test \"Expired cert (verify now)\" passed\n");
1458
1459     /* There is no "ERROR" from openssl */
1460     if ((ret = SSL_client_test("Error: Expired cert (verify later)", 
1461                     &ssl_ctx,
1462                     "-cert ../ssl/test/axTLS.x509_bad_after.pem "
1463                     "-key ../ssl/test/axTLS.key_512.pem", NULL,
1464                     DEFAULT_CLNT_OPTION|SSL_SERVER_VERIFY_LATER, NULL, 
1465                     NULL, NULL)) != SSL_X509_ERROR(X509_VFY_ERROR_EXPIRED))
1466     {
1467         printf("*** Error: %d\n", ret);
1468         goto cleanup;
1469     }
1470
1471     printf("SSL client test \"Expired cert (verify later)\" passed\n");
1472     ret = 0;
1473
1474 cleanup:
1475     if (ret)
1476     {
1477         ssl_display_error(ret);
1478         printf("Error: A client test failed\n");
1479         exit(1);
1480     }
1481     else
1482     {
1483         printf("All client tests passed\n"); TTY_FLUSH();
1484     }
1485
1486     return ret;
1487 }
1488
1489 /**************************************************************************
1490  * SSL Basic Testing (test a big packet handshake)
1491  *
1492  **************************************************************************/
1493 static uint8_t basic_buf[256*1024];
1494
1495 static void do_basic(void)
1496 {
1497     int client_fd;
1498     SSL *ssl_clnt;
1499     SSL_CTX *ssl_clnt_ctx = ssl_ctx_new(
1500                             DEFAULT_CLNT_OPTION, SSL_DEFAULT_CLNT_SESS);
1501     usleep(200000);           /* allow server to start */
1502
1503     if ((client_fd = client_socket_init(g_port)) < 0)
1504         goto error;
1505
1506     if (ssl_obj_load(ssl_clnt_ctx, SSL_OBJ_X509_CACERT, 
1507                                         "../ssl/test/axTLS.ca_x509.cer", NULL))
1508         goto error;
1509
1510     ssl_clnt = ssl_client_new(ssl_clnt_ctx, client_fd, NULL, 0);
1511
1512     /* check the return status */
1513     if (ssl_handshake_status(ssl_clnt) < 0)
1514     {
1515         printf("YA YA\n");
1516         ssl_display_error(ssl_handshake_status(ssl_clnt));
1517         goto error;
1518     }
1519
1520     ssl_write(ssl_clnt, basic_buf, sizeof(basic_buf));
1521     ssl_free(ssl_clnt);
1522
1523 error:
1524     ssl_ctx_free(ssl_clnt_ctx);
1525     SOCKET_CLOSE(client_fd);
1526
1527     /* exit this thread */
1528 }
1529
1530 static int SSL_basic_test(void)
1531 {
1532     int server_fd, client_fd, ret = 0, size = 0, offset = 0;
1533     SSL_CTX *ssl_svr_ctx = NULL;
1534     struct sockaddr_in client_addr;
1535     uint8_t *read_buf;
1536     socklen_t clnt_len = sizeof(client_addr);
1537     SSL *ssl_svr;
1538 #ifndef WIN32
1539     pthread_t thread;
1540 #endif
1541     memset(basic_buf, 0xA5, sizeof(basic_buf)/2);
1542     memset(&basic_buf[sizeof(basic_buf)/2], 0x5A, sizeof(basic_buf)/2);
1543
1544     if ((server_fd = server_socket_init(&g_port)) < 0)
1545         goto error;
1546
1547     ssl_svr_ctx = ssl_ctx_new(DEFAULT_SVR_OPTION, SSL_DEFAULT_SVR_SESS);
1548
1549 #ifndef WIN32
1550     pthread_create(&thread, NULL, 
1551                 (void *(*)(void *))do_basic, NULL);
1552     pthread_detach(thread);
1553 #else
1554     CreateThread(NULL, 1024, (LPTHREAD_START_ROUTINE)do_basic, NULL, 0, NULL);
1555 #endif
1556
1557     /* Wait for a client to connect */
1558     if ((client_fd = accept(server_fd, 
1559                     (struct sockaddr *) &client_addr, &clnt_len)) < 0)
1560     {
1561         ret = SSL_ERROR_SOCK_SETUP_FAILURE;
1562         goto error;
1563     }
1564     
1565     /* we are ready to go */
1566     ssl_svr = ssl_server_new(ssl_svr_ctx, client_fd);
1567     
1568     do
1569     {
1570         while ((size = ssl_read(ssl_svr, &read_buf)) == SSL_OK);
1571
1572         if (size < SSL_OK) /* got some alert or something nasty */
1573         {
1574             printf("Server ");
1575             ssl_display_error(size);
1576             ret = size;
1577             break;
1578         }
1579         else /* looks more promising */
1580         {
1581             if (memcmp(read_buf, &basic_buf[offset], size) != 0)
1582             {
1583                 ret = SSL_NOT_OK;
1584                 break;
1585             }
1586         }
1587
1588         offset += size;
1589     } while (offset < sizeof(basic_buf));
1590
1591     printf(ret == SSL_OK && offset == sizeof(basic_buf) ? 
1592                             "SSL basic test passed\n" :
1593                             "SSL basic test failed\n");
1594     TTY_FLUSH();
1595
1596     ssl_free(ssl_svr);
1597     SOCKET_CLOSE(server_fd);
1598     SOCKET_CLOSE(client_fd);
1599
1600 error:
1601     ssl_ctx_free(ssl_svr_ctx);
1602     return ret;
1603 }
1604
1605 #if !defined(WIN32) && defined(CONFIG_SSL_CTX_MUTEXING)
1606 /**************************************************************************
1607  * Multi-Threading Tests
1608  *
1609  **************************************************************************/
1610 #define NUM_THREADS         100
1611
1612 typedef struct
1613 {
1614     SSL_CTX *ssl_clnt_ctx;
1615     int port;
1616     int thread_id;
1617 } multi_t;
1618
1619 void do_multi_clnt(multi_t *multi_data)
1620 {
1621     int res = 1, client_fd, i;
1622     SSL *ssl = NULL;
1623     char tmp[5];
1624
1625     if ((client_fd = client_socket_init(multi_data->port)) < 0)
1626         goto client_test_exit;
1627
1628     sleep(1);
1629     ssl = ssl_client_new(multi_data->ssl_clnt_ctx, client_fd, NULL, 0);
1630
1631     if ((res = ssl_handshake_status(ssl)))
1632     {
1633         printf("Client ");
1634         ssl_display_error(res);
1635         goto client_test_exit;
1636     }
1637
1638     sprintf(tmp, "%d\n", multi_data->thread_id);
1639     for (i = 0; i < 10; i++)
1640         ssl_write(ssl, (uint8_t *)tmp, strlen(tmp)+1);
1641
1642 client_test_exit:
1643     ssl_free(ssl);
1644     SOCKET_CLOSE(client_fd);
1645     free(multi_data);
1646 }
1647
1648 void do_multi_svr(SSL *ssl)
1649 {
1650     uint8_t *read_buf;
1651     int *res_ptr = malloc(sizeof(int));
1652     int res;
1653
1654     for (;;)
1655     {
1656         res = ssl_read(ssl, &read_buf);
1657
1658         /* kill the client */
1659         if (res != SSL_OK)
1660         {
1661             if (res == SSL_ERROR_CONN_LOST)
1662             {
1663                 SOCKET_CLOSE(ssl->client_fd);
1664                 ssl_free(ssl);
1665                 break;
1666             }
1667             else if (res > 0)
1668             {
1669                 /* do nothing */
1670             }
1671             else /* some problem */
1672             {
1673                 printf("Server ");
1674                 ssl_display_error(res);
1675                 goto error;
1676             }
1677         }
1678     }
1679
1680     res = SSL_OK;
1681 error:
1682     *res_ptr = res;
1683     pthread_exit(res_ptr);
1684 }
1685
1686 int multi_thread_test(void)
1687 {
1688     int server_fd = -1;
1689     SSL_CTX *ssl_server_ctx;
1690     SSL_CTX *ssl_clnt_ctx;
1691     pthread_t clnt_threads[NUM_THREADS];
1692     pthread_t svr_threads[NUM_THREADS];
1693     int i, res = 0;
1694     struct sockaddr_in client_addr;
1695     socklen_t clnt_len = sizeof(client_addr);
1696
1697     printf("Do multi-threading test (takes a minute)\n");
1698
1699     ssl_server_ctx = ssl_ctx_new(DEFAULT_SVR_OPTION, SSL_DEFAULT_SVR_SESS);
1700     ssl_clnt_ctx = ssl_ctx_new(DEFAULT_CLNT_OPTION, SSL_DEFAULT_CLNT_SESS);
1701
1702     if (ssl_obj_load(ssl_clnt_ctx, SSL_OBJ_X509_CACERT, 
1703                                         "../ssl/test/axTLS.ca_x509.cer", NULL))
1704         goto error;
1705
1706     if ((server_fd = server_socket_init(&g_port)) < 0)
1707         goto error;
1708
1709     for (i = 0; i < NUM_THREADS; i++)
1710     {
1711         multi_t *multi_data = (multi_t *)malloc(sizeof(multi_t));
1712         multi_data->ssl_clnt_ctx = ssl_clnt_ctx;
1713         multi_data->port = g_port;
1714         multi_data->thread_id = i+1;
1715         pthread_create(&clnt_threads[i], NULL, 
1716                 (void *(*)(void *))do_multi_clnt, (void *)multi_data);
1717         pthread_detach(clnt_threads[i]);
1718     }
1719
1720     for (i = 0; i < NUM_THREADS; i++)
1721     { 
1722         SSL *ssl_svr;
1723         int client_fd = accept(server_fd, 
1724                       (struct sockaddr *)&client_addr, &clnt_len);
1725
1726         if (client_fd < 0)
1727             goto error;
1728
1729         ssl_svr = ssl_server_new(ssl_server_ctx, client_fd);
1730
1731         pthread_create(&svr_threads[i], NULL, 
1732                         (void *(*)(void *))do_multi_svr, (void *)ssl_svr);
1733     }
1734
1735     /* make sure we've run all of the threads */
1736     for (i = 0; i < NUM_THREADS; i++)
1737     {
1738         void *thread_res;
1739         pthread_join(svr_threads[i], &thread_res);
1740
1741         if (*((int *)thread_res) != 0)
1742             res = 1;
1743
1744         free(thread_res);
1745     } 
1746
1747     if (res) 
1748         goto error;
1749
1750     printf("Multi-thread test passed (%d)\n", NUM_THREADS);
1751 error:
1752     ssl_ctx_free(ssl_server_ctx);
1753     ssl_ctx_free(ssl_clnt_ctx);
1754     SOCKET_CLOSE(server_fd);
1755     return res;
1756 }
1757 #endif /* !defined(WIN32) && defined(CONFIG_SSL_CTX_MUTEXING) */ 
1758
1759 /**************************************************************************
1760  * Header issue
1761  *
1762  **************************************************************************/
1763 static void do_header_issue(void)
1764 {
1765     char axtls_buf[2048];
1766 #ifndef WIN32
1767     pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
1768 #endif
1769     sprintf(axtls_buf, "./axssl s_client -connect localhost:%d", g_port);
1770     system(axtls_buf);
1771 }
1772
1773 static int header_issue(void)
1774 {
1775     FILE *f = fopen("../ssl/test/header_issue.dat", "r");
1776     int server_fd = -1, client_fd = -1, ret = 1;
1777     uint8_t buf[2048];
1778     int size = 0;
1779     struct sockaddr_in client_addr;
1780     socklen_t clnt_len = sizeof(client_addr);
1781 #ifndef WIN32
1782     pthread_t thread;
1783 #endif
1784
1785     if (f == NULL || (server_fd = server_socket_init(&g_port)) < 0)
1786         goto error;
1787
1788 #ifndef WIN32
1789     pthread_create(&thread, NULL, 
1790                 (void *(*)(void *))do_header_issue, NULL);
1791     pthread_detach(thread);
1792 #else
1793     CreateThread(NULL, 1024, (LPTHREAD_START_ROUTINE)do_header_issue, 
1794                 NULL, 0, NULL);
1795 #endif
1796     if ((client_fd = accept(server_fd, 
1797                     (struct sockaddr *) &client_addr, &clnt_len)) < 0)
1798     {
1799         ret = SSL_ERROR_SOCK_SETUP_FAILURE;
1800         goto error;
1801     }
1802
1803     size = fread(buf, 1, sizeof(buf), f);
1804     SOCKET_WRITE(client_fd, buf, size);
1805     usleep(200000);
1806
1807     ret = 0;
1808 error:
1809     fclose(f);
1810     SOCKET_CLOSE(client_fd);
1811     SOCKET_CLOSE(server_fd);
1812     TTY_FLUSH();
1813     system("killall axssl");
1814     return ret;
1815 }
1816
1817 /**************************************************************************
1818  * main()
1819  *
1820  **************************************************************************/
1821 int main(int argc, char *argv[])
1822 {
1823     int ret = 1;
1824     BI_CTX *bi_ctx;
1825     int fd;
1826
1827 #ifdef WIN32
1828     WSADATA wsaData;
1829     WORD wVersionRequested = MAKEWORD(2, 2);
1830     WSAStartup(wVersionRequested, &wsaData);
1831     fd = _open("test_result.txt", O_WRONLY|O_TEMPORARY|O_CREAT, _S_IWRITE);
1832     dup2(fd, 2);                        /* write stderr to this file */
1833 #else
1834     fd = open("/dev/null", O_WRONLY);   /* write stderr to /dev/null */
1835     signal(SIGPIPE, SIG_IGN);           /* ignore pipe errors */
1836     dup2(fd, 2);
1837 #endif
1838
1839     /* can't do testing in this mode */
1840 #if defined CONFIG_SSL_GENERATE_X509_CERT
1841     printf("Error: Must compile with default key/certificates\n");
1842     exit(1);
1843 #endif
1844
1845     bi_ctx = bi_initialize();
1846
1847     if (AES_test(bi_ctx))
1848     {
1849         printf("AES tests failed\n");
1850         goto cleanup;
1851     }
1852     TTY_FLUSH();
1853
1854     if (RC4_test(bi_ctx))
1855     {
1856         printf("RC4 tests failed\n");
1857         goto cleanup;
1858     }
1859     TTY_FLUSH();
1860
1861     if (MD5_test(bi_ctx))
1862     {
1863         printf("MD5 tests failed\n");
1864         goto cleanup;
1865     }
1866     TTY_FLUSH();
1867
1868     if (SHA1_test(bi_ctx))
1869     {
1870         printf("SHA1 tests failed\n");
1871         goto cleanup;
1872     }
1873     TTY_FLUSH();
1874
1875     if (HMAC_test(bi_ctx))
1876     {
1877         printf("HMAC tests failed\n");
1878         goto cleanup;
1879     }
1880     TTY_FLUSH();
1881
1882     if (BIGINT_test(bi_ctx))
1883     {
1884         printf("BigInt tests failed!\n");
1885         goto cleanup;
1886     }
1887     TTY_FLUSH();
1888
1889     bi_terminate(bi_ctx);
1890
1891     if (RSA_test())
1892     {
1893         printf("RSA tests failed\n");
1894         goto cleanup;
1895     }
1896     TTY_FLUSH();
1897
1898     if (cert_tests())
1899     {
1900         printf("CERT tests failed\n");
1901         goto cleanup;
1902     }
1903     TTY_FLUSH();
1904
1905 #if !defined(WIN32) && defined(CONFIG_SSL_CTX_MUTEXING)
1906     if (multi_thread_test())
1907         goto cleanup;
1908 #endif
1909
1910     if (SSL_basic_test())
1911         goto cleanup;
1912
1913     system("sh ../ssl/test/killopenssl.sh");
1914
1915     if (SSL_client_tests())
1916         goto cleanup;
1917
1918     system("sh ../ssl/test/killopenssl.sh");
1919
1920     if (SSL_server_tests())
1921         goto cleanup;
1922
1923     system("sh ../ssl/test/killopenssl.sh");
1924
1925     if (header_issue())
1926     {
1927         printf("Header tests failed\n"); TTY_FLUSH();
1928         goto cleanup;
1929     }
1930
1931     ret = 0;        /* all ok */
1932     printf("**** ALL TESTS PASSED ****\n"); TTY_FLUSH();
1933 cleanup:
1934
1935     if (ret)
1936         printf("Error: Some tests failed!\n");
1937
1938     close(fd);
1939     return ret;
1940 }