Do not resume a session if the negotiated protocol version does not match
[openssl.git] / ssl / s3_srvr.c
index f17afaf330a86cd94c48fbe92c8f35a78bb633f7..f95f9c77e8c8be364ff925428a034e175598db17 100644 (file)
 #define NETSCAPE_HANG_BUG
 
 #include <stdio.h>
-#include <openssl/crypto.h>
 #include "ssl_locl.h"
 #include "kssl_lcl.h"
+#include "../crypto/constant_time_locl.h"
 #include <openssl/buffer.h>
 #include <openssl/rand.h>
 #include <openssl/objects.h>
 #endif
 #include <openssl/md5.h>
 
+#ifndef OPENSSL_NO_SSL3_METHOD
 static const SSL_METHOD *ssl3_get_server_method(int ver);
 
 static const SSL_METHOD *ssl3_get_server_method(int ver)
@@ -180,8 +181,14 @@ static const SSL_METHOD *ssl3_get_server_method(int ver)
                return(NULL);
        }
 
+IMPLEMENT_ssl3_meth_func(SSLv3_server_method,
+                       ssl3_accept,
+                       ssl_undefined_function,
+                       ssl3_get_server_method)
+#endif
+
 #ifndef OPENSSL_NO_SRP
-static int ssl_check_srp_ext_ClientHello(SSL *s,int *al)
+static int ssl_check_srp_ext_ClientHello(SSL *s, int *al)
        {
        int ret = SSL_ERROR_NONE;
 
@@ -206,11 +213,6 @@ static int ssl_check_srp_ext_ClientHello(SSL *s,int *al)
        }
 #endif
 
-IMPLEMENT_ssl3_meth_func(SSLv3_server_method,
-                       ssl3_accept,
-                       ssl_undefined_function,
-                       ssl3_get_server_method)
-
 int ssl3_accept(SSL *s)
        {
        BUF_MEM *buf;
@@ -238,6 +240,18 @@ int ssl3_accept(SSL *s)
                return(-1);
                }
 
+#ifndef OPENSSL_NO_HEARTBEATS
+       /* If we're awaiting a HeartbeatResponse, pretend we
+        * already got and don't await it anymore, because
+        * Heartbeats don't make sense during handshakes anyway.
+        */
+       if (s->tlsext_hb_pending)
+               {
+               s->tlsext_hb_pending = 0;
+               s->tlsext_hb_seq++;
+               }
+#endif
+
        for (;;)
                {
                state=s->state;
@@ -261,6 +275,14 @@ int ssl3_accept(SSL *s)
                                SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
                                return -1;
                                }
+
+                       if (!ssl_security(s, SSL_SECOP_VERSION, 0,
+                                                       s->version, NULL))
+                               {
+                               SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_VERSION_TOO_LOW);
+                               return -1;
+                               }
+
                        s->type=SSL_ST_ACCEPT;
 
                        if (s->init_buf == NULL)
@@ -285,6 +307,11 @@ int ssl3_accept(SSL *s)
                                }
 
                        s->init_num=0;
+                       s->s3->flags &= ~SSL3_FLAGS_SGC_RESTART_DONE;
+                       s->s3->flags &= ~TLS1_FLAGS_SKIP_CERT_VERIFY;
+                       s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
+                       /* Should have been reset by ssl3_get_finished, too. */
+                       s->s3->change_cipher_spec = 0;
 
                        if (s->state != SSL_ST_RENEGOTIATE)
                                {
@@ -339,23 +366,32 @@ int ssl3_accept(SSL *s)
                case SSL3_ST_SR_CLNT_HELLO_B:
                case SSL3_ST_SR_CLNT_HELLO_C:
 
-                       s->shutdown=0;
                        ret=ssl3_get_client_hello(s);
                        if (ret <= 0) goto end;
 #ifndef OPENSSL_NO_SRP
+                       s->state = SSL3_ST_SR_CLNT_HELLO_D;
+               case SSL3_ST_SR_CLNT_HELLO_D:
                        {
                        int al;
-
-                       if ((ret = ssl_check_srp_ext_ClientHello(s,&al)) != SSL_ERROR_NONE)
-                               {
-                               ssl3_send_alert(s,SSL3_AL_FATAL,al);                            
-                               SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_CLIENTHELLO_TLSEXT);                     
+                       if ((ret = ssl_check_srp_ext_ClientHello(s,&al))  < 0)
+                                       {
+                                       /* callback indicates firther work to be done */
+                                       s->rwstate=SSL_X509_LOOKUP;
+                                       goto end;
+                                       }
+                       if (ret != SSL_ERROR_NONE)
+                               {
+                               ssl3_send_alert(s,SSL3_AL_FATAL,al);    
+                               /* This is not really an error but the only means to
+                                   for a client to detect whether srp is supported. */
+                                  if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)      
+                                       SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_CLIENTHELLO_TLSEXT);                     
                                ret = SSL_TLSEXT_ERR_ALERT_FATAL;                       
                                ret= -1;
                                goto end;       
-                               }
+                               }
                        }
-#endif
+#endif         
                        
                        s->renegotiate = 2;
                        s->state=SSL3_ST_SW_SRVR_HELLO_A;
@@ -379,17 +415,16 @@ int ssl3_accept(SSL *s)
                                        s->state=SSL3_ST_SW_CHANGE_A;
 #endif
                        else
-                               s->state=SSL3_ST_SW_CERT_A;
-                       s->init_num=0;
+                                       s->state = SSL3_ST_SW_CERT_A;
+                       s->init_num = 0;
                        break;
 
                case SSL3_ST_SW_CERT_A:
                case SSL3_ST_SW_CERT_B:
                        /* Check if it is anon DH or anon ECDH, */
                        /* normal PSK or KRB5 or SRP */
