Add Next Protocol Negotiation.
[openssl.git] / ssl / s3_srvr.c
index 2ff4bc7ebdeb3dd494960e20753cbefa5fd37e52..57e516f6de655307d3a9771232e2383b0918cb91 100644 (file)
@@ -189,7 +189,6 @@ int ssl3_accept(SSL *s)
        BUF_MEM *buf;
        unsigned long alg_k,Time=(unsigned long)time(NULL);
        void (*cb)(const SSL *ssl,int type,int val)=NULL;
-       long num1;
        int ret= -1;
        int new_state,state,skip=0;
 
@@ -271,6 +270,18 @@ int ssl3_accept(SSL *s)
                                s->state=SSL3_ST_SR_CLNT_HELLO_A;
                                s->ctx->stats.sess_accept++;
                                }
+                       else if (!s->s3->send_connection_binding &&
+                               !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
+                               {
+                               /* Server attempting to renegotiate with
+                                * client that doesn't support secure
+                                * renegotiation.
+                                */
+                               SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
+                               ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
+                               ret = -1;
+                               goto end;
+                               }
                        else
                                {
                                /* s->state == SSL_ST_RENEGOTIATE,
@@ -314,9 +325,18 @@ int ssl3_accept(SSL *s)
                case SSL3_ST_SW_SRVR_HELLO_B:
                        ret=ssl3_send_server_hello(s);
                        if (ret <= 0) goto end;
-
+#ifndef OPENSSL_NO_TLSEXT
                        if (s->hit)
-                               s->state=SSL3_ST_SW_CHANGE_A;
+                               {
+                               if (s->tlsext_ticket_expected)
+                                       s->state=SSL3_ST_SW_SESSION_TICKET_A;
+                               else
+                                       s->state=SSL3_ST_SW_CHANGE_A;
+                               }
+#else
+                       if (s->hit)
+                                       s->state=SSL3_ST_SW_CHANGE_A;
+#endif
                        else
                                s->state=SSL3_ST_SW_CERT_A;
                        s->init_num=0;
@@ -462,15 +482,24 @@ int ssl3_accept(SSL *s)
                        break;
                
                case SSL3_ST_SW_FLUSH:
-                       /* number of bytes to be flushed */
-                       num1=BIO_ctrl(s->wbio,BIO_CTRL_INFO,0,NULL);
-                       if (num1 > 0)
+
+                       /* This code originally checked to see if
+                        * any data was pending using BIO_CTRL_INFO
+                        * and then flushed. This caused problems
+                        * as documented in PR#1939. The proposed
+                        * fix doesn't completely resolve this issue
+                        * as buggy implementations of BIO_CTRL_PENDING
+                        * still exist. So instead we just flush
+                        * unconditionally.
+                        */
+
+                       s->rwstate=SSL_WRITING;
+                       if (BIO_flush(s->wbio) <= 0)
                                {
-                               s->rwstate=SSL_WRITING;
-                               num1=BIO_flush(s->wbio);
-                               if (num1 <= 0) { ret= -1; goto end; }
-                               s->rwstate=SSL_NOTHING;
+                               ret= -1;
+                               goto end;
                                }
+                       s->rwstate=SSL_NOTHING;
 
                        s->state=s->s3->tmp.next_state;
                        break;
@@ -505,14 +534,25 @@ int ssl3_accept(SSL *s)
                                 * the client sends its ECDH pub key in
                                 * a certificate, the CertificateVerify
                                 * message is not sent.
+                                * Also for GOST ciphersuites when
+                                * the client uses its key from the certificate
+                                * for key exchange.
                                 */
+#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NPN)
                                s->state=SSL3_ST_SR_FINISHED_A;
+#else
+                               if (s->s3->next_proto_neg_seen)
+                                       s->state=SSL3_ST_SR_NEXT_PROTO_A;
+                               else
+                                       s->state=SSL3_ST_SR_FINISHED_A;
+#endif
                                s->init_num = 0;
                                }
                        else
                                {
                                int offset=0;
                                int dgst_num;
+
                                s->state=SSL3_ST_SR_CERT_VRFY_A;
                                s->init_num=0;
 
@@ -522,12 +562,21 @@ int ssl3_accept(SSL *s)
                                 * should be generalized. But it is next step
                                 */
                                if (s->s3->handshake_buffer)
-                                       ssl3_digest_cached_records(s);
+                                       if (!ssl3_digest_cached_records(s))
+                                               return -1;
                                for (dgst_num=0; dgst_num<SSL_MAX_DIGEST;dgst_num++)    
                                        if (s->s3->handshake_dgst[dgst_num]) 
                                                {
+                                               int dgst_size;
+
                                                s->method->ssl3_enc->cert_verify_mac(s,EVP_MD_CTX_type(s->s3->handshake_dgst[dgst_num]),&(s->s3->tmp.cert_verify_md[offset]));
-                                               offset+=EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]);
+                                               dgst_size=EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]);
+                                               if (dgst_size < 0)
+                                                       {
+                                                       ret = -1;
+                                                       goto end;
+                                                       }
+                                               offset+=dgst_size;
                                                }               
                                }
                        break;
