ssl_tls.c 222 KB
Newer Older
1 2 3
/*
 *  SSLv3/TLSv1 shared functions
 *
4
 *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
5
 *
6
 *  This file is part of mbed TLS (https://tls.mbed.org)
7
 *
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */
/*
 *  The SSL 3.0 specification was drafted by Netscape in 1996,
 *  and became an IETF standard in 1999.
 *
 *  http://wp.netscape.com/eng/ssl3/
 *  http://www.ietf.org/rfc/rfc2246.txt
 *  http://www.ietf.org/rfc/rfc4346.txt
 */

31
#if !defined(MBEDTLS_CONFIG_FILE)
32
#include "mbedtls/config.h"
33
#else
34
#include MBEDTLS_CONFIG_FILE
35
#endif
36

37
#if defined(MBEDTLS_SSL_TLS_C)
38

39 40
#include "mbedtls/debug.h"
#include "mbedtls/ssl.h"
41
#include "mbedtls/ssl_internal.h"
42

43 44
#include <string.h>

45 46
#if defined(MBEDTLS_X509_CRT_PARSE_C) && \
    defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
47
#include "mbedtls/oid.h"
48 49
#endif

50
#if defined(MBEDTLS_PLATFORM_C)
51
#include "mbedtls/platform.h"
52
#else
53
#include <stdlib.h>
54
#define mbedtls_calloc    calloc
55
#define mbedtls_free       free
56 57
#endif

58
/* Implementation that should never be optimized out by the compiler */
59
static void mbedtls_zeroize( void *v, size_t n ) {
60 61 62
    volatile unsigned char *p = v; while( n-- ) *p++ = 0;
}

63
/* Length of the "epoch" field in the record header */
64
static inline size_t ssl_ep_len( const mbedtls_ssl_context *ssl )
65
{
66
#if defined(MBEDTLS_SSL_PROTO_DTLS)
67
    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
68
        return( 2 );
69 70
#else
    ((void) ssl);
71 72 73 74
#endif
    return( 0 );
}

75 76 77 78
/*
 * Start a timer.
 * Passing millisecs = 0 cancels a running timer.
 */
79
static void ssl_set_timer( mbedtls_ssl_context *ssl, uint32_t millisecs )
80
{
81 82 83 84 85
    if( ssl->f_set_timer == NULL )
        return;

    MBEDTLS_SSL_DEBUG_MSG( 3, ( "set_timer to %d ms", (int) millisecs ) );
    ssl->f_set_timer( ssl->p_timer, millisecs / 4, millisecs );
86 87 88 89 90
}

/*
 * Return -1 is timer is expired, 0 if it isn't.
 */
91
static int ssl_check_timer( mbedtls_ssl_context *ssl )
92
{
93
    if( ssl->f_get_timer == NULL )
94
        return( 0 );
95 96

    if( ssl->f_get_timer( ssl->p_timer ) == 2 )
97 98
    {
        MBEDTLS_SSL_DEBUG_MSG( 3, ( "timer expired" ) );
99
        return( -1 );
100
    }
101 102 103 104

    return( 0 );
}

105
#if defined(MBEDTLS_SSL_PROTO_DTLS)
106 107 108 109
/*
 * Double the retransmit timeout value, within the allowed range,
 * returning -1 if the maximum value has already been reached.
 */
110
static int ssl_double_retransmit_timeout( mbedtls_ssl_context *ssl )
111 112 113
{
    uint32_t new_timeout;

114
    if( ssl->handshake->retransmit_timeout >= ssl->conf->hs_timeout_max )
115 116 117 118 119 120
        return( -1 );

    new_timeout = 2 * ssl->handshake->retransmit_timeout;

    /* Avoid arithmetic overflow and range overflow */
    if( new_timeout < ssl->handshake->retransmit_timeout ||
121
        new_timeout > ssl->conf->hs_timeout_max )
122
    {
123
        new_timeout = ssl->conf->hs_timeout_max;
124 125 126
    }

    ssl->handshake->retransmit_timeout = new_timeout;
127
    MBEDTLS_SSL_DEBUG_MSG( 3, ( "update timeout value to %d millisecs",
128 129 130 131 132
                        ssl->handshake->retransmit_timeout ) );

    return( 0 );
}

133
static void ssl_reset_retransmit_timeout( mbedtls_ssl_context *ssl )
134
{
135
    ssl->handshake->retransmit_timeout = ssl->conf->hs_timeout_min;
136
    MBEDTLS_SSL_DEBUG_MSG( 3, ( "update timeout value to %d millisecs",
137 138
                        ssl->handshake->retransmit_timeout ) );
}
139
#endif /* MBEDTLS_SSL_PROTO_DTLS */
140

141
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
142 143 144 145 146 147 148 149
/*
 * Convert max_fragment_length codes to length.
 * RFC 6066 says:
 *    enum{
 *        2^9(1), 2^10(2), 2^11(3), 2^12(4), (255)
 *    } MaxFragmentLength;
 * and we add 0 -> extension unused
 */
