ssl_tls.c 118 KB
Newer Older
1 2 3
/*
 *  SSLv3/TLSv1 shared functions
 *
4
 *  Copyright (C) 2006-2013, Brainspark B.V.
Paul Bakker's avatar
Paul Bakker committed
5 6
 *
 *  This file is part of PolarSSL (http://www.polarssl.org)
7
 *  Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org>
Paul Bakker's avatar
Paul Bakker committed
8
 *
9
 *  All rights reserved.
Paul Bakker's avatar
Paul Bakker committed
10
 *
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
 *  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
 */

34
#include "polarssl/config.h"
35

36
#if defined(POLARSSL_SSL_TLS_C)
37

38 39 40
#include "polarssl/debug.h"
#include "polarssl/ssl.h"

41 42 43 44 45 46 47
#if defined(POLARSSL_MEMORY_C)
#include "polarssl/memory.h"
#else
#define polarssl_malloc     malloc
#define polarssl_free       free
#endif

48 49
#include <stdlib.h>

50 51 52 53
#if defined _MSC_VER && !defined strcasecmp
#define strcasecmp _stricmp
#endif

54
#if defined(POLARSSL_SSL_MAX_FRAGMENT_LENGTH)
55 56 57 58 59 60 61 62
/*
 * 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
 */
63
static unsigned int mfl_code_to_length[SSL_MAX_FRAG_LEN_INVALID] =
64 65 66 67 68 69 70
{
    SSL_MAX_CONTENT_LEN,    /* SSL_MAX_FRAG_LEN_NONE */
    512,                    /* SSL_MAX_FRAG_LEN_512  */
    1024,                   /* SSL_MAX_FRAG_LEN_1024 */
    2048,                   /* SSL_MAX_FRAG_LEN_2048 */
    4096,                   /* SSL_MAX_FRAG_LEN_4096 */
};
71
#endif /* POLARSSL_SSL_MAX_FRAGMENT_LENGTH */
72

73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
static int ssl_session_copy( ssl_session *dst, const ssl_session *src )
{
    int ret;

    ssl_session_free( dst );
    memcpy( dst, src, sizeof( ssl_session ) );

#if defined(POLARSSL_X509_PARSE_C)
    if( src->peer_cert != NULL )
    {
        if( ( dst->peer_cert = polarssl_malloc( sizeof(x509_cert) ) ) == NULL )
            return( POLARSSL_ERR_SSL_MALLOC_FAILED );

        memset( dst->peer_cert, 0, sizeof(x509_cert) );

        if( ( ret = x509parse_crt( dst->peer_cert, src->peer_cert->raw.p,
                                   src->peer_cert->raw.len ) != 0 ) )
        {
            polarssl_free( dst->peer_cert );
            dst->peer_cert = NULL;
            return( ret );
        }
    }
#endif /* POLARSSL_X509_PARSE_C */

98
#if defined(POLARSSL_SSL_SESSION_TICKETS)
99 100 101 102 103 104 105
    if( src->ticket != NULL )
    {
        if( ( dst->ticket = polarssl_malloc( src->ticket_len ) ) == NULL )
            return( POLARSSL_ERR_SSL_MALLOC_FAILED );

        memcpy( dst->ticket, src->ticket, src->ticket_len );
    }
106
#endif /* POLARSSL_SSL_SESSION_TICKETS */
107 108 109 110

    return( 0 );
}

111 112 113
#if defined(POLARSSL_SSL_HW_RECORD_ACCEL)
int (*ssl_hw_record_init)(ssl_context *ssl,
                       const unsigned char *key_enc, const unsigned char *key_dec,
114
                       size_t keylen,
115
                       const unsigned char *iv_enc,  const unsigned char *iv_dec,
116 117 118 119
                       size_t ivlen,
                       const unsigned char *mac_enc, const unsigned char *mac_dec,
                       size_t maclen) = NULL;
int (*ssl_hw_record_activate)(ssl_context *ssl, int direction) = NULL;
120 121 122 123 124 125
int (*ssl_hw_record_reset)(ssl_context *ssl) = NULL;
int (*ssl_hw_record_write)(ssl_context *ssl) = NULL;
int (*ssl_hw_record_read)(ssl_context *ssl) = NULL;
int (*ssl_hw_record_finish)(ssl_context *ssl) = NULL;
#endif

126 127 128
/*
 * Key material generation
 */
