ssl_srv.c 99 KB
Newer Older
1 2 3
/*
 *  SSLv3/TLSv1 server-side 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
 *  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.
 */

26
#if !defined(POLARSSL_CONFIG_FILE)
27
#include "polarssl/config.h"
28 29 30
#else
#include POLARSSL_CONFIG_FILE
#endif
31

32
#if defined(POLARSSL_SSL_SRV_C)
33

34 35
#include "polarssl/debug.h"
#include "polarssl/ssl.h"
36 37 38
#if defined(POLARSSL_ECP_C)
#include "polarssl/ecp.h"
#endif
39

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

47 48
#include <stdlib.h>
#include <stdio.h>
49 50

#if defined(POLARSSL_HAVE_TIME)
51
#include <time.h>
52
#endif
53

54
#if defined(POLARSSL_SSL_SESSION_TICKETS)
55 56 57 58 59
/* Implementation that should never be optimized out by the compiler */
static void polarssl_zeroize( void *v, size_t n ) {
    volatile unsigned char *p = v; while( n-- ) *p++ = 0;
}

60 61 62 63 64 65 66 67
/*
 * Serialize a session in the following format:
 *  0   .   n-1     session structure, n = sizeof(ssl_session)
 *  n   .   n+2     peer_cert length = m (0 if no certificate)
 *  n+3 .   n+2+m   peer cert ASN.1
 *
 *  Assumes ticket is NULL (always true on server side).
 */
68 69 70
static int ssl_save_session( const ssl_session *session,
                             unsigned char *buf, size_t buf_len,
                             size_t *olen )
71 72
{
    unsigned char *p = buf;
73
    size_t left = buf_len;
74
#if defined(POLARSSL_X509_CRT_PARSE_C)
75
    size_t cert_len;
76
#endif /* POLARSSL_X509_CRT_PARSE_C */
77

78 79 80
    if( left < sizeof( ssl_session ) )
        return( -1 );

81 82
    memcpy( p, session, sizeof( ssl_session ) );
    p += sizeof( ssl_session );
83
    left -= sizeof( ssl_session );
84

85
#if defined(POLARSSL_X509_CRT_PARSE_C)
86 87 88 89 90
    if( session->peer_cert == NULL )
        cert_len = 0;
    else
        cert_len = session->peer_cert->raw.len;

91 92 93
    if( left < 3 + cert_len )
        return( -1 );

94 95 96 97 98 99 100 101
    *p++ = (unsigned char)( cert_len >> 16 & 0xFF );
    *p++ = (unsigned char)( cert_len >>  8 & 0xFF );
    *p++ = (unsigned char)( cert_len       & 0xFF );

    if( session->peer_cert != NULL )
        memcpy( p, session->peer_cert->raw.p, cert_len );

    p += cert_len;
102
#endif /* POLARSSL_X509_CRT_PARSE_C */
103 104

    *olen = p - buf;
105 106

    return( 0 );
107 108 109 110 111 112 113 114 115 116
}

/*
 * Unserialise session, see ssl_save_session()
 */
static int ssl_load_session( ssl_session *session,
                             const unsigned char *buf, size_t len )
{
    const unsigned char *p = buf;
    const unsigned char * const end = buf + len;
117
#if defined(POLARSSL_X509_CRT_PARSE_C)
118
    size_t cert_len;
119
#endif /* POLARSSL_X509_CRT_PARSE_C */
120 121 122 123 124 125 126

    if( p + sizeof( ssl_session ) > end )
        return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );

    memcpy( session, p, sizeof( ssl_session ) );
    p += sizeof( ssl_session );

127
#if defined(POLARSSL_X509_CRT_PARSE_C)
128 129 130 131 132 133 134 135 136 137 138 139
    if( p + 3 > end )
        return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );

    cert_len = ( p[0] << 16 ) | ( p[1] << 8 ) | p[2];
    p += 3;

    if( cert_len == 0 )
    {
        session->peer_cert = NULL;
    }
    else
    {
140 141
        int ret;

142 143 144
        if( p + cert_len > end )
            return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );

145
        session->peer_cert = polarssl_malloc( sizeof( x509_crt ) );
146 147 148 149

        if( session->peer_cert == NULL )
            return( POLARSSL_ERR_SSL_MALLOC_FAILED );

150
        x509_crt_init( session->peer_cert );
151

152 153
        if( ( ret = x509_crt_parse_der( session->peer_cert,
                                        p, cert_len ) ) != 0 )
154
        {
155
            x509_crt_free( session->peer_cert );
156 157 158 159 160 161 162
            polarssl_free( session->peer_cert );
            session->peer_cert = NULL;
            return( ret );
        }

        p += cert_len;
    }
163
#endif /* POLARSSL_X509_CRT_PARSE_C */
164 165 166 167 168 169 170

    if( p != end )
        return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );

    return( 0 );
}

171 172 173 174 175 176 177 178 179 180 181 182 183 184
/*
 * Create session ticket, secured as recommended in RFC 5077 section 4:
 *
 *    struct {
 *        opaque key_name[16];
 *        opaque iv[16];
 *        opaque encrypted_state<0..2^16-1>;
 *        opaque mac[32];
 *    } ticket;
 *
 * (the internal state structure differs, however).
 */
