ssl_tls.c 139 KB
Newer Older
1 2 3
/*
 *  SSLv3/TLSv1 shared functions
 *
4
 *  Copyright (C) 2006-2014, 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
#if defined(POLARSSL_PLATFORM_C)
#include "polarssl/platform.h"
43 44 45 46 47
#else
#define polarssl_malloc     malloc
#define polarssl_free       free
#endif

48 49
#include <stdlib.h>

50 51
#if defined(_MSC_VER) && !defined strcasecmp && !defined(EFIX64) && \
    !defined(EFI32)
52 53 54
#define strcasecmp _stricmp
#endif

55
#if defined(POLARSSL_SSL_MAX_FRAGMENT_LENGTH)
56 57 58 59 60 61 62 63
/*
 * 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
 */
64
static unsigned int mfl_code_to_length[SSL_MAX_FRAG_LEN_INVALID] =
65 66 67 68 69 70 71
{
    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 */
};
72
#endif /* POLARSSL_SSL_MAX_FRAGMENT_LENGTH */
73

74 75 76 77 78
static int ssl_session_copy( ssl_session *dst, const ssl_session *src )
{
    ssl_session_free( dst );
    memcpy( dst, src, sizeof( ssl_session ) );

79
#if defined(POLARSSL_X509_CRT_PARSE_C)
80 81
    if( src->peer_cert != NULL )
    {
82 83
        int ret;

84 85
        dst->peer_cert = (x509_crt *) polarssl_malloc( sizeof(x509_crt) );
        if( dst->peer_cert == NULL )
86 87
            return( POLARSSL_ERR_SSL_MALLOC_FAILED );

88
        x509_crt_init( dst->peer_cert );
89

90 91
        if( ( ret = x509_crt_parse( dst->peer_cert, src->peer_cert->raw.p,
                                    src->peer_cert->raw.len ) != 0 ) )
92 93 94 95 96 97
        {
            polarssl_free( dst->peer_cert );
            dst->peer_cert = NULL;
            return( ret );
        }
    }
98
#endif /* POLARSSL_X509_CRT_PARSE_C */
99

100
#if defined(POLARSSL_SSL_SESSION_TICKETS)
101 102
    if( src->ticket != NULL )
    {
103 104
        dst->ticket = (unsigned char *) polarssl_malloc( src->ticket_len );
        if( dst->ticket == NULL )
105 106 107 108
            return( POLARSSL_ERR_SSL_MALLOC_FAILED );

        memcpy( dst->ticket, src->ticket, src->ticket_len );
    }
109
#endif /* POLARSSL_SSL_SESSION_TICKETS */
110 111 112 113

    return( 0 );
}

114 115 116
#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,
117
                       size_t keylen,
118
                       const unsigned char *iv_enc,  const unsigned char *iv_dec,
119 120 121 122
                       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;
123 124 125 126 127 128
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

129 130 131
/*
 * Key material generation
 */
132
#if defined(POLARSSL_SSL_PROTO_SSL3)
133 134 135
static int ssl3_prf( const unsigned char *secret, size_t slen,
                     const char *label,
                     const unsigned char *random, size_t rlen,
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
                     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++ )
    {
155
        memset( padding, (unsigned char) ('A' + i), 1 + i );
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176

        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 );
}
177
#endif /* POLARSSL_SSL_PROTO_SSL3 */
178

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

    if( sizeof( tmp ) < 20 + strlen( label ) + rlen )
192
        return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
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 237 238 239

    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 );
}
240
#endif /* POLARSSL_SSL_PROTO_TLS1) || POLARSSL_SSL_PROTO_TLS1_1 */
241

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

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

        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 );
}
283
#endif /* POLARSSL_SHA256_C */
284

285
#if defined(POLARSSL_SHA512_C)
286 287 288
static int tls_prf_sha384( const unsigned char *secret, size_t slen,
                           const char *label,
                           const unsigned char *random, size_t rlen,
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
                           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]
     */
307
    sha512_hmac( secret, slen, tmp + 48, nb, tmp, 1 );
308 309 310

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

        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 );
}
325 326
#endif /* POLARSSL_SHA512_C */
#endif /* POLARSSL_SSL_PROTO_TLS1_2 */
327

328
static void ssl_update_checksum_start(ssl_context *, const unsigned char *, size_t);
329 330 331

#if defined(POLARSSL_SSL_PROTO_SSL3) || defined(POLARSSL_SSL_PROTO_TLS1) || \
    defined(POLARSSL_SSL_PROTO_TLS1_1)
