]> git.donarmstrong.com Git - qmk_firmware.git/blob - tool/mbed/mbed-sdk/libraries/net/https/axTLS/ssl/tls1.c
Squashed 'tmk_core/' changes from 7967731..b9e0ea0
[qmk_firmware.git] / tool / mbed / mbed-sdk / libraries / net / https / axTLS / ssl / tls1.c
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  * Common ssl/tlsv1 code to both the client and server implementations.
33  */
34
35
36 #include <string.h>
37 #include <stdlib.h>
38 #include <stdio.h>
39 #include <stdarg.h>
40 #include <errno.h>
41
42
43
44 #include "lwip/sockets.h"
45 #include "os_port.h"
46 #include "ssl.h"
47 #include "arch.h"
48
49
50 /* The session expiry time */
51 #define SSL_EXPIRY_TIME     (CONFIG_SSL_EXPIRY_TIME*3600)
52
53 static const uint8_t g_hello_request[] = { HS_HELLO_REQUEST, 0, 0, 0 };
54 static const uint8_t g_chg_cipher_spec_pkt[] = { 1 };
55 static const char * server_finished = "server finished";
56 static const char * client_finished = "client finished";
57
58 static int do_handshake(SSL *ssl, uint8_t *buf, int read_len);
59 static int set_key_block(SSL *ssl, int is_write);
60 static int verify_digest(SSL *ssl, int mode, const uint8_t *buf, int read_len);
61 static void *crypt_new(SSL *ssl, uint8_t *key, uint8_t *iv, int is_decrypt);
62 static int send_raw_packet(SSL *ssl, uint8_t protocol);
63
64 /**
65  * The server will pick the cipher based on the order that the order that the
66  * ciphers are listed. This order is defined at compile time.
67  */
68 #ifdef CONFIG_SSL_SKELETON_MODE
69 const uint8_t ssl_prot_prefs[NUM_PROTOCOLS] = 
70 { SSL_RC4_128_SHA };
71 #else
72 static void session_free(SSL_SESSION *ssl_sessions[], int sess_index);
73
74 const uint8_t ssl_prot_prefs[NUM_PROTOCOLS] = 
75 #ifdef CONFIG_SSL_PROT_LOW                  /* low security, fast speed */
76 { SSL_RC4_128_SHA, SSL_AES128_SHA, SSL_AES256_SHA, SSL_RC4_128_MD5 };
77 #elif CONFIG_SSL_PROT_MEDIUM                /* medium security, medium speed */
78 { SSL_AES128_SHA, SSL_AES256_SHA, SSL_RC4_128_SHA, SSL_RC4_128_MD5 };    
79 #else /* CONFIG_SSL_PROT_HIGH */            /* high security, low speed */
80 { SSL_AES256_SHA, SSL_AES128_SHA, SSL_RC4_128_SHA, SSL_RC4_128_MD5 };
81 #endif
82 #endif /* CONFIG_SSL_SKELETON_MODE */
83
84 /**
85  * The cipher map containing all the essentials for each cipher.
86  */
87 #ifdef CONFIG_SSL_SKELETON_MODE
88 static const cipher_info_t cipher_info[NUM_PROTOCOLS] = 
89 {
90     {   /* RC4-SHA */
91         SSL_RC4_128_SHA,                /* RC4-SHA */
92         16,                             /* key size */
93         0,                              /* iv size */ 
94         2*(SHA1_SIZE+16),               /* key block size */
95         0,                              /* no padding */
96         SHA1_SIZE,                      /* digest size */
97         hmac_sha1,                      /* hmac algorithm */
98         (crypt_func)RC4_crypt,          /* encrypt */
99         (crypt_func)RC4_crypt           /* decrypt */
100     },
101 };
102 #else
103 static const cipher_info_t cipher_info[NUM_PROTOCOLS] = 
104 {
105     {   /* AES128-SHA */
106         SSL_AES128_SHA,                 /* AES128-SHA */
107         16,                             /* key size */
108         16,                             /* iv size */ 
109         2*(SHA1_SIZE+16+16),            /* key block size */
110         16,                             /* block padding size */
111         SHA1_SIZE,                      /* digest size */
112         hmac_sha1,                      /* hmac algorithm */
113         (crypt_func)AES_cbc_encrypt,    /* encrypt */
114         (crypt_func)AES_cbc_decrypt     /* decrypt */
115     },
116     {   /* AES256-SHA */
117         SSL_AES256_SHA,                 /* AES256-SHA */
118         32,                             /* key size */
119         16,                             /* iv size */ 
120         2*(SHA1_SIZE+32+16),            /* key block size */
121         16,                             /* block padding size */
122         SHA1_SIZE,                      /* digest size */
123         hmac_sha1,                      /* hmac algorithm */
124         (crypt_func)AES_cbc_encrypt,    /* encrypt */
125         (crypt_func)AES_cbc_decrypt     /* decrypt */
126     },       
127     {   /* RC4-SHA */
128         SSL_RC4_128_SHA,                /* RC4-SHA */
129         16,                             /* key size */
130         0,                              /* iv size */ 
131         2*(SHA1_SIZE+16),               /* key block size */
132         0,                              /* no padding */
133         SHA1_SIZE,                      /* digest size */
134         hmac_sha1,                      /* hmac algorithm */
135         (crypt_func)RC4_crypt,          /* encrypt */
136         (crypt_func)RC4_crypt           /* decrypt */
137     },
138     /*
139      * This protocol is from SSLv2 days and is unlikely to be used - but was
140      * useful for testing different possible digest algorithms.
141      */
142     {   /* RC4-MD5 */
143         SSL_RC4_128_MD5,                /* RC4-MD5 */
144         16,                             /* key size */
145         0,                              /* iv size */ 
146         2*(MD5_SIZE+16),                /* key block size */
147         0,                              /* no padding */
148         MD5_SIZE,                       /* digest size */
149         hmac_md5,                       /* hmac algorithm */
150         (crypt_func)RC4_crypt,          /* encrypt */
151         (crypt_func)RC4_crypt           /* decrypt */
152     },
153 };
154 #endif
155
156 static void prf(const uint8_t *sec, int sec_len, uint8_t *seed, int seed_len,
157         uint8_t *out, int olen);
158 static const cipher_info_t *get_cipher_info(uint8_t cipher);
159 static void increment_read_sequence(SSL *ssl);
160 static void increment_write_sequence(SSL *ssl);
161 static void add_hmac_digest(SSL *ssl, int snd, uint8_t *hmac_header,
162         const uint8_t *buf, int buf_len, uint8_t *hmac_buf);
163
164 /* win32 VC6.0 doesn't have variadic macros */
165 #if defined(WIN32) && !defined(CONFIG_SSL_FULL_MODE)
166 void DISPLAY_BYTES(SSL *ssl, const char *format, 
167         const uint8_t *data, int size, ...) {}
168 #endif
169
170 /**
171  * Establish a new client/server context.
172  */
173 EXP_FUNC SSL_CTX *STDCALL ssl_ctx_new(SSL_CTX *ssl_ctx, uint32_t options, int num_sessions)
174 {
175     ssl_ctx->options = options;
176     RNG_initialize();
177
178     if (load_key_certs(ssl_ctx) < 0)
179     {
180         printf("error loading key certs\r\n");
181         //free(ssl_ctx);  /* can't load our key/certificate pair, so die */
182         return NULL;
183     }
184
185 #ifndef CONFIG_SSL_SKELETON_MODE
186     ssl_ctx->num_sessions = num_sessions;
187 #endif
188
189     SSL_CTX_MUTEX_INIT(ssl_ctx->mutex);
190
191 #ifndef CONFIG_SSL_SKELETON_MODE
192     if (num_sessions)
193     {
194         ssl_ctx->ssl_sessions = (SSL_SESSION **)
195                         calloc(1, num_sessions*sizeof(SSL_SESSION *));
196     }
197 #endif
198
199     return ssl_ctx;
200 }
201
202 /*
203  * Remove a client/server context.
204  */
205 EXP_FUNC void STDCALL ssl_ctx_free(SSL_CTX *ssl_ctx)
206 {
207     SSL *ssl;
208     int i;
209
210     if (ssl_ctx == NULL)
211         return;
212
213     ssl = ssl_ctx->head;
214
215     /* clear out all the ssl entries */
216     while (ssl)
217     {
218         SSL *next = ssl->next;
219         ssl_free(ssl);
220         ssl = next;
221     }
222
223 #ifndef CONFIG_SSL_SKELETON_MODE
224     /* clear out all the sessions */
225     for (i = 0; i < ssl_ctx->num_sessions; i++)
226         session_free(ssl_ctx->ssl_sessions, i);
227
228     free(ssl_ctx->ssl_sessions);
229 #endif
230
231     i = 0;
232     //while (i < CONFIG_SSL_MAX_CERTS && ssl_ctx->certs[i].buf)
233     {
234         //free(ssl_ctx->certs[i].buf);
235         //ssl_ctx->certs[i++].buf = NULL;
236     }
237
238 #ifdef CONFIG_SSL_CERT_VERIFICATION
239     remove_ca_certs(ssl_ctx->ca_cert_ctx);
240 #endif
241     ssl_ctx->chain_length = 0;
242     SSL_CTX_MUTEX_DESTROY(ssl_ctx->mutex);
243     RSA_free(ssl_ctx->rsa_ctx);
244     RNG_terminate();
245     //free(ssl_ctx);
246 }
247
248 /*
249  * Free any used resources used by this connection.
250  */
251 EXP_FUNC void STDCALL ssl_free(SSL *ssl)
252 {
253     SSL_CTX *ssl_ctx;
254
255     if (ssl == NULL)        /* just ignore null pointers */
256         return;
257
258     /* only notify if we weren't notified first */
259     /* spec says we must notify when we are dying */
260     if (!IS_SET_SSL_FLAG(SSL_SENT_CLOSE_NOTIFY))
261       send_alert(ssl, SSL_ALERT_CLOSE_NOTIFY);
262
263     ssl_ctx = ssl->ssl_ctx;
264
265     SSL_CTX_LOCK(ssl_ctx->mutex);
266
267     /* adjust the server SSL list */
268     if (ssl->prev)
269         ssl->prev->next = ssl->next;
270     else
271         ssl_ctx->head = ssl->next;
272
273     if (ssl->next)
274         ssl->next->prev = ssl->prev;
275     else
276         ssl_ctx->tail = ssl->prev;
277
278     SSL_CTX_UNLOCK(ssl_ctx->mutex);
279
280     /* may already be free - but be sure */
281     free(ssl->encrypt_ctx);
282     free(ssl->decrypt_ctx);
283     disposable_free(ssl);
284     
285 #ifdef CONFIG_SSL_CERT_VERIFICATION
286     x509_free(ssl->x509_ctx);
287 #endif
288     //free(ssl->ssl_ctx);
289     //free(ssl);
290 }
291
292 /*
293  * Write application data to the client
294  */
295 EXP_FUNC int STDCALL ssl_write(SSL *ssl, const uint8_t *out_data, int out_len)
296 {
297     int n = out_len, nw, i, tot = 0;
298
299     /* maximum size of a TLS packet is around 16kB, so fragment */
300     do 
301     {
302         nw = n;
303
304         if (nw > RT_MAX_PLAIN_LENGTH)    /* fragment if necessary */
305             nw = RT_MAX_PLAIN_LENGTH;
306
307         if ((i = send_packet(ssl, PT_APP_PROTOCOL_DATA, 
308                                             &out_data[tot], nw)) <= 0)
309         {
310             out_len = i;    /* an error */
311             break;
312         }
313
314         tot += i;
315         n -= i;
316     } while (n > 0);
317
318     return out_len;
319 }
320
321 /**
322  * Add a certificate to the certificate chain.
323  */
324 int add_cert(SSL_CTX *ssl_ctx, const uint8_t *buf, int len)
325 {
326     int ret = SSL_ERROR_NO_CERT_DEFINED, i = 0;
327     SSL_CERT *ssl_cert;
328     X509_CTX *cert = NULL;
329     int offset;
330
331     while (ssl_ctx->certs[i].buf && i < CONFIG_SSL_MAX_CERTS) 
332         i++;
333
334     if (i == CONFIG_SSL_MAX_CERTS) /* too many certs */
335     {
336 #ifdef CONFIG_SSL_FULL_MODE
337         printf("Error: maximum number of certs added (%d) - change of "
338                 "compile-time configuration required\n",
339                 CONFIG_SSL_MAX_CERTS);
340 #endif
341         goto error;
342     }
343
344     if ((ret = x509_new(buf, &offset, &cert)))
345         goto error;
346
347 #if defined (CONFIG_SSL_FULL_MODE)
348     if (ssl_ctx->options & SSL_DISPLAY_CERTS)
349         x509_print(cert, NULL);
350 #endif
351
352     ssl_cert = &ssl_ctx->certs[i];
353     ssl_cert->size = len;
354     ssl_cert->buf = buf;
355     ssl_ctx->chain_length++;
356     len -= offset;
357     ret = SSL_OK;           /* ok so far */
358
359     /* recurse? */
360     if (len > 0)
361     {
362         ret = add_cert(ssl_ctx, &buf[offset], len);
363     }
364
365 error:
366     x509_free(cert);        /* don't need anymore */
367     return ret;
368 }
369
370 #ifdef CONFIG_SSL_CERT_VERIFICATION
371 /**
372  * Add a certificate authority.
373  */
374 int add_cert_auth(SSL_CTX *ssl_ctx, const uint8_t *buf, int len)
375 {
376     int ret = SSL_OK; /* ignore errors for now */
377     int i = 0;
378     CA_CERT_CTX *ca_cert_ctx;
379
380     if (ssl_ctx->ca_cert_ctx == NULL)
381         ssl_ctx->ca_cert_ctx = (CA_CERT_CTX *)calloc(1, sizeof(CA_CERT_CTX));
382
383     ca_cert_ctx = ssl_ctx->ca_cert_ctx;
384
385     while (i < CONFIG_X509_MAX_CA_CERTS && ca_cert_ctx->cert[i]) 
386         i++;
387
388     while (len > 0)
389     {
390         int offset;
391         if (i >= CONFIG_X509_MAX_CA_CERTS)
392         {
393 #ifdef CONFIG_SSL_FULL_MODE
394             printf("Error: maximum number of CA certs added (%d) - change of "
395                     "compile-time configuration required\n", 
396                     CONFIG_X509_MAX_CA_CERTS);
397 #endif
398             break;
399         }
400
401
402         /* ignore the return code */
403         if (x509_new(buf, &offset, &ca_cert_ctx->cert[i]) == X509_OK)
404         {
405 #if defined (CONFIG_SSL_FULL_MODE)
406             if (ssl_ctx->options & SSL_DISPLAY_CERTS)
407                 x509_print(ca_cert_ctx->cert[i], NULL);
408 #endif
409         }
410
411         i++;
412         len -= offset;
413     }
414
415     return ret;
416 }
417
418 /*
419  * Retrieve an X.509 distinguished name component
420  */
421 EXP_FUNC const char * STDCALL ssl_get_cert_dn(const SSL *ssl, int component)
422 {
423     if (ssl->x509_ctx == NULL)
424         return NULL;
425
426     switch (component)
427     {
428         case SSL_X509_CERT_COMMON_NAME:
429             return ssl->x509_ctx->cert_dn[X509_COMMON_NAME];
430
431         case SSL_X509_CERT_ORGANIZATION:
432             return ssl->x509_ctx->cert_dn[X509_ORGANIZATION];
433
434         case SSL_X509_CERT_ORGANIZATIONAL_NAME:       
435             return ssl->x509_ctx->cert_dn[X509_ORGANIZATIONAL_UNIT];
436
437         case SSL_X509_CA_CERT_COMMON_NAME:
438             return ssl->x509_ctx->ca_cert_dn[X509_COMMON_NAME];
439
440         case SSL_X509_CA_CERT_ORGANIZATION:
441             return ssl->x509_ctx->ca_cert_dn[X509_ORGANIZATION];
442
443         case SSL_X509_CA_CERT_ORGANIZATIONAL_NAME:       
444             return ssl->x509_ctx->ca_cert_dn[X509_ORGANIZATIONAL_UNIT];
445
446         default:
447             return NULL;
448     }
449 }
450
451 /*
452  * Retrieve a "Subject Alternative Name" from a v3 certificate
453  */
454 EXP_FUNC const char * STDCALL ssl_get_cert_subject_alt_dnsname(const SSL *ssl,
455         int dnsindex)
456 {
457     int i;
458
459     if (ssl->x509_ctx == NULL || ssl->x509_ctx->subject_alt_dnsnames == NULL)
460         return NULL;
461
462     for (i = 0; i < dnsindex; ++i)
463     {
464         if (ssl->x509_ctx->subject_alt_dnsnames[i] == NULL)
465             return NULL;
466     }
467
468     return ssl->x509_ctx->subject_alt_dnsnames[dnsindex];
469 }
470
471 #endif /* CONFIG_SSL_CERT_VERIFICATION */
472
473 /*
474  * Find an ssl object based on the client's file descriptor.
475  */
476 EXP_FUNC SSL * STDCALL ssl_find(SSL_CTX *ssl_ctx, int client_fd)
477 {
478     SSL *ssl;
479
480     SSL_CTX_LOCK(ssl_ctx->mutex);
481     ssl = ssl_ctx->head;
482
483     /* search through all the ssl entries */
484     while (ssl)
485     {
486         if (ssl->client_fd == client_fd)
487         {
488             SSL_CTX_UNLOCK(ssl_ctx->mutex);
489             return ssl;
490         }
491
492         ssl = ssl->next;
493     }
494
495     SSL_CTX_UNLOCK(ssl_ctx->mutex);
496     return NULL;
497 }
498
499 /*
500  * Force the client to perform its handshake again.
501  */
502 EXP_FUNC int STDCALL ssl_renegotiate(SSL *ssl)
503 {
504     int ret = SSL_OK;
505
506     disposable_new(ssl);
507 #ifdef CONFIG_SSL_ENABLE_CLIENT
508     if (IS_SET_SSL_FLAG(SSL_IS_CLIENT))
509     {
510         ret = do_client_connect(ssl);
511     }
512     else
513 #endif
514     {
515         send_packet(ssl, PT_HANDSHAKE_PROTOCOL, 
516                 g_hello_request, sizeof(g_hello_request));
517         SET_SSL_FLAG(SSL_NEED_RECORD);
518     }
519
520     return ret;
521 }
522
523 /**
524  * @brief Get what we need for key info.
525  * @param cipher    [in]    The cipher information we are after
526  * @param key_size  [out]   The key size for the cipher
527  * @param iv_size   [out]   The iv size for the cipher
528  * @return  The amount of key information we need.
529  */
530 static const cipher_info_t *get_cipher_info(uint8_t cipher)
531 {
532     int i;
533
534     for (i = 0; i < NUM_PROTOCOLS; i++)
535     {
536         if (cipher_info[i].cipher == cipher)
537         {
538             return &cipher_info[i];
539         }
540     }
541
542     return NULL;  /* error */
543 }
544
545 /*
546  * Get a new ssl context for a new connection.
547  */
548 SSL *ssl_new(SSL *ssl, int client_fd)
549 {
550     SSL_CTX* ssl_ctx = ssl->ssl_ctx;
551     ssl->need_bytes = SSL_RECORD_SIZE;      /* need a record */
552     ssl->client_fd = 0;
553     ssl->flag = SSL_NEED_RECORD;
554     ssl->bm_data = ssl->bm_all_data + BM_RECORD_OFFSET; 
555     ssl->bm_read_index = 0;
556     ssl->hs_status = SSL_NOT_OK;            /* not connected */
557 #ifdef CONFIG_ENABLE_VERIFICATION
558     ssl->ca_cert_ctx = ssl_ctx->ca_cert_ctx;
559 #endif
560     disposable_new(ssl);
561
562     /* a bit hacky but saves a few bytes of memory */
563     ssl->flag |= ssl_ctx->options;
564     SSL_CTX_LOCK(ssl_ctx->mutex);
565
566     if (ssl_ctx->head == NULL)
567     {
568         ssl_ctx->head = ssl;
569         ssl_ctx->tail = ssl;
570     }
571     else
572     {
573         ssl->prev = ssl_ctx->tail;
574         ssl_ctx->tail->next = ssl;
575         ssl_ctx->tail = ssl;
576     }
577     ssl->encrypt_ctx = NULL;
578     ssl->decrypt_ctx = NULL;
579     
580     SSL_CTX_UNLOCK(ssl_ctx->mutex);
581     return ssl;
582 }
583
584 /*
585  * Add a private key to a context.
586  */
587 int add_private_key(SSL_CTX *ssl_ctx, SSLObjLoader *ssl_obj)
588 {
589     int ret = SSL_OK;
590
591     /* get the private key details */
592     if (asn1_get_private_key(ssl_obj->buf, ssl_obj->len, &ssl_ctx->rsa_ctx))
593     {
594         ret = SSL_ERROR_INVALID_KEY;
595         goto error;
596     }
597
598 error:
599     return ret;
600 }
601
602 /** 
603  * Increment the read sequence number (as a 64 bit endian indepenent #)
604  */     
605 static void increment_read_sequence(SSL *ssl)
606 {
607     int i;
608
609     for (i = 7; i >= 0; i--) 
610     {       
611         if (++ssl->read_sequence[i])
612             break;
613     }
614 }
615             
616 /**
617  * Increment the read sequence number (as a 64 bit endian indepenent #)
618  */      
619 static void increment_write_sequence(SSL *ssl)
620 {        
621     int i;                  
622          
623     for (i = 7; i >= 0; i--)
624     {                       
625         if (++ssl->write_sequence[i])
626             break;
627     }                       
628 }
629
630 /**
631  * Work out the HMAC digest in a packet.
632  */
633 static void add_hmac_digest(SSL *ssl, int mode, uint8_t *hmac_header,
634         const uint8_t *buf, int buf_len, uint8_t *hmac_buf)
635 {
636     int hmac_len = buf_len + 8 + SSL_RECORD_SIZE;
637     uint8_t *t_buf = (uint8_t *)alloca(hmac_len+10);
638
639     memcpy(t_buf, (mode == SSL_SERVER_WRITE || mode == SSL_CLIENT_WRITE) ? 
640                     ssl->write_sequence : ssl->read_sequence, 8);
641     memcpy(&t_buf[8], hmac_header, SSL_RECORD_SIZE);
642     memcpy(&t_buf[8+SSL_RECORD_SIZE], buf, buf_len);
643
644     ssl->cipher_info->hmac(t_buf, hmac_len, 
645             (mode == SSL_SERVER_WRITE || mode == SSL_CLIENT_READ) ? 
646                 ssl->server_mac : ssl->client_mac, 
647             ssl->cipher_info->digest_size, hmac_buf);
648
649 #if 0
650     print_blob("record", hmac_header, SSL_RECORD_SIZE);
651     print_blob("buf", buf, buf_len);
652     if (mode == SSL_SERVER_WRITE || mode == SSL_CLIENT_WRITE)
653     {
654         print_blob("write seq", ssl->write_sequence, 8);
655     }
656     else
657     {
658         print_blob("read seq", ssl->read_sequence, 8);
659     }
660
661     if (mode == SSL_SERVER_WRITE || mode == SSL_CLIENT_READ)
662     {
663         print_blob("server mac", 
664                 ssl->server_mac, ssl->cipher_info->digest_size);
665     }
666     else
667     {
668         print_blob("client mac", 
669                 ssl->client_mac, ssl->cipher_info->digest_size);
670     }
671     print_blob("hmac", hmac_buf, SHA1_SIZE);
672 #endif
673 }
674
675 /**
676  * Verify that the digest of a packet is correct.
677  */
678 static int verify_digest(SSL *ssl, int mode, const uint8_t *buf, int read_len)
679 {   
680     uint8_t hmac_buf[SHA1_SIZE];
681     int hmac_offset;
682    
683     if (ssl->cipher_info->padding_size)
684     {
685         int last_blk_size = buf[read_len-1], i;
686         hmac_offset = read_len-last_blk_size-ssl->cipher_info->digest_size-1;
687
688         /* guard against a timing attack - make sure we do the digest */
689         if (hmac_offset < 0)
690         {
691             hmac_offset = 0;
692         }
693         else
694         {
695             /* already looked at last byte */
696             for (i = 1; i < last_blk_size; i++)
697             {
698                 if (buf[read_len-i] != last_blk_size)
699                 {
700                     hmac_offset = 0;
701                     break;
702                 }
703             }
704         }
705     }
706     else /* stream cipher */
707     {
708         hmac_offset = read_len - ssl->cipher_info->digest_size;
709
710         if (hmac_offset < 0)
711         {
712             hmac_offset = 0;
713         }
714     }
715
716     /* sanity check the offset */
717     ssl->hmac_header[3] = hmac_offset >> 8;      /* insert size */
718     ssl->hmac_header[4] = hmac_offset & 0xff;
719     add_hmac_digest(ssl, mode, ssl->hmac_header, buf, hmac_offset, hmac_buf);
720
721     if (memcmp(hmac_buf, &buf[hmac_offset], ssl->cipher_info->digest_size))
722     {
723         return SSL_ERROR_INVALID_HMAC;
724     }
725
726     return hmac_offset;
727 }
728
729 /**
730  * Add a packet to the end of our sent and received packets, so that we may use
731  * it to calculate the hash at the end.
732  */
733 void add_packet(SSL *ssl, const uint8_t *pkt, int len)
734 {
735     MD5_Update(&ssl->dc->md5_ctx, pkt, len);
736     SHA1_Update(&ssl->dc->sha1_ctx, pkt, len);
737 }
738
739 /**
740  * Work out the MD5 PRF.
741  */
742 static void p_hash_md5(const uint8_t *sec, int sec_len, 
743         uint8_t *seed, int seed_len, uint8_t *out, int olen)
744 {
745     uint8_t a1[128];
746
747     /* A(1) */
748     hmac_md5(seed, seed_len, sec, sec_len, a1);
749     memcpy(&a1[MD5_SIZE], seed, seed_len);
750     hmac_md5(a1, MD5_SIZE+seed_len, sec, sec_len, out);
751
752     while (olen > MD5_SIZE)
753     {
754         uint8_t a2[MD5_SIZE];
755         out += MD5_SIZE;
756         olen -= MD5_SIZE;
757
758         /* A(N) */
759         hmac_md5(a1, MD5_SIZE, sec, sec_len, a2);
760         memcpy(a1, a2, MD5_SIZE);
761
762         /* work out the actual hash */
763         hmac_md5(a1, MD5_SIZE+seed_len, sec, sec_len, out);
764     }
765 }
766
767 /**
768  * Work out the SHA1 PRF.
769  */
770 static void p_hash_sha1(const uint8_t *sec, int sec_len, 
771         uint8_t *seed, int seed_len, uint8_t *out, int olen)
772 {
773     uint8_t a1[128];
774
775     /* A(1) */
776     hmac_sha1(seed, seed_len, sec, sec_len, a1);
777     memcpy(&a1[SHA1_SIZE], seed, seed_len);
778     hmac_sha1(a1, SHA1_SIZE+seed_len, sec, sec_len, out);
779
780     while (olen > SHA1_SIZE)
781     {
782         uint8_t a2[SHA1_SIZE];
783         out += SHA1_SIZE;
784         olen -= SHA1_SIZE;
785
786         /* A(N) */
787         hmac_sha1(a1, SHA1_SIZE, sec, sec_len, a2);
788         memcpy(a1, a2, SHA1_SIZE);
789
790         /* work out the actual hash */
791         hmac_sha1(a1, SHA1_SIZE+seed_len, sec, sec_len, out);
792     }
793 }
794
795 /**
796  * Work out the PRF.
797  */
798 static void prf(const uint8_t *sec, int sec_len, uint8_t *seed, int seed_len,
799         uint8_t *out, int olen)
800 {
801     int len, i;
802     const uint8_t *S1, *S2;
803     uint8_t xbuf[256]; /* needs to be > the amount of key data */
804     uint8_t ybuf[256]; /* needs to be > the amount of key data */
805
806     len = sec_len/2;
807     S1 = sec;
808     S2 = &sec[len];
809     len += (sec_len & 1); /* add for odd, make longer */
810
811     p_hash_md5(S1, len, seed, seed_len, xbuf, olen);
812     p_hash_sha1(S2, len, seed, seed_len, ybuf, olen);
813
814     for (i = 0; i < olen; i++)
815         out[i] = xbuf[i] ^ ybuf[i];
816 }
817
818 /**
819  * Generate a master secret based on the client/server random data and the
820  * premaster secret.
821  */
822 void generate_master_secret(SSL *ssl, const uint8_t *premaster_secret)
823 {
824     uint8_t buf[128];   /* needs to be > 13+32+32 in size */
825     strcpy((char *)buf, "master secret");
826     memcpy(&buf[13], ssl->dc->client_random, SSL_RANDOM_SIZE);
827     memcpy(&buf[45], ssl->dc->server_random, SSL_RANDOM_SIZE);
828     prf(premaster_secret, SSL_SECRET_SIZE, buf, 77, ssl->dc->master_secret,
829             SSL_SECRET_SIZE);
830 }
831
832 /**
833  * Generate a 'random' blob of data used for the generation of keys.
834  */
835 static void generate_key_block(uint8_t *client_random, uint8_t *server_random,
836         uint8_t *master_secret, uint8_t *key_block, int key_block_size)
837 {
838     uint8_t buf[128];
839     strcpy((char *)buf, "key expansion");
840     memcpy(&buf[13], server_random, SSL_RANDOM_SIZE);
841     memcpy(&buf[45], client_random, SSL_RANDOM_SIZE);
842     prf(master_secret, SSL_SECRET_SIZE, buf, 77, key_block, key_block_size);
843 }
844
845 /** 
846  * Calculate the digest used in the finished message. This function also
847  * doubles up as a certificate verify function.
848  */
849 void finished_digest(SSL *ssl, const char *label, uint8_t *digest)
850 {
851     uint8_t mac_buf[128]; 
852     uint8_t *q = mac_buf;
853     MD5_CTX md5_ctx = ssl->dc->md5_ctx;
854     SHA1_CTX sha1_ctx = ssl->dc->sha1_ctx;
855
856     if (label)
857     {
858         strcpy((char *)q, label);
859         q += strlen(label);
860     }
861
862     MD5_Final(q, &md5_ctx);
863     q += MD5_SIZE;
864     
865     SHA1_Final(q, &sha1_ctx);
866     q += SHA1_SIZE;
867
868     if (label)
869     {
870         prf(ssl->dc->master_secret, SSL_SECRET_SIZE, mac_buf, (int)(q-mac_buf),
871             digest, SSL_FINISHED_HASH_SIZE);
872     }
873     else    /* for use in a certificate verify */
874     {
875         memcpy(digest, mac_buf, MD5_SIZE + SHA1_SIZE);
876     }
877
878 #if 0
879     printf("label: %s\r\n", label);
880     print_blob("master secret", ssl->dc->master_secret, 48);
881     print_blob("mac_buf", mac_buf, q-mac_buf);
882     print_blob("finished digest", digest, SSL_FINISHED_HASH_SIZE);
883 #endif
884 }   
885     
886 /**
887  * Retrieve (and initialise) the context of a cipher.
888  */
889 static void *crypt_new(SSL *ssl, uint8_t *key, uint8_t *iv, int is_decrypt)
890 {
891     switch (ssl->cipher)
892     {
893 #ifndef CONFIG_SSL_SKELETON_MODE
894         case SSL_AES128_SHA:
895             {
896                 AES_CTX *aes_ctx = (AES_CTX *)malloc(sizeof(AES_CTX));
897                 AES_set_key(aes_ctx, key, iv, AES_MODE_128);
898
899                 if (is_decrypt)
900                 {
901                     AES_convert_key(aes_ctx);
902                 }
903
904                 return (void *)aes_ctx;
905             }
906
907         case SSL_AES256_SHA:
908             {
909                 AES_CTX *aes_ctx = (AES_CTX *)malloc(sizeof(AES_CTX));
910                 AES_set_key(aes_ctx, key, iv, AES_MODE_256);
911
912                 if (is_decrypt)
913                 {
914                     AES_convert_key(aes_ctx);
915                 }
916
917                 return (void *)aes_ctx;
918             }
919
920         case SSL_RC4_128_MD5:
921 #endif
922         case SSL_RC4_128_SHA:
923             {
924                 RC4_CTX *rc4_ctx = (RC4_CTX *)malloc(sizeof(RC4_CTX));
925                 RC4_setup(rc4_ctx, key, 16);
926                 return (void *)rc4_ctx;
927             }
928     }
929
930     return NULL;    /* its all gone wrong */
931 }
932
933
934 /**
935  * Send a packet over the socket.
936  */
937 static int send_raw_packet(SSL *ssl, uint8_t protocol)
938 {   
939     uint8_t *rec_buf = ssl->bm_all_data;
940     int pkt_size = SSL_RECORD_SIZE+ssl->bm_index;
941     int sent = 0;
942     int ret = SSL_OK;
943     rec_buf[0] = protocol;
944     rec_buf[1] = 0x03;      /* version = 3.1 or higher */
945     rec_buf[2] = ssl->version & 0x0f;
946     rec_buf[3] = ssl->bm_index >> 8;
947     rec_buf[4] = ssl->bm_index & 0xff;
948
949     DISPLAY_BYTES(ssl, "sending %d bytes", ssl->bm_all_data, 
950                              pkt_size, pkt_size);
951
952
953     
954     while (sent < pkt_size)
955     {
956         ret = SOCKET_WRITE(ssl->client_fd, 
957                         &ssl->bm_all_data[sent], pkt_size-sent);
958         if (ret >= 0)
959             sent += ret;
960         else
961         {
962
963 #ifdef WIN32
964             if (GetLastError() != WSAEWOULDBLOCK)
965 #else
966             if (errno != EAGAIN && errno != EWOULDBLOCK)
967 #endif
968                 return SSL_ERROR_CONN_LOST;
969         }
970
971         /* keep going until the write buffer has some space */
972         if (sent != pkt_size)
973         {
974             fd_set wfds;
975             FD_ZERO(&wfds);
976             FD_SET(ssl->client_fd, &wfds);
977
978             /* block and wait for it */
979             if (lwip_select(FD_SETSIZE, NULL, &wfds, NULL, NULL) < 0)
980                 return SSL_ERROR_CONN_LOST;
981             
982         }
983     }
984     fd_set wfds;
985     FD_ZERO(&wfds);
986     FD_SET(ssl->client_fd, &wfds);
987     
988     /* block and wait for it */
989     if (lwip_select(FD_SETSIZE, NULL, &wfds, NULL, NULL) < 0)
990         return SSL_ERROR_CONN_LOST;
991             
992     SET_SSL_FLAG(SSL_NEED_RECORD);  /* reset for next time */
993     ssl->bm_index = 0;
994
995     if (protocol != PT_APP_PROTOCOL_DATA)  
996     {
997         /* always return SSL_OK during handshake */   
998         ret = SSL_OK;
999     }
1000
1001     return ret;
1002 }
1003
1004 /**
1005  * Send an encrypted packet with padding bytes if necessary.
1006  */
1007 int send_packet(SSL *ssl, uint8_t protocol, const uint8_t *in, int length)
1008 {
1009     int ret, msg_length = 0;
1010
1011     /* if our state is bad, don't bother */
1012     if (ssl->hs_status == SSL_ERROR_DEAD)
1013         return SSL_ERROR_CONN_LOST;
1014
1015     if (in) /* has the buffer already been initialised? */
1016     {
1017         memcpy(ssl->bm_data, in, length);
1018     }
1019
1020     msg_length += length;
1021
1022     if (IS_SET_SSL_FLAG(SSL_TX_ENCRYPTED))
1023     {
1024         int mode = IS_SET_SSL_FLAG(SSL_IS_CLIENT) ? 
1025                             SSL_CLIENT_WRITE : SSL_SERVER_WRITE;
1026         uint8_t hmac_header[SSL_RECORD_SIZE] = 
1027         {
1028             protocol, 
1029             0x03, /* version = 3.1 or higher */
1030             ssl->version & 0x0f,
1031             msg_length >> 8,
1032             msg_length & 0xff 
1033         };
1034
1035         if (protocol == PT_HANDSHAKE_PROTOCOL)
1036         {
1037             DISPLAY_STATE(ssl, 1, ssl->bm_data[0], 0);
1038
1039             if (ssl->bm_data[0] != HS_HELLO_REQUEST)
1040             {
1041                 add_packet(ssl, ssl->bm_data, msg_length);
1042             }
1043         }
1044
1045         /* add the packet digest */
1046         add_hmac_digest(ssl, mode, hmac_header, ssl->bm_data, msg_length, 
1047                                                 &ssl->bm_data[msg_length]);
1048         msg_length += ssl->cipher_info->digest_size;
1049
1050         /* add padding? */
1051         if (ssl->cipher_info->padding_size)
1052         {
1053             int last_blk_size = msg_length%ssl->cipher_info->padding_size;
1054             int pad_bytes = ssl->cipher_info->padding_size - last_blk_size;
1055
1056             /* ensure we always have at least 1 padding byte */
1057             if (pad_bytes == 0)
1058                 pad_bytes += ssl->cipher_info->padding_size;
1059
1060             memset(&ssl->bm_data[msg_length], pad_bytes-1, pad_bytes);
1061             msg_length += pad_bytes;
1062         }
1063
1064         DISPLAY_BYTES(ssl, "unencrypted write", ssl->bm_data, msg_length);
1065         increment_write_sequence(ssl);
1066
1067         /* add the explicit IV for TLS1.1 */
1068         if (ssl->version >= SSL_PROTOCOL_VERSION1_1 &&
1069                         ssl->cipher_info->iv_size)
1070         {
1071             uint8_t iv_size = ssl->cipher_info->iv_size;
1072             uint8_t *t_buf = alloca(msg_length + iv_size);
1073             memcpy(t_buf + iv_size, ssl->bm_data, msg_length);
1074             get_random(iv_size, t_buf);
1075             msg_length += iv_size;
1076             memcpy(ssl->bm_data, t_buf, msg_length);
1077         }
1078
1079         /* now encrypt the packet */
1080         ssl->cipher_info->encrypt(ssl->encrypt_ctx, ssl->bm_data, 
1081                                             ssl->bm_data, msg_length);
1082     }
1083     else if (protocol == PT_HANDSHAKE_PROTOCOL)
1084     {
1085         DISPLAY_STATE(ssl, 1, ssl->bm_data[0], 0);
1086
1087         if (ssl->bm_data[0] != HS_HELLO_REQUEST)
1088         {
1089             add_packet(ssl, ssl->bm_data, length);
1090         }
1091     }
1092
1093     ssl->bm_index = msg_length;
1094     if ((ret = send_raw_packet(ssl, protocol)) <= 0)
1095         return ret;
1096
1097     return length;  /* just return what we wanted to send */
1098 }
1099
1100 /**
1101  * Work out the cipher keys we are going to use for this session based on the
1102  * master secret.
1103  */
1104 static int set_key_block(SSL *ssl, int is_write)
1105 {
1106     const cipher_info_t *ciph_info = get_cipher_info(ssl->cipher);
1107     uint8_t *q;
1108     uint8_t client_key[32], server_key[32]; /* big enough for AES256 */
1109     uint8_t client_iv[16], server_iv[16];   /* big enough for AES128/256 */
1110     int is_client = IS_SET_SSL_FLAG(SSL_IS_CLIENT);
1111
1112     if (ciph_info == NULL)
1113         return -1;
1114
1115     uint8_t key_tmp[MAX_KEYBLOCK_SIZE] = {0};
1116     /* only do once in a handshake */
1117     if (memcmp(ssl->dc->key_block, key_tmp, MAX_KEYBLOCK_SIZE) == 0)
1118     {
1119 #if 0
1120         print_blob("client", ssl->dc->client_random, 32);
1121         print_blob("server", ssl->dc->server_random, 32);
1122         print_blob("master", ssl->dc->master_secret, SSL_SECRET_SIZE);
1123 #endif
1124         generate_key_block(ssl->dc->client_random, ssl->dc->server_random,
1125             ssl->dc->master_secret, ssl->dc->key_block, 
1126             ciph_info->key_block_size);
1127 #if 0
1128         print_blob("keyblock", ssl->dc->key_block, ciph_info->key_block_size);
1129 #endif
1130     }
1131
1132     q = ssl->dc->key_block;
1133
1134     if ((is_client && is_write) || (!is_client && !is_write))
1135     {
1136         memcpy(ssl->client_mac, q, ciph_info->digest_size);
1137     }
1138
1139     q += ciph_info->digest_size;
1140
1141     if ((!is_client && is_write) || (is_client && !is_write))
1142     {
1143         memcpy(ssl->server_mac, q, ciph_info->digest_size);
1144     }
1145
1146     q += ciph_info->digest_size;
1147     memcpy(client_key, q, ciph_info->key_size);
1148     q += ciph_info->key_size;
1149     memcpy(server_key, q, ciph_info->key_size);
1150     q += ciph_info->key_size;
1151
1152 #ifndef CONFIG_SSL_SKELETON_MODE 
1153     if (ciph_info->iv_size)    /* RC4 has no IV, AES does */
1154     {
1155         memcpy(client_iv, q, ciph_info->iv_size);
1156         q += ciph_info->iv_size;
1157         memcpy(server_iv, q, ciph_info->iv_size);
1158         q += ciph_info->iv_size;
1159     }
1160 #endif
1161
1162     if( (is_write ? ssl->encrypt_ctx : ssl->decrypt_ctx) != NULL)
1163         free(is_write ? ssl->encrypt_ctx : ssl->decrypt_ctx);
1164
1165     /* now initialise the ciphers */
1166     if (is_client)
1167     {
1168         finished_digest(ssl, server_finished, ssl->dc->final_finish_mac);
1169
1170         if (is_write)
1171             ssl->encrypt_ctx = crypt_new(ssl, client_key, client_iv, 0);
1172         else
1173             ssl->decrypt_ctx = crypt_new(ssl, server_key, server_iv, 1);
1174     }
1175     else
1176     {
1177         finished_digest(ssl, client_finished, ssl->dc->final_finish_mac);
1178
1179         if (is_write)
1180             ssl->encrypt_ctx = crypt_new(ssl, server_key, server_iv, 0);
1181         else
1182             ssl->decrypt_ctx = crypt_new(ssl, client_key, client_iv, 1);
1183     }
1184
1185     ssl->cipher_info = ciph_info;
1186     return 0;
1187 }
1188
1189 /** 
1190   * Blocking read 
1191   * data must be valid buffer of size length at least
1192   * length 
1193   */
1194 int basic_read2(SSL *ssl, uint8_t *data, uint32_t length)
1195 {
1196    // printf("basic_read2\n");
1197     if(data == NULL)
1198         return -1;
1199
1200     int ret = 0;
1201     
1202     do
1203     {
1204         //printf("before_lwip_select\n");
1205         fd_set rfds;
1206         FD_ZERO(&rfds);
1207         FD_SET(ssl->client_fd, &rfds);
1208         
1209         /* block and wait for it */
1210         if (lwip_select(FD_SETSIZE, &rfds, NULL, NULL, NULL) < 0)
1211             return SSL_ERROR_CONN_LOST;
1212       //  printf("after_lwip_select\n");
1213
1214         int read_len = SOCKET_READ(ssl->client_fd, &data[ret], length-ret);
1215       //  printf("read_len = %d\n", read_len);
1216
1217         if (read_len < 0) 
1218         {
1219     
1220 #ifdef WIN32
1221             if (GetLastError() == WSAEWOULDBLOCK)
1222 #else
1223             if (errno == EAGAIN || errno == EWOULDBLOCK)
1224 #endif
1225                 continue;
1226         }
1227     
1228         /* connection has gone, so die */
1229         if (read_len <= 0)
1230         {
1231             printf("SSL_ERROR_CONN_LOST\n");
1232             ssl->hs_status = SSL_ERROR_DEAD;  /* make sure it stays dead */
1233             return SSL_ERROR_CONN_LOST;
1234         }
1235                 
1236         ret += read_len;
1237
1238     }while(ret < length);
1239     DISPLAY_BYTES(ssl, "received %d bytes", data, ret, ret);
1240     return ret;
1241 }
1242
1243 int read_record(SSL *ssl)
1244 {
1245     if(!IS_SET_SSL_FLAG(SSL_NEED_RECORD))
1246         return 0;
1247     uint8_t record[SSL_RECORD_SIZE];
1248     int ret = basic_read2(ssl, record, SSL_RECORD_SIZE);
1249     if(ret != SSL_RECORD_SIZE)
1250         return ret;
1251
1252        /* check for sslv2 "client hello" */
1253     if (record[0] & 0x80 && record[2] == 1)
1254     {
1255 #ifdef CONFIG_SSL_ENABLE_V23_HANDSHAKE
1256         uint8_t version = (record[3] << 4) + record[4];
1257         DISPLAY_BYTES(ssl, "ssl2 record", record, 5);
1258
1259         /* should be v3.1 (TLSv1) or better  */
1260         ssl->version = ssl->client_version = version;
1261
1262         if (version > SSL_PROTOCOL_VERSION_MAX)
1263         {
1264             /* use client's version */
1265             ssl->version = SSL_PROTOCOL_VERSION_MAX;
1266         }
1267         else if (version < SSL_PROTOCOL_MIN_VERSION)  
1268         {
1269             ret = SSL_ERROR_INVALID_VERSION;
1270             ssl_display_error(ret);
1271             return ret;
1272         }
1273
1274         add_packet(ssl, &record[2], 3);
1275         ret = process_sslv23_client_hello(ssl); 
1276 #else
1277         printf("Error: no SSLv23 handshaking allowed\n"); TTY_FLUSH();
1278         ret = SSL_ERROR_NOT_SUPPORTED;
1279 #endif
1280         return ret;
1281     }
1282
1283     ssl->need_bytes = (record[3] << 8) + record[4];
1284
1285
1286     memcpy(ssl->hmac_header, record, 3);       /* store for hmac */
1287     ssl->record_type = record[0];
1288     CLR_SSL_FLAG(SSL_NEED_RECORD);
1289     return SSL_OK;
1290 }
1291
1292 int basic_decrypt(SSL *ssl, uint8_t *buf, int len)
1293 {
1294    if (IS_SET_SSL_FLAG(SSL_RX_ENCRYPTED))
1295     {
1296         ssl->cipher_info->decrypt(ssl->decrypt_ctx, buf, buf, len);
1297
1298         if (ssl->version >= SSL_PROTOCOL_VERSION1_1 &&
1299                         ssl->cipher_info->iv_size)
1300         {
1301             buf += ssl->cipher_info->iv_size;
1302             ssl->need_bytes -= ssl->cipher_info->iv_size;
1303         }
1304         if(ssl->record_type != PT_APP_PROTOCOL_DATA)
1305             len = verify_digest(ssl, 
1306                     IS_SET_SSL_FLAG(SSL_IS_CLIENT) ? SSL_CLIENT_READ : SSL_SERVER_READ, buf, len);
1307
1308         /* does the hmac work? */
1309         if (ssl->need_bytes < 0)
1310         {
1311             return ssl->need_bytes;
1312         }
1313
1314         DISPLAY_BYTES(ssl, "decrypted", buf, len);
1315         increment_read_sequence(ssl);
1316     }
1317     return len;
1318 }
1319
1320 int ssl_read(SSL *ssl, uint8_t *in_data, int len)
1321 {
1322     if(len <= 0 || in_data == NULL)
1323         return 0;
1324    
1325     if(IS_SET_SSL_FLAG(SSL_NEED_RECORD))
1326     {
1327         read_record(ssl);
1328     }
1329    
1330     return process_data(ssl, in_data, len);
1331 }
1332
1333 int process_data(SSL* ssl, uint8_t *in_data, int len)
1334 {
1335     /* The main part of the SSL packet */
1336     switch (ssl->record_type)
1337     {
1338         case PT_HANDSHAKE_PROTOCOL:
1339
1340             if (ssl->dc != NULL)
1341             {
1342                 ssl->dc->bm_proc_index = 0;
1343                 int ret = do_handshake(ssl, NULL, 0);
1344                 SET_SSL_FLAG(SSL_NEED_RECORD);
1345                 return ret;
1346             }
1347             else /* no client renegotiation allowed */
1348             {
1349                 SET_SSL_FLAG(SSL_NEED_RECORD);
1350                 return SSL_ERROR_NO_CLIENT_RENOG;              
1351             }
1352
1353         case PT_CHANGE_CIPHER_SPEC:
1354         
1355             if(basic_read2(ssl, ssl->bm_data, ssl->need_bytes) != ssl->need_bytes)
1356                 return -1;
1357             ssl->need_bytes = basic_decrypt(ssl, ssl->bm_data, ssl->need_bytes);
1358             if(ssl->need_bytes < 0)
1359                 return -1;
1360
1361             if (ssl->next_state != HS_FINISHED)
1362             {
1363                 return SSL_ERROR_INVALID_HANDSHAKE;
1364             }
1365
1366             /* all encrypted from now on */
1367             SET_SSL_FLAG(SSL_RX_ENCRYPTED);
1368             if (set_key_block(ssl, 0) < 0)
1369             {
1370                 return SSL_ERROR_INVALID_HANDSHAKE;
1371             }
1372             
1373             memset(ssl->read_sequence, 0, 8);
1374             SET_SSL_FLAG(SSL_NEED_RECORD);
1375             break;
1376
1377         case PT_APP_PROTOCOL_DATA:
1378             if(len <= 0)
1379                 return 0;
1380             if(ssl->need_bytes == 0)
1381                 return 0;
1382             if (in_data)
1383             {
1384                 uint16_t index = ssl->bm_index % 2048;
1385                 if(ssl->bm_read_index == 0)
1386                 {
1387                     int read_len = len;
1388                     if(read_len > 2048-index)
1389                         read_len = 2048-index;
1390                     if(read_len > ssl->need_bytes)
1391                         read_len = ssl->need_bytes;
1392                     read_len -= read_len % AES_BLOCKSIZE;
1393
1394                     if(read_len <= 0)
1395                         read_len = AES_BLOCKSIZE;
1396                     if(ssl->need_bytes < AES_BLOCKSIZE)
1397                         read_len = AES_BLOCKSIZE;
1398                     int ret = basic_read2(ssl, ssl->bm_all_data + index, read_len);
1399                     if(ret != read_len)
1400                         return 0;
1401                     
1402                     ssl->bm_read_index = basic_decrypt(ssl, ssl->bm_all_data + index, read_len);
1403                     ssl->need_bytes -= ssl->bm_read_index;
1404                     if(ssl->need_bytes == 0)
1405                     {
1406                         ssl->bm_read_index = 0;
1407                         SET_SSL_FLAG(SSL_NEED_RECORD);
1408                         return ssl_read(ssl, in_data, len);
1409                     }
1410                 }
1411                 if(len > ssl->bm_read_index)
1412                     len = ssl->bm_read_index;
1413                 memcpy(in_data, ssl->bm_all_data+index, len);
1414                 ssl->bm_index += len;
1415                 ssl->bm_read_index -= len;
1416                 
1417                 if(ssl->need_bytes == 0)
1418                     SET_SSL_FLAG(SSL_NEED_RECORD);
1419                 if(ssl->bm_index >= 2048)
1420                     ssl->bm_index = 0;
1421                 return len;
1422             }
1423             return 0;
1424             
1425         case PT_ALERT_PROTOCOL:
1426             if(basic_read2(ssl, ssl->bm_data, ssl->need_bytes) != ssl->need_bytes)
1427                 return -1;
1428             ssl->need_bytes = basic_decrypt(ssl, ssl->bm_data, ssl->need_bytes);
1429             if(ssl->need_bytes < 0)
1430                 return -1; 
1431             
1432             SET_SSL_FLAG(SSL_NEED_RECORD);
1433
1434             /* return the alert # with alert bit set */
1435             if(ssl->bm_data[0] == SSL_ALERT_TYPE_WARNING &&
1436                ssl->bm_data[1] == SSL_ALERT_CLOSE_NOTIFY)
1437             {
1438                 send_alert(ssl, SSL_ALERT_CLOSE_NOTIFY);
1439                 SET_SSL_FLAG(SSL_SENT_CLOSE_NOTIFY);
1440                 return SSL_CLOSE_NOTIFY;
1441             }
1442             else 
1443             {
1444                 int ret = -ssl->bm_data[1];
1445                 DISPLAY_ALERT(ssl, -ret);
1446                 return ret;
1447             }
1448
1449         default:
1450             return SSL_ERROR_INVALID_PROT_MSG;
1451
1452     }
1453 }
1454
1455
1456 /**
1457  * Do some basic checking of data and then perform the appropriate handshaking.
1458  */
1459 static int do_handshake(SSL *ssl, uint8_t *buf, int read_len)
1460 {
1461     uint8_t hs_hdr[SSL_HS_HDR_SIZE];
1462     if (IS_SET_SSL_FLAG(SSL_RX_ENCRYPTED))
1463     {
1464         if(basic_read2(ssl, ssl->bm_data, ssl->need_bytes) != ssl->need_bytes)
1465             return -1;
1466         ssl->need_bytes = basic_decrypt(ssl, ssl->bm_data, ssl->need_bytes);
1467         if(ssl->need_bytes < 0)
1468             return -1; 
1469         buf = ssl->bm_data;
1470     }
1471     else
1472     {
1473         if(basic_read2(ssl, hs_hdr, SSL_HS_HDR_SIZE) != SSL_HS_HDR_SIZE)
1474             return -1;
1475         buf = hs_hdr;
1476     }
1477
1478     int hs_len = (buf[2]<<8) + buf[3];
1479     uint8_t handshake_type = buf[0];
1480     int ret = SSL_OK;
1481     int is_client = IS_SET_SSL_FLAG(SSL_IS_CLIENT);
1482
1483     /* some integrity checking on the handshake */
1484     //PARANOIA_CHECK(read_len-SSL_HS_HDR_SIZE, hs_len);
1485
1486     if (handshake_type != ssl->next_state)
1487     {
1488         /* handle a special case on the client */
1489         if (!is_client || handshake_type != HS_CERT_REQ ||
1490                         ssl->next_state != HS_SERVER_HELLO_DONE)
1491         {
1492             return SSL_ERROR_INVALID_HANDSHAKE;
1493         }
1494     }
1495
1496     //hs_len += SSL_HS_HDR_SIZE;  /* adjust for when adding packets */
1497     ssl->bm_index = hs_len+SSL_HS_HDR_SIZE;     /* store the size and check later */
1498     DISPLAY_STATE(ssl, 0, handshake_type, 0);
1499
1500     if (handshake_type != HS_CERT_VERIFY && handshake_type != HS_HELLO_REQUEST)
1501     {
1502         add_packet(ssl, buf, SSL_HS_HDR_SIZE); 
1503     }
1504     
1505     if(!IS_SET_SSL_FLAG(SSL_RX_ENCRYPTED))
1506     {
1507         if(hs_len != 0 && handshake_type != HS_CERTIFICATE)
1508         {
1509             if(basic_read2(ssl, ssl->bm_data, hs_len) != hs_len)
1510                 return -1;
1511             hs_len = basic_decrypt(ssl, ssl->bm_data, hs_len);
1512             if(hs_len < 0)
1513                 return -1; 
1514             
1515             buf = ssl->bm_data;
1516             if (handshake_type != HS_CERT_VERIFY && handshake_type != HS_HELLO_REQUEST)
1517                 add_packet(ssl, buf, hs_len);
1518         }
1519     }
1520     else if (handshake_type != HS_CERT_VERIFY && handshake_type != HS_HELLO_REQUEST)
1521         add_packet(ssl, ssl->bm_data+SSL_HS_HDR_SIZE, hs_len-SSL_HS_HDR_SIZE);
1522
1523 #if defined(CONFIG_SSL_ENABLE_CLIENT)
1524     ret = is_client ? 
1525         do_clnt_handshake(ssl, handshake_type, buf, hs_len) :
1526         do_svr_handshake(ssl, handshake_type, buf, hs_len);
1527 #else
1528     ret = do_svr_handshake(ssl, handshake_type, buf, hs_len);
1529 #endif
1530
1531     /* just use recursion to get the rest */
1532     //if (hs_len < read_len && ret == SSL_OK)
1533         //ret = do_handshake(ssl, &buf[hs_len], read_len-hs_len);
1534
1535     return ret;
1536 }
1537
1538 /**
1539  * Sends the change cipher spec message. We have just read a finished message
1540  * from the client.
1541  */
1542 int send_change_cipher_spec(SSL *ssl)
1543 {
1544     int ret = send_packet(ssl, PT_CHANGE_CIPHER_SPEC, 
1545             g_chg_cipher_spec_pkt, sizeof(g_chg_cipher_spec_pkt));
1546     SET_SSL_FLAG(SSL_TX_ENCRYPTED);
1547
1548     if (ret >= 0 && set_key_block(ssl, 1) < 0)
1549         ret = SSL_ERROR_INVALID_HANDSHAKE;
1550
1551     memset(ssl->write_sequence, 0, 8);
1552     return ret;
1553 }
1554
1555 /**
1556  * Send a "finished" message
1557  */
1558 int send_finished(SSL *ssl)
1559 {
1560     uint8_t buf[SSL_FINISHED_HASH_SIZE+4] = {
1561         HS_FINISHED, 0, 0, SSL_FINISHED_HASH_SIZE };
1562
1563     /* now add the finished digest mac (12 bytes) */
1564     finished_digest(ssl, 
1565         IS_SET_SSL_FLAG(SSL_IS_CLIENT) ?
1566                     client_finished : server_finished, &buf[4]);
1567
1568 #ifndef CONFIG_SSL_SKELETON_MODE
1569     /* store in the session cache */
1570     if (!IS_SET_SSL_FLAG(SSL_SESSION_RESUME) && ssl->ssl_ctx->num_sessions)
1571     {
1572         memcpy(ssl->session->master_secret,
1573                 ssl->dc->master_secret, SSL_SECRET_SIZE);
1574     }
1575 #endif
1576
1577     return send_packet(ssl, PT_HANDSHAKE_PROTOCOL,
1578                                 buf, SSL_FINISHED_HASH_SIZE+4);
1579 }
1580
1581 /**
1582  * Send an alert message.
1583  * Return 1 if the alert was an "error".
1584  */
1585 int send_alert(SSL *ssl, int error_code)
1586 {
1587     int alert_num = 0;
1588     int is_warning = 0;
1589     uint8_t buf[2];
1590
1591     /* Don't bother we're already dead */
1592     if (ssl->hs_status == SSL_ERROR_DEAD)
1593     {
1594         return SSL_ERROR_CONN_LOST;
1595     }
1596
1597 #ifdef CONFIG_SSL_FULL_MODE
1598     if (IS_SET_SSL_FLAG(SSL_DISPLAY_STATES))
1599         ssl_display_error(error_code);
1600 #endif
1601
1602     switch (error_code)
1603     {
1604         case SSL_ALERT_CLOSE_NOTIFY:
1605             is_warning = 1;
1606             alert_num = SSL_ALERT_CLOSE_NOTIFY;
1607             break;
1608
1609         case SSL_ERROR_CONN_LOST:       /* don't send alert just yet */
1610             is_warning = 1;
1611             break;
1612
1613         case SSL_ERROR_INVALID_HANDSHAKE:
1614         case SSL_ERROR_INVALID_PROT_MSG:
1615             alert_num = SSL_ALERT_HANDSHAKE_FAILURE;
1616             break;
1617
1618         case SSL_ERROR_INVALID_HMAC:
1619         case SSL_ERROR_FINISHED_INVALID:
1620             alert_num = SSL_ALERT_BAD_RECORD_MAC;
1621             break;
1622
1623         case SSL_ERROR_INVALID_VERSION:
1624             alert_num = SSL_ALERT_INVALID_VERSION;
1625             break;
1626
1627         case SSL_ERROR_INVALID_SESSION:
1628         case SSL_ERROR_NO_CIPHER:
1629         case SSL_ERROR_INVALID_KEY:
1630             alert_num = SSL_ALERT_ILLEGAL_PARAMETER;
1631             break;
1632
1633         case SSL_ERROR_BAD_CERTIFICATE:
1634             alert_num = SSL_ALERT_BAD_CERTIFICATE;
1635             break;
1636
1637         case SSL_ERROR_NO_CLIENT_RENOG:
1638             alert_num = SSL_ALERT_NO_RENEGOTIATION;
1639             break;
1640
1641         default:
1642             /* a catch-all for any badly verified certificates */
1643             alert_num = (error_code <= SSL_X509_OFFSET) ?  
1644                 SSL_ALERT_BAD_CERTIFICATE : SSL_ALERT_UNEXPECTED_MESSAGE;
1645             break;
1646     }
1647
1648     buf[0] = is_warning ? 1 : 2;
1649     buf[1] = alert_num;
1650
1651     send_packet(ssl, PT_ALERT_PROTOCOL, buf, sizeof(buf));
1652     DISPLAY_ALERT(ssl, alert_num);
1653     return is_warning ? 0 : 1;
1654 }
1655
1656 /**
1657  * Process a client finished message.
1658  */
1659 int process_finished(SSL *ssl, uint8_t *buf, int hs_len)
1660 {
1661     int is_client = IS_SET_SSL_FLAG(SSL_IS_CLIENT);
1662     int ret = SSL_OK;
1663     int resume = IS_SET_SSL_FLAG(SSL_SESSION_RESUME);
1664
1665     PARANOIA_CHECK(ssl->bm_index, SSL_FINISHED_HASH_SIZE);
1666
1667     /* check that we all work before we continue */
1668     if (memcmp(ssl->dc->final_finish_mac, &buf[4], SSL_FINISHED_HASH_SIZE))
1669     {
1670         return SSL_ERROR_FINISHED_INVALID;
1671     }
1672     if ((!is_client && !resume) || (is_client && resume))
1673     {
1674         if ((ret = send_change_cipher_spec(ssl)) == SSL_OK)
1675             ret = send_finished(ssl);
1676     }
1677
1678     /* if we ever renegotiate */
1679     ssl->next_state = is_client ? HS_HELLO_REQUEST : HS_CLIENT_HELLO;  
1680     ssl->hs_status = ret;  /* set the final handshake status */
1681 error:
1682     return ret;
1683 }
1684
1685 /**
1686  * Send a certificate.
1687  */
1688 int send_certificate(SSL *ssl)
1689 {
1690     int i = 0;
1691     uint8_t *buf = ssl->bm_data;
1692     int offset = 7;
1693     int chain_length;
1694
1695     buf[0] = HS_CERTIFICATE;
1696     buf[1] = 0;
1697     buf[4] = 0;
1698
1699     while (i < ssl->ssl_ctx->chain_length)
1700     {
1701         SSL_CERT *cert = &ssl->ssl_ctx->certs[i];
1702         buf[offset++] = 0;        
1703         buf[offset++] = cert->size >> 8;        /* cert 1 length */
1704         buf[offset++] = cert->size & 0xff;
1705         memcpy(&buf[offset], cert->buf, cert->size);
1706         offset += cert->size;
1707         i++;
1708     }
1709
1710     chain_length = offset - 7;
1711     buf[5] = chain_length >> 8;        /* cert chain length */
1712     buf[6] = chain_length & 0xff;
1713     chain_length += 3;
1714     buf[2] = chain_length >> 8;        /* handshake length */
1715     buf[3] = chain_length & 0xff;
1716     ssl->bm_index = offset;
1717     return send_packet(ssl, PT_HANDSHAKE_PROTOCOL, NULL, offset);
1718 }
1719
1720 /**
1721  * Create a blob of memory that we'll get rid of once the handshake is
1722  * complete.
1723  */
1724 void disposable_new(SSL *ssl)
1725 {
1726     if (ssl->dc == NULL)
1727     {
1728         ssl->dc = (DISPOSABLE_CTX *)calloc(1, sizeof(DISPOSABLE_CTX));
1729         memset(ssl->dc->key_block, 0, MAX_KEYBLOCK_SIZE);
1730         MD5_Init(&ssl->dc->md5_ctx);
1731         SHA1_Init(&ssl->dc->sha1_ctx);
1732     }
1733 }
1734
1735 /**
1736  * Remove the temporary blob of memory.
1737  */
1738 void disposable_free(SSL *ssl)
1739 {
1740     if (ssl->dc)
1741     {
1742         //free(ssl->dc->key_block);
1743         memset(ssl->dc, 0, sizeof(DISPOSABLE_CTX));
1744         free(ssl->dc);
1745         ssl->dc = NULL;
1746     }
1747
1748 }
1749
1750 #ifndef CONFIG_SSL_SKELETON_MODE     /* no session resumption in this mode */
1751 /**
1752  * Find if an existing session has the same session id. If so, use the
1753  * master secret from this session for session resumption.
1754  */
1755 SSL_SESSION *ssl_session_update(int max_sessions, SSL_SESSION *ssl_sessions[], 
1756         SSL *ssl, const uint8_t *session_id)
1757 {
1758     time_t tm = time(NULL);
1759     time_t oldest_sess_time = tm;
1760     SSL_SESSION *oldest_sess = NULL;
1761     int i;
1762
1763     /* no sessions? Then bail */
1764     if (max_sessions == 0)
1765         return NULL;
1766
1767     SSL_CTX_LOCK(ssl->ssl_ctx->mutex);
1768     if (session_id)
1769     {
1770         for (i = 0; i < max_sessions; i++)
1771         {
1772             if (ssl_sessions[i])
1773             {
1774                 /* kill off any expired sessions (including those in 
1775                    the future) */
1776                 if ((tm > ssl_sessions[i]->conn_time + SSL_EXPIRY_TIME) ||
1777                             (tm < ssl_sessions[i]->conn_time))
1778                 {
1779                     session_free(ssl_sessions, i);
1780                     continue;
1781                 }
1782
1783                 /* if the session id matches, it must still be less than 
1784                    the expiry time */
1785                 if (memcmp(ssl_sessions[i]->session_id, session_id,
1786                                                 SSL_SESSION_ID_SIZE) == 0)
1787                 {
1788                     ssl->session_index = i;
1789                     memcpy(ssl->dc->master_secret, 
1790                             ssl_sessions[i]->master_secret, SSL_SECRET_SIZE);
1791                     SET_SSL_FLAG(SSL_SESSION_RESUME);
1792                     SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex);
1793                     return ssl_sessions[i];  /* a session was found */
1794                 }
1795             }
1796         }
1797     }
1798
1799     /* If we've got here, no matching session was found - so create one */
1800     for (i = 0; i < max_sessions; i++)
1801     {
1802         if (ssl_sessions[i] == NULL)
1803         {
1804             /* perfect, this will do */
1805             ssl_sessions[i] = (SSL_SESSION *)calloc(1, sizeof(SSL_SESSION));
1806             ssl_sessions[i]->conn_time = tm;
1807             ssl->session_index = i;
1808             SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex);
1809             return ssl_sessions[i]; /* return the session object */
1810         }
1811         else if (ssl_sessions[i]->conn_time <= oldest_sess_time)
1812         {
1813             /* find the oldest session */
1814             oldest_sess_time = ssl_sessions[i]->conn_time;
1815             oldest_sess = ssl_sessions[i];
1816             ssl->session_index = i;
1817         }
1818     }
1819
1820     /* ok, we've used up all of our sessions. So blow the oldest session away */
1821     oldest_sess->conn_time = tm;
1822     memset(oldest_sess->session_id, 0, sizeof(SSL_SESSION_ID_SIZE));
1823     memset(oldest_sess->master_secret, 0, sizeof(SSL_SECRET_SIZE));
1824     SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex);
1825     return oldest_sess;
1826 }
1827
1828 /**
1829  * Free an existing session.
1830  */
1831 static void session_free(SSL_SESSION *ssl_sessions[], int sess_index)
1832 {
1833     if (ssl_sessions[sess_index])
1834     {
1835         free(ssl_sessions[sess_index]);
1836         ssl_sessions[sess_index] = NULL;
1837     }
1838 }
1839
1840 /**
1841  * This ssl object doesn't want this session anymore.
1842  */
1843 void kill_ssl_session(SSL_SESSION **ssl_sessions, SSL *ssl)
1844 {
1845     SSL_CTX_LOCK(ssl->ssl_ctx->mutex);
1846
1847     if (ssl->ssl_ctx->num_sessions)
1848     {
1849         session_free(ssl_sessions, ssl->session_index);
1850         ssl->session = NULL;
1851     }
1852
1853     SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex);
1854 }
1855 #endif /* CONFIG_SSL_SKELETON_MODE */
1856
1857 /*
1858  * Get the session id for a handshake. This will be a 32 byte sequence.
1859  */
1860 EXP_FUNC const uint8_t * STDCALL ssl_get_session_id(const SSL *ssl)
1861 {
1862     return ssl->session_id;
1863 }
1864
1865 /*
1866  * Get the session id size for a handshake. 
1867  */
1868 EXP_FUNC uint8_t STDCALL ssl_get_session_id_size(const SSL *ssl)
1869 {
1870     return ssl->sess_id_size;
1871 }
1872
1873 /*
1874  * Return the cipher id (in the SSL form).
1875  */
1876 EXP_FUNC uint8_t STDCALL ssl_get_cipher_id(const SSL *ssl)
1877 {
1878     return ssl->cipher;
1879 }
1880
1881 /*
1882  * Return the status of the handshake.
1883  */
1884 EXP_FUNC int STDCALL ssl_handshake_status(const SSL *ssl)
1885 {
1886     return ssl->hs_status;
1887 }
1888
1889 /*
1890  * Retrieve various parameters about the SSL engine.
1891  */
1892 EXP_FUNC int STDCALL ssl_get_config(int offset)
1893 {
1894     switch (offset)
1895     {
1896         /* return the appropriate build mode */
1897         case SSL_BUILD_MODE:
1898 #if defined(CONFIG_SSL_FULL_MODE)
1899             return SSL_BUILD_FULL_MODE;
1900 #elif defined(CONFIG_SSL_ENABLE_CLIENT)
1901             return SSL_BUILD_ENABLE_CLIENT;
1902 #elif defined(CONFIG_ENABLE_VERIFICATION)
1903             return SSL_BUILD_ENABLE_VERIFICATION;
1904 #elif defined(CONFIG_SSL_SERVER_ONLY )
1905             return SSL_BUILD_SERVER_ONLY;
1906 #else 
1907             return SSL_BUILD_SKELETON_MODE;
1908 #endif
1909
1910         case SSL_MAX_CERT_CFG_OFFSET:
1911             return CONFIG_SSL_MAX_CERTS;
1912
1913 #ifdef CONFIG_SSL_CERT_VERIFICATION
1914         case SSL_MAX_CA_CERT_CFG_OFFSET:
1915             return CONFIG_X509_MAX_CA_CERTS;
1916 #endif
1917 #ifdef CONFIG_SSL_HAS_PEM
1918         case SSL_HAS_PEM:
1919             return 1;
1920 #endif
1921         default:
1922             return 0;
1923     }
1924 }
1925
1926 #ifdef CONFIG_SSL_CERT_VERIFICATION
1927 /**
1928  * Authenticate a received certificate.
1929  */
1930 EXP_FUNC int STDCALL ssl_verify_cert(const SSL *ssl)
1931 {
1932     int ret;
1933     SSL_CTX_LOCK(ssl->ssl_ctx->mutex);
1934     ret = x509_verify(ssl->ssl_ctx->ca_cert_ctx, ssl->x509_ctx);
1935     SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex);
1936
1937     if (ret)        /* modify into an SSL error type */
1938     {
1939         ret = SSL_X509_ERROR(ret);
1940     }
1941
1942     return ret;
1943 }
1944
1945 /**
1946  * Process a certificate message.
1947  */
1948 int process_certificate(SSL *ssl, X509_CTX **x509_ctx)
1949 {
1950     int ret = SSL_OK;
1951     
1952     uint8_t cert_hdr[3];
1953     if(basic_read2(ssl, cert_hdr, 3) != 3)
1954     {
1955         ret = SSL_NOT_OK;
1956         return ret;
1957     }
1958
1959     add_packet(ssl, cert_hdr, 3);
1960     int len = 5;
1961     int pkt_size = ssl->bm_index;
1962     int cert_size;
1963     int total_cert_size = (cert_hdr[1]<<8) + cert_hdr[2];
1964     int is_client = IS_SET_SSL_FLAG(SSL_IS_CLIENT);
1965     X509_CTX **chain = x509_ctx;
1966     len += 2;
1967     PARANOIA_CHECK(total_cert_size, 3);
1968
1969     while (len < total_cert_size)
1970     {
1971
1972         if(basic_read2(ssl, cert_hdr, 3) != 3)
1973         {
1974             ret = SSL_NOT_OK;
1975             return ret;
1976         }
1977
1978         add_packet(ssl, cert_hdr, 3);
1979
1980         cert_size = (cert_hdr[1]<<8) + cert_hdr[2];
1981         if(cert_size > RT_MAX_PLAIN_LENGTH)
1982         {
1983             ret = SSL_NOT_OK;
1984             return ret;
1985         }
1986         
1987         len += 3;
1988
1989         if(basic_read2(ssl, ssl->bm_data, cert_size) != cert_size)
1990         {
1991             return SSL_NOT_OK;
1992         }
1993
1994         add_packet(ssl, ssl->bm_data, cert_size);
1995
1996         if (x509_new(ssl->bm_data, NULL, chain))
1997         {
1998             ret = SSL_ERROR_BAD_CERTIFICATE;
1999             goto error;
2000         }
2001
2002         chain = &((*chain)->next);
2003         len += cert_size;
2004     }
2005     PARANOIA_CHECK(pkt_size, len);
2006
2007     /* if we are client we can do the verify now or later */
2008     if (is_client && !IS_SET_SSL_FLAG(SSL_SERVER_VERIFY_LATER))
2009     {
2010         ret = ssl_verify_cert(ssl);
2011     }
2012
2013     ssl->next_state = is_client ? HS_SERVER_HELLO_DONE : HS_CLIENT_KEY_XCHG;
2014     ssl->dc->bm_proc_index += len;
2015 error:
2016
2017     return ret;
2018 }
2019
2020 #endif /* CONFIG_SSL_CERT_VERIFICATION */
2021
2022 /**
2023  * Debugging routine to display SSL handshaking stuff.
2024  */
2025 #ifdef CONFIG_SSL_FULL_MODE
2026 /**
2027  * Debugging routine to display SSL states.
2028  */
2029 void DISPLAY_STATE(SSL *ssl, int is_send, uint8_t state, int not_ok)
2030 {
2031     const char *str;
2032
2033     if (!IS_SET_SSL_FLAG(SSL_DISPLAY_STATES))
2034         return;
2035
2036     printf(not_ok ? "Error - invalid State:\t" : "State:\t");
2037     printf(is_send ? "sending " : "receiving ");
2038
2039     switch (state)
2040     {
2041         case HS_HELLO_REQUEST:
2042             str = "Hello Request (0)";
2043             break;
2044
2045         case HS_CLIENT_HELLO:
2046             str = "Client Hello (1)";
2047             break;
2048
2049         case HS_SERVER_HELLO:
2050             str = "Server Hello (2)";
2051             break;
2052
2053         case HS_CERTIFICATE:
2054             str = "Certificate (11)";
2055             break;
2056
2057         case HS_SERVER_KEY_XCHG:
2058             str = "Certificate Request (12)";
2059             break;
2060
2061         case HS_CERT_REQ:
2062             str = "Certificate Request (13)";
2063             break;
2064
2065         case HS_SERVER_HELLO_DONE:
2066             str = "Server Hello Done (14)";
2067             break;
2068
2069         case HS_CERT_VERIFY:
2070             str = "Certificate Verify (15)";
2071             break;
2072
2073         case HS_CLIENT_KEY_XCHG:
2074             str = "Client Key Exchange (16)";
2075             break;
2076
2077         case HS_FINISHED:
2078             str = "Finished (16)";
2079             break;
2080
2081         default:
2082             str = "Error (Unknown)";
2083             
2084             break;
2085     }
2086
2087     printf("%s\r\n", str);
2088     TTY_FLUSH();
2089 }
2090
2091 /**
2092  * Debugging routine to display RSA objects
2093  */
2094 void DISPLAY_RSA(SSL *ssl, const RSA_CTX *rsa_ctx)
2095 {
2096     if (!IS_SET_SSL_FLAG(SSL_DISPLAY_RSA))
2097         return;
2098
2099     RSA_print(rsa_ctx);
2100     TTY_FLUSH();
2101 }
2102
2103 /**
2104  * Debugging routine to display SSL handshaking bytes.
2105  */
2106 void DISPLAY_BYTES(SSL *ssl, const char *format, 
2107         const uint8_t *data, int size, ...)
2108 {
2109     va_list(ap);
2110
2111     if (!IS_SET_SSL_FLAG(SSL_DISPLAY_BYTES))
2112         return;
2113
2114     va_start(ap, size);
2115     print_blob(format, data, size, va_arg(ap, char *));
2116     va_end(ap);
2117     TTY_FLUSH();
2118 }
2119
2120 /**
2121  * Debugging routine to display SSL handshaking errors.
2122  */
2123 EXP_FUNC void STDCALL ssl_display_error(int error_code)
2124 {
2125     if (error_code == SSL_OK)
2126         return;
2127
2128     printf("Error: ");
2129
2130     /* X509 error? */
2131     if (error_code < SSL_X509_OFFSET)
2132     {
2133         printf("%s\r\n", x509_display_error(error_code - SSL_X509_OFFSET));
2134         return;
2135     }
2136
2137     /* SSL alert error code */
2138     if (error_code > SSL_ERROR_CONN_LOST)
2139     {
2140         printf("SSL error %d\n", -error_code);
2141         return;
2142     }
2143
2144     switch (error_code)
2145     {
2146         case SSL_ERROR_DEAD:
2147             printf("connection dead");
2148             break;
2149
2150         case SSL_ERROR_INVALID_HANDSHAKE:
2151             printf("invalid handshake");
2152             break;
2153
2154         case SSL_ERROR_INVALID_PROT_MSG:
2155             printf("invalid protocol message");
2156             break;
2157
2158         case SSL_ERROR_INVALID_HMAC:
2159             printf("invalid mac");
2160             break;
2161
2162         case SSL_ERROR_INVALID_VERSION:
2163             printf("invalid version");
2164             break;
2165
2166         case SSL_ERROR_INVALID_SESSION:
2167             printf("invalid session");
2168             break;
2169
2170         case SSL_ERROR_NO_CIPHER:
2171             printf("no cipher");
2172             break;
2173
2174         case SSL_ERROR_CONN_LOST:
2175             printf("connection lost");
2176             break;
2177
2178         case SSL_ERROR_BAD_CERTIFICATE:
2179             printf("bad certificate");
2180             break;
2181
2182         case SSL_ERROR_INVALID_KEY:
2183             printf("invalid key");
2184             break;
2185
2186         case SSL_ERROR_FINISHED_INVALID:
2187             printf("finished invalid");
2188             break;
2189
2190         case SSL_ERROR_NO_CERT_DEFINED:
2191             printf("no certificate defined");
2192             break;
2193
2194         case SSL_ERROR_NO_CLIENT_RENOG:
2195             printf("client renegotiation not supported");
2196             break;
2197             
2198         case SSL_ERROR_NOT_SUPPORTED:
2199             printf("Option not supported");
2200             break;
2201
2202         default:
2203             printf("undefined as yet - %d", error_code);
2204             break;
2205     }
2206
2207     printf("\r\n");
2208     TTY_FLUSH();
2209 }
2210
2211 /**
2212  * Debugging routine to display alerts.
2213  */
2214 void DISPLAY_ALERT(SSL *ssl, int alert)
2215 {
2216     if (!IS_SET_SSL_FLAG(SSL_DISPLAY_STATES))
2217         return;
2218
2219     printf("Alert: ");
2220
2221     switch (alert)
2222     {
2223         case SSL_ALERT_CLOSE_NOTIFY:
2224             printf("close notify");
2225             break;
2226
2227         case SSL_ALERT_INVALID_VERSION:
2228             printf("invalid version");
2229             break;
2230
2231         case SSL_ALERT_BAD_CERTIFICATE:
2232             printf("bad certificate");
2233             break;
2234
2235         case SSL_ALERT_UNEXPECTED_MESSAGE:
2236             printf("unexpected message");
2237             break;
2238
2239         case SSL_ALERT_BAD_RECORD_MAC:
2240             printf("bad record mac");
2241             break;
2242
2243         case SSL_ALERT_HANDSHAKE_FAILURE:
2244             printf("handshake failure");
2245             break;
2246
2247         case SSL_ALERT_ILLEGAL_PARAMETER:
2248             printf("illegal parameter");
2249             break;
2250
2251         case SSL_ALERT_DECODE_ERROR:
2252             printf("decode error");
2253             break;
2254
2255         case SSL_ALERT_DECRYPT_ERROR:
2256             printf("decrypt error");
2257             break;
2258
2259         case SSL_ALERT_NO_RENEGOTIATION:
2260             printf("no renegotiation");
2261             break;
2262
2263         default:
2264             printf("alert - (unknown %d)", alert);
2265             break;
2266     }
2267
2268     printf("\r\n");
2269     TTY_FLUSH();
2270 }
2271
2272 #endif /* CONFIG_SSL_FULL_MODE */
2273
2274 /**
2275  * Return the version of this library.
2276  */
2277 EXP_FUNC const char  * STDCALL ssl_version()
2278 {
2279     static const char * axtls_version = AXTLS_VERSION;
2280     return axtls_version;
2281 }
2282
2283 /**
2284  * Enable the various language bindings to work regardless of the
2285  * configuration - they just return an error statement and a bad return code.
2286  */
2287 #if !defined(CONFIG_SSL_FULL_MODE)
2288 EXP_FUNC void STDCALL ssl_display_error(int error_code) {}
2289 #endif
2290
2291 #ifdef CONFIG_BINDINGS
2292 #if !defined(CONFIG_SSL_ENABLE_CLIENT)
2293 EXP_FUNC SSL * STDCALL ssl_client_new(SSL_CTX *ssl_ctx, int client_fd, const
2294         uint8_t *session_id, uint8_t sess_id_size)
2295 {
2296     printf(unsupported_str);
2297     return NULL;
2298 }
2299 #endif
2300
2301 #if !defined(CONFIG_SSL_CERT_VERIFICATION)
2302 EXP_FUNC int STDCALL ssl_verify_cert(const SSL *ssl)
2303 {
2304     printf(unsupported_str);
2305     return -1;
2306 }
2307
2308
2309 EXP_FUNC const char * STDCALL ssl_get_cert_dn(const SSL *ssl, int component)
2310 {
2311     printf(unsupported_str);
2312     return NULL;
2313 }
2314
2315 EXP_FUNC const char * STDCALL ssl_get_cert_subject_alt_dnsname(const SSL *ssl, int index)
2316 {
2317     printf(unsupported_str);
2318     return NULL;
2319 }
2320
2321 #endif  /* CONFIG_SSL_CERT_VERIFICATION */
2322
2323 #endif /* CONFIG_BINDINGS */
2324