static int ssl_write_ticket( ssl_context *ssl, size_t *tlen )
{
185
    int ret;
186 187
    unsigned char * const start = ssl->out_msg + 10;
    unsigned char *p = start;
188 189 190
    unsigned char *state;
    unsigned char iv[16];
    size_t clear_len, enc_len, pad_len, i;
191

192 193
    *tlen = 0;

194 195 196
    if( ssl->ticket_keys == NULL )
        return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );

197
    /* Write key name */
198
    memcpy( p, ssl->ticket_keys->key_name, 16 );
199 200
    p += 16;

201 202 203 204
    /* Generate and write IV (with a copy for aes_crypt) */
    if( ( ret = ssl->f_rng( ssl->p_rng, p, 16 ) ) != 0 )
        return( ret );
    memcpy( iv, p, 16 );
205 206
    p += 16;

207 208 209 210 211 212
    /*
     * Dump session state
     *
     * After the session state itself, we still need room for 16 bytes of
     * padding and 32 bytes of MAC, so there's only so much room left
     */
213
    state = p + 2;
214
    if( ssl_save_session( ssl->session_negotiate, state,
215
                          SSL_MAX_CONTENT_LEN - ( state - ssl->out_ctr ) - 48,
216 217 218 219
                          &clear_len ) != 0 )
    {
        return( POLARSSL_ERR_SSL_CERTIFICATE_TOO_LARGE );
    }
220
    SSL_DEBUG_BUF( 3, "session ticket cleartext", state, clear_len );
221

222 223 224 225 226
    /* Apply PKCS padding */
    pad_len = 16 - clear_len % 16;
    enc_len = clear_len + pad_len;
    for( i = clear_len; i < enc_len; i++ )
        state[i] = (unsigned char) pad_len;
227

228 229 230 231 232 233 234 235 236 237 238
    /* Encrypt */
    if( ( ret = aes_crypt_cbc( &ssl->ticket_keys->enc, AES_ENCRYPT,
                               enc_len, iv, state, state ) ) != 0 )
    {
        return( ret );
    }

    /* Write length */
    *p++ = (unsigned char)( ( enc_len >> 8 ) & 0xFF );
    *p++ = (unsigned char)( ( enc_len      ) & 0xFF );
    p = state + enc_len;
239

240 241
    /* Compute and write MAC( key_name + iv + enc_state_len + enc_state ) */
    sha256_hmac( ssl->ticket_keys->mac_key, 16, start, p - start, p, 0 );
242 243 244 245
    p += 32;

    *tlen = p - start;

246
    SSL_DEBUG_BUF( 3, "session ticket structure", start, *tlen );
247 248 249 250 251 252 253 254

    return( 0 );
}

/*
 * Load session ticket (see ssl_write_ticket for structure)
 */
static int ssl_parse_ticket( ssl_context *ssl,
255
                             unsigned char *buf,
256 257 258 259
                             size_t len )
{
    int ret;
    ssl_session session;
260 261 262 263 264
    unsigned char *key_name = buf;
    unsigned char *iv = buf + 16;
    unsigned char *enc_len_p = iv + 16;
    unsigned char *ticket = enc_len_p + 2;
    unsigned char *mac;
265
    unsigned char computed_mac[32];
266
    size_t enc_len, clear_len, i;
267
    unsigned char pad_len, diff;
268 269

    SSL_DEBUG_BUF( 3, "session ticket structure", buf, len );
270

271
    if( len < 34 || ssl->ticket_keys == NULL )
272 273 274 275 276 277 278 279
        return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );

    enc_len = ( enc_len_p[0] << 8 ) | enc_len_p[1];
    mac = ticket + enc_len;

    if( len != enc_len + 66 )
        return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );

280 281 282 283 284
    /* Check name, in constant time though it's not a big secret */
    diff = 0;
    for( i = 0; i < 16; i++ )
        diff |= key_name[i] ^ ssl->ticket_keys->key_name[i];
    /* don't return yet, check the MAC anyway */
285

286
    /* Check mac, with constant-time buffer comparison */
287 288
    sha256_hmac( ssl->ticket_keys->mac_key, 16, buf, len - 32,
                 computed_mac, 0 );
289

290
    for( i = 0; i < 32; i++ )
291 292 293 294 295 296
        diff |= mac[i] ^ computed_mac[i];

    /* Now return if ticket is not authentic, since we want to avoid
     * decrypting arbitrary attacker-chosen data */
    if( diff != 0 )
        return( POLARSSL_ERR_SSL_INVALID_MAC );
297

298 299 300 301 302 303
    /* Decrypt */
    if( ( ret = aes_crypt_cbc( &ssl->ticket_keys->dec, AES_DECRYPT,
                               enc_len, iv, ticket, ticket ) ) != 0 )
    {
        return( ret );
    }
304