332
static void ssl_update_checksum_md5sha1(ssl_context *, const unsigned char *, size_t);
333
#endif
334

335
#if defined(POLARSSL_SSL_PROTO_SSL3)
336
static void ssl_calc_verify_ssl(ssl_context *,unsigned char *);
337
static void ssl_calc_finished_ssl(ssl_context *,unsigned char *,int);
338 339 340 341
#endif

#if defined(POLARSSL_SSL_PROTO_TLS1) || defined(POLARSSL_SSL_PROTO_TLS1_1)
static void ssl_calc_verify_tls(ssl_context *,unsigned char *);
342
static void ssl_calc_finished_tls(ssl_context *,unsigned char *,int);
343 344 345 346 347 348
#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 *);
349
static void ssl_calc_finished_tls_sha256(ssl_context *,unsigned char *,int);
350
#endif
351

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

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

372 373 374
    ssl_session *session = ssl->session_negotiate;
    ssl_transform *transform = ssl->transform_negotiate;
    ssl_handshake_params *handshake = ssl->handshake;
375 376 377

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

378 379 380
    cipher_info = cipher_info_from_type( transform->ciphersuite_info->cipher );
    if( cipher_info == NULL )
    {
381
        SSL_DEBUG_MSG( 1, ( "cipher info for %d not found",
382 383 384 385 386 387 388
                            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 )
    {
389
        SSL_DEBUG_MSG( 1, ( "md info for %d not found",
390 391 392 393
                            transform->ciphersuite_info->mac ) );
        return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
    }

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

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

456 457 458
        handshake->tls_prf( handshake->premaster, handshake->pmslen,
                            "master secret",
                            handshake->randbytes, 64, session->master, 48 );
459

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

    /*
     * Swap the client and server random values.
     */
468 469 470
    memcpy( tmp, handshake->randbytes, 64 );
    memcpy( handshake->randbytes, tmp + 32, 32 );
    memcpy( handshake->randbytes + 32, tmp, 32 );
471 472 473 474 475 476 477 478 479 480 481 482 483 484
    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 )
     */
485 486
    handshake->tls_prf( session->master, 48, "key expansion",
                        handshake->randbytes, 64, keyblk, 256 );
487

488 489 490 491
    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 );
492 493
    SSL_DEBUG_BUF( 4, "key block", keyblk, 256 );

494
    memset( handshake->randbytes, 0, sizeof( handshake->randbytes ) );
495 496 497 498

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

500 501 502 503 504 505 506 507 508 509 510 511 512
    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 )
        {
513 514
            int ret;

515 516 517 518 519 520 521 522 523 524 525
            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 );
            }
526

527
            transform->maclen = md_get_size( md_info );
528

529
#if defined(POLARSSL_SSL_TRUNCATED_HMAC)
530 531 532 533 534 535 536
            /*
             * 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;
537
#endif /* POLARSSL_SSL_TRUNCATED_HMAC */
538
        }
539

540 541 542
        transform->keylen = cipher_info->key_length;
        transform->keylen /= 8;
        transform->ivlen = cipher_info->iv_size;
543

544 545 546 547 548 549 550 551
        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;
        }
552 553 554
    }

    SSL_DEBUG_MSG( 3, ( "keylen: %d, minlen: %d, ivlen: %d, maclen: %d",
555 556
                   transform->keylen, transform->minlen, transform->ivlen,
                   transform->maclen ) );
557 558 559 560 561 562

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

566 567
        mac_enc = keyblk;
        mac_dec = keyblk + transform->maclen;
568

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

583 584
        mac_enc = keyblk + transform->maclen;
        mac_dec = keyblk;
585

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

596
#if defined(POLARSSL_SSL_PROTO_SSL3)
597 598
    if( ssl->minor_ver == SSL_MINOR_VERSION_0 )
    {
599 600 601 602 603 604
        if( transform->maclen > sizeof transform->mac_enc )
        {
            SSL_DEBUG_MSG( 1, ( "should never happen" ) );
            return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE );
        }

605 606 607 608
        memcpy( transform->mac_enc, mac_enc, transform->maclen );
        memcpy( transform->mac_dec, mac_dec, transform->maclen );
    }
    else
609 610 611 612
#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 )
613 614 615 616
    {
        md_hmac_starts( &transform->md_ctx_enc, mac_enc, transform->maclen );
        md_hmac_starts( &transform->md_ctx_dec, mac_dec, transform->maclen );
    }
