ssl_tls.c 100 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
#include "polarssl/aes.h"
#include "polarssl/arc4.h"
40
#include "polarssl/camellia.h"
41 42 43
#include "polarssl/des.h"
#include "polarssl/debug.h"
#include "polarssl/ssl.h"
44

45 46 47 48
#if defined(POLARSSL_GCM_C)
#include "polarssl/gcm.h"
#endif

49 50 51
#include <stdlib.h>
#include <time.h>

52 53 54 55
#if defined _MSC_VER && !defined strcasecmp
#define strcasecmp _stricmp
#endif

56 57 58
#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,
59
                       size_t keylen,
60
                       const unsigned char *iv_enc,  const unsigned char *iv_dec,
61 62 63 64
                       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;
65 66 67 68 69 70
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

71
#if defined(POLARSSL_RSA_C)
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
static int ssl_rsa_decrypt( void *ctx, int mode, size_t *olen,
                        const unsigned char *input, unsigned char *output,
                        size_t output_max_len )
{
    return rsa_pkcs1_decrypt( (rsa_context *) ctx, mode, olen, input, output,
                              output_max_len );
}

static int ssl_rsa_sign( void *ctx,
                    int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
                    int mode, int hash_id, unsigned int hashlen,
                    const unsigned char *hash, unsigned char *sig )
{
    return rsa_pkcs1_sign( (rsa_context *) ctx, f_rng, p_rng, mode, hash_id,
                           hashlen, hash, sig );
}

static size_t ssl_rsa_key_len( void *ctx )
{
    return ( (rsa_context *) ctx )->len;
}
93
#endif /* POLARSSL_RSA_C */
94

95 96 97
/*
 * Key material generation
 */
98 99 100
static int ssl3_prf( const unsigned char *secret, size_t slen,
                     const char *label,
                     const unsigned char *random, size_t rlen,
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
                     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 );
}

143 144 145
static int tls1_prf( const unsigned char *secret, size_t slen,
                     const char *label,
                     const unsigned char *random, size_t rlen,
146
                     unsigned char *dstbuf, size_t dlen )
147
{
148 149
    size_t nb, hs;
    size_t i, j, k;
150
    const unsigned char *S1, *S2;
151 152 153 154
    unsigned char tmp[128];
    unsigned char h_i[20];

    if( sizeof( tmp ) < 20 + strlen( label ) + rlen )
155
        return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203

    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 );
}

204 205 206
static int tls_prf_sha256( const unsigned char *secret, size_t slen,
                           const char *label,
                           const unsigned char *random, size_t rlen,
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
                           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]
     */
225
    sha256_hmac( secret, slen, tmp + 32, nb, tmp, 0 );
226 227 228

    for( i = 0; i < dlen; i += 32 )
    {
229 230
        sha256_hmac( secret, slen, tmp, 32 + nb, h_i, 0 );
        sha256_hmac( secret, slen, tmp, 32,      tmp, 0 );
231 232 233 234 235 236 237 238 239 240 241 242 243

        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 );
}

244
#if defined(POLARSSL_SHA512_C)
245 246 247
static int tls_prf_sha384( const unsigned char *secret, size_t slen,
                           const char *label,
                           const unsigned char *random, size_t rlen,
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
                           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]
     */
266
    sha512_hmac( secret, slen, tmp + 48, nb, tmp, 1 );
267 268 269

    for( i = 0; i < dlen; i += 48 )
    {
270 271
        sha512_hmac( secret, slen, tmp, 48 + nb, h_i, 1 );
        sha512_hmac( secret, slen, tmp, 48,      tmp, 1 );
272 273 274 275 276 277 278 279 280 281 282 283

        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 );
}
284
#endif
285

286 287 288
static void ssl_update_checksum_start(ssl_context *, const unsigned char *, size_t);
static void ssl_update_checksum_md5sha1(ssl_context *, const unsigned char *, size_t);
static void ssl_update_checksum_sha256(ssl_context *, const unsigned char *, size_t);
289 290 291 292 293

static void ssl_calc_verify_ssl(ssl_context *,unsigned char *);
static void ssl_calc_verify_tls(ssl_context *,unsigned char *);
static void ssl_calc_verify_tls_sha256(ssl_context *,unsigned char *);

