mbed TLS library

Dependents:   HTTPClient-SSL WS_SERVER

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers ssl_tls.c Source File

ssl_tls.c

00001 /*
00002  *  SSLv3/TLSv1 shared functions
00003  *
00004  *  Copyright (C) 2006-2014, ARM Limited, All Rights Reserved
00005  *
00006  *  This file is part of mbed TLS (https://tls.mbed.org)
00007  *
00008  *  This program is free software; you can redistribute it and/or modify
00009  *  it under the terms of the GNU General Public License as published by
00010  *  the Free Software Foundation; either version 2 of the License, or
00011  *  (at your option) any later version.
00012  *
00013  *  This program is distributed in the hope that it will be useful,
00014  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
00015  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00016  *  GNU General Public License for more details.
00017  *
00018  *  You should have received a copy of the GNU General Public License along
00019  *  with this program; if not, write to the Free Software Foundation, Inc.,
00020  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
00021  */
00022 /*
00023  *  The SSL 3.0 specification was drafted by Netscape in 1996,
00024  *  and became an IETF standard in 1999.
00025  *
00026  *  http://wp.netscape.com/eng/ssl3/
00027  *  http://www.ietf.org/rfc/rfc2246.txt
00028  *  http://www.ietf.org/rfc/rfc4346.txt
00029  */
00030 
00031 #if !defined(POLARSSL_CONFIG_FILE)
00032 #include "polarssl/config.h"
00033 #else
00034 #include POLARSSL_CONFIG_FILE
00035 #endif
00036 
00037 #if defined(POLARSSL_SSL_TLS_C)
00038 
00039 #include "polarssl/debug.h"
00040 #include "polarssl/ssl.h"
00041 
00042 #include <string.h>
00043 
00044 #if defined(POLARSSL_X509_CRT_PARSE_C) && \
00045     defined(POLARSSL_X509_CHECK_EXTENDED_KEY_USAGE)
00046 #include "polarssl/oid.h"
00047 #endif
00048 
00049 #if defined(POLARSSL_PLATFORM_C)
00050 #include "polarssl/platform.h"
00051 #else
00052 #include <stdlib.h>
00053 #define polarssl_malloc     malloc
00054 #define polarssl_free       free
00055 #endif
00056 
00057 #if defined(_MSC_VER) && !defined strcasecmp && !defined(EFIX64) && \
00058     !defined(EFI32)
00059 #define strcasecmp _stricmp
00060 #endif
00061 
00062 /* Implementation that should never be optimized out by the compiler */
00063 static void polarssl_zeroize( void *v, size_t n ) {
00064     volatile unsigned char *p = v; while( n-- ) *p++ = 0;
00065 }
00066 
00067 #if defined(POLARSSL_SSL_MAX_FRAGMENT_LENGTH)
00068 /*
00069  * Convert max_fragment_length codes to length.
00070  * RFC 6066 says:
00071  *    enum{
00072  *        2^9(1), 2^10(2), 2^11(3), 2^12(4), (255)
00073  *    } MaxFragmentLength;
00074  * and we add 0 -> extension unused
00075  */
00076 static unsigned int mfl_code_to_length[SSL_MAX_FRAG_LEN_INVALID] =
00077 {
00078     SSL_MAX_CONTENT_LEN,    /* SSL_MAX_FRAG_LEN_NONE */
00079     512,                    /* SSL_MAX_FRAG_LEN_512  */
00080     1024,                   /* SSL_MAX_FRAG_LEN_1024 */
00081     2048,                   /* SSL_MAX_FRAG_LEN_2048 */
00082     4096,                   /* SSL_MAX_FRAG_LEN_4096 */
00083 };
00084 #endif /* POLARSSL_SSL_MAX_FRAGMENT_LENGTH */
00085 
00086 static int ssl_session_copy( ssl_session *dst, const ssl_session *src )
00087 {
00088     ssl_session_free( dst );
00089     memcpy( dst, src, sizeof( ssl_session ) );
00090 
00091 #if defined(POLARSSL_X509_CRT_PARSE_C)
00092     if( src->peer_cert != NULL )
00093     {
00094         int ret;
00095 
00096         dst->peer_cert = polarssl_malloc( sizeof(x509_crt) );
00097         if( dst->peer_cert == NULL )
00098             return( POLARSSL_ERR_SSL_MALLOC_FAILED );
00099 
00100         x509_crt_init( dst->peer_cert );
00101 
00102         if( ( ret = x509_crt_parse_der( dst->peer_cert, src->peer_cert->raw.p,
00103                                         src->peer_cert->raw.len ) ) != 0 )
00104         {
00105             polarssl_free( dst->peer_cert );
00106             dst->peer_cert = NULL;
00107             return( ret );
00108         }
00109     }
00110 #endif /* POLARSSL_X509_CRT_PARSE_C */
00111 
00112 #if defined(POLARSSL_SSL_SESSION_TICKETS)
00113     if( src->ticket != NULL )
00114     {
00115         dst->ticket = polarssl_malloc( src->ticket_len );
00116         if( dst->ticket == NULL )
00117             return( POLARSSL_ERR_SSL_MALLOC_FAILED );
00118 
00119         memcpy( dst->ticket, src->ticket, src->ticket_len );
00120     }
00121 #endif /* POLARSSL_SSL_SESSION_TICKETS */
00122 
00123     return( 0 );
00124 }
00125 
00126 #if defined(POLARSSL_SSL_HW_RECORD_ACCEL)
00127 int (*ssl_hw_record_init)( ssl_context *ssl,
00128                      const unsigned char *key_enc, const unsigned char *key_dec,
00129                      size_t keylen,
00130                      const unsigned char *iv_enc,  const unsigned char *iv_dec,
00131                      size_t ivlen,
00132                      const unsigned char *mac_enc, const unsigned char *mac_dec,
00133                      size_t maclen ) = NULL;
00134 int (*ssl_hw_record_activate)( ssl_context *ssl, int direction) = NULL;
00135 int (*ssl_hw_record_reset)( ssl_context *ssl ) = NULL;
00136 int (*ssl_hw_record_write)( ssl_context *ssl ) = NULL;
00137 int (*ssl_hw_record_read)( ssl_context *ssl ) = NULL;
00138 int (*ssl_hw_record_finish)( ssl_context *ssl ) = NULL;
00139 #endif /* POLARSSL_SSL_HW_RECORD_ACCEL */
00140 
00141 /*
00142  * Key material generation
00143  */
00144 #if defined(POLARSSL_SSL_PROTO_SSL3)
00145 static int ssl3_prf( const unsigned char *secret, size_t slen,
00146                      const char *label,
00147                      const unsigned char *random, size_t rlen,
00148                      unsigned char *dstbuf, size_t dlen )
00149 {
00150     size_t i;
00151     md5_context md5;
00152     sha1_context sha1;
00153     unsigned char padding[16];
00154     unsigned char sha1sum[20];
00155     ((void)label);
00156 
00157     md5_init(  &md5  );
00158     sha1_init( &sha1 );
00159 
00160     /*
00161      *  SSLv3:
00162      *    block =
00163      *      MD5( secret + SHA1( 'A'    + secret + random ) ) +
00164      *      MD5( secret + SHA1( 'BB'   + secret + random ) ) +
00165      *      MD5( secret + SHA1( 'CCC'  + secret + random ) ) +
00166      *      ...
00167      */
00168     for( i = 0; i < dlen / 16; i++ )
00169     {
00170         memset( padding, (unsigned char) ('A' + i), 1 + i );
00171 
00172         sha1_starts( &sha1 );
00173         sha1_update( &sha1, padding, 1 + i );
00174         sha1_update( &sha1, secret, slen );
00175         sha1_update( &sha1, random, rlen );
00176         sha1_finish( &sha1, sha1sum );
00177 
00178         md5_starts( &md5 );
00179         md5_update( &md5, secret, slen );
00180         md5_update( &md5, sha1sum, 20 );
00181         md5_finish( &md5, dstbuf + i * 16 );
00182     }
00183 
00184     md5_free(  &md5  );
00185     sha1_free( &sha1 );
00186 
00187     polarssl_zeroize( padding, sizeof( padding ) );
00188     polarssl_zeroize( sha1sum, sizeof( sha1sum ) );
00189 
00190     return( 0 );
00191 }
00192 #endif /* POLARSSL_SSL_PROTO_SSL3 */
00193 
00194 #if defined(POLARSSL_SSL_PROTO_TLS1) || defined(POLARSSL_SSL_PROTO_TLS1_1)
00195 static int tls1_prf( const unsigned char *secret, size_t slen,
00196                      const char *label,
00197                      const unsigned char *random, size_t rlen,
00198                      unsigned char *dstbuf, size_t dlen )
00199 {
00200     size_t nb, hs;
00201     size_t i, j, k;
00202     const unsigned char *S1, *S2;
00203     unsigned char tmp[128];
00204     unsigned char h_i[20];
00205 
00206     if( sizeof( tmp ) < 20 + strlen( label ) + rlen )
00207         return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
00208 
00209     hs = ( slen + 1 ) / 2;
00210     S1 = secret;
00211     S2 = secret + slen - hs;
00212 
00213     nb = strlen( label );
00214     memcpy( tmp + 20, label, nb );
00215     memcpy( tmp + 20 + nb, random, rlen );
00216     nb += rlen;
00217 
00218     /*
00219      * First compute P_md5(secret,label+random)[0..dlen]
00220      */
00221     md5_hmac( S1, hs, tmp + 20, nb, 4 + tmp );
00222 
00223     for( i = 0; i < dlen; i += 16 )
00224     {
00225         md5_hmac( S1, hs, 4 + tmp, 16 + nb, h_i );
00226         md5_hmac( S1, hs, 4 + tmp, 16,  4 + tmp );
00227 
00228         k = ( i + 16 > dlen ) ? dlen % 16 : 16;
00229 
00230         for( j = 0; j < k; j++ )
00231             dstbuf[i + j]  = h_i[j];
00232     }
00233 
00234     /*
00235      * XOR out with P_sha1(secret,label+random)[0..dlen]
00236      */
00237     sha1_hmac( S2, hs, tmp + 20, nb, tmp );
00238 
00239     for( i = 0; i < dlen; i += 20 )
00240     {
00241         sha1_hmac( S2, hs, tmp, 20 + nb, h_i );
00242         sha1_hmac( S2, hs, tmp, 20,      tmp );
00243 
00244         k = ( i + 20 > dlen ) ? dlen % 20 : 20;
00245 
00246         for( j = 0; j < k; j++ )
00247             dstbuf[i + j] = (unsigned char)( dstbuf[i + j] ^ h_i[j] );
00248     }
00249 
00250     polarssl_zeroize( tmp, sizeof( tmp ) );
00251     polarssl_zeroize( h_i, sizeof( h_i ) );
00252 
00253     return( 0 );
00254 }
00255 #endif /* POLARSSL_SSL_PROTO_TLS1) || POLARSSL_SSL_PROTO_TLS1_1 */
00256 
00257 #if defined(POLARSSL_SSL_PROTO_TLS1_2)
00258 #if defined(POLARSSL_SHA256_C)
00259 static int tls_prf_sha256( const unsigned char *secret, size_t slen,
00260                            const char *label,
00261                            const unsigned char *random, size_t rlen,
00262                            unsigned char *dstbuf, size_t dlen )
00263 {
00264     size_t nb;
00265     size_t i, j, k;
00266     unsigned char tmp[128];
00267     unsigned char h_i[32];
00268 
00269     if( sizeof( tmp ) < 32 + strlen( label ) + rlen )
00270         return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
00271 
00272     nb = strlen( label );
00273     memcpy( tmp + 32, label, nb );
00274     memcpy( tmp + 32 + nb, random, rlen );
00275     nb += rlen;
00276 
00277     /*
00278      * Compute P_<hash>(secret, label + random)[0..dlen]
00279      */
00280     sha256_hmac( secret, slen, tmp + 32, nb, tmp, 0 );
00281 
00282     for( i = 0; i < dlen; i += 32 )
00283     {
00284         sha256_hmac( secret, slen, tmp, 32 + nb, h_i, 0 );
00285         sha256_hmac( secret, slen, tmp, 32,      tmp, 0 );
00286 
00287         k = ( i + 32 > dlen ) ? dlen % 32 : 32;
00288 
00289         for( j = 0; j < k; j++ )
00290             dstbuf[i + j]  = h_i[j];
00291     }
00292 
00293     polarssl_zeroize( tmp, sizeof( tmp ) );
00294     polarssl_zeroize( h_i, sizeof( h_i ) );
00295 
00296     return( 0 );
00297 }
00298 #endif /* POLARSSL_SHA256_C */
00299 
00300 #if defined(POLARSSL_SHA512_C)
00301 static int tls_prf_sha384( const unsigned char *secret, size_t slen,
00302                            const char *label,
00303                            const unsigned char *random, size_t rlen,
00304                            unsigned char *dstbuf, size_t dlen )
00305 {
00306     size_t nb;
00307     size_t i, j, k;
00308     unsigned char tmp[128];
00309     unsigned char h_i[48];
00310 
00311     if( sizeof( tmp ) < 48 + strlen( label ) + rlen )
00312         return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
00313 
00314     nb = strlen( label );
00315     memcpy( tmp + 48, label, nb );
00316     memcpy( tmp + 48 + nb, random, rlen );
00317     nb += rlen;
00318 
00319     /*
00320      * Compute P_<hash>(secret, label + random)[0..dlen]
00321      */
00322     sha512_hmac( secret, slen, tmp + 48, nb, tmp, 1 );
00323 
00324     for( i = 0; i < dlen; i += 48 )
00325     {
00326         sha512_hmac( secret, slen, tmp, 48 + nb, h_i, 1 );
00327         sha512_hmac( secret, slen, tmp, 48,      tmp, 1 );
00328 
00329         k = ( i + 48 > dlen ) ? dlen % 48 : 48;
00330 
00331         for( j = 0; j < k; j++ )
00332             dstbuf[i + j]  = h_i[j];
00333     }
00334 
00335     polarssl_zeroize( tmp, sizeof( tmp ) );
00336     polarssl_zeroize( h_i, sizeof( h_i ) );
00337 
00338     return( 0 );
00339 }
00340 #endif /* POLARSSL_SHA512_C */
00341 #endif /* POLARSSL_SSL_PROTO_TLS1_2 */
00342 
00343 static void ssl_update_checksum_start( ssl_context *, const unsigned char *, size_t );
00344 
00345 #if defined(POLARSSL_SSL_PROTO_SSL3) || defined(POLARSSL_SSL_PROTO_TLS1) || \
00346     defined(POLARSSL_SSL_PROTO_TLS1_1)
00347 static void ssl_update_checksum_md5sha1( ssl_context *, const unsigned char *, size_t );
00348 #endif
00349 
00350 #if defined(POLARSSL_SSL_PROTO_SSL3)
00351 static void ssl_calc_verify_ssl( ssl_context *, unsigned char * );
00352 static void ssl_calc_finished_ssl( ssl_context *, unsigned char *, int );
00353 #endif
00354 
00355 #if defined(POLARSSL_SSL_PROTO_TLS1) || defined(POLARSSL_SSL_PROTO_TLS1_1)
00356 static void ssl_calc_verify_tls( ssl_context *, unsigned char * );
00357 static void ssl_calc_finished_tls( ssl_context *, unsigned char *, int );
00358 #endif
00359 
00360 #if defined(POLARSSL_SSL_PROTO_TLS1_2)
00361 #if defined(POLARSSL_SHA256_C)
00362 static void ssl_update_checksum_sha256( ssl_context *, const unsigned char *, size_t );
00363 static void ssl_calc_verify_tls_sha256( ssl_context *,unsigned char * );
00364 static void ssl_calc_finished_tls_sha256( ssl_context *,unsigned char *, int );
00365 #endif
00366 
00367 #if defined(POLARSSL_SHA512_C)
00368 static void ssl_update_checksum_sha384( ssl_context *, const unsigned char *, size_t );
00369 static void ssl_calc_verify_tls_sha384( ssl_context *, unsigned char * );
00370 static void ssl_calc_finished_tls_sha384( ssl_context *, unsigned char *, int );
00371 #endif
00372 #endif /* POLARSSL_SSL_PROTO_TLS1_2 */
00373 
00374 int ssl_derive_keys( ssl_context *ssl )
00375 {
00376     int ret = 0;
00377     unsigned char tmp[64];
00378     unsigned char keyblk[256];
00379     unsigned char *key1;
00380     unsigned char *key2;
00381     unsigned char *mac_enc;
00382     unsigned char *mac_dec;
00383     size_t iv_copy_len;
00384     const cipher_info_t *cipher_info;
00385     const md_info_t *md_info;
00386 
00387     ssl_session *session = ssl->session_negotiate;
00388     ssl_transform *transform = ssl->transform_negotiate;
00389     ssl_handshake_params *handshake = ssl->handshake;
00390 
00391     SSL_DEBUG_MSG( 2, ( "=> derive keys" ) );
00392 
00393     cipher_info = cipher_info_from_type( transform->ciphersuite_info->cipher );
00394     if( cipher_info == NULL )
00395     {
00396         SSL_DEBUG_MSG( 1, ( "cipher info for %d not found",
00397                             transform->ciphersuite_info->cipher ) );
00398         return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
00399     }
00400 
00401     md_info = md_info_from_type( transform->ciphersuite_info->mac );
00402     if( md_info == NULL )
00403     {
00404         SSL_DEBUG_MSG( 1, ( "md info for %d not found",
00405                             transform->ciphersuite_info->mac ) );
00406         return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
00407     }
00408 
00409     /*
00410      * Set appropriate PRF function and other SSL / TLS / TLS1.2 functions
00411      */
00412 #if defined(POLARSSL_SSL_PROTO_SSL3)
00413     if( ssl->minor_ver == SSL_MINOR_VERSION_0 )
00414     {
00415         handshake->tls_prf = ssl3_prf;
00416         handshake->calc_verify = ssl_calc_verify_ssl;
00417         handshake->calc_finished = ssl_calc_finished_ssl;
00418     }
00419     else
00420 #endif
00421 #if defined(POLARSSL_SSL_PROTO_TLS1) || defined(POLARSSL_SSL_PROTO_TLS1_1)
00422     if( ssl->minor_ver < SSL_MINOR_VERSION_3 )
00423     {
00424         handshake->tls_prf = tls1_prf;
00425         handshake->calc_verify = ssl_calc_verify_tls;
00426         handshake->calc_finished = ssl_calc_finished_tls;
00427     }
00428     else
00429 #endif
00430 #if defined(POLARSSL_SSL_PROTO_TLS1_2)
00431 #if defined(POLARSSL_SHA512_C)
00432     if( ssl->minor_ver == SSL_MINOR_VERSION_3 &&
00433         transform->ciphersuite_info->mac == POLARSSL_MD_SHA384 )
00434     {
00435         handshake->tls_prf = tls_prf_sha384;
00436         handshake->calc_verify = ssl_calc_verify_tls_sha384;
00437         handshake->calc_finished = ssl_calc_finished_tls_sha384;
00438     }
00439     else
00440 #endif
00441 #if defined(POLARSSL_SHA256_C)
00442     if( ssl->minor_ver == SSL_MINOR_VERSION_3 )
00443     {
00444         handshake->tls_prf = tls_prf_sha256;
00445         handshake->calc_verify = ssl_calc_verify_tls_sha256;
00446         handshake->calc_finished = ssl_calc_finished_tls_sha256;
00447     }
00448     else
00449 #endif
00450 #endif /* POLARSSL_SSL_PROTO_TLS1_2 */
00451     {
00452         SSL_DEBUG_MSG( 1, ( "should never happen" ) );
00453         return( POLARSSL_ERR_SSL_INTERNAL_ERROR );
00454     }
00455 
00456     /*
00457      * SSLv3:
00458      *   master =
00459      *     MD5( premaster + SHA1( 'A'   + premaster + randbytes ) ) +
00460      *     MD5( premaster + SHA1( 'BB'  + premaster + randbytes ) ) +
00461      *     MD5( premaster + SHA1( 'CCC' + premaster + randbytes ) )
00462      *
00463      * TLSv1+:
00464      *   master = PRF( premaster, "master secret", randbytes )[0..47]
00465      */
00466     if( handshake->resume == 0 )
00467     {
00468         SSL_DEBUG_BUF( 3, "premaster secret", handshake->premaster,
00469                        handshake->pmslen );
00470 
00471 #if defined(POLARSSL_SSL_EXTENDED_MASTER_SECRET)
00472         if( ssl->handshake->extended_ms == SSL_EXTENDED_MS_ENABLED )
00473         {
00474             unsigned char session_hash[48];
00475             size_t hash_len;
00476 
00477             SSL_DEBUG_MSG( 3, ( "using extended master secret" ) );
00478 
00479             ssl->handshake->calc_verify( ssl, session_hash );
00480 
00481 #if defined(POLARSSL_SSL_PROTO_TLS1_2)
00482             if( ssl->minor_ver == SSL_MINOR_VERSION_3 )
00483             {
00484 #if defined(POLARSSL_SHA512_C)
00485                 if( ssl->transform_negotiate->ciphersuite_info->mac ==
00486                     POLARSSL_MD_SHA384 )
00487                 {
00488                     hash_len = 48;
00489                 }
00490                 else
00491 #endif
00492                     hash_len = 32;
00493             }
00494             else
00495 #endif /* POLARSSL_SSL_PROTO_TLS1_2 */
00496                 hash_len = 36;
00497 
00498             SSL_DEBUG_BUF( 3, "session hash", session_hash, hash_len );
00499 
00500             handshake->tls_prf( handshake->premaster, handshake->pmslen,
00501                                 "extended master secret",
00502                                 session_hash, hash_len, session->master, 48 );
00503 
00504         }
00505         else
00506 #endif
00507         handshake->tls_prf( handshake->premaster, handshake->pmslen,
00508                             "master secret",
00509                             handshake->randbytes, 64, session->master, 48 );
00510 
00511 
00512         polarssl_zeroize( handshake->premaster, sizeof(handshake->premaster) );
00513     }
00514     else
00515         SSL_DEBUG_MSG( 3, ( "no premaster (session resumed)" ) );
00516 
00517     /*
00518      * Swap the client and server random values.
00519      */
00520     memcpy( tmp, handshake->randbytes, 64 );
00521     memcpy( handshake->randbytes, tmp + 32, 32 );
00522     memcpy( handshake->randbytes + 32, tmp, 32 );
00523     polarssl_zeroize( tmp, sizeof( tmp ) );
00524 
00525     /*
00526      *  SSLv3:
00527      *    key block =
00528      *      MD5( master + SHA1( 'A'    + master + randbytes ) ) +
00529      *      MD5( master + SHA1( 'BB'   + master + randbytes ) ) +
00530      *      MD5( master + SHA1( 'CCC'  + master + randbytes ) ) +
00531      *      MD5( master + SHA1( 'DDDD' + master + randbytes ) ) +
00532      *      ...
00533      *
00534      *  TLSv1:
00535      *    key block = PRF( master, "key expansion", randbytes )
00536      */
00537     handshake->tls_prf( session->master, 48, "key expansion",
00538                         handshake->randbytes, 64, keyblk, 256 );
00539 
00540     SSL_DEBUG_MSG( 3, ( "ciphersuite = %s",
00541                    ssl_get_ciphersuite_name( session->ciphersuite ) ) );
00542     SSL_DEBUG_BUF( 3, "master secret", session->master, 48 );
00543     SSL_DEBUG_BUF( 4, "random bytes", handshake->randbytes, 64 );
00544     SSL_DEBUG_BUF( 4, "key block", keyblk, 256 );
00545 
00546     polarssl_zeroize( handshake->randbytes, sizeof( handshake->randbytes ) );
00547 
00548     /*
00549      * Determine the appropriate key, IV and MAC length.
00550      */
00551 
00552     transform->keylen = cipher_info->key_length / 8;
00553 
00554     if( cipher_info->mode == POLARSSL_MODE_GCM ||
00555         cipher_info->mode == POLARSSL_MODE_CCM )
00556     {
00557         transform->maclen = 0;
00558 
00559         transform->ivlen = 12;
00560         transform->fixed_ivlen = 4;
00561 
00562         /* Minimum length is expicit IV + tag */
00563         transform->minlen = transform->ivlen - transform->fixed_ivlen
00564                             + ( transform->ciphersuite_info->flags &
00565                                 POLARSSL_CIPHERSUITE_SHORT_TAG ? 8 : 16 );
00566     }
00567     else
00568     {
00569         int ret;
00570 
00571         /* Initialize HMAC contexts */
00572         if( ( ret = md_init_ctx( &transform->md_ctx_enc, md_info ) ) != 0 ||
00573             ( ret = md_init_ctx( &transform->md_ctx_dec, md_info ) ) != 0 )
00574         {
00575             SSL_DEBUG_RET( 1, "md_init_ctx", ret );
00576             return( ret );
00577         }
00578 
00579         /* Get MAC length */
00580         transform->maclen = md_get_size( md_info );
00581 
00582 #if defined(POLARSSL_SSL_TRUNCATED_HMAC)
00583         /*
00584          * If HMAC is to be truncated, we shall keep the leftmost bytes,
00585          * (rfc 6066 page 13 or rfc 2104 section 4),
00586          * so we only need to adjust the length here.
00587          */
00588         if( session->trunc_hmac == SSL_TRUNC_HMAC_ENABLED )
00589             transform->maclen = SSL_TRUNCATED_HMAC_LEN;
00590 #endif /* POLARSSL_SSL_TRUNCATED_HMAC */
00591 
00592         /* IV length */
00593         transform->ivlen = cipher_info->iv_size;
00594 
00595         /* Minimum length */
00596         if( cipher_info->mode == POLARSSL_MODE_STREAM )
00597             transform->minlen = transform->maclen;
00598         else
00599         {
00600             /*
00601              * GenericBlockCipher:
00602              * 1. if EtM is in use: one block plus MAC
00603              *    otherwise: * first multiple of blocklen greater than maclen
00604              * 2. IV except for SSL3 and TLS 1.0
00605              */
00606 #if defined(POLARSSL_SSL_ENCRYPT_THEN_MAC)
00607             if( session->encrypt_then_mac == SSL_ETM_ENABLED )
00608             {
00609                 transform->minlen = transform->maclen
00610                                   + cipher_info->block_size;
00611             }
00612             else
00613 #endif
00614             {
00615                 transform->minlen = transform->maclen
00616                                   + cipher_info->block_size
00617                                   - transform->maclen % cipher_info->block_size;
00618             }
00619 
00620 #if defined(POLARSSL_SSL_PROTO_SSL3) || defined(POLARSSL_SSL_PROTO_TLS1)
00621             if( ssl->minor_ver == SSL_MINOR_VERSION_0 ||
00622                 ssl->minor_ver == SSL_MINOR_VERSION_1 )
00623                 ; /* No need to adjust minlen */
00624             else
00625 #endif
00626 #if defined(POLARSSL_SSL_PROTO_TLS1_1) || defined(POLARSSL_SSL_PROTO_TLS1_2)
00627             if( ssl->minor_ver == SSL_MINOR_VERSION_2 ||
00628                 ssl->minor_ver == SSL_MINOR_VERSION_3 )
00629             {
00630                 transform->minlen += transform->ivlen;
00631             }
00632             else
00633 #endif
00634             {
00635                 SSL_DEBUG_MSG( 1, ( "should never happen" ) );
00636                 return( POLARSSL_ERR_SSL_INTERNAL_ERROR );
00637             }
00638         }
00639     }
00640 
00641     SSL_DEBUG_MSG( 3, ( "keylen: %d, minlen: %d, ivlen: %d, maclen: %d",
00642                    transform->keylen, transform->minlen, transform->ivlen,
00643                    transform->maclen ) );
00644 
00645     /*
00646      * Finally setup the cipher contexts, IVs and MAC secrets.
00647      */
00648 #if defined(POLARSSL_SSL_CLI_C)
00649     if( ssl->endpoint == SSL_IS_CLIENT )
00650     {
00651         key1 = keyblk + transform->maclen * 2;
00652         key2 = keyblk + transform->maclen * 2 + transform->keylen;
00653 
00654         mac_enc = keyblk;
00655         mac_dec = keyblk + transform->maclen;
00656 
00657         /*
00658          * This is not used in TLS v1.1.
00659          */
00660         iv_copy_len = ( transform->fixed_ivlen ) ?
00661                             transform->fixed_ivlen : transform->ivlen;
00662         memcpy( transform->iv_enc, key2 + transform->keylen,  iv_copy_len );
00663         memcpy( transform->iv_dec, key2 + transform->keylen + iv_copy_len,
00664                 iv_copy_len );
00665     }
00666     else
00667 #endif /* POLARSSL_SSL_CLI_C */
00668 #if defined(POLARSSL_SSL_SRV_C)
00669     if( ssl->endpoint == SSL_IS_SERVER )
00670     {
00671         key1 = keyblk + transform->maclen * 2 + transform->keylen;
00672         key2 = keyblk + transform->maclen * 2;
00673 
00674         mac_enc = keyblk + transform->maclen;
00675         mac_dec = keyblk;
00676 
00677         /*
00678          * This is not used in TLS v1.1.
00679          */
00680         iv_copy_len = ( transform->fixed_ivlen ) ?
00681                             transform->fixed_ivlen : transform->ivlen;
00682         memcpy( transform->iv_dec, key1 + transform->keylen,  iv_copy_len );
00683         memcpy( transform->iv_enc, key1 + transform->keylen + iv_copy_len,
00684                 iv_copy_len );
00685     }
00686     else
00687 #endif /* POLARSSL_SSL_SRV_C */
00688     {
00689         SSL_DEBUG_MSG( 1, ( "should never happen" ) );
00690         return( POLARSSL_ERR_SSL_INTERNAL_ERROR );
00691     }
00692 
00693 #if defined(POLARSSL_SSL_PROTO_SSL3)
00694     if( ssl->minor_ver == SSL_MINOR_VERSION_0 )
00695     {
00696         if( transform->maclen > sizeof transform->mac_enc )
00697         {
00698             SSL_DEBUG_MSG( 1, ( "should never happen" ) );
00699             return( POLARSSL_ERR_SSL_INTERNAL_ERROR );
00700         }
00701 
00702         memcpy( transform->mac_enc, mac_enc, transform->maclen );
00703         memcpy( transform->mac_dec, mac_dec, transform->maclen );
00704     }
00705     else
00706 #endif /* POLARSSL_SSL_PROTO_SSL3 */
00707 #if defined(POLARSSL_SSL_PROTO_TLS1) || defined(POLARSSL_SSL_PROTO_TLS1_1) || \
00708     defined(POLARSSL_SSL_PROTO_TLS1_2)
00709     if( ssl->minor_ver >= SSL_MINOR_VERSION_1 )
00710     {
00711         md_hmac_starts( &transform->md_ctx_enc, mac_enc, transform->maclen );
00712         md_hmac_starts( &transform->md_ctx_dec, mac_dec, transform->maclen );
00713     }
00714     else
00715 #endif
00716     {
00717         SSL_DEBUG_MSG( 1, ( "should never happen" ) );
00718         return( POLARSSL_ERR_SSL_INTERNAL_ERROR );
00719     }
00720 
00721 #if defined(POLARSSL_SSL_HW_RECORD_ACCEL)
00722     if( ssl_hw_record_init != NULL )
00723     {
00724         int ret = 0;
00725 
00726         SSL_DEBUG_MSG( 2, ( "going for ssl_hw_record_init()" ) );
00727 
00728         if( ( ret = ssl_hw_record_init( ssl, key1, key2, transform->keylen,
00729                                         transform->iv_enc, transform->iv_dec,
00730                                         iv_copy_len,
00731                                         mac_enc, mac_dec,
00732                                         transform->maclen ) ) != 0 )
00733         {
00734             SSL_DEBUG_RET( 1, "ssl_hw_record_init", ret );
00735             return( POLARSSL_ERR_SSL_HW_ACCEL_FAILED );
00736         }
00737     }
00738 #endif /* POLARSSL_SSL_HW_RECORD_ACCEL */
00739 
00740     if( ( ret = cipher_init_ctx( &transform->cipher_ctx_enc,
00741                                  cipher_info ) ) != 0 )
00742     {
00743         SSL_DEBUG_RET( 1, "cipher_init_ctx", ret );
00744         return( ret );
00745     }
00746 
00747     if( ( ret = cipher_init_ctx( &transform->cipher_ctx_dec,
00748                                  cipher_info ) ) != 0 )
00749     {
00750         SSL_DEBUG_RET( 1, "cipher_init_ctx", ret );
00751         return( ret );
00752     }
00753 
00754     if( ( ret = cipher_setkey( &transform->cipher_ctx_enc, key1,
00755                                cipher_info->key_length,
00756                                POLARSSL_ENCRYPT ) ) != 0 )
00757     {
00758         SSL_DEBUG_RET( 1, "cipher_setkey", ret );
00759         return( ret );
00760     }
00761 
00762     if( ( ret = cipher_setkey( &transform->cipher_ctx_dec, key2,
00763                                cipher_info->key_length,
00764                                POLARSSL_DECRYPT ) ) != 0 )
00765     {
00766         SSL_DEBUG_RET( 1, "cipher_setkey", ret );
00767         return( ret );
00768     }
00769 
00770 #if defined(POLARSSL_CIPHER_MODE_CBC)
00771     if( cipher_info->mode == POLARSSL_MODE_CBC )
00772     {
00773         if( ( ret = cipher_set_padding_mode( &transform->cipher_ctx_enc,
00774                                              POLARSSL_PADDING_NONE ) ) != 0 )
00775         {
00776             SSL_DEBUG_RET( 1, "cipher_set_padding_mode", ret );
00777             return( ret );
00778         }
00779 
00780         if( ( ret = cipher_set_padding_mode( &transform->cipher_ctx_dec,
00781                                              POLARSSL_PADDING_NONE ) ) != 0 )
00782         {
00783             SSL_DEBUG_RET( 1, "cipher_set_padding_mode", ret );
00784             return( ret );
00785         }
00786     }
00787 #endif /* POLARSSL_CIPHER_MODE_CBC */
00788 
00789     polarssl_zeroize( keyblk, sizeof( keyblk ) );
00790 
00791 #if defined(POLARSSL_ZLIB_SUPPORT)
00792     // Initialize compression
00793     //
00794     if( session->compression == SSL_COMPRESS_DEFLATE )
00795     {
00796         if( ssl->compress_buf == NULL )
00797         {
00798             SSL_DEBUG_MSG( 3, ( "Allocating compression buffer" ) );
00799             ssl->compress_buf = polarssl_malloc( SSL_BUFFER_LEN );
00800             if( ssl->compress_buf == NULL )
00801             {
00802                 SSL_DEBUG_MSG( 1, ( "malloc(%d bytes) failed",
00803                                     SSL_BUFFER_LEN ) );
00804                 return( POLARSSL_ERR_SSL_MALLOC_FAILED );
00805             }
00806         }
00807 
00808         SSL_DEBUG_MSG( 3, ( "Initializing zlib states" ) );
00809 
00810         memset( &transform->ctx_deflate, 0, sizeof( transform->ctx_deflate ) );
00811         memset( &transform->ctx_inflate, 0, sizeof( transform->ctx_inflate ) );
00812 
00813         if( deflateInit( &transform->ctx_deflate,
00814                          Z_DEFAULT_COMPRESSION )   != Z_OK ||
00815             inflateInit( &transform->ctx_inflate ) != Z_OK )
00816         {
00817             SSL_DEBUG_MSG( 1, ( "Failed to initialize compression" ) );
00818             return( POLARSSL_ERR_SSL_COMPRESSION_FAILED );
00819         }
00820     }
00821 #endif /* POLARSSL_ZLIB_SUPPORT */
00822 
00823     SSL_DEBUG_MSG( 2, ( "<= derive keys" ) );
00824 
00825     return( 0 );
00826 }
00827 
00828 #if defined(POLARSSL_SSL_PROTO_SSL3)
00829 void ssl_calc_verify_ssl( ssl_context *ssl, unsigned char hash[36] )
00830 {
00831     md5_context md5;
00832     sha1_context sha1;
00833     unsigned char pad_1[48];
00834     unsigned char pad_2[48];
00835 
00836     SSL_DEBUG_MSG( 2, ( "=> calc verify ssl" ) );
00837 
00838     memcpy( &md5 , &ssl->handshake->fin_md5 , sizeof(md5_context)  );
00839     memcpy( &sha1, &ssl->handshake->fin_sha1, sizeof(sha1_context) );
00840 
00841     memset( pad_1, 0x36, 48 );
00842     memset( pad_2, 0x5C, 48 );
00843 
00844     md5_update( &md5, ssl->session_negotiate->master, 48 );
00845     md5_update( &md5, pad_1, 48 );
00846     md5_finish( &md5, hash );
00847 
00848     md5_starts( &md5 );
00849     md5_update( &md5, ssl->session_negotiate->master, 48 );
00850     md5_update( &md5, pad_2, 48 );
00851     md5_update( &md5, hash,  16 );
00852     md5_finish( &md5, hash );
00853 
00854     sha1_update( &sha1, ssl->session_negotiate->master, 48 );
00855     sha1_update( &sha1, pad_1, 40 );
00856     sha1_finish( &sha1, hash + 16 );
00857 
00858     sha1_starts( &sha1 );
00859     sha1_update( &sha1, ssl->session_negotiate->master, 48 );
00860     sha1_update( &sha1, pad_2, 40 );
00861     sha1_update( &sha1, hash + 16, 20 );
00862     sha1_finish( &sha1, hash + 16 );
00863 
00864     SSL_DEBUG_BUF( 3, "calculated verify result", hash, 36 );
00865     SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
00866 
00867     md5_free(  &md5  );
00868     sha1_free( &sha1 );
00869 
00870     return;
00871 }
00872 #endif /* POLARSSL_SSL_PROTO_SSL3 */
00873 
00874 #if defined(POLARSSL_SSL_PROTO_TLS1) || defined(POLARSSL_SSL_PROTO_TLS1_1)
00875 void ssl_calc_verify_tls( ssl_context *ssl, unsigned char hash[36] )
00876 {
00877     md5_context md5;
00878     sha1_context sha1;
00879 
00880     SSL_DEBUG_MSG( 2, ( "=> calc verify tls" ) );
00881 
00882     memcpy( &md5 , &ssl->handshake->fin_md5 , sizeof(md5_context)  );
00883     memcpy( &sha1, &ssl->handshake->fin_sha1, sizeof(sha1_context) );
00884 
00885      md5_finish( &md5,  hash );
00886     sha1_finish( &sha1, hash + 16 );
00887 
00888     SSL_DEBUG_BUF( 3, "calculated verify result", hash, 36 );
00889     SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
00890 
00891     md5_free(  &md5  );
00892     sha1_free( &sha1 );
00893 
00894     return;
00895 }
00896 #endif /* POLARSSL_SSL_PROTO_TLS1 || POLARSSL_SSL_PROTO_TLS1_1 */
00897 
00898 #if defined(POLARSSL_SSL_PROTO_TLS1_2)
00899 #if defined(POLARSSL_SHA256_C)
00900 void ssl_calc_verify_tls_sha256( ssl_context *ssl, unsigned char hash[32] )
00901 {
00902     sha256_context sha256;
00903 
00904     SSL_DEBUG_MSG( 2, ( "=> calc verify sha256" ) );
00905 
00906     memcpy( &sha256, &ssl->handshake->fin_sha256, sizeof(sha256_context) );
00907     sha256_finish( &sha256, hash );
00908 
00909     SSL_DEBUG_BUF( 3, "calculated verify result", hash, 32 );
00910     SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
00911 
00912     sha256_free( &sha256 );
00913 
00914     return;
00915 }
00916 #endif /* POLARSSL_SHA256_C */
00917 
00918 #if defined(POLARSSL_SHA512_C)
00919 void ssl_calc_verify_tls_sha384( ssl_context *ssl, unsigned char hash[48] )
00920 {
00921     sha512_context sha512;
00922 
00923     SSL_DEBUG_MSG( 2, ( "=> calc verify sha384" ) );
00924 
00925     memcpy( &sha512, &ssl->handshake->fin_sha512, sizeof(sha512_context) );
00926     sha512_finish( &sha512, hash );
00927 
00928     SSL_DEBUG_BUF( 3, "calculated verify result", hash, 48 );
00929     SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
00930 
00931     sha512_free( &sha512 );
00932 
00933     return;
00934 }
00935 #endif /* POLARSSL_SHA512_C */
00936 #endif /* POLARSSL_SSL_PROTO_TLS1_2 */
00937 
00938 #if defined(POLARSSL_KEY_EXCHANGE__SOME__PSK_ENABLED)
00939 int ssl_psk_derive_premaster( ssl_context *ssl, key_exchange_type_t key_ex )
00940 {
00941     unsigned char *p = ssl->handshake->premaster;
00942     unsigned char *end = p + sizeof( ssl->handshake->premaster );
00943 
00944     /*
00945      * PMS = struct {
00946      *     opaque other_secret<0..2^16-1>;
00947      *     opaque psk<0..2^16-1>;
00948      * };
00949      * with "other_secret" depending on the particular key exchange
00950      */
00951 #if defined(POLARSSL_KEY_EXCHANGE_PSK_ENABLED)
00952     if( key_ex == POLARSSL_KEY_EXCHANGE_PSK )
00953     {
00954         if( end - p < 2 + (int) ssl->psk_len )
00955             return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
00956 
00957         *(p++) = (unsigned char)( ssl->psk_len >> 8 );
00958         *(p++) = (unsigned char)( ssl->psk_len      );
00959         p += ssl->psk_len;
00960     }
00961     else
00962 #endif /* POLARSSL_KEY_EXCHANGE_PSK_ENABLED */
00963 #if defined(POLARSSL_KEY_EXCHANGE_RSA_PSK_ENABLED)
00964     if( key_ex == POLARSSL_KEY_EXCHANGE_RSA_PSK )
00965     {
00966         /*
00967          * other_secret already set by the ClientKeyExchange message,
00968          * and is 48 bytes long
00969          */
00970         *p++ = 0;
00971         *p++ = 48;
00972         p += 48;
00973     }
00974     else
00975 #endif /* POLARSSL_KEY_EXCHANGE_RSA_PKS_ENABLED */
00976 #if defined(POLARSSL_KEY_EXCHANGE_DHE_PSK_ENABLED)
00977     if( key_ex == POLARSSL_KEY_EXCHANGE_DHE_PSK )
00978     {
00979         int ret;
00980         size_t len = end - ( p + 2 );
00981 
00982         /* Write length only when we know the actual value */
00983         if( ( ret = dhm_calc_secret( &ssl->handshake->dhm_ctx,
00984                                       p + 2, &len,
00985                                       ssl->f_rng, ssl->p_rng ) ) != 0 )
00986         {
00987             SSL_DEBUG_RET( 1, "dhm_calc_secret", ret );
00988             return( ret );
00989         }
00990         *(p++) = (unsigned char)( len >> 8 );
00991         *(p++) = (unsigned char)( len );
00992         p += len;
00993 
00994         SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K  );
00995     }
00996     else
00997 #endif /* POLARSSL_KEY_EXCHANGE_DHE_PSK_ENABLED */
00998 #if defined(POLARSSL_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
00999     if( key_ex == POLARSSL_KEY_EXCHANGE_ECDHE_PSK )
01000     {
01001         int ret;
01002         size_t zlen;
01003 
01004         if( ( ret = ecdh_calc_secret( &ssl->handshake->ecdh_ctx, &zlen,
01005                                        p + 2, end - ( p + 2 ),
01006                                        ssl->f_rng, ssl->p_rng ) ) != 0 )
01007         {
01008             SSL_DEBUG_RET( 1, "ecdh_calc_secret", ret );
01009             return( ret );
01010         }
01011 
01012         *(p++) = (unsigned char)( zlen >> 8 );
01013         *(p++) = (unsigned char)( zlen      );
01014         p += zlen;
01015 
01016         SSL_DEBUG_MPI( 3, "ECDH: z", &ssl->handshake->ecdh_ctx.z );
01017     }
01018     else
01019 #endif /* POLARSSL_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
01020     {
01021         SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01022         return( POLARSSL_ERR_SSL_INTERNAL_ERROR );
01023     }
01024 
01025     /* opaque psk<0..2^16-1>; */
01026     if( end - p < 2 + (int) ssl->psk_len )
01027             return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
01028 
01029     *(p++) = (unsigned char)( ssl->psk_len >> 8 );
01030     *(p++) = (unsigned char)( ssl->psk_len      );
01031     memcpy( p, ssl->psk, ssl->psk_len );
01032     p += ssl->psk_len;
01033 
01034     ssl->handshake->pmslen = p - ssl->handshake->premaster;
01035 
01036     return( 0 );
01037 }
01038 #endif /* POLARSSL_KEY_EXCHANGE__SOME__PSK_ENABLED */
01039 
01040 #if defined(POLARSSL_SSL_PROTO_SSL3)
01041 /*
01042  * SSLv3.0 MAC functions
01043  */
01044 static void ssl_mac( md_context_t *md_ctx, unsigned char *secret,
01045                      unsigned char *buf, size_t len,
01046                      unsigned char *ctr, int type )
01047 {
01048     unsigned char header[11];
01049     unsigned char padding[48];
01050     int padlen;
01051     int md_size = md_get_size( md_ctx->md_info );
01052     int md_type = md_get_type( md_ctx->md_info );
01053 
01054     /* Only MD5 and SHA-1 supported */
01055     if( md_type == POLARSSL_MD_MD5 )
01056         padlen = 48;
01057     else
01058         padlen = 40;
01059 
01060     memcpy( header, ctr, 8 );
01061     header[ 8] = (unsigned char)  type;
01062     header[ 9] = (unsigned char)( len >> 8 );
01063     header[10] = (unsigned char)( len      );
01064 
01065     memset( padding, 0x36, padlen );
01066     md_starts( md_ctx );
01067     md_update( md_ctx, secret,  md_size );
01068     md_update( md_ctx, padding, padlen  );
01069     md_update( md_ctx, header,  11      );
01070     md_update( md_ctx, buf,     len     );
01071     md_finish( md_ctx, buf +    len     );
01072 
01073     memset( padding, 0x5C, padlen );
01074     md_starts( md_ctx );
01075     md_update( md_ctx, secret,    md_size );
01076     md_update( md_ctx, padding,   padlen  );
01077     md_update( md_ctx, buf + len, md_size );
01078     md_finish( md_ctx, buf + len          );
01079 }
01080 #endif /* POLARSSL_SSL_PROTO_SSL3 */
01081 
01082 #if defined(POLARSSL_ARC4_C) || defined(POLARSSL_CIPHER_NULL_CIPHER) ||     \
01083     ( defined(POLARSSL_CIPHER_MODE_CBC) &&                                  \
01084       ( defined(POLARSSL_AES_C) || defined(POLARSSL_CAMELLIA_C) ) )
01085 #define POLARSSL_SOME_MODES_USE_MAC
01086 #endif
01087 
01088 /*
01089  * Encryption/decryption functions
01090  */
01091 static int ssl_encrypt_buf( ssl_context *ssl )
01092 {
01093     size_t i;
01094     cipher_mode_t mode;
01095     int auth_done = 0;
01096 
01097     SSL_DEBUG_MSG( 2, ( "=> encrypt buf" ) );
01098 
01099     if( ssl->session_out == NULL || ssl->transform_out == NULL )
01100     {
01101         SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01102         return( POLARSSL_ERR_SSL_INTERNAL_ERROR );
01103     }
01104 
01105     mode = cipher_get_cipher_mode( &ssl->transform_out->cipher_ctx_enc );
01106 
01107     SSL_DEBUG_BUF( 4, "before encrypt: output payload",
01108                       ssl->out_msg, ssl->out_msglen );
01109 
01110     /*
01111      * Add MAC before if needed
01112      */
01113 #if defined(POLARSSL_SOME_MODES_USE_MAC)
01114     if( mode == POLARSSL_MODE_STREAM ||
01115         ( mode == POLARSSL_MODE_CBC
01116 #if defined(POLARSSL_SSL_ENCRYPT_THEN_MAC)
01117           && ssl->session_out->encrypt_then_mac == SSL_ETM_DISABLED
01118 #endif
01119         ) )
01120     {
01121 #if defined(POLARSSL_SSL_PROTO_SSL3)
01122         if( ssl->minor_ver == SSL_MINOR_VERSION_0 )
01123         {
01124             ssl_mac( &ssl->transform_out->md_ctx_enc,
01125                       ssl->transform_out->mac_enc,
01126                       ssl->out_msg, ssl->out_msglen,
01127                       ssl->out_ctr, ssl->out_msgtype );
01128         }
01129         else
01130 #endif
01131 #if defined(POLARSSL_SSL_PROTO_TLS1) || defined(POLARSSL_SSL_PROTO_TLS1_1) || \
01132         defined(POLARSSL_SSL_PROTO_TLS1_2)
01133         if( ssl->minor_ver >= SSL_MINOR_VERSION_1 )
01134         {
01135             md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_ctr, 13 );
01136             md_hmac_update( &ssl->transform_out->md_ctx_enc,
01137                              ssl->out_msg, ssl->out_msglen );
01138             md_hmac_finish( &ssl->transform_out->md_ctx_enc,
01139                              ssl->out_msg + ssl->out_msglen );
01140             md_hmac_reset( &ssl->transform_out->md_ctx_enc );
01141         }
01142         else
01143 #endif
01144         {
01145             SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01146             return( POLARSSL_ERR_SSL_INTERNAL_ERROR );
01147         }
01148 
01149         SSL_DEBUG_BUF( 4, "computed mac",
01150                        ssl->out_msg + ssl->out_msglen,
01151                        ssl->transform_out->maclen );
01152 
01153         ssl->out_msglen += ssl->transform_out->maclen;
01154         auth_done++;
01155     }
01156 #endif /* AEAD not the only option */
01157 
01158     /*
01159      * Encrypt
01160      */
01161 #if defined(POLARSSL_ARC4_C) || defined(POLARSSL_CIPHER_NULL_CIPHER)
01162     if( mode == POLARSSL_MODE_STREAM )
01163     {
01164         int ret;
01165         size_t olen = 0;
01166 
01167         SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
01168                             "including %d bytes of padding",
01169                        ssl->out_msglen, 0 ) );
01170 
01171         if( ( ret = cipher_crypt( &ssl->transform_out->cipher_ctx_enc,
01172                                    ssl->transform_out->iv_enc,
01173                                    ssl->transform_out->ivlen,
01174                                    ssl->out_msg, ssl->out_msglen,
01175                                    ssl->out_msg, &olen ) ) != 0 )
01176         {
01177             SSL_DEBUG_RET( 1, "cipher_crypt", ret );
01178             return( ret );
01179         }
01180 
01181         if( ssl->out_msglen != olen )
01182         {
01183             SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01184             return( POLARSSL_ERR_SSL_INTERNAL_ERROR );
01185         }
01186     }
01187     else
01188 #endif /* POLARSSL_ARC4_C || POLARSSL_CIPHER_NULL_CIPHER */
01189 #if defined(POLARSSL_GCM_C) || defined(POLARSSL_CCM_C)
01190     if( mode == POLARSSL_MODE_GCM ||
01191         mode == POLARSSL_MODE_CCM )
01192     {
01193         int ret;
01194         size_t enc_msglen, olen;
01195         unsigned char *enc_msg;
01196         unsigned char add_data[13];
01197         unsigned char taglen = ssl->transform_out->ciphersuite_info->flags &
01198                                POLARSSL_CIPHERSUITE_SHORT_TAG ? 8 : 16;
01199 
01200         memcpy( add_data, ssl->out_ctr, 8 );
01201         add_data[8]  = ssl->out_msgtype;
01202         add_data[9]  = ssl->major_ver;
01203         add_data[10] = ssl->minor_ver;
01204         add_data[11] = ( ssl->out_msglen >> 8 ) & 0xFF;
01205         add_data[12] = ssl->out_msglen & 0xFF;
01206 
01207         SSL_DEBUG_BUF( 4, "additional data used for AEAD",
01208                        add_data, 13 );
01209 
01210         /*
01211          * Generate IV
01212          */
01213 #if defined(POLARSSL_SSL_AEAD_RANDOM_IV)
01214         ret = ssl->f_rng( ssl->p_rng,
01215                 ssl->transform_out->iv_enc + ssl->transform_out->fixed_ivlen,
01216                 ssl->transform_out->ivlen - ssl->transform_out->fixed_ivlen );
01217         if( ret != 0 )
01218             return( ret );
01219 
01220         memcpy( ssl->out_iv,
01221                 ssl->transform_out->iv_enc + ssl->transform_out->fixed_ivlen,
01222                 ssl->transform_out->ivlen - ssl->transform_out->fixed_ivlen );
01223 #else
01224         if( ssl->transform_out->ivlen - ssl->transform_out->fixed_ivlen != 8 )
01225         {
01226             /* Reminder if we ever add an AEAD mode with a different size */
01227             SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01228             return( POLARSSL_ERR_SSL_INTERNAL_ERROR );
01229         }
01230 
01231         memcpy( ssl->transform_out->iv_enc + ssl->transform_out->fixed_ivlen,
01232                              ssl->out_ctr, 8 );
01233         memcpy( ssl->out_iv, ssl->out_ctr, 8 );
01234 #endif
01235 
01236         SSL_DEBUG_BUF( 4, "IV used", ssl->out_iv,
01237                 ssl->transform_out->ivlen - ssl->transform_out->fixed_ivlen );
01238 
01239         /*
01240          * Fix pointer positions and message length with added IV
01241          */
01242         enc_msg = ssl->out_msg;
01243         enc_msglen = ssl->out_msglen;
01244         ssl->out_msglen += ssl->transform_out->ivlen -
01245                            ssl->transform_out->fixed_ivlen;
01246 
01247         SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
01248                             "including %d bytes of padding",
01249                        ssl->out_msglen, 0 ) );
01250 
01251         /*
01252          * Encrypt and authenticate
01253          */
01254         if( ( ret = cipher_auth_encrypt( &ssl->transform_out->cipher_ctx_enc,
01255                                          ssl->transform_out->iv_enc,
01256                                          ssl->transform_out->ivlen,
01257                                          add_data, 13,
01258                                          enc_msg, enc_msglen,
01259                                          enc_msg, &olen,
01260                                          enc_msg + enc_msglen, taglen ) ) != 0 )
01261         {
01262             SSL_DEBUG_RET( 1, "cipher_auth_encrypt", ret );
01263             return( ret );
01264         }
01265 
01266         if( olen != enc_msglen )
01267         {
01268             SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01269             return( POLARSSL_ERR_SSL_INTERNAL_ERROR );
01270         }
01271 
01272         ssl->out_msglen += taglen;
01273         auth_done++;
01274 
01275         SSL_DEBUG_BUF( 4, "after encrypt: tag", enc_msg + enc_msglen, taglen );
01276     }
01277     else
01278 #endif /* POLARSSL_GCM_C || POLARSSL_CCM_C */
01279 #if defined(POLARSSL_CIPHER_MODE_CBC) &&                                    \
01280     ( defined(POLARSSL_AES_C) || defined(POLARSSL_CAMELLIA_C) )
01281     if( mode == POLARSSL_MODE_CBC )
01282     {
01283         int ret;
01284         unsigned char *enc_msg;
01285         size_t enc_msglen, padlen, olen = 0;
01286 
01287         padlen = ssl->transform_out->ivlen - ( ssl->out_msglen + 1 ) %
01288                  ssl->transform_out->ivlen;
01289         if( padlen == ssl->transform_out->ivlen )
01290             padlen = 0;
01291 
01292         for( i = 0; i <= padlen; i++ )
01293             ssl->out_msg[ssl->out_msglen + i] = (unsigned char) padlen;
01294 
01295         ssl->out_msglen += padlen + 1;
01296 
01297         enc_msglen = ssl->out_msglen;
01298         enc_msg = ssl->out_msg;
01299 
01300 #if defined(POLARSSL_SSL_PROTO_TLS1_1) || defined(POLARSSL_SSL_PROTO_TLS1_2)
01301         /*
01302          * Prepend per-record IV for block cipher in TLS v1.1 and up as per
01303          * Method 1 (6.2.3.2. in RFC4346 and RFC5246)
01304          */
01305         if( ssl->minor_ver >= SSL_MINOR_VERSION_2 )
01306         {
01307             /*
01308              * Generate IV
01309              */
01310             int ret = ssl->f_rng( ssl->p_rng, ssl->transform_out->iv_enc,
01311                                   ssl->transform_out->ivlen );
01312             if( ret != 0 )
01313                 return( ret );
01314 
01315             memcpy( ssl->out_iv, ssl->transform_out->iv_enc,
01316                     ssl->transform_out->ivlen );
01317 
01318             /*
01319              * Fix pointer positions and message length with added IV
01320              */
01321             enc_msg = ssl->out_msg;
01322             enc_msglen = ssl->out_msglen;
01323             ssl->out_msglen += ssl->transform_out->ivlen;
01324         }
01325 #endif /* POLARSSL_SSL_PROTO_TLS1_1 || POLARSSL_SSL_PROTO_TLS1_2 */
01326 
01327         SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
01328                             "including %d bytes of IV and %d bytes of padding",
01329                             ssl->out_msglen, ssl->transform_out->ivlen,
01330                             padlen + 1 ) );
01331 
01332         if( ( ret = cipher_crypt( &ssl->transform_out->cipher_ctx_enc,
01333                                    ssl->transform_out->iv_enc,
01334                                    ssl->transform_out->ivlen,
01335                                    enc_msg, enc_msglen,
01336                                    enc_msg, &olen ) ) != 0 )
01337         {
01338             SSL_DEBUG_RET( 1, "cipher_crypt", ret );
01339             return( ret );
01340         }
01341 
01342         if( enc_msglen != olen )
01343         {
01344             SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01345             return( POLARSSL_ERR_SSL_INTERNAL_ERROR );
01346         }
01347 
01348 #if defined(POLARSSL_SSL_PROTO_SSL3) || defined(POLARSSL_SSL_PROTO_TLS1)
01349         if( ssl->minor_ver < SSL_MINOR_VERSION_2 )
01350         {
01351             /*
01352              * Save IV in SSL3 and TLS1
01353              */
01354             memcpy( ssl->transform_out->iv_enc,
01355                     ssl->transform_out->cipher_ctx_enc.iv,
01356                     ssl->transform_out->ivlen );
01357         }
01358 #endif
01359 
01360 #if defined(POLARSSL_SSL_ENCRYPT_THEN_MAC)
01361         if( auth_done == 0 )
01362         {
01363             /*
01364              * MAC(MAC_write_key, seq_num +
01365              *     TLSCipherText.type +
01366              *     TLSCipherText.version +
01367              *     length_of( (IV +) ENC(...) ) +
01368              *     IV + // except for TLS 1.0
01369              *     ENC(content + padding + padding_length));
01370              */
01371             unsigned char pseudo_hdr[13];
01372 
01373             SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) );
01374 
01375             memcpy( pseudo_hdr +  0, ssl->out_ctr, 8 );
01376             memcpy( pseudo_hdr +  8, ssl->out_hdr, 3 );
01377             pseudo_hdr[11] = (unsigned char)( ( ssl->out_msglen >> 8 ) & 0xFF );
01378             pseudo_hdr[12] = (unsigned char)( ( ssl->out_msglen      ) & 0xFF );
01379 
01380             SSL_DEBUG_BUF( 4, "MAC'd meta-data", pseudo_hdr, 13 );
01381 
01382             md_hmac_update( &ssl->transform_out->md_ctx_enc, pseudo_hdr, 13 );
01383             md_hmac_update( &ssl->transform_out->md_ctx_enc,
01384                              ssl->out_iv, ssl->out_msglen );
01385             md_hmac_finish( &ssl->transform_out->md_ctx_enc,
01386                              ssl->out_iv + ssl->out_msglen );
01387             md_hmac_reset( &ssl->transform_out->md_ctx_enc );
01388 
01389             ssl->out_msglen += ssl->transform_out->maclen;
01390             auth_done++;
01391         }
01392 #endif /* POLARSSL_SSL_ENCRYPT_THEN_MAC */
01393     }
01394     else
01395 #endif /* POLARSSL_CIPHER_MODE_CBC &&
01396           ( POLARSSL_AES_C || POLARSSL_CAMELLIA_C ) */
01397     {
01398         SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01399         return( POLARSSL_ERR_SSL_INTERNAL_ERROR );
01400     }
01401 
01402     /* Make extra sure authentication was performed, exactly once */
01403     if( auth_done != 1 )
01404     {
01405         SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01406         return( POLARSSL_ERR_SSL_INTERNAL_ERROR );
01407     }
01408 
01409     for( i = 8; i > 0; i-- )
01410         if( ++ssl->out_ctr[i - 1] != 0 )
01411             break;
01412 
01413     /* The loops goes to its end iff the counter is wrapping */
01414     if( i == 0 )
01415     {
01416         SSL_DEBUG_MSG( 1, ( "outgoing message counter would wrap" ) );
01417         return( POLARSSL_ERR_SSL_COUNTER_WRAPPING );
01418     }
01419 
01420     SSL_DEBUG_MSG( 2, ( "<= encrypt buf" ) );
01421 
01422     return( 0 );
01423 }
01424 
01425 #define POLARSSL_SSL_MAX_MAC_SIZE   48
01426 
01427 static int ssl_decrypt_buf( ssl_context *ssl )
01428 {
01429     size_t i;
01430     cipher_mode_t mode;
01431     int auth_done = 0;
01432 #if defined(POLARSSL_SOME_MODES_USE_MAC)
01433     size_t padlen = 0, correct = 1;
01434 #endif
01435 
01436     SSL_DEBUG_MSG( 2, ( "=> decrypt buf" ) );
01437 
01438     if( ssl->session_in == NULL || ssl->transform_in == NULL )
01439     {
01440         SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01441         return( POLARSSL_ERR_SSL_INTERNAL_ERROR );
01442     }
01443 
01444     mode = cipher_get_cipher_mode( &ssl->transform_in->cipher_ctx_dec );
01445 
01446     if( ssl->in_msglen < ssl->transform_in->minlen )
01447     {
01448         SSL_DEBUG_MSG( 1, ( "in_msglen (%d) < minlen (%d)",
01449                        ssl->in_msglen, ssl->transform_in->minlen ) );
01450         return( POLARSSL_ERR_SSL_INVALID_MAC );
01451     }
01452 
01453 #if defined(POLARSSL_ARC4_C) || defined(POLARSSL_CIPHER_NULL_CIPHER)
01454     if( mode == POLARSSL_MODE_STREAM )
01455     {
01456         int ret;
01457         size_t olen = 0;
01458 
01459         padlen = 0;
01460 
01461         if( ( ret = cipher_crypt( &ssl->transform_in->cipher_ctx_dec,
01462                                    ssl->transform_in->iv_dec,
01463                                    ssl->transform_in->ivlen,
01464                                    ssl->in_msg, ssl->in_msglen,
01465                                    ssl->in_msg, &olen ) ) != 0 )
01466         {
01467             SSL_DEBUG_RET( 1, "cipher_crypt", ret );
01468             return( ret );
01469         }
01470 
01471         if( ssl->in_msglen != olen )
01472         {
01473             SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01474             return( POLARSSL_ERR_SSL_INTERNAL_ERROR );
01475         }
01476     }
01477     else
01478 #endif /* POLARSSL_ARC4_C || POLARSSL_CIPHER_NULL_CIPHER */
01479 #if defined(POLARSSL_GCM_C) || defined(POLARSSL_CCM_C)
01480     if( mode == POLARSSL_MODE_GCM ||
01481         mode == POLARSSL_MODE_CCM )
01482     {
01483         int ret;
01484         size_t dec_msglen, olen;
01485         unsigned char *dec_msg;
01486         unsigned char *dec_msg_result;
01487         unsigned char add_data[13];
01488         unsigned char taglen = ssl->transform_in->ciphersuite_info->flags &
01489                                POLARSSL_CIPHERSUITE_SHORT_TAG ? 8 : 16;
01490         unsigned char explicit_iv_len =  ssl->transform_in->ivlen -
01491                                          ssl->transform_in->fixed_ivlen;
01492 
01493         if( ssl->in_msglen < (size_t) explicit_iv_len + taglen )
01494         {
01495             SSL_DEBUG_MSG( 1, ( "msglen (%d) < explicit_iv_len (%d) "
01496                                 "+ taglen (%d)", ssl->in_msglen,
01497                                 explicit_iv_len, taglen ) );
01498             return( POLARSSL_ERR_SSL_INVALID_MAC );
01499         }
01500         dec_msglen = ssl->in_msglen - explicit_iv_len - taglen;
01501 
01502         dec_msg = ssl->in_msg;
01503         dec_msg_result = ssl->in_msg;
01504         ssl->in_msglen = dec_msglen;
01505 
01506         memcpy( add_data, ssl->in_ctr, 8 );
01507         add_data[8]  = ssl->in_msgtype;
01508         add_data[9]  = ssl->major_ver;
01509         add_data[10] = ssl->minor_ver;
01510         add_data[11] = ( ssl->in_msglen >> 8 ) & 0xFF;
01511         add_data[12] = ssl->in_msglen & 0xFF;
01512 
01513         SSL_DEBUG_BUF( 4, "additional data used for AEAD",
01514                        add_data, 13 );
01515 
01516         memcpy( ssl->transform_in->iv_dec + ssl->transform_in->fixed_ivlen,
01517                 ssl->in_iv,
01518                 ssl->transform_in->ivlen - ssl->transform_in->fixed_ivlen );
01519 
01520         SSL_DEBUG_BUF( 4, "IV used", ssl->transform_in->iv_dec,
01521                                      ssl->transform_in->ivlen );
01522         SSL_DEBUG_BUF( 4, "TAG used", dec_msg + dec_msglen, taglen );
01523 
01524         /*
01525          * Decrypt and authenticate
01526          */
01527         if( ( ret = cipher_auth_decrypt( &ssl->transform_in->cipher_ctx_dec,
01528                                          ssl->transform_in->iv_dec,
01529                                          ssl->transform_in->ivlen,
01530                                          add_data, 13,
01531                                          dec_msg, dec_msglen,
01532                                          dec_msg_result, &olen,
01533                                          dec_msg + dec_msglen, taglen ) ) != 0 )
01534         {
01535             SSL_DEBUG_RET( 1, "cipher_auth_decrypt", ret );
01536 
01537             if( ret == POLARSSL_ERR_CIPHER_AUTH_FAILED )
01538                 return( POLARSSL_ERR_SSL_INVALID_MAC );
01539 
01540             return( ret );
01541         }
01542         auth_done++;
01543 
01544         if( olen != dec_msglen )
01545         {
01546             SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01547             return( POLARSSL_ERR_SSL_INTERNAL_ERROR );
01548         }
01549     }
01550     else
01551 #endif /* POLARSSL_GCM_C || POLARSSL_CCM_C */
01552 #if defined(POLARSSL_CIPHER_MODE_CBC) &&                                    \
01553     ( defined(POLARSSL_AES_C) || defined(POLARSSL_CAMELLIA_C) )
01554     if( mode == POLARSSL_MODE_CBC )
01555     {
01556         /*
01557          * Decrypt and check the padding
01558          */
01559         int ret;
01560         unsigned char *dec_msg;
01561         unsigned char *dec_msg_result;
01562         size_t dec_msglen;
01563         size_t minlen = 0;
01564         size_t olen = 0;
01565 
01566         /*
01567          * Check immediate ciphertext sanity
01568          */
01569 #if defined(POLARSSL_SSL_PROTO_TLS1_1) || defined(POLARSSL_SSL_PROTO_TLS1_2)
01570         if( ssl->minor_ver >= SSL_MINOR_VERSION_2 )
01571             minlen += ssl->transform_in->ivlen;
01572 #endif
01573 
01574         if( ssl->in_msglen < minlen + ssl->transform_in->ivlen ||
01575             ssl->in_msglen < minlen + ssl->transform_in->maclen + 1 )
01576         {
01577             SSL_DEBUG_MSG( 1, ( "msglen (%d) < max( ivlen(%d), maclen (%d) "
01578                                 "+ 1 ) ( + expl IV )", ssl->in_msglen,
01579                                 ssl->transform_in->ivlen,
01580                                 ssl->transform_in->maclen ) );
01581             return( POLARSSL_ERR_SSL_INVALID_MAC );
01582         }
01583 
01584         dec_msglen = ssl->in_msglen;
01585         dec_msg = ssl->in_msg;
01586         dec_msg_result = ssl->in_msg;
01587 
01588         /*
01589          * Authenticate before decrypt if enabled
01590          */
01591 #if defined(POLARSSL_SSL_ENCRYPT_THEN_MAC)
01592         if( ssl->session_in->encrypt_then_mac == SSL_ETM_ENABLED )
01593         {
01594             unsigned char computed_mac[POLARSSL_SSL_MAX_MAC_SIZE];
01595             unsigned char pseudo_hdr[13];
01596 
01597             SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) );
01598 
01599             dec_msglen -= ssl->transform_in->maclen;
01600             ssl->in_msglen -= ssl->transform_in->maclen;
01601 
01602             memcpy( pseudo_hdr +  0, ssl->in_ctr, 8 );
01603             memcpy( pseudo_hdr +  8, ssl->in_hdr, 3 );
01604             pseudo_hdr[11] = (unsigned char)( ( ssl->in_msglen >> 8 ) & 0xFF );
01605             pseudo_hdr[12] = (unsigned char)( ( ssl->in_msglen      ) & 0xFF );
01606 
01607             SSL_DEBUG_BUF( 4, "MAC'd meta-data", pseudo_hdr, 13 );
01608 
01609             md_hmac_update( &ssl->transform_in->md_ctx_dec, pseudo_hdr, 13 );
01610             md_hmac_update( &ssl->transform_in->md_ctx_dec,
01611                              ssl->in_iv, ssl->in_msglen );
01612             md_hmac_finish( &ssl->transform_in->md_ctx_dec, computed_mac );
01613             md_hmac_reset( &ssl->transform_in->md_ctx_dec );
01614 
01615             SSL_DEBUG_BUF( 4, "message  mac", ssl->in_iv + ssl->in_msglen,
01616                                               ssl->transform_in->maclen );
01617             SSL_DEBUG_BUF( 4, "computed mac", computed_mac,
01618                                               ssl->transform_in->maclen );
01619 
01620             if( safer_memcmp( ssl->in_iv + ssl->in_msglen, computed_mac,
01621                               ssl->transform_in->maclen ) != 0 )
01622             {
01623                 SSL_DEBUG_MSG( 1, ( "message mac does not match" ) );
01624 
01625                 return( POLARSSL_ERR_SSL_INVALID_MAC );
01626             }
01627             auth_done++;
01628         }
01629 #endif /* POLARSSL_SSL_ENCRYPT_THEN_MAC */
01630 
01631         /*
01632          * Check length sanity
01633          */
01634         if( ssl->in_msglen % ssl->transform_in->ivlen != 0 )
01635         {
01636             SSL_DEBUG_MSG( 1, ( "msglen (%d) %% ivlen (%d) != 0",
01637                            ssl->in_msglen, ssl->transform_in->ivlen ) );
01638             return( POLARSSL_ERR_SSL_INVALID_MAC );
01639         }
01640 
01641 #if defined(POLARSSL_SSL_PROTO_TLS1_1) || defined(POLARSSL_SSL_PROTO_TLS1_2)
01642         /*
01643          * Initialize for prepended IV for block cipher in TLS v1.1 and up
01644          */
01645         if( ssl->minor_ver >= SSL_MINOR_VERSION_2 )
01646         {
01647             dec_msglen -= ssl->transform_in->ivlen;
01648             ssl->in_msglen -= ssl->transform_in->ivlen;
01649 
01650             for( i = 0; i < ssl->transform_in->ivlen; i++ )
01651                 ssl->transform_in->iv_dec[i] = ssl->in_iv[i];
01652         }
01653 #endif /* POLARSSL_SSL_PROTO_TLS1_1 || POLARSSL_SSL_PROTO_TLS1_2 */
01654 
01655         if( ( ret = cipher_crypt( &ssl->transform_in->cipher_ctx_dec,
01656                                    ssl->transform_in->iv_dec,
01657                                    ssl->transform_in->ivlen,
01658                                    dec_msg, dec_msglen,
01659                                    dec_msg_result, &olen ) ) != 0 )
01660         {
01661             SSL_DEBUG_RET( 1, "cipher_crypt", ret );
01662             return( ret );
01663         }
01664 
01665         if( dec_msglen != olen )
01666         {
01667             SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01668             return( POLARSSL_ERR_SSL_INTERNAL_ERROR );
01669         }
01670 
01671 #if defined(POLARSSL_SSL_PROTO_SSL3) || defined(POLARSSL_SSL_PROTO_TLS1)
01672         if( ssl->minor_ver < SSL_MINOR_VERSION_2 )
01673         {
01674             /*
01675              * Save IV in SSL3 and TLS1
01676              */
01677             memcpy( ssl->transform_in->iv_dec,
01678                     ssl->transform_in->cipher_ctx_dec.iv,
01679                     ssl->transform_in->ivlen );
01680         }
01681 #endif
01682 
01683         padlen = 1 + ssl->in_msg[ssl->in_msglen - 1];
01684 
01685         if( ssl->in_msglen < ssl->transform_in->maclen + padlen &&
01686             auth_done == 0 )
01687         {
01688 #if defined(POLARSSL_SSL_DEBUG_ALL)
01689             SSL_DEBUG_MSG( 1, ( "msglen (%d) < maclen (%d) + padlen (%d)",
01690                         ssl->in_msglen, ssl->transform_in->maclen, padlen ) );
01691 #endif
01692             padlen = 0;
01693             correct = 0;
01694         }
01695 
01696 #if defined(POLARSSL_SSL_PROTO_SSL3)
01697         if( ssl->minor_ver == SSL_MINOR_VERSION_0 )
01698         {
01699             if( padlen > ssl->transform_in->ivlen )
01700             {
01701 #if defined(POLARSSL_SSL_DEBUG_ALL)
01702                 SSL_DEBUG_MSG( 1, ( "bad padding length: is %d, "
01703                                     "should be no more than %d",
01704                                padlen, ssl->transform_in->ivlen ) );
01705 #endif
01706                 correct = 0;
01707             }
01708         }
01709         else
01710 #endif /* POLARSSL_SSL_PROTO_SSL3 */
01711 #if defined(POLARSSL_SSL_PROTO_TLS1) || defined(POLARSSL_SSL_PROTO_TLS1_1) || \
01712     defined(POLARSSL_SSL_PROTO_TLS1_2)
01713         if( ssl->minor_ver > SSL_MINOR_VERSION_0 )
01714         {
01715             /*
01716              * TLSv1+: always check the padding up to the first failure
01717              * and fake check up to 256 bytes of padding
01718              */
01719             size_t pad_count = 0, real_count = 1;
01720             size_t padding_idx = ssl->in_msglen - padlen - 1;
01721 
01722             /*
01723              * Padding is guaranteed to be incorrect if:
01724              *   1. padlen >= ssl->in_msglen
01725              *
01726              *   2. padding_idx >= SSL_MAX_CONTENT_LEN +
01727              *                     ssl->transform_in->maclen
01728              *
01729              * In both cases we reset padding_idx to a safe value (0) to
01730              * prevent out-of-buffer reads.
01731              */
01732             correct &= ( ssl->in_msglen >= padlen + 1 );
01733             correct &= ( padding_idx < SSL_MAX_CONTENT_LEN +
01734                                        ssl->transform_in->maclen );
01735 
01736             padding_idx *= correct;
01737 
01738             for( i = 1; i <= 256; i++ )
01739             {
01740                 real_count &= ( i <= padlen );
01741                 pad_count += real_count *
01742                              ( ssl->in_msg[padding_idx + i] == padlen - 1 );
01743             }
01744 
01745             correct &= ( pad_count == padlen ); /* Only 1 on correct padding */
01746 
01747 #if defined(POLARSSL_SSL_DEBUG_ALL)
01748             if( padlen > 0 && correct == 0 )
01749                 SSL_DEBUG_MSG( 1, ( "bad padding byte detected" ) );
01750 #endif
01751             padlen &= correct * 0x1FF;
01752         }
01753         else
01754 #endif /* POLARSSL_SSL_PROTO_TLS1 || POLARSSL_SSL_PROTO_TLS1_1 || \
01755           POLARSSL_SSL_PROTO_TLS1_2 */
01756         {
01757             SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01758             return( POLARSSL_ERR_SSL_INTERNAL_ERROR );
01759         }
01760 
01761         ssl->in_msglen -= padlen;
01762     }
01763     else
01764 #endif /* POLARSSL_CIPHER_MODE_CBC &&
01765           ( POLARSSL_AES_C || POLARSSL_CAMELLIA_C ) */
01766     {
01767         SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01768         return( POLARSSL_ERR_SSL_INTERNAL_ERROR );
01769     }
01770 
01771     SSL_DEBUG_BUF( 4, "raw buffer after decryption",
01772                    ssl->in_msg, ssl->in_msglen );
01773 
01774     /*
01775      * Authenticate if not done yet.
01776      * Compute the MAC regardless of the padding result (RFC4346, CBCTIME).
01777      */
01778 #if defined(POLARSSL_SOME_MODES_USE_MAC)
01779     if( auth_done == 0 )
01780     {
01781         unsigned char tmp[POLARSSL_SSL_MAX_MAC_SIZE];
01782 
01783         ssl->in_msglen -= ssl->transform_in->maclen;
01784 
01785         ssl->in_hdr[3] = (unsigned char)( ssl->in_msglen >> 8 );
01786         ssl->in_hdr[4] = (unsigned char)( ssl->in_msglen      );
01787 
01788         memcpy( tmp, ssl->in_msg + ssl->in_msglen, ssl->transform_in->maclen );
01789 
01790 #if defined(POLARSSL_SSL_PROTO_SSL3)
01791         if( ssl->minor_ver == SSL_MINOR_VERSION_0 )
01792         {
01793             ssl_mac( &ssl->transform_in->md_ctx_dec,
01794                       ssl->transform_in->mac_dec,
01795                       ssl->in_msg, ssl->in_msglen,
01796                       ssl->in_ctr, ssl->in_msgtype );
01797         }
01798         else
01799 #endif /* POLARSSL_SSL_PROTO_SSL3 */
01800 #if defined(POLARSSL_SSL_PROTO_TLS1) || defined(POLARSSL_SSL_PROTO_TLS1_1) || \
01801         defined(POLARSSL_SSL_PROTO_TLS1_2)
01802         if( ssl->minor_ver > SSL_MINOR_VERSION_0 )
01803         {
01804             /*
01805              * Process MAC and always update for padlen afterwards to make
01806              * total time independent of padlen
01807              *
01808              * extra_run compensates MAC check for padlen
01809              *
01810              * Known timing attacks:
01811              *  - Lucky Thirteen (http://www.isg.rhul.ac.uk/tls/TLStiming.pdf)
01812              *
01813              * We use ( ( Lx + 8 ) / 64 ) to handle 'negative Lx' values
01814              * correctly. (We round down instead of up, so -56 is the correct
01815              * value for our calculations instead of -55)
01816              */
01817             size_t j, extra_run = 0;
01818             extra_run = ( 13 + ssl->in_msglen + padlen + 8 ) / 64 -
01819                         ( 13 + ssl->in_msglen          + 8 ) / 64;
01820 
01821             extra_run &= correct * 0xFF;
01822 
01823             md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_ctr, 13 );
01824             md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_msg,
01825                              ssl->in_msglen );
01826             md_hmac_finish( &ssl->transform_in->md_ctx_dec,
01827                              ssl->in_msg + ssl->in_msglen );
01828             /* Call md_process at least once due to cache attacks */
01829             for( j = 0; j < extra_run + 1; j++ )
01830                 md_process( &ssl->transform_in->md_ctx_dec, ssl->in_msg );
01831 
01832             md_hmac_reset( &ssl->transform_in->md_ctx_dec );
01833         }
01834         else
01835 #endif /* POLARSSL_SSL_PROTO_TLS1 || POLARSSL_SSL_PROTO_TLS1_1 || \
01836               POLARSSL_SSL_PROTO_TLS1_2 */
01837         {
01838             SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01839             return( POLARSSL_ERR_SSL_INTERNAL_ERROR );
01840         }
01841 
01842         SSL_DEBUG_BUF( 4, "message  mac", tmp, ssl->transform_in->maclen );
01843         SSL_DEBUG_BUF( 4, "computed mac", ssl->in_msg + ssl->in_msglen,
01844                        ssl->transform_in->maclen );
01845 
01846         if( safer_memcmp( tmp, ssl->in_msg + ssl->in_msglen,
01847                          ssl->transform_in->maclen ) != 0 )
01848         {
01849 #if defined(POLARSSL_SSL_DEBUG_ALL)
01850             SSL_DEBUG_MSG( 1, ( "message mac does not match" ) );
01851 #endif
01852             correct = 0;
01853         }
01854         auth_done++;
01855 
01856         /*
01857          * Finally check the correct flag
01858          */
01859         if( correct == 0 )
01860             return( POLARSSL_ERR_SSL_INVALID_MAC );
01861     }
01862 #endif /* POLARSSL_SOME_MODES_USE_MAC */
01863 
01864     /* Make extra sure authentication was performed, exactly once */
01865     if( auth_done != 1 )
01866     {
01867         SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01868         return( POLARSSL_ERR_SSL_INTERNAL_ERROR );
01869     }
01870 
01871     if( ssl->in_msglen == 0 )
01872     {
01873         ssl->nb_zero++;
01874 
01875         /*
01876          * Three or more empty messages may be a DoS attack
01877          * (excessive CPU consumption).
01878          */
01879         if( ssl->nb_zero > 3 )
01880         {
01881             SSL_DEBUG_MSG( 1, ( "received four consecutive empty "
01882                                 "messages, possible DoS attack" ) );
01883             return( POLARSSL_ERR_SSL_INVALID_MAC );
01884         }
01885     }
01886     else
01887         ssl->nb_zero = 0;
01888 
01889     for( i = 8; i > 0; i-- )
01890         if( ++ssl->in_ctr[i - 1] != 0 )
01891             break;
01892 
01893     /* The loops goes to its end iff the counter is wrapping */
01894     if( i == 0 )
01895     {
01896         SSL_DEBUG_MSG( 1, ( "incoming message counter would wrap" ) );
01897         return( POLARSSL_ERR_SSL_COUNTER_WRAPPING );
01898     }
01899 
01900     SSL_DEBUG_MSG( 2, ( "<= decrypt buf" ) );
01901 
01902     return( 0 );
01903 }
01904 
01905 #undef MAC_NONE
01906 #undef MAC_PLAINTEXT
01907 #undef MAC_CIPHERTEXT
01908 
01909 #if defined(POLARSSL_ZLIB_SUPPORT)
01910 /*
01911  * Compression/decompression functions
01912  */
01913 static int ssl_compress_buf( ssl_context *ssl )
01914 {
01915     int ret;
01916     unsigned char *msg_post = ssl->out_msg;
01917     size_t len_pre = ssl->out_msglen;
01918     unsigned char *msg_pre = ssl->compress_buf;
01919 
01920     SSL_DEBUG_MSG( 2, ( "=> compress buf" ) );
01921 
01922     if( len_pre == 0 )
01923         return( 0 );
01924 
01925     memcpy( msg_pre, ssl->out_msg, len_pre );
01926 
01927     SSL_DEBUG_MSG( 3, ( "before compression: msglen = %d, ",
01928                    ssl->out_msglen ) );
01929 
01930     SSL_DEBUG_BUF( 4, "before compression: output payload",
01931                    ssl->out_msg, ssl->out_msglen );
01932 
01933     ssl->transform_out->ctx_deflate.next_in = msg_pre;
01934     ssl->transform_out->ctx_deflate.avail_in = len_pre;
01935     ssl->transform_out->ctx_deflate.next_out = msg_post;
01936     ssl->transform_out->ctx_deflate.avail_out = SSL_BUFFER_LEN;
01937 
01938     ret = deflate( &ssl->transform_out->ctx_deflate, Z_SYNC_FLUSH );
01939     if( ret != Z_OK )
01940     {
01941         SSL_DEBUG_MSG( 1, ( "failed to perform compression (%d)", ret ) );
01942         return( POLARSSL_ERR_SSL_COMPRESSION_FAILED );
01943     }
01944 
01945     ssl->out_msglen = SSL_BUFFER_LEN -
01946                       ssl->transform_out->ctx_deflate.avail_out;
01947 
01948     SSL_DEBUG_MSG( 3, ( "after compression: msglen = %d, ",
01949                    ssl->out_msglen ) );
01950 
01951     SSL_DEBUG_BUF( 4, "after compression: output payload",
01952                    ssl->out_msg, ssl->out_msglen );
01953 
01954     SSL_DEBUG_MSG( 2, ( "<= compress buf" ) );
01955 
01956     return( 0 );
01957 }
01958 
01959 static int ssl_decompress_buf( ssl_context *ssl )
01960 {
01961     int ret;
01962     unsigned char *msg_post = ssl->in_msg;
01963     size_t len_pre = ssl->in_msglen;
01964     unsigned char *msg_pre = ssl->compress_buf;
01965 
01966     SSL_DEBUG_MSG( 2, ( "=> decompress buf" ) );
01967 
01968     if( len_pre == 0 )
01969         return( 0 );
01970 
01971     memcpy( msg_pre, ssl->in_msg, len_pre );
01972 
01973     SSL_DEBUG_MSG( 3, ( "before decompression: msglen = %d, ",
01974                    ssl->in_msglen ) );
01975 
01976     SSL_DEBUG_BUF( 4, "before decompression: input payload",
01977                    ssl->in_msg, ssl->in_msglen );
01978 
01979     ssl->transform_in->ctx_inflate.next_in = msg_pre;
01980     ssl->transform_in->ctx_inflate.avail_in = len_pre;
01981     ssl->transform_in->ctx_inflate.next_out = msg_post;
01982     ssl->transform_in->ctx_inflate.avail_out = SSL_MAX_CONTENT_LEN;
01983 
01984     ret = inflate( &ssl->transform_in->ctx_inflate, Z_SYNC_FLUSH );
01985     if( ret != Z_OK )
01986     {
01987         SSL_DEBUG_MSG( 1, ( "failed to perform decompression (%d)", ret ) );
01988         return( POLARSSL_ERR_SSL_COMPRESSION_FAILED );
01989     }
01990 
01991     ssl->in_msglen = SSL_MAX_CONTENT_LEN -
01992                      ssl->transform_in->ctx_inflate.avail_out;
01993 
01994     SSL_DEBUG_MSG( 3, ( "after decompression: msglen = %d, ",
01995                    ssl->in_msglen ) );
01996 
01997     SSL_DEBUG_BUF( 4, "after decompression: input payload",
01998                    ssl->in_msg, ssl->in_msglen );
01999 
02000     SSL_DEBUG_MSG( 2, ( "<= decompress buf" ) );
02001 
02002     return( 0 );
02003 }
02004 #endif /* POLARSSL_ZLIB_SUPPORT */
02005 
02006 /*
02007  * Fill the input message buffer
02008  */
02009 int ssl_fetch_input ( ssl_context *ssl, size_t nb_want )
02010 {
02011     int ret;
02012     size_t len;
02013 
02014     SSL_DEBUG_MSG( 2, ( "=> fetch input" ) );
02015 
02016     if( nb_want > SSL_BUFFER_LEN - 8 )
02017     {
02018         SSL_DEBUG_MSG( 1, ( "requesting more data than fits" ) );
02019         return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
02020     }
02021 
02022     while( ssl->in_left < nb_want )
02023     {
02024         len = nb_want - ssl->in_left;
02025         ret = ssl->f_recv( ssl->p_recv, ssl->in_hdr + ssl->in_left, len );
02026 
02027         SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
02028                        ssl->in_left, nb_want ) );
02029         SSL_DEBUG_RET( 2, "ssl->f_recv", ret );
02030 
02031         if( ret == 0 )
02032             return( POLARSSL_ERR_SSL_CONN_EOF );
02033 
02034         if( ret < 0 )
02035             return( ret );
02036 
02037         ssl->in_left += ret;
02038     }
02039 
02040     SSL_DEBUG_MSG( 2, ( "<= fetch input" ) );
02041 
02042     return( 0 );
02043 }
02044 
02045 /*
02046  * Flush any data not yet written
02047  */
02048 int ssl_flush_output( ssl_context *ssl )
02049 {
02050     int ret;
02051     unsigned char *buf;
02052 
02053     SSL_DEBUG_MSG( 2, ( "=> flush output" ) );
02054 
02055     while( ssl->out_left > 0 )
02056     {
02057         SSL_DEBUG_MSG( 2, ( "message length: %d, out_left: %d",
02058                        5 + ssl->out_msglen, ssl->out_left ) );
02059 
02060         buf = ssl->out_hdr + 5 + ssl->out_msglen - ssl->out_left;
02061         ret = ssl->f_send( ssl->p_send, buf, ssl->out_left );
02062 
02063         SSL_DEBUG_RET( 2, "ssl->f_send", ret );
02064 
02065         if( ret <= 0 )
02066             return( ret );
02067 
02068         ssl->out_left -= ret;
02069     }
02070 
02071     SSL_DEBUG_MSG( 2, ( "<= flush output" ) );
02072 
02073     return( 0 );
02074 }
02075 
02076 /*
02077  * Record layer functions
02078  */
02079 int ssl_write_record( ssl_context *ssl )
02080 {
02081     int ret, done = 0;
02082     size_t len = ssl->out_msglen;
02083 
02084     SSL_DEBUG_MSG( 2, ( "=> write record" ) );
02085 
02086     if( ssl->out_msgtype == SSL_MSG_HANDSHAKE )
02087     {
02088         ssl->out_msg[1] = (unsigned char)( ( len - 4 ) >> 16 );
02089         ssl->out_msg[2] = (unsigned char)( ( len - 4 ) >>  8 );
02090         ssl->out_msg[3] = (unsigned char)( ( len - 4 )       );
02091 
02092         if( ssl->out_msg[0] != SSL_HS_HELLO_REQUEST )
02093             ssl->handshake->update_checksum( ssl, ssl->out_msg, len );
02094     }
02095 
02096 #if defined(POLARSSL_ZLIB_SUPPORT)
02097     if( ssl->transform_out != NULL &&
02098         ssl->session_out->compression == SSL_COMPRESS_DEFLATE )
02099     {
02100         if( ( ret = ssl_compress_buf( ssl ) ) != 0 )
02101         {
02102             SSL_DEBUG_RET( 1, "ssl_compress_buf", ret );
02103             return( ret );
02104         }
02105 
02106         len = ssl->out_msglen;
02107     }
02108 #endif /*POLARSSL_ZLIB_SUPPORT */
02109 
02110 #if defined(POLARSSL_SSL_HW_RECORD_ACCEL)
02111     if( ssl_hw_record_write != NULL )
02112     {
02113         SSL_DEBUG_MSG( 2, ( "going for ssl_hw_record_write()" ) );
02114 
02115         ret = ssl_hw_record_write( ssl );
02116         if( ret != 0 && ret != POLARSSL_ERR_SSL_HW_ACCEL_FALLTHROUGH )
02117         {
02118             SSL_DEBUG_RET( 1, "ssl_hw_record_write", ret );
02119             return( POLARSSL_ERR_SSL_HW_ACCEL_FAILED );
02120         }
02121 
02122         if( ret == 0 )
02123             done = 1;
02124     }
02125 #endif /* POLARSSL_SSL_HW_RECORD_ACCEL */
02126     if( !done )
02127     {
02128         ssl->out_hdr[0] = (unsigned char) ssl->out_msgtype;
02129         ssl->out_hdr[1] = (unsigned char) ssl->major_ver;
02130         ssl->out_hdr[2] = (unsigned char) ssl->minor_ver;
02131         ssl->out_hdr[3] = (unsigned char)( len >> 8 );
02132         ssl->out_hdr[4] = (unsigned char)( len      );
02133 
02134         if( ssl->transform_out != NULL )
02135         {
02136             if( ( ret = ssl_encrypt_buf( ssl ) ) != 0 )
02137             {
02138                 SSL_DEBUG_RET( 1, "ssl_encrypt_buf", ret );
02139                 return( ret );
02140             }
02141 
02142             len = ssl->out_msglen;
02143             ssl->out_hdr[3] = (unsigned char)( len >> 8 );
02144             ssl->out_hdr[4] = (unsigned char)( len      );
02145         }
02146 
02147         ssl->out_left = 5 + ssl->out_msglen;
02148 
02149         SSL_DEBUG_MSG( 3, ( "output record: msgtype = %d, "
02150                             "version = [%d:%d], msglen = %d",
02151                        ssl->out_hdr[0], ssl->out_hdr[1], ssl->out_hdr[2],
02152                      ( ssl->out_hdr[3] << 8 ) | ssl->out_hdr[4] ) );
02153 
02154         SSL_DEBUG_BUF( 4, "output record sent to network",
02155                        ssl->out_hdr, 5 + ssl->out_msglen );
02156     }
02157 
02158     if( ( ret = ssl_flush_output( ssl ) ) != 0 )
02159     {
02160         SSL_DEBUG_RET( 1, "ssl_flush_output", ret );
02161         return( ret );
02162     }
02163 
02164     SSL_DEBUG_MSG( 2, ( "<= write record" ) );
02165 
02166     return( 0 );
02167 }
02168 
02169 int ssl_read_record( ssl_context *ssl )
02170 {
02171     int ret, done = 0;
02172 
02173     SSL_DEBUG_MSG( 2, ( "=> read record" ) );
02174 
02175     if( ssl->in_hslen != 0 &&
02176         ssl->in_hslen < ssl->in_msglen )
02177     {
02178         /*
02179          * Get next Handshake message in the current record
02180          */
02181         ssl->in_msglen -= ssl->in_hslen;
02182 
02183         memmove( ssl->in_msg, ssl->in_msg + ssl->in_hslen,
02184                  ssl->in_msglen );
02185 
02186         ssl->in_hslen  = 4;
02187         ssl->in_hslen += ( ssl->in_msg[2] << 8 ) | ssl->in_msg[3];
02188 
02189         SSL_DEBUG_MSG( 3, ( "handshake message: msglen ="
02190                             " %d, type = %d, hslen = %d",
02191                        ssl->in_msglen, ssl->in_msg[0], ssl->in_hslen ) );
02192 
02193         if( ssl->in_msglen < 4 || ssl->in_msg[1] != 0 )
02194         {
02195             SSL_DEBUG_MSG( 1, ( "bad handshake length" ) );
02196             return( POLARSSL_ERR_SSL_INVALID_RECORD );
02197         }
02198 
02199         if( ssl->in_msglen < ssl->in_hslen )
02200         {
02201             SSL_DEBUG_MSG( 1, ( "bad handshake length" ) );
02202             return( POLARSSL_ERR_SSL_INVALID_RECORD );
02203         }
02204 
02205         if( ssl->state != SSL_HANDSHAKE_OVER )
02206             ssl->handshake->update_checksum( ssl, ssl->in_msg, ssl->in_hslen );
02207 
02208         return( 0 );
02209     }
02210 
02211     ssl->in_hslen = 0;
02212 
02213     /*
02214      * Read the record header and validate it
02215      */
02216     if( ( ret = ssl_fetch_input ( ssl, 5 ) ) != 0 )
02217     {
02218         SSL_DEBUG_RET( 1, "ssl_fetch_input", ret );
02219         return( ret );
02220     }
02221 
02222     ssl->in_msgtype =  ssl->in_hdr[0];
02223     ssl->in_msglen = ( ssl->in_hdr[3] << 8 ) | ssl->in_hdr[4];
02224 
02225     SSL_DEBUG_MSG( 3, ( "input record: msgtype = %d, "
02226                         "version = [%d:%d], msglen = %d",
02227                      ssl->in_hdr[0], ssl->in_hdr[1], ssl->in_hdr[2],
02228                    ( ssl->in_hdr[3] << 8 ) | ssl->in_hdr[4] ) );
02229 
02230     if( ssl->in_hdr[1] != ssl->major_ver )
02231     {
02232         SSL_DEBUG_MSG( 1, ( "major version mismatch" ) );
02233         return( POLARSSL_ERR_SSL_INVALID_RECORD );
02234     }
02235 
02236     if( ssl->in_hdr[2] > ssl->max_minor_ver )
02237     {
02238         SSL_DEBUG_MSG( 1, ( "minor version mismatch" ) );
02239         return( POLARSSL_ERR_SSL_INVALID_RECORD );
02240     }
02241 
02242     /* Sanity check (outer boundaries) */
02243     if( ssl->in_msglen < 1 || ssl->in_msglen > SSL_BUFFER_LEN - 13 )
02244     {
02245         SSL_DEBUG_MSG( 1, ( "bad message length" ) );
02246         return( POLARSSL_ERR_SSL_INVALID_RECORD );
02247     }
02248 
02249     /*
02250      * Make sure the message length is acceptable for the current transform
02251      * and protocol version.
02252      */
02253     if( ssl->transform_in == NULL )
02254     {
02255         if( ssl->in_msglen > SSL_MAX_CONTENT_LEN )
02256         {
02257             SSL_DEBUG_MSG( 1, ( "bad message length" ) );
02258             return( POLARSSL_ERR_SSL_INVALID_RECORD );
02259         }
02260     }
02261     else
02262     {
02263         if( ssl->in_msglen < ssl->transform_in->minlen )
02264         {
02265             SSL_DEBUG_MSG( 1, ( "bad message length" ) );
02266             return( POLARSSL_ERR_SSL_INVALID_RECORD );
02267         }
02268 
02269 #if defined(POLARSSL_SSL_PROTO_SSL3)
02270         if( ssl->minor_ver == SSL_MINOR_VERSION_0 &&
02271             ssl->in_msglen > ssl->transform_in->minlen + SSL_MAX_CONTENT_LEN )
02272         {
02273             SSL_DEBUG_MSG( 1, ( "bad message length" ) );
02274             return( POLARSSL_ERR_SSL_INVALID_RECORD );
02275         }
02276 #endif
02277 
02278 #if defined(POLARSSL_SSL_PROTO_TLS1) || defined(POLARSSL_SSL_PROTO_TLS1_1) || \
02279     defined(POLARSSL_SSL_PROTO_TLS1_2)
02280         /*
02281          * TLS encrypted messages can have up to 256 bytes of padding
02282          */
02283         if( ssl->minor_ver >= SSL_MINOR_VERSION_1 &&
02284             ssl->in_msglen > ssl->transform_in->minlen +
02285                              SSL_MAX_CONTENT_LEN + 256 )
02286         {
02287             SSL_DEBUG_MSG( 1, ( "bad message length" ) );
02288             return( POLARSSL_ERR_SSL_INVALID_RECORD );
02289         }
02290 #endif
02291     }
02292 
02293     /*
02294      * Read and optionally decrypt the message contents
02295      */
02296     if( ( ret = ssl_fetch_input ( ssl, 5 + ssl->in_msglen ) ) != 0 )
02297     {
02298         SSL_DEBUG_RET( 1, "ssl_fetch_input", ret );
02299         return( ret );
02300     }
02301 
02302     SSL_DEBUG_BUF( 4, "input record from network",
02303                    ssl->in_hdr, 5 + ssl->in_msglen );
02304 
02305 #if defined(POLARSSL_SSL_HW_RECORD_ACCEL)
02306     if( ssl_hw_record_read != NULL )
02307     {
02308         SSL_DEBUG_MSG( 2, ( "going for ssl_hw_record_read()" ) );
02309 
02310         ret = ssl_hw_record_read( ssl );
02311         if( ret != 0 && ret != POLARSSL_ERR_SSL_HW_ACCEL_FALLTHROUGH )
02312         {
02313             SSL_DEBUG_RET( 1, "ssl_hw_record_read", ret );
02314             return( POLARSSL_ERR_SSL_HW_ACCEL_FAILED );
02315         }
02316 
02317         if( ret == 0 )
02318             done = 1;
02319     }
02320 #endif /* POLARSSL_SSL_HW_RECORD_ACCEL */
02321     if( !done && ssl->transform_in != NULL )
02322     {
02323         if( ( ret = ssl_decrypt_buf( ssl ) ) != 0 )
02324         {
02325 #if defined(POLARSSL_SSL_ALERT_MESSAGES)
02326             if( ret == POLARSSL_ERR_SSL_INVALID_MAC )
02327             {
02328                 ssl_send_alert_message( ssl,
02329                                         SSL_ALERT_LEVEL_FATAL,
02330                                         SSL_ALERT_MSG_BAD_RECORD_MAC );
02331             }
02332 #endif
02333             SSL_DEBUG_RET( 1, "ssl_decrypt_buf", ret );
02334             return( ret );
02335         }
02336 
02337         SSL_DEBUG_BUF( 4, "input payload after decrypt",
02338                        ssl->in_msg, ssl->in_msglen );
02339 
02340         if( ssl->in_msglen > SSL_MAX_CONTENT_LEN )
02341         {
02342             SSL_DEBUG_MSG( 1, ( "bad message length" ) );
02343             return( POLARSSL_ERR_SSL_INVALID_RECORD );
02344         }
02345     }
02346 
02347 #if defined(POLARSSL_ZLIB_SUPPORT)
02348     if( ssl->transform_in != NULL &&
02349         ssl->session_in->compression == SSL_COMPRESS_DEFLATE )
02350     {
02351         if( ( ret = ssl_decompress_buf( ssl ) ) != 0 )
02352         {
02353             SSL_DEBUG_RET( 1, "ssl_decompress_buf", ret );
02354             return( ret );
02355         }
02356 
02357         ssl->in_hdr[3] = (unsigned char)( ssl->in_msglen >> 8 );
02358         ssl->in_hdr[4] = (unsigned char)( ssl->in_msglen      );
02359     }
02360 #endif /* POLARSSL_ZLIB_SUPPORT */
02361 
02362     if( ssl->in_msgtype != SSL_MSG_HANDSHAKE &&
02363         ssl->in_msgtype != SSL_MSG_ALERT &&
02364         ssl->in_msgtype != SSL_MSG_CHANGE_CIPHER_SPEC &&
02365         ssl->in_msgtype != SSL_MSG_APPLICATION_DATA )
02366     {
02367         SSL_DEBUG_MSG( 1, ( "unknown record type" ) );
02368 
02369         if( ( ret = ssl_send_alert_message( ssl,
02370                         SSL_ALERT_LEVEL_FATAL,
02371                         SSL_ALERT_MSG_UNEXPECTED_MESSAGE ) ) != 0 )
02372         {
02373             return( ret );
02374         }
02375 
02376         return( POLARSSL_ERR_SSL_INVALID_RECORD );
02377     }
02378 
02379     if( ssl->in_msgtype == SSL_MSG_HANDSHAKE )
02380     {
02381         ssl->in_hslen  = 4;
02382         ssl->in_hslen += ( ssl->in_msg[2] << 8 ) | ssl->in_msg[3];
02383 
02384         SSL_DEBUG_MSG( 3, ( "handshake message: msglen ="
02385                             " %d, type = %d, hslen = %d",
02386                        ssl->in_msglen, ssl->in_msg[0], ssl->in_hslen ) );
02387 
02388         /*
02389          * Additional checks to validate the handshake header
02390          */
02391         if( ssl->in_msglen < 4 || ssl->in_msg[1] != 0 )
02392         {
02393             SSL_DEBUG_MSG( 1, ( "bad handshake length" ) );
02394             return( POLARSSL_ERR_SSL_INVALID_RECORD );
02395         }
02396 
02397         if( ssl->in_msglen < ssl->in_hslen )
02398         {
02399             SSL_DEBUG_MSG( 1, ( "bad handshake length" ) );
02400             return( POLARSSL_ERR_SSL_INVALID_RECORD );
02401         }
02402 
02403         if( ssl->state != SSL_HANDSHAKE_OVER )
02404             ssl->handshake->update_checksum( ssl, ssl->in_msg, ssl->in_hslen );
02405     }
02406 
02407     if( ssl->in_msgtype == SSL_MSG_ALERT )
02408     {
02409         SSL_DEBUG_MSG( 2, ( "got an alert message, type: [%d:%d]",
02410                        ssl->in_msg[0], ssl->in_msg[1] ) );
02411 
02412         /*
02413          * Ignore non-fatal alerts, except close_notify
02414          */
02415         if( ssl->in_msg[0] == SSL_ALERT_LEVEL_FATAL )
02416         {
02417             SSL_DEBUG_MSG( 1, ( "is a fatal alert message (msg %d)",
02418                            ssl->in_msg[1] ) );
02419             return( POLARSSL_ERR_SSL_FATAL_ALERT_MESSAGE );
02420         }
02421 
02422         if( ssl->in_msg[0] == SSL_ALERT_LEVEL_WARNING &&
02423             ssl->in_msg[1] == SSL_ALERT_MSG_CLOSE_NOTIFY )
02424         {
02425             SSL_DEBUG_MSG( 2, ( "is a close notify message" ) );
02426             return( POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY );
02427         }
02428     }
02429 
02430     ssl->in_left = 0;
02431 
02432     SSL_DEBUG_MSG( 2, ( "<= read record" ) );
02433 
02434     return( 0 );
02435 }
02436 
02437 int ssl_send_fatal_handshake_failure( ssl_context *ssl )
02438 {
02439     int ret;
02440 
02441     if( ( ret = ssl_send_alert_message( ssl,
02442                     SSL_ALERT_LEVEL_FATAL,
02443                     SSL_ALERT_MSG_HANDSHAKE_FAILURE ) ) != 0 )
02444     {
02445         return( ret );
02446     }
02447 
02448     return( 0 );
02449 }
02450 
02451 int ssl_send_alert_message( ssl_context *ssl,
02452                             unsigned char level,
02453                             unsigned char message )
02454 {
02455     int ret;
02456 
02457     SSL_DEBUG_MSG( 2, ( "=> send alert message" ) );
02458 
02459     ssl->out_msgtype = SSL_MSG_ALERT;
02460     ssl->out_msglen = 2;
02461     ssl->out_msg[0] = level;
02462     ssl->out_msg[1] = message;
02463 
02464     if( ( ret = ssl_write_record( ssl ) ) != 0 )
02465     {
02466         SSL_DEBUG_RET( 1, "ssl_write_record", ret );
02467         return( ret );
02468     }
02469 
02470     SSL_DEBUG_MSG( 2, ( "<= send alert message" ) );
02471 
02472     return( 0 );
02473 }
02474 
02475 /*
02476  * Handshake functions
02477  */
02478 #if !defined(POLARSSL_KEY_EXCHANGE_RSA_ENABLED)         && \
02479     !defined(POLARSSL_KEY_EXCHANGE_RSA_PSK_ENABLED)     && \
02480     !defined(POLARSSL_KEY_EXCHANGE_DHE_RSA_ENABLED)     && \
02481     !defined(POLARSSL_KEY_EXCHANGE_ECDHE_RSA_ENABLED)   && \
02482     !defined(POLARSSL_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) && \
02483     !defined(POLARSSL_KEY_EXCHANGE_ECDH_RSA_ENABLED)    && \
02484     !defined(POLARSSL_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
02485 int ssl_write_certificate( ssl_context *ssl )
02486 {
02487     const ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
02488 
02489     SSL_DEBUG_MSG( 2, ( "=> write certificate" ) );
02490 
02491     if( ciphersuite_info->key_exchange == POLARSSL_KEY_EXCHANGE_PSK ||
02492         ciphersuite_info->key_exchange == POLARSSL_KEY_EXCHANGE_DHE_PSK ||
02493         ciphersuite_info->key_exchange == POLARSSL_KEY_EXCHANGE_ECDHE_PSK )
02494     {
02495         SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
02496         ssl->state++;
02497         return( 0 );
02498     }
02499 
02500     SSL_DEBUG_MSG( 1, ( "should never happen" ) );
02501     return( POLARSSL_ERR_SSL_INTERNAL_ERROR );
02502 }
02503 
02504 int ssl_parse_certificate( ssl_context *ssl )
02505 {
02506     const ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
02507 
02508     SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) );
02509 
02510     if( ciphersuite_info->key_exchange == POLARSSL_KEY_EXCHANGE_PSK ||
02511         ciphersuite_info->key_exchange == POLARSSL_KEY_EXCHANGE_DHE_PSK ||
02512         ciphersuite_info->key_exchange == POLARSSL_KEY_EXCHANGE_ECDHE_PSK )
02513     {
02514         SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
02515         ssl->state++;
02516         return( 0 );
02517     }
02518 
02519     SSL_DEBUG_MSG( 1, ( "should never happen" ) );
02520     return( POLARSSL_ERR_SSL_INTERNAL_ERROR );
02521 }
02522 #else
02523 int ssl_write_certificate( ssl_context *ssl )
02524 {
02525     int ret = POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE;
02526     size_t i, n;
02527     const x509_crt *crt;
02528     const ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
02529 
02530     SSL_DEBUG_MSG( 2, ( "=> write certificate" ) );
02531 
02532     if( ciphersuite_info->key_exchange == POLARSSL_KEY_EXCHANGE_PSK ||
02533         ciphersuite_info->key_exchange == POLARSSL_KEY_EXCHANGE_DHE_PSK ||
02534         ciphersuite_info->key_exchange == POLARSSL_KEY_EXCHANGE_ECDHE_PSK )
02535     {
02536         SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
02537         ssl->state++;
02538         return( 0 );
02539     }
02540 
02541 #if defined(POLARSSL_SSL_CLI_C)
02542     if( ssl->endpoint == SSL_IS_CLIENT )
02543     {
02544         if( ssl->client_auth == 0 )
02545         {
02546             SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
02547             ssl->state++;
02548             return( 0 );
02549         }
02550 
02551 #if defined(POLARSSL_SSL_PROTO_SSL3)
02552         /*
02553          * If using SSLv3 and got no cert, send an Alert message
02554          * (otherwise an empty Certificate message will be sent).
02555          */
02556         if( ssl_own_cert( ssl )  == NULL &&
02557             ssl->minor_ver == SSL_MINOR_VERSION_0 )
02558         {
02559             ssl->out_msglen  = 2;
02560             ssl->out_msgtype = SSL_MSG_ALERT;
02561             ssl->out_msg[0]  = SSL_ALERT_LEVEL_WARNING;
02562             ssl->out_msg[1]  = SSL_ALERT_MSG_NO_CERT;
02563 
02564             SSL_DEBUG_MSG( 2, ( "got no certificate to send" ) );
02565             goto write_msg;
02566         }
02567 #endif /* POLARSSL_SSL_PROTO_SSL3 */
02568     }
02569 #endif /* POLARSSL_SSL_CLI_C */
02570 #if defined(POLARSSL_SSL_SRV_C)
02571     if( ssl->endpoint == SSL_IS_SERVER )
02572     {
02573         if( ssl_own_cert( ssl ) == NULL )
02574         {
02575             SSL_DEBUG_MSG( 1, ( "got no certificate to send" ) );
02576             return( POLARSSL_ERR_SSL_CERTIFICATE_REQUIRED );
02577         }
02578     }
02579 #endif
02580 
02581     SSL_DEBUG_CRT( 3, "own certificate", ssl_own_cert( ssl ) );
02582 
02583     /*
02584      *     0  .  0    handshake type
02585      *     1  .  3    handshake length
02586      *     4  .  6    length of all certs
02587      *     7  .  9    length of cert. 1
02588      *    10  . n-1   peer certificate
02589      *     n  . n+2   length of cert. 2
02590      *    n+3 . ...   upper level cert, etc.
02591      */
02592     i = 7;
02593     crt = ssl_own_cert( ssl );
02594 
02595     while( crt != NULL )
02596     {
02597         n = crt->raw.len;
02598         if( n > SSL_MAX_CONTENT_LEN - 3 - i )
02599         {
02600             SSL_DEBUG_MSG( 1, ( "certificate too large, %d > %d",
02601                            i + 3 + n, SSL_MAX_CONTENT_LEN ) );
02602             return( POLARSSL_ERR_SSL_CERTIFICATE_TOO_LARGE );
02603         }
02604 
02605         ssl->out_msg[i    ] = (unsigned char)( n >> 16 );
02606         ssl->out_msg[i + 1] = (unsigned char)( n >>  8 );
02607         ssl->out_msg[i + 2] = (unsigned char)( n       );
02608 
02609         i += 3; memcpy( ssl->out_msg + i, crt->raw.p, n );
02610         i += n; crt = crt->next;
02611     }
02612 
02613     ssl->out_msg[4]  = (unsigned char)( ( i - 7 ) >> 16 );
02614     ssl->out_msg[5]  = (unsigned char)( ( i - 7 ) >>  8 );
02615     ssl->out_msg[6]  = (unsigned char)( ( i - 7 )       );
02616 
02617     ssl->out_msglen  = i;
02618     ssl->out_msgtype = SSL_MSG_HANDSHAKE;
02619     ssl->out_msg[0]  = SSL_HS_CERTIFICATE;
02620 
02621 #if defined(POLARSSL_SSL_PROTO_SSL3)
02622 write_msg:
02623 #endif
02624 
02625     ssl->state++;
02626 
02627     if( ( ret = ssl_write_record( ssl ) ) != 0 )
02628     {
02629         SSL_DEBUG_RET( 1, "ssl_write_record", ret );
02630         return( ret );
02631     }
02632 
02633     SSL_DEBUG_MSG( 2, ( "<= write certificate" ) );
02634 
02635     return( ret );
02636 }
02637 
02638 int ssl_parse_certificate( ssl_context *ssl )
02639 {
02640     int ret = POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE;
02641     size_t i, n;
02642     const ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
02643 
02644     SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) );
02645 
02646     if( ciphersuite_info->key_exchange == POLARSSL_KEY_EXCHANGE_PSK ||
02647         ciphersuite_info->key_exchange == POLARSSL_KEY_EXCHANGE_DHE_PSK ||
02648         ciphersuite_info->key_exchange == POLARSSL_KEY_EXCHANGE_ECDHE_PSK )
02649     {
02650         SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
02651         ssl->state++;
02652         return( 0 );
02653     }
02654 
02655 #if defined(POLARSSL_SSL_SRV_C)
02656     if( ssl->endpoint == SSL_IS_SERVER &&
02657         ( ssl->authmode == SSL_VERIFY_NONE ||
02658           ciphersuite_info->key_exchange == POLARSSL_KEY_EXCHANGE_RSA_PSK ) )
02659     {
02660         ssl->session_negotiate->verify_result = BADCERT_SKIP_VERIFY;
02661         SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
02662         ssl->state++;
02663         return( 0 );
02664     }
02665 #endif
02666 
02667     if( ( ret = ssl_read_record( ssl ) ) != 0 )
02668     {
02669         SSL_DEBUG_RET( 1, "ssl_read_record", ret );
02670         return( ret );
02671     }
02672 
02673     ssl->state++;
02674 
02675 #if defined(POLARSSL_SSL_SRV_C)
02676 #if defined(POLARSSL_SSL_PROTO_SSL3)
02677     /*
02678      * Check if the client sent an empty certificate
02679      */
02680     if( ssl->endpoint  == SSL_IS_SERVER &&
02681         ssl->minor_ver == SSL_MINOR_VERSION_0 )
02682     {
02683         if( ssl->in_msglen  == 2                        &&
02684             ssl->in_msgtype == SSL_MSG_ALERT            &&
02685             ssl->in_msg[0]  == SSL_ALERT_LEVEL_WARNING  &&
02686             ssl->in_msg[1]  == SSL_ALERT_MSG_NO_CERT )
02687         {
02688             SSL_DEBUG_MSG( 1, ( "SSLv3 client has no certificate" ) );
02689 
02690             ssl->session_negotiate->verify_result = BADCERT_MISSING;
02691             if( ssl->authmode == SSL_VERIFY_OPTIONAL )
02692                 return( 0 );
02693             else
02694                 return( POLARSSL_ERR_SSL_NO_CLIENT_CERTIFICATE );
02695         }
02696     }
02697 #endif /* POLARSSL_SSL_PROTO_SSL3 */
02698 
02699 #if defined(POLARSSL_SSL_PROTO_TLS1) || defined(POLARSSL_SSL_PROTO_TLS1_1) || \
02700     defined(POLARSSL_SSL_PROTO_TLS1_2)
02701     if( ssl->endpoint  == SSL_IS_SERVER &&
02702         ssl->minor_ver != SSL_MINOR_VERSION_0 )
02703     {
02704         if( ssl->in_hslen   == 7                    &&
02705             ssl->in_msgtype == SSL_MSG_HANDSHAKE    &&
02706             ssl->in_msg[0]  == SSL_HS_CERTIFICATE   &&
02707             memcmp( ssl->in_msg + 4, "\0\0\0", 3 ) == 0 )
02708         {
02709             SSL_DEBUG_MSG( 1, ( "TLSv1 client has no certificate" ) );
02710 
02711             ssl->session_negotiate->verify_result = BADCERT_MISSING;
02712             if( ssl->authmode == SSL_VERIFY_REQUIRED )
02713                 return( POLARSSL_ERR_SSL_NO_CLIENT_CERTIFICATE );
02714             else
02715                 return( 0 );
02716         }
02717     }
02718 #endif /* POLARSSL_SSL_PROTO_TLS1 || POLARSSL_SSL_PROTO_TLS1_1 || \
02719           POLARSSL_SSL_PROTO_TLS1_2 */
02720 #endif /* POLARSSL_SSL_SRV_C */
02721 
02722     if( ssl->in_msgtype != SSL_MSG_HANDSHAKE )
02723     {
02724         SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
02725         return( POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE );
02726     }
02727 
02728     if( ssl->in_msg[0] != SSL_HS_CERTIFICATE || ssl->in_hslen < 10 )
02729     {
02730         SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
02731         return( POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE );
02732     }
02733 
02734     /*
02735      * Same message structure as in ssl_write_certificate()
02736      */
02737     n = ( ssl->in_msg[5] << 8 ) | ssl->in_msg[6];
02738 
02739     if( ssl->in_msg[4] != 0 || ssl->in_hslen != 7 + n )
02740     {
02741         SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
02742         return( POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE );
02743     }
02744 
02745     /* In case we tried to reuse a session but it failed */
02746     if( ssl->session_negotiate->peer_cert != NULL )
02747     {
02748         x509_crt_free( ssl->session_negotiate->peer_cert );
02749         polarssl_free( ssl->session_negotiate->peer_cert );
02750     }
02751 
02752     if( ( ssl->session_negotiate->peer_cert = polarssl_malloc(
02753                     sizeof( x509_crt ) ) ) == NULL )
02754     {
02755         SSL_DEBUG_MSG( 1, ( "malloc(%d bytes) failed",
02756                        sizeof( x509_crt ) ) );
02757         return( POLARSSL_ERR_SSL_MALLOC_FAILED );
02758     }
02759 
02760     x509_crt_init( ssl->session_negotiate->peer_cert );
02761 
02762     i = 7;
02763 
02764     while( i < ssl->in_hslen )
02765     {
02766         if( ssl->in_msg[i] != 0 )
02767         {
02768             SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
02769             return( POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE );
02770         }
02771 
02772         n = ( (unsigned int) ssl->in_msg[i + 1] << 8 )
02773             | (unsigned int) ssl->in_msg[i + 2];
02774         i += 3;
02775 
02776         if( n < 128 || i + n > ssl->in_hslen )
02777         {
02778             SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
02779             return( POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE );
02780         }
02781 
02782         ret = x509_crt_parse_der( ssl->session_negotiate->peer_cert,
02783                                   ssl->in_msg + i, n );
02784         if( ret != 0 )
02785         {
02786             SSL_DEBUG_RET( 1, " x509_crt_parse_der", ret );
02787             return( ret );
02788         }
02789 
02790         i += n;
02791     }
02792 
02793     SSL_DEBUG_CRT( 3, "peer certificate", ssl->session_negotiate->peer_cert );
02794 
02795     /*
02796      * On client, make sure the server cert doesn't change during renego to
02797      * avoid "triple handshake" attack: https://secure-resumption.com/
02798      */
02799 #if defined(POLARSSL_SSL_RENEGOTIATION) && defined(POLARSSL_SSL_CLI_C)
02800     if( ssl->endpoint == SSL_IS_CLIENT &&
02801         ssl->renegotiation == SSL_RENEGOTIATION )
02802     {
02803         if( ssl->session->peer_cert == NULL )
02804         {
02805             SSL_DEBUG_MSG( 1, ( "new server cert during renegotiation" ) );
02806             return( POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE );
02807         }
02808 
02809         if( ssl->session->peer_cert->raw.len !=
02810             ssl->session_negotiate->peer_cert->raw.len ||
02811             memcmp( ssl->session->peer_cert->raw.p,
02812                     ssl->session_negotiate->peer_cert->raw.p,
02813                     ssl->session->peer_cert->raw.len ) != 0 )
02814         {
02815             SSL_DEBUG_MSG( 1, ( "server cert changed during renegotiation" ) );
02816             return( POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE );
02817         }
02818     }
02819 #endif /* POLARSSL_SSL_RENEGOTIATION && POLARSSL_SSL_CLI_C */
02820 
02821     if( ssl->authmode != SSL_VERIFY_NONE )
02822     {
02823         if( ssl->ca_chain == NULL )
02824         {
02825             SSL_DEBUG_MSG( 1, ( "got no CA chain" ) );
02826             return( POLARSSL_ERR_SSL_CA_CHAIN_REQUIRED );
02827         }
02828 
02829         /*
02830          * Main check: verify certificate
02831          */
02832         ret = x509_crt_verify( ssl->session_negotiate->peer_cert,
02833                                ssl->ca_chain, ssl->ca_crl, ssl->peer_cn,
02834                               &ssl->session_negotiate->verify_result,
02835                                ssl->f_vrfy, ssl->p_vrfy );
02836 
02837         if( ret != 0 )
02838         {
02839             SSL_DEBUG_RET( 1, "x509_verify_cert", ret );
02840         }
02841 
02842         /*
02843          * Secondary checks: always done, but change 'ret' only if it was 0
02844          */
02845 
02846 #if defined(POLARSSL_SSL_SET_CURVES)
02847         {
02848             pk_context *pk = &ssl->session_negotiate->peer_cert->pk;
02849 
02850             /* If certificate uses an EC key, make sure the curve is OK */
02851             if( pk_can_do( pk, POLARSSL_PK_ECKEY ) &&
02852                 ! ssl_curve_is_acceptable( ssl, pk_ec( *pk )->grp.id ) )
02853             {
02854                 SSL_DEBUG_MSG( 1, ( "bad certificate (EC key curve)" ) );
02855                 if( ret == 0 )
02856                     ret = POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE;
02857             }
02858         }
02859 #endif /* POLARSSL_SSL_SET_CURVES */
02860 
02861         if( ssl_check_cert_usage( ssl->session_negotiate->peer_cert,
02862                                   ciphersuite_info,
02863                                   ! ssl->endpoint,
02864                                  &ssl->session_negotiate->verify_result ) != 0 )
02865         {
02866             SSL_DEBUG_MSG( 1, ( "bad certificate (usage extensions)" ) );
02867             if( ret == 0 )
02868                 ret = POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE;
02869         }
02870 
02871         if( ssl->authmode != SSL_VERIFY_REQUIRED )
02872             ret = 0;
02873     }
02874 
02875     SSL_DEBUG_MSG( 2, ( "<= parse certificate" ) );
02876 
02877     return( ret );
02878 }
02879 #endif /* !POLARSSL_KEY_EXCHANGE_RSA_ENABLED
02880           !POLARSSL_KEY_EXCHANGE_RSA_PSK_ENABLED
02881           !POLARSSL_KEY_EXCHANGE_DHE_RSA_ENABLED
02882           !POLARSSL_KEY_EXCHANGE_ECDHE_RSA_ENABLED
02883           !POLARSSL_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
02884           !POLARSSL_KEY_EXCHANGE_ECDH_RSA_ENABLED
02885           !POLARSSL_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
02886 
02887 int ssl_write_change_cipher_spec( ssl_context *ssl )
02888 {
02889     int ret;
02890 
02891     SSL_DEBUG_MSG( 2, ( "=> write change cipher spec" ) );
02892 
02893     ssl->out_msgtype = SSL_MSG_CHANGE_CIPHER_SPEC;
02894     ssl->out_msglen  = 1;
02895     ssl->out_msg[0]  = 1;
02896 
02897     ssl->state++;
02898 
02899     if( ( ret = ssl_write_record( ssl ) ) != 0 )
02900     {
02901         SSL_DEBUG_RET( 1, "ssl_write_record", ret );
02902         return( ret );
02903     }
02904 
02905     SSL_DEBUG_MSG( 2, ( "<= write change cipher spec" ) );
02906 
02907     return( 0 );
02908 }
02909 
02910 int ssl_parse_change_cipher_spec( ssl_context *ssl )
02911 {
02912     int ret;
02913 
02914     SSL_DEBUG_MSG( 2, ( "=> parse change cipher spec" ) );
02915 
02916     if( ( ret = ssl_read_record( ssl ) ) != 0 )
02917     {
02918         SSL_DEBUG_RET( 1, "ssl_read_record", ret );
02919         return( ret );
02920     }
02921 
02922     if( ssl->in_msgtype != SSL_MSG_CHANGE_CIPHER_SPEC )
02923     {
02924         SSL_DEBUG_MSG( 1, ( "bad change cipher spec message" ) );
02925         return( POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE );
02926     }
02927 
02928     if( ssl->in_msglen != 1 || ssl->in_msg[0] != 1 )
02929     {
02930         SSL_DEBUG_MSG( 1, ( "bad change cipher spec message" ) );
02931         return( POLARSSL_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC );
02932     }
02933 
02934     ssl->state++;
02935 
02936     SSL_DEBUG_MSG( 2, ( "<= parse change cipher spec" ) );
02937 
02938     return( 0 );
02939 }
02940 
02941 void ssl_optimize_checksum( ssl_context *ssl,
02942                             const ssl_ciphersuite_t *ciphersuite_info )
02943 {
02944     ((void) ciphersuite_info);
02945 
02946 #if defined(POLARSSL_SSL_PROTO_SSL3) || defined(POLARSSL_SSL_PROTO_TLS1) || \
02947     defined(POLARSSL_SSL_PROTO_TLS1_1)
02948     if( ssl->minor_ver < SSL_MINOR_VERSION_3 )
02949         ssl->handshake->update_checksum = ssl_update_checksum_md5sha1;
02950     else
02951 #endif
02952 #if defined(POLARSSL_SSL_PROTO_TLS1_2)
02953 #if defined(POLARSSL_SHA512_C)
02954     if( ciphersuite_info->mac == POLARSSL_MD_SHA384 )
02955         ssl->handshake->update_checksum = ssl_update_checksum_sha384;
02956     else
02957 #endif
02958 #if defined(POLARSSL_SHA256_C)
02959     if( ciphersuite_info->mac != POLARSSL_MD_SHA384 )
02960         ssl->handshake->update_checksum = ssl_update_checksum_sha256;
02961     else
02962 #endif
02963 #endif /* POLARSSL_SSL_PROTO_TLS1_2 */
02964     {
02965         SSL_DEBUG_MSG( 1, ( "should never happen" ) );
02966         return;
02967     }
02968 }
02969 
02970 static void ssl_update_checksum_start( ssl_context *ssl,
02971                                        const unsigned char *buf, size_t len )
02972 {
02973 #if defined(POLARSSL_SSL_PROTO_SSL3) || defined(POLARSSL_SSL_PROTO_TLS1) || \
02974     defined(POLARSSL_SSL_PROTO_TLS1_1)
02975      md5_update( &ssl->handshake->fin_md5 , buf, len );
02976     sha1_update( &ssl->handshake->fin_sha1, buf, len );
02977 #endif
02978 #if defined(POLARSSL_SSL_PROTO_TLS1_2)
02979 #if defined(POLARSSL_SHA256_C)
02980     sha256_update( &ssl->handshake->fin_sha256, buf, len );
02981 #endif
02982 #if defined(POLARSSL_SHA512_C)
02983     sha512_update( &ssl->handshake->fin_sha512, buf, len );
02984 #endif
02985 #endif /* POLARSSL_SSL_PROTO_TLS1_2 */
02986 }
02987 
02988 #if defined(POLARSSL_SSL_PROTO_SSL3) || defined(POLARSSL_SSL_PROTO_TLS1) || \
02989     defined(POLARSSL_SSL_PROTO_TLS1_1)
02990 static void ssl_update_checksum_md5sha1( ssl_context *ssl,
02991                                          const unsigned char *buf, size_t len )
02992 {
02993      md5_update( &ssl->handshake->fin_md5 , buf, len );
02994     sha1_update( &ssl->handshake->fin_sha1, buf, len );
02995 }
02996 #endif
02997 
02998 #if defined(POLARSSL_SSL_PROTO_TLS1_2)
02999 #if defined(POLARSSL_SHA256_C)
03000 static void ssl_update_checksum_sha256( ssl_context *ssl,
03001                                         const unsigned char *buf, size_t len )
03002 {
03003     sha256_update( &ssl->handshake->fin_sha256, buf, len );
03004 }
03005 #endif
03006 
03007 #if defined(POLARSSL_SHA512_C)
03008 static void ssl_update_checksum_sha384( ssl_context *ssl,
03009                                         const unsigned char *buf, size_t len )
03010 {
03011     sha512_update( &ssl->handshake->fin_sha512, buf, len );
03012 }
03013 #endif
03014 #endif /* POLARSSL_SSL_PROTO_TLS1_2 */
03015 
03016 #if defined(POLARSSL_SSL_PROTO_SSL3)
03017 static void ssl_calc_finished_ssl(
03018                 ssl_context *ssl, unsigned char *buf, int from )
03019 {
03020     const char *sender;
03021     md5_context  md5;
03022     sha1_context sha1;
03023 
03024     unsigned char padbuf[48];
03025     unsigned char md5sum[16];
03026     unsigned char sha1sum[20];
03027 
03028     ssl_session *session = ssl->session_negotiate;
03029     if( !session )
03030         session = ssl->session;
03031 
03032     SSL_DEBUG_MSG( 2, ( "=> calc  finished ssl" ) );
03033 
03034     memcpy( &md5 , &ssl->handshake->fin_md5 , sizeof(md5_context)  );
03035     memcpy( &sha1, &ssl->handshake->fin_sha1, sizeof(sha1_context) );
03036 
03037     /*
03038      * SSLv3:
03039      *   hash =
03040      *      MD5( master + pad2 +
03041      *          MD5( handshake + sender + master + pad1 ) )
03042      *   + SHA1( master + pad2 +
03043      *         SHA1( handshake + sender + master + pad1 ) )
03044      */
03045 
03046 #if !defined(POLARSSL_MD5_ALT)
03047     SSL_DEBUG_BUF( 4, "finished  md5 state", (unsigned char *)
03048                     md5.state , sizeof(  md5.state  ) );
03049 #endif
03050 
03051 #if !defined(POLARSSL_SHA1_ALT)
03052     SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *)
03053                    sha1.state , sizeof( sha1.state  ) );
03054 #endif
03055 
03056     sender = ( from == SSL_IS_CLIENT ) ? "CLNT"
03057                                        : "SRVR";
03058 
03059     memset( padbuf, 0x36, 48 );
03060 
03061     md5_update( &md5, (const unsigned char *) sender, 4 );
03062     md5_update( &md5, session->master, 48 );
03063     md5_update( &md5, padbuf, 48 );
03064     md5_finish( &md5, md5sum );
03065 
03066     sha1_update( &sha1, (const unsigned char *) sender, 4 );
03067     sha1_update( &sha1, session->master, 48 );
03068     sha1_update( &sha1, padbuf, 40 );
03069     sha1_finish( &sha1, sha1sum );
03070 
03071     memset( padbuf, 0x5C, 48 );
03072 
03073     md5_starts( &md5 );
03074     md5_update( &md5, session->master, 48 );
03075     md5_update( &md5, padbuf, 48 );
03076     md5_update( &md5, md5sum, 16 );
03077     md5_finish( &md5, buf );
03078 
03079     sha1_starts( &sha1 );
03080     sha1_update( &sha1, session->master, 48 );
03081     sha1_update( &sha1, padbuf , 40 );
03082     sha1_update( &sha1, sha1sum, 20 );
03083     sha1_finish( &sha1, buf + 16 );
03084 
03085     SSL_DEBUG_BUF( 3, "calc finished result", buf, 36 );
03086 
03087     md5_free(  &md5  );
03088     sha1_free( &sha1 );
03089 
03090     polarssl_zeroize(  padbuf, sizeof(  padbuf ) );
03091     polarssl_zeroize(  md5sum, sizeof(  md5sum ) );
03092     polarssl_zeroize( sha1sum, sizeof( sha1sum ) );
03093 
03094     SSL_DEBUG_MSG( 2, ( "<= calc  finished" ) );
03095 }
03096 #endif /* POLARSSL_SSL_PROTO_SSL3 */
03097 
03098 #if defined(POLARSSL_SSL_PROTO_TLS1) || defined(POLARSSL_SSL_PROTO_TLS1_1)
03099 static void ssl_calc_finished_tls(
03100                 ssl_context *ssl, unsigned char *buf, int from )
03101 {
03102     int len = 12;
03103     const char *sender;
03104     md5_context  md5;
03105     sha1_context sha1;
03106     unsigned char padbuf[36];
03107 
03108     ssl_session *session = ssl->session_negotiate;
03109     if( !session )
03110         session = ssl->session;
03111 
03112     SSL_DEBUG_MSG( 2, ( "=> calc  finished tls" ) );
03113 
03114     memcpy( &md5 , &ssl->handshake->fin_md5 , sizeof(md5_context)  );
03115     memcpy( &sha1, &ssl->handshake->fin_sha1, sizeof(sha1_context) );
03116 
03117     /*
03118      * TLSv1:
03119      *   hash = PRF( master, finished_label,
03120      *               MD5( handshake ) + SHA1( handshake ) )[0..11]
03121      */
03122 
03123 #if !defined(POLARSSL_MD5_ALT)
03124     SSL_DEBUG_BUF( 4, "finished  md5 state", (unsigned char *)
03125                     md5.state , sizeof(  md5.state  ) );
03126 #endif
03127 
03128 #if !defined(POLARSSL_SHA1_ALT)
03129     SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *)
03130                    sha1.state , sizeof( sha1.state  ) );
03131 #endif
03132 
03133     sender = ( from == SSL_IS_CLIENT )
03134              ? "client finished"
03135              : "server finished";
03136 
03137     md5_finish(  &md5, padbuf );
03138     sha1_finish( &sha1, padbuf + 16 );
03139 
03140     ssl->handshake->tls_prf( session->master, 48, sender,
03141                              padbuf, 36, buf, len );
03142 
03143     SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
03144 
03145     md5_free(  &md5  );
03146     sha1_free( &sha1 );
03147 
03148     polarssl_zeroize(  padbuf, sizeof(  padbuf ) );
03149 
03150     SSL_DEBUG_MSG( 2, ( "<= calc  finished" ) );
03151 }
03152 #endif /* POLARSSL_SSL_PROTO_TLS1 || POLARSSL_SSL_PROTO_TLS1_1 */
03153 
03154 #if defined(POLARSSL_SSL_PROTO_TLS1_2)
03155 #if defined(POLARSSL_SHA256_C)
03156 static void ssl_calc_finished_tls_sha256(
03157                 ssl_context *ssl, unsigned char *buf, int from )
03158 {
03159     int len = 12;
03160     const char *sender;
03161     sha256_context sha256;
03162     unsigned char padbuf[32];
03163 
03164     ssl_session *session = ssl->session_negotiate;
03165     if( !session )
03166         session = ssl->session;
03167 
03168     SSL_DEBUG_MSG( 2, ( "=> calc  finished tls sha256" ) );
03169 
03170     memcpy( &sha256, &ssl->handshake->fin_sha256, sizeof(sha256_context) );
03171 
03172     /*
03173      * TLSv1.2:
03174      *   hash = PRF( master, finished_label,
03175      *               Hash( handshake ) )[0.11]
03176      */
03177 
03178 #if !defined(POLARSSL_SHA256_ALT)
03179     SSL_DEBUG_BUF( 4, "finished sha2 state", (unsigned char *)
03180                    sha256.state , sizeof( sha256.state  ) );
03181 #endif
03182 
03183     sender = ( from == SSL_IS_CLIENT )
03184              ? "client finished"
03185              : "server finished";
03186 
03187     sha256_finish( &sha256, padbuf );
03188 
03189     ssl->handshake->tls_prf( session->master, 48, sender,
03190                              padbuf, 32, buf, len );
03191 
03192     SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
03193 
03194     sha256_free( &sha256 );
03195 
03196     polarssl_zeroize(  padbuf, sizeof(  padbuf ) );
03197 
03198     SSL_DEBUG_MSG( 2, ( "<= calc  finished" ) );
03199 }
03200 #endif /* POLARSSL_SHA256_C */
03201 
03202 #if defined(POLARSSL_SHA512_C)
03203 static void ssl_calc_finished_tls_sha384(
03204                 ssl_context *ssl, unsigned char *buf, int from )
03205 {
03206     int len = 12;
03207     const char *sender;
03208     sha512_context sha512;
03209     unsigned char padbuf[48];
03210 
03211     ssl_session *session = ssl->session_negotiate;
03212     if( !session )
03213         session = ssl->session;
03214 
03215     SSL_DEBUG_MSG( 2, ( "=> calc  finished tls sha384" ) );
03216 
03217     memcpy( &sha512, &ssl->handshake->fin_sha512, sizeof(sha512_context) );
03218 
03219     /*
03220      * TLSv1.2:
03221      *   hash = PRF( master, finished_label,
03222      *               Hash( handshake ) )[0.11]
03223      */
03224 
03225 #if !defined(POLARSSL_SHA512_ALT)
03226     SSL_DEBUG_BUF( 4, "finished sha512 state", (unsigned char *)
03227                    sha512.state , sizeof( sha512.state  ) );
03228 #endif
03229 
03230     sender = ( from == SSL_IS_CLIENT )
03231              ? "client finished"
03232              : "server finished";
03233 
03234     sha512_finish( &sha512, padbuf );
03235 
03236     ssl->handshake->tls_prf( session->master, 48, sender,
03237                              padbuf, 48, buf, len );
03238 
03239     SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
03240 
03241     sha512_free( &sha512 );
03242 
03243     polarssl_zeroize(  padbuf, sizeof( padbuf ) );
03244 
03245     SSL_DEBUG_MSG( 2, ( "<= calc  finished" ) );
03246 }
03247 #endif /* POLARSSL_SHA512_C */
03248 #endif /* POLARSSL_SSL_PROTO_TLS1_2 */
03249 
03250 void ssl_handshake_wrapup( ssl_context *ssl )
03251 {
03252     int resume = ssl->handshake->resume;
03253 
03254     SSL_DEBUG_MSG( 3, ( "=> handshake wrapup" ) );
03255 
03256     /*
03257      * Free our handshake params
03258      */
03259     ssl_handshake_free( ssl->handshake );
03260     polarssl_free( ssl->handshake );
03261     ssl->handshake = NULL;
03262 
03263 #if defined(POLARSSL_SSL_RENEGOTIATION)
03264     if( ssl->renegotiation == SSL_RENEGOTIATION )
03265     {
03266         ssl->renegotiation =  SSL_RENEGOTIATION_DONE;
03267         ssl->renego_records_seen = 0;
03268     }
03269 #endif
03270 
03271     /*
03272      * Switch in our now active transform context
03273      */
03274     if( ssl->transform )
03275     {
03276         ssl_transform_free( ssl->transform );
03277         polarssl_free( ssl->transform );
03278     }
03279     ssl->transform = ssl->transform_negotiate;
03280     ssl->transform_negotiate = NULL;
03281 
03282     if( ssl->session )
03283     {
03284 #if defined(POLARSSL_SSL_ENCRYPT_THEN_MAC)
03285         /* RFC 7366 3.1: keep the EtM state */
03286         ssl->session_negotiate->encrypt_then_mac =
03287                   ssl->session->encrypt_then_mac;
03288 #endif
03289 
03290         ssl_session_free( ssl->session );
03291         polarssl_free( ssl->session );
03292     }
03293     ssl->session = ssl->session_negotiate;
03294     ssl->session_negotiate = NULL;
03295 
03296     /*
03297      * Add cache entry
03298      */
03299     if( ssl->f_set_cache != NULL &&
03300         ssl->session->length != 0 &&
03301         resume == 0 )
03302     {
03303         if( ssl->f_set_cache( ssl->p_set_cache, ssl->session ) != 0 )
03304             SSL_DEBUG_MSG( 1, ( "cache did not store session" ) );
03305     }
03306 
03307     ssl->state++;
03308 
03309     SSL_DEBUG_MSG( 3, ( "<= handshake wrapup" ) );
03310 }
03311 
03312 int ssl_write_finished( ssl_context *ssl )
03313 {
03314     int ret, hash_len;
03315 
03316     SSL_DEBUG_MSG( 2, ( "=> write finished" ) );
03317 
03318     /*
03319      * Set the out_msg pointer to the correct location based on IV length
03320      */
03321     if( ssl->minor_ver >= SSL_MINOR_VERSION_2 )
03322     {
03323         ssl->out_msg = ssl->out_iv + ssl->transform_negotiate->ivlen -
03324                        ssl->transform_negotiate->fixed_ivlen;
03325     }
03326     else
03327         ssl->out_msg = ssl->out_iv;
03328 
03329     ssl->handshake->calc_finished( ssl, ssl->out_msg + 4, ssl->endpoint );
03330 
03331     // TODO TLS/1.2 Hash length is determined by cipher suite (Page 63)
03332     hash_len = ( ssl->minor_ver == SSL_MINOR_VERSION_0 ) ? 36 : 12;
03333 
03334 #if defined(POLARSSL_SSL_RENEGOTIATION)
03335     ssl->verify_data_len = hash_len;
03336     memcpy( ssl->own_verify_data, ssl->out_msg + 4, hash_len );
03337 #endif
03338 
03339     ssl->out_msglen  = 4 + hash_len;
03340     ssl->out_msgtype = SSL_MSG_HANDSHAKE;
03341     ssl->out_msg[0]  = SSL_HS_FINISHED;
03342 
03343     /*
03344      * In case of session resuming, invert the client and server
03345      * ChangeCipherSpec messages order.
03346      */
03347     if( ssl->handshake->resume != 0 )
03348     {
03349 #if defined(POLARSSL_SSL_CLI_C)
03350         if( ssl->endpoint == SSL_IS_CLIENT )
03351             ssl->state = SSL_HANDSHAKE_WRAPUP;
03352 #endif
03353 #if defined(POLARSSL_SSL_SRV_C)
03354         if( ssl->endpoint == SSL_IS_SERVER )
03355             ssl->state = SSL_CLIENT_CHANGE_CIPHER_SPEC;
03356 #endif
03357     }
03358     else
03359         ssl->state++;
03360 
03361     /*
03362      * Switch to our negotiated transform and session parameters for outbound
03363      * data.
03364      */
03365     SSL_DEBUG_MSG( 3, ( "switching to new transform spec for outbound data" ) );
03366     ssl->transform_out = ssl->transform_negotiate;
03367     ssl->session_out = ssl->session_negotiate;
03368     memset( ssl->out_ctr, 0, 8 );
03369 
03370 #if defined(POLARSSL_SSL_HW_RECORD_ACCEL)
03371     if( ssl_hw_record_activate != NULL )
03372     {
03373         if( ( ret = ssl_hw_record_activate( ssl, SSL_CHANNEL_OUTBOUND ) ) != 0 )
03374         {
03375             SSL_DEBUG_RET( 1, "ssl_hw_record_activate", ret );
03376             return( POLARSSL_ERR_SSL_HW_ACCEL_FAILED );
03377         }
03378     }
03379 #endif
03380 
03381     if( ( ret = ssl_write_record( ssl ) ) != 0 )
03382     {
03383         SSL_DEBUG_RET( 1, "ssl_write_record", ret );
03384         return( ret );
03385     }
03386 
03387     SSL_DEBUG_MSG( 2, ( "<= write finished" ) );
03388 
03389     return( 0 );
03390 }
03391 
03392 int ssl_parse_finished( ssl_context *ssl )
03393 {
03394     int ret;
03395     unsigned int hash_len;
03396     unsigned char buf[36];
03397 
03398     SSL_DEBUG_MSG( 2, ( "=> parse finished" ) );
03399 
03400     ssl->handshake->calc_finished( ssl, buf, ssl->endpoint ^ 1 );
03401 
03402     /*
03403      * Switch to our negotiated transform and session parameters for inbound
03404      * data.
03405      */
03406     SSL_DEBUG_MSG( 3, ( "switching to new transform spec for inbound data" ) );
03407     ssl->transform_in = ssl->transform_negotiate;
03408     ssl->session_in = ssl->session_negotiate;
03409     memset( ssl->in_ctr, 0, 8 );
03410 
03411     /*
03412      * Set the in_msg pointer to the correct location based on IV length
03413      */
03414     if( ssl->minor_ver >= SSL_MINOR_VERSION_2 )
03415     {
03416         ssl->in_msg = ssl->in_iv + ssl->transform_negotiate->ivlen -
03417                       ssl->transform_negotiate->fixed_ivlen;
03418     }
03419     else
03420         ssl->in_msg = ssl->in_iv;
03421 
03422 #if defined(POLARSSL_SSL_HW_RECORD_ACCEL)
03423     if( ssl_hw_record_activate != NULL )
03424     {
03425         if( ( ret = ssl_hw_record_activate( ssl, SSL_CHANNEL_INBOUND ) ) != 0 )
03426         {
03427             SSL_DEBUG_RET( 1, "ssl_hw_record_activate", ret );
03428             return( POLARSSL_ERR_SSL_HW_ACCEL_FAILED );
03429         }
03430     }
03431 #endif
03432 
03433     if( ( ret = ssl_read_record( ssl ) ) != 0 )
03434     {
03435         SSL_DEBUG_RET( 1, "ssl_read_record", ret );
03436         return( ret );
03437     }
03438 
03439     if( ssl->in_msgtype != SSL_MSG_HANDSHAKE )
03440     {
03441         SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
03442         return( POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE );
03443     }
03444 
03445     // TODO TLS/1.2 Hash length is determined by cipher suite (Page 63)
03446     hash_len = ( ssl->minor_ver == SSL_MINOR_VERSION_0 ) ? 36 : 12;
03447 
03448     if( ssl->in_msg[0] != SSL_HS_FINISHED ||
03449         ssl->in_hslen  != 4 + hash_len )
03450     {
03451         SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
03452         return( POLARSSL_ERR_SSL_BAD_HS_FINISHED );
03453     }
03454 
03455     if( safer_memcmp( ssl->in_msg + 4, buf, hash_len ) != 0 )
03456     {
03457         SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
03458         return( POLARSSL_ERR_SSL_BAD_HS_FINISHED );
03459     }
03460 
03461 #if defined(POLARSSL_SSL_RENEGOTIATION)
03462     ssl->verify_data_len = hash_len;
03463     memcpy( ssl->peer_verify_data, buf, hash_len );
03464 #endif
03465 
03466     if( ssl->handshake->resume != 0 )
03467     {
03468 #if defined(POLARSSL_SSL_CLI_C)
03469         if( ssl->endpoint == SSL_IS_CLIENT )
03470             ssl->state = SSL_CLIENT_CHANGE_CIPHER_SPEC;
03471 #endif
03472 #if defined(POLARSSL_SSL_SRV_C)
03473         if( ssl->endpoint == SSL_IS_SERVER )
03474             ssl->state = SSL_HANDSHAKE_WRAPUP;
03475 #endif
03476     }
03477     else
03478         ssl->state++;
03479 
03480     SSL_DEBUG_MSG( 2, ( "<= parse finished" ) );
03481 
03482     return( 0 );
03483 }
03484 
03485 static void ssl_handshake_params_init( ssl_handshake_params *handshake )
03486 {
03487     memset( handshake, 0, sizeof( ssl_handshake_params ) );
03488 
03489 #if defined(POLARSSL_SSL_PROTO_SSL3) || defined(POLARSSL_SSL_PROTO_TLS1) || \
03490     defined(POLARSSL_SSL_PROTO_TLS1_1)
03491      md5_init(   &handshake->fin_md5  );
03492     sha1_init(   &handshake->fin_sha1 );
03493      md5_starts( &handshake->fin_md5  );
03494     sha1_starts( &handshake->fin_sha1 );
03495 #endif
03496 #if defined(POLARSSL_SSL_PROTO_TLS1_2)
03497 #if defined(POLARSSL_SHA256_C)
03498     sha256_init(   &handshake->fin_sha256    );
03499     sha256_starts( &handshake->fin_sha256, 0 );
03500 #endif
03501 #if defined(POLARSSL_SHA512_C)
03502     sha512_init(   &handshake->fin_sha512    );
03503     sha512_starts( &handshake->fin_sha512, 1 );
03504 #endif
03505 #endif /* POLARSSL_SSL_PROTO_TLS1_2 */
03506 
03507     handshake->update_checksum = ssl_update_checksum_start;
03508     handshake->sig_alg = SSL_HASH_SHA1;
03509 
03510 #if defined(POLARSSL_DHM_C)
03511     dhm_init( &handshake->dhm_ctx );
03512 #endif
03513 #if defined(POLARSSL_ECDH_C)
03514     ecdh_init( &handshake->ecdh_ctx );
03515 #endif
03516 }
03517 
03518 static void ssl_transform_init( ssl_transform *transform )
03519 {
03520     memset( transform, 0, sizeof(ssl_transform) );
03521 
03522     cipher_init( &transform->cipher_ctx_enc );
03523     cipher_init( &transform->cipher_ctx_dec );
03524 
03525     md_init( &transform->md_ctx_enc );
03526     md_init( &transform->md_ctx_dec );
03527 }
03528 
03529 void ssl_session_init( ssl_session *session )
03530 {
03531     memset( session, 0, sizeof(ssl_session) );
03532 }
03533 
03534 static int ssl_handshake_init( ssl_context *ssl )
03535 {
03536     /* Clear old handshake information if present */
03537     if( ssl->transform_negotiate )
03538         ssl_transform_free( ssl->transform_negotiate );
03539     if( ssl->session_negotiate )
03540         ssl_session_free( ssl->session_negotiate );
03541     if( ssl->handshake )
03542         ssl_handshake_free( ssl->handshake );
03543 
03544     /*
03545      * Either the pointers are now NULL or cleared properly and can be freed.
03546      * Now allocate missing structures.
03547      */
03548     if( ssl->transform_negotiate == NULL )
03549     {
03550         ssl->transform_negotiate = polarssl_malloc( sizeof(ssl_transform) );
03551     }
03552 
03553     if( ssl->session_negotiate == NULL )
03554     {
03555         ssl->session_negotiate = polarssl_malloc( sizeof(ssl_session) );
03556     }
03557 
03558     if( ssl->handshake == NULL )
03559     {
03560         ssl->handshake = polarssl_malloc( sizeof(ssl_handshake_params) );
03561     }
03562 
03563     /* All pointers should exist and can be directly freed without issue */
03564     if( ssl->handshake == NULL ||
03565         ssl->transform_negotiate == NULL ||
03566         ssl->session_negotiate == NULL )
03567     {
03568         SSL_DEBUG_MSG( 1, ( "malloc() of ssl sub-contexts failed" ) );
03569 
03570         polarssl_free( ssl->handshake );
03571         polarssl_free( ssl->transform_negotiate );
03572         polarssl_free( ssl->session_negotiate );
03573 
03574         ssl->handshake = NULL;
03575         ssl->transform_negotiate = NULL;
03576         ssl->session_negotiate = NULL;
03577 
03578         return( POLARSSL_ERR_SSL_MALLOC_FAILED );
03579     }
03580 
03581     /* Initialize structures */
03582     ssl_session_init( ssl->session_negotiate );
03583     ssl_transform_init( ssl->transform_negotiate );
03584     ssl_handshake_params_init( ssl->handshake );
03585 
03586 #if defined(POLARSSL_X509_CRT_PARSE_C)
03587     ssl->handshake->key_cert = ssl->key_cert;
03588 #endif
03589 
03590     return( 0 );
03591 }
03592 
03593 /*
03594  * Initialize an SSL context
03595  */
03596 int ssl_init( ssl_context *ssl )
03597 {
03598     int ret;
03599     int len = SSL_BUFFER_LEN;
03600 
03601     memset( ssl, 0, sizeof( ssl_context ) );
03602 
03603     /*
03604      * Sane defaults
03605      */
03606     ssl->min_major_ver = SSL_MIN_MAJOR_VERSION;
03607     ssl->min_minor_ver = SSL_MIN_MINOR_VERSION;
03608     ssl->max_major_ver = SSL_MAX_MAJOR_VERSION;
03609     ssl->max_minor_ver = SSL_MAX_MINOR_VERSION;
03610 
03611     ssl_set_ciphersuites( ssl, ssl_list_ciphersuites() );
03612 
03613 #if defined(POLARSSL_SSL_RENEGOTIATION)
03614     ssl->renego_max_records = SSL_RENEGO_MAX_RECORDS_DEFAULT;
03615     memset( ssl->renego_period, 0xFF, 7 );
03616     ssl->renego_period[7] = 0x00;
03617 #endif
03618 
03619 #if defined(POLARSSL_DHM_C)
03620     if( ( ret = mpi_read_string( &ssl->dhm_P, 16,
03621                                  POLARSSL_DHM_RFC5114_MODP_1024_P) ) != 0 ||
03622         ( ret = mpi_read_string( &ssl->dhm_G, 16,
03623                                  POLARSSL_DHM_RFC5114_MODP_1024_G) ) != 0 )
03624     {
03625         SSL_DEBUG_RET( 1, "mpi_read_string", ret );
03626         return( ret );
03627     }
03628 #endif
03629 
03630     /*
03631      * Prepare base structures
03632      */
03633     if( ( ssl->in_ctr = polarssl_malloc( len ) ) == NULL ||
03634         ( ssl->out_ctr = polarssl_malloc( len ) ) == NULL )
03635     {
03636         SSL_DEBUG_MSG( 1, ( "malloc(%d bytes) failed", len ) );
03637         polarssl_free( ssl->in_ctr );
03638         ssl->in_ctr = NULL;
03639         return( POLARSSL_ERR_SSL_MALLOC_FAILED );
03640     }
03641 
03642     memset( ssl-> in_ctr, 0, SSL_BUFFER_LEN );
03643     memset( ssl->out_ctr, 0, SSL_BUFFER_LEN );
03644 
03645     ssl->in_hdr = ssl->in_ctr +  8;
03646     ssl->in_iv  = ssl->in_ctr + 13;
03647     ssl->in_msg = ssl->in_ctr + 13;
03648 
03649     ssl->out_hdr = ssl->out_ctr +  8;
03650     ssl->out_iv  = ssl->out_ctr + 13;
03651     ssl->out_msg = ssl->out_ctr + 13;
03652 
03653 #if defined(POLARSSL_SSL_ENCRYPT_THEN_MAC)
03654     ssl->encrypt_then_mac = SSL_ETM_ENABLED;
03655 #endif
03656 
03657 #if defined(POLARSSL_SSL_EXTENDED_MASTER_SECRET)
03658     ssl->extended_ms = SSL_EXTENDED_MS_ENABLED;
03659 #endif
03660 
03661 #if defined(POLARSSL_SSL_SESSION_TICKETS)
03662     ssl->ticket_lifetime = SSL_DEFAULT_TICKET_LIFETIME;
03663 #endif
03664 
03665 #if defined(POLARSSL_SSL_SET_CURVES)
03666     ssl->curve_list = ecp_grp_id_list( );
03667 #endif
03668 
03669     if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
03670         return( ret );
03671 
03672     return( 0 );
03673 }
03674 
03675 /*
03676  * Reset an initialized and used SSL context for re-use while retaining
03677  * all application-set variables, function pointers and data.
03678  */
03679 int ssl_session_reset( ssl_context *ssl )
03680 {
03681     int ret;
03682 
03683     ssl->state = SSL_HELLO_REQUEST;
03684 
03685 #if defined(POLARSSL_SSL_RENEGOTIATION)
03686     ssl->renegotiation = SSL_INITIAL_HANDSHAKE;
03687     ssl->renego_records_seen = 0;
03688 
03689     ssl->verify_data_len = 0;
03690     memset( ssl->own_verify_data, 0, SSL_VERIFY_DATA_MAX_LEN );
03691     memset( ssl->peer_verify_data, 0, SSL_VERIFY_DATA_MAX_LEN );
03692 #endif
03693     ssl->secure_renegotiation = SSL_LEGACY_RENEGOTIATION;
03694 
03695     ssl->in_offt = NULL;
03696 
03697     ssl->in_msg = ssl->in_ctr + 13;
03698     ssl->in_msgtype = 0;
03699     ssl->in_msglen = 0;
03700     ssl->in_left = 0;
03701 
03702     ssl->in_hslen = 0;
03703     ssl->nb_zero = 0;
03704     ssl->record_read = 0;
03705 
03706     ssl->out_msg = ssl->out_ctr + 13;
03707     ssl->out_msgtype = 0;
03708     ssl->out_msglen = 0;
03709     ssl->out_left = 0;
03710 #if defined(POLARSSL_SSL_CBC_RECORD_SPLITTING)
03711     if( ssl->split_done != SSL_CBC_RECORD_SPLITTING_DISABLED )
03712         ssl->split_done = 0;
03713 #endif
03714 
03715     ssl->transform_in = NULL;
03716     ssl->transform_out = NULL;
03717 
03718     memset( ssl->out_ctr, 0, SSL_BUFFER_LEN );
03719     memset( ssl->in_ctr, 0, SSL_BUFFER_LEN );
03720 
03721 #if defined(POLARSSL_SSL_HW_RECORD_ACCEL)
03722     if( ssl_hw_record_reset != NULL )
03723     {
03724         SSL_DEBUG_MSG( 2, ( "going for ssl_hw_record_reset()" ) );
03725         if( ( ret = ssl_hw_record_reset( ssl ) ) != 0 )
03726         {
03727             SSL_DEBUG_RET( 1, "ssl_hw_record_reset", ret );
03728             return( POLARSSL_ERR_SSL_HW_ACCEL_FAILED );
03729         }
03730     }
03731 #endif
03732 
03733     if( ssl->transform )
03734     {
03735         ssl_transform_free( ssl->transform );
03736         polarssl_free( ssl->transform );
03737         ssl->transform = NULL;
03738     }
03739 
03740     if( ssl->session )
03741     {
03742         ssl_session_free( ssl->session );
03743         polarssl_free( ssl->session );
03744         ssl->session = NULL;
03745     }
03746 
03747 #if defined(POLARSSL_SSL_ALPN)
03748     ssl->alpn_chosen = NULL;
03749 #endif
03750 
03751     if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
03752         return( ret );
03753 
03754     return( 0 );
03755 }
03756 
03757 #if defined(POLARSSL_SSL_SESSION_TICKETS)
03758 static void ssl_ticket_keys_free( ssl_ticket_keys *tkeys )
03759 {
03760     aes_free( &tkeys->enc );
03761     aes_free( &tkeys->dec );
03762 
03763     polarssl_zeroize( tkeys, sizeof(ssl_ticket_keys) );
03764 }
03765 
03766 /*
03767  * Allocate and initialize ticket keys
03768  */
03769 static int ssl_ticket_keys_init( ssl_context *ssl )
03770 {
03771     int ret;
03772     ssl_ticket_keys *tkeys;
03773     unsigned char buf[16];
03774 
03775     if( ssl->ticket_keys != NULL )
03776         return( 0 );
03777 
03778     tkeys = polarssl_malloc( sizeof(ssl_ticket_keys) );
03779     if( tkeys == NULL )
03780         return( POLARSSL_ERR_SSL_MALLOC_FAILED );
03781 
03782     aes_init( &tkeys->enc );
03783     aes_init( &tkeys->dec );
03784 
03785     if( ( ret = ssl->f_rng( ssl->p_rng, tkeys->key_name, 16 ) ) != 0 )
03786     {
03787         ssl_ticket_keys_free( tkeys );
03788         polarssl_free( tkeys );
03789         return( ret );
03790     }
03791 
03792     if( ( ret = ssl->f_rng( ssl->p_rng, buf, 16 ) ) != 0 ||
03793         ( ret = aes_setkey_enc( &tkeys->enc, buf, 128 ) ) != 0 ||
03794         ( ret = aes_setkey_dec( &tkeys->dec, buf, 128 ) ) != 0 )
03795     {
03796         ssl_ticket_keys_free( tkeys );
03797         polarssl_free( tkeys );
03798         return( ret );
03799     }
03800 
03801     if( ( ret = ssl->f_rng( ssl->p_rng, tkeys->mac_key, 16 ) ) != 0 )
03802     {
03803         ssl_ticket_keys_free( tkeys );
03804         polarssl_free( tkeys );
03805         return( ret );
03806     }
03807 
03808     ssl->ticket_keys = tkeys;
03809 
03810     return( 0 );
03811 }
03812 #endif /* POLARSSL_SSL_SESSION_TICKETS */
03813 
03814 /*
03815  * SSL set accessors
03816  */
03817 void ssl_set_endpoint( ssl_context *ssl, int endpoint )
03818 {
03819     ssl->endpoint   = endpoint;
03820 
03821 #if defined(POLARSSL_SSL_SESSION_TICKETS) && \
03822     defined(POLARSSL_SSL_CLI_C)
03823     if( endpoint == SSL_IS_CLIENT )
03824         ssl->session_tickets = SSL_SESSION_TICKETS_ENABLED;
03825 #endif
03826 
03827 #if defined(POLARSSL_SSL_TRUNCATED_HMAC)
03828     if( endpoint == SSL_IS_SERVER )
03829         ssl->trunc_hmac = SSL_TRUNC_HMAC_ENABLED;
03830 #endif
03831 }
03832 
03833 void ssl_set_authmode( ssl_context *ssl, int authmode )
03834 {
03835     ssl->authmode   = authmode;
03836 }
03837 
03838 #if defined(POLARSSL_X509_CRT_PARSE_C)
03839 void ssl_set_verify( ssl_context *ssl,
03840                      int (*f_vrfy)(void *, x509_crt *, int, int *),
03841                      void *p_vrfy )
03842 {
03843     ssl->f_vrfy      = f_vrfy;
03844     ssl->p_vrfy      = p_vrfy;
03845 }
03846 #endif /* POLARSSL_X509_CRT_PARSE_C */
03847 
03848 void ssl_set_rng( ssl_context *ssl,
03849                   int (*f_rng)(void *, unsigned char *, size_t),
03850                   void *p_rng )
03851 {
03852     ssl->f_rng      = f_rng;
03853     ssl->p_rng      = p_rng;
03854 }
03855 
03856 void ssl_set_dbg( ssl_context *ssl,
03857                   void (*f_dbg)(void *, int, const char *),
03858                   void  *p_dbg )
03859 {
03860     ssl->f_dbg      = f_dbg;
03861     ssl->p_dbg      = p_dbg;
03862 }
03863 
03864 void ssl_set_bio( ssl_context *ssl,
03865             int (*f_recv)(void *, unsigned char *, size_t), void *p_recv,
03866             int (*f_send)(void *, const unsigned char *, size_t), void *p_send )
03867 {
03868     ssl->f_recv     = f_recv;
03869     ssl->f_send     = f_send;
03870     ssl->p_recv     = p_recv;
03871     ssl->p_send     = p_send;
03872 }
03873 
03874 #if defined(POLARSSL_SSL_SRV_C)
03875 void ssl_set_session_cache( ssl_context *ssl,
03876         int (*f_get_cache)(void *, ssl_session *), void *p_get_cache,
03877         int (*f_set_cache)(void *, const ssl_session *), void *p_set_cache )
03878 {
03879     ssl->f_get_cache = f_get_cache;
03880     ssl->p_get_cache = p_get_cache;
03881     ssl->f_set_cache = f_set_cache;
03882     ssl->p_set_cache = p_set_cache;
03883 }
03884 #endif /* POLARSSL_SSL_SRV_C */
03885 
03886 #if defined(POLARSSL_SSL_CLI_C)
03887 int ssl_set_session( ssl_context *ssl, const ssl_session *session )
03888 {
03889     int ret;
03890 
03891     if( ssl == NULL ||
03892         session == NULL ||
03893         ssl->session_negotiate == NULL ||
03894         ssl->endpoint != SSL_IS_CLIENT )
03895     {
03896         return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
03897     }
03898 
03899     if( ( ret = ssl_session_copy( ssl->session_negotiate, session ) ) != 0 )
03900         return( ret );
03901 
03902     ssl->handshake->resume = 1;
03903 
03904     return( 0 );
03905 }
03906 #endif /* POLARSSL_SSL_CLI_C */
03907 
03908 void ssl_set_ciphersuites( ssl_context *ssl, const int *ciphersuites )
03909 {
03910     ssl->ciphersuite_list[SSL_MINOR_VERSION_0] = ciphersuites;
03911     ssl->ciphersuite_list[SSL_MINOR_VERSION_1] = ciphersuites;
03912     ssl->ciphersuite_list[SSL_MINOR_VERSION_2] = ciphersuites;
03913     ssl->ciphersuite_list[SSL_MINOR_VERSION_3] = ciphersuites;
03914 }
03915 
03916 void ssl_set_ciphersuites_for_version( ssl_context *ssl,
03917                                        const int *ciphersuites,
03918                                        int major, int minor )
03919 {
03920     if( major != SSL_MAJOR_VERSION_3 )
03921         return;
03922 
03923     if( minor < SSL_MINOR_VERSION_0 || minor > SSL_MINOR_VERSION_3 )
03924         return;
03925 
03926     ssl->ciphersuite_list[minor] = ciphersuites;
03927 }
03928 
03929 #if defined(POLARSSL_X509_CRT_PARSE_C)
03930 /* Add a new (empty) key_cert entry an return a pointer to it */
03931 static ssl_key_cert *ssl_add_key_cert( ssl_context *ssl )
03932 {
03933     ssl_key_cert *key_cert, *last;
03934 
03935     key_cert = polarssl_malloc( sizeof(ssl_key_cert) );
03936     if( key_cert == NULL )
03937         return( NULL );
03938 
03939     memset( key_cert, 0, sizeof( ssl_key_cert ) );
03940 
03941     /* Append the new key_cert to the (possibly empty) current list */
03942     if( ssl->key_cert == NULL )
03943     {
03944         ssl->key_cert = key_cert;
03945         if( ssl->handshake != NULL )
03946             ssl->handshake->key_cert = key_cert;
03947     }
03948     else
03949     {
03950         last = ssl->key_cert;
03951         while( last->next != NULL )
03952             last = last->next;
03953         last->next = key_cert;
03954     }
03955 
03956     return( key_cert );
03957 }
03958 
03959 void ssl_set_ca_chain( ssl_context *ssl, x509_crt *ca_chain,
03960                        x509_crl *ca_crl, const char *peer_cn )
03961 {
03962     ssl->ca_chain   = ca_chain;
03963     ssl->ca_crl     = ca_crl;
03964     ssl->peer_cn    = peer_cn;
03965 }
03966 
03967 int ssl_set_own_cert( ssl_context *ssl, x509_crt *own_cert,
03968                        pk_context *pk_key )
03969 {
03970     ssl_key_cert *key_cert = ssl_add_key_cert( ssl );
03971 
03972     if( key_cert == NULL )
03973         return( POLARSSL_ERR_SSL_MALLOC_FAILED );
03974 
03975     key_cert->cert = own_cert;
03976     key_cert->key  = pk_key;
03977 
03978     return( 0 );
03979 }
03980 
03981 #if ! defined(POLARSSL_DEPRECATED_REMOVED)
03982 #if defined(POLARSSL_RSA_C)
03983 int ssl_set_own_cert_rsa( ssl_context *ssl, x509_crt *own_cert,
03984                            rsa_context *rsa_key )
03985 {
03986     int ret;
03987     ssl_key_cert *key_cert = ssl_add_key_cert( ssl );
03988 
03989     if( key_cert == NULL )
03990         return( POLARSSL_ERR_SSL_MALLOC_FAILED );
03991 
03992     key_cert->key = polarssl_malloc( sizeof(pk_context) );
03993     if( key_cert->key == NULL )
03994         return( POLARSSL_ERR_SSL_MALLOC_FAILED );
03995 
03996     pk_init( key_cert->key );
03997 
03998     ret = pk_init_ctx( key_cert->key, pk_info_from_type( POLARSSL_PK_RSA ) );
03999     if( ret != 0 )
04000         return( ret );
04001 
04002     if( ( ret = rsa_copy( pk_rsa( *key_cert->key ), rsa_key ) ) != 0 )
04003         return( ret );
04004 
04005     key_cert->cert = own_cert;
04006     key_cert->key_own_alloc = 1;
04007 
04008     return( 0 );
04009 }
04010 #endif /* POLARSSL_RSA_C */
04011 
04012 int ssl_set_own_cert_alt( ssl_context *ssl, x509_crt *own_cert,
04013                           void *rsa_key,
04014                           rsa_decrypt_func rsa_decrypt,
04015                           rsa_sign_func rsa_sign,
04016                           rsa_key_len_func rsa_key_len )
04017 {
04018     int ret;
04019     ssl_key_cert *key_cert = ssl_add_key_cert( ssl );
04020 
04021     if( key_cert == NULL )
04022         return( POLARSSL_ERR_SSL_MALLOC_FAILED );
04023 
04024     key_cert->key = polarssl_malloc( sizeof(pk_context) );
04025     if( key_cert->key == NULL )
04026         return( POLARSSL_ERR_SSL_MALLOC_FAILED );
04027 
04028     pk_init( key_cert->key );
04029 
04030     if( ( ret = pk_init_ctx_rsa_alt( key_cert->key, rsa_key,
04031                                  rsa_decrypt, rsa_sign, rsa_key_len ) ) != 0 )
04032         return( ret );
04033 
04034     key_cert->cert = own_cert;
04035     key_cert->key_own_alloc = 1;
04036 
04037     return( 0 );
04038 }
04039 #endif /* POLARSSL_DEPRECATED_REMOVED */
04040 #endif /* POLARSSL_X509_CRT_PARSE_C */
04041 
04042 #if defined(POLARSSL_KEY_EXCHANGE__SOME__PSK_ENABLED)
04043 int ssl_set_psk( ssl_context *ssl, const unsigned char *psk, size_t psk_len,
04044                  const unsigned char *psk_identity, size_t psk_identity_len )
04045 {
04046     if( psk == NULL || psk_identity == NULL )
04047         return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
04048 
04049     if( psk_len > POLARSSL_PSK_MAX_LEN )
04050         return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
04051 
04052     if( ssl->psk != NULL || ssl->psk_identity != NULL )
04053     {
04054         polarssl_free( ssl->psk );
04055         polarssl_free( ssl->psk_identity );
04056     }
04057 
04058     if( ( ssl->psk = polarssl_malloc( psk_len ) ) == NULL ||
04059         ( ssl->psk_identity = polarssl_malloc( psk_identity_len ) ) == NULL )
04060     {
04061         polarssl_free( ssl->psk );
04062         ssl->psk = NULL;
04063         return( POLARSSL_ERR_SSL_MALLOC_FAILED );
04064     }
04065 
04066     ssl->psk_len = psk_len;
04067     ssl->psk_identity_len = psk_identity_len;
04068 
04069     memcpy( ssl->psk, psk, ssl->psk_len );
04070     memcpy( ssl->psk_identity, psk_identity, ssl->psk_identity_len );
04071 
04072     return( 0 );
04073 }
04074 
04075 void ssl_set_psk_cb( ssl_context *ssl,
04076                      int (*f_psk)(void *, ssl_context *, const unsigned char *,
04077                      size_t),
04078                      void *p_psk )
04079 {
04080     ssl->f_psk = f_psk;
04081     ssl->p_psk = p_psk;
04082 }
04083 #endif /* POLARSSL_KEY_EXCHANGE__SOME__PSK_ENABLED */
04084 
04085 #if defined(POLARSSL_DHM_C)
04086 int ssl_set_dh_param( ssl_context *ssl, const char *dhm_P, const char *dhm_G )
04087 {
04088     int ret;
04089 
04090     if( ( ret = mpi_read_string( &ssl->dhm_P, 16, dhm_P ) ) != 0 )
04091     {
04092         SSL_DEBUG_RET( 1, "mpi_read_string", ret );
04093         return( ret );
04094     }
04095 
04096     if( ( ret = mpi_read_string( &ssl->dhm_G, 16, dhm_G ) ) != 0 )
04097     {
04098         SSL_DEBUG_RET( 1, "mpi_read_string", ret );
04099         return( ret );
04100     }
04101 
04102     return( 0 );
04103 }
04104 
04105 int ssl_set_dh_param_ctx( ssl_context *ssl, dhm_context *dhm_ctx )
04106 {
04107     int ret;
04108 
04109     if( ( ret = mpi_copy( &ssl->dhm_P, &dhm_ctx->P  ) ) != 0 )
04110     {
04111         SSL_DEBUG_RET( 1, "mpi_copy", ret );
04112         return( ret );
04113     }
04114 
04115     if( ( ret = mpi_copy( &ssl->dhm_G, &dhm_ctx->G  ) ) != 0 )
04116     {
04117         SSL_DEBUG_RET( 1, "mpi_copy", ret );
04118         return( ret );
04119     }
04120 
04121     return( 0 );
04122 }
04123 #endif /* POLARSSL_DHM_C */
04124 
04125 #if defined(POLARSSL_SSL_SET_CURVES)
04126 /*
04127  * Set the allowed elliptic curves
04128  */
04129 void ssl_set_curves( ssl_context *ssl, const ecp_group_id *curve_list )
04130 {
04131   ssl->curve_list = curve_list;
04132 }
04133 #endif
04134 
04135 #if defined(POLARSSL_SSL_SERVER_NAME_INDICATION)
04136 int ssl_set_hostname( ssl_context *ssl, const char *hostname )
04137 {
04138     if( hostname == NULL )
04139         return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
04140 
04141     ssl->hostname_len = strlen( hostname );
04142 
04143     if( ssl->hostname_len + 1 == 0 )
04144         return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
04145 
04146     ssl->hostname = polarssl_malloc( ssl->hostname_len + 1 );
04147 
04148     if( ssl->hostname == NULL )
04149         return( POLARSSL_ERR_SSL_MALLOC_FAILED );
04150 
04151     memcpy( ssl->hostname, (const unsigned char *) hostname,
04152             ssl->hostname_len );
04153 
04154     ssl->hostname[ssl->hostname_len] = '\0';
04155 
04156     return( 0 );
04157 }
04158 
04159 void ssl_set_sni( ssl_context *ssl,
04160                   int (*f_sni)(void *, ssl_context *,
04161                                 const unsigned char *, size_t),
04162                   void *p_sni )
04163 {
04164     ssl->f_sni = f_sni;
04165     ssl->p_sni = p_sni;
04166 }
04167 #endif /* POLARSSL_SSL_SERVER_NAME_INDICATION */
04168 
04169 #if defined(POLARSSL_SSL_ALPN)
04170 int ssl_set_alpn_protocols( ssl_context *ssl, const char **protos )
04171 {
04172     size_t cur_len, tot_len;
04173     const char **p;
04174 
04175     /*
04176      * "Empty strings MUST NOT be included and byte strings MUST NOT be
04177      * truncated". Check lengths now rather than later.
04178      */
04179     tot_len = 0;
04180     for( p = protos; *p != NULL; p++ )
04181     {
04182         cur_len = strlen( *p );
04183         tot_len += cur_len;
04184 
04185         if( cur_len == 0 || cur_len > 255 || tot_len > 65535 )
04186             return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
04187     }
04188 
04189     ssl->alpn_list = protos;
04190 
04191     return( 0 );
04192 }
04193 
04194 const char *ssl_get_alpn_protocol( const ssl_context *ssl )
04195 {
04196     return( ssl->alpn_chosen );
04197 }
04198 #endif /* POLARSSL_SSL_ALPN */
04199 
04200 void ssl_set_max_version( ssl_context *ssl, int major, int minor )
04201 {
04202     if( major >= SSL_MIN_MAJOR_VERSION && major <= SSL_MAX_MAJOR_VERSION &&
04203         minor >= SSL_MIN_MINOR_VERSION && minor <= SSL_MAX_MINOR_VERSION )
04204     {
04205         ssl->max_major_ver = major;
04206         ssl->max_minor_ver = minor;
04207     }
04208 }
04209 
04210 void ssl_set_min_version( ssl_context *ssl, int major, int minor )
04211 {
04212     if( major >= SSL_MIN_MAJOR_VERSION && major <= SSL_MAX_MAJOR_VERSION &&
04213         minor >= SSL_MIN_MINOR_VERSION && minor <= SSL_MAX_MINOR_VERSION )
04214     {
04215         ssl->min_major_ver = major;
04216         ssl->min_minor_ver = minor;
04217     }
04218 }
04219 
04220 #if defined(POLARSSL_SSL_FALLBACK_SCSV) && defined(POLARSSL_SSL_CLI_C)
04221 void ssl_set_fallback( ssl_context *ssl, char fallback )
04222 {
04223     ssl->fallback = fallback;
04224 }
04225 #endif
04226 
04227 #if defined(POLARSSL_SSL_ENCRYPT_THEN_MAC)
04228 void ssl_set_encrypt_then_mac( ssl_context *ssl, char etm )
04229 {
04230     ssl->encrypt_then_mac = etm;
04231 }
04232 #endif
04233 
04234 #if defined(POLARSSL_SSL_EXTENDED_MASTER_SECRET)
04235 void ssl_set_extended_master_secret( ssl_context *ssl, char ems )
04236 {
04237     ssl->extended_ms = ems;
04238 }
04239 #endif
04240 
04241 void ssl_set_arc4_support( ssl_context *ssl, char arc4 )
04242 {
04243     ssl->arc4_disabled = arc4;
04244 }
04245 
04246 #if defined(POLARSSL_SSL_MAX_FRAGMENT_LENGTH)
04247 int ssl_set_max_frag_len( ssl_context *ssl, unsigned char mfl_code )
04248 {
04249     if( mfl_code >= SSL_MAX_FRAG_LEN_INVALID ||
04250         mfl_code_to_length[mfl_code] > SSL_MAX_CONTENT_LEN )
04251     {
04252         return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
04253     }
04254 
04255     ssl->mfl_code = mfl_code;
04256 
04257     return( 0 );
04258 }
04259 #endif /* POLARSSL_SSL_MAX_FRAGMENT_LENGTH */
04260 
04261 #if defined(POLARSSL_SSL_TRUNCATED_HMAC)
04262 int ssl_set_truncated_hmac( ssl_context *ssl, int truncate )
04263 {
04264     ssl->trunc_hmac = truncate;
04265 
04266     return( 0 );
04267 }
04268 #endif /* POLARSSL_SSL_TRUNCATED_HMAC */
04269 
04270 #if defined(POLARSSL_SSL_CBC_RECORD_SPLITTING)
04271 void ssl_set_cbc_record_splitting( ssl_context *ssl, char split )
04272 {
04273     ssl->split_done = split;
04274 }
04275 #endif
04276 
04277 void ssl_legacy_renegotiation( ssl_context *ssl, int allow_legacy )
04278 {
04279     ssl->allow_legacy_renegotiation = allow_legacy;
04280 }
04281 
04282 #if defined(POLARSSL_SSL_RENEGOTIATION)
04283 void ssl_set_renegotiation( ssl_context *ssl, int renegotiation )
04284 {
04285     ssl->disable_renegotiation = renegotiation;
04286 }
04287 
04288 void ssl_set_renegotiation_enforced( ssl_context *ssl, int max_records )
04289 {
04290     ssl->renego_max_records = max_records;
04291 }
04292 
04293 void ssl_set_renegotiation_period( ssl_context *ssl,
04294                                    const unsigned char period[8] )
04295 {
04296     memcpy( ssl->renego_period, period, 8 );
04297 }
04298 #endif /* POLARSSL_SSL_RENEGOTIATION */
04299 
04300 #if defined(POLARSSL_SSL_SESSION_TICKETS)
04301 int ssl_set_session_tickets( ssl_context *ssl, int use_tickets )
04302 {
04303     ssl->session_tickets = use_tickets;
04304 
04305 #if defined(POLARSSL_SSL_CLI_C)
04306     if( ssl->endpoint == SSL_IS_CLIENT )
04307         return( 0 );
04308 #endif
04309 
04310     if( use_tickets == SSL_SESSION_TICKETS_DISABLED )
04311         return( 0 );
04312 
04313     if( ssl->f_rng == NULL )
04314         return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
04315 
04316     return( ssl_ticket_keys_init( ssl ) );
04317 }
04318 
04319 void ssl_set_session_ticket_lifetime( ssl_context *ssl, int lifetime )
04320 {
04321     ssl->ticket_lifetime = lifetime;
04322 }
04323 #endif /* POLARSSL_SSL_SESSION_TICKETS */
04324 
04325 /*
04326  * SSL get accessors
04327  */
04328 size_t ssl_get_bytes_avail( const ssl_context *ssl )
04329 {
04330     return( ssl->in_offt == NULL ? 0 : ssl->in_msglen );
04331 }
04332 
04333 int ssl_get_verify_result( const ssl_context *ssl )
04334 {
04335     if( ssl->session != NULL )
04336         return( ssl->session->verify_result );
04337 
04338     if( ssl->session_negotiate != NULL )
04339         return( ssl->session_negotiate->verify_result );
04340 
04341     return( -1 );
04342 }
04343 
04344 const char *ssl_get_ciphersuite( const ssl_context *ssl )
04345 {
04346     if( ssl == NULL || ssl->session == NULL )
04347         return( NULL );
04348 
04349     return ssl_get_ciphersuite_name( ssl->session->ciphersuite );
04350 }
04351 
04352 const char *ssl_get_version( const ssl_context *ssl )
04353 {
04354     switch( ssl->minor_ver )
04355     {
04356         case SSL_MINOR_VERSION_0:
04357             return( "SSLv3.0" );
04358 
04359         case SSL_MINOR_VERSION_1:
04360             return( "TLSv1.0" );
04361 
04362         case SSL_MINOR_VERSION_2:
04363             return( "TLSv1.1" );
04364 
04365         case SSL_MINOR_VERSION_3:
04366             return( "TLSv1.2" );
04367 
04368         default:
04369             break;
04370     }
04371     return( "unknown" );
04372 }
04373 
04374 #if defined(POLARSSL_X509_CRT_PARSE_C)
04375 const x509_crt *ssl_get_peer_cert( const ssl_context *ssl )
04376 {
04377     if( ssl == NULL || ssl->session == NULL )
04378         return( NULL );
04379 
04380     return( ssl->session->peer_cert );
04381 }
04382 #endif /* POLARSSL_X509_CRT_PARSE_C */
04383 
04384 #if defined(POLARSSL_SSL_CLI_C)
04385 int ssl_get_session( const ssl_context *ssl, ssl_session *dst )
04386 {
04387     if( ssl == NULL ||
04388         dst == NULL ||
04389         ssl->session == NULL ||
04390         ssl->endpoint != SSL_IS_CLIENT )
04391     {
04392         return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
04393     }
04394 
04395     return( ssl_session_copy( dst, ssl->session ) );
04396 }
04397 #endif /* POLARSSL_SSL_CLI_C */
04398 
04399 /*
04400  * Perform a single step of the SSL handshake
04401  */
04402 int ssl_handshake_step( ssl_context *ssl )
04403 {
04404     int ret = POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE;
04405 
04406 #if defined(POLARSSL_SSL_CLI_C)
04407     if( ssl->endpoint == SSL_IS_CLIENT )
04408         ret = ssl_handshake_client_step( ssl );
04409 #endif
04410 #if defined(POLARSSL_SSL_SRV_C)
04411     if( ssl->endpoint == SSL_IS_SERVER )
04412         ret = ssl_handshake_server_step( ssl );
04413 #endif
04414 
04415     return( ret );
04416 }
04417 
04418 /*
04419  * Perform the SSL handshake
04420  */
04421 int ssl_handshake( ssl_context *ssl )
04422 {
04423     int ret = 0;
04424 
04425     SSL_DEBUG_MSG( 2, ( "=> handshake" ) );
04426 
04427     while( ssl->state != SSL_HANDSHAKE_OVER )
04428     {
04429         ret = ssl_handshake_step( ssl );
04430 
04431         if( ret != 0 )
04432             break;
04433     }
04434 
04435     SSL_DEBUG_MSG( 2, ( "<= handshake" ) );
04436 
04437     return( ret );
04438 }
04439 
04440 #if defined(POLARSSL_SSL_RENEGOTIATION)
04441 #if defined(POLARSSL_SSL_SRV_C)
04442 /*
04443  * Write HelloRequest to request renegotiation on server
04444  */
04445 static int ssl_write_hello_request( ssl_context *ssl )
04446 {
04447     int ret;
04448 
04449     SSL_DEBUG_MSG( 2, ( "=> write hello request" ) );
04450 
04451     ssl->out_msglen  = 4;
04452     ssl->out_msgtype = SSL_MSG_HANDSHAKE;
04453     ssl->out_msg[0]  = SSL_HS_HELLO_REQUEST;
04454 
04455     if( ( ret = ssl_write_record( ssl ) ) != 0 )
04456     {
04457         SSL_DEBUG_RET( 1, "ssl_write_record", ret );
04458         return( ret );
04459     }
04460 
04461     SSL_DEBUG_MSG( 2, ( "<= write hello request" ) );
04462 
04463     return( 0 );
04464 }
04465 #endif /* POLARSSL_SSL_SRV_C */
04466 
04467 /*
04468  * Actually renegotiate current connection, triggered by either:
04469  * - any side: calling ssl_renegotiate(),
04470  * - client: receiving a HelloRequest during ssl_read(),
04471  * - server: receiving any handshake message on server during ssl_read() after
04472  *   the initial handshake is completed.
04473  * If the handshake doesn't complete due to waiting for I/O, it will continue
04474  * during the next calls to ssl_renegotiate() or ssl_read() respectively.
04475  */
04476 static int ssl_start_renegotiation( ssl_context *ssl )
04477 {
04478     int ret;
04479 
04480     SSL_DEBUG_MSG( 2, ( "=> renegotiate" ) );
04481 
04482     if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
04483         return( ret );
04484 
04485     ssl->state = SSL_HELLO_REQUEST;
04486     ssl->renegotiation = SSL_RENEGOTIATION;
04487 
04488     if( ( ret = ssl_handshake( ssl ) ) != 0 )
04489     {
04490         SSL_DEBUG_RET( 1, "ssl_handshake", ret );
04491         return( ret );
04492     }
04493 
04494     SSL_DEBUG_MSG( 2, ( "<= renegotiate" ) );
04495 
04496     return( 0 );
04497 }
04498 
04499 /*
04500  * Renegotiate current connection on client,
04501  * or request renegotiation on server
04502  */
04503 int ssl_renegotiate( ssl_context *ssl )
04504 {
04505     int ret = POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE;
04506 
04507 #if defined(POLARSSL_SSL_SRV_C)
04508     /* On server, just send the request */
04509     if( ssl->endpoint == SSL_IS_SERVER )
04510     {
04511         if( ssl->state != SSL_HANDSHAKE_OVER )
04512             return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
04513 
04514         ssl->renegotiation = SSL_RENEGOTIATION_PENDING;
04515 
04516         /* Did we already try/start sending HelloRequest? */
04517         if( ssl->out_left != 0 )
04518             return( ssl_flush_output( ssl ) );
04519 
04520         return( ssl_write_hello_request( ssl ) );
04521     }
04522 #endif /* POLARSSL_SSL_SRV_C */
04523 
04524 #if defined(POLARSSL_SSL_CLI_C)
04525     /*
04526      * On client, either start the renegotiation process or,
04527      * if already in progress, continue the handshake
04528      */
04529     if( ssl->renegotiation != SSL_RENEGOTIATION )
04530     {
04531         if( ssl->state != SSL_HANDSHAKE_OVER )
04532             return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
04533 
04534         if( ( ret = ssl_start_renegotiation( ssl ) ) != 0 )
04535         {
04536             SSL_DEBUG_RET( 1, "ssl_start_renegotiation", ret );
04537             return( ret );
04538         }
04539     }
04540     else
04541     {
04542         if( ( ret = ssl_handshake( ssl ) ) != 0 )
04543         {
04544             SSL_DEBUG_RET( 1, "ssl_handshake", ret );
04545             return( ret );
04546         }
04547     }
04548 #endif /* POLARSSL_SSL_CLI_C */
04549 
04550     return( ret );
04551 }
04552 
04553 /*
04554  * Check record counters and renegotiate if they're above the limit.
04555  */
04556 static int ssl_check_ctr_renegotiate( ssl_context *ssl )
04557 {
04558     if( ssl->state != SSL_HANDSHAKE_OVER ||
04559         ssl->renegotiation == SSL_RENEGOTIATION_PENDING ||
04560         ssl->disable_renegotiation == SSL_RENEGOTIATION_DISABLED )
04561     {
04562         return( 0 );
04563     }
04564 
04565     // TODO: adapt for DTLS
04566     if( memcmp( ssl->in_ctr,  ssl->renego_period, 8 ) <= 0 &&
04567         memcmp( ssl->out_ctr, ssl->renego_period, 8 ) <= 0 )
04568     {
04569         return( 0 );
04570     }
04571 
04572     SSL_DEBUG_MSG( 0, ( "record counter limit reached: renegotiate" ) );
04573     return( ssl_renegotiate( ssl ) );
04574 }
04575 #endif /* POLARSSL_SSL_RENEGOTIATION */
04576 
04577 /*
04578  * Receive application data decrypted from the SSL layer
04579  */
04580 int ssl_read( ssl_context *ssl, unsigned char *buf, size_t len )
04581 {
04582     int ret, record_read = 0;
04583     size_t n;
04584 
04585     SSL_DEBUG_MSG( 2, ( "=> read" ) );
04586 
04587 #if defined(POLARSSL_SSL_RENEGOTIATION)
04588     if( ( ret = ssl_check_ctr_renegotiate( ssl ) ) != 0 )
04589     {
04590         SSL_DEBUG_RET( 1, "ssl_check_ctr_renegotiate", ret );
04591         return( ret );
04592     }
04593 #endif
04594 
04595     if( ssl->state != SSL_HANDSHAKE_OVER )
04596     {
04597         ret = ssl_handshake( ssl );
04598         if( ret == POLARSSL_ERR_SSL_WAITING_SERVER_HELLO_RENEGO )
04599         {
04600             record_read = 1;
04601         }
04602         else if( ret != 0 )
04603         {
04604             SSL_DEBUG_RET( 1, "ssl_handshake", ret );
04605             return( ret );
04606         }
04607     }
04608 
04609     if( ssl->in_offt == NULL )
04610     {
04611         if( ! record_read )
04612         {
04613             if( ( ret = ssl_read_record( ssl ) ) != 0 )
04614             {
04615                 if( ret == POLARSSL_ERR_SSL_CONN_EOF )
04616                     return( 0 );
04617 
04618                 SSL_DEBUG_RET( 1, "ssl_read_record", ret );
04619                 return( ret );
04620             }
04621         }
04622 
04623         if( ssl->in_msglen  == 0 &&
04624             ssl->in_msgtype == SSL_MSG_APPLICATION_DATA )
04625         {
04626             /*
04627              * OpenSSL sends empty messages to randomize the IV
04628              */
04629             if( ( ret = ssl_read_record( ssl ) ) != 0 )
04630             {
04631                 if( ret == POLARSSL_ERR_SSL_CONN_EOF )
04632                     return( 0 );
04633 
04634                 SSL_DEBUG_RET( 1, "ssl_read_record", ret );
04635                 return( ret );
04636             }
04637         }
04638 
04639 #if defined(POLARSSL_SSL_RENEGOTIATION)
04640         if( ssl->in_msgtype == SSL_MSG_HANDSHAKE )
04641         {
04642             SSL_DEBUG_MSG( 1, ( "received handshake message" ) );
04643 
04644 #if defined(POLARSSL_SSL_CLI_C)
04645             if( ssl->endpoint == SSL_IS_CLIENT &&
04646                 ( ssl->in_msg[0] != SSL_HS_HELLO_REQUEST ||
04647                   ssl->in_hslen != 4 ) )
04648             {
04649                 SSL_DEBUG_MSG( 1, ( "handshake received (not HelloRequest)" ) );
04650                 return( POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE );
04651             }
04652 #endif
04653 
04654             if( ssl->disable_renegotiation == SSL_RENEGOTIATION_DISABLED ||
04655                 ( ssl->secure_renegotiation == SSL_LEGACY_RENEGOTIATION &&
04656                   ssl->allow_legacy_renegotiation ==
04657                                                 SSL_LEGACY_NO_RENEGOTIATION ) )
04658             {
04659                 SSL_DEBUG_MSG( 3, ( "ignoring renegotiation, sending alert" ) );
04660 
04661 #if defined(POLARSSL_SSL_PROTO_SSL3)
04662                 if( ssl->minor_ver == SSL_MINOR_VERSION_0 )
04663                 {
04664                     /*
04665                      * SSLv3 does not have a "no_renegotiation" alert
04666                      */
04667                     if( ( ret = ssl_send_fatal_handshake_failure( ssl ) ) != 0 )
04668                         return( ret );
04669                 }
04670                 else
04671 #endif /* POLARSSL_SSL_PROTO_SSL3 */
04672 #if defined(POLARSSL_SSL_PROTO_TLS1) || defined(POLARSSL_SSL_PROTO_TLS1_1) || \
04673     defined(POLARSSL_SSL_PROTO_TLS1_2)
04674                 if( ssl->minor_ver >= SSL_MINOR_VERSION_1 )
04675                 {
04676                     if( ( ret = ssl_send_alert_message( ssl,
04677                                     SSL_ALERT_LEVEL_WARNING,
04678                                     SSL_ALERT_MSG_NO_RENEGOTIATION ) ) != 0 )
04679                     {
04680                         return( ret );
04681                     }
04682                 }
04683                 else
04684 #endif /* POLARSSL_SSL_PROTO_TLS1 || POLARSSL_SSL_PROTO_TLS1_1 ||
04685           POLARSSL_SSL_PROTO_TLS1_2 */
04686                 {
04687                     SSL_DEBUG_MSG( 1, ( "should never happen" ) );
04688                     return( POLARSSL_ERR_SSL_INTERNAL_ERROR );
04689                 }
04690             }
04691             else
04692             {
04693                 ret = ssl_start_renegotiation( ssl );
04694                 if( ret == POLARSSL_ERR_SSL_WAITING_SERVER_HELLO_RENEGO )
04695                 {
04696                     record_read = 1;
04697                 }
04698                 else if( ret != 0 )
04699                 {
04700                     SSL_DEBUG_RET( 1, "ssl_start_renegotiation", ret );
04701                     return( ret );
04702                 }
04703             }
04704 
04705             /* If a non-handshake record was read during renego, fallthrough,
04706              * else tell the user they should call ssl_read() again */
04707             if( ! record_read )
04708                 return( POLARSSL_ERR_NET_WANT_READ );
04709         }
04710         else if( ssl->renegotiation == SSL_RENEGOTIATION_PENDING )
04711         {
04712             ssl->renego_records_seen++;
04713 
04714             if( ssl->renego_max_records >= 0 &&
04715                 ssl->renego_records_seen > ssl->renego_max_records )
04716             {
04717                 SSL_DEBUG_MSG( 1, ( "renegotiation requested, "
04718                                     "but not honored by client" ) );
04719                 return( POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE );
04720             }
04721         }
04722 #endif /* POLARSSL_SSL_RENEGOTIATION */
04723 
04724         /* Fatal and closure alerts handled by ssl_read_record() */
04725         if( ssl->in_msgtype == SSL_MSG_ALERT )
04726         {
04727             SSL_DEBUG_MSG( 2, ( "ignoring non-fatal non-closure alert" ) );
04728             return( POLARSSL_ERR_NET_WANT_READ );
04729         }
04730 
04731         if( ssl->in_msgtype != SSL_MSG_APPLICATION_DATA )
04732         {
04733             SSL_DEBUG_MSG( 1, ( "bad application data message" ) );
04734             return( POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE );
04735         }
04736 
04737         ssl->in_offt = ssl->in_msg;
04738     }
04739 
04740     n = ( len < ssl->in_msglen )
04741         ? len : ssl->in_msglen;
04742 
04743     memcpy( buf, ssl->in_offt, n );
04744     ssl->in_msglen -= n;
04745 
04746     if( ssl->in_msglen == 0 )
04747         /* all bytes consumed  */
04748         ssl->in_offt = NULL;
04749     else
04750         /* more data available */
04751         ssl->in_offt += n;
04752 
04753     SSL_DEBUG_MSG( 2, ( "<= read" ) );
04754 
04755     return( (int) n );
04756 }
04757 
04758 /*
04759  * Send application data to be encrypted by the SSL layer,
04760  * taking care of max fragment length and buffer size
04761  */
04762 static int ssl_write_real( ssl_context *ssl,
04763                            const unsigned char *buf, size_t len )
04764 {
04765     int ret;
04766     size_t n;
04767     unsigned int max_len = SSL_MAX_CONTENT_LEN;
04768 
04769 #if defined(POLARSSL_SSL_MAX_FRAGMENT_LENGTH)
04770     /*
04771      * Assume mfl_code is correct since it was checked when set
04772      */
04773     max_len = mfl_code_to_length[ssl->mfl_code];
04774 
04775     /*
04776      * Check if a smaller max length was negotiated
04777      */
04778     if( ssl->session_out != NULL &&
04779         mfl_code_to_length[ssl->session_out->mfl_code] < max_len )
04780     {
04781         max_len = mfl_code_to_length[ssl->session_out->mfl_code];
04782     }
04783 #endif /* POLARSSL_SSL_MAX_FRAGMENT_LENGTH */
04784 
04785     n = ( len < max_len) ? len : max_len;
04786 
04787     if( ssl->out_left != 0 )
04788     {
04789         if( ( ret = ssl_flush_output( ssl ) ) != 0 )
04790         {
04791             SSL_DEBUG_RET( 1, "ssl_flush_output", ret );
04792             return( ret );
04793         }
04794     }
04795     else
04796     {
04797         ssl->out_msglen  = n;
04798         ssl->out_msgtype = SSL_MSG_APPLICATION_DATA;
04799         memcpy( ssl->out_msg, buf, n );
04800 
04801         if( ( ret = ssl_write_record( ssl ) ) != 0 )
04802         {
04803             SSL_DEBUG_RET( 1, "ssl_write_record", ret );
04804             return( ret );
04805         }
04806     }
04807 
04808     return( (int) n );
04809 }
04810 
04811 /*
04812  * Write application data, doing 1/n-1 splitting if necessary.
04813  *
04814  * With non-blocking I/O, ssl_write_real() may return WANT_WRITE,
04815  * then the caller will call us again with the same arguments, so
04816  * remember wether we already did the split or not.
04817  */
04818 #if defined(POLARSSL_SSL_CBC_RECORD_SPLITTING)
04819 static int ssl_write_split( ssl_context *ssl,
04820                             const unsigned char *buf, size_t len )
04821 {
04822     int ret;
04823 
04824     if( ssl->split_done == SSL_CBC_RECORD_SPLITTING_DISABLED ||
04825         len <= 1 ||
04826         ssl->minor_ver > SSL_MINOR_VERSION_1 ||
04827         cipher_get_cipher_mode( &ssl->transform_out->cipher_ctx_enc )
04828                                 != POLARSSL_MODE_CBC )
04829     {
04830         return( ssl_write_real( ssl, buf, len ) );
04831     }
04832 
04833     if( ssl->split_done == 0 )
04834     {
04835         if( ( ret = ssl_write_real( ssl, buf, 1 ) ) <= 0 )
04836             return( ret );
04837         ssl->split_done = 1;
04838     }
04839 
04840     if( ( ret = ssl_write_real( ssl, buf + 1, len - 1 ) ) <= 0 )
04841         return( ret );
04842     ssl->split_done = 0;
04843 
04844     return( ret + 1 );
04845 }
04846 #endif /* POLARSSL_SSL_CBC_RECORD_SPLITTING */
04847 
04848 /*
04849  * Write application data (public-facing wrapper)
04850  */
04851 int ssl_write( ssl_context *ssl, const unsigned char *buf, size_t len )
04852 {
04853     int ret;
04854 
04855     SSL_DEBUG_MSG( 2, ( "=> write" ) );
04856 
04857 #if defined(POLARSSL_SSL_RENEGOTIATION)
04858     if( ( ret = ssl_check_ctr_renegotiate( ssl ) ) != 0 )
04859     {
04860         SSL_DEBUG_RET( 1, "ssl_check_ctr_renegotiate", ret );
04861         return( ret );
04862     }
04863 #endif
04864 
04865     if( ssl->state != SSL_HANDSHAKE_OVER )
04866     {
04867         if( ( ret = ssl_handshake( ssl ) ) != 0 )
04868         {
04869             SSL_DEBUG_RET( 1, "ssl_handshake", ret );
04870             return( ret );
04871         }
04872     }
04873 
04874 #if defined(POLARSSL_SSL_CBC_RECORD_SPLITTING)
04875     ret = ssl_write_split( ssl, buf, len );
04876 #else
04877     ret = ssl_write_real( ssl, buf, len );
04878 #endif
04879 
04880     SSL_DEBUG_MSG( 2, ( "<= write" ) );
04881 
04882     return( ret );
04883 }
04884 
04885 /*
04886  * Notify the peer that the connection is being closed
04887  */
04888 int ssl_close_notify( ssl_context *ssl )
04889 {
04890     int ret;
04891 
04892     SSL_DEBUG_MSG( 2, ( "=> write close notify" ) );
04893 
04894     if( ssl->out_left != 0 )
04895         return( ssl_flush_output( ssl ) );
04896 
04897     if( ssl->state == SSL_HANDSHAKE_OVER )
04898     {
04899         if( ( ret = ssl_send_alert_message( ssl,
04900                         SSL_ALERT_LEVEL_WARNING,
04901                         SSL_ALERT_MSG_CLOSE_NOTIFY ) ) != 0 )
04902         {
04903             SSL_DEBUG_RET( 1, "ssl_send_alert_message", ret );
04904             return( ret );
04905         }
04906     }
04907 
04908     SSL_DEBUG_MSG( 2, ( "<= write close notify" ) );
04909 
04910     return( 0 );
04911 }
04912 
04913 void ssl_transform_free( ssl_transform *transform )
04914 {
04915     if( transform == NULL )
04916         return;
04917 
04918 #if defined(POLARSSL_ZLIB_SUPPORT)
04919     deflateEnd( &transform->ctx_deflate );
04920     inflateEnd( &transform->ctx_inflate );
04921 #endif
04922 
04923     cipher_free( &transform->cipher_ctx_enc );
04924     cipher_free( &transform->cipher_ctx_dec );
04925 
04926     md_free( &transform->md_ctx_enc );
04927     md_free( &transform->md_ctx_dec );
04928 
04929     polarssl_zeroize( transform, sizeof( ssl_transform ) );
04930 }
04931 
04932 #if defined(POLARSSL_X509_CRT_PARSE_C)
04933 static void ssl_key_cert_free( ssl_key_cert *key_cert )
04934 {
04935     ssl_key_cert *cur = key_cert, *next;
04936 
04937     while( cur != NULL )
04938     {
04939         next = cur->next;
04940 
04941         if( cur->key_own_alloc )
04942         {
04943             pk_free( cur->key );
04944             polarssl_free( cur->key );
04945         }
04946         polarssl_free( cur );
04947 
04948         cur = next;
04949     }
04950 }
04951 #endif /* POLARSSL_X509_CRT_PARSE_C */
04952 
04953 void ssl_handshake_free( ssl_handshake_params *handshake )
04954 {
04955     if( handshake == NULL )
04956         return;
04957 
04958 #if defined(POLARSSL_DHM_C)
04959     dhm_free( &handshake->dhm_ctx );
04960 #endif
04961 #if defined(POLARSSL_ECDH_C)
04962     ecdh_free( &handshake->ecdh_ctx );
04963 #endif
04964 
04965 #if defined(POLARSSL_ECDH_C) || defined(POLARSSL_ECDSA_C)
04966     /* explicit void pointer cast for buggy MS compiler */
04967     polarssl_free( (void *) handshake->curves );
04968 #endif
04969 
04970 #if defined(POLARSSL_X509_CRT_PARSE_C) && \
04971     defined(POLARSSL_SSL_SERVER_NAME_INDICATION)
04972     /*
04973      * Free only the linked list wrapper, not the keys themselves
04974      * since the belong to the SNI callback
04975      */
04976     if( handshake->sni_key_cert != NULL )
04977     {
04978         ssl_key_cert *cur = handshake->sni_key_cert, *next;
04979 
04980         while( cur != NULL )
04981         {
04982             next = cur->next;
04983             polarssl_free( cur );
04984             cur = next;
04985         }
04986     }
04987 #endif /* POLARSSL_X509_CRT_PARSE_C && POLARSSL_SSL_SERVER_NAME_INDICATION */
04988 
04989     polarssl_zeroize( handshake, sizeof( ssl_handshake_params ) );
04990 }
04991 
04992 void ssl_session_free( ssl_session *session )
04993 {
04994     if( session == NULL )
04995         return;
04996 
04997 #if defined(POLARSSL_X509_CRT_PARSE_C)
04998     if( session->peer_cert != NULL )
04999     {
05000         x509_crt_free( session->peer_cert );
05001         polarssl_free( session->peer_cert );
05002     }
05003 #endif
05004 
05005 #if defined(POLARSSL_SSL_SESSION_TICKETS)
05006     polarssl_free( session->ticket );
05007 #endif
05008 
05009     polarssl_zeroize( session, sizeof( ssl_session ) );
05010 }
05011 
05012 /*
05013  * Free an SSL context
05014  */
05015 void ssl_free( ssl_context *ssl )
05016 {
05017     if( ssl == NULL )
05018         return;
05019 
05020     SSL_DEBUG_MSG( 2, ( "=> free" ) );
05021 
05022     if( ssl->out_ctr != NULL )
05023     {
05024         polarssl_zeroize( ssl->out_ctr, SSL_BUFFER_LEN );
05025         polarssl_free( ssl->out_ctr );
05026     }
05027 
05028     if( ssl->in_ctr != NULL )
05029     {
05030         polarssl_zeroize( ssl->in_ctr, SSL_BUFFER_LEN );
05031         polarssl_free( ssl->in_ctr );
05032     }
05033 
05034 #if defined(POLARSSL_ZLIB_SUPPORT)
05035     if( ssl->compress_buf != NULL )
05036     {
05037         polarssl_zeroize( ssl->compress_buf, SSL_BUFFER_LEN );
05038         polarssl_free( ssl->compress_buf );
05039     }
05040 #endif
05041 
05042 #if defined(POLARSSL_DHM_C)
05043     mpi_free( &ssl->dhm_P );
05044     mpi_free( &ssl->dhm_G );
05045 #endif
05046 
05047     if( ssl->transform )
05048     {
05049         ssl_transform_free( ssl->transform );
05050         polarssl_free( ssl->transform );
05051     }
05052 
05053     if( ssl->handshake )
05054     {
05055         ssl_handshake_free( ssl->handshake );
05056         ssl_transform_free( ssl->transform_negotiate );
05057         ssl_session_free( ssl->session_negotiate );
05058 
05059         polarssl_free( ssl->handshake );
05060         polarssl_free( ssl->transform_negotiate );
05061         polarssl_free( ssl->session_negotiate );
05062     }
05063 
05064     if( ssl->session )
05065     {
05066         ssl_session_free( ssl->session );
05067         polarssl_free( ssl->session );
05068     }
05069 
05070 #if defined(POLARSSL_SSL_SESSION_TICKETS)
05071     if( ssl->ticket_keys )
05072     {
05073         ssl_ticket_keys_free( ssl->ticket_keys );
05074         polarssl_free( ssl->ticket_keys );
05075     }
05076 #endif
05077 
05078 #if defined(POLARSSL_SSL_SERVER_NAME_INDICATION)
05079     if( ssl->hostname != NULL )
05080     {
05081         polarssl_zeroize( ssl->hostname, ssl->hostname_len );
05082         polarssl_free( ssl->hostname );
05083         ssl->hostname_len = 0;
05084     }
05085 #endif
05086 
05087 #if defined(POLARSSL_KEY_EXCHANGE__SOME__PSK_ENABLED)
05088     if( ssl->psk != NULL )
05089     {
05090         polarssl_zeroize( ssl->psk, ssl->psk_len );
05091         polarssl_zeroize( ssl->psk_identity, ssl->psk_identity_len );
05092         polarssl_free( ssl->psk );
05093         polarssl_free( ssl->psk_identity );
05094         ssl->psk_len = 0;
05095         ssl->psk_identity_len = 0;
05096     }
05097 #endif
05098 
05099 #if defined(POLARSSL_X509_CRT_PARSE_C)
05100     ssl_key_cert_free( ssl->key_cert );
05101 #endif
05102 
05103 #if defined(POLARSSL_SSL_HW_RECORD_ACCEL)
05104     if( ssl_hw_record_finish != NULL )
05105     {
05106         SSL_DEBUG_MSG( 2, ( "going for ssl_hw_record_finish()" ) );
05107         ssl_hw_record_finish( ssl );
05108     }
05109 #endif
05110 
05111     SSL_DEBUG_MSG( 2, ( "<= free" ) );
05112 
05113     /* Actually clear after last debug message */
05114     polarssl_zeroize( ssl, sizeof( ssl_context ) );
05115 }
05116 
05117 #if defined(POLARSSL_PK_C)
05118 /*
05119  * Convert between POLARSSL_PK_XXX and SSL_SIG_XXX
05120  */
05121 unsigned char ssl_sig_from_pk( pk_context *pk )
05122 {
05123 #if defined(POLARSSL_RSA_C)
05124     if( pk_can_do( pk, POLARSSL_PK_RSA ) )
05125         return( SSL_SIG_RSA );
05126 #endif
05127 #if defined(POLARSSL_ECDSA_C)
05128     if( pk_can_do( pk, POLARSSL_PK_ECDSA ) )
05129         return( SSL_SIG_ECDSA );
05130 #endif
05131     return( SSL_SIG_ANON );
05132 }
05133 
05134 pk_type_t ssl_pk_alg_from_sig( unsigned char sig )
05135 {
05136     switch( sig )
05137     {
05138 #if defined(POLARSSL_RSA_C)
05139         case SSL_SIG_RSA:
05140             return( POLARSSL_PK_RSA );
05141 #endif
05142 #if defined(POLARSSL_ECDSA_C)
05143         case SSL_SIG_ECDSA:
05144             return( POLARSSL_PK_ECDSA );
05145 #endif
05146         default:
05147             return( POLARSSL_PK_NONE );
05148     }
05149 }
05150 #endif /* POLARSSL_PK_C */
05151 
05152 /*
05153  * Convert between SSL_HASH_XXX and POLARSSL_MD_XXX
05154  */
05155 md_type_t ssl_md_alg_from_hash( unsigned char hash )
05156 {
05157     switch( hash )
05158     {
05159 #if defined(POLARSSL_MD5_C)
05160         case SSL_HASH_MD5:
05161             return( POLARSSL_MD_MD5 );
05162 #endif
05163 #if defined(POLARSSL_SHA1_C)
05164         case SSL_HASH_SHA1:
05165             return( POLARSSL_MD_SHA1 );
05166 #endif
05167 #if defined(POLARSSL_SHA256_C)
05168         case SSL_HASH_SHA224:
05169             return( POLARSSL_MD_SHA224 );
05170         case SSL_HASH_SHA256:
05171             return( POLARSSL_MD_SHA256 );
05172 #endif
05173 #if defined(POLARSSL_SHA512_C)
05174         case SSL_HASH_SHA384:
05175             return( POLARSSL_MD_SHA384 );
05176         case SSL_HASH_SHA512:
05177             return( POLARSSL_MD_SHA512 );
05178 #endif
05179         default:
05180             return( POLARSSL_MD_NONE );
05181     }
05182 }
05183 
05184 #if defined(POLARSSL_SSL_SET_CURVES)
05185 /*
05186  * Check is a curve proposed by the peer is in our list.
05187  * Return 1 if we're willing to use it, 0 otherwise.
05188  */
05189 int ssl_curve_is_acceptable( const ssl_context *ssl, ecp_group_id grp_id )
05190 {
05191     const ecp_group_id *gid;
05192 
05193     for( gid = ssl->curve_list; *gid != POLARSSL_ECP_DP_NONE; gid++ )
05194         if( *gid == grp_id )
05195             return( 1 );
05196 
05197     return( 0 );
05198 }
05199 #endif /* POLARSSL_SSL_SET_CURVES */
05200 
05201 #if defined(POLARSSL_X509_CRT_PARSE_C)
05202 int ssl_check_cert_usage( const x509_crt *cert,
05203                           const ssl_ciphersuite_t *ciphersuite,
05204                           int cert_endpoint,
05205                           int *flags )
05206 {
05207     int ret = 0;
05208 #if defined(POLARSSL_X509_CHECK_KEY_USAGE)
05209     int usage = 0;
05210 #endif
05211 #if defined(POLARSSL_X509_CHECK_EXTENDED_KEY_USAGE)
05212     const char *ext_oid;
05213     size_t ext_len;
05214 #endif
05215 
05216 #if !defined(POLARSSL_X509_CHECK_KEY_USAGE) &&          \
05217     !defined(POLARSSL_X509_CHECK_EXTENDED_KEY_USAGE)
05218     ((void) cert);
05219     ((void) cert_endpoint);
05220     ((void) flags);
05221 #endif
05222 
05223 #if defined(POLARSSL_X509_CHECK_KEY_USAGE)
05224     if( cert_endpoint == SSL_IS_SERVER )
05225     {
05226         /* Server part of the key exchange */
05227         switch( ciphersuite->key_exchange )
05228         {
05229             case POLARSSL_KEY_EXCHANGE_RSA:
05230             case POLARSSL_KEY_EXCHANGE_RSA_PSK:
05231                 usage = KU_KEY_ENCIPHERMENT;
05232                 break;
05233 
05234             case POLARSSL_KEY_EXCHANGE_DHE_RSA:
05235             case POLARSSL_KEY_EXCHANGE_ECDHE_RSA:
05236             case POLARSSL_KEY_EXCHANGE_ECDHE_ECDSA:
05237                 usage = KU_DIGITAL_SIGNATURE;
05238                 break;
05239 
05240             case POLARSSL_KEY_EXCHANGE_ECDH_RSA:
05241             case POLARSSL_KEY_EXCHANGE_ECDH_ECDSA:
05242                 usage = KU_KEY_AGREEMENT;
05243                 break;
05244 
05245             /* Don't use default: we want warnings when adding new values */
05246             case POLARSSL_KEY_EXCHANGE_NONE:
05247             case POLARSSL_KEY_EXCHANGE_PSK:
05248             case POLARSSL_KEY_EXCHANGE_DHE_PSK:
05249             case POLARSSL_KEY_EXCHANGE_ECDHE_PSK:
05250                 usage = 0;
05251         }
05252     }
05253     else
05254     {
05255         /* Client auth: we only implement rsa_sign and ecdsa_sign for now */
05256         usage = KU_DIGITAL_SIGNATURE;
05257     }
05258 
05259     if( x509_crt_check_key_usage( cert, usage ) != 0 )
05260     {
05261         *flags |= BADCERT_KEY_USAGE;
05262         ret = -1;
05263     }
05264 #else
05265     ((void) ciphersuite);
05266 #endif /* POLARSSL_X509_CHECK_KEY_USAGE */
05267 
05268 #if defined(POLARSSL_X509_CHECK_EXTENDED_KEY_USAGE)
05269     if( cert_endpoint == SSL_IS_SERVER )
05270     {
05271         ext_oid = OID_SERVER_AUTH;
05272         ext_len = OID_SIZE( OID_SERVER_AUTH );
05273     }
05274     else
05275     {
05276         ext_oid = OID_CLIENT_AUTH;
05277         ext_len = OID_SIZE( OID_CLIENT_AUTH );
05278     }
05279 
05280     if( x509_crt_check_extended_key_usage( cert, ext_oid, ext_len ) != 0 )
05281     {
05282         *flags |= BADCERT_EXT_KEY_USAGE;
05283         ret = -1;
05284     }
05285 #endif /* POLARSSL_X509_CHECK_EXTENDED_KEY_USAGE */
05286 
05287     return( ret );
05288 }
05289 #endif /* POLARSSL_X509_CRT_PARSE_C */
05290 
05291 #endif /* POLARSSL_SSL_TLS_C */
05292