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