305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
    /* Check PKCS padding */
    pad_len = ticket[enc_len - 1];

    ret = 0;
    for( i = 2; i < pad_len; i++ )
        if( ticket[enc_len - i] != pad_len )
            ret = POLARSSL_ERR_SSL_BAD_INPUT_DATA;
    if( ret != 0 )
        return( ret );

    clear_len = enc_len - pad_len;

    SSL_DEBUG_BUF( 3, "session ticket cleartext", ticket, clear_len );

    /* Actually load session */
320 321 322
    if( ( ret = ssl_load_session( &session, ticket, clear_len ) ) != 0 )
    {
        SSL_DEBUG_MSG( 1, ( "failed to parse ticket content" ) );
323
        ssl_session_free( &session );
324 325 326
        return( ret );
    }

327 328 329 330 331
#if defined(POLARSSL_HAVE_TIME)
    /* Check if still valid */
    if( (int) ( time( NULL) - session.start ) > ssl->ticket_lifetime )
    {
        SSL_DEBUG_MSG( 1, ( "session ticket expired" ) );
332
        ssl_session_free( &session );
333 334 335 336
        return( POLARSSL_ERR_SSL_SESSION_TICKET_EXPIRED );
    }
#endif

337 338 339 340 341 342 343 344 345
    /*
     * Keep the session ID sent by the client, since we MUST send it back to
     * inform him we're accepting the ticket  (RFC 5077 section 3.4)
     */
    session.length = ssl->session_negotiate->length;
    memcpy( &session.id, ssl->session_negotiate->id, session.length );

    ssl_session_free( ssl->session_negotiate );
    memcpy( ssl->session_negotiate, &session, sizeof( ssl_session ) );
346 347

    /* Zeroize instead of free as we copied the content */
348
    polarssl_zeroize( &session, sizeof( ssl_session ) );
349 350 351

    return( 0 );
}
352
#endif /* POLARSSL_SSL_SESSION_TICKETS */
353

354
#if defined(POLARSSL_SSL_SERVER_NAME_INDICATION)
355
/*
356 357
 * Wrapper around f_sni, allowing use of ssl_set_own_cert() but
 * making it act on ssl->hanshake->sni_key_cert instead.
358 359 360 361 362 363 364 365 366
 */
static int ssl_sni_wrapper( ssl_context *ssl,
                            const unsigned char* name, size_t len )
{
    int ret;
    ssl_key_cert *key_cert_ori = ssl->key_cert;

    ssl->key_cert = NULL;
    ret = ssl->f_sni( ssl->p_sni, ssl, name, len );
367
    ssl->handshake->sni_key_cert = ssl->key_cert;
368 369 370 371 372 373

    ssl->key_cert = key_cert_ori;

    return( ret );
}

374
static int ssl_parse_servername_ext( ssl_context *ssl,
375
                                     const unsigned char *buf,
376 377 378 379
                                     size_t len )
{
    int ret;
    size_t servername_list_size, hostname_len;
380
    const unsigned char *p;
381

Manuel Pégourié-Gonnard's avatar
Manuel Pégourié-Gonnard committed
382 383
    SSL_DEBUG_MSG( 3, ( "parse ServerName extension" ) );

384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
    servername_list_size = ( ( buf[0] << 8 ) | ( buf[1] ) );
    if( servername_list_size + 2 != len )
    {
        SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
        return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );
    }

    p = buf + 2;
    while( servername_list_size > 0 )
    {
        hostname_len = ( ( p[1] << 8 ) | p[2] );
        if( hostname_len + 3 > servername_list_size )
        {
            SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
            return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );
        }

        if( p[0] == TLS_EXT_SERVERNAME_HOSTNAME )
        {
403
            ret = ssl_sni_wrapper( ssl, p + 3, hostname_len );
404 405
            if( ret != 0 )
            {
Manuel Pégourié-Gonnard's avatar
Manuel Pégourié-Gonnard committed
406
                SSL_DEBUG_RET( 1, "ssl_sni_wrapper", ret );
407 408 409 410
                ssl_send_alert_message( ssl, SSL_ALERT_LEVEL_FATAL,
                        SSL_ALERT_MSG_UNRECOGNIZED_NAME );
                return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );
            }
411
            return( 0 );
412 413 414
        }

        servername_list_size -= hostname_len + 3;
415 416 417 418 419 420 421
        p += hostname_len + 3;
    }

    if( servername_list_size != 0 )
    {
        SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
        return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );
422 423 424 425
    }

    return( 0 );
}
426
#endif /* POLARSSL_SSL_SERVER_NAME_INDICATION */
427