-                       if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
-                               && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)
-                               && !(s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5))
+                       if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aKRB5|SSL_aSRP))
+                               && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
                                {
                                ret=ssl3_send_server_certificate(s);
                                if (ret <= 0) goto end;
@@ -455,8 +490,8 @@ int ssl3_accept(SSL *s)
                            /* SRP: send ServerKeyExchange */
                            || (alg_k & SSL_kSRP)
 #endif
-                           || (alg_k & (SSL_kDHr|SSL_kDHd|SSL_kEDH))
-                           || (alg_k & SSL_kEECDH)
+                           || (alg_k & SSL_kDHE)
+                           || (alg_k & SSL_kECDHE)
                            || ((alg_k & SSL_kRSA)
                                && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
                                    || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
@@ -492,7 +527,9 @@ int ssl3_accept(SSL *s)
                                  * (against the specs, but s3_clnt.c accepts this for SSL 3) */
                                 !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
                                 /* never request cert in Kerberos ciphersuites */
-                               (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5)
+                               (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) ||
+                               /* don't request certificate for SRP auth */
+                               (s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)
                                /* With normal PSK Certificates and
                                 * Certificate Requests are omitted */
                                || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
@@ -596,13 +633,13 @@ int ssl3_accept(SSL *s)
 #endif
                                s->init_num = 0;
                                }
-                       else if (TLS1_get_version(s) >= TLS1_2_VERSION)
+                       else if (SSL_USE_SIGALGS(s))
                                {
                                s->state=SSL3_ST_SR_CERT_VRFY_A;
                                s->init_num=0;
                                if (!s->session->peer)
                                        break;
-                               /* For TLS v1.2 freeze the handshake buffer
+                               /* For sigalgs freeze the handshake buffer
                                 * at this point and digest cached records.
                                 */
                                if (!s->s3->handshake_buffer)
@@ -649,7 +686,14 @@ int ssl3_accept(SSL *s)
 
                case SSL3_ST_SR_CERT_VRFY_A:
                case SSL3_ST_SR_CERT_VRFY_B:
-
+                       /*
+                        * This *should* be the first time we enable CCS, but be
+                        * extra careful about surrounding code changes. We need
+                        * to set this here because we don't know if we're
+                        * expecting a CertificateVerify or not.
+                        */
+                       if (!s->s3->change_cipher_spec)
+                               s->s3->flags |= SSL3_FLAGS_CCS_OK;
                        /* we should decide if we expected this one */
                        ret=ssl3_get_cert_verify(s);
                        if (ret <= 0) goto end;
@@ -668,6 +712,19 @@ int ssl3_accept(SSL *s)
 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
                case SSL3_ST_SR_NEXT_PROTO_A:
                case SSL3_ST_SR_NEXT_PROTO_B:
+                       /*
+                        * Enable CCS for resumed handshakes with NPN.
+                        * In a full handshake with NPN, we end up here through
+                        * SSL3_ST_SR_CERT_VRFY_B, where SSL3_FLAGS_CCS_OK was
+                        * already set. Receiving a CCS clears the flag, so make
+                        * sure not to re-enable it to ban duplicates.
+                        * s->s3->change_cipher_spec is set when a CCS is
+                        * processed in s3_pkt.c, and remains set until
+                        * the client's Finished message is read.
+                        */
+                       if (!s->s3->change_cipher_spec)
+                               s->s3->flags |= SSL3_FLAGS_CCS_OK;
+
                        ret=ssl3_get_next_proto(s);
                        if (ret <= 0) goto end;
                        s->init_num = 0;
@@ -677,6 +734,18 @@ int ssl3_accept(SSL *s)
 
                case SSL3_ST_SR_FINISHED_A:
                case SSL3_ST_SR_FINISHED_B:
+                       /*
+                        * Enable CCS for resumed handshakes without NPN.
+                        * In a full handshake, we end up here through
+                        * SSL3_ST_SR_CERT_VRFY_B, where SSL3_FLAGS_CCS_OK was
+                        * already set. Receiving a CCS clears the flag, so make
+                        * sure not to re-enable it to ban duplicates.
+                        * s->s3->change_cipher_spec is set when a CCS is
+                        * processed in s3_pkt.c, and remains set until
+                        * the client's Finished message is read.
+                        */
+                       if (!s->s3->change_cipher_spec)
+                               s->s3->flags |= SSL3_FLAGS_CCS_OK;
                        ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A,
                                SSL3_ST_SR_FINISHED_B);
                        if (ret <= 0) goto end;
@@ -747,7 +816,9 @@ int ssl3_accept(SSL *s)
                                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
@@ -824,24 +895,15 @@ end:
 
 int ssl3_send_hello_request(SSL *s)
        {
-       unsigned char *p;
 
        if (s->state == SSL3_ST_SW_HELLO_REQ_A)
                {
-               p=(unsigned char *)s->init_buf->data;
-               *(p++)=SSL3_MT_HELLO_REQUEST;
-               *(p++)=0;
-               *(p++)=0;
-               *(p++)=0;
-
+               ssl_set_handshake_header(s, SSL3_MT_HELLO_REQUEST, 0);
                s->state=SSL3_ST_SW_HELLO_REQ_B;
-               /* number of bytes to write */
-               s->init_num=4;
-               s->init_off=0;
                }
 
        /* SSL3_ST_SW_HELLO_REQ_B */
-       return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
+       return ssl_do_write(s);
        }
 
 int ssl3_check_client_hello(SSL *s)
@@ -861,6 +923,13 @@ int ssl3_check_client_hello(SSL *s)
        s->s3->tmp.reuse_message = 1;
        if (s->s3->tmp.message_type == SSL3_MT_CLIENT_HELLO)
                {
+               /* We only allow the client to restart the handshake once per
+                * negotiation. */
+               if (s->s3->flags & SSL3_FLAGS_SGC_RESTART_DONE)
+                       {
+                       SSLerr(SSL_F_SSL3_CHECK_CLIENT_HELLO, SSL_R_MULTIPLE_SGC_RESTARTS);
+                       return -1;
+                       }
                /* Throw away what we have done so far in the current handshake,
                 * which will now be aborted. (A full SSL_clear would be too much.) */
 #ifndef OPENSSL_NO_DH
@@ -877,6 +946,7 @@ int ssl3_check_client_hello(SSL *s)
                        s->s3->tmp.ecdh = NULL;
                        }
 #endif
+               s->s3->flags |= SSL3_FLAGS_SGC_RESTART_DONE;
                return 2;
                }
        return 1;
