ssl_srv.c 98.6 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
#include "polarssl/config.h"
27

28
#if defined(POLARSSL_SSL_SRV_C)
29

30 31
#include "polarssl/debug.h"
#include "polarssl/ssl.h"
32 33 34
#if defined(POLARSSL_ECP_C)
#include "polarssl/ecp.h"
#endif
35

36 37
#if defined(POLARSSL_PLATFORM_C)
#include "polarssl/platform.h"
38 39 40 41 42
#else
#define polarssl_malloc     malloc
#define polarssl_free       free
#endif

43 44
#include <stdlib.h>
#include <stdio.h>
45 46

#if defined(POLARSSL_HAVE_TIME)
47
#include <time.h>
48
#endif
49

50
#if defined(POLARSSL_SSL_SESSION_TICKETS)
51 52 53 54 55 56 57 58
/*
 * 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).
 */
59 60 61
static int ssl_save_session( const ssl_session *session,
                             unsigned char *buf, size_t buf_len,
                             size_t *olen )
62 63
{
    unsigned char *p = buf;
64
    size_t left = buf_len;
65
#if defined(POLARSSL_X509_CRT_PARSE_C)
66
    size_t cert_len;
67
#endif /* POLARSSL_X509_CRT_PARSE_C */
68

69 70 71
    if( left < sizeof( ssl_session ) )
        return( -1 );

72 73
    memcpy( p, session, sizeof( ssl_session ) );
    p += sizeof( ssl_session );
74
    left -= sizeof( ssl_session );
75

76
#if defined(POLARSSL_X509_CRT_PARSE_C)
77 78 79 80 81
    if( session->peer_cert == NULL )
        cert_len = 0;
    else
        cert_len = session->peer_cert->raw.len;

82 83 84
    if( left < 3 + cert_len )
        return( -1 );

85 86 87 88 89 90 91 92
    *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;
93
#endif /* POLARSSL_X509_CRT_PARSE_C */
94 95

    *olen = p - buf;
96 97

    return( 0 );
98 99 100 101 102 103 104 105 106 107
}

/*
 * 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;
108
#if defined(POLARSSL_X509_CRT_PARSE_C)
109
    size_t cert_len;
110
#endif /* POLARSSL_X509_CRT_PARSE_C */
111 112 113 114 115 116 117

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

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

118
#if defined(POLARSSL_X509_CRT_PARSE_C)
119 120 121 122 123 124 125 126 127 128 129 130
    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
    {
131 132
        int ret;

133 134 135
        if( p + cert_len > end )
            return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );

136
        session->peer_cert = polarssl_malloc( sizeof( x509_crt ) );
137 138 139 140

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

141
        x509_crt_init( session->peer_cert );
142

143
        if( ( ret = x509_crt_parse( session->peer_cert, p, cert_len ) ) != 0 )
144
        {
145
            x509_crt_free( session->peer_cert );
146 147 148 149 150 151 152
            polarssl_free( session->peer_cert );
            session->peer_cert = NULL;
            return( ret );
        }

        p += cert_len;
    }
153
#endif /* POLARSSL_X509_CRT_PARSE_C */
154 155 156 157 158 159 160

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

    return( 0 );
}

161 162 163 164 165 166 167 168 169 170 171 172 173 174
/*
 * 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 )
{
175
    int ret;
176 177
    unsigned char * const start = ssl->out_msg + 10;
    unsigned char *p = start;
178 179 180
    unsigned char *state;
    unsigned char iv[16];
    size_t clear_len, enc_len, pad_len, i;
181

182 183
    *tlen = 0;

184 185 186
    if( ssl->ticket_keys == NULL )
        return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );

187
    /* Write key name */
188
    memcpy( p, ssl->ticket_keys->key_name, 16 );
189 190
    p += 16;

191 192 193 194
    /* 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 );
195 196
    p += 16;

197 198 199 200 201 202
    /*
     * 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
     */
203
    state = p + 2;
204 205 206 207 208 209
    if( ssl_save_session( ssl->session_negotiate, state,
                          SSL_MAX_CONTENT_LEN - (state - ssl->out_ctr) - 48,
                          &clear_len ) != 0 )
    {
        return( POLARSSL_ERR_SSL_CERTIFICATE_TOO_LARGE );
    }