129
#if defined(POLARSSL_SSL_PROTO_SSL3)
130 131 132
static int ssl3_prf( const unsigned char *secret, size_t slen,
                     const char *label,
                     const unsigned char *random, size_t rlen,
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
                     unsigned char *dstbuf, size_t dlen )
{
    size_t i;
    md5_context md5;
    sha1_context sha1;
    unsigned char padding[16];
    unsigned char sha1sum[20];
    ((void)label);

    /*
     *  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++ )
    {
        memset( padding, 'A' + i, 1 + i );

        sha1_starts( &sha1 );
        sha1_update( &sha1, padding, 1 + i );
        sha1_update( &sha1, secret, slen );
        sha1_update( &sha1, random, rlen );
        sha1_finish( &sha1, sha1sum );

        md5_starts( &md5 );
        md5_update( &md5, secret, slen );
        md5_update( &md5, sha1sum, 20 );
        md5_finish( &md5, dstbuf + i * 16 );
    }

    memset( &md5,  0, sizeof( md5  ) );
    memset( &sha1, 0, sizeof( sha1 ) );

    memset( padding, 0, sizeof( padding ) );
    memset( sha1sum, 0, sizeof( sha1sum ) );

    return( 0 );
}
174
#endif /* POLARSSL_SSL_PROTO_SSL3 */
175

176
#if defined(POLARSSL_SSL_PROTO_TLS1) || defined(POLARSSL_SSL_PROTO_TLS1_1)
177 178 179
static int tls1_prf( const unsigned char *secret, size_t slen,
                     const char *label,
                     const unsigned char *random, size_t rlen,
180
                     unsigned char *dstbuf, size_t dlen )
181
{
182 183
    size_t nb, hs;
    size_t i, j, k;
184
    const unsigned char *S1, *S2;
185 186 187 188
    unsigned char tmp[128];
    unsigned char h_i[20];

    if( sizeof( tmp ) < 20 + strlen( label ) + rlen )
189
        return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236

    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]
     */
    md5_hmac( S1, hs, tmp + 20, nb, 4 + tmp );

    for( i = 0; i < dlen; i += 16 )
    {
        md5_hmac( S1, hs, 4 + tmp, 16 + nb, h_i );
        md5_hmac( S1, hs, 4 + tmp, 16,  4 + tmp );

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

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

    /*
     * XOR out with P_sha1(secret,label+random)[0..dlen]
     */
    sha1_hmac( S2, hs, tmp + 20, nb, tmp );

    for( i = 0; i < dlen; i += 20 )
    {
        sha1_hmac( S2, hs, tmp, 20 + nb, h_i );
        sha1_hmac( S2, hs, tmp, 20,      tmp );

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

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

    memset( tmp, 0, sizeof( tmp ) );
    memset( h_i, 0, sizeof( h_i ) );

    return( 0 );
}
237
#endif /* POLARSSL_SSL_PROTO_TLS1) || POLARSSL_SSL_PROTO_TLS1_1 */
238

239 240
#if defined(POLARSSL_SSL_PROTO_TLS1_2)
#if defined(POLARSSL_SHA256_C)
241 242 243
static int tls_prf_sha256( const unsigned char *secret, size_t slen,
                           const char *label,
                           const unsigned char *random, size_t rlen,
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
                           unsigned char *dstbuf, size_t dlen )
{
    size_t nb;
    size_t i, j, k;
    unsigned char tmp[128];
    unsigned char h_i[32];

    if( sizeof( tmp ) < 32 + strlen( label ) + rlen )
        return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );

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

    /*
     * Compute P_<hash>(secret, label + random)[0..dlen]
     */
262
    sha256_hmac( secret, slen, tmp + 32, nb, tmp, 0 );
263 264 265

    for( i = 0; i < dlen; i += 32 )
    {
266 267
        sha256_hmac( secret, slen, tmp, 32 + nb, h_i, 0 );
        sha256_hmac( secret, slen, tmp, 32,      tmp, 0 );
268 269 270 271 272 273 274 275 276 277 278 279

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

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

    memset( tmp, 0, sizeof( tmp ) );
    memset( h_i, 0, sizeof( h_i ) );

    return( 0 );
}
280
#endif /* POLARSSL_SHA256_C */
281

282
#if defined(POLARSSL_SHA512_C)
283 284 285
static int tls_prf_sha384( const unsigned char *secret, size_t slen,
                           const char *label,
                           const unsigned char *random, size_t rlen,
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
                           unsigned char *dstbuf, size_t dlen )
{
    size_t nb;
    size_t i, j, k;
    unsigned char tmp[128];
    unsigned char h_i[48];

    if( sizeof( tmp ) < 48 + strlen( label ) + rlen )
        return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );

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

    /*
     * Compute P_<hash>(secret, label + random)[0..dlen]
     */
304
    sha512_hmac( secret, slen, tmp + 48, nb, tmp, 1 );
305 306 307

    for( i = 0; i < dlen; i += 48 )
    {
308 309
        sha512_hmac( secret, slen, tmp, 48 + nb, h_i, 1 );
        sha512_hmac( secret, slen, tmp, 48,      tmp, 1 );
310 311 312 313 314 315 316 317 318 319 320 321

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

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

    memset( tmp, 0, sizeof( tmp ) );
    memset( h_i, 0, sizeof( h_i ) );

    return( 0 );
}
322 323
#endif /* POLARSSL_SHA512_C */
#endif /* POLARSSL_SSL_PROTO_TLS1_2 */
324

325
static void ssl_update_checksum_start(ssl_context *, const unsigned char *, size_t);
326 327 328

#if defined(POLARSSL_SSL_PROTO_SSL3) || defined(POLARSSL_SSL_PROTO_TLS1) || \
    defined(POLARSSL_SSL_PROTO_TLS1_1)
329
static void ssl_update_checksum_md5sha1(ssl_context *, const unsigned char *, size_t);
330
#endif
331

332
#if defined(POLARSSL_SSL_PROTO_SSL3)
333
static void ssl_calc_verify_ssl(ssl_context *,unsigned char *);
334
static void ssl_calc_finished_ssl(ssl_context *,unsigned char *,int);
335 336 337 338
#endif

#if defined(POLARSSL_SSL_PROTO_TLS1) || defined(POLARSSL_SSL_PROTO_TLS1_1)
static void ssl_calc_verify_tls(ssl_context *,unsigned char *);
339
static void ssl_calc_finished_tls(ssl_context *,unsigned char *,int);
340 341 342 343 344 345
#endif

#if defined(POLARSSL_SSL_PROTO_TLS1_2)
#if defined(POLARSSL_SHA256_C)
static void ssl_update_checksum_sha256(ssl_context *, const unsigned char *, size_t);
static void ssl_calc_verify_tls_sha256(ssl_context *,unsigned char *);
346
static void ssl_calc_finished_tls_sha256(ssl_context *,unsigned char *,int);
347
#endif
348

349
#if defined(POLARSSL_SHA512_C)
350
static void ssl_update_checksum_sha384(ssl_context *, const unsigned char *, size_t);
351
static void ssl_calc_verify_tls_sha384(ssl_context *,unsigned char *);
352
static void ssl_calc_finished_tls_sha384(ssl_context *,unsigned char *,int);
353
#endif
354
#endif
355

356 357
int ssl_derive_keys( ssl_context *ssl )
{
358
    int ret = 0;
359 360 361 362
    unsigned char tmp[64];
    unsigned char keyblk[256];
    unsigned char *key1;
    unsigned char *key2;
363 364
    unsigned char *mac_enc;
    unsigned char *mac_dec;
365
    unsigned int iv_copy_len;
366 367 368
    const cipher_info_t *cipher_info;
    const md_info_t *md_info;

369 370 371
    ssl_session *session = ssl->session_negotiate;
    ssl_transform *transform = ssl->transform_negotiate;
    ssl_handshake_params *handshake = ssl->handshake;
372 373 374

    SSL_DEBUG_MSG( 2, ( "=> derive keys" ) );

375 376 377
    cipher_info = cipher_info_from_type( transform->ciphersuite_info->cipher );
    if( cipher_info == NULL )
    {
378
        SSL_DEBUG_MSG( 1, ( "cipher info for %d not found",
379 380 381 382 383 384 385
                            transform->ciphersuite_info->cipher ) );
        return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
    }

    md_info = md_info_from_type( transform->ciphersuite_info->mac );
    if( md_info == NULL )
    {
386
        SSL_DEBUG_MSG( 1, ( "md info for %d not found",
387 388 389 390
                            transform->ciphersuite_info->mac ) );
        return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
    }

391
    /*
392
     * Set appropriate PRF function and other SSL / TLS / TLS1.2 functions
393
     */
394
#if defined(POLARSSL_SSL_PROTO_SSL3)
395
    if( ssl->minor_ver == SSL_MINOR_VERSION_0 )
396
    {
397 398 399
        handshake->tls_prf = ssl3_prf;
        handshake->calc_verify = ssl_calc_verify_ssl;
        handshake->calc_finished = ssl_calc_finished_ssl;
400
    }
401 402 403 404
    else
#endif
#if defined(POLARSSL_SSL_PROTO_TLS1) || defined(POLARSSL_SSL_PROTO_TLS1_1)
    if( ssl->minor_ver < SSL_MINOR_VERSION_3 )
405
    {
406 407 408
        handshake->tls_prf = tls1_prf;
        handshake->calc_verify = ssl_calc_verify_tls;
        handshake->calc_finished = ssl_calc_finished_tls;
409
    }
410 411 412
    else
#endif
#if defined(POLARSSL_SSL_PROTO_TLS1_2)
413
#if defined(POLARSSL_SHA512_C)
414 415
    if( ssl->minor_ver == SSL_MINOR_VERSION_3 &&
        transform->ciphersuite_info->mac == POLARSSL_MD_SHA384 )
416
    {
417 418 419
        handshake->tls_prf = tls_prf_sha384;
        handshake->calc_verify = ssl_calc_verify_tls_sha384;
        handshake->calc_finished = ssl_calc_finished_tls_sha384;
420
    }
421
    else
422 423 424
#endif
#if defined(POLARSSL_SHA256_C)
    if( ssl->minor_ver == SSL_MINOR_VERSION_3 )
425
    {
426 427 428
        handshake->tls_prf = tls_prf_sha256;
        handshake->calc_verify = ssl_calc_verify_tls_sha256;
        handshake->calc_finished = ssl_calc_finished_tls_sha256;
429
    }
430 431 432
    else
#endif
#endif
433 434
    {
        SSL_DEBUG_MSG( 1, ( "should never happen" ) );
435
        return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE );
436
    }
437

438 439 440 441 442 443
    /*
     * SSLv3:
     *   master =
     *     MD5( premaster + SHA1( 'A'   + premaster + randbytes ) ) +
     *     MD5( premaster + SHA1( 'BB'  + premaster + randbytes ) ) +
     *     MD5( premaster + SHA1( 'CCC' + premaster + randbytes ) )
444
     *
445
     * TLSv1+:
446 447
     *   master = PRF( premaster, "master secret", randbytes )[0..47]
     */
448
    if( handshake->resume == 0 )
449
    {
450 451
        SSL_DEBUG_BUF( 3, "premaster secret", handshake->premaster,
                       handshake->pmslen );
452

453 454 455
        handshake->tls_prf( handshake->premaster, handshake->pmslen,
                            "master secret",
                            handshake->randbytes, 64, session->master, 48 );
456

457
        memset( handshake->premaster, 0, sizeof( handshake->premaster ) );
458 459 460 461 462 463 464
    }
    else
        SSL_DEBUG_MSG( 3, ( "no premaster (session resumed)" ) );

    /*
     * Swap the client and server random values.
     */
465 466 467
    memcpy( tmp, handshake->randbytes, 64 );
    memcpy( handshake->randbytes, tmp + 32, 32 );
    memcpy( handshake->randbytes + 32, tmp, 32 );
468 469 470 471 472 473 474 475 476 477 478 479 480 481
    memset( tmp, 0, sizeof( tmp ) );

    /*
     *  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 )
     */
482 483
    handshake->tls_prf( session->master, 48, "key expansion",
                        handshake->randbytes, 64, keyblk, 256 );
484

485 486 487 488
    SSL_DEBUG_MSG( 3, ( "ciphersuite = %s",
                   ssl_get_ciphersuite_name( session->ciphersuite ) ) );
    SSL_DEBUG_BUF( 3, "master secret", session->master, 48 );
    SSL_DEBUG_BUF( 4, "random bytes", handshake->randbytes, 64 );
489 490
    SSL_DEBUG_BUF( 4, "key block", keyblk, 256 );

491
    memset( handshake->randbytes, 0, sizeof( handshake->randbytes ) );
492 493 494 495

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

497 498 499 500 501 502 503 504 505 506 507 508 509
    if( cipher_info->mode == POLARSSL_MODE_GCM )
    {
        transform->keylen = cipher_info->key_length;
        transform->keylen /= 8;
        transform->minlen = 1;
        transform->ivlen = 12;
        transform->fixed_ivlen = 4;
        transform->maclen = 0;
    }
    else
    {
        if( md_info->type != POLARSSL_MD_NONE )
        {
510 511
            int ret;

512 513 514 515 516 517 518 519 520 521 522
            if( ( ret = md_init_ctx( &transform->md_ctx_enc, md_info ) ) != 0 )
            {
                SSL_DEBUG_RET( 1, "md_init_ctx", ret );
                return( ret );
            }

            if( ( ret = md_init_ctx( &transform->md_ctx_dec, md_info ) ) != 0 )
            {
                SSL_DEBUG_RET( 1, "md_init_ctx", ret );
                return( ret );
            }
523

524
            transform->maclen = md_get_size( md_info );
525

526
#if defined(POLARSSL_SSL_TRUNCATED_HMAC)
527 528 529 530 531 532 533
            /*
             * 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.
             */
            if( session->trunc_hmac == SSL_TRUNC_HMAC_ENABLED )
                transform->maclen = SSL_TRUNCATED_HMAC_LEN;
534
#endif /* POLARSSL_SSL_TRUNCATED_HMAC */
535
        }
536

537 538 539
        transform->keylen = cipher_info->key_length;
        transform->keylen /= 8;
        transform->ivlen = cipher_info->iv_size;
540

541 542 543 544 545 546 547 548
        transform->minlen = transform->keylen;
        if( transform->minlen < transform->maclen )
        {
            if( cipher_info->mode == POLARSSL_MODE_STREAM )
                transform->minlen = transform->maclen;
            else
                transform->minlen += transform->keylen;
        }
549 550 551
    }

    SSL_DEBUG_MSG( 3, ( "keylen: %d, minlen: %d, ivlen: %d, maclen: %d",
552 553
                   transform->keylen, transform->minlen, transform->ivlen,
                   transform->maclen ) );
554 555 556 557 558 559

    /*
     * Finally setup the cipher contexts, IVs and MAC secrets.
     */
    if( ssl->endpoint == SSL_IS_CLIENT )
    {
560 561
        key1 = keyblk + transform->maclen * 2;
        key2 = keyblk + transform->maclen * 2 + transform->keylen;
562

563 564
        mac_enc = keyblk;
        mac_dec = keyblk + transform->maclen;
565

Paul Bakker's avatar
Paul Bakker committed
566 567 568
        /*
         * This is not used in TLS v1.1.
         */
569 570 571 572
        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,
573
                iv_copy_len );
574 575 576
    }
    else
    {
577 578
        key1 = keyblk + transform->maclen * 2 + transform->keylen;
        key2 = keyblk + transform->maclen * 2;
579

580 581
        mac_enc = keyblk + transform->maclen;
        mac_dec = keyblk;
582

Paul Bakker's avatar
Paul Bakker committed
583 584 585
        /*
         * This is not used in TLS v1.1.
         */
586 587 588 589
        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,
590
                iv_copy_len );
591 592
    }

