joey shelton / LED_Demo

Dependencies:   MAX44000 PWM_Tone_Library nexpaq_mdk

Fork of LED_Demo by Maxim nexpaq

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers tls1.c Source File

tls1.c

00001 /*
00002  * Copyright (c) 2007, Cameron Rich
00003  * 
00004  * All rights reserved.
00005  * 
00006  * Redistribution and use in source and binary forms, with or without 
00007  * modification, are permitted provided that the following conditions are met:
00008  *
00009  * * Redistributions of source code must retain the above copyright notice, 
00010  *   this list of conditions and the following disclaimer.
00011  * * Redistributions in binary form must reproduce the above copyright notice, 
00012  *   this list of conditions and the following disclaimer in the documentation 
00013  *   and/or other materials provided with the distribution.
00014  * * Neither the name of the axTLS project nor the names of its contributors 
00015  *   may be used to endorse or promote products derived from this software 
00016  *   without specific prior written permission.
00017  *
00018  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
00019  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
00020  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
00021  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
00022  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
00023  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
00024  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
00025  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
00026  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
00027  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
00028  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00029  */
00030 
00031 /**
00032  * Common ssl/tlsv1 code to both the client and server implementations.
00033  */
00034 
00035 
00036 #include <string.h>
00037 #include <stdlib.h>
00038 #include <stdio.h>
00039 #include <stdarg.h>
00040 #include <errno.h>
00041 
00042 
00043 
00044 #include "lwip/sockets.h"
00045 #include "os_port.h"
00046 #include "ssl.h"
00047 #include "arch.h"
00048 
00049 
00050 /* The session expiry time */
00051 #define SSL_EXPIRY_TIME     (CONFIG_SSL_EXPIRY_TIME*3600)
00052 
00053 static const uint8_t g_hello_request[] = { HS_HELLO_REQUEST, 0, 0, 0 };
00054 static const uint8_t g_chg_cipher_spec_pkt[] = { 1 };
00055 static const char * server_finished = "server finished";
00056 static const char * client_finished = "client finished";
00057 
00058 static int do_handshake(SSL *ssl, uint8_t *buf, int read_len);
00059 static int set_key_block(SSL *ssl, int is_write);
00060 static int verify_digest(SSL *ssl, int mode, const uint8_t *buf, int read_len);
00061 static void *crypt_new(SSL *ssl, uint8_t *key, uint8_t *iv, int is_decrypt);
00062 static int send_raw_packet(SSL *ssl, uint8_t protocol);
00063 
00064 /**
00065  * The server will pick the cipher based on the order that the order that the
00066  * ciphers are listed. This order is defined at compile time.
00067  */
00068 #ifdef CONFIG_SSL_SKELETON_MODE
00069 const uint8_t ssl_prot_prefs[NUM_PROTOCOLS] = 
00070 { SSL_RC4_128_SHA };
00071 #else
00072 static void session_free(SSL_SESSION *ssl_sessions[], int sess_index);
00073 
00074 const uint8_t ssl_prot_prefs[NUM_PROTOCOLS] = 
00075 #ifdef CONFIG_SSL_PROT_LOW                  /* low security, fast speed */
00076 { SSL_RC4_128_SHA, SSL_AES128_SHA, SSL_AES256_SHA, SSL_RC4_128_MD5 };
00077 #elif CONFIG_SSL_PROT_MEDIUM                /* medium security, medium speed */
00078 { SSL_AES128_SHA, SSL_AES256_SHA, SSL_RC4_128_SHA, SSL_RC4_128_MD5 };    
00079 #else /* CONFIG_SSL_PROT_HIGH */            /* high security, low speed */
00080 { SSL_AES256_SHA, SSL_AES128_SHA, SSL_RC4_128_SHA, SSL_RC4_128_MD5 };
00081 #endif
00082 #endif /* CONFIG_SSL_SKELETON_MODE */
00083 
00084 /**
00085  * The cipher map containing all the essentials for each cipher.
00086  */
00087 #ifdef CONFIG_SSL_SKELETON_MODE
00088 static const cipher_info_t cipher_info[NUM_PROTOCOLS] = 
00089 {
00090     {   /* RC4-SHA */
00091         SSL_RC4_128_SHA,                /* RC4-SHA */
00092         16,                             /* key size */
00093         0,                              /* iv size */ 
00094         2*(SHA1_SIZE+16),               /* key block size */
00095         0,                              /* no padding */
00096         SHA1_SIZE,                      /* digest size */
00097         hmac_sha1,                      /* hmac algorithm */
00098         (crypt_func)RC4_crypt,          /* encrypt */
00099         (crypt_func)RC4_crypt           /* decrypt */
00100     },
00101 };
00102 #else
00103 static const cipher_info_t cipher_info[NUM_PROTOCOLS] = 
00104 {
00105     {   /* AES128-SHA */
00106         SSL_AES128_SHA,                 /* AES128-SHA */
00107         16,                             /* key size */
00108         16,                             /* iv size */ 
00109         2*(SHA1_SIZE+16+16),            /* key block size */
00110         16,                             /* block padding size */
00111         SHA1_SIZE,                      /* digest size */
00112         hmac_sha1,                      /* hmac algorithm */
00113         (crypt_func)AES_cbc_encrypt,    /* encrypt */
00114         (crypt_func)AES_cbc_decrypt     /* decrypt */
00115     },
00116     {   /* AES256-SHA */
00117         SSL_AES256_SHA,                 /* AES256-SHA */
00118         32,                             /* key size */
00119         16,                             /* iv size */ 
00120         2*(SHA1_SIZE+32+16),            /* key block size */
00121         16,                             /* block padding size */
00122         SHA1_SIZE,                      /* digest size */
00123         hmac_sha1,                      /* hmac algorithm */
00124         (crypt_func)AES_cbc_encrypt,    /* encrypt */
00125         (crypt_func)AES_cbc_decrypt     /* decrypt */
00126     },       
00127     {   /* RC4-SHA */
00128         SSL_RC4_128_SHA,                /* RC4-SHA */
00129         16,                             /* key size */
00130         0,                              /* iv size */ 
00131         2*(SHA1_SIZE+16),               /* key block size */
00132         0,                              /* no padding */
00133         SHA1_SIZE,                      /* digest size */
00134         hmac_sha1,                      /* hmac algorithm */
00135         (crypt_func)RC4_crypt,          /* encrypt */
00136         (crypt_func)RC4_crypt           /* decrypt */
00137     },
00138     /*
00139      * This protocol is from SSLv2 days and is unlikely to be used - but was
00140      * useful for testing different possible digest algorithms.
00141      */
00142     {   /* RC4-MD5 */
00143         SSL_RC4_128_MD5,                /* RC4-MD5 */
00144         16,                             /* key size */
00145         0,                              /* iv size */ 
00146         2*(MD5_SIZE+16),                /* key block size */
00147         0,                              /* no padding */
00148         MD5_SIZE,                       /* digest size */
00149         hmac_md5,                       /* hmac algorithm */
00150         (crypt_func)RC4_crypt,          /* encrypt */
00151         (crypt_func)RC4_crypt           /* decrypt */
00152     },
00153 };
00154 #endif
00155 
00156 static void prf(const uint8_t *sec, int sec_len, uint8_t *seed, int seed_len,
00157         uint8_t *out, int olen);
00158 static const cipher_info_t *get_cipher_info(uint8_t cipher);
00159 static void increment_read_sequence(SSL *ssl);
00160 static void increment_write_sequence(SSL *ssl);
00161 static void add_hmac_digest(SSL *ssl, int snd, uint8_t *hmac_header,
00162         const uint8_t *buf, int buf_len, uint8_t *hmac_buf);
00163 
00164 /* win32 VC6.0 doesn't have variadic macros */
00165 #if defined(WIN32) && !defined(CONFIG_SSL_FULL_MODE)
00166 void DISPLAY_BYTES(SSL *ssl, const char *format, 
00167         const uint8_t *data, int size, ...) {}
00168 #endif
00169 
00170 /**
00171  * Establish a new client/server context.
00172  */
00173 EXP_FUNC SSL_CTX *STDCALL ssl_ctx_new(SSL_CTX *ssl_ctx, uint32_t options, int num_sessions)
00174 {
00175     ssl_ctx->options = options;
00176     RNG_initialize();
00177 
00178     if (load_key_certs(ssl_ctx) < 0)
00179     {
00180         printf("error loading key certs\r\n");
00181         //free(ssl_ctx);  /* can't load our key/certificate pair, so die */
00182         return NULL;
00183     }
00184 
00185 #ifndef CONFIG_SSL_SKELETON_MODE
00186     ssl_ctx->num_sessions = num_sessions;
00187 #endif
00188 
00189     SSL_CTX_MUTEX_INIT(ssl_ctx->mutex);
00190 
00191 #ifndef CONFIG_SSL_SKELETON_MODE
00192     if (num_sessions)
00193     {
00194         ssl_ctx->ssl_sessions = (SSL_SESSION **)
00195                         calloc(1, num_sessions*sizeof(SSL_SESSION *));
00196     }
00197 #endif
00198 
00199     return ssl_ctx;
00200 }
00201 
00202 /*
00203  * Remove a client/server context.
00204  */
00205 EXP_FUNC void STDCALL ssl_ctx_free(SSL_CTX *ssl_ctx)
00206 {
00207     SSL *ssl;
00208     int i;
00209 
00210     if (ssl_ctx == NULL)
00211         return;
00212 
00213     ssl = ssl_ctx->head;
00214 
00215     /* clear out all the ssl entries */
00216     while (ssl)
00217     {
00218         SSL *next = ssl->next;
00219         ssl_free(ssl);
00220         ssl = next;
00221     }
00222 
00223 #ifndef CONFIG_SSL_SKELETON_MODE
00224     /* clear out all the sessions */
00225     for (i = 0; i < ssl_ctx->num_sessions; i++)
00226         session_free(ssl_ctx->ssl_sessions, i);
00227 
00228     free(ssl_ctx->ssl_sessions);
00229 #endif
00230 
00231     i = 0;
00232     //while (i < CONFIG_SSL_MAX_CERTS && ssl_ctx->certs[i].buf)
00233     {
00234         //free(ssl_ctx->certs[i].buf);
00235         //ssl_ctx->certs[i++].buf = NULL;
00236     }
00237 
00238 #ifdef CONFIG_SSL_CERT_VERIFICATION
00239     remove_ca_certs(ssl_ctx->ca_cert_ctx);
00240 #endif
00241     ssl_ctx->chain_length = 0;
00242     SSL_CTX_MUTEX_DESTROY(ssl_ctx->mutex);
00243     RSA_free(ssl_ctx->rsa_ctx);
00244     RNG_terminate();
00245     //free(ssl_ctx);
00246 }
00247 
00248 /*
00249  * Free any used resources used by this connection.
00250  */
00251 EXP_FUNC void STDCALL ssl_free(SSL *ssl)
00252 {
00253     SSL_CTX *ssl_ctx;
00254 
00255     if (ssl == NULL)        /* just ignore null pointers */
00256         return;
00257 
00258     /* only notify if we weren't notified first */
00259     /* spec says we must notify when we are dying */
00260     if (!IS_SET_SSL_FLAG(SSL_SENT_CLOSE_NOTIFY))
00261       send_alert(ssl, SSL_ALERT_CLOSE_NOTIFY);
00262 
00263     ssl_ctx = ssl->ssl_ctx;
00264 
00265     SSL_CTX_LOCK(ssl_ctx->mutex);
00266 
00267     /* adjust the server SSL list */
00268     if (ssl->prev)
00269         ssl->prev->next = ssl->next;
00270     else
00271         ssl_ctx->head = ssl->next;
00272 
00273     if (ssl->next)
00274         ssl->next->prev = ssl->prev;
00275     else
00276         ssl_ctx->tail = ssl->prev;
00277 
00278     SSL_CTX_UNLOCK(ssl_ctx->mutex);
00279 
00280     /* may already be free - but be sure */
00281     free(ssl->encrypt_ctx);
00282     free(ssl->decrypt_ctx);
00283     disposable_free(ssl);
00284     
00285 #ifdef CONFIG_SSL_CERT_VERIFICATION
00286     x509_free(ssl->x509_ctx);
00287 #endif
00288     //free(ssl->ssl_ctx);
00289     //free(ssl);
00290 }
00291 
00292 /*
00293  * Write application data to the client
00294  */
00295 EXP_FUNC int STDCALL ssl_write(SSL *ssl, const uint8_t *out_data, int out_len)
00296 {
00297     int n = out_len, nw, i, tot = 0;
00298 
00299     /* maximum size of a TLS packet is around 16kB, so fragment */
00300     do 
00301     {
00302         nw = n;
00303 
00304         if (nw > RT_MAX_PLAIN_LENGTH)    /* fragment if necessary */
00305             nw = RT_MAX_PLAIN_LENGTH;
00306 
00307         if ((i = send_packet(ssl, PT_APP_PROTOCOL_DATA, 
00308                                             &out_data[tot], nw)) <= 0)
00309         {
00310             out_len = i;    /* an error */
00311             break;
00312         }
00313 
00314         tot += i;
00315         n -= i;
00316     } while (n > 0);
00317 
00318     return out_len;
00319 }
00320 
00321 /**
00322  * Add a certificate to the certificate chain.
00323  */
00324 int add_cert(SSL_CTX *ssl_ctx, const uint8_t *buf, int len)
00325 {
00326     int ret = SSL_ERROR_NO_CERT_DEFINED, i = 0;
00327     SSL_CERT *ssl_cert;
00328     X509_CTX *cert = NULL;
00329     int offset;
00330 
00331     while (ssl_ctx->certs[i].buf && i < CONFIG_SSL_MAX_CERTS) 
00332         i++;
00333 
00334     if (i == CONFIG_SSL_MAX_CERTS) /* too many certs */
00335     {
00336 #ifdef CONFIG_SSL_FULL_MODE
00337         printf("Error: maximum number of certs added (%d) - change of "
00338                 "compile-time configuration required\n",
00339                 CONFIG_SSL_MAX_CERTS);
00340 #endif
00341         goto error;
00342     }
00343 
00344     if ((ret = x509_new(buf, &offset, &cert)))
00345         goto error;
00346 
00347 #if defined (CONFIG_SSL_FULL_MODE)
00348     if (ssl_ctx->options & SSL_DISPLAY_CERTS)
00349         x509_print(cert, NULL);
00350 #endif
00351 
00352     ssl_cert = &ssl_ctx->certs[i];
00353     ssl_cert->size = len;
00354     ssl_cert->buf = buf;
00355     ssl_ctx->chain_length++;
00356     len -= offset;
00357     ret = SSL_OK;           /* ok so far */
00358 
00359     /* recurse? */
00360     if (len > 0)
00361     {
00362         ret = add_cert(ssl_ctx, &buf[offset], len);
00363     }
00364 
00365 error:
00366     x509_free(cert);        /* don't need anymore */
00367     return ret;
00368 }
00369 
00370 #ifdef CONFIG_SSL_CERT_VERIFICATION
00371 /**
00372  * Add a certificate authority.
00373  */
00374 int add_cert_auth(SSL_CTX *ssl_ctx, const uint8_t *buf, int len)
00375 {
00376     int ret = SSL_OK; /* ignore errors for now */
00377     int i = 0;
00378     CA_CERT_CTX *ca_cert_ctx;
00379 
00380     if (ssl_ctx->ca_cert_ctx == NULL)
00381         ssl_ctx->ca_cert_ctx = (CA_CERT_CTX *)calloc(1, sizeof(CA_CERT_CTX));
00382 
00383     ca_cert_ctx = ssl_ctx->ca_cert_ctx;
00384 
00385     while (i < CONFIG_X509_MAX_CA_CERTS && ca_cert_ctx->cert[i]) 
00386         i++;
00387 
00388     while (len > 0)
00389     {
00390         int offset;
00391         if (i >= CONFIG_X509_MAX_CA_CERTS)
00392         {
00393 #ifdef CONFIG_SSL_FULL_MODE
00394             printf("Error: maximum number of CA certs added (%d) - change of "
00395                     "compile-time configuration required\n", 
00396                     CONFIG_X509_MAX_CA_CERTS);
00397 #endif
00398             break;
00399         }
00400 
00401 
00402         /* ignore the return code */
00403         if (x509_new(buf, &offset, &ca_cert_ctx->cert[i]) == X509_OK)
00404         {
00405 #if defined (CONFIG_SSL_FULL_MODE)
00406             if (ssl_ctx->options & SSL_DISPLAY_CERTS)
00407                 x509_print(ca_cert_ctx->cert[i], NULL);
00408 #endif
00409         }
00410 
00411         i++;
00412         len -= offset;
00413     }
00414 
00415     return ret;
00416 }
00417 
00418 /*
00419  * Retrieve an X.509 distinguished name component
00420  */
00421 EXP_FUNC const char * STDCALL ssl_get_cert_dn(const SSL *ssl, int component)
00422 {
00423     if (ssl->x509_ctx == NULL)
00424         return NULL;
00425 
00426     switch (component)
00427     {
00428         case SSL_X509_CERT_COMMON_NAME:
00429             return ssl->x509_ctx->cert_dn[X509_COMMON_NAME];
00430 
00431         case SSL_X509_CERT_ORGANIZATION:
00432             return ssl->x509_ctx->cert_dn[X509_ORGANIZATION];
00433 
00434         case SSL_X509_CERT_ORGANIZATIONAL_NAME:       
00435             return ssl->x509_ctx->cert_dn[X509_ORGANIZATIONAL_UNIT];
00436 
00437         case SSL_X509_CA_CERT_COMMON_NAME:
00438             return ssl->x509_ctx->ca_cert_dn[X509_COMMON_NAME];
00439 
00440         case SSL_X509_CA_CERT_ORGANIZATION:
00441             return ssl->x509_ctx->ca_cert_dn[X509_ORGANIZATION];
00442 
00443         case SSL_X509_CA_CERT_ORGANIZATIONAL_NAME:       
00444             return ssl->x509_ctx->ca_cert_dn[X509_ORGANIZATIONAL_UNIT];
00445 
00446         default:
00447             return NULL;
00448     }
00449 }
00450 
00451 /*
00452  * Retrieve a "Subject Alternative Name" from a v3 certificate
00453  */
00454 EXP_FUNC const char * STDCALL ssl_get_cert_subject_alt_dnsname(const SSL *ssl,
00455         int dnsindex)
00456 {
00457     int i;
00458 
00459     if (ssl->x509_ctx == NULL || ssl->x509_ctx->subject_alt_dnsnames == NULL)
00460         return NULL;
00461 
00462     for (i = 0; i < dnsindex; ++i)
00463     {
00464         if (ssl->x509_ctx->subject_alt_dnsnames[i] == NULL)
00465             return NULL;
00466     }
00467 
00468     return ssl->x509_ctx->subject_alt_dnsnames[dnsindex];
00469 }
00470 
00471 #endif /* CONFIG_SSL_CERT_VERIFICATION */
00472 
00473 /*
00474  * Find an ssl object based on the client's file descriptor.
00475  */
00476 EXP_FUNC SSL * STDCALL ssl_find(SSL_CTX *ssl_ctx, int client_fd)
00477 {
00478     SSL *ssl;
00479 
00480     SSL_CTX_LOCK(ssl_ctx->mutex);
00481     ssl = ssl_ctx->head;
00482 
00483     /* search through all the ssl entries */
00484     while (ssl)
00485     {
00486         if (ssl->client_fd == client_fd)
00487         {
00488             SSL_CTX_UNLOCK(ssl_ctx->mutex);
00489             return ssl;
00490         }
00491 
00492         ssl = ssl->next;
00493     }
00494 
00495     SSL_CTX_UNLOCK(ssl_ctx->mutex);
00496     return NULL;
00497 }
00498 
00499 /*
00500  * Force the client to perform its handshake again.
00501  */
00502 EXP_FUNC int STDCALL ssl_renegotiate(SSL *ssl)
00503 {
00504     int ret = SSL_OK;
00505 
00506     disposable_new(ssl);
00507 #ifdef CONFIG_SSL_ENABLE_CLIENT
00508     if (IS_SET_SSL_FLAG(SSL_IS_CLIENT))
00509     {
00510         ret = do_client_connect(ssl);
00511     }
00512     else
00513 #endif
00514     {
00515         send_packet(ssl, PT_HANDSHAKE_PROTOCOL, 
00516                 g_hello_request, sizeof(g_hello_request));
00517         SET_SSL_FLAG(SSL_NEED_RECORD);
00518     }
00519 
00520     return ret;
00521 }
00522 
00523 /**
00524  * @brief Get what we need for key info.
00525  * @param cipher    [in]    The cipher information we are after
00526  * @param key_size  [out]   The key size for the cipher
00527  * @param iv_size   [out]   The iv size for the cipher
00528  * @return  The amount of key information we need.
00529  */
00530 static const cipher_info_t *get_cipher_info(uint8_t cipher)
00531 {
00532     int i;
00533 
00534     for (i = 0; i < NUM_PROTOCOLS; i++)
00535     {
00536         if (cipher_info[i].cipher == cipher)
00537         {
00538             return &cipher_info[i];
00539         }
00540     }
00541 
00542     return NULL;  /* error */
00543 }
00544 
00545 /*
00546  * Get a new ssl context for a new connection.
00547  */
00548 SSL *ssl_new(SSL *ssl, int client_fd)
00549 {
00550     SSL_CTX* ssl_ctx = ssl->ssl_ctx;
00551     ssl->need_bytes = SSL_RECORD_SIZE;      /* need a record */
00552     ssl->client_fd = 0;
00553     ssl->flag = SSL_NEED_RECORD;
00554     ssl->bm_data = ssl->bm_all_data + BM_RECORD_OFFSET; 
00555     ssl->bm_read_index = 0;
00556     ssl->hs_status = SSL_NOT_OK;            /* not connected */
00557 #ifdef CONFIG_ENABLE_VERIFICATION
00558     ssl->ca_cert_ctx = ssl_ctx->ca_cert_ctx;
00559 #endif
00560     disposable_new(ssl);
00561 
00562     /* a bit hacky but saves a few bytes of memory */
00563     ssl->flag |= ssl_ctx->options;
00564     SSL_CTX_LOCK(ssl_ctx->mutex);
00565 
00566     if (ssl_ctx->head == NULL)
00567     {
00568         ssl_ctx->head = ssl;
00569         ssl_ctx->tail = ssl;
00570     }
00571     else
00572     {
00573         ssl->prev = ssl_ctx->tail;
00574         ssl_ctx->tail->next = ssl;
00575         ssl_ctx->tail = ssl;
00576     }
00577     ssl->encrypt_ctx = NULL;
00578     ssl->decrypt_ctx = NULL;
00579     
00580     SSL_CTX_UNLOCK(ssl_ctx->mutex);
00581     return ssl;
00582 }
00583 
00584 /*
00585  * Add a private key to a context.
00586  */
00587 int add_private_key(SSL_CTX *ssl_ctx, SSLObjLoader *ssl_obj)
00588 {
00589     int ret = SSL_OK;
00590 
00591     /* get the private key details */
00592     if (asn1_get_private_key(ssl_obj->buf, ssl_obj->len, &ssl_ctx->rsa_ctx))
00593     {
00594         ret = SSL_ERROR_INVALID_KEY;
00595         goto error;
00596     }
00597 
00598 error:
00599     return ret;
00600 }
00601 
00602 /** 
00603  * Increment the read sequence number (as a 64 bit endian indepenent #)
00604  */     
00605 static void increment_read_sequence(SSL *ssl)
00606 {
00607     int i;
00608 
00609     for (i = 7; i >= 0; i--) 
00610     {       
00611         if (++ssl->read_sequence[i])
00612             break;
00613     }
00614 }
00615             
00616 /**
00617  * Increment the read sequence number (as a 64 bit endian indepenent #)
00618  */      
00619 static void increment_write_sequence(SSL *ssl)
00620 {        
00621     int i;                  
00622          
00623     for (i = 7; i >= 0; i--)
00624     {                       
00625         if (++ssl->write_sequence[i])
00626             break;
00627     }                       
00628 }
00629 
00630 /**
00631  * Work out the HMAC digest in a packet.
00632  */
00633 static void add_hmac_digest(SSL *ssl, int mode, uint8_t *hmac_header,
00634         const uint8_t *buf, int buf_len, uint8_t *hmac_buf)
00635 {
00636     int hmac_len = buf_len + 8 + SSL_RECORD_SIZE;
00637     uint8_t *t_buf = (uint8_t *)alloca(hmac_len+10);
00638 
00639     memcpy(t_buf, (mode == SSL_SERVER_WRITE || mode == SSL_CLIENT_WRITE) ? 
00640                     ssl->write_sequence : ssl->read_sequence, 8);
00641     memcpy(&t_buf[8], hmac_header, SSL_RECORD_SIZE);
00642     memcpy(&t_buf[8+SSL_RECORD_SIZE], buf, buf_len);
00643 
00644     ssl->cipher_info->hmac(t_buf, hmac_len, 
00645             (mode == SSL_SERVER_WRITE || mode == SSL_CLIENT_READ) ? 
00646                 ssl->server_mac : ssl->client_mac, 
00647             ssl->cipher_info->digest_size, hmac_buf);
00648 
00649 #if 0
00650     print_blob("record", hmac_header, SSL_RECORD_SIZE);
00651     print_blob("buf", buf, buf_len);
00652     if (mode == SSL_SERVER_WRITE || mode == SSL_CLIENT_WRITE)
00653     {
00654         print_blob("write seq", ssl->write_sequence, 8);
00655     }
00656     else
00657     {
00658         print_blob("read seq", ssl->read_sequence, 8);
00659     }
00660 
00661     if (mode == SSL_SERVER_WRITE || mode == SSL_CLIENT_READ)
00662     {
00663         print_blob("server mac", 
00664                 ssl->server_mac, ssl->cipher_info->digest_size);
00665     }
00666     else
00667     {
00668         print_blob("client mac", 
00669                 ssl->client_mac, ssl->cipher_info->digest_size);
00670     }
00671     print_blob("hmac", hmac_buf, SHA1_SIZE);
00672 #endif
00673 }
00674 
00675 /**
00676  * Verify that the digest of a packet is correct.
00677  */
00678 static int verify_digest(SSL *ssl, int mode, const uint8_t *buf, int read_len)
00679 {   
00680     uint8_t hmac_buf[SHA1_SIZE];
00681     int hmac_offset;
00682    
00683     if (ssl->cipher_info->padding_size)
00684     {
00685         int last_blk_size = buf[read_len-1], i;
00686         hmac_offset = read_len-last_blk_size-ssl->cipher_info->digest_size-1;
00687 
00688         /* guard against a timing attack - make sure we do the digest */
00689         if (hmac_offset < 0)
00690         {
00691             hmac_offset = 0;
00692         }
00693         else
00694         {
00695             /* already looked at last byte */
00696             for (i = 1; i < last_blk_size; i++)
00697             {
00698                 if (buf[read_len-i] != last_blk_size)
00699                 {
00700                     hmac_offset = 0;
00701                     break;
00702                 }
00703             }
00704         }
00705     }
00706     else /* stream cipher */
00707     {
00708         hmac_offset = read_len - ssl->cipher_info->digest_size;
00709 
00710         if (hmac_offset < 0)
00711         {
00712             hmac_offset = 0;
00713         }
00714     }
00715 
00716     /* sanity check the offset */
00717     ssl->hmac_header[3] = hmac_offset >> 8;      /* insert size */
00718     ssl->hmac_header[4] = hmac_offset & 0xff;
00719     add_hmac_digest(ssl, mode, ssl->hmac_header, buf, hmac_offset, hmac_buf);
00720 
00721     if (memcmp(hmac_buf, &buf[hmac_offset], ssl->cipher_info->digest_size))
00722     {
00723         return SSL_ERROR_INVALID_HMAC;
00724     }
00725 
00726     return hmac_offset;
00727 }
00728 
00729 /**
00730  * Add a packet to the end of our sent and received packets, so that we may use
00731  * it to calculate the hash at the end.
00732  */
00733 void add_packet(SSL *ssl, const uint8_t *pkt, int len)
00734 {
00735     MD5_Update(&ssl->dc->md5_ctx, pkt, len);
00736     SHA1_Update(&ssl->dc->sha1_ctx, pkt, len);
00737 }
00738 
00739 /**
00740  * Work out the MD5 PRF.
00741  */
00742 static void p_hash_md5(const uint8_t *sec, int sec_len, 
00743         uint8_t *seed, int seed_len, uint8_t *out, int olen)
00744 {
00745     uint8_t a1[128];
00746 
00747     /* A(1) */
00748     hmac_md5(seed, seed_len, sec, sec_len, a1);
00749     memcpy(&a1[MD5_SIZE], seed, seed_len);
00750     hmac_md5(a1, MD5_SIZE+seed_len, sec, sec_len, out);
00751 
00752     while (olen > MD5_SIZE)
00753     {
00754         uint8_t a2[MD5_SIZE];
00755         out += MD5_SIZE;
00756         olen -= MD5_SIZE;
00757 
00758         /* A(N) */
00759         hmac_md5(a1, MD5_SIZE, sec, sec_len, a2);
00760         memcpy(a1, a2, MD5_SIZE);
00761 
00762         /* work out the actual hash */
00763         hmac_md5(a1, MD5_SIZE+seed_len, sec, sec_len, out);
00764     }
00765 }
00766 
00767 /**
00768  * Work out the SHA1 PRF.
00769  */
00770 static void p_hash_sha1(const uint8_t *sec, int sec_len, 
00771         uint8_t *seed, int seed_len, uint8_t *out, int olen)
00772 {
00773     uint8_t a1[128];
00774 
00775     /* A(1) */
00776     hmac_sha1(seed, seed_len, sec, sec_len, a1);
00777     memcpy(&a1[SHA1_SIZE], seed, seed_len);
00778     hmac_sha1(a1, SHA1_SIZE+seed_len, sec, sec_len, out);
00779 
00780     while (olen > SHA1_SIZE)
00781     {
00782         uint8_t a2[SHA1_SIZE];
00783         out += SHA1_SIZE;
00784         olen -= SHA1_SIZE;
00785 
00786         /* A(N) */
00787         hmac_sha1(a1, SHA1_SIZE, sec, sec_len, a2);
00788         memcpy(a1, a2, SHA1_SIZE);
00789 
00790         /* work out the actual hash */
00791         hmac_sha1(a1, SHA1_SIZE+seed_len, sec, sec_len, out);
00792     }
00793 }
00794 
00795 /**
00796  * Work out the PRF.
00797  */
00798 static void prf(const uint8_t *sec, int sec_len, uint8_t *seed, int seed_len,
00799         uint8_t *out, int olen)
00800 {
00801     int len, i;
00802     const uint8_t *S1, *S2;
00803     uint8_t xbuf[256]; /* needs to be > the amount of key data */
00804     uint8_t ybuf[256]; /* needs to be > the amount of key data */
00805 
00806     len = sec_len/2;
00807     S1 = sec;
00808     S2 = &sec[len];
00809     len += (sec_len & 1); /* add for odd, make longer */
00810 
00811     p_hash_md5(S1, len, seed, seed_len, xbuf, olen);
00812     p_hash_sha1(S2, len, seed, seed_len, ybuf, olen);
00813 
00814     for (i = 0; i < olen; i++)
00815         out[i] = xbuf[i] ^ ybuf[i];
00816 }
00817 
00818 /**
00819  * Generate a master secret based on the client/server random data and the
00820  * premaster secret.
00821  */
00822 void generate_master_secret(SSL *ssl, const uint8_t *premaster_secret)
00823 {
00824     uint8_t buf[128];   /* needs to be > 13+32+32 in size */
00825     strcpy((char *)buf, "master secret");
00826     memcpy(&buf[13], ssl->dc->client_random, SSL_RANDOM_SIZE);
00827     memcpy(&buf[45], ssl->dc->server_random, SSL_RANDOM_SIZE);
00828     prf(premaster_secret, SSL_SECRET_SIZE, buf, 77, ssl->dc->master_secret,
00829             SSL_SECRET_SIZE);
00830 }
00831 
00832 /**
00833  * Generate a 'random' blob of data used for the generation of keys.
00834  */
00835 static void generate_key_block(uint8_t *client_random, uint8_t *server_random,
00836         uint8_t *master_secret, uint8_t *key_block, int key_block_size)
00837 {
00838     uint8_t buf[128];
00839     strcpy((char *)buf, "key expansion");
00840     memcpy(&buf[13], server_random, SSL_RANDOM_SIZE);
00841     memcpy(&buf[45], client_random, SSL_RANDOM_SIZE);
00842     prf(master_secret, SSL_SECRET_SIZE, buf, 77, key_block, key_block_size);
00843 }
00844 
00845 /** 
00846  * Calculate the digest used in the finished message. This function also
00847  * doubles up as a certificate verify function.
00848  */
00849 void finished_digest(SSL *ssl, const char *label, uint8_t *digest)
00850 {
00851     uint8_t mac_buf[128]; 
00852     uint8_t *q = mac_buf;
00853     MD5_CTX md5_ctx = ssl->dc->md5_ctx;
00854     SHA1_CTX sha1_ctx = ssl->dc->sha1_ctx;
00855 
00856     if (label)
00857     {
00858         strcpy((char *)q, label);
00859         q += strlen(label);
00860     }
00861 
00862     MD5_Final(q, &md5_ctx);
00863     q += MD5_SIZE;
00864     
00865     SHA1_Final(q, &sha1_ctx);
00866     q += SHA1_SIZE;
00867 
00868     if (label)
00869     {
00870         prf(ssl->dc->master_secret, SSL_SECRET_SIZE, mac_buf, (int)(q-mac_buf),
00871             digest, SSL_FINISHED_HASH_SIZE);
00872     }
00873     else    /* for use in a certificate verify */
00874     {
00875         memcpy(digest, mac_buf, MD5_SIZE + SHA1_SIZE);
00876     }
00877 
00878 #if 0
00879     printf("label: %s\r\n", label);
00880     print_blob("master secret", ssl->dc->master_secret, 48);
00881     print_blob("mac_buf", mac_buf, q-mac_buf);
00882     print_blob("finished digest", digest, SSL_FINISHED_HASH_SIZE);
00883 #endif
00884 }   
00885     
00886 /**
00887  * Retrieve (and initialise) the context of a cipher.
00888  */
00889 static void *crypt_new(SSL *ssl, uint8_t *key, uint8_t *iv, int is_decrypt)
00890 {
00891     switch (ssl->cipher)
00892     {
00893 #ifndef CONFIG_SSL_SKELETON_MODE
00894         case SSL_AES128_SHA:
00895             {
00896                 AES_CTX *aes_ctx = (AES_CTX *)malloc(sizeof(AES_CTX));
00897                 AES_set_key(aes_ctx, key, iv, AES_MODE_128);
00898 
00899                 if (is_decrypt)
00900                 {
00901                     AES_convert_key(aes_ctx);
00902                 }
00903 
00904                 return (void *)aes_ctx;
00905             }
00906 
00907         case SSL_AES256_SHA:
00908             {
00909                 AES_CTX *aes_ctx = (AES_CTX *)malloc(sizeof(AES_CTX));
00910                 AES_set_key(aes_ctx, key, iv, AES_MODE_256);
00911 
00912                 if (is_decrypt)
00913                 {
00914                     AES_convert_key(aes_ctx);
00915                 }
00916 
00917                 return (void *)aes_ctx;
00918             }
00919 
00920         case SSL_RC4_128_MD5:
00921 #endif
00922         case SSL_RC4_128_SHA:
00923             {
00924                 RC4_CTX *rc4_ctx = (RC4_CTX *)malloc(sizeof(RC4_CTX));
00925                 RC4_setup(rc4_ctx, key, 16);
00926                 return (void *)rc4_ctx;
00927             }
00928     }
00929 
00930     return NULL;    /* its all gone wrong */
00931 }
00932 
00933 
00934 /**
00935  * Send a packet over the socket.
00936  */
00937 static int send_raw_packet(SSL *ssl, uint8_t protocol)
00938 {   
00939     uint8_t *rec_buf = ssl->bm_all_data;
00940     int pkt_size = SSL_RECORD_SIZE+ssl->bm_index;
00941     int sent = 0;
00942     int ret = SSL_OK;
00943     rec_buf[0] = protocol;
00944     rec_buf[1] = 0x03;      /* version = 3.1 or higher */
00945     rec_buf[2] = ssl->version & 0x0f;
00946     rec_buf[3] = ssl->bm_index >> 8;
00947     rec_buf[4] = ssl->bm_index & 0xff;
00948 
00949     DISPLAY_BYTES(ssl, "sending %d bytes", ssl->bm_all_data, 
00950                              pkt_size, pkt_size);
00951 
00952 
00953     
00954     while (sent < pkt_size)
00955     {
00956         ret = SOCKET_WRITE(ssl->client_fd, 
00957                         &ssl->bm_all_data[sent], pkt_size-sent);
00958         if (ret >= 0)
00959             sent += ret;
00960         else
00961         {
00962 
00963 #ifdef WIN32
00964             if (GetLastError() != WSAEWOULDBLOCK)
00965 #else
00966             if (errno != EAGAIN && errno != EWOULDBLOCK)
00967 #endif
00968                 return SSL_ERROR_CONN_LOST;
00969         }
00970 
00971         /* keep going until the write buffer has some space */
00972         if (sent != pkt_size)
00973         {
00974             fd_set wfds;
00975             FD_ZERO(&wfds);
00976             FD_SET(ssl->client_fd, &wfds);
00977 
00978             /* block and wait for it */
00979             if (lwip_select(FD_SETSIZE, NULL, &wfds, NULL, NULL) < 0)
00980                 return SSL_ERROR_CONN_LOST;
00981             
00982         }
00983     }
00984     fd_set wfds;
00985     FD_ZERO(&wfds);
00986     FD_SET(ssl->client_fd, &wfds);
00987     
00988     /* block and wait for it */
00989     if (lwip_select(FD_SETSIZE, NULL, &wfds, NULL, NULL) < 0)
00990         return SSL_ERROR_CONN_LOST;
00991             
00992     SET_SSL_FLAG(SSL_NEED_RECORD);  /* reset for next time */
00993     ssl->bm_index = 0;
00994 
00995     if (protocol != PT_APP_PROTOCOL_DATA)  
00996     {
00997         /* always return SSL_OK during handshake */   
00998         ret = SSL_OK;
00999     }
01000 
01001     return ret;
01002 }
01003 
01004 /**
01005  * Send an encrypted packet with padding bytes if necessary.
01006  */
01007 int send_packet(SSL *ssl, uint8_t protocol, const uint8_t *in, int length)
01008 {
01009     int ret, msg_length = 0;
01010 
01011     /* if our state is bad, don't bother */
01012     if (ssl->hs_status == SSL_ERROR_DEAD)
01013         return SSL_ERROR_CONN_LOST;
01014 
01015     if (in) /* has the buffer already been initialised? */
01016     {
01017         memcpy(ssl->bm_data, in, length);
01018     }
01019 
01020     msg_length += length;
01021 
01022     if (IS_SET_SSL_FLAG(SSL_TX_ENCRYPTED))
01023     {
01024         int mode = IS_SET_SSL_FLAG(SSL_IS_CLIENT) ? 
01025                             SSL_CLIENT_WRITE : SSL_SERVER_WRITE;
01026         uint8_t hmac_header[SSL_RECORD_SIZE] = 
01027         {
01028             protocol, 
01029             0x03, /* version = 3.1 or higher */
01030             ssl->version & 0x0f,
01031             msg_length >> 8,
01032             msg_length & 0xff 
01033         };
01034 
01035         if (protocol == PT_HANDSHAKE_PROTOCOL)
01036         {
01037             DISPLAY_STATE(ssl, 1, ssl->bm_data[0], 0);
01038 
01039             if (ssl->bm_data[0] != HS_HELLO_REQUEST)
01040             {
01041                 add_packet(ssl, ssl->bm_data, msg_length);
01042             }
01043         }
01044 
01045         /* add the packet digest */
01046         add_hmac_digest(ssl, mode, hmac_header, ssl->bm_data, msg_length, 
01047                                                 &ssl->bm_data[msg_length]);
01048         msg_length += ssl->cipher_info->digest_size;
01049 
01050         /* add padding? */
01051         if (ssl->cipher_info->padding_size)
01052         {
01053             int last_blk_size = msg_length%ssl->cipher_info->padding_size;
01054             int pad_bytes = ssl->cipher_info->padding_size - last_blk_size;
01055 
01056             /* ensure we always have at least 1 padding byte */
01057             if (pad_bytes == 0)
01058                 pad_bytes += ssl->cipher_info->padding_size;
01059 
01060             memset(&ssl->bm_data[msg_length], pad_bytes-1, pad_bytes);
01061             msg_length += pad_bytes;
01062         }
01063 
01064         DISPLAY_BYTES(ssl, "unencrypted write", ssl->bm_data, msg_length);
01065         increment_write_sequence(ssl);
01066 
01067         /* add the explicit IV for TLS1.1 */
01068         if (ssl->version >= SSL_PROTOCOL_VERSION1_1 &&
01069                         ssl->cipher_info->iv_size)
01070         {
01071             uint8_t iv_size = ssl->cipher_info->iv_size;
01072             uint8_t *t_buf = alloca(msg_length + iv_size);
01073             memcpy(t_buf + iv_size, ssl->bm_data, msg_length);
01074             get_random(iv_size, t_buf);
01075             msg_length += iv_size;
01076             memcpy(ssl->bm_data, t_buf, msg_length);
01077         }
01078 
01079         /* now encrypt the packet */
01080         ssl->cipher_info->encrypt(ssl->encrypt_ctx, ssl->bm_data, 
01081                                             ssl->bm_data, msg_length);
01082     }
01083     else if (protocol == PT_HANDSHAKE_PROTOCOL)
01084     {
01085         DISPLAY_STATE(ssl, 1, ssl->bm_data[0], 0);
01086 
01087         if (ssl->bm_data[0] != HS_HELLO_REQUEST)
01088         {
01089             add_packet(ssl, ssl->bm_data, length);
01090         }
01091     }
01092 
01093     ssl->bm_index = msg_length;
01094     if ((ret = send_raw_packet(ssl, protocol)) <= 0)
01095         return ret;
01096 
01097     return length;  /* just return what we wanted to send */
01098 }
01099 
01100 /**
01101  * Work out the cipher keys we are going to use for this session based on the
01102  * master secret.
01103  */
01104 static int set_key_block(SSL *ssl, int is_write)
01105 {
01106     const cipher_info_t *ciph_info = get_cipher_info(ssl->cipher);
01107     uint8_t *q;
01108     uint8_t client_key[32], server_key[32]; /* big enough for AES256 */
01109     uint8_t client_iv[16], server_iv[16];   /* big enough for AES128/256 */
01110     int is_client = IS_SET_SSL_FLAG(SSL_IS_CLIENT);
01111 
01112     if (ciph_info == NULL)
01113         return -1;
01114 
01115     uint8_t key_tmp[MAX_KEYBLOCK_SIZE] = {0};
01116     /* only do once in a handshake */
01117     if (memcmp(ssl->dc->key_block, key_tmp, MAX_KEYBLOCK_SIZE) == 0)
01118     {
01119 #if 0
01120         print_blob("client", ssl->dc->client_random, 32);
01121         print_blob("server", ssl->dc->server_random, 32);
01122         print_blob("master", ssl->dc->master_secret, SSL_SECRET_SIZE);
01123 #endif
01124         generate_key_block(ssl->dc->client_random, ssl->dc->server_random,
01125             ssl->dc->master_secret, ssl->dc->key_block, 
01126             ciph_info->key_block_size);
01127 #if 0
01128         print_blob("keyblock", ssl->dc->key_block, ciph_info->key_block_size);
01129 #endif
01130     }
01131 
01132     q = ssl->dc->key_block;
01133 
01134     if ((is_client && is_write) || (!is_client && !is_write))
01135     {
01136         memcpy(ssl->client_mac, q, ciph_info->digest_size);
01137     }
01138 
01139     q += ciph_info->digest_size;
01140 
01141     if ((!is_client && is_write) || (is_client && !is_write))
01142     {
01143         memcpy(ssl->server_mac, q, ciph_info->digest_size);
01144     }
01145 
01146     q += ciph_info->digest_size;
01147     memcpy(client_key, q, ciph_info->key_size);
01148     q += ciph_info->key_size;
01149     memcpy(server_key, q, ciph_info->key_size);
01150     q += ciph_info->key_size;
01151 
01152 #ifndef CONFIG_SSL_SKELETON_MODE 
01153     if (ciph_info->iv_size)    /* RC4 has no IV, AES does */
01154     {
01155         memcpy(client_iv, q, ciph_info->iv_size);
01156         q += ciph_info->iv_size;
01157         memcpy(server_iv, q, ciph_info->iv_size);
01158         q += ciph_info->iv_size;
01159     }
01160 #endif
01161 
01162     if( (is_write ? ssl->encrypt_ctx : ssl->decrypt_ctx) != NULL)
01163         free(is_write ? ssl->encrypt_ctx : ssl->decrypt_ctx);
01164 
01165     /* now initialise the ciphers */
01166     if (is_client)
01167     {
01168         finished_digest(ssl, server_finished, ssl->dc->final_finish_mac);
01169 
01170         if (is_write)
01171             ssl->encrypt_ctx = crypt_new(ssl, client_key, client_iv, 0);
01172         else
01173             ssl->decrypt_ctx = crypt_new(ssl, server_key, server_iv, 1);
01174     }
01175     else
01176     {
01177         finished_digest(ssl, client_finished, ssl->dc->final_finish_mac);
01178 
01179         if (is_write)
01180             ssl->encrypt_ctx = crypt_new(ssl, server_key, server_iv, 0);
01181         else
01182             ssl->decrypt_ctx = crypt_new(ssl, client_key, client_iv, 1);
01183     }
01184 
01185     ssl->cipher_info = ciph_info;
01186     return 0;
01187 }
01188 
01189 /** 
01190   * Blocking read 
01191   * data must be valid buffer of size length at least
01192   * length 
01193   */
01194 int basic_read2(SSL *ssl, uint8_t *data, uint32_t length)
01195 {
01196    // printf("basic_read2\n");
01197     if(data == NULL)
01198         return -1;
01199 
01200     int ret = 0;
01201     
01202     do
01203     {
01204         //printf("before_lwip_select\n");
01205         fd_set rfds;
01206         FD_ZERO(&rfds);
01207         FD_SET(ssl->client_fd, &rfds);
01208         
01209         /* block and wait for it */
01210         if (lwip_select(FD_SETSIZE, &rfds, NULL, NULL, NULL) < 0)
01211             return SSL_ERROR_CONN_LOST;
01212       //  printf("after_lwip_select\n");
01213 
01214         int read_len = SOCKET_READ(ssl->client_fd, &data[ret], length-ret);
01215       //  printf("read_len = %d\n", read_len);
01216 
01217         if (read_len < 0) 
01218         {
01219     
01220 #ifdef WIN32
01221             if (GetLastError() == WSAEWOULDBLOCK)
01222 #else
01223             if (errno == EAGAIN || errno == EWOULDBLOCK)
01224 #endif
01225                 continue;
01226         }
01227     
01228         /* connection has gone, so die */
01229         if (read_len <= 0)
01230         {
01231             printf("SSL_ERROR_CONN_LOST\n");
01232             ssl->hs_status = SSL_ERROR_DEAD;  /* make sure it stays dead */
01233             return SSL_ERROR_CONN_LOST;
01234         }
01235                 
01236         ret += read_len;
01237 
01238     }while(ret < length);
01239     DISPLAY_BYTES(ssl, "received %d bytes", data, ret, ret);
01240     return ret;
01241 }
01242 
01243 int read_record(SSL *ssl)
01244 {
01245     if(!IS_SET_SSL_FLAG(SSL_NEED_RECORD))
01246         return 0;
01247     uint8_t record[SSL_RECORD_SIZE];
01248     int ret = basic_read2(ssl, record, SSL_RECORD_SIZE);
01249     if(ret != SSL_RECORD_SIZE)
01250         return ret;
01251 
01252        /* check for sslv2 "client hello" */
01253     if (record[0] & 0x80 && record[2] == 1)
01254     {
01255 #ifdef CONFIG_SSL_ENABLE_V23_HANDSHAKE
01256         uint8_t version = (record[3] << 4) + record[4];
01257         DISPLAY_BYTES(ssl, "ssl2 record", record, 5);
01258 
01259         /* should be v3.1 (TLSv1) or better  */
01260         ssl->version = ssl->client_version = version;
01261 
01262         if (version > SSL_PROTOCOL_VERSION_MAX)
01263         {
01264             /* use client's version */
01265             ssl->version = SSL_PROTOCOL_VERSION_MAX;
01266         }
01267         else if (version < SSL_PROTOCOL_MIN_VERSION)  
01268         {
01269             ret = SSL_ERROR_INVALID_VERSION;
01270             ssl_display_error(ret);
01271             return ret;
01272         }
01273 
01274         add_packet(ssl, &record[2], 3);
01275         ret = process_sslv23_client_hello(ssl); 
01276 #else
01277         printf("Error: no SSLv23 handshaking allowed\n"); TTY_FLUSH();
01278         ret = SSL_ERROR_NOT_SUPPORTED;
01279 #endif
01280         return ret;
01281     }
01282 
01283     ssl->need_bytes = (record[3] << 8) + record[4];
01284 
01285 
01286     memcpy(ssl->hmac_header, record, 3);       /* store for hmac */
01287     ssl->record_type = record[0];
01288     CLR_SSL_FLAG(SSL_NEED_RECORD);
01289     return SSL_OK;
01290 }
01291 
01292 int basic_decrypt(SSL *ssl, uint8_t *buf, int len)
01293 {
01294    if (IS_SET_SSL_FLAG(SSL_RX_ENCRYPTED))
01295     {
01296         ssl->cipher_info->decrypt(ssl->decrypt_ctx, buf, buf, len);
01297 
01298         if (ssl->version >= SSL_PROTOCOL_VERSION1_1 &&
01299                         ssl->cipher_info->iv_size)
01300         {
01301             buf += ssl->cipher_info->iv_size;
01302             ssl->need_bytes -= ssl->cipher_info->iv_size;
01303         }
01304         if(ssl->record_type != PT_APP_PROTOCOL_DATA)
01305             len = verify_digest(ssl, 
01306                     IS_SET_SSL_FLAG(SSL_IS_CLIENT) ? SSL_CLIENT_READ : SSL_SERVER_READ, buf, len);
01307 
01308         /* does the hmac work? */
01309         if (ssl->need_bytes < 0)
01310         {
01311             return ssl->need_bytes;
01312         }
01313 
01314         DISPLAY_BYTES(ssl, "decrypted", buf, len);
01315         increment_read_sequence(ssl);
01316     }
01317     return len;
01318 }
01319 
01320 int ssl_read(SSL *ssl, uint8_t *in_data, int len)
01321 {
01322     if(len <= 0 || in_data == NULL)
01323         return 0;
01324    
01325     if(IS_SET_SSL_FLAG(SSL_NEED_RECORD))
01326     {
01327         read_record(ssl);
01328     }
01329    
01330     return process_data(ssl, in_data, len);
01331 }
01332 
01333 int process_data(SSL* ssl, uint8_t *in_data, int len)
01334 {
01335     /* The main part of the SSL packet */
01336     switch (ssl->record_type)
01337     {
01338         case PT_HANDSHAKE_PROTOCOL:
01339 
01340             if (ssl->dc != NULL)
01341             {
01342                 ssl->dc->bm_proc_index = 0;
01343                 int ret = do_handshake(ssl, NULL, 0);
01344                 SET_SSL_FLAG(SSL_NEED_RECORD);
01345                 return ret;
01346             }
01347             else /* no client renegotiation allowed */
01348             {
01349                 SET_SSL_FLAG(SSL_NEED_RECORD);
01350                 return SSL_ERROR_NO_CLIENT_RENOG;              
01351             }
01352 
01353         case PT_CHANGE_CIPHER_SPEC:
01354         
01355             if(basic_read2(ssl, ssl->bm_data, ssl->need_bytes) != ssl->need_bytes)
01356                 return -1;
01357             ssl->need_bytes = basic_decrypt(ssl, ssl->bm_data, ssl->need_bytes);
01358             if(ssl->need_bytes < 0)
01359                 return -1;
01360 
01361             if (ssl->next_state != HS_FINISHED)
01362             {
01363                 return SSL_ERROR_INVALID_HANDSHAKE;
01364             }
01365 
01366             /* all encrypted from now on */
01367             SET_SSL_FLAG(SSL_RX_ENCRYPTED);
01368             if (set_key_block(ssl, 0) < 0)
01369             {
01370                 return SSL_ERROR_INVALID_HANDSHAKE;
01371             }
01372             
01373             memset(ssl->read_sequence, 0, 8);
01374             SET_SSL_FLAG(SSL_NEED_RECORD);
01375             break;
01376 
01377         case PT_APP_PROTOCOL_DATA:
01378             if(len <= 0)
01379                 return 0;
01380             if(ssl->need_bytes == 0)
01381                 return 0;
01382             if (in_data)
01383             {
01384                 uint16_t index = ssl->bm_index % 2048;
01385                 if(ssl->bm_read_index == 0)
01386                 {
01387                     int read_len = len;
01388                     if(read_len > 2048-index)
01389                         read_len = 2048-index;
01390                     if(read_len > ssl->need_bytes)
01391                         read_len = ssl->need_bytes;
01392                     read_len -= read_len % AES_BLOCKSIZE;
01393 
01394                     if(read_len <= 0)
01395                         read_len = AES_BLOCKSIZE;
01396                     if(ssl->need_bytes < AES_BLOCKSIZE)
01397                         read_len = AES_BLOCKSIZE;
01398                     int ret = basic_read2(ssl, ssl->bm_all_data + index, read_len);
01399                     if(ret != read_len)
01400                         return 0;
01401                     
01402                     ssl->bm_read_index = basic_decrypt(ssl, ssl->bm_all_data + index, read_len);
01403                     ssl->need_bytes -= ssl->bm_read_index;
01404                     if(ssl->need_bytes == 0)
01405                     {
01406                         ssl->bm_read_index = 0;
01407                         SET_SSL_FLAG(SSL_NEED_RECORD);
01408                         return ssl_read(ssl, in_data, len);
01409                     }
01410                 }
01411                 if(len > ssl->bm_read_index)
01412                     len = ssl->bm_read_index;
01413                 memcpy(in_data, ssl->bm_all_data+index, len);
01414                 ssl->bm_index += len;
01415                 ssl->bm_read_index -= len;
01416                 
01417                 if(ssl->need_bytes == 0)
01418                     SET_SSL_FLAG(SSL_NEED_RECORD);
01419                 if(ssl->bm_index >= 2048)
01420                     ssl->bm_index = 0;
01421                 return len;
01422             }
01423             return 0;
01424             
01425         case PT_ALERT_PROTOCOL:
01426             if(basic_read2(ssl, ssl->bm_data, ssl->need_bytes) != ssl->need_bytes)
01427                 return -1;
01428             ssl->need_bytes = basic_decrypt(ssl, ssl->bm_data, ssl->need_bytes);
01429             if(ssl->need_bytes < 0)
01430                 return -1; 
01431             
01432             SET_SSL_FLAG(SSL_NEED_RECORD);
01433 
01434             /* return the alert # with alert bit set */
01435             if(ssl->bm_data[0] == SSL_ALERT_TYPE_WARNING &&
01436                ssl->bm_data[1] == SSL_ALERT_CLOSE_NOTIFY)
01437             {
01438                 send_alert(ssl, SSL_ALERT_CLOSE_NOTIFY);
01439                 SET_SSL_FLAG(SSL_SENT_CLOSE_NOTIFY);
01440                 return SSL_CLOSE_NOTIFY;
01441             }
01442             else 
01443             {
01444                 int ret = -ssl->bm_data[1];
01445                 DISPLAY_ALERT(ssl, -ret);
01446                 return ret;
01447             }
01448 
01449         default:
01450             return SSL_ERROR_INVALID_PROT_MSG;
01451 
01452     }
01453 }
01454 
01455 
01456 /**
01457  * Do some basic checking of data and then perform the appropriate handshaking.
01458  */
01459 static int do_handshake(SSL *ssl, uint8_t *buf, int read_len)
01460 {
01461     uint8_t hs_hdr[SSL_HS_HDR_SIZE];
01462     if (IS_SET_SSL_FLAG(SSL_RX_ENCRYPTED))
01463     {
01464         if(basic_read2(ssl, ssl->bm_data, ssl->need_bytes) != ssl->need_bytes)
01465             return -1;
01466         ssl->need_bytes = basic_decrypt(ssl, ssl->bm_data, ssl->need_bytes);
01467         if(ssl->need_bytes < 0)
01468             return -1; 
01469         buf = ssl->bm_data;
01470     }
01471     else
01472     {
01473         if(basic_read2(ssl, hs_hdr, SSL_HS_HDR_SIZE) != SSL_HS_HDR_SIZE)
01474             return -1;
01475         buf = hs_hdr;
01476     }
01477 
01478     int hs_len = (buf[2]<<8) + buf[3];
01479     uint8_t handshake_type = buf[0];
01480     int ret = SSL_OK;
01481     int is_client = IS_SET_SSL_FLAG(SSL_IS_CLIENT);
01482 
01483     /* some integrity checking on the handshake */
01484     //PARANOIA_CHECK(read_len-SSL_HS_HDR_SIZE, hs_len);
01485 
01486     if (handshake_type != ssl->next_state)
01487     {
01488         /* handle a special case on the client */
01489         if (!is_client || handshake_type != HS_CERT_REQ ||
01490                         ssl->next_state != HS_SERVER_HELLO_DONE)
01491         {
01492             return SSL_ERROR_INVALID_HANDSHAKE;
01493         }
01494     }
01495 
01496     //hs_len += SSL_HS_HDR_SIZE;  /* adjust for when adding packets */
01497     ssl->bm_index = hs_len+SSL_HS_HDR_SIZE;     /* store the size and check later */
01498     DISPLAY_STATE(ssl, 0, handshake_type, 0);
01499 
01500     if (handshake_type != HS_CERT_VERIFY && handshake_type != HS_HELLO_REQUEST)
01501     {
01502         add_packet(ssl, buf, SSL_HS_HDR_SIZE); 
01503     }
01504     
01505     if(!IS_SET_SSL_FLAG(SSL_RX_ENCRYPTED))
01506     {
01507         if(hs_len != 0 && handshake_type != HS_CERTIFICATE)
01508         {
01509             if(basic_read2(ssl, ssl->bm_data, hs_len) != hs_len)
01510                 return -1;
01511             hs_len = basic_decrypt(ssl, ssl->bm_data, hs_len);
01512             if(hs_len < 0)
01513                 return -1; 
01514             
01515             buf = ssl->bm_data;
01516             if (handshake_type != HS_CERT_VERIFY && handshake_type != HS_HELLO_REQUEST)
01517                 add_packet(ssl, buf, hs_len);
01518         }
01519     }
01520     else if (handshake_type != HS_CERT_VERIFY && handshake_type != HS_HELLO_REQUEST)
01521         add_packet(ssl, ssl->bm_data+SSL_HS_HDR_SIZE, hs_len-SSL_HS_HDR_SIZE);
01522 
01523 #if defined(CONFIG_SSL_ENABLE_CLIENT)
01524     ret = is_client ? 
01525         do_clnt_handshake(ssl, handshake_type, buf, hs_len) :
01526         do_svr_handshake(ssl, handshake_type, buf, hs_len);
01527 #else
01528     ret = do_svr_handshake(ssl, handshake_type, buf, hs_len);
01529 #endif
01530 
01531     /* just use recursion to get the rest */
01532     //if (hs_len < read_len && ret == SSL_OK)
01533         //ret = do_handshake(ssl, &buf[hs_len], read_len-hs_len);
01534 
01535     return ret;
01536 }
01537 
01538 /**
01539  * Sends the change cipher spec message. We have just read a finished message
01540  * from the client.
01541  */
01542 int send_change_cipher_spec(SSL *ssl)
01543 {
01544     int ret = send_packet(ssl, PT_CHANGE_CIPHER_SPEC, 
01545             g_chg_cipher_spec_pkt, sizeof(g_chg_cipher_spec_pkt));
01546     SET_SSL_FLAG(SSL_TX_ENCRYPTED);
01547 
01548     if (ret >= 0 && set_key_block(ssl, 1) < 0)
01549         ret = SSL_ERROR_INVALID_HANDSHAKE;
01550 
01551     memset(ssl->write_sequence, 0, 8);
01552     return ret;
01553 }
01554 
01555 /**
01556  * Send a "finished" message
01557  */
01558 int send_finished(SSL *ssl)
01559 {
01560     uint8_t buf[SSL_FINISHED_HASH_SIZE+4] = {
01561         HS_FINISHED, 0, 0, SSL_FINISHED_HASH_SIZE };
01562 
01563     /* now add the finished digest mac (12 bytes) */
01564     finished_digest(ssl, 
01565         IS_SET_SSL_FLAG(SSL_IS_CLIENT) ?
01566                     client_finished : server_finished, &buf[4]);
01567 
01568 #ifndef CONFIG_SSL_SKELETON_MODE
01569     /* store in the session cache */
01570     if (!IS_SET_SSL_FLAG(SSL_SESSION_RESUME) && ssl->ssl_ctx->num_sessions)
01571     {
01572         memcpy(ssl->session->master_secret,
01573                 ssl->dc->master_secret, SSL_SECRET_SIZE);
01574     }
01575 #endif
01576 
01577     return send_packet(ssl, PT_HANDSHAKE_PROTOCOL,
01578                                 buf, SSL_FINISHED_HASH_SIZE+4);
01579 }
01580 
01581 /**
01582  * Send an alert message.
01583  * Return 1 if the alert was an "error".
01584  */
01585 int send_alert(SSL *ssl, int error_code)
01586 {
01587     int alert_num = 0;
01588     int is_warning = 0;
01589     uint8_t buf[2];
01590 
01591     /* Don't bother we're already dead */
01592     if (ssl->hs_status == SSL_ERROR_DEAD)
01593     {
01594         return SSL_ERROR_CONN_LOST;
01595     }
01596 
01597 #ifdef CONFIG_SSL_FULL_MODE
01598     if (IS_SET_SSL_FLAG(SSL_DISPLAY_STATES))
01599         ssl_display_error(error_code);
01600 #endif
01601 
01602     switch (error_code)
01603     {
01604         case SSL_ALERT_CLOSE_NOTIFY:
01605             is_warning = 1;
01606             alert_num = SSL_ALERT_CLOSE_NOTIFY;
01607             break;
01608 
01609         case SSL_ERROR_CONN_LOST:       /* don't send alert just yet */
01610             is_warning = 1;
01611             break;
01612 
01613         case SSL_ERROR_INVALID_HANDSHAKE:
01614         case SSL_ERROR_INVALID_PROT_MSG:
01615             alert_num = SSL_ALERT_HANDSHAKE_FAILURE;
01616             break;
01617 
01618         case SSL_ERROR_INVALID_HMAC:
01619         case SSL_ERROR_FINISHED_INVALID:
01620             alert_num = SSL_ALERT_BAD_RECORD_MAC;
01621             break;
01622 
01623         case SSL_ERROR_INVALID_VERSION:
01624             alert_num = SSL_ALERT_INVALID_VERSION;
01625             break;
01626 
01627         case SSL_ERROR_INVALID_SESSION:
01628         case SSL_ERROR_NO_CIPHER:
01629         case SSL_ERROR_INVALID_KEY:
01630             alert_num = SSL_ALERT_ILLEGAL_PARAMETER;
01631             break;
01632 
01633         case SSL_ERROR_BAD_CERTIFICATE:
01634             alert_num = SSL_ALERT_BAD_CERTIFICATE;
01635             break;
01636 
01637         case SSL_ERROR_NO_CLIENT_RENOG:
01638             alert_num = SSL_ALERT_NO_RENEGOTIATION;
01639             break;
01640 
01641         default:
01642             /* a catch-all for any badly verified certificates */
01643             alert_num = (error_code <= SSL_X509_OFFSET) ?  
01644                 SSL_ALERT_BAD_CERTIFICATE : SSL_ALERT_UNEXPECTED_MESSAGE;
01645             break;
01646     }
01647 
01648     buf[0] = is_warning ? 1 : 2;
01649     buf[1] = alert_num;
01650 
01651     send_packet(ssl, PT_ALERT_PROTOCOL, buf, sizeof(buf));
01652     DISPLAY_ALERT(ssl, alert_num);
01653     return is_warning ? 0 : 1;
01654 }
01655 
01656 /**
01657  * Process a client finished message.
01658  */
01659 int process_finished(SSL *ssl, uint8_t *buf, int hs_len)
01660 {
01661     int is_client = IS_SET_SSL_FLAG(SSL_IS_CLIENT);
01662     int ret = SSL_OK;
01663     int resume = IS_SET_SSL_FLAG(SSL_SESSION_RESUME);
01664 
01665     PARANOIA_CHECK(ssl->bm_index, SSL_FINISHED_HASH_SIZE);
01666 
01667     /* check that we all work before we continue */
01668     if (memcmp(ssl->dc->final_finish_mac, &buf[4], SSL_FINISHED_HASH_SIZE))
01669     {
01670         return SSL_ERROR_FINISHED_INVALID;
01671     }
01672     if ((!is_client && !resume) || (is_client && resume))
01673     {
01674         if ((ret = send_change_cipher_spec(ssl)) == SSL_OK)
01675             ret = send_finished(ssl);
01676     }
01677 
01678     /* if we ever renegotiate */
01679     ssl->next_state = is_client ? HS_HELLO_REQUEST : HS_CLIENT_HELLO;  
01680     ssl->hs_status = ret;  /* set the final handshake status */
01681 error:
01682     return ret;
01683 }
01684 
01685 /**
01686  * Send a certificate.
01687  */
01688 int send_certificate(SSL *ssl)
01689 {
01690     int i = 0;
01691     uint8_t *buf = ssl->bm_data;
01692     int offset = 7;
01693     int chain_length;
01694 
01695     buf[0] = HS_CERTIFICATE;
01696     buf[1] = 0;
01697     buf[4] = 0;
01698 
01699     while (i < ssl->ssl_ctx->chain_length)
01700     {
01701         SSL_CERT *cert = &ssl->ssl_ctx->certs[i];
01702         buf[offset++] = 0;        
01703         buf[offset++] = cert->size >> 8;        /* cert 1 length */
01704         buf[offset++] = cert->size & 0xff;
01705         memcpy(&buf[offset], cert->buf, cert->size);
01706         offset += cert->size;
01707         i++;
01708     }
01709 
01710     chain_length = offset - 7;
01711     buf[5] = chain_length >> 8;        /* cert chain length */
01712     buf[6] = chain_length & 0xff;
01713     chain_length += 3;
01714     buf[2] = chain_length >> 8;        /* handshake length */
01715     buf[3] = chain_length & 0xff;
01716     ssl->bm_index = offset;
01717     return send_packet(ssl, PT_HANDSHAKE_PROTOCOL, NULL, offset);
01718 }
01719 
01720 /**
01721  * Create a blob of memory that we'll get rid of once the handshake is
01722  * complete.
01723  */
01724 void disposable_new(SSL *ssl)
01725 {
01726     if (ssl->dc == NULL)
01727     {
01728         ssl->dc = (DISPOSABLE_CTX *)calloc(1, sizeof(DISPOSABLE_CTX));
01729         memset(ssl->dc->key_block, 0, MAX_KEYBLOCK_SIZE);
01730         MD5_Init(&ssl->dc->md5_ctx);
01731         SHA1_Init(&ssl->dc->sha1_ctx);
01732     }
01733 }
01734 
01735 /**
01736  * Remove the temporary blob of memory.
01737  */
01738 void disposable_free(SSL *ssl)
01739 {
01740     if (ssl->dc)
01741     {
01742         //free(ssl->dc->key_block);
01743         memset(ssl->dc, 0, sizeof(DISPOSABLE_CTX));
01744         free(ssl->dc);
01745         ssl->dc = NULL;
01746     }
01747 
01748 }
01749 
01750 #ifndef CONFIG_SSL_SKELETON_MODE     /* no session resumption in this mode */
01751 /**
01752  * Find if an existing session has the same session id. If so, use the
01753  * master secret from this session for session resumption.
01754  */
01755 SSL_SESSION *ssl_session_update(int max_sessions, SSL_SESSION *ssl_sessions[], 
01756         SSL *ssl, const uint8_t *session_id)
01757 {
01758     time_t tm = time(NULL);
01759     time_t oldest_sess_time = tm;
01760     SSL_SESSION *oldest_sess = NULL;
01761     int i;
01762 
01763     /* no sessions? Then bail */
01764     if (max_sessions == 0)
01765         return NULL;
01766 
01767     SSL_CTX_LOCK(ssl->ssl_ctx->mutex);
01768     if (session_id)
01769     {
01770         for (i = 0; i < max_sessions; i++)
01771         {
01772             if (ssl_sessions[i])
01773             {
01774                 /* kill off any expired sessions (including those in 
01775                    the future) */
01776                 if ((tm > ssl_sessions[i]->conn_time + SSL_EXPIRY_TIME) ||
01777                             (tm < ssl_sessions[i]->conn_time))
01778                 {
01779                     session_free(ssl_sessions, i);
01780                     continue;
01781                 }
01782 
01783                 /* if the session id matches, it must still be less than 
01784                    the expiry time */
01785                 if (memcmp(ssl_sessions[i]->session_id, session_id,
01786                                                 SSL_SESSION_ID_SIZE) == 0)
01787                 {
01788                     ssl->session_index = i;
01789                     memcpy(ssl->dc->master_secret, 
01790                             ssl_sessions[i]->master_secret, SSL_SECRET_SIZE);
01791                     SET_SSL_FLAG(SSL_SESSION_RESUME);
01792                     SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex);
01793                     return ssl_sessions[i];  /* a session was found */
01794                 }
01795             }
01796         }
01797     }
01798 
01799     /* If we've got here, no matching session was found - so create one */
01800     for (i = 0; i < max_sessions; i++)
01801     {
01802         if (ssl_sessions[i] == NULL)
01803         {
01804             /* perfect, this will do */
01805             ssl_sessions[i] = (SSL_SESSION *)calloc(1, sizeof(SSL_SESSION));
01806             ssl_sessions[i]->conn_time = tm;
01807             ssl->session_index = i;
01808             SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex);
01809             return ssl_sessions[i]; /* return the session object */
01810         }
01811         else if (ssl_sessions[i]->conn_time <= oldest_sess_time)
01812         {
01813             /* find the oldest session */
01814             oldest_sess_time = ssl_sessions[i]->conn_time;
01815             oldest_sess = ssl_sessions[i];
01816             ssl->session_index = i;
01817         }
01818     }
01819 
01820     /* ok, we've used up all of our sessions. So blow the oldest session away */
01821     oldest_sess->conn_time = tm;
01822     memset(oldest_sess->session_id, 0, sizeof(SSL_SESSION_ID_SIZE));
01823     memset(oldest_sess->master_secret, 0, sizeof(SSL_SECRET_SIZE));
01824     SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex);
01825     return oldest_sess;
01826 }
01827 
01828 /**
01829  * Free an existing session.
01830  */
01831 static void session_free(SSL_SESSION *ssl_sessions[], int sess_index)
01832 {
01833     if (ssl_sessions[sess_index])
01834     {
01835         free(ssl_sessions[sess_index]);
01836         ssl_sessions[sess_index] = NULL;
01837     }
01838 }
01839 
01840 /**
01841  * This ssl object doesn't want this session anymore.
01842  */
01843 void kill_ssl_session(SSL_SESSION **ssl_sessions, SSL *ssl)
01844 {
01845     SSL_CTX_LOCK(ssl->ssl_ctx->mutex);
01846 
01847     if (ssl->ssl_ctx->num_sessions)
01848     {
01849         session_free(ssl_sessions, ssl->session_index);
01850         ssl->session = NULL;
01851     }
01852 
01853     SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex);
01854 }
01855 #endif /* CONFIG_SSL_SKELETON_MODE */
01856 
01857 /*
01858  * Get the session id for a handshake. This will be a 32 byte sequence.
01859  */
01860 EXP_FUNC const uint8_t * STDCALL ssl_get_session_id(const SSL *ssl)
01861 {
01862     return ssl->session_id;
01863 }
01864 
01865 /*
01866  * Get the session id size for a handshake. 
01867  */
01868 EXP_FUNC uint8_t STDCALL ssl_get_session_id_size(const SSL *ssl)
01869 {
01870     return ssl->sess_id_size;
01871 }
01872 
01873 /*
01874  * Return the cipher id (in the SSL form).
01875  */
01876 EXP_FUNC uint8_t STDCALL ssl_get_cipher_id(const SSL *ssl)
01877 {
01878     return ssl->cipher;
01879 }
01880 
01881 /*
01882  * Return the status of the handshake.
01883  */
01884 EXP_FUNC int STDCALL ssl_handshake_status(const SSL *ssl)
01885 {
01886     return ssl->hs_status;
01887 }
01888 
01889 /*
01890  * Retrieve various parameters about the SSL engine.
01891  */
01892 EXP_FUNC int STDCALL ssl_get_config(int offset)
01893 {
01894     switch (offset)
01895     {
01896         /* return the appropriate build mode */
01897         case SSL_BUILD_MODE:
01898 #if defined(CONFIG_SSL_FULL_MODE)
01899             return SSL_BUILD_FULL_MODE;
01900 #elif defined(CONFIG_SSL_ENABLE_CLIENT)
01901             return SSL_BUILD_ENABLE_CLIENT;
01902 #elif defined(CONFIG_ENABLE_VERIFICATION)
01903             return SSL_BUILD_ENABLE_VERIFICATION;
01904 #elif defined(CONFIG_SSL_SERVER_ONLY )
01905             return SSL_BUILD_SERVER_ONLY;
01906 #else 
01907             return SSL_BUILD_SKELETON_MODE;
01908 #endif
01909 
01910         case SSL_MAX_CERT_CFG_OFFSET:
01911             return CONFIG_SSL_MAX_CERTS;
01912 
01913 #ifdef CONFIG_SSL_CERT_VERIFICATION
01914         case SSL_MAX_CA_CERT_CFG_OFFSET:
01915             return CONFIG_X509_MAX_CA_CERTS;
01916 #endif
01917 #ifdef CONFIG_SSL_HAS_PEM
01918         case SSL_HAS_PEM:
01919             return 1;
01920 #endif
01921         default:
01922             return 0;
01923     }
01924 }
01925 
01926 #ifdef CONFIG_SSL_CERT_VERIFICATION
01927 /**
01928  * Authenticate a received certificate.
01929  */
01930 EXP_FUNC int STDCALL ssl_verify_cert(const SSL *ssl)
01931 {
01932     int ret;
01933     SSL_CTX_LOCK(ssl->ssl_ctx->mutex);
01934     ret = x509_verify(ssl->ssl_ctx->ca_cert_ctx, ssl->x509_ctx);
01935     SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex);
01936 
01937     if (ret)        /* modify into an SSL error type */
01938     {
01939         ret = SSL_X509_ERROR(ret);
01940     }
01941 
01942     return ret;
01943 }
01944 
01945 /**
01946  * Process a certificate message.
01947  */
01948 int process_certificate(SSL *ssl, X509_CTX **x509_ctx)
01949 {
01950     int ret = SSL_OK;
01951     
01952     uint8_t cert_hdr[3];
01953     if(basic_read2(ssl, cert_hdr, 3) != 3)
01954     {
01955         ret = SSL_NOT_OK;
01956         return ret;
01957     }
01958 
01959     add_packet(ssl, cert_hdr, 3);
01960     int len = 5;
01961     int pkt_size = ssl->bm_index;
01962     int cert_size;
01963     int total_cert_size = (cert_hdr[1]<<8) + cert_hdr[2];
01964     int is_client = IS_SET_SSL_FLAG(SSL_IS_CLIENT);
01965     X509_CTX **chain = x509_ctx;
01966     len += 2;
01967     PARANOIA_CHECK(total_cert_size, 3);
01968 
01969     while (len < total_cert_size)
01970     {
01971 
01972         if(basic_read2(ssl, cert_hdr, 3) != 3)
01973         {
01974             ret = SSL_NOT_OK;
01975             return ret;
01976         }
01977 
01978         add_packet(ssl, cert_hdr, 3);
01979 
01980         cert_size = (cert_hdr[1]<<8) + cert_hdr[2];
01981         if(cert_size > RT_MAX_PLAIN_LENGTH)
01982         {
01983             ret = SSL_NOT_OK;
01984             return ret;
01985         }
01986         
01987         len += 3;
01988 
01989         if(basic_read2(ssl, ssl->bm_data, cert_size) != cert_size)
01990         {
01991             return SSL_NOT_OK;
01992         }
01993 
01994         add_packet(ssl, ssl->bm_data, cert_size);
01995 
01996         if (x509_new(ssl->bm_data, NULL, chain))
01997         {
01998             ret = SSL_ERROR_BAD_CERTIFICATE;
01999             goto error;
02000         }
02001 
02002         chain = &((*chain)->next);
02003         len += cert_size;
02004     }
02005     PARANOIA_CHECK(pkt_size, len);
02006 
02007     /* if we are client we can do the verify now or later */
02008     if (is_client && !IS_SET_SSL_FLAG(SSL_SERVER_VERIFY_LATER))
02009     {
02010         ret = ssl_verify_cert(ssl);
02011     }
02012 
02013     ssl->next_state = is_client ? HS_SERVER_HELLO_DONE : HS_CLIENT_KEY_XCHG;
02014     ssl->dc->bm_proc_index += len;
02015 error:
02016 
02017     return ret;
02018 }
02019 
02020 #endif /* CONFIG_SSL_CERT_VERIFICATION */
02021 
02022 /**
02023  * Debugging routine to display SSL handshaking stuff.
02024  */
02025 #ifdef CONFIG_SSL_FULL_MODE
02026 /**
02027  * Debugging routine to display SSL states.
02028  */
02029 void DISPLAY_STATE(SSL *ssl, int is_send, uint8_t state, int not_ok)
02030 {
02031     const char *str;
02032 
02033     if (!IS_SET_SSL_FLAG(SSL_DISPLAY_STATES))
02034         return;
02035 
02036     printf(not_ok ? "Error - invalid State:\t" : "State:\t");
02037     printf(is_send ? "sending " : "receiving ");
02038 
02039     switch (state)
02040     {
02041         case HS_HELLO_REQUEST:
02042             str = "Hello Request (0)";
02043             break;
02044 
02045         case HS_CLIENT_HELLO:
02046             str = "Client Hello (1)";
02047             break;
02048 
02049         case HS_SERVER_HELLO:
02050             str = "Server Hello (2)";
02051             break;
02052 
02053         case HS_CERTIFICATE:
02054             str = "Certificate (11)";
02055             break;
02056 
02057         case HS_SERVER_KEY_XCHG:
02058             str = "Certificate Request (12)";
02059             break;
02060 
02061         case HS_CERT_REQ:
02062             str = "Certificate Request (13)";
02063             break;
02064 
02065         case HS_SERVER_HELLO_DONE:
02066             str = "Server Hello Done (14)";
02067             break;
02068 
02069         case HS_CERT_VERIFY:
02070             str = "Certificate Verify (15)";
02071             break;
02072 
02073         case HS_CLIENT_KEY_XCHG:
02074             str = "Client Key Exchange (16)";
02075             break;
02076 
02077         case HS_FINISHED:
02078             str = "Finished (16)";
02079             break;
02080 
02081         default:
02082             str = "Error (Unknown)";
02083             
02084             break;
02085     }
02086 
02087     printf("%s\r\n", str);
02088     TTY_FLUSH();
02089 }
02090 
02091 /**
02092  * Debugging routine to display RSA objects
02093  */
02094 void DISPLAY_RSA(SSL *ssl, const RSA_CTX *rsa_ctx)
02095 {
02096     if (!IS_SET_SSL_FLAG(SSL_DISPLAY_RSA))
02097         return;
02098 
02099     RSA_print(rsa_ctx);
02100     TTY_FLUSH();
02101 }
02102 
02103 /**
02104  * Debugging routine to display SSL handshaking bytes.
02105  */
02106 void DISPLAY_BYTES(SSL *ssl, const char *format, 
02107         const uint8_t *data, int size, ...)
02108 {
02109     va_list(ap);
02110 
02111     if (!IS_SET_SSL_FLAG(SSL_DISPLAY_BYTES))
02112         return;
02113 
02114     va_start(ap, size);
02115     print_blob(format, data, size, va_arg(ap, char *));
02116     va_end(ap);
02117     TTY_FLUSH();
02118 }
02119 
02120 /**
02121  * Debugging routine to display SSL handshaking errors.
02122  */
02123 EXP_FUNC void STDCALL ssl_display_error(int error_code)
02124 {
02125     if (error_code == SSL_OK)
02126         return;
02127 
02128     printf("Error: ");
02129 
02130     /* X509 error? */
02131     if (error_code < SSL_X509_OFFSET)
02132     {
02133         printf("%s\r\n", x509_display_error(error_code - SSL_X509_OFFSET));
02134         return;
02135     }
02136 
02137     /* SSL alert error code */
02138     if (error_code > SSL_ERROR_CONN_LOST)
02139     {
02140         printf("SSL error %d\n", -error_code);
02141         return;
02142     }
02143 
02144     switch (error_code)
02145     {
02146         case SSL_ERROR_DEAD:
02147             printf("connection dead");
02148             break;
02149 
02150         case SSL_ERROR_INVALID_HANDSHAKE:
02151             printf("invalid handshake");
02152             break;
02153 
02154         case SSL_ERROR_INVALID_PROT_MSG:
02155             printf("invalid protocol message");
02156             break;
02157 
02158         case SSL_ERROR_INVALID_HMAC:
02159             printf("invalid mac");
02160             break;
02161 
02162         case SSL_ERROR_INVALID_VERSION:
02163             printf("invalid version");
02164             break;
02165 
02166         case SSL_ERROR_INVALID_SESSION:
02167             printf("invalid session");
02168             break;
02169 
02170         case SSL_ERROR_NO_CIPHER:
02171             printf("no cipher");
02172             break;
02173 
02174         case SSL_ERROR_CONN_LOST:
02175             printf("connection lost");
02176             break;
02177 
02178         case SSL_ERROR_BAD_CERTIFICATE:
02179             printf("bad certificate");
02180             break;
02181 
02182         case SSL_ERROR_INVALID_KEY:
02183             printf("invalid key");
02184             break;
02185 
02186         case SSL_ERROR_FINISHED_INVALID:
02187             printf("finished invalid");
02188             break;
02189 
02190         case SSL_ERROR_NO_CERT_DEFINED:
02191             printf("no certificate defined");
02192             break;
02193 
02194         case SSL_ERROR_NO_CLIENT_RENOG:
02195             printf("client renegotiation not supported");
02196             break;
02197             
02198         case SSL_ERROR_NOT_SUPPORTED:
02199             printf("Option not supported");
02200             break;
02201 
02202         default:
02203             printf("undefined as yet - %d", error_code);
02204             break;
02205     }
02206 
02207     printf("\r\n");
02208     TTY_FLUSH();
02209 }
02210 
02211 /**
02212  * Debugging routine to display alerts.
02213  */
02214 void DISPLAY_ALERT(SSL *ssl, int alert)
02215 {
02216     if (!IS_SET_SSL_FLAG(SSL_DISPLAY_STATES))
02217         return;
02218 
02219     printf("Alert: ");
02220 
02221     switch (alert)
02222     {
02223         case SSL_ALERT_CLOSE_NOTIFY:
02224             printf("close notify");
02225             break;
02226 
02227         case SSL_ALERT_INVALID_VERSION:
02228             printf("invalid version");
02229             break;
02230 
02231         case SSL_ALERT_BAD_CERTIFICATE:
02232             printf("bad certificate");
02233             break;
02234 
02235         case SSL_ALERT_UNEXPECTED_MESSAGE:
02236             printf("unexpected message");
02237             break;
02238 
02239         case SSL_ALERT_BAD_RECORD_MAC:
02240             printf("bad record mac");
02241             break;
02242 
02243         case SSL_ALERT_HANDSHAKE_FAILURE:
02244             printf("handshake failure");
02245             break;
02246 
02247         case SSL_ALERT_ILLEGAL_PARAMETER:
02248             printf("illegal parameter");
02249             break;
02250 
02251         case SSL_ALERT_DECODE_ERROR:
02252             printf("decode error");
02253             break;
02254 
02255         case SSL_ALERT_DECRYPT_ERROR:
02256             printf("decrypt error");
02257             break;
02258 
02259         case SSL_ALERT_NO_RENEGOTIATION:
02260             printf("no renegotiation");
02261             break;
02262 
02263         default:
02264             printf("alert - (unknown %d)", alert);
02265             break;
02266     }
02267 
02268     printf("\r\n");
02269     TTY_FLUSH();
02270 }
02271 
02272 #endif /* CONFIG_SSL_FULL_MODE */
02273 
02274 /**
02275  * Return the version of this library.
02276  */
02277 EXP_FUNC const char  * STDCALL ssl_version()
02278 {
02279     static const char * axtls_version = AXTLS_VERSION;
02280     return axtls_version;
02281 }
02282 
02283 /**
02284  * Enable the various language bindings to work regardless of the
02285  * configuration - they just return an error statement and a bad return code.
02286  */
02287 #if !defined(CONFIG_SSL_FULL_MODE)
02288 EXP_FUNC void STDCALL ssl_display_error(int error_code) {}
02289 #endif
02290 
02291 #ifdef CONFIG_BINDINGS
02292 #if !defined(CONFIG_SSL_ENABLE_CLIENT)
02293 EXP_FUNC SSL * STDCALL ssl_client_new(SSL_CTX *ssl_ctx, int client_fd, const
02294         uint8_t *session_id, uint8_t sess_id_size)
02295 {
02296     printf(unsupported_str);
02297     return NULL;
02298 }
02299 #endif
02300 
02301 #if !defined(CONFIG_SSL_CERT_VERIFICATION)
02302 EXP_FUNC int STDCALL ssl_verify_cert(const SSL *ssl)
02303 {
02304     printf(unsupported_str);
02305     return -1;
02306 }
02307 
02308 
02309 EXP_FUNC const char * STDCALL ssl_get_cert_dn(const SSL *ssl, int component)
02310 {
02311     printf(unsupported_str);
02312     return NULL;
02313 }
02314 
02315 EXP_FUNC const char * STDCALL ssl_get_cert_subject_alt_dnsname(const SSL *ssl, int index)
02316 {
02317     printf(unsupported_str);
02318     return NULL;
02319 }
02320 
02321 #endif  /* CONFIG_SSL_CERT_VERIFICATION */
02322 
02323 #endif /* CONFIG_BINDINGS */
02324