428
static int ssl_parse_renegotiation_info( ssl_context *ssl,
429
                                         const unsigned char *buf,
430 431
                                         size_t len )
{
432 433
    int ret;

434 435 436 437 438
    if( ssl->renegotiation == SSL_INITIAL_HANDSHAKE )
    {
        if( len != 1 || buf[0] != 0x0 )
        {
            SSL_DEBUG_MSG( 1, ( "non-zero length renegotiated connection field" ) );
439 440 441 442

            if( ( ret = ssl_send_fatal_handshake_failure( ssl ) ) != 0 )
                return( ret );

443 444 445 446 447 448 449
            return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );
        }

        ssl->secure_renegotiation = SSL_SECURE_RENEGOTIATION;
    }
    else
    {
450
        /* Check verify-data in constant-time. The length OTOH is no secret */
451 452
        if( len    != 1 + ssl->verify_data_len ||
            buf[0] !=     ssl->verify_data_len ||
453 454
            safer_memcmp( buf + 1, ssl->peer_verify_data,
                          ssl->verify_data_len ) != 0 )
455 456
        {
            SSL_DEBUG_MSG( 1, ( "non-matching renegotiated connection field" ) );
457 458 459 460

            if( ( ret = ssl_send_fatal_handshake_failure( ssl ) ) != 0 )
                return( ret );

461 462 463 464 465 466 467
            return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );
        }
    }

    return( 0 );
}

468
#if defined(POLARSSL_SSL_PROTO_TLS1_2)
469 470 471 472 473 474
static int ssl_parse_signature_algorithms_ext( ssl_context *ssl,
                                               const unsigned char *buf,
                                               size_t len )
{
    size_t sig_alg_list_size;
    const unsigned char *p;
475 476 477
    const unsigned char *end = buf + len;
    const int *md_cur;

478 479 480

    sig_alg_list_size = ( ( buf[0] << 8 ) | ( buf[1] ) );
    if( sig_alg_list_size + 2 != len ||
481
        sig_alg_list_size % 2 != 0 )
482 483 484 485 486
    {
        SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
        return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );
    }

487 488 489 490 491 492 493 494 495 496
    /*
     * For now, ignore the SignatureAlgorithm part and rely on offered
     * ciphersuites only for that part. To be fixed later.
     *
     * So, just look at the HashAlgorithm part.
     */
    for( md_cur = md_list(); *md_cur != POLARSSL_MD_NONE; md_cur++ ) {
        for( p = buf + 2; p < end; p += 2 ) {
            if( *md_cur == (int) ssl_md_alg_from_hash( p[0] ) ) {
                ssl->handshake->sig_alg = p[0];
497
                goto have_sig_alg;
498
            }
499 500 501
        }
    }

502 503 504 505 506
    /* Some key echanges do not need signatures at all */
    SSL_DEBUG_MSG( 3, ( "no signature_algorithm in common" ) );
    return( 0 );

have_sig_alg:
507 508 509 510 511
    SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext: %d",
                   ssl->handshake->sig_alg ) );

    return( 0 );
}
512
#endif /* POLARSSL_SSL_PROTO_TLS1_2 */
513

514
#if defined(POLARSSL_ECDH_C) || defined(POLARSSL_ECDSA_C)
515 516 517
static int ssl_parse_supported_elliptic_curves( ssl_context *ssl,
                                                const unsigned char *buf,
                                                size_t len )
518
{
519
    size_t list_size, our_size;
520
    const unsigned char *p;
521
    const ecp_curve_info *curve_info, **curves;
522 523 524 525 526 527 528 529 530

    list_size = ( ( buf[0] << 8 ) | ( buf[1] ) );
    if( list_size + 2 != len ||
        list_size % 2 != 0 )
    {
        SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
        return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );
    }

531
    /* Don't allow our peer to make us allocate too much memory,
532 533 534 535 536 537 538 539
     * and leave room for a final 0 */
    our_size = list_size / 2 + 1;
    if( our_size > POLARSSL_ECP_DP_MAX )
        our_size = POLARSSL_ECP_DP_MAX;

    if( ( curves = polarssl_malloc( our_size * sizeof( *curves ) ) ) == NULL )
        return( POLARSSL_ERR_SSL_MALLOC_FAILED );

540
    /* explicit void pointer cast for buggy MS compiler */
541
    memset( (void *) curves, 0, our_size * sizeof( *curves ) );
542 543
    ssl->handshake->curves = curves;

544
    p = buf + 2;
545
    while( list_size > 0 && our_size > 1 )
546
    {
547
        curve_info = ecp_curve_info_from_tls_id( ( p[0] << 8 ) | p[1] );
548

549
        if( curve_info != NULL )
550
        {
551 552
            *curves++ = curve_info;
            our_size--;
553
        }
554 555 556 557 558 559 560 561

        list_size -= 2;
        p += 2;
    }

    return( 0 );
}

562 563 564
static int ssl_parse_supported_point_formats( ssl_context *ssl,
                                              const unsigned char *buf,
                                              size_t len )
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
{
    size_t list_size;
    const unsigned char *p;

    list_size = buf[0];
    if( list_size + 1 != len )
    {
        SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
        return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );
    }

    p = buf + 2;
    while( list_size > 0 )
    {
        if( p[0] == POLARSSL_ECP_PF_UNCOMPRESSED ||
            p[0] == POLARSSL_ECP_PF_COMPRESSED )
        {
582
            ssl->handshake->ecdh_ctx.point_format = p[0];
583
            SSL_DEBUG_MSG( 4, ( "point format selected: %d", p[0] ) );
584 585 586 587 588 589 590 591 592
            return( 0 );
        }

        list_size--;
        p++;
    }

    return( 0 );
}
593
#endif /* POLARSSL_ECDH_C || POLARSSL_ECDSA_C */
594