593
#if defined(POLARSSL_SSL_PROTO_SSL3)
594 595 596 597 598 599
    if( ssl->minor_ver == SSL_MINOR_VERSION_0 )
    {
        memcpy( transform->mac_enc, mac_enc, transform->maclen );
        memcpy( transform->mac_dec, mac_dec, transform->maclen );
    }
    else
600 601 602 603
#endif
#if defined(POLARSSL_SSL_PROTO_TLS1) || defined(POLARSSL_SSL_PROTO_TLS1_1) || \
    defined(POLARSSL_SSL_PROTO_TLS1_2)
    if( ssl->minor_ver >= SSL_MINOR_VERSION_1 )
604 605 606 607
    {
        md_hmac_starts( &transform->md_ctx_enc, mac_enc, transform->maclen );
        md_hmac_starts( &transform->md_ctx_dec, mac_dec, transform->maclen );
    }
608 609
    else
#endif
610 611
    {
        SSL_DEBUG_MSG( 1, ( "should never happen" ) );
612
        return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE );
613
    }
614

615 616 617 618 619 620 621
#if defined(POLARSSL_SSL_HW_RECORD_ACCEL)
    if( ssl_hw_record_init != NULL)
    {
        int ret = 0;

        SSL_DEBUG_MSG( 2, ( "going for ssl_hw_record_init()" ) );

622 623 624
        if( ( ret = ssl_hw_record_init( ssl, key1, key2, transform->keylen,
                                        transform->iv_enc, transform->iv_dec,
                                        iv_copy_len,
625
                                        mac_enc, mac_dec,
626
                                        transform->maclen ) ) != 0 )
627 628 629 630 631 632 633
        {
            SSL_DEBUG_RET( 1, "ssl_hw_record_init", ret );
            return POLARSSL_ERR_SSL_HW_ACCEL_FAILED;
        }
    }