150
static unsigned int mfl_code_to_length[MBEDTLS_SSL_MAX_FRAG_LEN_INVALID] =
151
{
152 153 154 155 156
    MBEDTLS_SSL_MAX_CONTENT_LEN,    /* MBEDTLS_SSL_MAX_FRAG_LEN_NONE */
    512,                    /* MBEDTLS_SSL_MAX_FRAG_LEN_512  */
    1024,                   /* MBEDTLS_SSL_MAX_FRAG_LEN_1024 */
    2048,                   /* MBEDTLS_SSL_MAX_FRAG_LEN_2048 */
    4096,                   /* MBEDTLS_SSL_MAX_FRAG_LEN_4096 */
157
};
158
#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
159

160
#if defined(MBEDTLS_SSL_CLI_C)
161
static int ssl_session_copy( mbedtls_ssl_session *dst, const mbedtls_ssl_session *src )
162
{
163 164
    mbedtls_ssl_session_free( dst );
    memcpy( dst, src, sizeof( mbedtls_ssl_session ) );
165

166
#if defined(MBEDTLS_X509_CRT_PARSE_C)
167 168
    if( src->peer_cert != NULL )
    {
169 170
        int ret;

171
        dst->peer_cert = mbedtls_calloc( 1, sizeof(mbedtls_x509_crt) );
172
        if( dst->peer_cert == NULL )
173
            return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
174

175
        mbedtls_x509_crt_init( dst->peer_cert );
176

177
        if( ( ret = mbedtls_x509_crt_parse_der( dst->peer_cert, src->peer_cert->raw.p,
178
                                        src->peer_cert->raw.len ) ) != 0 )
179
        {
180
            mbedtls_free( dst->peer_cert );
181 182 183 184
            dst->peer_cert = NULL;
            return( ret );
        }
    }
185
#endif /* MBEDTLS_X509_CRT_PARSE_C */
186

187
#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
188 189
    if( src->ticket != NULL )
    {
190
        dst->ticket = mbedtls_calloc( 1, src->ticket_len );
191
        if( dst->ticket == NULL )
192
            return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
193 194 195

        memcpy( dst->ticket, src->ticket, src->ticket_len );
    }
196
#endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
197 198 199

    return( 0 );
}
200
#endif /* MBEDTLS_SSL_CLI_C */
201

202 203
#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
int (*mbedtls_ssl_hw_record_init)( mbedtls_ssl_context *ssl,
204 205 206 207 208
                     const unsigned char *key_enc, const unsigned char *key_dec,
                     size_t keylen,
                     const unsigned char *iv_enc,  const unsigned char *iv_dec,
                     size_t ivlen,
                     const unsigned char *mac_enc, const unsigned char *mac_dec,
209
                     size_t maclen ) = NULL;
210 211 212 213 214 215
int (*mbedtls_ssl_hw_record_activate)( mbedtls_ssl_context *ssl, int direction) = NULL;
int (*mbedtls_ssl_hw_record_reset)( mbedtls_ssl_context *ssl ) = NULL;
int (*mbedtls_ssl_hw_record_write)( mbedtls_ssl_context *ssl ) = NULL;
int (*mbedtls_ssl_hw_record_read)( mbedtls_ssl_context *ssl ) = NULL;
int (*mbedtls_ssl_hw_record_finish)( mbedtls_ssl_context *ssl ) = NULL;
#endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
216

217 218 219
/*
 * Key material generation
 */
220
#if defined(MBEDTLS_SSL_PROTO_SSL3)
221 222 223
static int ssl3_prf( const unsigned char *secret, size_t slen,
                     const char *label,
                     const unsigned char *random, size_t rlen,
224 225 226
                     unsigned char *dstbuf, size_t dlen )
{
    size_t i;
227 228
    mbedtls_md5_context md5;
    mbedtls_sha1_context sha1;
229 230 231 232
    unsigned char padding[16];
    unsigned char sha1sum[20];
    ((void)label);

233 234
    mbedtls_md5_init(  &md5  );
    mbedtls_sha1_init( &sha1 );
235

236 237 238 239 240 241 242 243 244 245
    /*
     *  SSLv3:
     *    block =
     *      MD5( secret + SHA1( 'A'    + secret + random ) ) +
     *      MD5( secret + SHA1( 'BB'   + secret + random ) ) +
     *      MD5( secret + SHA1( 'CCC'  + secret + random ) ) +
     *      ...
     */
    for( i = 0; i < dlen / 16; i++ )
    {
246
        memset( padding, (unsigned char) ('A' + i), 1 + i );
247

248 249 250 251 252
        mbedtls_sha1_starts( &sha1 );
        mbedtls_sha1_update( &sha1, padding, 1 + i );
        mbedtls_sha1_update( &sha1, secret, slen );
        mbedtls_sha1_update( &sha1, random, rlen );
        mbedtls_sha1_finish( &sha1, sha1sum );
253

254 255 256 257
        mbedtls_md5_starts( &md5 );
        mbedtls_md5_update( &md5, secret, slen );
        mbedtls_md5_update( &md5, sha1sum, 20 );
        mbedtls_md5_finish( &md5, dstbuf + i * 16 );
258 259
    }

260 261
    mbedtls_md5_free(  &md5  );
    mbedtls_sha1_free( &sha1 );
262

263 264
    mbedtls_zeroize( padding, sizeof( padding ) );
    mbedtls_zeroize( sha1sum, sizeof( sha1sum ) );
265 266 267

    return( 0 );
}
268
#endif /* MBEDTLS_SSL_PROTO_SSL3 */
269