595
#if defined(POLARSSL_SSL_MAX_FRAGMENT_LENGTH)
596 597 598 599
static int ssl_parse_max_fragment_length_ext( ssl_context *ssl,
                                              const unsigned char *buf,
                                              size_t len )
{
600
    if( len != 1 || buf[0] >= SSL_MAX_FRAG_LEN_INVALID )
601 602 603 604 605
    {
        SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
        return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );
    }

606 607
    ssl->session_negotiate->mfl_code = buf[0];

608 609
    return( 0 );
}
610
#endif /* POLARSSL_SSL_MAX_FRAGMENT_LENGTH */
611

612
#if defined(POLARSSL_SSL_TRUNCATED_HMAC)
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
static int ssl_parse_truncated_hmac_ext( ssl_context *ssl,
                                         const unsigned char *buf,
                                         size_t len )
{
    if( len != 0 )
    {
        SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
        return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );
    }

    ((void) buf);

    ssl->session_negotiate->trunc_hmac = SSL_TRUNC_HMAC_ENABLED;

    return( 0 );
}
629
#endif /* POLARSSL_SSL_TRUNCATED_HMAC */
630

631
#if defined(POLARSSL_SSL_SESSION_TICKETS)
632
static int ssl_parse_session_ticket_ext( ssl_context *ssl,
633
                                         unsigned char *buf,
634 635
                                         size_t len )
{
636 637
    int ret;

638 639 640
    if( ssl->session_tickets == SSL_SESSION_TICKETS_DISABLED )
        return( 0 );

641
    /* Remember the client asked us to send a new ticket */
642 643
    ssl->handshake->new_session_ticket = 1;

644 645
    SSL_DEBUG_MSG( 3, ( "ticket length: %d", len ) );

646 647 648
    if( len == 0 )
        return( 0 );

649 650 651 652 653
    if( ssl->renegotiation != SSL_INITIAL_HANDSHAKE )
    {
        SSL_DEBUG_MSG( 3, ( "ticket rejected: renegotiating" ) );
        return( 0 );
    }
654 655 656 657

    /*
     * Failures are ok: just ignore the ticket and proceed.
     */
658 659 660
    if( ( ret = ssl_parse_ticket( ssl, buf, len ) ) != 0 )
    {
        SSL_DEBUG_RET( 1, "ssl_parse_ticket", ret );
661
        return( 0 );
662
    }
663 664 665 666

    SSL_DEBUG_MSG( 3, ( "session successfully restored from ticket" ) );

    ssl->handshake->resume = 1;
667

668 669 670
    /* Don't send a new ticket after all, this one is OK */
    ssl->handshake->new_session_ticket = 0;

671 672
    return( 0 );
}
673
#endif /* POLARSSL_SSL_SESSION_TICKETS */
674

675 676
#if defined(POLARSSL_SSL_ALPN)
static int ssl_parse_alpn_ext( ssl_context *ssl,
Manuel Pégourié-Gonnard's avatar
Manuel Pégourié-Gonnard committed
677
                               const unsigned char *buf, size_t len )
678
{
679
    size_t list_len, cur_len, ours_len;
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
    const unsigned char *theirs, *start, *end;
    const char **ours;

    /* If ALPN not configured, just ignore the extension */
    if( ssl->alpn_list == NULL )
        return( 0 );

    /*
     * opaque ProtocolName<1..2^8-1>;
     *
     * struct {
     *     ProtocolName protocol_name_list<2..2^16-1>
     * } ProtocolNameList;
     */

    /* Min length is 2 (list_len) + 1 (name_len) + 1 (name) */
    if( len < 4 )
        return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );

    list_len = ( buf[0] << 8 ) | buf[1];
    if( list_len != len - 2 )
        return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );

    /*
     * Use our order of preference
     */
    start = buf + 2;
    end = buf + len;
    for( ours = ssl->alpn_list; *ours != NULL; ours++ )
    {
710
        ours_len = strlen( *ours );
711 712 713 714 715 716 717 718 719 720 721 722
        for( theirs = start; theirs != end; theirs += cur_len )
        {
            /* If the list is well formed, we should get equality first */
            if( theirs > end )
                return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );

            cur_len = *theirs++;

            /* Empty strings MUST NOT be included */
            if( cur_len == 0 )
                return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );

723
            if( cur_len == ours_len &&
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
                memcmp( theirs, *ours, cur_len ) == 0 )
            {
                ssl->alpn_chosen = *ours;
                return( 0 );
            }
        }
    }

    /* If we get there, no match was found */
    ssl_send_alert_message( ssl, SSL_ALERT_LEVEL_FATAL,
                            SSL_ALERT_MSG_NO_APPLICATION_PROTOCOL );
    return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
#endif /* POLARSSL_SSL_ALPN */

739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
/*
 * Auxiliary functions for ServerHello parsing and related actions
 */

#if defined(POLARSSL_X509_CRT_PARSE_C)
/*
 * Return 1 if the given EC key uses the given curve, 0 otherwise
 */