@@ -884,17 +954,21 @@ int ssl3_check_client_hello(SSL *s)
 
 int ssl3_get_client_hello(SSL *s)
        {
-       int i,j,ok,al,ret= -1;
+       int i,j,ok,al=SSL_AD_INTERNAL_ERROR,ret= -1;
        unsigned int cookie_len;
        long n;
        unsigned long id;
-       unsigned char *p,*d,*q;
+       unsigned char *p,*d;
        SSL_CIPHER *c;
 #ifndef OPENSSL_NO_COMP
+       unsigned char *q;
        SSL_COMP *comp=NULL;
 #endif
        STACK_OF(SSL_CIPHER) *ciphers=NULL;
 
+       if (s->state == SSL3_ST_SR_CLNT_HELLO_C && !s->first_packet)
+               goto retry_cert;
+
        /* We do this so that we will respond with our native type.
         * If we are TLSv1 and we get SSLv3, we will respond with TLSv1,
         * This down switching should be handled by a different method.
@@ -923,11 +997,13 @@ int ssl3_get_client_hello(SSL *s)
        s->client_version=(((int)p[0])<<8)|(int)p[1];
        p+=2;
 
-       if ((s->version == DTLS1_VERSION && s->client_version > s->version) ||
-           (s->version != DTLS1_VERSION && s->client_version < s->version))
+       if (SSL_IS_DTLS(s)  ?   (s->client_version > s->version &&
+                                s->method->version != DTLS_ANY_VERSION)
+                           :   (s->client_version < s->version))
                {
                SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER);
-               if ((s->client_version>>8) == SSL3_VERSION_MAJOR)
+               if ((s->client_version>>8) == SSL3_VERSION_MAJOR &&
+                       !s->enc_write_ctx && !s->write_hash)
                        {
                        /* similar to ssl3_get_record, send alert using remote version number */
                        s->version = s->client_version;
@@ -978,7 +1054,16 @@ int ssl3_get_client_hello(SSL *s)
        else
                {
                i=ssl_get_prev_session(s, p, j, d + n);
-               if (i == 1)
+               /*
+                * Only resume if the session's version matches the negotiated
+                * version.
+                * RFC 5246 does not provide much useful advice on resumption
+                * with a different protocol version. It doesn't forbid it but
+                * the sanity of such behaviour would be questionable.
+                * In practice, clients do not accept a version mismatch and
+                * will abort the handshake with an error.
+                */
+               if (i == 1 && s->version == s->session->ssl_version)
                        { /* previous session */
                        s->hit=1;
                        }
@@ -993,7 +1078,7 @@ int ssl3_get_client_hello(SSL *s)
 
        p+=j;
 
-       if (s->version == DTLS1_VERSION || s->version == DTLS1_BAD_VER)
+       if (SSL_IS_DTLS(s))
                {
                /* cookie stuff */
                cookie_len = *(p++);
@@ -1037,11 +1122,42 @@ int ssl3_get_client_hello(SSL *s)
                                                SSL_R_COOKIE_MISMATCH);
                                        goto f_err;
                                }
-
-                       ret = 2;
+                       /* Set to -2 so if successful we return 2 */
+                       ret = -2;
                        }
 
                p += cookie_len;
+               if (s->method->version == DTLS_ANY_VERSION)
+                       {
+                       /* Select version to use */
+                       if (s->client_version <= DTLS1_2_VERSION &&
+                               !(s->options & SSL_OP_NO_DTLSv1_2))
+                               {
+                               s->version = DTLS1_2_VERSION;
+                               s->method = DTLSv1_2_server_method();
+                               }
+                       else if (tls1_suiteb(s))
+                               {
+                               SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
+                               s->version = s->client_version;
+                               al = SSL_AD_PROTOCOL_VERSION;
+                               goto f_err;
+                               }
+                       else if (s->client_version <= DTLS1_VERSION &&
+                               !(s->options & SSL_OP_NO_DTLSv1))
+                               {
+                               s->version = DTLS1_VERSION;
+                               s->method = DTLSv1_server_method();
+                               }
+                       else
+                               {
+                               SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER);
+                               s->version = s->client_version;
+                               al = SSL_AD_PROTOCOL_VERSION;
+                               goto f_err;
+                               }
+                       s->session->ssl_version = s->version;
+                       }
                }
 
        n2s(p,i);
@@ -1126,7 +1242,9 @@ int ssl3_get_client_hello(SSL *s)
                SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH);
                goto f_err;
                }
+#ifndef OPENSSL_NO_COMP
        q=p;
+#endif
        for (j=0; j<i; j++)
                {
                if (p[j] == 0) break;
@@ -1145,16 +1263,11 @@ int ssl3_get_client_hello(SSL *s)
        /* TLS extensions*/
        if (s->version >= SSL3_VERSION)
                {
-               if (!ssl_parse_clienthello_tlsext(s,&p,d,n, &al))
+               if (!ssl_parse_clienthello_tlsext(s,&p,d,n))
                        {
-                       /* 'al' set by ssl_parse_clienthello_tlsext */
                        SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_PARSE_TLSEXT);
-                       goto f_err;
-                       }
-               }
-               if (ssl_check_clienthello_tlsext(s) <= 0) {
-                       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
@@ -1162,14 +1275,10 @@ int ssl3_get_client_hello(SSL *s)
         * 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)
+               if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0)
                        {
-                       al=SSL_AD_INTERNAL_ERROR;
                        goto f_err;
                        }
        }
@@ -1222,9 +1331,8 @@ int ssl3_get_client_hello(SSL *s)
                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)
+               if (!ssl_allow_compression(s))
                        {
-                       al=SSL_AD_INTERNAL_ERROR;
                        SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INCONSISTENT_COMPRESSION);
                        goto f_err;
                        }
@@ -1240,7 +1348,6 @@ int ssl3_get_client_hello(SSL *s)
                        }
                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;
                        }
@@ -1259,7 +1366,7 @@ int ssl3_get_client_hello(SSL *s)
                }
        else if (s->hit)
                comp = NULL;
-       else if (!(s->options & SSL_OP_NO_COMPRESSION) && s->ctx->comp_methods)
+       else if (ssl_allow_compression(s) && s->ctx->comp_methods)
                { /* See if we have a match */
                int m,nn,o,v,done=0;
 
@@ -1289,7 +1396,6 @@ int ssl3_get_client_hello(SSL *s)
         */
        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;
                }
@@ -1315,6 +1421,29 @@ int ssl3_get_client_hello(SSL *s)
                        goto f_err;
                        }
                ciphers=NULL;
+               if (!tls1_set_server_sigalgs(s))
+                       {
+                       SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
+                       goto err;
+                       }
+               /* Let cert callback update server certificates if required */
+               retry_cert:             
+               if (s->cert->cert_cb)
+                       {
+                       int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
+                       if (rv == 0)
+                               {
+                               al=SSL_AD_INTERNAL_ERROR;
+                               SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_CERT_CB_ERROR);
+                               goto f_err;
+                               }
+                       if (rv < 0)
+                               {
+                               s->rwstate=SSL_X509_LOOKUP;
+                               return -1;
+                               }
+                       s->rwstate = SSL_NOTHING;
+                       }
                c=ssl3_choose_cipher(s,s->session->ciphers,
                                     SSL_get_ciphers(s));
 
@@ -1328,7 +1457,7 @@ int ssl3_get_client_hello(SSL *s)
                /* check whether we should disable session resumption */
                if (s->not_resumable_session_cb != NULL)
                        s->session->not_resumable=s->not_resumable_session_cb(s,
-                               ((c->algorithm_mkey & (SSL_kEDH | SSL_kEECDH)) != 0));
+                               ((c->algorithm_mkey & (SSL_kDHE | SSL_kECDHE)) != 0));
                if (s->session->not_resumable)
                        /* do not send a session ticket */
                        s->tlsext_ticket_expected = 0;
@@ -1364,7 +1493,7 @@ int ssl3_get_client_hello(SSL *s)
                s->s3->tmp.new_cipher=s->session->cipher;
                }
 