270
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
271 272 273
static int tls1_prf( const unsigned char *secret, size_t slen,
                     const char *label,
                     const unsigned char *random, size_t rlen,
274
                     unsigned char *dstbuf, size_t dlen )
275
{
276 277
    size_t nb, hs;
    size_t i, j, k;
278
    const unsigned char *S1, *S2;
279 280
    unsigned char tmp[128];
    unsigned char h_i[20];
281 282
    const mbedtls_md_info_t *md_info;
    mbedtls_md_context_t md_ctx;
283 284
    int ret;

285
    mbedtls_md_init( &md_ctx );
286 287

    if( sizeof( tmp ) < 20 + strlen( label ) + rlen )
288
        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
289 290 291 292 293 294 295 296 297 298 299 300 301

    hs = ( slen + 1 ) / 2;
    S1 = secret;
    S2 = secret + slen - hs;

    nb = strlen( label );
    memcpy( tmp + 20, label, nb );
    memcpy( tmp + 20 + nb, random, rlen );
    nb += rlen;

    /*
     * First compute P_md5(secret,label+random)[0..dlen]
     */
302 303
    if( ( md_info = mbedtls_md_info_from_type( MBEDTLS_MD_MD5 ) ) == NULL )
        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
304

305
    if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
306 307
        return( ret );

308 309 310
    mbedtls_md_hmac_starts( &md_ctx, S1, hs );
    mbedtls_md_hmac_update( &md_ctx, tmp + 20, nb );
    mbedtls_md_hmac_finish( &md_ctx, 4 + tmp );
311 312 313

    for( i = 0; i < dlen; i += 16 )
    {
314 315 316
        mbedtls_md_hmac_reset ( &md_ctx );
        mbedtls_md_hmac_update( &md_ctx, 4 + tmp, 16 + nb );
        mbedtls_md_hmac_finish( &md_ctx, h_i );
317

318 319 320
        mbedtls_md_hmac_reset ( &md_ctx );
        mbedtls_md_hmac_update( &md_ctx, 4 + tmp, 16 );
        mbedtls_md_hmac_finish( &md_ctx, 4 + tmp );
321 322 323 324 325 326 327

        k = ( i + 16 > dlen ) ? dlen % 16 : 16;

        for( j = 0; j < k; j++ )
            dstbuf[i + j]  = h_i[j];
    }

328
    mbedtls_md_free( &md_ctx );
329

330 331 332
    /*
     * XOR out with P_sha1(secret,label+random)[0..dlen]
     */
333 334
    if( ( md_info = mbedtls_md_info_from_type( MBEDTLS_MD_SHA1 ) ) == NULL )
        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
335

336
    if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
337 338
        return( ret );

339 340 341
    mbedtls_md_hmac_starts( &md_ctx, S2, hs );
    mbedtls_md_hmac_update( &md_ctx, tmp + 20, nb );
    mbedtls_md_hmac_finish( &md_ctx, tmp );
342 343 344

    for( i = 0; i < dlen; i += 20 )
    {
345 346 347
        mbedtls_md_hmac_reset ( &md_ctx );
        mbedtls_md_hmac_update( &md_ctx, tmp, 20 + nb );
        mbedtls_md_hmac_finish( &md_ctx, h_i );
348

349 350 351
        mbedtls_md_hmac_reset ( &md_ctx );
        mbedtls_md_hmac_update( &md_ctx, tmp, 20 );
        mbedtls_md_hmac_finish( &md_ctx, tmp );
352 353 354 355 356 357 358

        k = ( i + 20 > dlen ) ? dlen % 20 : 20;

        for( j = 0; j < k; j++ )
            dstbuf[i + j] = (unsigned char)( dstbuf[i + j] ^ h_i[j] );
    }

359
    mbedtls_md_free( &md_ctx );
360

361 362
    mbedtls_zeroize( tmp, sizeof( tmp ) );
    mbedtls_zeroize( h_i, sizeof( h_i ) );
363 364 365

    return( 0 );
}
366
#endif /* MBEDTLS_SSL_PROTO_TLS1) || MBEDTLS_SSL_PROTO_TLS1_1 */
367

368 369
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
static int tls_prf_generic( mbedtls_md_type_t md_type,
370 371 372 373
                            const unsigned char *secret, size_t slen,
                            const char *label,
                            const unsigned char *random, size_t rlen,
                            unsigned char *dstbuf, size_t dlen )