#if defined(POLARSSL_ECDSA_C)
static int ssl_key_matches_curves( pk_context *pk,
                                   const ecp_curve_info **curves )
{
    const ecp_curve_info **crv = curves;
    ecp_group_id grp_id = pk_ec( *pk )->grp.id;

    while( *crv != NULL )
    {
        if( (*crv)->grp_id == grp_id )
            return( 1 );
        crv++;
    }

    return( 0 );
}
#endif /* POLARSSL_ECDSA_C */

/*
 * Try picking a certificate for this ciphersuite,
 * return 0 on success and -1 on failure.
 */
static int ssl_pick_cert( ssl_context *ssl,
                          const ssl_ciphersuite_t * ciphersuite_info )
{
    ssl_key_cert *cur, *list;
    pk_type_t pk_alg = ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info );

#if defined(POLARSSL_SSL_SERVER_NAME_INDICATION)
    if( ssl->handshake->sni_key_cert != NULL )
        list = ssl->handshake->sni_key_cert;
    else
#endif
        list = ssl->handshake->key_cert;

    if( pk_alg == POLARSSL_PK_NONE )
        return( 0 );

    for( cur = list; cur != NULL; cur = cur->next )
    {
        if( ! pk_can_do( cur->key, pk_alg ) )
            continue;

790 791 792 793 794 795 796 797 798 799 800 801 802 803
        /*
         * This avoids sending the client a cert it'll reject based on
         * keyUsage or other extensions.
         *
         * It also allows the user to provision different certificates for
         * different uses based on keyUsage, eg if they want to avoid signing
         * and decrypting with the same RSA key.
         */
        if( ssl_check_cert_usage( cur->cert, ciphersuite_info,
                                  SSL_IS_SERVER ) != 0 )
        {
            continue;
        }

804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
#if defined(POLARSSL_ECDSA_C)
        if( pk_alg == POLARSSL_PK_ECDSA )
        {
            if( ssl_key_matches_curves( cur->key, ssl->handshake->curves ) )
                break;
        }
        else
#endif
            break;
    }

    if( cur == NULL )
        return( -1 );

    ssl->handshake->key_cert = cur;
    return( 0 );
}
#endif /* POLARSSL_X509_CRT_PARSE_C */

/*
 * Check if a given ciphersuite is suitable for use with our config/keys/etc
 * Sets ciphersuite_info only if the suite matches.
 */
static int ssl_ciphersuite_match( ssl_context *ssl, int suite_id,
                                  const ssl_ciphersuite_t **ciphersuite_info )
{
    const ssl_ciphersuite_t *suite_info;

    suite_info = ssl_ciphersuite_from_id( suite_id );
    if( suite_info == NULL )
    {
        SSL_DEBUG_MSG( 1, ( "ciphersuite info for %04x not found", suite_id ) );
        return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
    }

    if( suite_info->min_minor_ver > ssl->minor_ver ||
        suite_info->max_minor_ver < ssl->minor_ver )
        return( 0 );

#if defined(POLARSSL_ECDH_C) || defined(POLARSSL_ECDSA_C)
    if( ssl_ciphersuite_uses_ec( suite_info ) &&
        ( ssl->handshake->curves == NULL ||
          ssl->handshake->curves[0] == NULL ) )
        return( 0 );
#endif

#if defined(POLARSSL_KEY_EXCHANGE__SOME__PSK_ENABLED)
    /* If the ciphersuite requires a pre-shared key and we don't
     * have one, skip it now rather than failing later */
    if( ssl_ciphersuite_uses_psk( suite_info ) &&
        ssl->f_psk == NULL &&
        ( ssl->psk == NULL || ssl->psk_identity == NULL ||
          ssl->psk_identity_len == 0 || ssl->psk_len == 0 ) )
        return( 0 );
#endif

#if defined(POLARSSL_X509_CRT_PARSE_C)
    /*
     * Final check: if ciphersuite requires us to have a
     * certificate/key of a particular type:
     * - select the appropriate certificate if we have one, or
     * - try the next ciphersuite if we don't
     * This must be done last since we modify the key_cert list.
     */
    if( ssl_pick_cert( ssl, suite_info ) != 0 )
        return( 0 );
#endif

    *ciphersuite_info = suite_info;
    return( 0 );
}