@@ -539,20 +588,40 @@ int ssl3_accept(SSL *s)
                        ret=ssl3_get_cert_verify(s);
                        if (ret <= 0) goto end;
 
+#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NPN)
                        s->state=SSL3_ST_SR_FINISHED_A;
+#else
+                       if (s->s3->next_proto_neg_seen)
+                               s->state=SSL3_ST_SR_NEXT_PROTO_A;
+                       else
+                               s->state=SSL3_ST_SR_FINISHED_A;
+#endif
                        s->init_num=0;
                        break;
 
+#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NPN)
+               case SSL3_ST_SR_NEXT_PROTO_A:
+               case SSL3_ST_SR_NEXT_PROTO_B:
+                       ret=ssl3_get_next_proto(s);
+                       if (ret <= 0) goto end;
+                       s->init_num = 0;
+                       s->state=SSL3_ST_SR_FINISHED_A;
+                       break;
+#endif
+
                case SSL3_ST_SR_FINISHED_A:
                case SSL3_ST_SR_FINISHED_B:
                        ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A,
                                SSL3_ST_SR_FINISHED_B);
                        if (ret <= 0) goto end;
-                       if (s->hit)
-                               s->state=SSL_ST_OK;
 #ifndef OPENSSL_NO_TLSEXT
-                       else if (s->tlsext_ticket_expected)
+                       if (s->tlsext_ticket_expected)
                                s->state=SSL3_ST_SW_SESSION_TICKET_A;
+                       else if (s->hit)
+                               s->state=SSL_ST_OK;
+#else
+                       if (s->hit)
+                               s->state=SSL_ST_OK;
 #endif
                        else
                                s->state=SSL3_ST_SW_CHANGE_A;
@@ -610,7 +679,16 @@ int ssl3_accept(SSL *s)
                        if (ret <= 0) goto end;
                        s->state=SSL3_ST_SW_FLUSH;
                        if (s->hit)
+                               {
+#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NPN)
                                s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;
+#else
+                               if (s->s3->next_proto_neg_seen)
+                                       s->s3->tmp.next_state=SSL3_ST_SR_NEXT_PROTO_A;
+                               else
+                                       s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;
+#endif
+                               }
                        else
                                s->s3->tmp.next_state=SSL_ST_OK;
                        s->init_num=0;
@@ -791,6 +869,21 @@ int ssl3_get_client_hello(SSL *s)
                goto f_err;
                }
 
+       /* If we require cookies and this ClientHello doesn't
+        * contain one, just return since we do not want to
+        * allocate any memory yet. So check cookie length...
+        */
+       if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE)
+               {
+               unsigned int session_length, cookie_length;
+               
+               session_length = *(p + SSL3_RANDOM_SIZE);
+               cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1);
+
+               if (cookie_length == 0)
+                       return 1;
+               }
+
        /* load the client random */
        memcpy(s->s3->client_random,p,SSL3_RANDOM_SIZE);
        p+=SSL3_RANDOM_SIZE;
@@ -830,23 +923,11 @@ int ssl3_get_client_hello(SSL *s)
 
        p+=j;
 