294 295 296
static void ssl_calc_finished_ssl(ssl_context *,unsigned char *,int);
static void ssl_calc_finished_tls(ssl_context *,unsigned char *,int);
static void ssl_calc_finished_tls_sha256(ssl_context *,unsigned char *,int);
297

298
#if defined(POLARSSL_SHA512_C)
299
static void ssl_update_checksum_sha384(ssl_context *, const unsigned char *, size_t);
300
static void ssl_calc_verify_tls_sha384(ssl_context *,unsigned char *);
301
static void ssl_calc_finished_tls_sha384(ssl_context *,unsigned char *,int);
302
#endif
303

304 305 306 307 308 309
int ssl_derive_keys( ssl_context *ssl )
{
    unsigned char tmp[64];
    unsigned char keyblk[256];
    unsigned char *key1;
    unsigned char *key2;
310 311
    unsigned char *mac_enc;
    unsigned char *mac_dec;
312
    unsigned int iv_copy_len;
313 314 315
    const cipher_info_t *cipher_info;
    const md_info_t *md_info;

316 317 318
    ssl_session *session = ssl->session_negotiate;
    ssl_transform *transform = ssl->transform_negotiate;
    ssl_handshake_params *handshake = ssl->handshake;
319 320 321

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

322 323 324
    cipher_info = cipher_info_from_type( transform->ciphersuite_info->cipher );
    if( cipher_info == NULL )
    {
325
        SSL_DEBUG_MSG( 1, ( "cipher info for %d not found",
326 327 328 329 330 331 332
                            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 )
    {
333
        SSL_DEBUG_MSG( 1, ( "md info for %d not found",
334 335 336 337
                            transform->ciphersuite_info->mac ) );
        return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
    }

338
    /*
339
     * Set appropriate PRF function and other SSL / TLS / TLS1.2 functions
340 341
     */
    if( ssl->minor_ver == SSL_MINOR_VERSION_0 )
342
    {
343 344 345
        handshake->tls_prf = ssl3_prf;
        handshake->calc_verify = ssl_calc_verify_ssl;
        handshake->calc_finished = ssl_calc_finished_ssl;
346
    }
347
    else if( ssl->minor_ver < SSL_MINOR_VERSION_3 )
348
    {
349 350 351
        handshake->tls_prf = tls1_prf;
        handshake->calc_verify = ssl_calc_verify_tls;
        handshake->calc_finished = ssl_calc_finished_tls;
352
    }
353
#if defined(POLARSSL_SHA512_C)
354 355
    else if( transform->ciphersuite_info->mac ==
             POLARSSL_MD_SHA384 )
356
    {
357 358 359
        handshake->tls_prf = tls_prf_sha384;
        handshake->calc_verify = ssl_calc_verify_tls_sha384;
        handshake->calc_finished = ssl_calc_finished_tls_sha384;
360
    }
361
#endif
362
    else
363
    {
364 365 366
        handshake->tls_prf = tls_prf_sha256;
        handshake->calc_verify = ssl_calc_verify_tls_sha256;
        handshake->calc_finished = ssl_calc_finished_tls_sha256;
367
    }
368

369 370 371 372 373 374
    /*
     * SSLv3:
     *   master =
     *     MD5( premaster + SHA1( 'A'   + premaster + randbytes ) ) +
     *     MD5( premaster + SHA1( 'BB'  + premaster + randbytes ) ) +
     *     MD5( premaster + SHA1( 'CCC' + premaster + randbytes ) )
375
     *
376 377 378
     * TLSv1:
     *   master = PRF( premaster, "master secret", randbytes )[0..47]
     */
379
    if( handshake->resume == 0 )
380
    {
381 382
        SSL_DEBUG_BUF( 3, "premaster secret", handshake->premaster,
                       handshake->pmslen );
383

384 385 386
        handshake->tls_prf( handshake->premaster, handshake->pmslen,
                            "master secret",
                            handshake->randbytes, 64, session->master, 48 );
387

388
        memset( handshake->premaster, 0, sizeof( handshake->premaster ) );
389 390 391 392 393 394 395
    }
    else
        SSL_DEBUG_MSG( 3, ( "no premaster (session resumed)" ) );

    /*
     * Swap the client and server random values.
     */
396 397 398
    memcpy( tmp, handshake->randbytes, 64 );
    memcpy( handshake->randbytes, tmp + 32, 32 );
    memcpy( handshake->randbytes + 32, tmp, 32 );
399 400 401 402 403 404 405 406 407 408 409 410 411 412
    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 )
     */
413 414
    handshake->tls_prf( session->master, 48, "key expansion",
                        handshake->randbytes, 64, keyblk, 256 );
415

416 417 418 419
    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 );
420 421
    SSL_DEBUG_BUF( 4, "key block", keyblk, 256 );

422
    memset( handshake->randbytes, 0, sizeof( handshake->randbytes ) );
423 424 425 426

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

428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
    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 )
        {
            md_init_ctx( &transform->md_ctx_enc, md_info );
            md_init_ctx( &transform->md_ctx_dec, md_info );
443

444 445
            transform->maclen = md_get_size( md_info );
        }