#endif

634
    switch( cipher_info->type )
635
    {
636 637
        case POLARSSL_CIPHER_ARC4_128:
        case POLARSSL_CIPHER_DES_EDE3_CBC:
638 639
        case POLARSSL_CIPHER_CAMELLIA_128_CBC:
        case POLARSSL_CIPHER_CAMELLIA_256_CBC:
640 641
        case POLARSSL_CIPHER_AES_128_CBC:
        case POLARSSL_CIPHER_AES_256_CBC:
642
        case POLARSSL_CIPHER_DES_CBC:
643 644
        case POLARSSL_CIPHER_AES_128_GCM:
        case POLARSSL_CIPHER_AES_256_GCM:
645 646 647
            if( ( ret = cipher_init_ctx( &transform->cipher_ctx_enc,
                                         cipher_info ) ) != 0 )
            {
648
                SSL_DEBUG_RET( 1, "cipher_init_ctx", ret );
649 650 651 652 653 654
                return( ret );
            }

            if( ( ret = cipher_init_ctx( &transform->cipher_ctx_dec,
                                         cipher_info ) ) != 0 )
            {
655
                SSL_DEBUG_RET( 1, "cipher_init_ctx", ret );
656 657 658
                return( ret );
            }

659 660 661
            if( ( ret = cipher_setkey( &transform->cipher_ctx_enc, key1,
                                       cipher_info->key_length,
                                       POLARSSL_ENCRYPT ) ) != 0 )
662
            {
663 664
                SSL_DEBUG_RET( 1, "cipher_setkey", ret );
                return( ret );
665 666
            }

667 668 669 670 671 672
            if( ( ret = cipher_setkey( &transform->cipher_ctx_dec, key2,
                                       cipher_info->key_length,
                                       POLARSSL_DECRYPT ) ) != 0 )
            {
                SSL_DEBUG_RET( 1, "cipher_setkey", ret );
                return( ret );
673 674
            }

675
            if( cipher_info->mode == POLARSSL_MODE_CBC )
676
            {
677 678 679
                if( ( ret = cipher_set_padding_mode( &transform->cipher_ctx_enc,
                                                     POLARSSL_PADDING_NONE ) ) != 0 )
                {
680
                    SSL_DEBUG_RET( 1, "cipher_set_padding_mode", ret );
681 682 683 684 685 686
                    return( ret );
                }

                if( ( ret = cipher_set_padding_mode( &transform->cipher_ctx_dec,
                                                     POLARSSL_PADDING_NONE ) ) != 0 )
                {
687
                    SSL_DEBUG_RET( 1, "cipher_set_padding_mode", ret );
688 689
                    return( ret );
                }
690
            }
691 692
            break;

693 694
        case POLARSSL_CIPHER_NULL:
            break;
695

696
        default:
697
            return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE );
698 699 700 701
    }

    memset( keyblk, 0, sizeof( keyblk ) );

702 703 704
#if defined(POLARSSL_ZLIB_SUPPORT)
    // Initialize compression
    //
705
    if( session->compression == SSL_COMPRESS_DEFLATE )
706 707 708
    {
        SSL_DEBUG_MSG( 3, ( "Initializing zlib states" ) );

709 710
        memset( &transform->ctx_deflate, 0, sizeof( transform->ctx_deflate ) );
        memset( &transform->ctx_inflate, 0, sizeof( transform->ctx_inflate ) );
711

712 713
        if( deflateInit( &transform->ctx_deflate, Z_DEFAULT_COMPRESSION ) != Z_OK ||
            inflateInit( &transform->ctx_inflate ) != Z_OK )
714 715 716 717 718 719 720
        {
            SSL_DEBUG_MSG( 1, ( "Failed to initialize compression" ) );
            return( POLARSSL_ERR_SSL_COMPRESSION_FAILED );
        }
    }
#endif /* POLARSSL_ZLIB_SUPPORT */

721 722 723 724 725
    SSL_DEBUG_MSG( 2, ( "<= derive keys" ) );

    return( 0 );
}

726
#if defined(POLARSSL_SSL_PROTO_SSL3)
727
void ssl_calc_verify_ssl( ssl_context *ssl, unsigned char hash[36] )
728 729 730 731 732 733
{
    md5_context md5;
    sha1_context sha1;
    unsigned char pad_1[48];
    unsigned char pad_2[48];

734
    SSL_DEBUG_MSG( 2, ( "=> calc verify ssl" ) );
735

736 737
    memcpy( &md5 , &ssl->handshake->fin_md5 , sizeof(md5_context)  );
    memcpy( &sha1, &ssl->handshake->fin_sha1, sizeof(sha1_context) );
738

739 740
    memset( pad_1, 0x36, 48 );
    memset( pad_2, 0x5C, 48 );
741

742
    md5_update( &md5, ssl->session_negotiate->master, 48 );
743 744
    md5_update( &md5, pad_1, 48 );
    md5_finish( &md5, hash );
745

746
    md5_starts( &md5 );
747
    md5_update( &md5, ssl->session_negotiate->master, 48 );
748 749 750
    md5_update( &md5, pad_2, 48 );
    md5_update( &md5, hash,  16 );
    md5_finish( &md5, hash );
751

752
    sha1_update( &sha1, ssl->session_negotiate->master, 48 );
753 754 755 756
    sha1_update( &sha1, pad_1, 40 );
    sha1_finish( &sha1, hash + 16 );

    sha1_starts( &sha1 );
757
    sha1_update( &sha1, ssl->session_negotiate->master, 48 );
758 759 760 761 762 763 764 765 766
    sha1_update( &sha1, pad_2, 40 );
    sha1_update( &sha1, hash + 16, 20 );
    sha1_finish( &sha1, hash + 16 );

    SSL_DEBUG_BUF( 3, "calculated verify result", hash, 36 );
    SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );

    return;
}
767
#endif
768