-       if (TLS1_get_version(s) < TLS1_2_VERSION || !(s->verify_mode & SSL_VERIFY_PEER))
+       if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER))
                {
                if (!ssl3_digest_cached_records(s))
                        goto f_err;
@@ -1378,10 +1507,20 @@ int ssl3_get_client_hello(SSL *s)
         * ssl version is set   - sslv3
         * s->session           - The ssl session has been setup.
         * s->hit               - session reuse flag
-        * s->tmp.new_cipher    - the new cipher to use.
+        * s->s3->tmp.new_cipher- the new cipher to use.
         */
 
-       if (ret < 0) ret=1;
+       /* Handles TLS extensions that we couldn't check earlier */
+       if (s->version >= SSL3_VERSION)
+               {
+               if (ssl_check_clienthello_tlsext_late(s) <= 0)
+                       {
+                       SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
+                       goto err;
+                       }
+               }
+
+       if (ret < 0) ret=-ret;
        if (0)
                {
 f_err:
@@ -1389,7 +1528,7 @@ f_err:
                }
 err:
        if (ciphers != NULL) sk_SSL_CIPHER_free(ciphers);
-       return(ret);
+       return ret < 0 ? -1 : ret;
        }
 
 int ssl3_send_server_hello(SSL *s)
@@ -1397,24 +1536,19 @@ int ssl3_send_server_hello(SSL *s)
        unsigned char *buf;
        unsigned char *p,*d;
        int i,sl;
+       int al = 0;
        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)
+               if (ssl_fill_hello_random(s, 1, p, SSL3_RANDOM_SIZE) <= 0)
                        return -1;
 #endif
                /* Do the message type and length last */
-               d=p= &(buf[4]);
+               d=p= ssl_handshake_start(s);
 
                *(p++)=s->version>>8;
                *(p++)=s->version&0xff;
@@ -1472,50 +1606,34 @@ int ssl3_send_server_hello(SSL *s)
                        SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,SSL_R_SERVERHELLO_TLSEXT);
                        return -1;
                        }
-               if ((p = ssl_add_serverhello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH)) == NULL)
+               if ((p = ssl_add_serverhello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH, &al)) == NULL)
                        {
+                       ssl3_send_alert(s, SSL3_AL_FATAL, al);
                        SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,ERR_R_INTERNAL_ERROR);
                        return -1;
                        }
 #endif
                /* do the header */
                l=(p-d);
-               d=buf;
-               *(d++)=SSL3_MT_SERVER_HELLO;
-               l2n3(l,d);
-
+               ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l);
                s->state=SSL3_ST_SW_SRVR_HELLO_B;
-               /* number of bytes to write */
-               s->init_num=p-buf;
-               s->init_off=0;
                }
 
        /* SSL3_ST_SW_SRVR_HELLO_B */
-       return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
+       return ssl_do_write(s);
        }
 
 int ssl3_send_server_done(SSL *s)
        {
-       unsigned char *p;
 
        if (s->state == SSL3_ST_SW_SRVR_DONE_A)
                {
-               p=(unsigned char *)s->init_buf->data;
-
-               /* do the header */
-               *(p++)=SSL3_MT_SERVER_DONE;
-               *(p++)=0;
-               *(p++)=0;
-               *(p++)=0;
-
-               s->state=SSL3_ST_SW_SRVR_DONE_B;
-               /* number of bytes to write */
-               s->init_num=4;
-               s->init_off=0;
+               ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0);
+               s->state = SSL3_ST_SW_SRVR_DONE_B;
                }
 
        /* SSL3_ST_SW_SRVR_DONE_B */
-       return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
+       return ssl_do_write(s);
        }
 
 int ssl3_send_server_key_exchange(SSL *s)
@@ -1590,9 +1708,20 @@ int ssl3_send_server_key_exchange(SSL *s)
                else
 #endif
 #ifndef OPENSSL_NO_DH
-                       if (type & SSL_kEDH)
+                       if (type & SSL_kDHE)
                        {
-                       dhp=cert->dh_tmp;
+                       if (s->cert->dh_tmp_auto)
+                               {
+                               dhp = ssl_get_auto_dh(s);
+                               if (dhp == NULL)
+                                       {
+                                       al=SSL_AD_INTERNAL_ERROR;
+                                       SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
+                                       goto f_err;
+                                       }
+                               }
+                       else
+                               dhp=cert->dh_tmp;
                        if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
                                dhp=s->cert->dh_tmp_cb(s,
                                      SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
@@ -1603,14 +1732,22 @@ int ssl3_send_server_key_exchange(SSL *s)
                                SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
                                goto f_err;
                                }
-
+                       if (!ssl_security(s, SSL_SECOP_TMP_DH,
+                                               DH_security_bits(dhp), 0, dhp))
+                               {
+                               al=SSL_AD_HANDSHAKE_FAILURE;
+                               SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_DH_KEY_TOO_SMALL);
+                               goto f_err;
+                               }
                        if (s->s3->tmp.dh != NULL)
                                {
                                SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
                                goto err;
                                }
 