446

447 448 449
        transform->keylen = cipher_info->key_length;
        transform->keylen /= 8;
        transform->ivlen = cipher_info->iv_size;
450

451 452 453 454 455 456 457 458
        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;
        }
459 460 461
    }

    SSL_DEBUG_MSG( 3, ( "keylen: %d, minlen: %d, ivlen: %d, maclen: %d",
462 463
                   transform->keylen, transform->minlen, transform->ivlen,
                   transform->maclen ) );
464 465 466 467 468 469

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

473 474
        mac_enc = keyblk;
        mac_dec = keyblk + transform->maclen;
475

Paul Bakker's avatar
Paul Bakker committed
476 477 478
        /*
         * This is not used in TLS v1.1.
         */
479 480 481 482
        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,
483
                iv_copy_len );
484 485 486
    }
    else
    {
487 488
        key1 = keyblk + transform->maclen * 2 + transform->keylen;
        key2 = keyblk + transform->maclen * 2;
489

490 491
        mac_enc = keyblk + transform->maclen;
        mac_dec = keyblk;
492

Paul Bakker's avatar
Paul Bakker committed
493 494 495
        /*
         * This is not used in TLS v1.1.
         */
496 497 498 499
        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,
500
                iv_copy_len );
501 502
    }

503 504 505 506 507 508 509 510 511 512 513
    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
    {
        md_hmac_starts( &transform->md_ctx_enc, mac_enc, transform->maclen );
        md_hmac_starts( &transform->md_ctx_dec, mac_dec, transform->maclen );
    }

514 515 516 517 518 519 520
#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()" ) );

521 522 523
        if( ( ret = ssl_hw_record_init( ssl, key1, key2, transform->keylen,
                                        transform->iv_enc, transform->iv_dec,
                                        iv_copy_len,
524
                                        mac_enc, mac_dec,
525
                                        transform->maclen ) ) != 0 )
526 527 528 529 530 531 532
        {
            SSL_DEBUG_RET( 1, "ssl_hw_record_init", ret );
            return POLARSSL_ERR_SSL_HW_ACCEL_FAILED;
        }
    }
#endif

533
    switch( cipher_info->type )