-       if (s->version == DTLS1_VERSION)
+       if (s->version == DTLS1_VERSION || s->version == DTLS1_BAD_VER)
                {
                /* cookie stuff */
                cookie_len = *(p++);
 
-               if ( (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) &&
-                       s->d1->send_cookie == 0)
-                       {
-                       /* HelloVerifyMessage has already been sent */
-                       if ( cookie_len != s->d1->cookie_len)
-                               {
-                               al = SSL_AD_HANDSHAKE_FAILURE;
-                               SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
-                               goto f_err;
-                               }
-                       }
-
                /* 
                 * The ClientHello may contain a cookie even if the
                 * HelloVerify message has not been sent--make sure that it
@@ -861,7 +942,7 @@ int ssl3_get_client_hello(SSL *s)
                        }
 
                /* verify the cookie if appropriate option is set. */
-               if ( (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) &&
+               if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) &&
                        cookie_len > 0)
                        {
                        memcpy(s->d1->rcvd_cookie, p, cookie_len);
@@ -886,6 +967,8 @@ int ssl3_get_client_hello(SSL *s)
                                                SSL_R_COOKIE_MISMATCH);
                                        goto f_err;
                                }
+
+                       ret = 2;
                        }
 
                p += cookie_len;
@@ -935,22 +1018,28 @@ int ssl3_get_client_hello(SSL *s)
                                break;
                                }
                        }
-               if (j == 0)
+               if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG) && (sk_SSL_CIPHER_num(ciphers) == 1))
                        {
-                       if ((s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG) && (sk_SSL_CIPHER_num(ciphers) == 1))
-                               {
-                               /* Very bad for multi-threading.... */
-                               s->session->cipher=sk_SSL_CIPHER_value(ciphers, 0);
-                               }
-                       else
+                       /* Special case as client bug workaround: the previously used cipher may
+                        * not be in the current list, the client instead might be trying to
+                        * continue using a cipher that before wasn't chosen due to server
+                        * preferences.  We'll have to reject the connection if the cipher is not
+                        * enabled, though. */
+                       c = sk_SSL_CIPHER_value(ciphers, 0);
+                       if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0)
                                {
-                               /* we need to have the cipher in the cipher
-                                * list if we are asked to reuse it */
-                               al=SSL_AD_ILLEGAL_PARAMETER;
-                               SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_REQUIRED_CIPHER_MISSING);
-                               goto f_err;
+                               s->session->cipher = c;
+                               j = 1;
                                }
                        }
+               if (j == 0)
+                       {
+                       /* we need to have the cipher in the cipher
+                        * list if we are asked to reuse it */
+                       al=SSL_AD_ILLEGAL_PARAMETER;
+                       SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_REQUIRED_CIPHER_MISSING);
+                       goto f_err;
+                       }
                }
 
        /* compression */
@@ -979,7 +1068,7 @@ int ssl3_get_client_hello(SSL *s)
 
 #ifndef OPENSSL_NO_TLSEXT
        /* TLS extensions*/
-       if (s->version > SSL3_VERSION)
+       if (s->version >= SSL3_VERSION)
                {
                if (!ssl_parse_clienthello_tlsext(s,&p,d,n, &al))
                        {
@@ -992,6 +1081,59 @@ int ssl3_get_client_hello(SSL *s)
                        SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_CLIENTHELLO_TLSEXT);
                        goto err;
                }
+
+       /* Check if we want to use external pre-shared secret for this
+        * handshake for not reused session only. We need to generate
+        * server_random before calling tls_session_secret_cb in order to allow
+        * SessionTicket processing to use it in key derivation. */
+       {
+               unsigned long Time;
+               unsigned char *pos;
+               Time=(unsigned long)time(NULL);                 /* Time */
+               pos=s->s3->server_random;
+               l2n(Time,pos);
+               if (RAND_pseudo_bytes(pos,SSL3_RANDOM_SIZE-4) <= 0)
+                       {
+                       al=SSL_AD_INTERNAL_ERROR;
+                       goto f_err;
+                       }
+       }
+
+       if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb)
+               {
+               SSL_CIPHER *pref_cipher=NULL;
+
+               s->session->master_key_length=sizeof(s->session->master_key);
+               if(s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length,
+                       ciphers, &pref_cipher, s->tls_session_secret_cb_arg))
+                       {
+                       s->hit=1;
+                       s->session->ciphers=ciphers;
+                       s->session->verify_result=X509_V_OK;
+
+                       ciphers=NULL;
+
+                       /* check if some cipher was preferred by call back */
+                       pref_cipher=pref_cipher ? pref_cipher : ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
+                       if (pref_cipher == NULL)
+                               {
+                               al=SSL_AD_HANDSHAKE_FAILURE;
+                               SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_SHARED_CIPHER);
+                               goto f_err;
+                               }
+
+                       s->session->cipher=pref_cipher;
+
+                       if (s->cipher_list)
+                               sk_SSL_CIPHER_free(s->cipher_list);
+
+                       if (s->cipher_list_by_id)
+                               sk_SSL_CIPHER_free(s->cipher_list_by_id);
+
+                       s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
+                       s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
+                       }
+               }
 #endif
 
        /* Worst case, we will use the NULL compression, but if we have other
@@ -999,7 +1141,50 @@ int ssl3_get_client_hello(SSL *s)
         * algorithms from the client, starting at q. */
        s->s3->tmp.new_compression=NULL;
 #ifndef OPENSSL_NO_COMP