-                       if ((dh=DHparams_dup(dhp)) == NULL)
+                       if (s->cert->dh_tmp_auto)
+                               dh = dhp;
+                       else if ((dh=DHparams_dup(dhp)) == NULL)
                                {
                                SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
                                goto err;
@@ -1646,12 +1783,19 @@ int ssl3_send_server_key_exchange(SSL *s)
                else 
 #endif
 #ifndef OPENSSL_NO_ECDH
-                       if (type & SSL_kEECDH)
+                       if (type & SSL_kECDHE)
                        {
                        const EC_GROUP *group;
 
                        ecdhp=cert->ecdh_tmp;
-                       if ((ecdhp == NULL) && (s->cert->ecdh_tmp_cb != NULL))
+                       if (s->cert->ecdh_tmp_auto)
+                               {
+                               /* Get NID of appropriate shared curve */
+                               int nid = tls1_shared_curve(s, -2);
+                               if (nid != NID_undef)
+                                       ecdhp = EC_KEY_new_by_curve_name(nid);
+                               }
+                       else if ((ecdhp == NULL) && s->cert->ecdh_tmp_cb)
                                {
                                ecdhp=s->cert->ecdh_tmp_cb(s,
                                      SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
@@ -1676,7 +1820,9 @@ int ssl3_send_server_key_exchange(SSL *s)
                                SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
                                goto err;
                                }
-                       if ((ecdh = EC_KEY_dup(ecdhp)) == NULL)
+                       if (s->cert->ecdh_tmp_auto)
+                               ecdh = ecdhp;
+                       else if ((ecdh = EC_KEY_dup(ecdhp)) == NULL)
                                {
                                SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
                                goto err;
@@ -1802,7 +1948,7 @@ int ssl3_send_server_key_exchange(SSL *s)
                        SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
                        goto f_err;
                        }
-               for (i=0; r[i] != NULL && i<4; i++)
+               for (i=0; i < 4 && r[i] != NULL; i++)
                        {
                        nr[i]=BN_num_bytes(r[i]);
 #ifndef OPENSSL_NO_SRP
@@ -1813,7 +1959,7 @@ int ssl3_send_server_key_exchange(SSL *s)
                        n+=2+nr[i];
                        }
 
-               if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
+               if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aSRP))
                        && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
                        {
                        if ((pkey=ssl_get_sign_pkey(s,s->s3->tmp.new_cipher,&md))
@@ -1830,15 +1976,14 @@ int ssl3_send_server_key_exchange(SSL *s)
                        kn=0;
                        }
 
-               if (!BUF_MEM_grow_clean(buf,n+4+kn))
+               if (!BUF_MEM_grow_clean(buf,n+SSL_HM_HEADER_LENGTH(s)+kn))
                        {
                        SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_BUF);
                        goto err;
                        }
-               d=(unsigned char *)s->init_buf->data;
-               p= &(d[4]);
+               d = p = ssl_handshake_start(s);
 
-               for (i=0; r[i] != NULL && i<4; i++)
+               for (i=0; i < 4 && r[i] != NULL; i++)
                        {
 #ifndef OPENSSL_NO_SRP
                        if ((i == 2) && (type & SSL_kSRP))
@@ -1854,7 +1999,7 @@ int ssl3_send_server_key_exchange(SSL *s)
                        }
 
 #ifndef OPENSSL_NO_ECDH
-               if (type & SSL_kEECDH
+               if (type & SSL_kECDHE
                        {
                        /* XXX: For now, we only support named (not generic) curves.
                         * In this situation, the serverKeyExchange message has:
@@ -1895,8 +2040,7 @@ int ssl3_send_server_key_exchange(SSL *s)
                        /* n is the length of the params, they start at &(d[4])
                         * and p points to the space at the end. */
 #ifndef OPENSSL_NO_RSA
-                       if (pkey->type == EVP_PKEY_RSA
-                                       && TLS1_get_version(s) < TLS1_2_VERSION)
+                       if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s))
                                {
                                q=md_buf;
                                j=0;
@@ -1908,7 +2052,7 @@ int ssl3_send_server_key_exchange(SSL *s)
                                                ?s->ctx->md5:s->ctx->sha1, NULL);
                                        EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
                                        EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
-                                       EVP_DigestUpdate(&md_ctx,&(d[4]),n);
+                                       EVP_DigestUpdate(&md_ctx,d,n);
                                        EVP_DigestFinal_ex(&md_ctx,q,
                                                (unsigned int *)&i);
                                        q+=i;
@@ -1927,9 +2071,8 @@ int ssl3_send_server_key_exchange(SSL *s)
 #endif
                        if (md)
                                {
-                               /* For TLS1.2 and later send signature
-                                * algorithm */
-                               if (TLS1_get_version(s) >= TLS1_2_VERSION)
+                               /* send signature algorithm */
+                               if (SSL_USE_SIGALGS(s))
                                        {
                                        if (!tls12_get_sigandhash(p, pkey, md))
                                                {
@@ -1947,7 +2090,7 @@ int ssl3_send_server_key_exchange(SSL *s)
                                EVP_SignInit_ex(&md_ctx, md, NULL);
                                EVP_SignUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
                                EVP_SignUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
-                               EVP_SignUpdate(&md_ctx,&(d[4]),n);
+                               EVP_SignUpdate(&md_ctx,d,n);
                                if (!EVP_SignFinal(&md_ctx,&(p[2]),
                                        (unsigned int *)&i,pkey))
                                        {
@@ -1956,7 +2099,7 @@ int ssl3_send_server_key_exchange(SSL *s)
                                        }
                                s2n(i,p);
                                n+=i+2;
-                               if (TLS1_get_version(s) >= TLS1_2_VERSION)
+                               if (SSL_USE_SIGALGS(s))
                                        n+= 2;
                                }
                        else
@@ -1968,18 +2111,12 @@ int ssl3_send_server_key_exchange(SSL *s)
                                }
                        }
 
-               *(d++)=SSL3_MT_SERVER_KEY_EXCHANGE;
-               l2n3(n,d);
-
-               /* we should now have things packed up, so lets send
-                * it off */
-               s->init_num=n+4;
-               s->init_off=0;
+               ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n);
                }
 
        s->state = SSL3_ST_SW_KEY_EXCH_B;
        EVP_MD_CTX_cleanup(&md_ctx);
-       return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
+       return ssl_do_write(s);
 f_err:
        ssl3_send_alert(s,SSL3_AL_FATAL,al);
 err:
@@ -2003,7 +2140,7 @@ int ssl3_send_certificate_request(SSL *s)
                {
                buf=s->init_buf;
 
-               d=p=(unsigned char *)&(buf->data[4]);
+               d=p=ssl_handshake_start(s);
 
                /* get the list of acceptable cert types */
                p++;
@@ -2012,11 +2149,17 @@ int ssl3_send_certificate_request(SSL *s)
                p+=n;
                n++;
 
-               if (TLS1_get_version(s) >= TLS1_2_VERSION)
+               if (SSL_USE_SIGALGS(s))
                        {
-                       nl = tls12_get_req_sig_algs(s, p + 2);
-                       s2n(nl, p);
-                       p += nl + 2;
+                       const unsigned char *psigs;
+                       unsigned char *etmp = p;
+                       nl = tls12_get_psigalgs(s, &psigs);
+                       /* Skip over length for now */
+                       p += 2;
+                       nl = tls12_copy_sigalgs(s, p, psigs, nl);
+                       /* Now fill in length */
+                       s2n(nl, etmp);
+                       p += nl;
                        n += nl + 2;
                        }
 
@@ -2032,12 +2175,12 @@ int ssl3_send_certificate_request(SSL *s)
                                {
                                name=sk_X509_NAME_value(sk,i);
                                j=i2d_X509_NAME(name,NULL);
-                               if (!BUF_MEM_grow_clean(buf,4+n+j+2))
+                               if (!BUF_MEM_grow_clean(buf,SSL_HM_HEADER_LENGTH(s)+n+j+2))
                                        {
                                        SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,ERR_R_BUF_LIB);
                                        goto err;
                                        }
-                               p=(unsigned char *)&(buf->data[4+n]);
+                               p = ssl_handshake_start(s) + n;
                                if (!(s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
                                        {
                                        s2n(j,p);
@@ -2056,34 +2199,34 @@ int ssl3_send_certificate_request(SSL *s)
                                }
                        }
                /* else no CA names */
-               p=(unsigned char *)&(buf->data[4+off]);
+               p = ssl_handshake_start(s) + off;
                s2n(nl,p);
 
-               d=(unsigned char *)buf->data;
-               *(d++)=SSL3_MT_CERTIFICATE_REQUEST;
-               l2n3(n,d);
-
-               /* we should now have things packed up, so lets send
-                * it off */
+               ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n);
 
-               s->init_num=n+4;
-               s->init_off=0;
 #ifdef NETSCAPE_HANG_BUG
-               p=(unsigned char *)s->init_buf->data + s->init_num;
-
-               /* do the header */
-               *(p++)=SSL3_MT_SERVER_DONE;
-               *(p++)=0;
-               *(p++)=0;
-               *(p++)=0;
-               s->init_num += 4;
+               if (!SSL_IS_DTLS(s))
+                       {
+                       if (!BUF_MEM_grow_clean(buf, s->init_num + 4))
+                               {
+                               SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,ERR_R_BUF_LIB);
+                               goto err;
+                               }
+                       p=(unsigned char *)s->init_buf->data + s->init_num;
+                       /* do the header */
+                       *(p++)=SSL3_MT_SERVER_DONE;
+                       *(p++)=0;
+                       *(p++)=0;
+                       *(p++)=0;
+                       s->init_num += 4;
+                       }
 #endif
 
                s->state = SSL3_ST_SW_CERT_REQ_B;
                }
 
        /* SSL3_ST_SW_CERT_REQ_B */