534
    {
535
#if defined(POLARSSL_ARC4_C)
536
        case POLARSSL_CIPHER_ARC4_128:
537 538 539 540
            arc4_setup( (arc4_context *) transform->ctx_enc, key1,
                        transform->keylen );
            arc4_setup( (arc4_context *) transform->ctx_dec, key2,
                        transform->keylen );
541 542 543
            break;
#endif

544
#if defined(POLARSSL_DES_C)
545 546 547 548
        case POLARSSL_CIPHER_DES_EDE3_CBC:
             des3_set3key_enc( (des3_context *) transform->ctx_enc, key1 );
             des3_set3key_dec( (des3_context *) transform->ctx_dec, key2 );
             break;
549 550
#endif

551
#if defined(POLARSSL_AES_C)
552 553 554 555 556 557
        case POLARSSL_CIPHER_AES_128_CBC:
        case POLARSSL_CIPHER_AES_256_CBC:
            aes_setkey_enc( (aes_context*) transform->ctx_enc, key1,
                            cipher_info->key_length );
            aes_setkey_dec( (aes_context*) transform->ctx_dec, key2,
                            cipher_info->key_length );
558 559 560
            break;
#endif

561
#if defined(POLARSSL_CAMELLIA_C)
562 563 564 565 566 567
        case POLARSSL_CIPHER_CAMELLIA_128_CBC:
        case POLARSSL_CIPHER_CAMELLIA_256_CBC:
            camellia_setkey_enc( (camellia_context*) transform->ctx_enc, key1,
                                 cipher_info->key_length );
            camellia_setkey_dec( (camellia_context*) transform->ctx_dec, key2,
                                 cipher_info->key_length );
568 569 570
            break;
#endif

571
#if defined(POLARSSL_DES_C)
572
        case POLARSSL_CIPHER_DES_CBC:
573 574
            des_setkey_enc( (des_context *) transform->ctx_enc, key1 );
            des_setkey_dec( (des_context *) transform->ctx_dec, key2 );
575 576
            break;
#endif
577 578 579 580 581 582 583 584 585 586 587 588 589

#if defined(POLARSSL_GCM_C)
        case POLARSSL_CIPHER_AES_128_GCM:
        case POLARSSL_CIPHER_AES_256_GCM:
            gcm_init( (gcm_context *) transform->ctx_enc, key1,
                      cipher_info->key_length );
            gcm_init( (gcm_context *) transform->ctx_dec, key2,
                      cipher_info->key_length );
            break;
#endif

        case POLARSSL_CIPHER_NULL:
            break;
590

591
        default:
592
            return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE );
593 594 595 596
    }

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

597 598 599
#if defined(POLARSSL_ZLIB_SUPPORT)
    // Initialize compression
    //
600
    if( session->compression == SSL_COMPRESS_DEFLATE )
601 602 603
    {
        SSL_DEBUG_MSG( 3, ( "Initializing zlib states" ) );

604 605
        memset( &transform->ctx_deflate, 0, sizeof( transform->ctx_deflate ) );
        memset( &transform->ctx_inflate, 0, sizeof( transform->ctx_inflate ) );
606

607 608
        if( deflateInit( &transform->ctx_deflate, Z_DEFAULT_COMPRESSION ) != Z_OK ||
            inflateInit( &transform->ctx_inflate ) != Z_OK )
609 610 611 612 613 614 615
        {
            SSL_DEBUG_MSG( 1, ( "Failed to initialize compression" ) );
            return( POLARSSL_ERR_SSL_COMPRESSION_FAILED );
        }
    }
#endif /* POLARSSL_ZLIB_SUPPORT */

616 617 618 619 620
    SSL_DEBUG_MSG( 2, ( "<= derive keys" ) );

    return( 0 );
}

621
void ssl_calc_verify_ssl( ssl_context *ssl, unsigned char hash[36] )
622 623 624 625 626 627
{
    md5_context md5;
    sha1_context sha1;
    unsigned char pad_1[48];
    unsigned char pad_2[48];

628
    SSL_DEBUG_MSG( 2, ( "=> calc verify ssl" ) );
629

630 631
    memcpy( &md5 , &ssl->handshake->fin_md5 , sizeof(md5_context)  );
    memcpy( &sha1, &ssl->handshake->fin_sha1, sizeof(sha1_context) );
632

633 634
    memset( pad_1, 0x36, 48 );
    memset( pad_2, 0x5C, 48 );
635

636
    md5_update( &md5, ssl->session_negotiate->master, 48 );
637 638
    md5_update( &md5, pad_1, 48 );
    md5_finish( &md5, hash );
639

640
    md5_starts( &md5 );
641
    md5_update( &md5, ssl->session_negotiate->master, 48 );
642 643 644
    md5_update( &md5, pad_2, 48 );
    md5_update( &md5, hash,  16 );
    md5_finish( &md5, hash );
645

646
    sha1_update( &sha1, ssl->session_negotiate->master, 48 );
647 648 649 650
    sha1_update( &sha1, pad_1, 40 );
    sha1_finish( &sha1, hash + 16 );

    sha1_starts( &sha1 );
651
    sha1_update( &sha1, ssl->session_negotiate->master, 48 );
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
    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;
}

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" ) );