876 877 878 879 880 881 882 883
#if defined(POLARSSL_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO)
static int ssl_parse_client_hello_v2( ssl_context *ssl )
{
    int ret;
    unsigned int i, j;
    size_t n;
    unsigned int ciph_len, sess_len, chal_len;
    unsigned char *buf, *p;
884
    const int *ciphersuites;
885
    const ssl_ciphersuite_t *ciphersuite_info;
886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935

    SSL_DEBUG_MSG( 2, ( "=> parse client hello v2" ) );

    if( ssl->renegotiation != SSL_INITIAL_HANDSHAKE )
    {
        SSL_DEBUG_MSG( 1, ( "client hello v2 illegal for renegotiation" ) );

        if( ( ret = ssl_send_fatal_handshake_failure( ssl ) ) != 0 )
            return( ret );

        return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );
    }

    buf = ssl->in_hdr;

    SSL_DEBUG_BUF( 4, "record header", buf, 5 );

    SSL_DEBUG_MSG( 3, ( "client hello v2, message type: %d",
                   buf[2] ) );
    SSL_DEBUG_MSG( 3, ( "client hello v2, message len.: %d",
                   ( ( buf[0] & 0x7F ) << 8 ) | buf[1] ) );
    SSL_DEBUG_MSG( 3, ( "client hello v2, max. version: [%d:%d]",
                   buf[3], buf[4] ) );

    /*
     * SSLv2 Client Hello
     *
     * Record layer:
     *     0  .   1   message length
     *
     * SSL layer:
     *     2  .   2   message type
     *     3  .   4   protocol version
     */
    if( buf[2] != SSL_HS_CLIENT_HELLO ||
        buf[3] != SSL_MAJOR_VERSION_3 )
    {
        SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
        return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );
    }

    n = ( ( buf[0] << 8 ) | buf[1] ) & 0x7FFF;

    if( n < 17 || n > 512 )
    {
        SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
        return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );
    }

    ssl->major_ver = SSL_MAJOR_VERSION_3;
936 937
    ssl->minor_ver = ( buf[4] <= ssl->max_minor_ver )
                     ? buf[4]  : ssl->max_minor_ver;
938 939 940 941

    if( ssl->minor_ver < ssl->min_minor_ver )
    {
        SSL_DEBUG_MSG( 1, ( "client only supports ssl smaller than minimum"
942 943
                            " [%d:%d] < [%d:%d]",
                            ssl->major_ver, ssl->minor_ver,
944 945 946 947 948 949 950
                            ssl->min_major_ver, ssl->min_minor_ver ) );

        ssl_send_alert_message( ssl, SSL_ALERT_LEVEL_FATAL,
                                     SSL_ALERT_MSG_PROTOCOL_VERSION );
        return( POLARSSL_ERR_SSL_BAD_HS_PROTOCOL_VERSION );
    }

951 952
    ssl->handshake->max_major_ver = buf[3];
    ssl->handshake->max_minor_ver = buf[4];
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017

    if( ( ret = ssl_fetch_input( ssl, 2 + n ) ) != 0 )
    {
        SSL_DEBUG_RET( 1, "ssl_fetch_input", ret );
        return( ret );
    }

    ssl->handshake->update_checksum( ssl, buf + 2, n );

    buf = ssl->in_msg;
    n = ssl->in_left - 5;

    /*
     *    0  .   1   ciphersuitelist length
     *    2  .   3   session id length
     *    4  .   5   challenge length
     *    6  .  ..   ciphersuitelist
     *   ..  .  ..   session id
     *   ..  .  ..   challenge
     */
    SSL_DEBUG_BUF( 4, "record contents", buf, n );

    ciph_len = ( buf[0] << 8 ) | buf[1];
    sess_len = ( buf[2] << 8 ) | buf[3];
    chal_len = ( buf[4] << 8 ) | buf[5];

    SSL_DEBUG_MSG( 3, ( "ciph_len: %d, sess_len: %d, chal_len: %d",
                   ciph_len, sess_len, chal_len ) );

    /*
     * Make sure each parameter length is valid
     */
    if( ciph_len < 3 || ( ciph_len % 3 ) != 0 )
    {
        SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
        return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );
    }

    if( sess_len > 32 )
    {
        SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
        return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );
    }

    if( chal_len < 8 || chal_len > 32 )
    {
        SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
        return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );
    }

    if( n != 6 + ciph_len + sess_len + chal_len )
    {
        SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
        return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );
    }

    SSL_DEBUG_BUF( 3, "client hello, ciphersuitelist",
                   buf + 6, ciph_len );
    SSL_DEBUG_BUF( 3, "client hello, session id",
                   buf + 6 + ciph_len, sess_len );
    SSL_DEBUG_BUF( 3, "client hello, challenge",
                   buf + 6 + ciph_len + sess_len, chal_len );

    p = buf + 6 + ciph_len;
    ssl->session_negotiate->length = sess_len;
1018 1019
    memset( ssl->session_negotiate->id, 0,
            sizeof( ssl->session_negotiate->id ) );
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
    memcpy( ssl->session_negotiate->id, p, ssl->session_negotiate->length );

    p += sess_len;
    memset( ssl->handshake->randbytes, 0, 64 );
    memcpy( ssl->handshake->randbytes + 32 - chal_len, p, chal_len );

    /*
     * Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV
     */
    for( i = 0, p = buf + 6; i < ciph_len; i += 3, p += 3 )
    {
        if( p[0] == 0 && p[1] == 0 && p[2] == SSL_EMPTY_RENEGOTIATION_INFO )
        {
            SSL_DEBUG_MSG( 3, ( "received TLS_EMPTY_RENEGOTIATION_INFO " ) );
            if( ssl->renegotiation == SSL_RENEGOTIATION )
            {
                SSL_DEBUG_MSG( 1, ( "received RENEGOTIATION SCSV during renegotiation" ) );

                if( ( ret = ssl_send_fatal_handshake_failure( ssl ) ) != 0 )
                    return( ret );

                return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );
            }
            ssl->secure_renegotiation = SSL_SECURE_RENEGOTIATION;
            break;
        }
    }