210
    SSL_DEBUG_BUF( 3, "session ticket cleartext", state, clear_len );
211

212 213 214 215 216
    /* 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;
217

218 219 220 221 222 223 224 225 226 227 228
    /* 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;
229

230 231
    /* 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 );
232 233 234 235
    p += 32;

    *tlen = p - start;

236
    SSL_DEBUG_BUF( 3, "session ticket structure", start, *tlen );
237 238 239 240 241 242 243 244

    return( 0 );
}

/*
 * Load session ticket (see ssl_write_ticket for structure)
 */
static int ssl_parse_ticket( ssl_context *ssl,
245
                             unsigned char *buf,
246 247 248 249
                             size_t len )
{
    int ret;
    ssl_session session;
250 251 252 253 254
    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;
255
    unsigned char computed_mac[32];
256
    size_t enc_len, clear_len, i;
257
    unsigned char pad_len, diff;
258 259

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

261
    if( len < 34 || ssl->ticket_keys == NULL )
262 263 264 265 266 267 268 269
        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 );

270 271 272 273 274
    /* 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 */
275

276
    /* Check mac, with constant-time buffer comparison */
277 278
    sha256_hmac( ssl->ticket_keys->mac_key, 16, buf, len - 32,
                 computed_mac, 0 );
279

280
    for( i = 0; i < 32; i++ )
281 282 283 284 285 286
        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 );
287

288 289 290 291 292 293
    /* Decrypt */
    if( ( ret = aes_crypt_cbc( &ssl->ticket_keys->dec, AES_DECRYPT,
                               enc_len, iv, ticket, ticket ) ) != 0 )
    {
        return( ret );
    }
294

295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
    /* 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 */
310 311 312
    if( ( ret = ssl_load_session( &session, ticket, clear_len ) ) != 0 )
    {
        SSL_DEBUG_MSG( 1, ( "failed to parse ticket content" ) );
313
        ssl_session_free( &session );
314 315 316
        return( ret );
    }

317 318 319 320 321
#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" ) );
322
        ssl_session_free( &session );
323 324 325 326
        return( POLARSSL_ERR_SSL_SESSION_TICKET_EXPIRED );
    }
#endif

327 328 329 330 331 332 333 334 335 336 337 338 339
    /*
     * 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 ) );
    memset( &session, 0, sizeof( ssl_session ) );

    return( 0 );
}
340
#endif /* POLARSSL_SSL_SESSION_TICKETS */
341

342
#if defined(POLARSSL_SSL_SERVER_NAME_INDICATION)
343
/*
344 345
 * Wrapper around f_sni, allowing use of ssl_set_own_cert() but
 * making it act on ssl->hanshake->sni_key_cert instead.
346 347 348 349 350 351 352 353 354
 */
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 );
355
    ssl->handshake->sni_key_cert = ssl->key_cert;
356 357 358 359 360 361

    ssl->key_cert = key_cert_ori;

    return( ret );
}

362
static int ssl_parse_servername_ext( ssl_context *ssl,
363
                                     const unsigned char *buf,
364 365 366 367
                                     size_t len )
{
    int ret;
    size_t servername_list_size, hostname_len;
368
    const unsigned char *p;
369

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

372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
    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 )
        {
391
            ret = ssl_sni_wrapper( ssl, p + 3, hostname_len );
392 393
            if( ret != 0 )
            {
Manuel Pégourié-Gonnard's avatar
Manuel Pégourié-Gonnard committed
394
                SSL_DEBUG_RET( 1, "ssl_sni_wrapper", ret );
395 396 397 398
                ssl_send_alert_message( ssl, SSL_ALERT_LEVEL_FATAL,
                        SSL_ALERT_MSG_UNRECOGNIZED_NAME );
                return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );
            }
399
            return( 0 );
400 401 402
        }

        servername_list_size -= hostname_len + 3;
403 404 405 406 407 408 409
        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 );
410 411 412 413
    }

    return( 0 );
}
414
#endif /* POLARSSL_SSL_SERVER_NAME_INDICATION */
415