374 375
{
    size_t nb;
376
    size_t i, j, k, md_len;
377
    unsigned char tmp[128];
378 379 380
    unsigned char h_i[MBEDTLS_MD_MAX_SIZE];
    const mbedtls_md_info_t *md_info;
    mbedtls_md_context_t md_ctx;
381 382
    int ret;

383
    mbedtls_md_init( &md_ctx );
384

385 386
    if( ( md_info = mbedtls_md_info_from_type( md_type ) ) == NULL )
        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
387

388
    md_len = mbedtls_md_get_size( md_info );
389 390

    if( sizeof( tmp ) < md_len + strlen( label ) + rlen )
391
        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
392 393

    nb = strlen( label );
394 395
    memcpy( tmp + md_len, label, nb );
    memcpy( tmp + md_len + nb, random, rlen );
396 397 398 399 400
    nb += rlen;

    /*
     * Compute P_<hash>(secret, label + random)[0..dlen]
     */
401
    if ( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
402 403
        return( ret );

404 405 406
    mbedtls_md_hmac_starts( &md_ctx, secret, slen );
    mbedtls_md_hmac_update( &md_ctx, tmp + md_len, nb );
    mbedtls_md_hmac_finish( &md_ctx, tmp );
407

408
    for( i = 0; i < dlen; i += md_len )
409
    {
410 411 412
        mbedtls_md_hmac_reset ( &md_ctx );
        mbedtls_md_hmac_update( &md_ctx, tmp, md_len + nb );
        mbedtls_md_hmac_finish( &md_ctx, h_i );
413

414 415 416
        mbedtls_md_hmac_reset ( &md_ctx );
        mbedtls_md_hmac_update( &md_ctx, tmp, md_len );
        mbedtls_md_hmac_finish( &md_ctx, tmp );
417

418
        k = ( i + md_len > dlen ) ? dlen % md_len : md_len;
419 420 421 422 423

        for( j = 0; j < k; j++ )
            dstbuf[i + j]  = h_i[j];
    }

424
    mbedtls_md_free( &md_ctx );
425

426 427
    mbedtls_zeroize( tmp, sizeof( tmp ) );
    mbedtls_zeroize( h_i, sizeof( h_i ) );
428 429 430

    return( 0 );
}
431

432
#if defined(MBEDTLS_SHA256_C)
433 434 435 436 437
static int tls_prf_sha256( const unsigned char *secret, size_t slen,
                           const char *label,
                           const unsigned char *random, size_t rlen,
                           unsigned char *dstbuf, size_t dlen )
{
438
    return( tls_prf_generic( MBEDTLS_MD_SHA256, secret, slen,
439 440
                             label, random, rlen, dstbuf, dlen ) );
}
441
#endif /* MBEDTLS_SHA256_C */
442

443
#if defined(MBEDTLS_SHA512_C)
444 445 446
static int tls_prf_sha384( const unsigned char *secret, size_t slen,
                           const char *label,
                           const unsigned char *random, size_t rlen,
447 448
                           unsigned char *dstbuf, size_t dlen )
{
449
    return( tls_prf_generic( MBEDTLS_MD_SHA384, secret, slen,
450
                             label, random, rlen, dstbuf, dlen ) );
451
}
452 453
#endif /* MBEDTLS_SHA512_C */
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
454

455
static void ssl_update_checksum_start( mbedtls_ssl_context *, const unsigned char *, size_t );
456

457 458 459
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
    defined(MBEDTLS_SSL_PROTO_TLS1_1)
static void ssl_update_checksum_md5sha1( mbedtls_ssl_context *, const unsigned char *, size_t );
460
#endif
461

462 463 464
#if defined(MBEDTLS_SSL_PROTO_SSL3)
static void ssl_calc_verify_ssl( mbedtls_ssl_context *, unsigned char * );
static void ssl_calc_finished_ssl( mbedtls_ssl_context *, unsigned char *, int );
465 466
#endif

467 468 469
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
static void ssl_calc_verify_tls( mbedtls_ssl_context *, unsigned char * );
static void ssl_calc_finished_tls( mbedtls_ssl_context *, unsigned char *, int );
470 471
#endif

472 473 474 475 476
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
#if defined(MBEDTLS_SHA256_C)
static void ssl_update_checksum_sha256( mbedtls_ssl_context *, const unsigned char *, size_t );
static void ssl_calc_verify_tls_sha256( mbedtls_ssl_context *,unsigned char * );
static void ssl_calc_finished_tls_sha256( mbedtls_ssl_context *,unsigned char *, int );
477
#endif
478

479 480 481 482
#if defined(MBEDTLS_SHA512_C)
static void ssl_update_checksum_sha384( mbedtls_ssl_context *, const unsigned char *, size_t );
static void ssl_calc_verify_tls_sha384( mbedtls_ssl_context *, unsigned char * );
static void ssl_calc_finished_tls_sha384( mbedtls_ssl_context *, unsigned char *, int );
483
#endif
484
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
485

486
int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl )
487
{
488
    int ret = 0;
489 490 491 492
    unsigned char tmp[64];
    unsigned char keyblk[256];
    unsigned char *key1;
    unsigned char *key2;
493 494
    unsigned char *mac_enc;
    unsigned char *mac_dec;
495
    size_t iv_copy_len;
496 497
    const mbedtls_cipher_info_t *cipher_info;
    const mbedtls_md_info_t *md_info;
498

499 500 501
    mbedtls_ssl_session *session = ssl->session_negotiate;
    mbedtls_ssl_transform *transform = ssl->transform_negotiate;
    mbedtls_ssl_handshake_params *handshake = ssl->handshake;
502

503
    MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> derive keys" ) );
504

505
    cipher_info = mbedtls_cipher_info_from_type( transform->ciphersuite_info->cipher );
506 507
    if( cipher_info == NULL )
    {
508
        MBEDTLS_SSL_DEBUG_MSG( 1, ( "cipher info for %d not found",
509
                            transform->ciphersuite_info->cipher ) );
510
        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
511 512
    }

513
    md_info = mbedtls_md_info_from_type( transform->ciphersuite_info->mac );
514 515
    if( md_info == NULL )
    {
516
        MBEDTLS_SSL_DEBUG_MSG( 1, ( "mbedtls_md info for %d not found",
517
                            transform->ciphersuite_info->mac ) );
518
        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
519 520
    }

521
    /*
522
     * Set appropriate PRF function and other SSL / TLS / TLS1.2 functions
523
     */
524 525
#if defined(MBEDTLS_SSL_PROTO_SSL3)
    if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
526
    {
527 528 529
        handshake->tls_prf = ssl3_prf;
        handshake->calc_verify = ssl_calc_verify_ssl;
        handshake->calc_finished = ssl_calc_finished_ssl;
530
    }
531 532
    else
#endif
533 534
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
    if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
535
    {
536 537 538
        handshake->tls_prf = tls1_prf;
        handshake->calc_verify = ssl_calc_verify_tls;
        handshake->calc_finished = ssl_calc_finished_tls;
539
    }
540 541
    else
#endif
542 543 544 545
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
#if defined(MBEDTLS_SHA512_C)
    if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 &&
        transform->ciphersuite_info->mac == MBEDTLS_MD_SHA384 )