769
#if defined(POLARSSL_SSL_PROTO_TLS1) || defined(POLARSSL_SSL_PROTO_TLS1_1)
770 771 772 773 774 775 776
void ssl_calc_verify_tls( ssl_context *ssl, unsigned char hash[36] )
{
    md5_context md5;
    sha1_context sha1;

    SSL_DEBUG_MSG( 2, ( "=> calc verify tls" ) );

777 778
    memcpy( &md5 , &ssl->handshake->fin_md5 , sizeof(md5_context)  );
    memcpy( &sha1, &ssl->handshake->fin_sha1, sizeof(sha1_context) );
779

780
     md5_finish( &md5,  hash );
781 782 783 784 785 786 787
    sha1_finish( &sha1, hash + 16 );

    SSL_DEBUG_BUF( 3, "calculated verify result", hash, 36 );
    SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );

    return;
}
788
#endif /* POLARSSL_SSL_PROTO_TLS1 || POLARSSL_SSL_PROTO_TLS1_1 */
789

790 791
#if defined(POLARSSL_SSL_PROTO_TLS1_2)
#if defined(POLARSSL_SHA256_C)
792 793
void ssl_calc_verify_tls_sha256( ssl_context *ssl, unsigned char hash[32] )
{
794
    sha256_context sha256;
795 796 797

    SSL_DEBUG_MSG( 2, ( "=> calc verify sha256" ) );

798 799
    memcpy( &sha256, &ssl->handshake->fin_sha256, sizeof(sha256_context) );
    sha256_finish( &sha256, hash );
800 801 802 803 804 805

    SSL_DEBUG_BUF( 3, "calculated verify result", hash, 32 );
    SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );

    return;
}
806
#endif /* POLARSSL_SHA256_C */
807