669 670
    memcpy( &md5 , &ssl->handshake->fin_md5 , sizeof(md5_context)  );
    memcpy( &sha1, &ssl->handshake->fin_sha1, sizeof(sha1_context) );
671

672
     md5_finish( &md5,  hash );
673 674 675 676 677 678 679 680 681 682
    sha1_finish( &sha1, hash + 16 );

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

    return;
}

void ssl_calc_verify_tls_sha256( ssl_context *ssl, unsigned char hash[32] )
{
683
    sha256_context sha256;
684 685 686

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

687 688
    memcpy( &sha256, &ssl->handshake->fin_sha256, sizeof(sha256_context) );
    sha256_finish( &sha256, hash );
689 690 691 692 693 694 695

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

    return;
}

696
#if defined(POLARSSL_SHA512_C)
697 698
void ssl_calc_verify_tls_sha384( ssl_context *ssl, unsigned char hash[48] )
{
699
    sha512_context sha512;
700 701 702

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

703 704
    memcpy( &sha512, &ssl->handshake->fin_sha512, sizeof(sha512_context) );
    sha512_finish( &sha512, hash );
705

706
    SSL_DEBUG_BUF( 3, "calculated verify result", hash, 48 );
707 708 709 710
    SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );

    return;
}
711
#endif
712 713 714 715

/*
 * SSLv3.0 MAC functions
 */
716 717 718
static void ssl_mac( md_context_t *md_ctx, unsigned char *secret,
                     unsigned char *buf, size_t len,
                     unsigned char *ctr, int type )
719 720 721
{
    unsigned char header[11];
    unsigned char padding[48];
722 723 724
    int padlen = 0;
    int md_size = md_get_size( md_ctx->md_info );
    int md_type = md_get_type( md_ctx->md_info );
725

726 727 728 729 730 731
    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;
732 733 734 735 736 737

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

738 739 740 741 742 743 744
    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     );
745

746 747 748 749 750 751
    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          );
752 753
}

754 755
/*
 * Encryption/decryption functions
756
 */
757 758
static int ssl_encrypt_buf( ssl_context *ssl )
{
759
    size_t i, padlen;
760 761 762 763 764 765 766 767

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

    /*
     * Add MAC then encrypt
     */
    if( ssl->minor_ver == SSL_MINOR_VERSION_0 )
    {
768 769 770 771
        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 );
772 773 774
    }
    else
    {
775 776 777 778 779 780
        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 );
781 782 783
    }

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

786
    ssl->out_msglen += ssl->transform_out->maclen;
787

788 789 790 791 792 793 794 795 796
#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 defined(POLARSSL_ARC4_C)
    if( ssl->transform_out->ciphersuite_info->cipher == POLARSSL_CIPHER_ARC4_128 )
797 798 799 800 801 802 803 804 805 806
    {
        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 );

807 808 809
        arc4_crypt( (arc4_context *) ssl->transform_out->ctx_enc,
                    ssl->out_msglen, ssl->out_msg,
                    ssl->out_msg );
810
    }
811 812 813 814 815
    else
#endif /* POLARSSL_ARC4_C */
#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 )
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
    {
        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 );

835 836 837 838
        /*
         * Generate IV
         */
        ret = ssl->f_rng( ssl->p_rng,
839
                    ssl->transform_out->iv_enc + ssl->transform_out->fixed_ivlen,
840 841 842
                    ssl->transform_out->ivlen - ssl->transform_out->fixed_ivlen );
        if( ret != 0 )
            return( ret );
843

844 845 846
        memcpy( ssl->out_iv,
                ssl->transform_out->iv_enc + ssl->transform_out->fixed_ivlen,
                ssl->transform_out->ivlen - ssl->transform_out->fixed_ivlen );
847

848 849 850 851 852 853 854
        /*
         * Fix pointer positions and message length with added IV
         */
        enc_msg = ssl->out_msg;
        enc_msglen = ssl->out_msglen;
        ssl->out_msglen += ssl->transform_out->ivlen -
                           ssl->transform_out->fixed_ivlen;
855

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

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

863 864 865 866
        /*
         * Adjust for tag
         */
        ssl->out_msglen += 16;
867