617 618
    else
#endif
619 620
    {
        SSL_DEBUG_MSG( 1, ( "should never happen" ) );
621
        return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE );
622
    }
623

624 625 626 627 628 629 630
#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()" ) );

631 632 633
        if( ( ret = ssl_hw_record_init( ssl, key1, key2, transform->keylen,
                                        transform->iv_enc, transform->iv_dec,
                                        iv_copy_len,
634
                                        mac_enc, mac_dec,
635
                                        transform->maclen ) ) != 0 )
636 637 638 639 640 641 642
        {
            SSL_DEBUG_RET( 1, "ssl_hw_record_init", ret );
            return POLARSSL_ERR_SSL_HW_ACCEL_FAILED;
        }
    }
#endif

643 644
    if( ( ret = cipher_init_ctx( &transform->cipher_ctx_enc,
                                 cipher_info ) ) != 0 )
645
    {
646 647 648
        SSL_DEBUG_RET( 1, "cipher_init_ctx", ret );
        return( ret );
    }
649

650 651 652 653 654 655
    if( ( ret = cipher_init_ctx( &transform->cipher_ctx_dec,
                                 cipher_info ) ) != 0 )
    {
        SSL_DEBUG_RET( 1, "cipher_init_ctx", ret );
        return( ret );
    }
656

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

665 666 667 668 669 670 671 672 673 674 675 676 677
    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 );
    }

#if defined(POLARSSL_CIPHER_MODE_CBC)
    if( cipher_info->mode == POLARSSL_MODE_CBC )
    {
        if( ( ret = cipher_set_padding_mode( &transform->cipher_ctx_enc,
                                             POLARSSL_PADDING_NONE ) ) != 0 )
678
        {
679
            SSL_DEBUG_RET( 1, "cipher_set_padding_mode", ret );
680 681
            return( ret );
        }
682

683 684
        if( ( ret = cipher_set_padding_mode( &transform->cipher_ctx_dec,
                                             POLARSSL_PADDING_NONE ) ) != 0 )
685
        {
686 687
            SSL_DEBUG_RET( 1, "cipher_set_padding_mode", ret );
            return( ret );
688
        }
689
    }
690
#endif /* POLARSSL_CIPHER_MODE_CBC */
691 692 693

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

694 695 696
#if defined(POLARSSL_ZLIB_SUPPORT)
    // Initialize compression
    //
697
    if( session->compression == SSL_COMPRESS_DEFLATE )
698
    {
699 700 701 702 703 704 705 706 707 708 709 710
        if( ssl->compress_buf == NULL )
        {
            SSL_DEBUG_MSG( 3, ( "Allocating compression buffer" ) );
            ssl->compress_buf = polarssl_malloc( SSL_BUFFER_LEN );
            if( ssl->compress_buf == NULL )
            {
                SSL_DEBUG_MSG( 1, ( "malloc(%d bytes) failed",
                                    SSL_BUFFER_LEN ) );
                return( POLARSSL_ERR_SSL_MALLOC_FAILED );
            }
        }

711 712
        SSL_DEBUG_MSG( 3, ( "Initializing zlib states" ) );

713 714
        memset( &transform->ctx_deflate, 0, sizeof( transform->ctx_deflate ) );
        memset( &transform->ctx_inflate, 0, sizeof( transform->ctx_inflate ) );
715

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

725 726 727 728 729
    SSL_DEBUG_MSG( 2, ( "<= derive keys" ) );

    return( 0 );
}

730
#if defined(POLARSSL_SSL_PROTO_SSL3)
731
void ssl_calc_verify_ssl( ssl_context *ssl, unsigned char hash[36] )
732 733 734 735 736 737
{
    md5_context md5;
    sha1_context sha1;
    unsigned char pad_1[48];
    unsigned char pad_2[48];

738
    SSL_DEBUG_MSG( 2, ( "=> calc verify ssl" ) );
739

740 741
    memcpy( &md5 , &ssl->handshake->fin_md5 , sizeof(md5_context)  );
    memcpy( &sha1, &ssl->handshake->fin_sha1, sizeof(sha1_context) );
742

743 744
    memset( pad_1, 0x36, 48 );
    memset( pad_2, 0x5C, 48 );
745

746
    md5_update( &md5, ssl->session_negotiate->master, 48 );
747 748
    md5_update( &md5, pad_1, 48 );
    md5_finish( &md5, hash );
749

750
    md5_starts( &md5 );
751
    md5_update( &md5, ssl->session_negotiate->master, 48 );
752 753 754
    md5_update( &md5, pad_2, 48 );
    md5_update( &md5, hash,  16 );
    md5_finish( &md5, hash );
755

756
    sha1_update( &sha1, ssl->session_negotiate->master, 48 );
757 758 759 760
    sha1_update( &sha1, pad_1, 40 );
    sha1_finish( &sha1, hash + 16 );

    sha1_starts( &sha1 );
761
    sha1_update( &sha1, ssl->session_negotiate->master, 48 );
762 763 764 765 766 767 768 769 770
    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;
}
771
#endif
772