546
    {
547 548 549
        handshake->tls_prf = tls_prf_sha384;
        handshake->calc_verify = ssl_calc_verify_tls_sha384;
        handshake->calc_finished = ssl_calc_finished_tls_sha384;
550
    }
551
    else
552
#endif
553 554
#if defined(MBEDTLS_SHA256_C)
    if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
555
    {
556 557 558
        handshake->tls_prf = tls_prf_sha256;
        handshake->calc_verify = ssl_calc_verify_tls_sha256;
        handshake->calc_finished = ssl_calc_finished_tls_sha256;
559
    }
560 561
    else
#endif
562
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
563
    {
564 565
        MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
566
    }
567

568 569 570 571 572 573
    /*
     * SSLv3:
     *   master =
     *     MD5( premaster + SHA1( 'A'   + premaster + randbytes ) ) +
     *     MD5( premaster + SHA1( 'BB'  + premaster + randbytes ) ) +
     *     MD5( premaster + SHA1( 'CCC' + premaster + randbytes ) )
574
     *
575
     * TLSv1+:
576 577
     *   master = PRF( premaster, "master secret", randbytes )[0..47]
     */
578
    if( handshake->resume == 0 )
579
    {
580
        MBEDTLS_SSL_DEBUG_BUF( 3, "premaster secret", handshake->premaster,
581
                       handshake->pmslen );
582

583 584
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
        if( ssl->handshake->extended_ms == MBEDTLS_SSL_EXTENDED_MS_ENABLED )
585 586 587 588
        {
            unsigned char session_hash[48];
            size_t hash_len;

589
            MBEDTLS_SSL_DEBUG_MSG( 3, ( "using extended master secret" ) );
590 591 592

            ssl->handshake->calc_verify( ssl, session_hash );

593 594
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
            if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
595
            {
596
#if defined(MBEDTLS_SHA512_C)
597
                if( ssl->transform_negotiate->ciphersuite_info->mac ==
598
                    MBEDTLS_MD_SHA384 )
599 600 601 602 603 604 605 606
                {
                    hash_len = 48;
                }
                else
#endif
                    hash_len = 32;
            }
            else
607
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
608 609
                hash_len = 36;

610
            MBEDTLS_SSL_DEBUG_BUF( 3, "session hash", session_hash, hash_len );
611

612 613 614 615 616 617
            ret = handshake->tls_prf( handshake->premaster, handshake->pmslen,
                                      "extended master secret",
                                      session_hash, hash_len,
                                      session->master, 48 );
            if( ret != 0 )
            {
618
                MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
619 620
                return( ret );
            }
621 622 623

        }
        else
624
#endif
625 626 627 628 629 630
        ret = handshake->tls_prf( handshake->premaster, handshake->pmslen,
                                  "master secret",
                                  handshake->randbytes, 64,
                                  session->master, 48 );
        if( ret != 0 )
        {
631
            MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
632 633
            return( ret );
        }
634

635
        mbedtls_zeroize( handshake->premaster, sizeof(handshake->premaster) );
636 637
    }
    else