-       return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
+       return ssl_do_write(s);
 err:
        return(-1);
        }
@@ -2100,7 +2243,7 @@ int ssl3_get_client_key_exchange(SSL *s)
 #endif
 #ifndef OPENSSL_NO_DH
        BIGNUM *pub=NULL;
-       DH *dh_srvr;
+       DH *dh_srvr, *dh_clnt = NULL;
 #endif
 #ifndef OPENSSL_NO_KRB5
        KSSL_ERR kssl_err;
@@ -2128,6 +2271,10 @@ int ssl3_get_client_key_exchange(SSL *s)
 #ifndef OPENSSL_NO_RSA
        if (alg_k & SSL_kRSA)
                {
+               unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
+               int decrypt_len;
+               unsigned char decrypt_good, version_good;
+
                /* FIX THIS UP EAY EAY EAY EAY */
                if (s->s3->tmp.use_rsa_tmp)
                        {
@@ -2175,54 +2322,61 @@ int ssl3_get_client_key_exchange(SSL *s)
                                n=i;
                        }
 
-               i=RSA_private_decrypt((int)n,p,p,rsa,RSA_PKCS1_PADDING);
+               /* We must not leak whether a decryption failure occurs because
+                * of Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see
+                * RFC 2246, section 7.4.7.1). The code follows that advice of
+                * the TLS RFC and generates a random premaster secret for the
+                * case that the decrypt fails. See
+                * https://tools.ietf.org/html/rfc5246#section-7.4.7.1 */
 
-               al = -1;
-               
-               if (i != SSL_MAX_MASTER_KEY_LENGTH)
-                       {
-                       al=SSL_AD_DECODE_ERROR;
-                       /* SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT); */
-                       }
-
-               if ((al == -1) && !((p[0] == (s->client_version>>8)) && (p[1] == (s->client_version & 0xff))))
-                       {
-                       /* The premaster secret must contain the same version number as the
-                        * ClientHello to detect version rollback attacks (strangely, the
-                        * protocol does not offer such protection for DH ciphersuites).
-                        * However, buggy clients exist that send the negotiated protocol
-                        * version instead if the server does not support the requested
-                        * protocol version.
-                        * If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. */
-                       if (!((s->options & SSL_OP_TLS_ROLLBACK_BUG) &&
-                               (p[0] == (s->version>>8)) && (p[1] == (s->version & 0xff))))
-                               {
-                               al=SSL_AD_DECODE_ERROR;
-                               /* SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_PROTOCOL_VERSION_NUMBER); */
-
-                               /* The Klima-Pokorny-Rosa extension of Bleichenbacher's attack
-                                * (http://eprint.iacr.org/2003/052/) exploits the version
-                                * number check as a "bad version oracle" -- an alert would
-                                * reveal that the plaintext corresponding to some ciphertext
-                                * made up by the adversary is properly formatted except
-                                * that the version number is wrong.  To avoid such attacks,
-                                * we should treat this just like any other decryption error. */
-                               }
+               /* should be RAND_bytes, but we cannot work around a failure. */
+               if (RAND_pseudo_bytes(rand_premaster_secret,
+                                     sizeof(rand_premaster_secret)) <= 0)
+                       goto err;
+               decrypt_len = RSA_private_decrypt((int)n,p,p,rsa,RSA_PKCS1_PADDING);
+               ERR_clear_error();
+
+               /* decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH.
+                * decrypt_good will be 0xff if so and zero otherwise. */
+               decrypt_good = constant_time_eq_int_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH);
+
+               /* If the version in the decrypted pre-master secret is correct
+                * then version_good will be 0xff, otherwise it'll be zero.
+                * The Klima-Pokorny-Rosa extension of Bleichenbacher's attack
+                * (http://eprint.iacr.org/2003/052/) exploits the version
+                * number check as a "bad version oracle". Thus version checks
+                * are done in constant time and are treated like any other
+                * decryption error. */
+               version_good = constant_time_eq_8(p[0], (unsigned)(s->client_version>>8));
+               version_good &= constant_time_eq_8(p[1], (unsigned)(s->client_version&0xff));
+
+               /* The premaster secret must contain the same version number as
+                * the ClientHello to detect version rollback attacks
+                * (strangely, the protocol does not offer such protection for
+                * DH ciphersuites). However, buggy clients exist that send the
+                * negotiated protocol version instead if the server does not
+                * support the requested protocol version. If
+                * SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. */
+               if (s->options & SSL_OP_TLS_ROLLBACK_BUG)
+                       {
+                       unsigned char workaround_good;
+                       workaround_good = constant_time_eq_8(p[0], (unsigned)(s->version>>8));
+                       workaround_good &= constant_time_eq_8(p[1], (unsigned)(s->version&0xff));
+                       version_good |= workaround_good;
+                       }
+
+               /* Both decryption and version must be good for decrypt_good
+                * to remain non-zero (0xff). */
+               decrypt_good &= version_good;
+
+               /* Now copy rand_premaster_secret over p using
+                * decrypt_good_mask. */
+               for (i = 0; i < (int) sizeof(rand_premaster_secret); i++)
+                       {
+                       p[i] = constant_time_select_8(decrypt_good, p[i],
+                                                     rand_premaster_secret[i]);
                        }
 
-               if (al != -1)
-                       {
-                       /* Some decryption failure -- use random value instead as countermeasure
-                        * against Bleichenbacher's attack on PKCS #1 v1.5 RSA padding
-                        * (see RFC 2246, section 7.4.7.1). */
-                       ERR_clear_error();
-                       i = SSL_MAX_MASTER_KEY_LENGTH;
-                       p[0] = s->client_version >> 8;
-                       p[1] = s->client_version & 0xff;
-                       if (RAND_pseudo_bytes(p+2, i-2) <= 0) /* should be RAND_bytes, but we cannot work around a failure */
-                               goto err;
-                       }
-       
                s->session->master_key_length=
                        s->method->ssl3_enc->generate_master_secret(s,
                                s->session->master_key,
@@ -2232,10 +2386,15 @@ int ssl3_get_client_key_exchange(SSL *s)
        else
 #endif
 #ifndef OPENSSL_NO_DH
-               if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
+               if (alg_k & (SSL_kDHE|SSL_kDHr|SSL_kDHd))
                {
-               n2s(p,i);
-               if (n != i+2)
+               int idx = -1;
+               EVP_PKEY *skey = NULL;
+               if (n)
+                       n2s(p,i);
+               else
+                       i = 0;
+               if (n && n != i+2)
                        {
                        if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG))
                                {
@@ -2248,26 +2407,52 @@ int ssl3_get_client_key_exchange(SSL *s)
                                i=(int)n;
                                }
                        }
-
-               if (n == 0L) /* the parameters are in the cert */
+               if (alg_k & SSL_kDHr)
+                       idx = SSL_PKEY_DH_RSA;
+               else if (alg_k & SSL_kDHd)
+                       idx = SSL_PKEY_DH_DSA;
+               if (idx >= 0)
+                       {
+                       skey = s->cert->pkeys[idx].privatekey;
+                       if ((skey == NULL) ||
+                               (skey->type != EVP_PKEY_DH) ||
+                               (skey->pkey.dh == NULL))
+                               {
+                               al=SSL_AD_HANDSHAKE_FAILURE;
+                               SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_RSA_CERTIFICATE);
+                               goto f_err;
+                               }
+                       dh_srvr = skey->pkey.dh;
+                       }
+               else if (s->s3->tmp.dh == NULL)
                        {
                        al=SSL_AD_HANDSHAKE_FAILURE;
-                       SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_DECODE_DH_CERTS);
+                       SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
                        goto f_err;
                        }
                else