-       if (!(s->options & SSL_OP_NO_COMPRESSION) && s->ctx->comp_methods)
+       /* This only happens if we have a cache hit */
+       if (s->session->compress_meth != 0)
+               {
+               int m, comp_id = s->session->compress_meth;
+               /* Perform sanity checks on resumed compression algorithm */
+               /* Can't disable compression */
+               if (s->options & SSL_OP_NO_COMPRESSION)
+                       {
+                       al=SSL_AD_INTERNAL_ERROR;
+                       SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INCONSISTENT_COMPRESSION);
+                       goto f_err;
+                       }
+               /* Look for resumed compression method */
+               for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++)
+                       {
+                       comp=sk_SSL_COMP_value(s->ctx->comp_methods,m);
+                       if (comp_id == comp->id)
+                               {
+                               s->s3->tmp.new_compression=comp;
+                               break;
+                               }
+                       }
+               if (s->s3->tmp.new_compression == NULL)
+                       {
+                       al=SSL_AD_INTERNAL_ERROR;
+                       SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INVALID_COMPRESSION_ALGORITHM);
+                       goto f_err;
+                       }
+               /* Look for resumed method in compression list */
+               for (m = 0; m < i; m++)
+                       {
+                       if (q[m] == comp_id)
+                               break;
+                       }
+               if (m >= i)
+                       {
+                       al=SSL_AD_ILLEGAL_PARAMETER;
+                       SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING);
+                       goto f_err;
+                       }
+               }
+       else if (s->hit)
+               comp = NULL;
+       else if (!(s->options & SSL_OP_NO_COMPRESSION) && s->ctx->comp_methods)
                { /* See if we have a match */
                int m,nn,o,v,done=0;
 
@@ -1023,6 +1208,16 @@ int ssl3_get_client_hello(SSL *s)
                else
                        comp=NULL;
                }
+#else
+       /* If compression is disabled we'd better not try to resume a session
+        * using compression.
+        */
+       if (s->session->compress_meth != 0)
+               {
+               al=SSL_AD_INTERNAL_ERROR;
+               SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INCONSISTENT_COMPRESSION);
+               goto f_err;
+               }
 #endif
 
        /* Given s->session->ciphers and SSL_get_ciphers, we must
@@ -1055,7 +1250,6 @@ int ssl3_get_client_hello(SSL *s)
                        goto f_err;
                        }
                s->s3->tmp.new_cipher=c;
-               ssl3_digest_cached_records(s);
                }
        else
                {
@@ -1086,10 +1280,10 @@ int ssl3_get_client_hello(SSL *s)
                else
 #endif
                s->s3->tmp.new_cipher=s->session->cipher;
-               /* Clear cached handshake records */
-               BIO_free(s->s3->handshake_buffer);
-               s->s3->handshake_buffer = NULL;
                }
+
+       if (!ssl3_digest_cached_records(s))
+               goto f_err;
        
        /* we now have the following setup. 
         * client_random
@@ -1102,7 +1296,7 @@ int ssl3_get_client_hello(SSL *s)
         * s->tmp.new_cipher    - the new cipher to use.
         */
 