868 869 870 871 872 873 874 875 876
        gcm_crypt_and_tag( (gcm_context *) ssl->transform_out->ctx_enc,
                GCM_ENCRYPT, enc_msglen,
                ssl->transform_out->iv_enc, ssl->transform_out->ivlen,
                add_data, 13,
                enc_msg, enc_msg,
                16, enc_msg + enc_msglen );

        SSL_DEBUG_BUF( 4, "after encrypt: tag",
                       enc_msg + enc_msglen, 16 );
877
    }
878
    else
879
#endif /* POLARSSL_GCM_C */
880
    {
Paul Bakker's avatar
Paul Bakker committed
881
        unsigned char *enc_msg;
882
        size_t enc_msglen;
Paul Bakker's avatar
Paul Bakker committed
883

884 885 886
        padlen = ssl->transform_out->ivlen - ( ssl->out_msglen + 1 ) %
                 ssl->transform_out->ivlen;
        if( padlen == ssl->transform_out->ivlen )
887 888 889 890 891 892 893
            padlen = 0;

        for( i = 0; i <= padlen; i++ )
            ssl->out_msg[ssl->out_msglen + i] = (unsigned char) padlen;

        ssl->out_msglen += padlen + 1;

Paul Bakker's avatar
Paul Bakker committed
894 895 896 897
        enc_msglen = ssl->out_msglen;
        enc_msg = ssl->out_msg;

        /*
898 899
         * Prepend per-record IV for block cipher in TLS v1.1 and up as per
         * Method 1 (6.2.3.2. in RFC4346 and RFC5246)
Paul Bakker's avatar
Paul Bakker committed
900
         */
901
        if( ssl->minor_ver >= SSL_MINOR_VERSION_2 )
Paul Bakker's avatar
Paul Bakker committed
902 903 904 905
        {
            /*
             * Generate IV
             */
906 907
            int ret = ssl->f_rng( ssl->p_rng, ssl->transform_out->iv_enc,
                                  ssl->transform_out->ivlen );
908 909
            if( ret != 0 )
                return( ret );
Paul Bakker's avatar
Paul Bakker committed
910

911
            memcpy( ssl->out_iv, ssl->transform_out->iv_enc,
912
                    ssl->transform_out->ivlen );
Paul Bakker's avatar
Paul Bakker committed
913 914 915 916

            /*
             * Fix pointer positions and message length with added IV
             */
917
            enc_msg = ssl->out_msg;
Paul Bakker's avatar
Paul Bakker committed
918
            enc_msglen = ssl->out_msglen;
919
            ssl->out_msglen += ssl->transform_out->ivlen;
Paul Bakker's avatar
Paul Bakker committed
920 921
        }

922
        SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
Paul Bakker's avatar
Paul Bakker committed
923
                            "including %d bytes of IV and %d bytes of padding",
924
                       ssl->out_msglen, ssl->transform_out->ivlen, padlen + 1 ) );
925 926

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

929
        switch( ssl->transform_out->ciphersuite_info->cipher )
930
        {
931 932 933 934
            case POLARSSL_CIPHER_DES_CBC:
                des_crypt_cbc( (des_context *) ssl->transform_out->ctx_enc,
                               DES_ENCRYPT, enc_msglen,
                               ssl->transform_out->iv_enc, enc_msg, enc_msg );
935 936
                break;

937 938 939 940 941
            case POLARSSL_CIPHER_DES_EDE3_CBC:
                des3_crypt_cbc( (des3_context *) ssl->transform_out->ctx_enc,
                               DES_ENCRYPT, enc_msglen,
                               ssl->transform_out->iv_enc, enc_msg, enc_msg );
                break;
942

943 944 945 946 947 948 949 950 951 952 953 954 955
            case POLARSSL_CIPHER_AES_128_CBC:
            case POLARSSL_CIPHER_AES_256_CBC:
                aes_crypt_cbc( (aes_context *) ssl->transform_out->ctx_enc,
                               AES_ENCRYPT, enc_msglen,
                               ssl->transform_out->iv_enc, enc_msg, enc_msg );
                break;

            case POLARSSL_CIPHER_CAMELLIA_128_CBC:
            case POLARSSL_CIPHER_CAMELLIA_256_CBC:
                camellia_crypt_cbc( (camellia_context *) ssl->transform_out->ctx_enc,
                                    CAMELLIA_ENCRYPT, enc_msglen,
                                    ssl->transform_out->iv_enc, enc_msg, enc_msg );
                break;
956 957

            default:
958
                return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE );
959 960 961
        }
    }

962 963 964 965
    for( i = 8; i > 0; i-- )
        if( ++ssl->out_ctr[i - 1] != 0 )
            break;

966 967 968 969 970
    SSL_DEBUG_MSG( 2, ( "<= encrypt buf" ) );

    return( 0 );
}

971
#define POLARSSL_SSL_MAX_MAC_SIZE   48
972

973 974
static int ssl_decrypt_buf( ssl_context *ssl )
{
975
    size_t i, padlen = 0, correct = 1;
976
    unsigned char tmp[POLARSSL_SSL_MAX_MAC_SIZE];
977 978 979

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

980
    if( ssl->in_msglen < ssl->transform_in->minlen )
981 982
    {
        SSL_DEBUG_MSG( 1, ( "in_msglen (%d) < minlen (%d)",
983
                       ssl->in_msglen, ssl->transform_in->minlen ) );
984
        return( POLARSSL_ERR_SSL_INVALID_MAC );
985 986
    }

987 988
#if defined(POLARSSL_CIPHER_NULL_CIPHER)
    if( ssl->transform_in->ciphersuite_info->cipher == POLARSSL_CIPHER_NULL )
989
    {
990 991 992 993
        padlen = 0;
    }
    else
#endif /* POLARSSL_CIPHER_NULL_CIPHER */
994
#if defined(POLARSSL_ARC4_C)
995 996 997 998 999
    if( ssl->transform_in->ciphersuite_info->cipher == POLARSSL_CIPHER_ARC4_128 )
    {
        padlen = 0;

        arc4_crypt( (arc4_context *) ssl->transform_in->ctx_dec,
1000 1001
                    ssl->in_msglen, ssl->in_msg,
                    ssl->in_msg );
1002
    }
1003 1004 1005 1006 1007
    else
#endif /* POLARSSL_ARC4_C */
#if defined(POLARSSL_GCM_C)
    if( ssl->transform_in->ciphersuite_info->cipher == POLARSSL_CIPHER_AES_128_GCM ||
        ssl->transform_in->ciphersuite_info->cipher == POLARSSL_CIPHER_AES_256_GCM )
1008 1009 1010 1011 1012 1013 1014
    {
        unsigned char *dec_msg;
        unsigned char *dec_msg_result;
        size_t dec_msglen;
        unsigned char add_data[13];
        int ret = POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE;

1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
        padlen = 0;

        dec_msglen = ssl->in_msglen - ( ssl->transform_in->ivlen -
                                        ssl->transform_in->fixed_ivlen );
        dec_msglen -= 16;
        dec_msg = ssl->in_msg;
        dec_msg_result = ssl->in_msg;
        ssl->in_msglen = dec_msglen;

        memcpy( add_data, ssl->in_ctr, 8 );
        add_data[8]  = ssl->in_msgtype;
        add_data[9]  = ssl->major_ver;
        add_data[10] = ssl->minor_ver;
        add_data[11] = ( ssl->in_msglen >> 8 ) & 0xFF;
        add_data[12] = ssl->in_msglen & 0xFF;

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

        memcpy( ssl->transform_in->iv_dec + ssl->transform_in->fixed_ivlen,
                ssl->in_iv,
                ssl->transform_in->ivlen - ssl->transform_in->fixed_ivlen );

        SSL_DEBUG_BUF( 4, "IV used", ssl->transform_in->iv_dec,
                                     ssl->transform_in->ivlen );
        SSL_DEBUG_BUF( 4, "TAG used", dec_msg + dec_msglen, 16 );

        ret = gcm_auth_decrypt( (gcm_context *) ssl->transform_in->ctx_dec,
                                 dec_msglen,
                                 ssl->transform_in->iv_dec,
                                 ssl->transform_in->ivlen,
                                 add_data, 13,
                                 dec_msg + dec_msglen, 16,
                                 dec_msg, dec_msg_result );

        if( ret != 0 )
1051
        {