638
        MBEDTLS_SSL_DEBUG_MSG( 3, ( "no premaster (session resumed)" ) );
639 640 641 642

    /*
     * Swap the client and server random values.
     */
643 644 645
    memcpy( tmp, handshake->randbytes, 64 );
    memcpy( handshake->randbytes, tmp + 32, 32 );
    memcpy( handshake->randbytes + 32, tmp, 32 );
646
    mbedtls_zeroize( tmp, sizeof( tmp ) );
647 648 649 650 651 652 653 654 655 656 657 658 659

    /*
     *  SSLv3:
     *    key block =
     *      MD5( master + SHA1( 'A'    + master + randbytes ) ) +
     *      MD5( master + SHA1( 'BB'   + master + randbytes ) ) +
     *      MD5( master + SHA1( 'CCC'  + master + randbytes ) ) +
     *      MD5( master + SHA1( 'DDDD' + master + randbytes ) ) +
     *      ...
     *
     *  TLSv1:
     *    key block = PRF( master, "key expansion", randbytes )
     */
660 661 662 663
    ret = handshake->tls_prf( session->master, 48, "key expansion",
                              handshake->randbytes, 64, keyblk, 256 );
    if( ret != 0 )
    {
664
        MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
665 666
        return( ret );
    }
667

668 669 670 671 672
    MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite = %s",
                   mbedtls_ssl_get_ciphersuite_name( session->ciphersuite ) ) );
    MBEDTLS_SSL_DEBUG_BUF( 3, "master secret", session->master, 48 );
    MBEDTLS_SSL_DEBUG_BUF( 4, "random bytes", handshake->randbytes, 64 );
    MBEDTLS_SSL_DEBUG_BUF( 4, "key block", keyblk, 256 );
673

674
    mbedtls_zeroize( handshake->randbytes, sizeof( handshake->randbytes ) );
675 676 677 678

    /*
     * Determine the appropriate key, IV and MAC length.
     */
679

680
    transform->keylen = cipher_info->key_bitlen / 8;
681

682 683
    if( cipher_info->mode == MBEDTLS_MODE_GCM ||
        cipher_info->mode == MBEDTLS_MODE_CCM )
684
    {
685 686
        transform->maclen = 0;

687 688
        transform->ivlen = 12;
        transform->fixed_ivlen = 4;
689

690 691 692
        /* Minimum length is expicit IV + tag */
        transform->minlen = transform->ivlen - transform->fixed_ivlen
                            + ( transform->ciphersuite_info->flags &
693
                                MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16 );
694 695 696
    }
    else
    {
697
        /* Initialize HMAC contexts */
698 699
        if( ( ret = mbedtls_md_setup( &transform->md_ctx_enc, md_info, 1 ) ) != 0 ||
            ( ret = mbedtls_md_setup( &transform->md_ctx_dec, md_info, 1 ) ) != 0 )
700
        {
701
            MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_setup", ret );
702 703
            return( ret );
        }
704

705
        /* Get MAC length */
706
        transform->maclen = mbedtls_md_get_size( md_info );
707

708
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
709 710 711 712 713
        /*
         * If HMAC is to be truncated, we shall keep the leftmost bytes,
         * (rfc 6066 page 13 or rfc 2104 section 4),
         * so we only need to adjust the length here.
         */
714 715 716
        if( session->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_ENABLED )
            transform->maclen = MBEDTLS_SSL_TRUNCATED_HMAC_LEN;
#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
717

718
        /* IV length */
719
        transform->ivlen = cipher_info->iv_size;
720

721
        /* Minimum length */
722
        if( cipher_info->mode == MBEDTLS_MODE_STREAM )
723 724
            transform->minlen = transform->maclen;
        else
725
        {
726 727
            /*
             * GenericBlockCipher:
728 729 730
             * 1. if EtM is in use: one block plus MAC
             *    otherwise: * first multiple of blocklen greater than maclen
             * 2. IV except for SSL3 and TLS 1.0
731
             */
732 733
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
            if( session->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED )
734 735 736 737 738 739 740 741 742 743 744
            {
                transform->minlen = transform->maclen
                                  + cipher_info->block_size;
            }
            else
#endif
            {
                transform->minlen = transform->maclen
                                  + cipher_info->block_size
                                  - transform->maclen % cipher_info->block_size;
            }
745

746 747 748
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
            if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ||
                ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_1 )
749
                ; /* No need to adjust minlen */
750
            else
751
#endif
752 753 754
#if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
            if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_2 ||
                ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
755 756 757 758 759 760
            {
                transform->minlen += transform->ivlen;
            }
            else
#endif
            {
761 762
                MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
                return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
763
            }
764
        }
765 766
    }

767
    MBEDTLS_SSL_DEBUG_MSG( 3, ( "keylen: %d, minlen: %d, ivlen: %d, maclen: %d",
768 769
                   transform->keylen, transform->minlen, transform->ivlen,
                   transform->maclen ) );
770 771 772 773

    /*
     * Finally setup the cipher contexts, IVs and MAC secrets.
     */