-       ret=1;
+       if (ret < 0) ret=1;
        if (0)
                {
 f_err:
@@ -1118,16 +1312,22 @@ int ssl3_send_server_hello(SSL *s)
        unsigned char *buf;
        unsigned char *p,*d;
        int i,sl;
-       unsigned long l,Time;
+       unsigned long l;
+#ifdef OPENSSL_NO_TLSEXT
+       unsigned long Time;
+#endif
 
        if (s->state == SSL3_ST_SW_SRVR_HELLO_A)
                {
                buf=(unsigned char *)s->init_buf->data;
+#ifdef OPENSSL_NO_TLSEXT
                p=s->s3->server_random;
+               /* Generate server_random if it was not needed previously */
                Time=(unsigned long)time(NULL);                 /* Time */
                l2n(Time,p);
                if (RAND_pseudo_bytes(p,SSL3_RANDOM_SIZE-4) <= 0)
                        return -1;
+#endif
                /* Do the message type and length last */
                d=p= &(buf[4]);
 
@@ -1198,13 +1398,13 @@ int ssl3_send_server_hello(SSL *s)
                *(d++)=SSL3_MT_SERVER_HELLO;
                l2n3(l,d);
 
-               s->state=SSL3_ST_CW_CLNT_HELLO_B;
+               s->state=SSL3_ST_SW_SRVR_HELLO_B;
                /* number of bytes to write */
                s->init_num=p-buf;
                s->init_off=0;
                }
 
-       /* SSL3_ST_CW_CLNT_HELLO_B */
+       /* SSL3_ST_SW_SRVR_HELLO_B */
        return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
        }
 
@@ -1228,7 +1428,7 @@ int ssl3_send_server_done(SSL *s)
                s->init_off=0;
                }
 
-       /* SSL3_ST_CW_CLNT_HELLO_B */
+       /* SSL3_ST_SW_SRVR_DONE_B */
        return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
        }
 
@@ -1834,7 +2034,7 @@ int ssl3_get_client_key_exchange(SSL *s)
                        }
 
                /* TLS and [incidentally] DTLS{0xFEFF} */
-               if (s->version > SSL3_VERSION)
+               if (s->version > SSL3_VERSION && s->version != DTLS1_BAD_VER)
                        {
                        n2s(p,i);
                        if (n != i+2)
@@ -1979,7 +2179,7 @@ int ssl3_get_client_key_exchange(SSL *s)
                krb5_data               enc_pms;
                KSSL_CTX                *kssl_ctx = s->kssl_ctx;
                EVP_CIPHER_CTX          ciph_ctx;
-               EVP_CIPHER              *enc = NULL;
+               const EVP_CIPHER        *enc = NULL;
                unsigned char           iv[EVP_MAX_IV_LENGTH];
                unsigned char           pms[SSL_MAX_MASTER_KEY_LENGTH
                                               + EVP_MAX_BLOCK_LENGTH];
@@ -1994,7 +2194,7 @@ int ssl3_get_client_key_exchange(SSL *s)
                n2s(p,i);
                enc_ticket.length = i;
 
-               if (n < enc_ticket.length + 6)
+               if (n < (long)(enc_ticket.length + 6))
                        {
                        SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
                                SSL_R_DATA_LENGTH_TOO_LONG);
@@ -2007,7 +2207,7 @@ int ssl3_get_client_key_exchange(SSL *s)
                n2s(p,i);
                authenticator.length = i;
 
-               if (n < enc_ticket.length + authenticator.length + 6)
+               if (n < (long)(enc_ticket.length + authenticator.length + 6))
                        {
                        SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
                                SSL_R_DATA_LENGTH_TOO_LONG);
@@ -2119,7 +2319,7 @@ int ssl3_get_client_key_exchange(SSL *s)
                                SSL_R_DATA_LENGTH_TOO_LONG);
                        goto err;
                        }