773
#if defined(POLARSSL_SSL_PROTO_TLS1) || defined(POLARSSL_SSL_PROTO_TLS1_1)
774 775 776 777 778 779 780
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" ) );

781 782
    memcpy( &md5 , &ssl->handshake->fin_md5 , sizeof(md5_context)  );
    memcpy( &sha1, &ssl->handshake->fin_sha1, sizeof(sha1_context) );
783

784
     md5_finish( &md5,  hash );
785 786 787 788 789 790 791
    sha1_finish( &sha1, hash + 16 );

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

    return;
}
792
#endif /* POLARSSL_SSL_PROTO_TLS1 || POLARSSL_SSL_PROTO_TLS1_1 */
793

794 795
#if defined(POLARSSL_SSL_PROTO_TLS1_2)
#if defined(POLARSSL_SHA256_C)
796 797
void ssl_calc_verify_tls_sha256( ssl_context *ssl, unsigned char hash[32] )
{
798
    sha256_context sha256;
799 800 801

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

802 803
    memcpy( &sha256, &ssl->handshake->fin_sha256, sizeof(sha256_context) );
    sha256_finish( &sha256, hash );
804 805 806 807 808 809

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

    return;
}
810
#endif /* POLARSSL_SHA256_C */
811

812
#if defined(POLARSSL_SHA512_C)
813 814
void ssl_calc_verify_tls_sha384( ssl_context *ssl, unsigned char hash[48] )
{
815
    sha512_context sha512;
816 817 818

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

819 820
    memcpy( &sha512, &ssl->handshake->fin_sha512, sizeof(sha512_context) );
    sha512_finish( &sha512, hash );
821

822
    SSL_DEBUG_BUF( 3, "calculated verify result", hash, 48 );
823 824 825 826
    SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );

    return;
}
827 828
#endif /* POLARSSL_SHA512_C */
#endif /* POLARSSL_SSL_PROTO_TLS1_2 */
829

830
#if defined(POLARSSL_KEY_EXCHANGE__SOME__PSK_ENABLED)
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
int ssl_psk_derive_premaster( ssl_context *ssl, key_exchange_type_t key_ex )
{
    unsigned char *p = ssl->handshake->premaster;
    unsigned char *end = p + sizeof( ssl->handshake->premaster );

    /*
     * PMS = struct {
     *     opaque other_secret<0..2^16-1>;
     *     opaque psk<0..2^16-1>;
     * };
     * with "other_secret" depending on the particular key exchange
     */
#if defined(POLARSSL_KEY_EXCHANGE_PSK_ENABLED)
    if( key_ex == POLARSSL_KEY_EXCHANGE_PSK )
    {
        if( end - p < 2 + (int) ssl->psk_len )
            return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );

        *(p++) = (unsigned char)( ssl->psk_len >> 8 );
        *(p++) = (unsigned char)( ssl->psk_len      );
        p += ssl->psk_len;
    }
    else
#endif /* POLARSSL_KEY_EXCHANGE_PSK_ENABLED */
855 856 857 858 859 860 861 862 863 864 865 866 867
#if defined(POLARSSL_KEY_EXCHANGE_RSA_PSK_ENABLED)
    if( key_ex == POLARSSL_KEY_EXCHANGE_RSA_PSK )
    {
        /*
         * other_secret already set by the ClientKeyExchange message,
         * and is 48 bytes long
         */
        *p++ = 0;
        *p++ = 48;
        p += 48;
    }
    else