774
#if defined(MBEDTLS_SSL_CLI_C)
775
    if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
776
    {
777 778
        key1 = keyblk + transform->maclen * 2;
        key2 = keyblk + transform->maclen * 2 + transform->keylen;
779

780 781
        mac_enc = keyblk;
        mac_dec = keyblk + transform->maclen;
782

783 784 785
        /*
         * This is not used in TLS v1.1.
         */
786 787 788 789
        iv_copy_len = ( transform->fixed_ivlen ) ?
                            transform->fixed_ivlen : transform->ivlen;
        memcpy( transform->iv_enc, key2 + transform->keylen,  iv_copy_len );
        memcpy( transform->iv_dec, key2 + transform->keylen + iv_copy_len,
790
                iv_copy_len );
791 792
    }
    else
793 794
#endif /* MBEDTLS_SSL_CLI_C */
#if defined(MBEDTLS_SSL_SRV_C)
795
    if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
796
    {
797 798
        key1 = keyblk + transform->maclen * 2 + transform->keylen;
        key2 = keyblk + transform->maclen * 2;
799

800 801
        mac_enc = keyblk + transform->maclen;
        mac_dec = keyblk;
802

803 804 805
        /*
         * This is not used in TLS v1.1.
         */
806 807 808 809
        iv_copy_len = ( transform->fixed_ivlen ) ?
                            transform->fixed_ivlen : transform->ivlen;
        memcpy( transform->iv_dec, key1 + transform->keylen,  iv_copy_len );
        memcpy( transform->iv_enc, key1 + transform->keylen + iv_copy_len,
810
                iv_copy_len );
811
    }
812
    else
813
#endif /* MBEDTLS_SSL_SRV_C */
814
    {
815 816
        MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
817
    }
818

819 820
#if defined(MBEDTLS_SSL_PROTO_SSL3)
    if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
821
    {
822 823
        if( transform->maclen > sizeof transform->mac_enc )
        {
824 825
            MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
            return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
826 827
        }

828 829 830 831
        memcpy( transform->mac_enc, mac_enc, transform->maclen );
        memcpy( transform->mac_dec, mac_dec, transform->maclen );
    }
    else
832 833 834 835
#endif /* MBEDTLS_SSL_PROTO_SSL3 */
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
    defined(MBEDTLS_SSL_PROTO_TLS1_2)
    if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )
836
    {
837 838
        mbedtls_md_hmac_starts( &transform->md_ctx_enc, mac_enc, transform->maclen );
        mbedtls_md_hmac_starts( &transform->md_ctx_dec, mac_dec, transform->maclen );
839
    }
840 841
    else
#endif
842
    {
843 844
        MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
845
    }
846

847 848
#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
    if( mbedtls_ssl_hw_record_init != NULL )
849 850 851
    {
        int ret = 0;

852
        MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_init()" ) );
853

854
        if( ( ret = mbedtls_ssl_hw_record_init( ssl, key1, key2, transform->keylen,
855 856
                                        transform->iv_enc, transform->iv_dec,
                                        iv_copy_len,
857
                                        mac_enc, mac_dec,
858
                                        transform->maclen ) ) != 0 )
859
        {
860 861
            MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_init", ret );
            return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
862 863
        }
    }
864
#endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
865

866
    if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_enc,
867
                                 cipher_info ) ) != 0 )
868
    {
869
        MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret );
870 871
        return( ret );
    }
872

873
    if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_dec,
874 875
                                 cipher_info ) ) != 0 )
    {
876
        MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret );
877 878
        return( ret );
    }
879

880
    if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_enc, key1,
881
                               cipher_info->key_bitlen,
882
                               MBEDTLS_ENCRYPT ) ) != 0 )
883
    {
884
        MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret );
885 886
        return( ret );
    }
887

888
    if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_dec, key2,
889
                               cipher_info->key_bitlen,
890
                               MBEDTLS_DECRYPT ) ) != 0 )
891
    {
892
        MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret );
893 894 895
        return( ret );
    }

896 897
#if defined(MBEDTLS_CIPHER_MODE_CBC)
    if( cipher_info->mode == MBEDTLS_MODE_CBC )
898
    {
899 900
        if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_enc,
                                             MBEDTLS_PADDING_NONE ) ) != 0 )
901
        {
902
            MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret );
903 904
            return( ret );
        }
905

906 907
        if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_dec,
                                             MBEDTLS_PADDING_NONE ) ) != 0 )
908
        {
909
            MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret );
910
            return( ret );
911
        }
912
    }
913
#endif /* MBEDTLS_CIPHER_MODE_CBC */
914

915
    mbedtls_zeroize( keyblk, sizeof( keyblk ) );
916

917
#if defined(MBEDTLS_ZLIB_SUPPORT)
918 919
    // Initialize compression
    //
920
    if( session->compression == MBEDTLS_SSL_COMPRESS_DEFLATE )