-               if (!((p[0] == (s->client_version>>8)) && (p[1] == (s->client_version & 0xff))))
+               if (!((pms[0] == (s->client_version>>8)) && (pms[1] == (s->client_version & 0xff))))
                    {
                    /* The premaster secret must contain the same version number as the
                     * ClientHello to detect version rollback attacks (strangely, the
@@ -2129,8 +2329,7 @@ int ssl3_get_client_key_exchange(SSL *s)
                     * If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. 
                     * (Perhaps we should have a separate BUG value for the Kerberos cipher)
                     */
-                   if (!((s->options & SSL_OP_TLS_ROLLBACK_BUG) &&
-                          (p[0] == (s->version>>8)) && (p[1] == (s->version & 0xff))))
+                   if (!(s->options & SSL_OP_TLS_ROLLBACK_BUG))
                        {
                        SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
                               SSL_AD_DECODE_ERROR);
@@ -2300,9 +2499,10 @@ int ssl3_get_client_key_exchange(SSL *s)
 
                EVP_PKEY_free(clnt_pub_pkey);
                EC_POINT_free(clnt_ecpoint);
-               if (srvr_ecdh != NULL) 
-                       EC_KEY_free(srvr_ecdh);
+               EC_KEY_free(srvr_ecdh);
                BN_CTX_free(bn_ctx);
+               EC_KEY_free(s->s3->tmp.ecdh);
+               s->s3->tmp.ecdh = NULL; 
 
                /* Compute the master secret */
                s->session->master_key_length = s->method->ssl3_enc-> \
@@ -2409,33 +2609,70 @@ int ssl3_get_client_key_exchange(SSL *s)
                else
 #endif
                if (alg_k & SSL_kGOST) 
-               {
+                       {
+                       int ret = 0;
                        EVP_PKEY_CTX *pkey_ctx;
-                       unsigned char premaster_secret[32];
-                       size_t outlen;                  
+                       EVP_PKEY *client_pub_pkey = NULL;
+                       unsigned char premaster_secret[32], *start;
+                       size_t outlen=32, inlen;                        
 
-                       /* Get our certificate privatec key*/
+                       /* Get our certificate private key*/
                        pkey_ctx = EVP_PKEY_CTX_new(s->cert->key->privatekey,NULL);     
                        EVP_PKEY_decrypt_init(pkey_ctx);
+                       /* If client certificate is present and is of the same type, maybe
+                        * use it for key exchange.  Don't mind errors from
+                        * EVP_PKEY_derive_set_peer, because it is completely valid to use
+                        * a client certificate for authorization only. */
+                       client_pub_pkey = X509_get_pubkey(s->session->peer);
+                       if (client_pub_pkey)
+                               {
+                               if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
+                                       ERR_clear_error();
+                               }
                        /* Decrypt session key */
-                       if ((*p!=( V_ASN1_SEQUENCE| V_ASN1_CONSTRUCTED)) || p[1]!=0x81 
+                       if ((*p!=( V_ASN1_SEQUENCE| V_ASN1_CONSTRUCTED))) 
                                {
                                SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DECRYPTION_FAILED);
-                               goto err;
-                               }       
-                       if (EVP_PKEY_decrypt(pkey_ctx,premaster_secret,&outlen,p+3,p[2]) <0) 
+                               goto gerr;
+                               }
+                       if (p[1] == 0x81)
+                               {
+                               start = p+3;
+                               inlen = p[2];
+                               }
+                       else if (p[1] < 0x80)
+                               {
+                               start = p+2;
+                               inlen = p[1];
+                               }
+                       else
+                               {
+                               SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DECRYPTION_FAILED);
+                               goto gerr;
+                               }
+                       if (EVP_PKEY_decrypt(pkey_ctx,premaster_secret,&outlen,start,inlen) <=0) 
 
                                {
                                SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DECRYPTION_FAILED);
-                               goto err;
+                               goto gerr;
                                }
                        /* Generate master secret */
-                       EVP_PKEY_CTX_free(pkey_ctx);
                        s->session->master_key_length=
                                s->method->ssl3_enc->generate_master_secret(s,
                                        s->session->master_key,premaster_secret,32);
-
-               }
+                       /* Check if pubkey from client certificate was used */
+                       if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
+                               ret = 2;
+                       else
+                               ret = 1;
+               gerr:
+                       EVP_PKEY_free(client_pub_pkey);
+                       EVP_PKEY_CTX_free(pkey_ctx);
+                       if (ret)
+                               return ret;
+                       else
+                               goto err;
+                       }
                else
                {
                al=SSL_AD_HANDSHAKE_FAILURE;
@@ -2759,7 +2996,7 @@ int ssl3_get_client_certificate(SSL *s)
        else
                {
                i=ssl_verify_cert_chain(s,sk);
-               if (!i)
+               if (i <= 0)
                        {
                        al=ssl_verify_alarm_type(s->verify_result);
                        SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_NO_CERTIFICATE_RETURNED);
@@ -2841,6 +3078,9 @@ int ssl3_send_newsession_ticket(SSL *s)
                unsigned int hlen;
                EVP_CIPHER_CTX ctx;
                HMAC_CTX hctx;
+               SSL_CTX *tctx = s->initial_ctx;
+               unsigned char iv[EVP_MAX_IV_LENGTH];
+               unsigned char key_name[16];
 
                /* get session encoding length */
                slen = i2d_SSL_SESSION(s->session, NULL);
@@ -2871,29 +3111,47 @@ int ssl3_send_newsession_ticket(SSL *s)
                *(p++)=SSL3_MT_NEWSESSION_TICKET;
                /* Skip message length for now */
                p += 3;
+               EVP_CIPHER_CTX_init(&ctx);
+               HMAC_CTX_init(&hctx);
+               /* Initialize HMAC and cipher contexts. If callback present
+                * it does all the work otherwise use generated values
+                * from parent ctx.
+                */
+               if (tctx->tlsext_ticket_key_cb)
+                       {
+                       if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
+                                                        &hctx, 1) < 0)
+                               {
+                               OPENSSL_free(senc);
+                               return -1;
+                               }
+                       }
+               else
+                       {
+                       RAND_pseudo_bytes(iv, 16);
+                       EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
+                                       tctx->tlsext_tick_aes_key, iv);
+                       HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
+                                       tlsext_tick_md(), NULL);
+                       memcpy(key_name, tctx->tlsext_tick_key_name, 16);
+                       }
                l2n(s->session->tlsext_tick_lifetime_hint, p);
                /* Skip ticket length for now */
                p += 2;
                /* Output key name */
                macstart = p;