#endif /* POLARSSL_KEY_EXCHANGE_RSA_PKS_ENABLED */
868 869 870
#if defined(POLARSSL_KEY_EXCHANGE_DHE_PSK_ENABLED)
    if( key_ex == POLARSSL_KEY_EXCHANGE_DHE_PSK )
    {
871
        int ret;
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
        size_t len = ssl->handshake->dhm_ctx.len;

        if( end - p < 2 + (int) len )
            return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );

        *(p++) = (unsigned char)( len >> 8 );
        *(p++) = (unsigned char)( len );
        if( ( ret = dhm_calc_secret( &ssl->handshake->dhm_ctx,
                                      p, &len, ssl->f_rng, ssl->p_rng ) ) != 0 )
        {
            SSL_DEBUG_RET( 1, "dhm_calc_secret", ret );
            return( ret );
        }
        p += len;

        SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K  );
    }
    else
#endif /* POLARSSL_KEY_EXCHANGE_DHE_PSK_ENABLED */
#if defined(POLARSSL_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
    if( key_ex == POLARSSL_KEY_EXCHANGE_ECDHE_PSK )
    {
894
        int ret;
895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
        size_t zlen;

        if( ( ret = ecdh_calc_secret( &ssl->handshake->ecdh_ctx, &zlen,
                                       p + 2, end - (p + 2),
                                       ssl->f_rng, ssl->p_rng ) ) != 0 )
        {
            SSL_DEBUG_RET( 1, "ecdh_calc_secret", ret );
            return( ret );
        }

        *(p++) = (unsigned char)( zlen >> 8 );
        *(p++) = (unsigned char)( zlen      );
        p += zlen;

        SSL_DEBUG_MPI( 3, "ECDH: z", &ssl->handshake->ecdh_ctx.z );
    }
    else
#endif /* POLARSSL_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
    {
        SSL_DEBUG_MSG( 1, ( "should never happen" ) );
        return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE );
    }

    /* opaque psk<0..2^16-1>; */
919 920 921
    if( end - p < 2 + (int) ssl->psk_len )
            return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );

922 923 924 925 926 927 928 929 930
    *(p++) = (unsigned char)( ssl->psk_len >> 8 );
    *(p++) = (unsigned char)( ssl->psk_len      );
    memcpy( p, ssl->psk, ssl->psk_len );
    p += ssl->psk_len;

    ssl->handshake->pmslen = p - ssl->handshake->premaster;

    return( 0 );
}
931
#endif /* POLARSSL_KEY_EXCHANGE__SOME__PSK_ENABLED */
932

933
#if defined(POLARSSL_SSL_PROTO_SSL3)
934 935 936
/*
 * SSLv3.0 MAC functions
 */
937 938 939
static void ssl_mac( md_context_t *md_ctx, unsigned char *secret,
                     unsigned char *buf, size_t len,
                     unsigned char *ctr, int type )
940 941 942
{
    unsigned char header[11];
    unsigned char padding[48];
943 944 945
    int padlen = 0;
    int md_size = md_get_size( md_ctx->md_info );
    int md_type = md_get_type( md_ctx->md_info );
946

947 948 949 950 951 952
    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;
953 954
    else if( md_type == POLARSSL_MD_SHA384 )
        padlen = 16;
955 956 957 958 959 960

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

961 962 963 964 965 966 967
    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     );
968

969 970 971 972 973 974
    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          );
975
}
976
#endif /* POLARSSL_SSL_PROTO_SSL3 */
977

978 979
/*
 * Encryption/decryption functions
980
 */
981 982
static int ssl_encrypt_buf( ssl_context *ssl )
{
983
    size_t i;
984 985 986 987

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

    /*
988
     * Add MAC before encrypt, except for GCM
989
     */
990 991 992 993 994
#if defined(POLARSSL_ARC4_C) || defined(POLARSSL_CIPHER_NULL_CIPHER) ||     \
    ( defined(POLARSSL_CIPHER_MODE_CBC) &&                                  \
      ( defined(POLARSSL_AES_C) || defined(POLARSSL_CAMELLIA_C) ) )
    if( ssl->transform_out->cipher_ctx_enc.cipher_info->mode !=
                                                        POLARSSL_MODE_GCM )
995
    {
996 997 998 999 1000 1001 1002 1003 1004
#if defined(POLARSSL_SSL_PROTO_SSL3)
        if( ssl->minor_ver == SSL_MINOR_VERSION_0 )
        {
            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 );
        }
        else
1005 1006
#endif
#if defined(POLARSSL_SSL_PROTO_TLS1) || defined(POLARSSL_SSL_PROTO_TLS1_1) || \
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
        defined(POLARSSL_SSL_PROTO_TLS1_2)
        if( ssl->minor_ver >= SSL_MINOR_VERSION_1 )
        {
            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 );
        }
        else
Paul Bakker's avatar