+                       dh_srvr=s->s3->tmp.dh;
+
+               if (n == 0L)
                        {
-                       if (s->s3->tmp.dh == NULL)
+                       /* Get pubkey from cert */
+                       EVP_PKEY *clkey=X509_get_pubkey(s->session->peer);
+                       if (clkey)
+                               {
+                               if (EVP_PKEY_cmp_parameters(clkey, skey) == 1)
+                                       dh_clnt = EVP_PKEY_get1_DH(clkey);
+                               }
+                       if (dh_clnt == NULL)
                                {
                                al=SSL_AD_HANDSHAKE_FAILURE;
                                SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
                                goto f_err;
                                }
-                       else
-                               dh_srvr=s->s3->tmp.dh;
+                       EVP_PKEY_free(clkey);
+                       pub = dh_clnt->pub_key;
                        }
-
-               pub=BN_bin2bn(p,i,NULL);
+               else
+                       pub=BN_bin2bn(p,i,NULL);
                if (pub == NULL)
                        {
                        SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BN_LIB);
@@ -2279,18 +2464,23 @@ int ssl3_get_client_key_exchange(SSL *s)
                if (i <= 0)
                        {
                        SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
+                       BN_clear_free(pub);
                        goto err;
                        }
 
                DH_free(s->s3->tmp.dh);
                s->s3->tmp.dh=NULL;
-
-               BN_clear_free(pub);
+               if (dh_clnt)
+                       DH_free(dh_clnt);
+               else
+                       BN_clear_free(pub);
                pub=NULL;
                s->session->master_key_length=
                        s->method->ssl3_enc->generate_master_secret(s,
                                s->session->master_key,p,i);
                OPENSSL_cleanse(p,i);
+               if (dh_clnt)
+                       return 2;
                }
        else
 #endif
@@ -2488,7 +2678,7 @@ int ssl3_get_client_key_exchange(SSL *s)
 #endif /* OPENSSL_NO_KRB5 */
 
 #ifndef OPENSSL_NO_ECDH
-               if (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe))
+               if (alg_k & (SSL_kECDHE|SSL_kECDHr|SSL_kECDHe))
                {
                int ret = 1;
                int field_size = 0;
@@ -2541,7 +2731,7 @@ int ssl3_get_client_key_exchange(SSL *s)
                        {
                        /* Client Publickey was in Client Certificate */
 
-                        if (alg_k & SSL_kEECDH)
+                        if (alg_k & SSL_kECDHE)
                                 {
                                 al=SSL_AD_HANDSHAKE_FAILURE;
                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY);
@@ -2756,6 +2946,13 @@ int ssl3_get_client_key_exchange(SSL *s)
                                SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_BN_LIB);
                                goto err;
                                }
+                       if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0
+                               || BN_is_zero(s->srp_ctx.A))
+                               {
+                               al=SSL_AD_ILLEGAL_PARAMETER;
+                               SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_SRP_PARAMETERS);
+                               goto f_err;
+                               }
                        if (s->session->srp_username != NULL)
                                OPENSSL_free(s->session->srp_username);
                        s->session->srp_username = BUF_strdup(s->srp_ctx.login);
@@ -2784,6 +2981,8 @@ int ssl3_get_client_key_exchange(SSL *s)
                        unsigned char premaster_secret[32], *start;
                        size_t outlen=32, inlen;
                        unsigned long alg_a;
+                       int Ttag, Tclass;
+                       long Tlen;
 
                        /* Get our certificate private key*/
                        alg_a = s->s3->tmp.new_cipher->algorithm_auth;
@@ -2805,26 +3004,15 @@ int ssl3_get_client_key_exchange(SSL *s)
                                        ERR_clear_error();
                                }
                        /* Decrypt session key */
-                       if ((*p!=( V_ASN1_SEQUENCE| V_ASN1_CONSTRUCTED))) 
-                               {
-                               SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DECRYPTION_FAILED);
-                               goto gerr;
-                               }
-                       if (p[1] == 0x81)
-                               {
-                               start = p+3;
-                               inlen = p[2];
-                               }
-                       else if (p[1] < 0x80)
-                               {
-                               start = p+2;
-                               inlen = p[1];
-                               }
-                       else
+                       if (ASN1_get_object((const unsigned char **)&p, &Tlen, &Ttag, &Tclass, n) != V_ASN1_CONSTRUCTED || 
+                               Ttag != V_ASN1_SEQUENCE ||
+                               Tclass != V_ASN1_UNIVERSAL) 
                                {
                                SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DECRYPTION_FAILED);
                                goto gerr;
                                }
+                       start = p;
+                       inlen = Tlen;
                        if (EVP_PKEY_decrypt(pkey_ctx,premaster_secret,&outlen,start,inlen) <=0) 
 
                                {
@@ -2888,7 +3076,7 @@ int ssl3_get_cert_verify(SSL *s)
                SSL3_ST_SR_CERT_VRFY_A,
                SSL3_ST_SR_CERT_VRFY_B,
                -1,
-               514, /* 514? */
+               SSL3_RT_MAX_PLAIN_LENGTH,
                &ok);
 
        if (!ok) return((int)n);