921
    {
922 923
        if( ssl->compress_buf == NULL )
        {
924
            MBEDTLS_SSL_DEBUG_MSG( 3, ( "Allocating compression buffer" ) );
925
            ssl->compress_buf = mbedtls_calloc( 1, MBEDTLS_SSL_BUFFER_LEN );
926 927
            if( ssl->compress_buf == NULL )
            {
928
                MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed",
929
                                    MBEDTLS_SSL_BUFFER_LEN ) );
930
                return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
931 932 933
            }
        }

934
        MBEDTLS_SSL_DEBUG_MSG( 3, ( "Initializing zlib states" ) );
935

936 937
        memset( &transform->ctx_deflate, 0, sizeof( transform->ctx_deflate ) );
        memset( &transform->ctx_inflate, 0, sizeof( transform->ctx_inflate ) );
938

939 940
        if( deflateInit( &transform->ctx_deflate,
                         Z_DEFAULT_COMPRESSION )   != Z_OK ||
941
            inflateInit( &transform->ctx_inflate ) != Z_OK )
942
        {
943 944
            MBEDTLS_SSL_DEBUG_MSG( 1, ( "Failed to initialize compression" ) );
            return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );
945 946
        }
    }
947
#endif /* MBEDTLS_ZLIB_SUPPORT */
948

949
    MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= derive keys" ) );
950 951 952 953

    return( 0 );
}

954 955
#if defined(MBEDTLS_SSL_PROTO_SSL3)
void ssl_calc_verify_ssl( mbedtls_ssl_context *ssl, unsigned char hash[36] )
956
{
957 958
    mbedtls_md5_context md5;
    mbedtls_sha1_context sha1;
959 960 961
    unsigned char pad_1[48];
    unsigned char pad_2[48];

962
    MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify ssl" ) );
963

964 965 966 967 968
    mbedtls_md5_init( &md5 );
    mbedtls_sha1_init( &sha1 );

    mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
    mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
969

970 971
    memset( pad_1, 0x36, 48 );
    memset( pad_2, 0x5C, 48 );
972

973 974 975
    mbedtls_md5_update( &md5, ssl->session_negotiate->master, 48 );
    mbedtls_md5_update( &md5, pad_1, 48 );
    mbedtls_md5_finish( &md5, hash );
976

977 978 979 980 981
    mbedtls_md5_starts( &md5 );
    mbedtls_md5_update( &md5, ssl->session_negotiate->master, 48 );
    mbedtls_md5_update( &md5, pad_2, 48 );
    mbedtls_md5_update( &md5, hash,  16 );
    mbedtls_md5_finish( &md5, hash );
982

983 984 985
    mbedtls_sha1_update( &sha1, ssl->session_negotiate->master, 48 );
    mbedtls_sha1_update( &sha1, pad_1, 40 );
    mbedtls_sha1_finish( &sha1, hash + 16 );
986

987 988 989 990 991
    mbedtls_sha1_starts( &sha1 );
    mbedtls_sha1_update( &sha1, ssl->session_negotiate->master, 48 );
    mbedtls_sha1_update( &sha1, pad_2, 40 );
    mbedtls_sha1_update( &sha1, hash + 16, 20 );
    mbedtls_sha1_finish( &sha1, hash + 16 );
992

993 994
    MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 36 );
    MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
995

996 997
    mbedtls_md5_free(  &md5  );
    mbedtls_sha1_free( &sha1 );
998

999 1000
    return;
}
1001
#endif /* MBEDTLS_SSL_PROTO_SSL3 */
1002

1003 1004
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
void ssl_calc_verify_tls( mbedtls_ssl_context *ssl, unsigned char hash[36] )
1005
{
1006 1007
    mbedtls_md5_context md5;
    mbedtls_sha1_context sha1;
1008

1009
    MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify tls" ) );
1010

1011 1012 1013 1014 1015
    mbedtls_md5_init( &md5 );
    mbedtls_sha1_init( &sha1 );

    mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
    mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
1016

1017 1018
     mbedtls_md5_finish( &md5,  hash );
    mbedtls_sha1_finish( &sha1, hash + 16 );
1019

1020 1021
    MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 36 );
    MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
1022

1023 1024
    mbedtls_md5_free(  &md5  );
    mbedtls_sha1_free( &sha1 );
1025

1026 1027
    return;
}
1028
#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
1029

1030 1031 1032
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
#if defined(MBEDTLS_SHA256_C)
void ssl_calc_verify_tls_sha256( mbedtls_ssl_context *ssl, unsigned char hash[32] )
1033
{
1034
    mbedtls_sha256_context sha256;
1035

1036 1037
    mbedtls_sha256_init( &sha256 );

1038
    MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha256" ) );
1039

1040
    mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 );
1041
    mbedtls_sha256_finish( &sha256, hash );
1042

1043 1044
    MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 32 );
    MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
1045

1046
    mbedtls_sha256_free( &sha256 );
1047

1048 1049
    return;
}
1050
#endif /* MBEDTLS_SHA256_C */
1051

1052 1053
#if defined(MBEDTLS_SHA512_C)
void ssl_calc_verify_tls_sha384( mbedtls_ssl_context *ssl, unsigned char hash[48] )