1048
    ciphersuites = ssl->ciphersuite_list[ssl->minor_ver];
1049
    ciphersuite_info = NULL;
1050 1051 1052 1053 1054
#if defined(POLARSSL_SSL_SRV_RESPECT_CLIENT_PREFERENCE)
    for( j = 0, p = buf + 6; j < ciph_len; j += 3, p += 3 )
    {
        for( i = 0; ciphersuites[i] != 0; i++ )
#else
1055
    for( i = 0; ciphersuites[i] != 0; i++ )
1056 1057
    {
        for( j = 0, p = buf + 6; j < ciph_len; j += 3, p += 3 )
1058
#endif
1059
        {
1060 1061 1062 1063
            if( p[0] != 0 ||
                p[1] != ( ( ciphersuites[i] >> 8 ) & 0xFF ) ||
                p[2] != ( ( ciphersuites[i]      ) & 0xFF ) )
                continue;
1064

1065 1066 1067
            if( ( ret = ssl_ciphersuite_match( ssl, ciphersuites[i],
                                               &ciphersuite_info ) ) != 0 )
                return( ret );
1068

1069
            if( ciphersuite_info != NULL )
1070 1071 1072 1073 1074 1075 1076 1077 1078
                goto have_ciphersuite_v2;
        }
    }

    SSL_DEBUG_MSG( 1, ( "got no ciphersuites in common" ) );

    return( POLARSSL_ERR_SSL_NO_CIPHER_CHOSEN );

have_ciphersuite_v2:
1079
    ssl->session_negotiate->ciphersuite = ciphersuites[i];
1080
    ssl->transform_negotiate->ciphersuite_info = ciphersuite_info;
1081
    ssl_optimize_checksum( ssl, ssl->transform_negotiate->ciphersuite_info );
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105

    /*
     * SSLv2 Client Hello relevant renegotiation security checks
     */
    if( ssl->secure_renegotiation == SSL_LEGACY_RENEGOTIATION &&
        ssl->allow_legacy_renegotiation == SSL_LEGACY_BREAK_HANDSHAKE )
    {
        SSL_DEBUG_MSG( 1, ( "legacy renegotiation, breaking off handshake" ) );

        if( ( ret = ssl_send_fatal_handshake_failure( ssl ) ) != 0 )
            return( ret );

        return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );
    }

    ssl->in_left = 0;
    ssl->state++;

    SSL_DEBUG_MSG( 2, ( "<= parse client hello v2" ) );

    return( 0 );
}
#endif /* POLARSSL_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO */

1106 1107
static int ssl_parse_client_hello( ssl_context *ssl )
{
1108 1109 1110 1111
    int ret;
    unsigned int i, j;
    size_t n;
    unsigned int ciph_len, sess_len;
1112
    unsigned int comp_len;
1113 1114
    unsigned int ext_len = 0;
    unsigned char *buf, *p, *ext;
1115 1116
    int renegotiation_info_seen = 0;
    int handshake_failure = 0;
1117
    const int *ciphersuites;
1118
    const ssl_ciphersuite_t *ciphersuite_info;
1119 1120 1121

    SSL_DEBUG_MSG( 2, ( "=> parse client hello" ) );

1122 1123
    if( ssl->renegotiation == SSL_INITIAL_HANDSHAKE &&
        ( ret = ssl_fetch_input( ssl, 5 ) ) != 0 )
1124 1125 1126 1127 1128 1129 1130
    {
        SSL_DEBUG_RET( 1, "ssl_fetch_input", ret );
        return( ret );
    }

    buf = ssl->in_hdr;

1131 1132 1133 1134 1135
#if defined(POLARSSL_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO)
    if( ( buf[0] & 0x80 ) != 0 )
        return ssl_parse_client_hello_v2( ssl );
#endif

1136
    SSL_DEBUG_BUF( 4, "record header", buf, 5 );
1137

1138 1139 1140 1141 1142 1143
    SSL_DEBUG_MSG( 3, ( "client hello v3, message type: %d",
                   buf[0] ) );
    SSL_DEBUG_MSG( 3, ( "client hello v3, message len.: %d",
                   ( buf[3] << 8 ) | buf[4] ) );
    SSL_DEBUG_MSG( 3, ( "client hello v3, protocol ver: [%d:%d]",
                   buf[1], buf[2] ) );
1144

1145
    /*
1146
     * SSLv3/TLS Client Hello
1147 1148 1149 1150 1151 1152
     *
     * Record layer:
     *     0  .   0   message type
     *     1  .   2   protocol version
     *     3  .   4   message length
     */
1153 1154 1155 1156 1157

    /* According to RFC 5246 Appendix E.1, the version here is typically
     * "{03,00}, the lowest version number supported by the client, [or] the
     * value of ClientHello.client_version", so the only meaningful check here
     * is the major version shouldn't be less than 3 */
1158
    if( buf[0] != SSL_MSG_HANDSHAKE ||
1159
        buf[1] < SSL_MAJOR_VERSION_3 )
Paul Bakker's avatar