808
#if defined(POLARSSL_SHA512_C)
809 810
void ssl_calc_verify_tls_sha384( ssl_context *ssl, unsigned char hash[48] )
{
811
    sha512_context sha512;
812 813 814

    SSL_DEBUG_MSG( 2, ( "=> calc verify sha384" ) );

815 816
    memcpy( &sha512, &ssl->handshake->fin_sha512, sizeof(sha512_context) );
    sha512_finish( &sha512, hash );
817

818
    SSL_DEBUG_BUF( 3, "calculated verify result", hash, 48 );
819 820 821 822
    SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );

    return;
}
823 824
#endif /* POLARSSL_SHA512_C */
#endif /* POLARSSL_SSL_PROTO_TLS1_2 */
825

826
#if defined(POLARSSL_SSL_PROTO_SSL3)
827 828 829
/*
 * SSLv3.0 MAC functions
 */
830 831 832
static void ssl_mac( md_context_t *md_ctx, unsigned char *secret,
                     unsigned char *buf, size_t len,
                     unsigned char *ctr, int type )
833 834 835
{
    unsigned char header[11];
    unsigned char padding[48];
836 837 838
    int padlen = 0;
    int md_size = md_get_size( md_ctx->md_info );
    int md_type = md_get_type( md_ctx->md_info );
839

840 841 842 843 844 845
    if( md_type == POLARSSL_MD_MD5 )
        padlen = 48;
    else if( md_type == POLARSSL_MD_SHA1 )
        padlen = 40;
    else if( md_type == POLARSSL_MD_SHA256 )
        padlen = 32;
846 847 848 849 850 851

    memcpy( header, ctr, 8 );
    header[ 8] = (unsigned char)  type;
    header[ 9] = (unsigned char)( len >> 8 );
    header[10] = (unsigned char)( len      );

852 853 854 855 856 857 858
    memset( padding, 0x36, padlen );
    md_starts( md_ctx );
    md_update( md_ctx, secret,  md_size );
    md_update( md_ctx, padding, padlen  );
    md_update( md_ctx, header,  11      );
    md_update( md_ctx, buf,     len     );
    md_finish( md_ctx, buf +    len     );
859

860 861 862 863 864 865
    memset( padding, 0x5C, padlen );
    md_starts( md_ctx );
    md_update( md_ctx, secret,    md_size );
    md_update( md_ctx, padding,   padlen  );
    md_update( md_ctx, buf + len, md_size );
    md_finish( md_ctx, buf + len          );
866
}
867
#endif /* POLARSSL_SSL_PROTO_SSL3 */
868

869 870
/*
 * Encryption/decryption functions
871
 */
872 873
static int ssl_encrypt_buf( ssl_context *ssl )
{
874
    size_t i, padlen;
875 876 877 878 879 880

    SSL_DEBUG_MSG( 2, ( "=> encrypt buf" ) );

    /*
     * Add MAC then encrypt
     */
881
#if defined(POLARSSL_SSL_PROTO_SSL3)
882 883
    if( ssl->minor_ver == SSL_MINOR_VERSION_0 )
    {
884 885 886 887
        ssl_mac( &ssl->transform_out->md_ctx_enc,
                  ssl->transform_out->mac_enc,
                  ssl->out_msg, ssl->out_msglen,
                  ssl->out_ctr, ssl->out_msgtype );
888 889
    }
    else
890 891 892 893
#endif
#if defined(POLARSSL_SSL_PROTO_TLS1) || defined(POLARSSL_SSL_PROTO_TLS1_1) || \
    defined(POLARSSL_SSL_PROTO_TLS1_2)
    if( ssl->minor_ver >= SSL_MINOR_VERSION_1 )
894
    {
895 896 897 898 899 900
        md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_ctr, 13 );
        md_hmac_update( &ssl->transform_out->md_ctx_enc,
                         ssl->out_msg, ssl->out_msglen );
        md_hmac_finish( &ssl->transform_out->md_ctx_enc,
                         ssl->out_msg + ssl->out_msglen );
        md_hmac_reset( &ssl->transform_out->md_ctx_enc );
901
    }