@@ -2908,7 +3096,7 @@ int ssl3_get_cert_verify(SSL *s)
        if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY)
                {
                s->s3->tmp.reuse_message=1;
-               if ((peer != NULL) && (type | EVP_PKT_SIGN))
+               if ((peer != NULL) && (type & EVP_PKT_SIGN))
                        {
                        al=SSL_AD_UNEXPECTED_MESSAGE;
                        SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_MISSING_VERIFY_MESSAGE);
@@ -2951,28 +3139,17 @@ int ssl3_get_cert_verify(SSL *s)
                } 
        else 
                {       
-               if (TLS1_get_version(s) >= TLS1_2_VERSION)
+               if (SSL_USE_SIGALGS(s))
                        {
-                       int sigalg = tls12_get_sigid(pkey);
-                       /* Should never happen */
-                       if (sigalg == -1)
+                       int rv = tls12_check_peer_sigalg(&md, s, p, pkey);
+                       if (rv == -1)
                                {
-                               SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,ERR_R_INTERNAL_ERROR);
-                               al=SSL_AD_INTERNAL_ERROR;
+                               al = SSL_AD_INTERNAL_ERROR;
                                goto f_err;
                                }
-                       /* Check key type is consistent with signature */
-                       if (sigalg != (int)p[1])
+                       else if (rv == 0)
                                {
-                               SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_WRONG_SIGNATURE_TYPE);
-                               al=SSL_AD_DECODE_ERROR;
-                               goto f_err;
-                               }
-                       md = tls12_get_hash(p[0]);
-                       if (md == NULL)
-                               {
-                               SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_UNKNOWN_DIGEST);
-                               al=SSL_AD_DECODE_ERROR;
+                               al = SSL_AD_DECODE_ERROR;
                                goto f_err;
                                }
 #ifdef SSL_DEBUG
@@ -2998,7 +3175,7 @@ fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
                goto f_err;
                }
 
-       if (TLS1_get_version(s) >= TLS1_2_VERSION)
+       if (SSL_USE_SIGALGS(s))
                {
                long hdatalen = 0;
                void *hdata;
@@ -3247,13 +3424,29 @@ int ssl3_get_client_certificate(SSL *s)
                }
        else
                {
+               EVP_PKEY *pkey;
                i=ssl_verify_cert_chain(s,sk);
                if (i <= 0)
                        {
                        al=ssl_verify_alarm_type(s->verify_result);
-                       SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_NO_CERTIFICATE_RETURNED);
+                       SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERTIFICATE_VERIFY_FAILED);
+                       goto f_err;
+                       }
+               if (i > 1)
+                       {
+                       SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, i);
+                       al = SSL_AD_HANDSHAKE_FAILURE;
+                       goto f_err;
+                       }
+               pkey = X509_get_pubkey(sk_X509_value(sk, 0));
+               if (pkey == NULL)
+                       {
+                       al=SSL3_AD_HANDSHAKE_FAILURE;
+                       SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
+                                               SSL_R_UNKNOWN_CERTIFICATE_TYPE);
                        goto f_err;
                        }
+               EVP_PKEY_free(pkey);
                }
 
        if (s->session->peer != NULL) /* This should not be needed */
@@ -3294,13 +3487,12 @@ err:
 
 int ssl3_send_server_certificate(SSL *s)
        {
-       unsigned long l;
-       X509 *x;
+       CERT_PKEY *cpk;
 
        if (s->state == SSL3_ST_SW_CERT_A)
                {
-               x=ssl_get_server_send_cert(s);
-               if (x == NULL)
+               cpk=ssl_get_server_send_pkey(s);
+               if (cpk == NULL)
                        {
                        /* VRS: allow null cert if auth == KRB5 */
                        if ((s->s3->tmp.new_cipher->algorithm_auth != SSL_aKRB5) ||
@@ -3311,14 +3503,16 @@ int ssl3_send_server_certificate(SSL *s)
                                }
                        }
 
-               l=ssl3_output_cert_chain(s,x);
+               if (!ssl3_output_cert_chain(s,cpk))
+                       {
+                       SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,ERR_R_INTERNAL_ERROR);
+                       return(0);
+                       }
                s->state=SSL3_ST_SW_CERT_B;
-               s->init_num=(int)l;
-               s->init_off=0;
                }
 
        /* SSL3_ST_SW_CERT_B */
-       return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
+       return ssl_do_write(s);
        }
 
 #ifndef OPENSSL_NO_TLSEXT
@@ -3372,22 +3566,17 @@ int ssl3_send_newsession_ticket(SSL *s)
                SSL_SESSION_free(sess);
 
                /* Grow buffer if need be: the length calculation is as
-                * follows 1 (size of message name) + 3 (message length
-                * bytes) + 4 (ticket lifetime hint) + 2 (ticket length) +
+                * follows handshake_header_length +
+                * 4 (ticket lifetime hint) + 2 (ticket length) +
                 * 16 (key name) + max_iv_len (iv length) +
                 * session_length + max_enc_block_size (max encrypted session
                 * length) + max_md_size (HMAC).
                 */
                if (!BUF_MEM_grow(s->init_buf,
-                       26 + EVP_MAX_IV_LENGTH + EVP_MAX_BLOCK_LENGTH +
-                       EVP_MAX_MD_SIZE + slen))
+                       SSL_HM_HEADER_LENGTH(s) + 22 + EVP_MAX_IV_LENGTH +
+                       EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE + slen))
                        return -1;
-
-               p=(unsigned char *)s->init_buf->data;
-               /* do the header */
-               *(p++)=SSL3_MT_NEWSESSION_TICKET;
-               /* Skip message length for now */
-               p += 3;
+               p = ssl_handshake_start(s);
                EVP_CIPHER_CTX_init(&ctx);
                HMAC_CTX_init(&hctx);
                /* Initialize HMAC and cipher contexts. If callback present
@@ -3442,21 +3631,17 @@ int ssl3_send_newsession_ticket(SSL *s)
                p += hlen;
                /* Now write out lengths: p points to end of data written */
                /* Total length */
-               len = p - (unsigned char *)s->init_buf->data;
-               p=(unsigned char *)s->init_buf->data + 1;
-               l2n3(len - 4, p); /* Message length */
-               p += 4;
-               s2n(len - 10, p);  /* Ticket length */
-
-               /* number of bytes to write */
-               s->init_num= len;
+               len = p - ssl_handshake_start(s);
+               ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len);
+               /* Skip ticket lifetime hint */
+               p = ssl_handshake_start(s) + 4;
+               s2n(len - 6, p);
                s->state=SSL3_ST_SW_SESSION_TICKET_B;
-               s->init_off=0;
                OPENSSL_free(senc);
                }
 
        /* SSL3_ST_SW_SESSION_TICKET_B */
-       return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
+       return ssl_do_write(s);
        }
 
 int ssl3_send_cert_status(SSL *s)
@@ -3494,7 +3679,7 @@ int ssl3_send_cert_status(SSL *s)
        return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
        }
 
-# ifndef OPENSSL_NO_NPN
+# ifndef OPENSSL_NO_NEXTPROTONEG
 /* 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)
@@ -3561,4 +3746,5 @@ int ssl3_get_next_proto(SSL *s)
        return 1;
        }
 # endif
+
 #endif