-               memcpy(p, s->ctx->tlsext_tick_key_name, 16);
+               memcpy(p, key_name, 16);
                p += 16;
-               /* Generate and output IV */
-               RAND_pseudo_bytes(p, 16);
-               EVP_CIPHER_CTX_init(&ctx);
+               /* output IV */
+               memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
+               p += EVP_CIPHER_CTX_iv_length(&ctx);
                /* Encrypt session data */
-               EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
-                                       s->ctx->tlsext_tick_aes_key, p);
-               p += 16;
                EVP_EncryptUpdate(&ctx, p, &len, senc, slen);
                p += len;
                EVP_EncryptFinal(&ctx, p, &len);
                p += len;
                EVP_CIPHER_CTX_cleanup(&ctx);
 
-               HMAC_CTX_init(&hctx);
-               HMAC_Init_ex(&hctx, s->ctx->tlsext_tick_hmac_key, 16,
-                               tlsext_tick_md(), NULL);
                HMAC_Update(&hctx, macstart, p - macstart);
                HMAC_Final(&hctx, p, &hlen);
                HMAC_CTX_cleanup(&hctx);
@@ -2952,4 +3210,72 @@ int ssl3_send_cert_status(SSL *s)
        /* SSL3_ST_SW_CERT_STATUS_B */
        return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
        }
+
+# ifndef OPENSSL_NO_NPN
+/* ssl3_get_next_proto reads a Next Protocol Negotiation handshake message. It
+ * sets the next_proto member in s if found */
+int ssl3_get_next_proto(SSL *s)
+       {
+       int ok;
+       unsigned proto_len, padding_len;
+       long n;
+       const unsigned char *p;
+
+       /* Clients cannot send a NextProtocol message if we didn't see the
+        * extension in their ClientHello */
+       if (!s->s3->next_proto_neg_seen)
+               {
+               SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
+               return -1;
+               }
+
+       n=s->method->ssl_get_message(s,
+               SSL3_ST_SR_NEXT_PROTO_A,
+               SSL3_ST_SR_NEXT_PROTO_B,
+               SSL3_MT_NEXT_PROTO,
+               129,
+               &ok);
+
+       if (!ok)
+               return((int)n);
+
+       /* s->state doesn't reflect whether ChangeCipherSpec has been received
+        * in this handshake, but s->s3->change_cipher_spec does (will be reset
+        * by ssl3_get_finished). */
+       if (!s->s3->change_cipher_spec)
+               {
+               SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS);
+               return -1;
+               }
+
+       if (n < 2)
+               return 0;  /* The body must be > 1 bytes long */
+
+       p=(unsigned char *)s->init_msg;
+
+       /* The payload looks like:
+        *   uint8 proto_len;
+        *   uint8 proto[proto_len];
+        *   uint8 padding_len;
+        *   uint8 padding[padding_len];
+        */
+       proto_len = p[0];
+       if (proto_len + 2 > s->init_num)
+               return 0;
+       padding_len = p[proto_len + 1];
+       if (proto_len + padding_len + 2 != s->init_num)
+               return 0;
+
+       s->next_proto_negotiated = OPENSSL_malloc(proto_len);
+       if (!s->next_proto_negotiated)
+               {
+               SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,ERR_R_MALLOC_FAILURE);
+               return 0;
+               }
+       memcpy(s->next_proto_negotiated, p + 1, proto_len);
+       s->next_proto_negotiated_len = proto_len;
+
+       return 1;
+       }
+# endif
 #endif