416
static int ssl_parse_renegotiation_info( ssl_context *ssl,
417
                                         const unsigned char *buf,
418 419
                                         size_t len )
{
420 421
    int ret;

422 423 424 425 426
    if( ssl->renegotiation == SSL_INITIAL_HANDSHAKE )
    {
        if( len != 1 || buf[0] != 0x0 )
        {
            SSL_DEBUG_MSG( 1, ( "non-zero length renegotiated connection field" ) );
427 428 429 430

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

431 432 433 434 435 436 437
            return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );
        }

        ssl->secure_renegotiation = SSL_SECURE_RENEGOTIATION;
    }
    else
    {
438
        /* Check verify-data in constant-time. The length OTOH is no secret */
439 440
        if( len    != 1 + ssl->verify_data_len ||
            buf[0] !=     ssl->verify_data_len ||
441 442
            safer_memcmp( buf + 1, ssl->peer_verify_data,
                          ssl->verify_data_len ) != 0 )
443 444
        {
            SSL_DEBUG_MSG( 1, ( "non-matching renegotiated connection field" ) );
445 446 447 448

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

449 450 451 452 453 454 455
            return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );
        }
    }

    return( 0 );
}

456
#if defined(POLARSSL_SSL_PROTO_TLS1_2)
457 458 459 460 461 462 463 464 465 466 467 468 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;

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

    p = buf + 2;
    while( sig_alg_list_size > 0 )
    {
475 476 477 478
        /*
         * For now, just ignore signature algorithm and rely on offered
         * ciphersuites only. To be fixed later.
         */
479
#if defined(POLARSSL_SHA512_C)
480 481 482 483 484 485 486 487 488 489 490
        if( p[0] == SSL_HASH_SHA512 )
        {
            ssl->handshake->sig_alg = SSL_HASH_SHA512;
            break;
        }
        if( p[0] == SSL_HASH_SHA384 )
        {
            ssl->handshake->sig_alg = SSL_HASH_SHA384;
            break;
        }
#endif
491
#if defined(POLARSSL_SHA256_C)
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
        if( p[0] == SSL_HASH_SHA256 )
        {
            ssl->handshake->sig_alg = SSL_HASH_SHA256;
            break;
        }
        if( p[0] == SSL_HASH_SHA224 )
        {
            ssl->handshake->sig_alg = SSL_HASH_SHA224;
            break;
        }
#endif
        if( p[0] == SSL_HASH_SHA1 )
        {
            ssl->handshake->sig_alg = SSL_HASH_SHA1;
            break;
        }
        if( p[0] == SSL_HASH_MD5 )
        {
            ssl->handshake->sig_alg = SSL_HASH_MD5;
            break;
        }

        sig_alg_list_size -= 2;
        p += 2;
    }

    SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext: %d",
                   ssl->handshake->sig_alg ) );

    return( 0 );
}
523
#endif /* POLARSSL_SSL_PROTO_TLS1_2 */
524

525
#if defined(POLARSSL_ECDH_C) || defined(POLARSSL_ECDSA_C)
526 527 528
static int ssl_parse_supported_elliptic_curves( ssl_context *ssl,
                                                const unsigned char *buf,
                                                size_t len )
529
{
530
    size_t list_size, our_size;
531
    const unsigned char *p;
532
    const ecp_curve_info *curve_info, **curves;
533 534 535 536 537 538 539 540 541

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

542
    /* Don't allow our peer to make us allocate too much memory,
543 544 545 546 547 548 549 550
     * 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 );

551 552
	/* explicit void pointer cast for buggy MS compiler */
    memset( (void *) curves, 0, our_size * sizeof( *curves ) );
553 554
    ssl->handshake->curves = curves;

555
    p = buf + 2;
556
    while( list_size > 0 && our_size > 1 )
557
    {
558
        curve_info = ecp_curve_info_from_tls_id( ( p[0] << 8 ) | p[1] );
559

560
        if( curve_info != NULL )
561
        {
562 563
            *curves++ = curve_info;
            our_size--;
564
        }
565 566 567 568 569 570 571 572

        list_size -= 2;
        p += 2;
    }

    return( 0 );
}

