This is a fork of the mbed port of axTLS

Dependents:   TLS_axTLS-Example HTTPSClientExample

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