902 903
    else
#endif
904 905
    {
        SSL_DEBUG_MSG( 1, ( "should never happen" ) );
906
        return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE );
907
    }
908 909

    SSL_DEBUG_BUF( 4, "computed mac",
910
                   ssl->out_msg + ssl->out_msglen, ssl->transform_out->maclen );
911

912
    ssl->out_msglen += ssl->transform_out->maclen;
913

914 915 916 917 918 919 920 921
#if defined(POLARSSL_CIPHER_NULL_CIPHER)
    if( ssl->transform_out->ciphersuite_info->cipher == POLARSSL_CIPHER_NULL )
    {
        padlen = 0;
    }
    else
#endif /* POLARSSL_CIPHER_NULL_CIPHER */
    if( ssl->transform_out->ciphersuite_info->cipher == POLARSSL_CIPHER_ARC4_128 )
922
    {
923 924 925
        int ret;
        size_t olen = 0;

926 927 928 929 930 931 932 933 934
        padlen = 0;

        SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
                            "including %d bytes of padding",
                       ssl->out_msglen, 0 ) );

        SSL_DEBUG_BUF( 4, "before encrypt: output payload",
                       ssl->out_msg, ssl->out_msglen );

935 936 937 938 939 940 941 942 943
        if( ( ret = cipher_reset( &ssl->transform_out->cipher_ctx_enc ) ) != 0 )
        {
            SSL_DEBUG_RET( 1, "cipher_reset", ret );
            return( ret );
        }

        if( ( ret = cipher_set_iv( &ssl->transform_out->cipher_ctx_enc,
                                   ssl->transform_out->iv_enc,
                                   ssl->transform_out->ivlen ) ) != 0 )
944
        {
945
            SSL_DEBUG_RET( 1, "cipher_set_iv", ret );
946 947 948 949 950 951 952
            return( ret );
        }

        if( ( ret = cipher_update( &ssl->transform_out->cipher_ctx_enc,
                                   ssl->out_msg, ssl->out_msglen, ssl->out_msg,
                                   &olen ) ) != 0 )
        {
953
            SSL_DEBUG_RET( 1, "cipher_update", ret );
954 955 956 957 958 959 960 961 962 963 964 965
            return( ret );
        }

        if( ssl->out_msglen != olen )
        {
            SSL_DEBUG_MSG( 1, ( "total encrypted length incorrect %d %d",
                                ssl->out_msglen, olen ) );
            // TODO Real error number
            return( -1 );
        }

        if( ( ret = cipher_finish( &ssl->transform_out->cipher_ctx_enc,
966
                                   ssl->out_msg + olen, &olen ) ) != 0 )
967
        {
968
            SSL_DEBUG_RET( 1, "cipher_finish", ret );
969 970 971 972 973 974 975 976 977 978
            return( ret );
        }

        if( 0 != olen )
        {
            SSL_DEBUG_MSG( 1, ( "total encrypted length incorrect %d %d",
                                0, olen ) );
            // TODO Real error number
            return( -1 );
        }
979
    }
980 981 982 983
    else
#if defined(POLARSSL_GCM_C)
    if( ssl->transform_out->ciphersuite_info->cipher == POLARSSL_CIPHER_AES_128_GCM ||
        ssl->transform_out->ciphersuite_info->cipher == POLARSSL_CIPHER_AES_256_GCM )
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
    {
        size_t enc_msglen;
        unsigned char *enc_msg;
        unsigned char add_data[13];
        int ret = POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE;

        padlen = 0;
        enc_msglen = ssl->out_msglen;

        memcpy( add_data, ssl->out_ctr, 8 );
        add_data[8]  = ssl->out_msgtype;
        add_data[9]  = ssl->major_ver;
        add_data[10] = ssl->minor_ver;
        add_data[11] = ( ssl->out_msglen >> 8 ) & 0xFF;
        add_data[12] = ssl->out_msglen & 0xFF;

        SSL_DEBUG_BUF( 4, "additional data used for AEAD",
                       add_data, 13 );

1003 1004 1005 1006
        /*
         * Generate IV
         */
        ret = ssl->f_rng( ssl->p_rng,
1007