573 574 575
static int ssl_parse_supported_point_formats( ssl_context *ssl,
                                              const unsigned char *buf,
                                              size_t len )
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
{
    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 )
        {
593
            ssl->handshake->ecdh_ctx.point_format = p[0];
594
            SSL_DEBUG_MSG( 4, ( "point format selected: %d", p[0] ) );
595 596 597 598 599 600 601 602 603
            return( 0 );
        }

        list_size--;
        p++;
    }

    return( 0 );
}
604
#endif /* POLARSSL_ECDH_C || POLARSSL_ECDSA_C */
605

606
#if defined(POLARSSL_SSL_MAX_FRAGMENT_LENGTH)
607 608 609 610
static int ssl_parse_max_fragment_length_ext( ssl_context *ssl,
                                              const unsigned char *buf,
                                              size_t len )
{
611
    if( len != 1 || buf[0] >= SSL_MAX_FRAG_LEN_INVALID )
612 613 614 615 616
    {
        SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
        return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );
    }

617 618
    ssl->session_negotiate->mfl_code = buf[0];

619 620
    return( 0 );
}
621
#endif /* POLARSSL_SSL_MAX_FRAGMENT_LENGTH */
622

623
#if defined(POLARSSL_SSL_TRUNCATED_HMAC)
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
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 );
}
640
#endif /* POLARSSL_SSL_TRUNCATED_HMAC */
641

642
#if defined(POLARSSL_SSL_SESSION_TICKETS)
643
static int ssl_parse_session_ticket_ext( ssl_context *ssl,
644
                                         unsigned char *buf,
645 646
                                         size_t len )
{
647 648
    int ret;

649 650 651
    if( ssl->session_tickets == SSL_SESSION_TICKETS_DISABLED )
        return( 0 );

652
    /* Remember the client asked us to send a new ticket */
653 654
    ssl->handshake->new_session_ticket = 1;

655 656
    SSL_DEBUG_MSG( 3, ( "ticket length: %d", len ) );

657 658 659
    if( len == 0 )
        return( 0 );

660 661 662 663 664
    if( ssl->renegotiation != SSL_INITIAL_HANDSHAKE )
    {
        SSL_DEBUG_MSG( 3, ( "ticket rejected: renegotiating" ) );
        return( 0 );
    }
665 666 667 668

    /*
     * Failures are ok: just ignore the ticket and proceed.
     */
669 670 671
    if( ( ret = ssl_parse_ticket( ssl, buf, len ) ) != 0 )
    {
        SSL_DEBUG_RET( 1, "ssl_parse_ticket", ret );
672
        return( 0 );
673
    }
674 675 676 677

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

    ssl->handshake->resume = 1;
678

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

682 683
    return( 0 );
}
684
#endif /* POLARSSL_SSL_SESSION_TICKETS */
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 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
#if defined(POLARSSL_SSL_ALPN)
static int ssl_parse_alpn_ext( ssl_context *ssl,
                               unsigned char *buf, size_t len )
{
    size_t list_len, cur_len;
    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++ )
    {
        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 );

            if( cur_len == strlen( *ours ) &&
                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 */

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 790 791 792 793 794 795 796 797 798 799
/*
 * 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;

800 801 802 803 804 805 806 807 808 809 810 811 812 813
        /*
         * 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;
        }

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 876 877 878 879 880 881 882 883 884 885
#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 );
}

886 887 888 889 890 891 892 893
#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;
894
    const int *ciphersuites;
895
    const ssl_ciphersuite_t *ciphersuite_info;
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 936 937 938 939 940 941 942 943 944 945

    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;
946 947
    ssl->minor_ver = ( buf[4] <= ssl->max_minor_ver )
                     ? buf[4]  : ssl->max_minor_ver;
948 949 950 951 952 953 954 955 956 957 958 959

    if( ssl->minor_ver < ssl->min_minor_ver )
    {
        SSL_DEBUG_MSG( 1, ( "client only supports ssl smaller than minimum"
                            " [%d:%d] < [%d:%d]", ssl->major_ver, ssl->minor_ver,
                            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 );
    }

960 961
    ssl->handshake->max_major_ver = buf[3];
    ssl->handshake->max_minor_ver = buf[4];
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 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 1051 1052 1053 1054 1055

    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;
    memset( ssl->session_negotiate->id, 0, sizeof( ssl->session_negotiate->id ) );
    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;
        }
    }

1056
    ciphersuites = ssl->ciphersuite_list[ssl->minor_ver];
1057
    ciphersuite_info = NULL;
1058 1059 1060 1061 1062
#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
1063
    for( i = 0; ciphersuites[i] != 0; i++ )
1064 1065
    {
        for( j = 0, p = buf + 6; j < ciph_len; j += 3, p += 3 )
1066
#endif
1067
        {
1068 1069 1070 1071
            if( p[0] != 0 ||
                p[1] != ( ( ciphersuites[i] >> 8 ) & 0xFF ) ||
                p[2] != ( ( ciphersuites[i]      ) & 0xFF ) )
                continue;
1072

1073 1074 1075
            if( ( ret = ssl_ciphersuite_match( ssl, ciphersuites[i],
                                               &ciphersuite_info ) ) != 0 )
                return( ret );
1076

1077
            if( ciphersuite_info != NULL )
1078 1079 1080 1081 1082 1083 1084 1085 1086
                goto have_ciphersuite_v2;
        }
    }

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

    return( POLARSSL_ERR_SSL_NO_CIPHER_CHOSEN );

have_ciphersuite_v2:
1087
    ssl->session_negotiate->ciphersuite = ciphersuites[i];
1088
    ssl->transform_negotiate->ciphersuite_info = ciphersuite_info;
1089
    ssl_optimize_checksum( ssl, ssl->transform_negotiate->ciphersuite_info );
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113

    /*
     * 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 */

1114 1115
static int ssl_parse_client_hello( ssl_context *ssl )
{
1116 1117 1118 1119
    int ret;
    unsigned int i, j;
    size_t n;
    unsigned int ciph_len, sess_len;
1120
    unsigned int comp_len;
1121 1122
    unsigned int ext_len = 0;
    unsigned char *buf, *p, *ext;
1123 1124
    int renegotiation_info_seen = 0;
    int handshake_failure = 0;
1125
    const int *ciphersuites;
1126
    const ssl_ciphersuite_t *ciphersuite_info;
1127 1128 1129

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

1130 1131
    if( ssl->renegotiation == SSL_INITIAL_HANDSHAKE &&
        ( ret = ssl_fetch_input( ssl, 5 ) ) != 0 )
1132 1133 1134 1135 1136 1137 1138
    {
        SSL_DEBUG_RET( 1, "ssl_fetch_input", ret );
        return( ret );
    }

    buf = ssl->in_hdr;

1139 1140 1141 1142 1143
#if defined(POLARSSL_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO)
    if( ( buf[0] & 0x80 ) != 0 )
        return ssl_parse_client_hello_v2( ssl );
#endif

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

1146 1147 1148 1149 1150 1151
    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] ) );
1152

1153
    /*
1154
     * SSLv3/TLS Client Hello
1155 1156 1157 1158 1159 1160
     *
     * Record layer:
     *     0  .   0   message type
     *     1  .   2   protocol version
     *     3  .   4   message length
     */
1161 1162 1163 1164 1165

    /* 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 */
1166
    if( buf[0] != SSL_MSG_HANDSHAKE ||
1167
        buf[1] < SSL_MAJOR_VERSION_3 )
1168 1169 1170 1171
    {
        SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
        return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );
    }
1172

1173
    n = ( buf[3] << 8 ) | buf[4];
1174

1175
    if( n < 45 || n > SSL_MAX_CONTENT_LEN )
1176 1177 1178
    {
        SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
        return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );
1179
    }
1180

1181 1182
    if( ssl->renegotiation == SSL_INITIAL_HANDSHAKE &&
        ( ret = ssl_fetch_input( ssl, 5 + n ) ) != 0 )
1183
    {
1184 1185 1186
        SSL_DEBUG_RET( 1, "ssl_fetch_input", ret );
        return( ret );
    }
1187

1188
    buf = ssl->in_msg;
1189 1190 1191 1192
    if( !ssl->renegotiation )
        n = ssl->in_left - 5;
    else
        n = ssl->in_msglen;
1193

1194
    ssl->handshake->update_checksum( ssl, buf, n );
1195