e6aa1d3892de32c2db569dacc31b8a06da38b071
[openssl.git] / ssl / s3_srvr.c
1 /* ssl/s3_srvr.c -*- mode:C; c-file-style: "eay" -*- */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer.
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111 /* ====================================================================
112  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
113  *
114  * Portions of the attached software ("Contribution") are developed by
115  * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
116  *
117  * The Contribution is licensed pursuant to the OpenSSL open source
118  * license provided above.
119  *
120  * ECC cipher suite support in OpenSSL originally written by
121  * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
122  *
123  */
124 /* ====================================================================
125  * Copyright 2005 Nokia. All rights reserved.
126  *
127  * The portions of the attached software ("Contribution") is developed by
128  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
129  * license.
130  *
131  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
132  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
133  * support (see RFC 4279) to OpenSSL.
134  *
135  * No patent licenses or other rights except those expressly stated in
136  * the OpenSSL open source license shall be deemed granted or received
137  * expressly, by implication, estoppel, or otherwise.
138  *
139  * No assurances are provided by Nokia that the Contribution does not
140  * infringe the patent or other intellectual property rights of any third
141  * party or that the license provides you with all the necessary rights
142  * to make use of the Contribution.
143  *
144  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
145  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
146  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
147  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
148  * OTHERWISE.
149  */
150
151
152 #include <stdio.h>
153 #include "ssl_locl.h"
154 #include "internal/constant_time_locl.h"
155 #include <openssl/buffer.h>
156 #include <openssl/rand.h>
157 #include <openssl/objects.h>
158 #include <openssl/evp.h>
159 #include <openssl/hmac.h>
160 #include <openssl/x509.h>
161 #ifndef OPENSSL_NO_DH
162 # include <openssl/dh.h>
163 #endif
164 #include <openssl/bn.h>
165 #include <openssl/md5.h>
166
167 static STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list(SSL *s, unsigned char *p,
168     int num, STACK_OF(SSL_CIPHER) **skp, int sslv2format);
169
170
171 #ifndef OPENSSL_NO_SRP
172 static int ssl_check_srp_ext_ClientHello(SSL *s, int *al)
173 {
174     int ret = SSL_ERROR_NONE;
175
176     *al = SSL_AD_UNRECOGNIZED_NAME;
177
178     if ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) &&
179         (s->srp_ctx.TLS_ext_srp_username_callback != NULL)) {
180         if (s->srp_ctx.login == NULL) {
181             /*
182              * RFC 5054 says SHOULD reject, we do so if There is no srp
183              * login name
184              */
185             ret = SSL3_AL_FATAL;
186             *al = SSL_AD_UNKNOWN_PSK_IDENTITY;
187         } else {
188             ret = SSL_srp_server_param_with_username(s, al);
189         }
190     }
191     return ret;
192 }
193 #endif
194
195 int ssl3_accept(SSL *s)
196 {
197     BUF_MEM *buf;
198     unsigned long alg_k, Time = (unsigned long)time(NULL);
199     void (*cb) (const SSL *ssl, int type, int val) = NULL;
200     int ret = -1;
201     int new_state, state, skip = 0;
202
203     RAND_add(&Time, sizeof(Time), 0);
204     ERR_clear_error();
205     clear_sys_error();
206
207     if (s->info_callback != NULL)
208         cb = s->info_callback;
209     else if (s->ctx->info_callback != NULL)
210         cb = s->ctx->info_callback;
211
212     /* init things to blank */
213     s->in_handshake++;
214     if (!SSL_in_init(s) || SSL_in_before(s)) {
215         if (!SSL_clear(s))
216             return -1;
217     }
218
219 #ifndef OPENSSL_NO_HEARTBEATS
220     /*
221      * If we're awaiting a HeartbeatResponse, pretend we already got and
222      * don't await it anymore, because Heartbeats don't make sense during
223      * handshakes anyway.
224      */
225     if (s->tlsext_hb_pending) {
226         s->tlsext_hb_pending = 0;
227         s->tlsext_hb_seq++;
228     }
229 #endif
230
231     for (;;) {
232         state = s->state;
233
234         switch (s->state) {
235         case SSL_ST_RENEGOTIATE:
236             s->renegotiate = 1;
237             /* s->state=SSL_ST_ACCEPT; */
238
239         case SSL_ST_BEFORE:
240         case SSL_ST_ACCEPT:
241         case SSL_ST_BEFORE | SSL_ST_ACCEPT:
242         case SSL_ST_OK | SSL_ST_ACCEPT:
243
244             s->server = 1;
245             if (cb != NULL)
246                 cb(s, SSL_CB_HANDSHAKE_START, 1);
247
248             if ((s->version >> 8 != 3) && s->version != TLS_ANY_VERSION) {
249                 SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
250                 s->state = SSL_ST_ERR;
251                 return -1;
252             }
253
254             if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL)) {
255                 SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_VERSION_TOO_LOW);
256                 return -1;
257             }
258
259             s->type = SSL_ST_ACCEPT;
260
261             if (s->init_buf == NULL) {
262                 if ((buf = BUF_MEM_new()) == NULL) {
263                     ret = -1;
264                     s->state = SSL_ST_ERR;
265                     goto end;
266                 }
267                 if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
268                     BUF_MEM_free(buf);
269                     ret = -1;
270                     s->state = SSL_ST_ERR;
271                     goto end;
272                 }
273                 s->init_buf = buf;
274             }
275
276             if (!ssl3_setup_buffers(s)) {
277                 ret = -1;
278                 s->state = SSL_ST_ERR;
279                 goto end;
280             }
281
282             s->init_num = 0;
283             s->s3->flags &= ~TLS1_FLAGS_SKIP_CERT_VERIFY;
284             s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
285             /*
286              * Should have been reset by ssl3_get_finished, too.
287              */
288             s->s3->change_cipher_spec = 0;
289
290             if (s->state != SSL_ST_RENEGOTIATE) {
291                 /*
292                  * Ok, we now need to push on a buffering BIO so that the
293                  * output is sent in a way that TCP likes :-)
294                  */
295                 if (!ssl_init_wbio_buffer(s, 1)) {
296                     ret = -1;
297                     s->state = SSL_ST_ERR;
298                     goto end;
299                 }
300
301                 ssl3_init_finished_mac(s);
302                 s->state = SSL3_ST_SR_CLNT_HELLO_A;
303                 s->ctx->stats.sess_accept++;
304             } else if (!s->s3->send_connection_binding &&
305                        !(s->options &
306                          SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
307                 /*
308                  * Server attempting to renegotiate with client that doesn't
309                  * support secure renegotiation.
310                  */
311                 SSLerr(SSL_F_SSL3_ACCEPT,
312                        SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
313                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
314                 ret = -1;
315                 s->state = SSL_ST_ERR;
316                 goto end;
317             } else {
318                 /*
319                  * s->state == SSL_ST_RENEGOTIATE, we will just send a
320                  * HelloRequest
321                  */
322                 s->ctx->stats.sess_accept_renegotiate++;
323                 s->state = SSL3_ST_SW_HELLO_REQ_A;
324             }
325             break;
326
327         case SSL3_ST_SW_HELLO_REQ_A:
328         case SSL3_ST_SW_HELLO_REQ_B:
329
330             s->shutdown = 0;
331             ret = ssl3_send_hello_request(s);
332             if (ret <= 0)
333                 goto end;
334             s->s3->tmp.next_state = SSL3_ST_SW_HELLO_REQ_C;
335             s->state = SSL3_ST_SW_FLUSH;
336             s->init_num = 0;
337
338             ssl3_init_finished_mac(s);
339             break;
340
341         case SSL3_ST_SW_HELLO_REQ_C:
342             s->state = SSL_ST_OK;
343             break;
344
345         case SSL3_ST_SR_CLNT_HELLO_A:
346         case SSL3_ST_SR_CLNT_HELLO_B:
347         case SSL3_ST_SR_CLNT_HELLO_C:
348
349             ret = ssl3_get_client_hello(s);
350             if (ret <= 0)
351                 goto end;
352 #ifndef OPENSSL_NO_SRP
353             s->state = SSL3_ST_SR_CLNT_HELLO_D;
354         case SSL3_ST_SR_CLNT_HELLO_D:
355             {
356                 int al;
357                 if ((ret = ssl_check_srp_ext_ClientHello(s, &al)) < 0) {
358                     /*
359                      * callback indicates firther work to be done
360                      */
361                     s->rwstate = SSL_X509_LOOKUP;
362                     goto end;
363                 }
364                 if (ret != SSL_ERROR_NONE) {
365                     ssl3_send_alert(s, SSL3_AL_FATAL, al);
366                     /*
367                      * This is not really an error but the only means to for
368                      * a client to detect whether srp is supported.
369                      */
370                     if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)
371                         SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_CLIENTHELLO_TLSEXT);
372                     ret = SSL_TLSEXT_ERR_ALERT_FATAL;
373                     ret = -1;
374                     s->state = SSL_ST_ERR;
375                     goto end;
376                 }
377             }
378 #endif
379
380             s->renegotiate = 2;
381             s->state = SSL3_ST_SW_SRVR_HELLO_A;
382             s->init_num = 0;
383             break;
384
385         case SSL3_ST_SW_SRVR_HELLO_A:
386         case SSL3_ST_SW_SRVR_HELLO_B:
387             ret = ssl3_send_server_hello(s);
388             if (ret <= 0)
389                 goto end;
390
391             if (s->hit) {
392                 if (s->tlsext_ticket_expected)
393                     s->state = SSL3_ST_SW_SESSION_TICKET_A;
394                 else
395                     s->state = SSL3_ST_SW_CHANGE_A;
396             } else {
397                 s->state = SSL3_ST_SW_CERT_A;
398             }
399             s->init_num = 0;
400             break;
401
402         case SSL3_ST_SW_CERT_A:
403         case SSL3_ST_SW_CERT_B:
404             /* Check if it is anon DH or anon ECDH, */
405             /* normal PSK or SRP */
406             if (!
407                 (s->s3->tmp.
408                  new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP))
409 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
410                 ret = ssl3_send_server_certificate(s);
411                 if (ret <= 0)
412                     goto end;
413
414                 if (s->tlsext_status_expected)
415                     s->state = SSL3_ST_SW_CERT_STATUS_A;
416                 else
417                     s->state = SSL3_ST_SW_KEY_EXCH_A;
418             } else {
419                 skip = 1;
420                 s->state = SSL3_ST_SW_KEY_EXCH_A;
421             }
422             s->init_num = 0;
423             break;
424
425         case SSL3_ST_SW_KEY_EXCH_A:
426         case SSL3_ST_SW_KEY_EXCH_B:
427             alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
428
429             /*
430              * clear this, it may get reset by
431              * send_server_key_exchange
432              */
433             s->s3->tmp.use_rsa_tmp = 0;
434
435             /*
436              * only send if a DH key exchange, fortezza or RSA but we have a
437              * sign only certificate PSK: may send PSK identity hints For
438              * ECC ciphersuites, we send a serverKeyExchange message only if
439              * the cipher suite is either ECDH-anon or ECDHE. In other cases,
440              * the server certificate contains the server's public key for
441              * key exchange.
442              */
443             if (0
444                 /*
445                  * PSK: send ServerKeyExchange if PSK identity hint if
446                  * provided
447                  */
448 #ifndef OPENSSL_NO_PSK
449                 || ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint)
450 #endif
451 #ifndef OPENSSL_NO_SRP
452                 /* SRP: send ServerKeyExchange */
453                 || (alg_k & SSL_kSRP)
454 #endif
455                 || (alg_k & SSL_kDHE)
456                 || (alg_k & SSL_kECDHE)
457                 || ((alg_k & SSL_kRSA)
458                     && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
459                         || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
460                             && EVP_PKEY_size(s->cert->pkeys
461                                              [SSL_PKEY_RSA_ENC].privatekey) *
462                             8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
463                         )
464                     )
465                 )
466                 ) {
467                 ret = ssl3_send_server_key_exchange(s);
468                 if (ret <= 0)
469                     goto end;
470             } else
471                 skip = 1;
472
473             s->state = SSL3_ST_SW_CERT_REQ_A;
474             s->init_num = 0;
475             break;
476
477         case SSL3_ST_SW_CERT_REQ_A:
478         case SSL3_ST_SW_CERT_REQ_B:
479             if (                /* don't request cert unless asked for it: */
480                    !(s->verify_mode & SSL_VERIFY_PEER) ||
481                    /*
482                     * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert
483                     * during re-negotiation:
484                     */
485                    ((s->session->peer != NULL) &&
486                     (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
487                    /*
488                     * never request cert in anonymous ciphersuites (see
489                     * section "Certificate request" in SSL 3 drafts and in
490                     * RFC 2246):
491                     */
492                    ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
493                    /*
494                     * ... except when the application insists on
495                     * verification (against the specs, but s3_clnt.c accepts
496                     * this for SSL 3)
497                     */
498                    !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
499                    /* don't request certificate for SRP auth */
500                    (s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)
501                    /*
502                     * With normal PSK Certificates and Certificate Requests
503                     * are omitted
504                     */
505                    || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
506                 /* no cert request */
507                 skip = 1;
508                 s->s3->tmp.cert_request = 0;
509                 s->state = SSL3_ST_SW_SRVR_DONE_A;
510                 if (s->s3->handshake_buffer) {
511                     if (!ssl3_digest_cached_records(s)) {
512                         s->state = SSL_ST_ERR;
513                         return -1;
514                     }
515                 }
516             } else {
517                 s->s3->tmp.cert_request = 1;
518                 ret = ssl3_send_certificate_request(s);
519                 if (ret <= 0)
520                     goto end;
521                 s->state = SSL3_ST_SW_SRVR_DONE_A;
522                 s->init_num = 0;
523             }
524             break;
525
526         case SSL3_ST_SW_SRVR_DONE_A:
527         case SSL3_ST_SW_SRVR_DONE_B:
528             ret = ssl3_send_server_done(s);
529             if (ret <= 0)
530                 goto end;
531             s->s3->tmp.next_state = SSL3_ST_SR_CERT_A;
532             s->state = SSL3_ST_SW_FLUSH;
533             s->init_num = 0;
534             break;
535
536         case SSL3_ST_SW_FLUSH:
537
538             /*
539              * This code originally checked to see if any data was pending
540              * using BIO_CTRL_INFO and then flushed. This caused problems as
541              * documented in PR#1939. The proposed fix doesn't completely
542              * resolve this issue as buggy implementations of
543              * BIO_CTRL_PENDING still exist. So instead we just flush
544              * unconditionally.
545              */
546
547             s->rwstate = SSL_WRITING;
548             if (BIO_flush(s->wbio) <= 0) {
549                 ret = -1;
550                 goto end;
551             }
552             s->rwstate = SSL_NOTHING;
553
554             s->state = s->s3->tmp.next_state;
555             break;
556
557         case SSL3_ST_SR_CERT_A:
558         case SSL3_ST_SR_CERT_B:
559             if (s->s3->tmp.cert_request) {
560                 ret = ssl3_get_client_certificate(s);
561                 if (ret <= 0)
562                     goto end;
563             }
564             s->init_num = 0;
565             s->state = SSL3_ST_SR_KEY_EXCH_A;
566             break;
567
568         case SSL3_ST_SR_KEY_EXCH_A:
569         case SSL3_ST_SR_KEY_EXCH_B:
570             ret = ssl3_get_client_key_exchange(s);
571             if (ret <= 0)
572                 goto end;
573             if (ret == 2) {
574                 /*
575                  * For the ECDH ciphersuites when the client sends its ECDH
576                  * pub key in a certificate, the CertificateVerify message is
577                  * not sent. Also for GOST ciphersuites when the client uses
578                  * its key from the certificate for key exchange.
579                  */
580 #if defined(OPENSSL_NO_NEXTPROTONEG)
581                 s->state = SSL3_ST_SR_FINISHED_A;
582 #else
583                 if (s->s3->next_proto_neg_seen)
584                     s->state = SSL3_ST_SR_NEXT_PROTO_A;
585                 else
586                     s->state = SSL3_ST_SR_FINISHED_A;
587 #endif
588                 s->init_num = 0;
589             } else if (SSL_USE_SIGALGS(s)) {
590                 s->state = SSL3_ST_SR_CERT_VRFY_A;
591                 s->init_num = 0;
592                 if (!s->session->peer)
593                     break;
594                 if (!s->s3->handshake_buffer) {
595                     SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
596                     s->state = SSL_ST_ERR;
597                     return -1;
598                 }
599                 /*
600                  * For sigalgs freeze the handshake buffer. If we support
601                  * extms we've done this already.
602                  */
603                 if (!(s->s3->flags & SSL_SESS_FLAG_EXTMS)) {
604                     s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE;
605                     if (!ssl3_digest_cached_records(s)) {
606                         s->state = SSL_ST_ERR;
607                         return -1;
608                     }
609                 }
610             } else {
611                 int offset = 0;
612                 int dgst_num;
613
614                 s->state = SSL3_ST_SR_CERT_VRFY_A;
615                 s->init_num = 0;
616
617                 /*
618                  * We need to get hashes here so if there is a client cert,
619                  * it can be verified FIXME - digest processing for
620                  * CertificateVerify should be generalized. But it is next
621                  * step
622                  */
623                 if (s->s3->handshake_buffer) {
624                     if (!ssl3_digest_cached_records(s)) {
625                         s->state = SSL_ST_ERR;
626                         return -1;
627                     }
628                 }
629                 for (dgst_num = 0; dgst_num < SSL_MAX_DIGEST; dgst_num++)
630                     if (s->s3->handshake_dgst[dgst_num]) {
631                         int dgst_size;
632
633                         s->method->ssl3_enc->cert_verify_mac(s,
634                                                              EVP_MD_CTX_type
635                                                              (s->
636                                                               s3->handshake_dgst
637                                                               [dgst_num]),
638                                                              &(s->s3->
639                                                                tmp.cert_verify_md
640                                                                [offset]));
641                         dgst_size =
642                             EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]);
643                         if (dgst_size < 0) {
644                             s->state = SSL_ST_ERR;
645                             ret = -1;
646                             goto end;
647                         }
648                         offset += dgst_size;
649                     }
650             }
651             break;
652
653         case SSL3_ST_SR_CERT_VRFY_A:
654         case SSL3_ST_SR_CERT_VRFY_B:
655             ret = ssl3_get_cert_verify(s);
656             if (ret <= 0)
657                 goto end;
658
659 #if defined(OPENSSL_NO_NEXTPROTONEG)
660             s->state = SSL3_ST_SR_FINISHED_A;
661 #else
662             if (s->s3->next_proto_neg_seen)
663                 s->state = SSL3_ST_SR_NEXT_PROTO_A;
664             else
665                 s->state = SSL3_ST_SR_FINISHED_A;
666 #endif
667             s->init_num = 0;
668             break;
669
670 #if !defined(OPENSSL_NO_NEXTPROTONEG)
671         case SSL3_ST_SR_NEXT_PROTO_A:
672         case SSL3_ST_SR_NEXT_PROTO_B:
673             /*
674              * Enable CCS for NPN. Receiving a CCS clears the flag, so make
675              * sure not to re-enable it to ban duplicates. This *should* be the
676              * first time we have received one - but we check anyway to be
677              * cautious.
678              * s->s3->change_cipher_spec is set when a CCS is
679              * processed in s3_pkt.c, and remains set until
680              * the client's Finished message is read.
681              */
682             if (!s->s3->change_cipher_spec)
683                 s->s3->flags |= SSL3_FLAGS_CCS_OK;
684
685             ret = ssl3_get_next_proto(s);
686             if (ret <= 0)
687                 goto end;
688             s->init_num = 0;
689             s->state = SSL3_ST_SR_FINISHED_A;
690             break;
691 #endif
692
693         case SSL3_ST_SR_FINISHED_A:
694         case SSL3_ST_SR_FINISHED_B:
695             /*
696              * Enable CCS for handshakes without NPN. In NPN the CCS flag has
697              * already been set. Receiving a CCS clears the flag, so make
698              * sure not to re-enable it to ban duplicates.
699              * s->s3->change_cipher_spec is set when a CCS is
700              * processed in s3_pkt.c, and remains set until
701              * the client's Finished message is read.
702              */
703             if (!s->s3->change_cipher_spec)
704                 s->s3->flags |= SSL3_FLAGS_CCS_OK;
705             ret = ssl3_get_finished(s, SSL3_ST_SR_FINISHED_A,
706                                     SSL3_ST_SR_FINISHED_B);
707             if (ret <= 0)
708                 goto end;
709             if (s->hit)
710                 s->state = SSL_ST_OK;
711             else if (s->tlsext_ticket_expected)
712                 s->state = SSL3_ST_SW_SESSION_TICKET_A;
713             else
714                 s->state = SSL3_ST_SW_CHANGE_A;
715             s->init_num = 0;
716             break;
717
718         case SSL3_ST_SW_SESSION_TICKET_A:
719         case SSL3_ST_SW_SESSION_TICKET_B:
720             ret = ssl3_send_newsession_ticket(s);
721             if (ret <= 0)
722                 goto end;
723             s->state = SSL3_ST_SW_CHANGE_A;
724             s->init_num = 0;
725             break;
726
727         case SSL3_ST_SW_CERT_STATUS_A:
728         case SSL3_ST_SW_CERT_STATUS_B:
729             ret = ssl3_send_cert_status(s);
730             if (ret <= 0)
731                 goto end;
732             s->state = SSL3_ST_SW_KEY_EXCH_A;
733             s->init_num = 0;
734             break;
735
736         case SSL3_ST_SW_CHANGE_A:
737         case SSL3_ST_SW_CHANGE_B:
738
739             s->session->cipher = s->s3->tmp.new_cipher;
740             if (!s->method->ssl3_enc->setup_key_block(s)) {
741                 ret = -1;
742                 s->state = SSL_ST_ERR;
743                 goto end;
744             }
745
746             ret = ssl3_send_change_cipher_spec(s,
747                                                SSL3_ST_SW_CHANGE_A,
748                                                SSL3_ST_SW_CHANGE_B);
749
750             if (ret <= 0)
751                 goto end;
752             s->state = SSL3_ST_SW_FINISHED_A;
753             s->init_num = 0;
754
755             if (!s->method->ssl3_enc->change_cipher_state(s,
756                                                           SSL3_CHANGE_CIPHER_SERVER_WRITE))
757             {
758                 ret = -1;
759                 s->state = SSL_ST_ERR;
760                 goto end;
761             }
762
763             break;
764
765         case SSL3_ST_SW_FINISHED_A:
766         case SSL3_ST_SW_FINISHED_B:
767             ret = ssl3_send_finished(s,
768                                      SSL3_ST_SW_FINISHED_A,
769                                      SSL3_ST_SW_FINISHED_B,
770                                      s->method->
771                                      ssl3_enc->server_finished_label,
772                                      s->method->
773                                      ssl3_enc->server_finished_label_len);
774             if (ret <= 0)
775                 goto end;
776             s->state = SSL3_ST_SW_FLUSH;
777             if (s->hit) {
778 #if defined(OPENSSL_NO_NEXTPROTONEG)
779                 s->s3->tmp.next_state = SSL3_ST_SR_FINISHED_A;
780 #else
781                 if (s->s3->next_proto_neg_seen) {
782                     s->s3->tmp.next_state = SSL3_ST_SR_NEXT_PROTO_A;
783                 } else
784                     s->s3->tmp.next_state = SSL3_ST_SR_FINISHED_A;
785 #endif
786             } else
787                 s->s3->tmp.next_state = SSL_ST_OK;
788             s->init_num = 0;
789             break;
790
791         case SSL_ST_OK:
792             /* clean a few things up */
793             ssl3_cleanup_key_block(s);
794
795             BUF_MEM_free(s->init_buf);
796             s->init_buf = NULL;
797
798             /* remove buffering on output */
799             ssl_free_wbio_buffer(s);
800
801             s->init_num = 0;
802
803             if (s->renegotiate == 2) { /* skipped if we just sent a
804                                         * HelloRequest */
805                 s->renegotiate = 0;
806                 s->new_session = 0;
807
808                 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
809
810                 s->ctx->stats.sess_accept_good++;
811                 /* s->server=1; */
812                 s->handshake_func = ssl3_accept;
813
814                 if (cb != NULL)
815                     cb(s, SSL_CB_HANDSHAKE_DONE, 1);
816             }
817
818             ret = 1;
819             goto end;
820             /* break; */
821
822         case SSL_ST_ERR:
823         default:
824             SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNKNOWN_STATE);
825             ret = -1;
826             goto end;
827             /* break; */
828         }
829
830         if (!s->s3->tmp.reuse_message && !skip) {
831             if (s->debug) {
832                 if ((ret = BIO_flush(s->wbio)) <= 0)
833                     goto end;
834             }
835
836             if ((cb != NULL) && (s->state != state)) {
837                 new_state = s->state;
838                 s->state = state;
839                 cb(s, SSL_CB_ACCEPT_LOOP, 1);
840                 s->state = new_state;
841             }
842         }
843         skip = 0;
844     }
845  end:
846     /* BIO_flush(s->wbio); */
847
848     s->in_handshake--;
849     if (cb != NULL)
850         cb(s, SSL_CB_ACCEPT_EXIT, ret);
851     return (ret);
852 }
853
854 int ssl3_send_hello_request(SSL *s)
855 {
856
857     if (s->state == SSL3_ST_SW_HELLO_REQ_A) {
858         if (!ssl_set_handshake_header(s, SSL3_MT_HELLO_REQUEST, 0)) {
859             SSLerr(SSL_F_SSL3_SEND_HELLO_REQUEST, ERR_R_INTERNAL_ERROR);
860             return -1;
861         }
862         s->state = SSL3_ST_SW_HELLO_REQ_B;
863     }
864
865     /* SSL3_ST_SW_HELLO_REQ_B */
866     return ssl_do_write(s);
867 }
868
869 int ssl3_get_client_hello(SSL *s)
870 {
871     int i, complen, j, ok, al = SSL_AD_INTERNAL_ERROR, ret = -1;
872     unsigned int cookie_len;
873     long n;
874     unsigned long id;
875     unsigned char *p, *d;
876     SSL_CIPHER *c;
877 #ifndef OPENSSL_NO_COMP
878     unsigned char *q = NULL;
879     SSL_COMP *comp = NULL;
880 #endif
881     STACK_OF(SSL_CIPHER) *ciphers = NULL;
882     int protverr = 1;
883
884     if (s->state == SSL3_ST_SR_CLNT_HELLO_C && !s->first_packet)
885         goto retry_cert;
886
887     /*
888      * We do this so that we will respond with our native type. If we are
889      * TLSv1 and we get SSLv3, we will respond with TLSv1, This down
890      * switching should be handled by a different method. If we are SSLv3, we
891      * will respond with SSLv3, even if prompted with TLSv1.
892      */
893     if (s->state == SSL3_ST_SR_CLNT_HELLO_A) {
894         s->state = SSL3_ST_SR_CLNT_HELLO_B;
895     }
896     s->first_packet = 1;
897     n = s->method->ssl_get_message(s,
898                                    SSL3_ST_SR_CLNT_HELLO_B,
899                                    SSL3_ST_SR_CLNT_HELLO_C,
900                                    SSL3_MT_CLIENT_HELLO,
901                                    SSL3_RT_MAX_PLAIN_LENGTH, &ok);
902
903     if (!ok)
904         return ((int)n);
905     s->first_packet = 0;
906     d = p = (unsigned char *)s->init_msg;
907
908     /* First lets get s->client_version set correctly */
909     if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
910         /*-
911          * An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2
912          * header is sent directly on the wire, not wrapped as a TLS
913          * record. Our record layer just processes the message length and passes
914          * the rest right through. Its format is:
915          * Byte  Content
916          * 0-1   msg_length - decoded by the record layer
917          * 2     msg_type - s->init_msg points here
918          * 3-4   version
919          * 5-6   cipher_spec_length
920          * 7-8   session_id_length
921          * 9-10  challenge_length
922          * ...   ...
923          */
924
925         if (p[0] != SSL2_MT_CLIENT_HELLO) {
926             /*
927              * Should never happen. We should have tested this in the record
928              * layer in order to have determined that this is a SSLv2 record
929              * in the first place
930              */
931             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
932             goto err;
933         }
934
935         if ((p[1] == 0x00) && (p[2] == 0x02)) {
936             /* This is real SSLv2. We don't support it. */
937             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
938             goto err;
939         } else if (p[1] == SSL3_VERSION_MAJOR) {
940             /* SSLv3/TLS */
941             s->client_version = (((int)p[1]) << 8) | (int)p[2];
942         } else {
943             /* No idea what protocol this is */
944             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
945             goto err;
946         }
947     } else {
948         /*
949          * 2 bytes for client version, SSL3_RANDOM_SIZE bytes for random, 1 byte
950          * for session id length
951          */
952         if (n < 2 + SSL3_RANDOM_SIZE + 1) {
953             al = SSL_AD_DECODE_ERROR;
954             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
955             goto f_err;
956         }
957
958         /*
959          * use version from inside client hello, not from record header (may
960          * differ: see RFC 2246, Appendix E, second paragraph)
961          */
962         s->client_version = (((int)p[0]) << 8) | (int)p[1];
963     }
964
965     /* Do SSL/TLS version negotiation if applicable */
966     if (!SSL_IS_DTLS(s)) {
967         if (s->version != TLS_ANY_VERSION) {
968             if (s->client_version >= s->version) {
969                 protverr = 0;
970             }
971         } else if (s->client_version >= SSL3_VERSION) {
972             switch(s->client_version) {
973             default:
974             case TLS1_2_VERSION:
975                 if(!(s->options & SSL_OP_NO_TLSv1_2)) {
976                     s->version = TLS1_2_VERSION;
977                     s->method = TLSv1_2_server_method();
978                     protverr = 0;
979                     break;
980                 }
981                 /* Deliberately fall through */
982             case TLS1_1_VERSION:
983                 if(!(s->options & SSL_OP_NO_TLSv1_1)) {
984                     s->version = TLS1_1_VERSION;
985                     s->method = TLSv1_1_server_method();
986                     protverr = 0;
987                     break;
988                 }
989                 /* Deliberately fall through */
990             case TLS1_VERSION:
991                 if(!(s->options & SSL_OP_NO_TLSv1)) {
992                     s->version = TLS1_VERSION;
993                     s->method = TLSv1_server_method();
994                     protverr = 0;
995                     break;
996                 }
997                 /* Deliberately fall through */
998             case SSL3_VERSION:
999 #ifndef OPENSSL_NO_SSL3
1000                 if(!(s->options & SSL_OP_NO_SSLv3)) {
1001                     s->version = SSL3_VERSION;
1002                     s->method = SSLv3_server_method();
1003                     protverr = 0;
1004                     break;
1005                 }
1006 #else
1007                 break;
1008 #endif
1009             }
1010         }
1011     } else if (s->client_version <= s->version
1012                 || s->method->version == DTLS_ANY_VERSION) {
1013         /*
1014          * For DTLS we just check versions are potentially compatible. Version
1015          * negotiation comes later.
1016          */
1017         protverr = 0;
1018     }
1019
1020     if (protverr) {
1021         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
1022         if ((!s->enc_write_ctx && !s->write_hash)) {
1023             /*
1024              * similar to ssl3_get_record, send alert using remote version
1025              * number
1026              */
1027             s->version = s->client_version;
1028         }
1029         al = SSL_AD_PROTOCOL_VERSION;
1030         goto f_err;
1031     }
1032
1033     if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1034         /*
1035          * Handle an SSLv2 backwards compatible ClientHello
1036          * Note, this is only for SSLv3+ using the backward compatible format.
1037          * Real SSLv2 is not supported, and is rejected above.
1038          */
1039         unsigned int csl, sil, cl;
1040
1041         p += 3;
1042         n2s(p, csl);
1043         n2s(p, sil);
1044         n2s(p, cl);
1045
1046         if (csl + sil + cl + MIN_SSL2_RECORD_LEN != (unsigned int) n) {
1047             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_RECORD_LENGTH_MISMATCH);
1048             al = SSL_AD_DECODE_ERROR;
1049             goto f_err;
1050         }
1051
1052         if (csl == 0) {
1053             /* we need at least one cipher */
1054             al = SSL_AD_ILLEGAL_PARAMETER;
1055             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_CIPHERS_SPECIFIED);
1056             goto f_err;
1057         }
1058
1059         if (ssl_bytes_to_cipher_list(s, p, csl, &(ciphers), 1) == NULL) {
1060             goto err;
1061         }
1062
1063         /*
1064          * Ignore any session id. We don't allow resumption in a backwards
1065          * compatible ClientHello
1066          */
1067         s->hit = 0;
1068
1069         if (!ssl_get_new_session(s, 1))
1070             goto err;
1071
1072         /* Load the client random */
1073         i = (cl > SSL3_RANDOM_SIZE) ? SSL3_RANDOM_SIZE : cl;
1074         memset(s->s3->client_random, 0, SSL3_RANDOM_SIZE);
1075         memcpy(s->s3->client_random, &(p[csl + sil]), i);
1076
1077         /* Set p to end of packet to ensure we don't look for extensions */
1078         p = d + n;
1079
1080         /* No compression, so set complen to 0 */
1081         complen = 0;
1082     } else {
1083         /* If we get here we've got SSLv3+ in an SSLv3+ record */
1084
1085         p += 2;
1086
1087         /*
1088          * If we require cookies and this ClientHello doesn't contain one, just
1089          * return since we do not want to allocate any memory yet. So check
1090          * cookie length...
1091          */
1092         if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1093             unsigned int session_length, cookie_length;
1094
1095             session_length = *(p + SSL3_RANDOM_SIZE);
1096
1097             if (p + SSL3_RANDOM_SIZE + session_length + 1 >= d + n) {
1098                 al = SSL_AD_DECODE_ERROR;
1099                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1100                 goto f_err;
1101             }
1102             cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1);
1103
1104             if (cookie_length == 0)
1105                 return 1;
1106         }
1107
1108         /* load the client random */
1109         memcpy(s->s3->client_random, p, SSL3_RANDOM_SIZE);
1110         p += SSL3_RANDOM_SIZE;
1111
1112         /* get the session-id */
1113         j = *(p++);
1114
1115         if (p + j > d + n) {
1116             al = SSL_AD_DECODE_ERROR;
1117             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1118             goto f_err;
1119         }
1120
1121         s->hit = 0;
1122         /*
1123          * Versions before 0.9.7 always allow clients to resume sessions in
1124          * renegotiation. 0.9.7 and later allow this by default, but optionally
1125          * ignore resumption requests with flag
1126          * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
1127          * than a change to default behavior so that applications relying on
1128          * this for security won't even compile against older library versions).
1129          * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
1130          * request renegotiation but not a new session (s->new_session remains
1131          * unset): for servers, this essentially just means that the
1132          * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be
1133          * ignored.
1134          */
1135         if ((s->new_session
1136              && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
1137             if (!ssl_get_new_session(s, 1))
1138                 goto err;
1139         } else {
1140             i = ssl_get_prev_session(s, p, j, d + n);
1141             /*
1142              * Only resume if the session's version matches the negotiated
1143              * version.
1144              * RFC 5246 does not provide much useful advice on resumption
1145              * with a different protocol version. It doesn't forbid it but
1146              * the sanity of such behaviour would be questionable.
1147              * In practice, clients do not accept a version mismatch and
1148              * will abort the handshake with an error.
1149              */
1150             if (i == 1 && s->version == s->session->ssl_version) {
1151                 /* previous session */
1152                 s->hit = 1;
1153             } else if (i == -1)
1154                 goto err;
1155             else {
1156                 /* i == 0 */
1157                 if (!ssl_get_new_session(s, 1))
1158                     goto err;
1159             }
1160         }
1161
1162         p += j;
1163
1164         if (SSL_IS_DTLS(s)) {
1165             /* cookie stuff */
1166             if (p + 1 > d + n) {
1167                 al = SSL_AD_DECODE_ERROR;
1168                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1169                 goto f_err;
1170             }
1171             cookie_len = *(p++);
1172
1173             if (p + cookie_len > d + n) {
1174                 al = SSL_AD_DECODE_ERROR;
1175                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1176                 goto f_err;
1177             }
1178
1179             /*
1180              * The ClientHello may contain a cookie even if the
1181              * HelloVerify message has not been sent--make sure that it
1182              * does not cause an overflow.
1183              */
1184             if (cookie_len > sizeof(s->d1->rcvd_cookie)) {
1185                 /* too much data */
1186                 al = SSL_AD_DECODE_ERROR;
1187                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1188                 goto f_err;
1189             }
1190
1191             /* verify the cookie if appropriate option is set. */
1192             if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE)
1193                     && cookie_len > 0) {
1194                 memcpy(s->d1->rcvd_cookie, p, cookie_len);
1195
1196                 if (s->ctx->app_verify_cookie_cb != NULL) {
1197                     if (s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie,
1198                                                      cookie_len) == 0) {
1199                         al = SSL_AD_HANDSHAKE_FAILURE;
1200                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1201                                SSL_R_COOKIE_MISMATCH);
1202                         goto f_err;
1203                     }
1204                     /* else cookie verification succeeded */
1205                 }
1206                 /* default verification */
1207                 else if (memcmp(s->d1->rcvd_cookie, s->d1->cookie,
1208                                 s->d1->cookie_len) != 0) {
1209                     al = SSL_AD_HANDSHAKE_FAILURE;
1210                     SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1211                     goto f_err;
1212                 }
1213                 /* Set to -2 so if successful we return 2 */
1214                 ret = -2;
1215             }
1216
1217             p += cookie_len;
1218             if (s->method->version == DTLS_ANY_VERSION) {
1219                 /* Select version to use */
1220                 if (s->client_version <= DTLS1_2_VERSION &&
1221                     !(s->options & SSL_OP_NO_DTLSv1_2)) {
1222                     s->version = DTLS1_2_VERSION;
1223                     s->method = DTLSv1_2_server_method();
1224                 } else if (tls1_suiteb(s)) {
1225                     SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1226                            SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
1227                     s->version = s->client_version;
1228                     al = SSL_AD_PROTOCOL_VERSION;
1229                     goto f_err;
1230                 } else if (s->client_version <= DTLS1_VERSION &&
1231                            !(s->options & SSL_OP_NO_DTLSv1)) {
1232                     s->version = DTLS1_VERSION;
1233                     s->method = DTLSv1_server_method();
1234                 } else {
1235                     SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1236                            SSL_R_WRONG_VERSION_NUMBER);
1237                     s->version = s->client_version;
1238                     al = SSL_AD_PROTOCOL_VERSION;
1239                     goto f_err;
1240                 }
1241                 s->session->ssl_version = s->version;
1242             }
1243         }
1244
1245         if (p + 2 > d + n) {
1246             al = SSL_AD_DECODE_ERROR;
1247             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1248             goto f_err;
1249         }
1250         n2s(p, i);
1251
1252         if (i == 0) {
1253             al = SSL_AD_ILLEGAL_PARAMETER;
1254             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_CIPHERS_SPECIFIED);
1255             goto f_err;
1256         }
1257
1258         /* i bytes of cipher data + 1 byte for compression length later */
1259         if ((p + i + 1) > (d + n)) {
1260             /* not enough data */
1261             al = SSL_AD_DECODE_ERROR;
1262             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1263             goto f_err;
1264         }
1265         if (ssl_bytes_to_cipher_list(s, p, i, &(ciphers), 0) == NULL) {
1266             goto err;
1267         }
1268         p += i;
1269
1270         /* If it is a hit, check that the cipher is in the list */
1271         if (s->hit) {
1272             j = 0;
1273             id = s->session->cipher->id;
1274
1275 #ifdef CIPHER_DEBUG
1276             fprintf(stderr, "client sent %d ciphers\n",
1277                     sk_SSL_CIPHER_num(ciphers));
1278 #endif
1279             for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1280                 c = sk_SSL_CIPHER_value(ciphers, i);
1281 #ifdef CIPHER_DEBUG
1282                 fprintf(stderr, "client [%2d of %2d]:%s\n",
1283                         i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
1284 #endif
1285                 if (c->id == id) {
1286                     j = 1;
1287                     break;
1288                 }
1289             }
1290             /*
1291              * Disabled because it can be used in a ciphersuite downgrade
1292              * attack:
1293              * CVE-2010-4180.
1294              */
1295 #if 0
1296             if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG)
1297                 && (sk_SSL_CIPHER_num(ciphers) == 1)) {
1298                 /*
1299                  * Special case as client bug workaround: the previously used
1300                  * cipher may not be in the current list, the client instead
1301                  * might be trying to continue using a cipher that before wasn't
1302                  * chosen due to server preferences.  We'll have to reject the
1303                  * connection if the cipher is not enabled, though.
1304                  */
1305                 c = sk_SSL_CIPHER_value(ciphers, 0);
1306                 if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0) {
1307                     s->session->cipher = c;
1308                     j = 1;
1309                 }
1310             }
1311 #endif
1312             if (j == 0) {
1313                 /*
1314                  * we need to have the cipher in the cipher list if we are asked
1315                  * to reuse it
1316                  */
1317                 al = SSL_AD_ILLEGAL_PARAMETER;
1318                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1319                        SSL_R_REQUIRED_CIPHER_MISSING);
1320                 goto f_err;
1321             }
1322         }
1323
1324         /* compression */
1325         complen = *(p++);
1326         if ((p + complen) > (d + n)) {
1327             /* not enough data */
1328             al = SSL_AD_DECODE_ERROR;
1329             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1330             goto f_err;
1331         }
1332 #ifndef OPENSSL_NO_COMP
1333         q = p;
1334 #endif
1335         for (j = 0; j < complen; j++) {
1336             if (p[j] == 0)
1337                 break;
1338         }
1339
1340         p += complen;
1341         if (j >= complen) {
1342             /* no compress */
1343             al = SSL_AD_DECODE_ERROR;
1344             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED);
1345             goto f_err;
1346         }
1347     }
1348
1349     /* TLS extensions */
1350     if (s->version >= SSL3_VERSION) {
1351         if (!ssl_parse_clienthello_tlsext(s, &p, d, n)) {
1352             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_PARSE_TLSEXT);
1353             goto err;
1354         }
1355     }
1356
1357     /*
1358      * Check if we want to use external pre-shared secret for this handshake
1359      * for not reused session only. We need to generate server_random before
1360      * calling tls_session_secret_cb in order to allow SessionTicket
1361      * processing to use it in key derivation.
1362      */
1363     {
1364         unsigned char *pos;
1365         pos = s->s3->server_random;
1366         if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0) {
1367             goto f_err;
1368         }
1369     }
1370
1371     if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb) {
1372         SSL_CIPHER *pref_cipher = NULL;
1373
1374         s->session->master_key_length = sizeof(s->session->master_key);
1375         if (s->tls_session_secret_cb(s, s->session->master_key,
1376                                      &s->session->master_key_length, ciphers,
1377                                      &pref_cipher,
1378                                      s->tls_session_secret_cb_arg)) {
1379             s->hit = 1;
1380             s->session->ciphers = ciphers;
1381             s->session->verify_result = X509_V_OK;
1382
1383             ciphers = NULL;
1384
1385             /* check if some cipher was preferred by call back */
1386             pref_cipher =
1387                 pref_cipher ? pref_cipher : ssl3_choose_cipher(s,
1388                                                                s->
1389                                                                session->ciphers,
1390                                                                SSL_get_ciphers
1391                                                                (s));
1392             if (pref_cipher == NULL) {
1393                 al = SSL_AD_HANDSHAKE_FAILURE;
1394                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1395                 goto f_err;
1396             }
1397
1398             s->session->cipher = pref_cipher;
1399             sk_SSL_CIPHER_free(s->cipher_list);
1400             s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1401             sk_SSL_CIPHER_free(s->cipher_list_by_id);
1402             s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1403         }
1404     }
1405
1406     /*
1407      * Worst case, we will use the NULL compression, but if we have other
1408      * options, we will now look for them.  We have complen-1 compression
1409      * algorithms from the client, starting at q.
1410      */
1411     s->s3->tmp.new_compression = NULL;
1412 #ifndef OPENSSL_NO_COMP
1413     /* This only happens if we have a cache hit */
1414     if (s->session->compress_meth != 0) {
1415         int m, comp_id = s->session->compress_meth;
1416         /* Perform sanity checks on resumed compression algorithm */
1417         /* Can't disable compression */
1418         if (!ssl_allow_compression(s)) {
1419             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1420                    SSL_R_INCONSISTENT_COMPRESSION);
1421             goto f_err;
1422         }
1423         /* Look for resumed compression method */
1424         for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) {
1425             comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1426             if (comp_id == comp->id) {
1427                 s->s3->tmp.new_compression = comp;
1428                 break;
1429             }
1430         }
1431         if (s->s3->tmp.new_compression == NULL) {
1432             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1433                    SSL_R_INVALID_COMPRESSION_ALGORITHM);
1434             goto f_err;
1435         }
1436         /* Look for resumed method in compression list */
1437         for (m = 0; m < complen; m++) {
1438             if (q[m] == comp_id)
1439                 break;
1440         }
1441         if (m >= complen) {
1442             al = SSL_AD_ILLEGAL_PARAMETER;
1443             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1444                    SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING);
1445             goto f_err;
1446         }
1447     } else if (s->hit)
1448         comp = NULL;
1449     else if (ssl_allow_compression(s) && s->ctx->comp_methods) {
1450         /* See if we have a match */
1451         int m, nn, o, v, done = 0;
1452
1453         nn = sk_SSL_COMP_num(s->ctx->comp_methods);
1454         for (m = 0; m < nn; m++) {
1455             comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1456             v = comp->id;
1457             for (o = 0; o < complen; o++) {
1458                 if (v == q[o]) {
1459                     done = 1;
1460                     break;
1461                 }
1462             }
1463             if (done)
1464                 break;
1465         }
1466         if (done)
1467             s->s3->tmp.new_compression = comp;
1468         else
1469             comp = NULL;
1470     }
1471 #else
1472     /*
1473      * If compression is disabled we'd better not try to resume a session
1474      * using compression.
1475      */
1476     if (s->session->compress_meth != 0) {
1477         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
1478         goto f_err;
1479     }
1480 #endif
1481
1482     /*
1483      * Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher
1484      */
1485
1486     if (!s->hit) {
1487 #ifdef OPENSSL_NO_COMP
1488         s->session->compress_meth = 0;
1489 #else
1490         s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
1491 #endif
1492         sk_SSL_CIPHER_free(s->session->ciphers);
1493         s->session->ciphers = ciphers;
1494         if (ciphers == NULL) {
1495             al = SSL_AD_INTERNAL_ERROR;
1496             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1497             goto f_err;
1498         }
1499         ciphers = NULL;
1500         if (!tls1_set_server_sigalgs(s)) {
1501             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1502             goto err;
1503         }
1504         /* Let cert callback update server certificates if required */
1505  retry_cert:
1506         if (s->cert->cert_cb) {
1507             int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
1508             if (rv == 0) {
1509                 al = SSL_AD_INTERNAL_ERROR;
1510                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CERT_CB_ERROR);
1511                 goto f_err;
1512             }
1513             if (rv < 0) {
1514                 s->rwstate = SSL_X509_LOOKUP;
1515                 return -1;
1516             }
1517             s->rwstate = SSL_NOTHING;
1518         }
1519         c = ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
1520
1521         if (c == NULL) {
1522             al = SSL_AD_HANDSHAKE_FAILURE;
1523             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1524             goto f_err;
1525         }
1526         s->s3->tmp.new_cipher = c;
1527         /* check whether we should disable session resumption */
1528         if (s->not_resumable_session_cb != NULL)
1529             s->session->not_resumable = s->not_resumable_session_cb(s,
1530                                                                     ((c->algorithm_mkey & (SSL_kDHE | SSL_kECDHE))
1531                                                                      != 0));
1532         if (s->session->not_resumable)
1533             /* do not send a session ticket */
1534             s->tlsext_ticket_expected = 0;
1535     } else {
1536         /* Session-id reuse */
1537         s->s3->tmp.new_cipher = s->session->cipher;
1538     }
1539
1540     if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER)) {
1541         if (!ssl3_digest_cached_records(s))
1542             goto f_err;
1543     }
1544
1545     /*-
1546      * we now have the following setup.
1547      * client_random
1548      * cipher_list          - our prefered list of ciphers
1549      * ciphers              - the clients prefered list of ciphers
1550      * compression          - basically ignored right now
1551      * ssl version is set   - sslv3
1552      * s->session           - The ssl session has been setup.
1553      * s->hit               - session reuse flag
1554      * s->s3->tmp.new_cipher- the new cipher to use.
1555      */
1556
1557     /* Handles TLS extensions that we couldn't check earlier */
1558     if (s->version >= SSL3_VERSION) {
1559         if (ssl_check_clienthello_tlsext_late(s) <= 0) {
1560             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1561             goto err;
1562         }
1563     }
1564
1565     if (ret < 0)
1566         ret = -ret;
1567     if (0) {
1568  f_err:
1569         ssl3_send_alert(s, SSL3_AL_FATAL, al);
1570  err:
1571         s->state = SSL_ST_ERR;
1572     }
1573
1574     sk_SSL_CIPHER_free(ciphers);
1575     return ret < 0 ? -1 : ret;
1576 }
1577
1578 int ssl3_send_server_hello(SSL *s)
1579 {
1580     unsigned char *buf;
1581     unsigned char *p, *d;
1582     int i, sl;
1583     int al = 0;
1584     unsigned long l;
1585
1586     if (s->state == SSL3_ST_SW_SRVR_HELLO_A) {
1587         buf = (unsigned char *)s->init_buf->data;
1588
1589         p = s->s3->server_random;
1590         if (ssl_fill_hello_random(s, 1, p, SSL3_RANDOM_SIZE) <= 0) {
1591             s->state = SSL_ST_ERR;
1592             return -1;
1593         }
1594
1595         /* Do the message type and length last */
1596         d = p = ssl_handshake_start(s);
1597
1598         *(p++) = s->version >> 8;
1599         *(p++) = s->version & 0xff;
1600
1601         /* Random stuff */
1602         memcpy(p, s->s3->server_random, SSL3_RANDOM_SIZE);
1603         p += SSL3_RANDOM_SIZE;
1604
1605         /*-
1606          * There are several cases for the session ID to send
1607          * back in the server hello:
1608          * - For session reuse from the session cache,
1609          *   we send back the old session ID.
1610          * - If stateless session reuse (using a session ticket)
1611          *   is successful, we send back the client's "session ID"
1612          *   (which doesn't actually identify the session).
1613          * - If it is a new session, we send back the new
1614          *   session ID.
1615          * - However, if we want the new session to be single-use,
1616          *   we send back a 0-length session ID.
1617          * s->hit is non-zero in either case of session reuse,
1618          * so the following won't overwrite an ID that we're supposed
1619          * to send back.
1620          */
1621         if (s->session->not_resumable ||
1622             (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1623              && !s->hit))
1624             s->session->session_id_length = 0;
1625
1626         sl = s->session->session_id_length;
1627         if (sl > (int)sizeof(s->session->session_id)) {
1628             SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1629             s->state = SSL_ST_ERR;
1630             return -1;
1631         }
1632         *(p++) = sl;
1633         memcpy(p, s->session->session_id, sl);
1634         p += sl;
1635
1636         /* put the cipher */
1637         i = ssl3_put_cipher_by_char(s->s3->tmp.new_cipher, p);
1638         p += i;
1639
1640         /* put the compression method */
1641 #ifdef OPENSSL_NO_COMP
1642         *(p++) = 0;
1643 #else
1644         if (s->s3->tmp.new_compression == NULL)
1645             *(p++) = 0;
1646         else
1647             *(p++) = s->s3->tmp.new_compression->id;
1648 #endif
1649
1650         if (ssl_prepare_serverhello_tlsext(s) <= 0) {
1651             SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, SSL_R_SERVERHELLO_TLSEXT);
1652             s->state = SSL_ST_ERR;
1653             return -1;
1654         }
1655         if ((p =
1656              ssl_add_serverhello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,
1657                                         &al)) == NULL) {
1658             ssl3_send_alert(s, SSL3_AL_FATAL, al);
1659             SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1660             s->state = SSL_ST_ERR;
1661             return -1;
1662         }
1663
1664         /* do the header */
1665         l = (p - d);
1666         if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l)) {
1667             SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1668             return -1;
1669         }
1670         s->state = SSL3_ST_SW_SRVR_HELLO_B;
1671     }
1672
1673     /* SSL3_ST_SW_SRVR_HELLO_B */
1674     return ssl_do_write(s);
1675 }
1676
1677 int ssl3_send_server_done(SSL *s)
1678 {
1679
1680     if (s->state == SSL3_ST_SW_SRVR_DONE_A) {
1681         if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0)) {
1682             SSLerr(SSL_F_SSL3_SEND_SERVER_DONE, ERR_R_INTERNAL_ERROR);
1683             return -1;
1684         }
1685         s->state = SSL3_ST_SW_SRVR_DONE_B;
1686     }
1687
1688     /* SSL3_ST_SW_SRVR_DONE_B */
1689     return ssl_do_write(s);
1690 }
1691
1692 int ssl3_send_server_key_exchange(SSL *s)
1693 {
1694 #ifndef OPENSSL_NO_RSA
1695     unsigned char *q;
1696     int j, num;
1697     RSA *rsa;
1698     unsigned char md_buf[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH];
1699     unsigned int u;
1700 #endif
1701 #ifndef OPENSSL_NO_DH
1702     DH *dh = NULL, *dhp;
1703 #endif
1704 #ifndef OPENSSL_NO_EC
1705     EC_KEY *ecdh = NULL, *ecdhp;
1706     unsigned char *encodedPoint = NULL;
1707     int encodedlen = 0;
1708     int curve_id = 0;
1709     BN_CTX *bn_ctx = NULL;
1710 #endif
1711     EVP_PKEY *pkey;
1712     const EVP_MD *md = NULL;
1713     unsigned char *p, *d;
1714     int al, i;
1715     unsigned long type;
1716     int n;
1717     CERT *cert;
1718     BIGNUM *r[4];
1719     int nr[4], kn;
1720     BUF_MEM *buf;
1721     EVP_MD_CTX md_ctx;
1722
1723     EVP_MD_CTX_init(&md_ctx);
1724     if (s->state == SSL3_ST_SW_KEY_EXCH_A) {
1725         type = s->s3->tmp.new_cipher->algorithm_mkey;
1726         cert = s->cert;
1727
1728         buf = s->init_buf;
1729
1730         r[0] = r[1] = r[2] = r[3] = NULL;
1731         n = 0;
1732 #ifndef OPENSSL_NO_RSA
1733         if (type & SSL_kRSA) {
1734             rsa = cert->rsa_tmp;
1735             if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL)) {
1736                 rsa = s->cert->rsa_tmp_cb(s,
1737                                           SSL_C_IS_EXPORT(s->s3->
1738                                                           tmp.new_cipher),
1739                                           SSL_C_EXPORT_PKEYLENGTH(s->s3->
1740                                                                   tmp.new_cipher));
1741                 if (rsa == NULL) {
1742                     al = SSL_AD_HANDSHAKE_FAILURE;
1743                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1744                            SSL_R_ERROR_GENERATING_TMP_RSA_KEY);
1745                     goto f_err;
1746                 }
1747                 RSA_up_ref(rsa);
1748                 cert->rsa_tmp = rsa;
1749             }
1750             if (rsa == NULL) {
1751                 al = SSL_AD_HANDSHAKE_FAILURE;
1752                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1753                        SSL_R_MISSING_TMP_RSA_KEY);
1754                 goto f_err;
1755             }
1756             r[0] = rsa->n;
1757             r[1] = rsa->e;
1758             s->s3->tmp.use_rsa_tmp = 1;
1759         } else
1760 #endif
1761 #ifndef OPENSSL_NO_DH
1762         if (type & SSL_kDHE) {
1763             if (s->cert->dh_tmp_auto) {
1764                 dhp = ssl_get_auto_dh(s);
1765                 if (dhp == NULL) {
1766                     al = SSL_AD_INTERNAL_ERROR;
1767                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1768                            ERR_R_INTERNAL_ERROR);
1769                     goto f_err;
1770                 }
1771             } else
1772                 dhp = cert->dh_tmp;
1773             if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1774                 dhp = s->cert->dh_tmp_cb(s,
1775                                          SSL_C_IS_EXPORT(s->s3->
1776                                                          tmp.new_cipher),
1777                                          SSL_C_EXPORT_PKEYLENGTH(s->s3->
1778                                                                  tmp.new_cipher));
1779             if (dhp == NULL) {
1780                 al = SSL_AD_HANDSHAKE_FAILURE;
1781                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1782                        SSL_R_MISSING_TMP_DH_KEY);
1783                 goto f_err;
1784             }
1785             if (!ssl_security(s, SSL_SECOP_TMP_DH,
1786                               DH_security_bits(dhp), 0, dhp)) {
1787                 al = SSL_AD_HANDSHAKE_FAILURE;
1788                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1789                        SSL_R_DH_KEY_TOO_SMALL);
1790                 goto f_err;
1791             }
1792             if (s->s3->tmp.dh != NULL) {
1793                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1794                        ERR_R_INTERNAL_ERROR);
1795                 goto err;
1796             }
1797
1798             if (s->cert->dh_tmp_auto)
1799                 dh = dhp;
1800             else if ((dh = DHparams_dup(dhp)) == NULL) {
1801                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1802                 goto err;
1803             }
1804
1805             s->s3->tmp.dh = dh;
1806             if ((dhp->pub_key == NULL ||
1807                  dhp->priv_key == NULL ||
1808                  (s->options & SSL_OP_SINGLE_DH_USE))) {
1809                 if (!DH_generate_key(dh)) {
1810                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1811                     goto err;
1812                 }
1813             } else {
1814                 dh->pub_key = BN_dup(dhp->pub_key);
1815                 dh->priv_key = BN_dup(dhp->priv_key);
1816                 if ((dh->pub_key == NULL) || (dh->priv_key == NULL)) {
1817                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1818                     goto err;
1819                 }
1820             }
1821             r[0] = dh->p;
1822             r[1] = dh->g;
1823             r[2] = dh->pub_key;
1824         } else
1825 #endif
1826 #ifndef OPENSSL_NO_EC
1827         if (type & SSL_kECDHE) {
1828             const EC_GROUP *group;
1829
1830             ecdhp = cert->ecdh_tmp;
1831             if (s->cert->ecdh_tmp_auto) {
1832                 /* Get NID of appropriate shared curve */
1833                 int nid = tls1_shared_curve(s, -2);
1834                 if (nid != NID_undef)
1835                     ecdhp = EC_KEY_new_by_curve_name(nid);
1836             } else if ((ecdhp == NULL) && s->cert->ecdh_tmp_cb) {
1837                 ecdhp = s->cert->ecdh_tmp_cb(s,
1838                                              SSL_C_IS_EXPORT(s->s3->
1839                                                              tmp.new_cipher),
1840                                              SSL_C_EXPORT_PKEYLENGTH(s->
1841                                                                      s3->tmp.new_cipher));
1842             }
1843             if (ecdhp == NULL) {
1844                 al = SSL_AD_HANDSHAKE_FAILURE;
1845                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1846                        SSL_R_MISSING_TMP_ECDH_KEY);
1847                 goto f_err;
1848             }
1849
1850             if (s->s3->tmp.ecdh != NULL) {
1851                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1852                        ERR_R_INTERNAL_ERROR);
1853                 goto err;
1854             }
1855
1856             /* Duplicate the ECDH structure. */
1857             if (ecdhp == NULL) {
1858                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1859                 goto err;
1860             }
1861             if (s->cert->ecdh_tmp_auto)
1862                 ecdh = ecdhp;
1863             else if ((ecdh = EC_KEY_dup(ecdhp)) == NULL) {
1864                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1865                 goto err;
1866             }
1867
1868             s->s3->tmp.ecdh = ecdh;
1869             if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1870                 (EC_KEY_get0_private_key(ecdh) == NULL) ||
1871                 (s->options & SSL_OP_SINGLE_ECDH_USE)) {
1872                 if (!EC_KEY_generate_key(ecdh)) {
1873                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1874                            ERR_R_ECDH_LIB);
1875                     goto err;
1876                 }
1877             }
1878
1879             if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1880                 (EC_KEY_get0_public_key(ecdh) == NULL) ||
1881                 (EC_KEY_get0_private_key(ecdh) == NULL)) {
1882                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1883                 goto err;
1884             }
1885
1886             if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1887                 (EC_GROUP_get_degree(group) > 163)) {
1888                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1889                        SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1890                 goto err;
1891             }
1892
1893             /*
1894              * XXX: For now, we only support ephemeral ECDH keys over named
1895              * (not generic) curves. For supported named curves, curve_id is
1896              * non-zero.
1897              */
1898             if ((curve_id =
1899                  tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group)))
1900                 == 0) {
1901                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1902                        SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1903                 goto err;
1904             }
1905
1906             /*
1907              * Encode the public key. First check the size of encoding and
1908              * allocate memory accordingly.
1909              */
1910             encodedlen = EC_POINT_point2oct(group,
1911                                             EC_KEY_get0_public_key(ecdh),
1912                                             POINT_CONVERSION_UNCOMPRESSED,
1913                                             NULL, 0, NULL);
1914
1915             encodedPoint = (unsigned char *)
1916                 OPENSSL_malloc(encodedlen * sizeof(unsigned char));
1917             bn_ctx = BN_CTX_new();
1918             if ((encodedPoint == NULL) || (bn_ctx == NULL)) {
1919                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1920                        ERR_R_MALLOC_FAILURE);
1921                 goto err;
1922             }
1923
1924             encodedlen = EC_POINT_point2oct(group,
1925                                             EC_KEY_get0_public_key(ecdh),
1926                                             POINT_CONVERSION_UNCOMPRESSED,
1927                                             encodedPoint, encodedlen, bn_ctx);
1928
1929             if (encodedlen == 0) {
1930                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1931                 goto err;
1932             }
1933
1934             BN_CTX_free(bn_ctx);
1935             bn_ctx = NULL;
1936
1937             /*
1938              * XXX: For now, we only support named (not generic) curves in
1939              * ECDH ephemeral key exchanges. In this situation, we need four
1940              * additional bytes to encode the entire ServerECDHParams
1941              * structure.
1942              */
1943             n = 4 + encodedlen;
1944
1945             /*
1946              * We'll generate the serverKeyExchange message explicitly so we
1947              * can set these to NULLs
1948              */
1949             r[0] = NULL;
1950             r[1] = NULL;
1951             r[2] = NULL;
1952             r[3] = NULL;
1953         } else
1954 #endif                          /* !OPENSSL_NO_EC */
1955 #ifndef OPENSSL_NO_PSK
1956         if (type & SSL_kPSK) {
1957             /*
1958              * reserve size for record length and PSK identity hint
1959              */
1960             n += 2 + strlen(s->ctx->psk_identity_hint);
1961         } else
1962 #endif                          /* !OPENSSL_NO_PSK */
1963 #ifndef OPENSSL_NO_SRP
1964         if (type & SSL_kSRP) {
1965             if ((s->srp_ctx.N == NULL) ||
1966                 (s->srp_ctx.g == NULL) ||
1967                 (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
1968                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1969                        SSL_R_MISSING_SRP_PARAM);
1970                 goto err;
1971             }
1972             r[0] = s->srp_ctx.N;
1973             r[1] = s->srp_ctx.g;
1974             r[2] = s->srp_ctx.s;
1975             r[3] = s->srp_ctx.B;
1976         } else
1977 #endif
1978         {
1979             al = SSL_AD_HANDSHAKE_FAILURE;
1980             SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1981                    SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1982             goto f_err;
1983         }
1984         for (i = 0; i < 4 && r[i] != NULL; i++) {
1985             nr[i] = BN_num_bytes(r[i]);
1986 #ifndef OPENSSL_NO_SRP
1987             if ((i == 2) && (type & SSL_kSRP))
1988                 n += 1 + nr[i];
1989             else
1990 #endif
1991                 n += 2 + nr[i];
1992         }
1993
1994         if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP))
1995             && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
1996             if ((pkey = ssl_get_sign_pkey(s, s->s3->tmp.new_cipher, &md))
1997                 == NULL) {
1998                 al = SSL_AD_DECODE_ERROR;
1999                 goto f_err;
2000             }
2001             kn = EVP_PKEY_size(pkey);
2002         } else {
2003             pkey = NULL;
2004             kn = 0;
2005         }
2006
2007         if (!BUF_MEM_grow_clean(buf, n + SSL_HM_HEADER_LENGTH(s) + kn)) {
2008             SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_BUF);
2009             goto err;
2010         }
2011         d = p = ssl_handshake_start(s);
2012
2013         for (i = 0; i < 4 && r[i] != NULL; i++) {
2014 #ifndef OPENSSL_NO_SRP
2015             if ((i == 2) && (type & SSL_kSRP)) {
2016                 *p = nr[i];
2017                 p++;
2018             } else
2019 #endif
2020                 s2n(nr[i], p);
2021             BN_bn2bin(r[i], p);
2022             p += nr[i];
2023         }
2024
2025 #ifndef OPENSSL_NO_EC
2026         if (type & SSL_kECDHE) {
2027             /*
2028              * XXX: For now, we only support named (not generic) curves. In
2029              * this situation, the serverKeyExchange message has: [1 byte
2030              * CurveType], [2 byte CurveName] [1 byte length of encoded
2031              * point], followed by the actual encoded point itself
2032              */
2033             *p = NAMED_CURVE_TYPE;
2034             p += 1;
2035             *p = 0;
2036             p += 1;
2037             *p = curve_id;
2038             p += 1;
2039             *p = encodedlen;
2040             p += 1;
2041             memcpy(p, encodedPoint, encodedlen);
2042             OPENSSL_free(encodedPoint);
2043             encodedPoint = NULL;
2044             p += encodedlen;
2045         }
2046 #endif
2047
2048 #ifndef OPENSSL_NO_PSK
2049         if (type & SSL_kPSK) {
2050             /* copy PSK identity hint */
2051             s2n(strlen(s->ctx->psk_identity_hint), p);
2052             strncpy((char *)p, s->ctx->psk_identity_hint,
2053                     strlen(s->ctx->psk_identity_hint));
2054             p += strlen(s->ctx->psk_identity_hint);
2055         }
2056 #endif
2057
2058         /* not anonymous */
2059         if (pkey != NULL) {
2060             /*
2061              * n is the length of the params, they start at &(d[4]) and p
2062              * points to the space at the end.
2063              */
2064 #ifndef OPENSSL_NO_RSA
2065             if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) {
2066                 q = md_buf;
2067                 j = 0;
2068                 for (num = 2; num > 0; num--) {
2069                     EVP_MD_CTX_set_flags(&md_ctx,
2070                                          EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
2071                     EVP_DigestInit_ex(&md_ctx, (num == 2)
2072                                       ? s->ctx->md5 : s->ctx->sha1, NULL);
2073                     EVP_DigestUpdate(&md_ctx, &(s->s3->client_random[0]),
2074                                      SSL3_RANDOM_SIZE);
2075                     EVP_DigestUpdate(&md_ctx, &(s->s3->server_random[0]),
2076                                      SSL3_RANDOM_SIZE);
2077                     EVP_DigestUpdate(&md_ctx, d, n);
2078                     EVP_DigestFinal_ex(&md_ctx, q, (unsigned int *)&i);
2079                     q += i;
2080                     j += i;
2081                 }
2082                 if (RSA_sign(NID_md5_sha1, md_buf, j,
2083                              &(p[2]), &u, pkey->pkey.rsa) <= 0) {
2084                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_RSA);
2085                     goto err;
2086                 }
2087                 s2n(u, p);
2088                 n += u + 2;
2089             } else
2090 #endif
2091             if (md) {
2092                 /* send signature algorithm */
2093                 if (SSL_USE_SIGALGS(s)) {
2094                     if (!tls12_get_sigandhash(p, pkey, md)) {
2095                         /* Should never happen */
2096                         al = SSL_AD_INTERNAL_ERROR;
2097                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
2098                                ERR_R_INTERNAL_ERROR);
2099                         goto f_err;
2100                     }
2101                     p += 2;
2102                 }
2103 #ifdef SSL_DEBUG
2104                 fprintf(stderr, "Using hash %s\n", EVP_MD_name(md));
2105 #endif
2106                 EVP_SignInit_ex(&md_ctx, md, NULL);
2107                 EVP_SignUpdate(&md_ctx, &(s->s3->client_random[0]),
2108                                SSL3_RANDOM_SIZE);
2109                 EVP_SignUpdate(&md_ctx, &(s->s3->server_random[0]),
2110                                SSL3_RANDOM_SIZE);
2111                 EVP_SignUpdate(&md_ctx, d, n);
2112                 if (!EVP_SignFinal(&md_ctx, &(p[2]),
2113                                    (unsigned int *)&i, pkey)) {
2114                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_EVP);
2115                     goto err;
2116                 }
2117                 s2n(i, p);
2118                 n += i + 2;
2119                 if (SSL_USE_SIGALGS(s))
2120                     n += 2;
2121             } else {
2122                 /* Is this error check actually needed? */
2123                 al = SSL_AD_HANDSHAKE_FAILURE;
2124                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
2125                        SSL_R_UNKNOWN_PKEY_TYPE);
2126                 goto f_err;
2127             }
2128         }
2129
2130         if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n)) {
2131             al = SSL_AD_HANDSHAKE_FAILURE;
2132             SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2133             goto f_err;
2134         }
2135     }
2136
2137     s->state = SSL3_ST_SW_KEY_EXCH_B;
2138     EVP_MD_CTX_cleanup(&md_ctx);
2139     return ssl_do_write(s);
2140  f_err:
2141     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2142  err:
2143 #ifndef OPENSSL_NO_EC
2144     OPENSSL_free(encodedPoint);
2145     BN_CTX_free(bn_ctx);
2146 #endif
2147     EVP_MD_CTX_cleanup(&md_ctx);
2148     s->state = SSL_ST_ERR;
2149     return (-1);
2150 }
2151
2152 int ssl3_send_certificate_request(SSL *s)
2153 {
2154     unsigned char *p, *d;
2155     int i, j, nl, off, n;
2156     STACK_OF(X509_NAME) *sk = NULL;
2157     X509_NAME *name;
2158     BUF_MEM *buf;
2159
2160     if (s->state == SSL3_ST_SW_CERT_REQ_A) {
2161         buf = s->init_buf;
2162
2163         d = p = ssl_handshake_start(s);
2164
2165         /* get the list of acceptable cert types */
2166         p++;
2167         n = ssl3_get_req_cert_type(s, p);
2168         d[0] = n;
2169         p += n;
2170         n++;
2171
2172         if (SSL_USE_SIGALGS(s)) {
2173             const unsigned char *psigs;
2174             unsigned char *etmp = p;
2175             nl = tls12_get_psigalgs(s, &psigs);
2176             /* Skip over length for now */
2177             p += 2;
2178             nl = tls12_copy_sigalgs(s, p, psigs, nl);
2179             /* Now fill in length */
2180             s2n(nl, etmp);
2181             p += nl;
2182             n += nl + 2;
2183         }
2184
2185         off = n;
2186         p += 2;
2187         n += 2;
2188
2189         sk = SSL_get_client_CA_list(s);
2190         nl = 0;
2191         if (sk != NULL) {
2192             for (i = 0; i < sk_X509_NAME_num(sk); i++) {
2193                 name = sk_X509_NAME_value(sk, i);
2194                 j = i2d_X509_NAME(name, NULL);
2195                 if (!BUF_MEM_grow_clean
2196                     (buf, SSL_HM_HEADER_LENGTH(s) + n + j + 2)) {
2197                     SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,
2198                            ERR_R_BUF_LIB);
2199                     goto err;
2200                 }
2201                 p = ssl_handshake_start(s) + n;
2202                 s2n(j, p);
2203                 i2d_X509_NAME(name, &p);
2204                 n += 2 + j;
2205                 nl += 2 + j;
2206             }
2207         }
2208         /* else no CA names */
2209         p = ssl_handshake_start(s) + off;
2210         s2n(nl, p);
2211
2212         if (!ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n)) {
2213             SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR);
2214             return -1;
2215         }
2216
2217         s->state = SSL3_ST_SW_CERT_REQ_B;
2218     }
2219
2220     /* SSL3_ST_SW_CERT_REQ_B */
2221     return ssl_do_write(s);
2222  err:
2223     s->state = SSL_ST_ERR;
2224     return (-1);
2225 }
2226
2227 int ssl3_get_client_key_exchange(SSL *s)
2228 {
2229     int i, al, ok;
2230     long n;
2231     unsigned long alg_k;
2232     unsigned char *p;
2233 #ifndef OPENSSL_NO_RSA
2234     RSA *rsa = NULL;
2235     EVP_PKEY *pkey = NULL;
2236 #endif
2237 #ifndef OPENSSL_NO_DH
2238     BIGNUM *pub = NULL;
2239     DH *dh_srvr, *dh_clnt = NULL;
2240 #endif
2241 #ifndef OPENSSL_NO_EC
2242     EC_KEY *srvr_ecdh = NULL;
2243     EVP_PKEY *clnt_pub_pkey = NULL;
2244     EC_POINT *clnt_ecpoint = NULL;
2245     BN_CTX *bn_ctx = NULL;
2246 #endif
2247
2248     n = s->method->ssl_get_message(s,
2249                                    SSL3_ST_SR_KEY_EXCH_A,
2250                                    SSL3_ST_SR_KEY_EXCH_B,
2251                                    SSL3_MT_CLIENT_KEY_EXCHANGE, 2048, &ok);
2252
2253     if (!ok)
2254         return ((int)n);
2255     p = (unsigned char *)s->init_msg;
2256
2257     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2258
2259 #ifndef OPENSSL_NO_RSA
2260     if (alg_k & SSL_kRSA) {
2261         unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2262         int decrypt_len;
2263         unsigned char decrypt_good, version_good;
2264         size_t j;
2265
2266         /* FIX THIS UP EAY EAY EAY EAY */
2267         if (s->s3->tmp.use_rsa_tmp) {
2268             if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
2269                 rsa = s->cert->rsa_tmp;
2270             /*
2271              * Don't do a callback because rsa_tmp should be sent already
2272              */
2273             if (rsa == NULL) {
2274                 al = SSL_AD_HANDSHAKE_FAILURE;
2275                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2276                        SSL_R_MISSING_TMP_RSA_PKEY);
2277                 goto f_err;
2278
2279             }
2280         } else {
2281             pkey = s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
2282             if ((pkey == NULL) ||
2283                 (pkey->type != EVP_PKEY_RSA) || (pkey->pkey.rsa == NULL)) {
2284                 al = SSL_AD_HANDSHAKE_FAILURE;
2285                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2286                        SSL_R_MISSING_RSA_CERTIFICATE);
2287                 goto f_err;
2288             }
2289             rsa = pkey->pkey.rsa;
2290         }
2291
2292         /* TLS and [incidentally] DTLS{0xFEFF} */
2293         if (s->version > SSL3_VERSION && s->version != DTLS1_BAD_VER) {
2294             n2s(p, i);
2295             if (n != i + 2) {
2296                 if (!(s->options & SSL_OP_TLS_D5_BUG)) {
2297                     al = SSL_AD_DECODE_ERROR;
2298                     SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2299                            SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2300                     goto f_err;
2301                 } else
2302                     p -= 2;
2303             } else
2304                 n = i;
2305         }
2306
2307         /*
2308          * Reject overly short RSA ciphertext because we want to be sure
2309          * that the buffer size makes it safe to iterate over the entire
2310          * size of a premaster secret (SSL_MAX_MASTER_KEY_LENGTH). The
2311          * actual expected size is larger due to RSA padding, but the
2312          * bound is sufficient to be safe.
2313          */
2314         if (n < SSL_MAX_MASTER_KEY_LENGTH) {
2315             al = SSL_AD_DECRYPT_ERROR;
2316             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2317                    SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2318             goto f_err;
2319         }
2320
2321         /*
2322          * We must not leak whether a decryption failure occurs because of
2323          * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
2324          * section 7.4.7.1). The code follows that advice of the TLS RFC and
2325          * generates a random premaster secret for the case that the decrypt
2326          * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
2327          */
2328
2329         if (RAND_bytes(rand_premaster_secret,
2330                               sizeof(rand_premaster_secret)) <= 0)
2331             goto err;
2332         decrypt_len =
2333             RSA_private_decrypt((int)n, p, p, rsa, RSA_PKCS1_PADDING);
2334         ERR_clear_error();
2335
2336         /*
2337          * decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH. decrypt_good will
2338          * be 0xff if so and zero otherwise.
2339          */
2340         decrypt_good =
2341             constant_time_eq_int_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH);
2342
2343         /*
2344          * If the version in the decrypted pre-master secret is correct then
2345          * version_good will be 0xff, otherwise it'll be zero. The
2346          * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
2347          * (http://eprint.iacr.org/2003/052/) exploits the version number
2348          * check as a "bad version oracle". Thus version checks are done in
2349          * constant time and are treated like any other decryption error.
2350          */
2351         version_good =
2352             constant_time_eq_8(p[0], (unsigned)(s->client_version >> 8));
2353         version_good &=
2354             constant_time_eq_8(p[1], (unsigned)(s->client_version & 0xff));
2355
2356         /*
2357          * The premaster secret must contain the same version number as the
2358          * ClientHello to detect version rollback attacks (strangely, the
2359          * protocol does not offer such protection for DH ciphersuites).
2360          * However, buggy clients exist that send the negotiated protocol
2361          * version instead if the server does not support the requested
2362          * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
2363          * clients.
2364          */
2365         if (s->options & SSL_OP_TLS_ROLLBACK_BUG) {
2366             unsigned char workaround_good;
2367             workaround_good =
2368                 constant_time_eq_8(p[0], (unsigned)(s->version >> 8));
2369             workaround_good &=
2370                 constant_time_eq_8(p[1], (unsigned)(s->version & 0xff));
2371             version_good |= workaround_good;
2372         }
2373
2374         /*
2375          * Both decryption and version must be good for decrypt_good to
2376          * remain non-zero (0xff).
2377          */
2378         decrypt_good &= version_good;
2379
2380         /*
2381          * Now copy rand_premaster_secret over from p using
2382          * decrypt_good_mask. If decryption failed, then p does not
2383          * contain valid plaintext, however, a check above guarantees
2384          * it is still sufficiently large to read from.
2385          */
2386         for (j = 0; j < sizeof(rand_premaster_secret); j++) {
2387             p[j] = constant_time_select_8(decrypt_good, p[j],
2388                                           rand_premaster_secret[j]);
2389         }
2390
2391         s->session->master_key_length =
2392             s->method->ssl3_enc->generate_master_secret(s,
2393                                                         s->
2394                                                         session->master_key,
2395                                                         p,
2396                                                         sizeof
2397                                                         (rand_premaster_secret));
2398         OPENSSL_cleanse(p, sizeof(rand_premaster_secret));
2399         if (s->session->master_key_length < 0) {
2400             al = SSL_AD_INTERNAL_ERROR;
2401             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2402             goto f_err;
2403         }
2404     } else
2405 #endif
2406 #ifndef OPENSSL_NO_DH
2407     if (alg_k & (SSL_kDHE | SSL_kDHr | SSL_kDHd)) {
2408         int idx = -1;
2409         EVP_PKEY *skey = NULL;
2410         if (n > 1) {
2411             n2s(p, i);
2412         } else {
2413             if (alg_k & SSL_kDHE) {
2414                 al = SSL_AD_HANDSHAKE_FAILURE;
2415                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2416                        SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2417                 goto f_err;
2418             }
2419             i = 0;
2420         }
2421         if (n && n != i + 2) {
2422             if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG)) {
2423                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2424                        SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2425                 goto err;
2426             } else {
2427                 p -= 2;
2428                 i = (int)n;
2429             }
2430         }
2431         if (alg_k & SSL_kDHr)
2432             idx = SSL_PKEY_DH_RSA;
2433         else if (alg_k & SSL_kDHd)
2434             idx = SSL_PKEY_DH_DSA;
2435         if (idx >= 0) {
2436             skey = s->cert->pkeys[idx].privatekey;
2437             if ((skey == NULL) ||
2438                 (skey->type != EVP_PKEY_DH) || (skey->pkey.dh == NULL)) {
2439                 al = SSL_AD_HANDSHAKE_FAILURE;
2440                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2441                        SSL_R_MISSING_RSA_CERTIFICATE);
2442                 goto f_err;
2443             }
2444             dh_srvr = skey->pkey.dh;
2445         } else if (s->s3->tmp.dh == NULL) {
2446             al = SSL_AD_HANDSHAKE_FAILURE;
2447             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2448                    SSL_R_MISSING_TMP_DH_KEY);
2449             goto f_err;
2450         } else
2451             dh_srvr = s->s3->tmp.dh;
2452
2453         if (n == 0L) {
2454             /* Get pubkey from cert */
2455             EVP_PKEY *clkey = X509_get_pubkey(s->session->peer);
2456             if (clkey) {
2457                 if (EVP_PKEY_cmp_parameters(clkey, skey) == 1)
2458                     dh_clnt = EVP_PKEY_get1_DH(clkey);
2459             }
2460             if (dh_clnt == NULL) {
2461                 al = SSL_AD_HANDSHAKE_FAILURE;
2462                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2463                        SSL_R_MISSING_TMP_DH_KEY);
2464                 goto f_err;
2465             }
2466             EVP_PKEY_free(clkey);
2467             pub = dh_clnt->pub_key;
2468         } else
2469             pub = BN_bin2bn(p, i, NULL);
2470         if (pub == NULL) {
2471             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_BN_LIB);
2472             goto err;
2473         }
2474
2475         i = DH_compute_key(p, pub, dh_srvr);
2476
2477         if (i <= 0) {
2478             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
2479             BN_clear_free(pub);
2480             goto err;
2481         }
2482
2483         DH_free(s->s3->tmp.dh);
2484         s->s3->tmp.dh = NULL;
2485         if (dh_clnt)
2486             DH_free(dh_clnt);
2487         else
2488             BN_clear_free(pub);
2489         pub = NULL;
2490         s->session->master_key_length =
2491             s->method->ssl3_enc->generate_master_secret(s,
2492                                                         s->
2493                                                         session->master_key,
2494                                                         p, i);
2495         OPENSSL_cleanse(p, i);
2496         if (s->session->master_key_length < 0) {
2497             al = SSL_AD_INTERNAL_ERROR;
2498             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2499             goto f_err;
2500         }
2501         if (dh_clnt)
2502             return 2;
2503     } else
2504 #endif
2505
2506 #ifndef OPENSSL_NO_EC
2507     if (alg_k & (SSL_kECDHE | SSL_kECDHr | SSL_kECDHe)) {
2508         int ret = 1;
2509         int field_size = 0;
2510         const EC_KEY *tkey;
2511         const EC_GROUP *group;
2512         const BIGNUM *priv_key;
2513
2514         /* initialize structures for server's ECDH key pair */
2515         if ((srvr_ecdh = EC_KEY_new()) == NULL) {
2516             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2517             goto err;
2518         }
2519
2520         /* Let's get server private key and group information */
2521         if (alg_k & (SSL_kECDHr | SSL_kECDHe)) {
2522             /* use the certificate */
2523             tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec;
2524         } else {
2525             /*
2526              * use the ephermeral values we saved when generating the
2527              * ServerKeyExchange msg.
2528              */
2529             tkey = s->s3->tmp.ecdh;
2530         }
2531
2532         group = EC_KEY_get0_group(tkey);
2533         priv_key = EC_KEY_get0_private_key(tkey);
2534
2535         if (!EC_KEY_set_group(srvr_ecdh, group) ||
2536             !EC_KEY_set_private_key(srvr_ecdh, priv_key)) {
2537             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2538             goto err;
2539         }
2540
2541         /* Let's get client's public key */
2542         if ((clnt_ecpoint = EC_POINT_new(group)) == NULL) {
2543             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2544             goto err;
2545         }
2546
2547         if (n == 0L) {
2548             /* Client Publickey was in Client Certificate */
2549
2550             if (alg_k & SSL_kECDHE) {
2551                 al = SSL_AD_HANDSHAKE_FAILURE;
2552                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2553                        SSL_R_MISSING_TMP_ECDH_KEY);
2554                 goto f_err;
2555             }
2556             if (((clnt_pub_pkey = X509_get_pubkey(s->session->peer))
2557                  == NULL) || (clnt_pub_pkey->type != EVP_PKEY_EC)) {
2558                 /*
2559                  * XXX: For now, we do not support client authentication
2560                  * using ECDH certificates so this branch (n == 0L) of the
2561                  * code is never executed. When that support is added, we
2562                  * ought to ensure the key received in the certificate is
2563                  * authorized for key agreement. ECDH_compute_key implicitly
2564                  * checks that the two ECDH shares are for the same group.
2565                  */
2566                 al = SSL_AD_HANDSHAKE_FAILURE;
2567                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2568                        SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
2569                 goto f_err;
2570             }
2571
2572             if (EC_POINT_copy(clnt_ecpoint,
2573                               EC_KEY_get0_public_key(clnt_pub_pkey->
2574                                                      pkey.ec)) == 0) {
2575                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2576                 goto err;
2577             }
2578             ret = 2;            /* Skip certificate verify processing */
2579         } else {
2580             /*
2581              * Get client's public key from encoded point in the
2582              * ClientKeyExchange message.
2583              */
2584             if ((bn_ctx = BN_CTX_new()) == NULL) {
2585                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2586                        ERR_R_MALLOC_FAILURE);
2587                 goto err;
2588             }
2589
2590             /* Get encoded point length */
2591             i = *p;
2592             p += 1;
2593             if (n != 1 + i) {
2594                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2595                 goto err;
2596             }
2597             if (EC_POINT_oct2point(group, clnt_ecpoint, p, i, bn_ctx) == 0) {
2598                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2599                 goto err;
2600             }
2601             /*
2602              * p is pointing to somewhere in the buffer currently, so set it
2603              * to the start
2604              */
2605             p = (unsigned char *)s->init_buf->data;
2606         }
2607
2608         /* Compute the shared pre-master secret */
2609         field_size = EC_GROUP_get_degree(group);
2610         if (field_size <= 0) {
2611             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2612             goto err;
2613         }
2614         i = ECDH_compute_key(p, (field_size + 7) / 8, clnt_ecpoint, srvr_ecdh,
2615                              NULL);
2616         if (i <= 0) {
2617             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2618             goto err;
2619         }
2620
2621         EVP_PKEY_free(clnt_pub_pkey);
2622         EC_POINT_free(clnt_ecpoint);
2623         EC_KEY_free(srvr_ecdh);
2624         BN_CTX_free(bn_ctx);
2625         EC_KEY_free(s->s3->tmp.ecdh);
2626         s->s3->tmp.ecdh = NULL;
2627
2628         /* Compute the master secret */
2629         s->session->master_key_length =
2630             s->method->ssl3_enc->generate_master_secret(s,
2631                                                         s->
2632                                                         session->master_key,
2633                                                         p, i);
2634
2635         OPENSSL_cleanse(p, i);
2636         if (s->session->master_key_length < 0) {
2637             al = SSL_AD_INTERNAL_ERROR;
2638             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2639             goto f_err;
2640         }
2641         return (ret);
2642     } else
2643 #endif
2644 #ifndef OPENSSL_NO_PSK
2645     if (alg_k & SSL_kPSK) {
2646         unsigned char *t = NULL;
2647         unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN * 2 + 4];
2648         unsigned int pre_ms_len = 0, psk_len = 0;
2649         int psk_err = 1;
2650         char tmp_id[PSK_MAX_IDENTITY_LEN + 1];
2651
2652         al = SSL_AD_HANDSHAKE_FAILURE;
2653
2654         n2s(p, i);
2655         if (n != i + 2) {
2656             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
2657             goto psk_err;
2658         }
2659         if (i > PSK_MAX_IDENTITY_LEN) {
2660             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2661                    SSL_R_DATA_LENGTH_TOO_LONG);
2662             goto psk_err;
2663         }
2664         if (s->psk_server_callback == NULL) {
2665             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2666                    SSL_R_PSK_NO_SERVER_CB);
2667             goto psk_err;
2668         }
2669
2670         /*
2671          * Create guaranteed NULL-terminated identity string for the callback
2672          */
2673         memcpy(tmp_id, p, i);
2674         memset(tmp_id + i, 0, PSK_MAX_IDENTITY_LEN + 1 - i);
2675         psk_len = s->psk_server_callback(s, tmp_id,
2676                                          psk_or_pre_ms,
2677                                          sizeof(psk_or_pre_ms));
2678         OPENSSL_cleanse(tmp_id, sizeof(tmp_id));
2679
2680         if (psk_len > PSK_MAX_PSK_LEN) {
2681             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2682             goto psk_err;
2683         } else if (psk_len == 0) {
2684             /*
2685              * PSK related to the given identity not found
2686              */
2687             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2688                    SSL_R_PSK_IDENTITY_NOT_FOUND);
2689             al = SSL_AD_UNKNOWN_PSK_IDENTITY;
2690             goto psk_err;
2691         }
2692
2693         /* create PSK pre_master_secret */
2694         pre_ms_len = 2 + psk_len + 2 + psk_len;
2695         t = psk_or_pre_ms;
2696         memmove(psk_or_pre_ms + psk_len + 4, psk_or_pre_ms, psk_len);
2697         s2n(psk_len, t);
2698         memset(t, 0, psk_len);
2699         t += psk_len;
2700         s2n(psk_len, t);
2701
2702         OPENSSL_free(s->session->psk_identity);
2703         s->session->psk_identity = BUF_strdup((char *)p);
2704         if (s->session->psk_identity == NULL) {
2705             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2706             goto psk_err;
2707         }
2708
2709         OPENSSL_free(s->session->psk_identity_hint);
2710         s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
2711         if (s->ctx->psk_identity_hint != NULL &&
2712             s->session->psk_identity_hint == NULL) {
2713             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2714             goto psk_err;
2715         }
2716
2717         s->session->master_key_length =
2718             s->method->ssl3_enc->generate_master_secret(s,
2719                                                         s->
2720                                                         session->master_key,
2721                                                         psk_or_pre_ms,
2722                                                         pre_ms_len);
2723         if (s->session->master_key_length < 0) {
2724             al = SSL_AD_INTERNAL_ERROR;
2725             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2726             goto psk_err;
2727         }
2728         psk_err = 0;
2729  psk_err:
2730         OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
2731         if (psk_err != 0)
2732             goto f_err;
2733     } else
2734 #endif
2735 #ifndef OPENSSL_NO_SRP
2736     if (alg_k & SSL_kSRP) {
2737         int param_len;
2738
2739         n2s(p, i);
2740         param_len = i + 2;
2741         if (param_len > n) {
2742             al = SSL_AD_DECODE_ERROR;
2743             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2744                    SSL_R_BAD_SRP_A_LENGTH);
2745             goto f_err;
2746         }
2747         if ((s->srp_ctx.A = BN_bin2bn(p, i, NULL)) == NULL) {
2748             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_BN_LIB);
2749             goto err;
2750         }
2751         if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0
2752             || BN_is_zero(s->srp_ctx.A)) {
2753             al = SSL_AD_ILLEGAL_PARAMETER;
2754             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2755                    SSL_R_BAD_SRP_PARAMETERS);
2756             goto f_err;
2757         }
2758         OPENSSL_free(s->session->srp_username);
2759         s->session->srp_username = BUF_strdup(s->srp_ctx.login);
2760         if (s->session->srp_username == NULL) {
2761             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2762             goto err;
2763         }
2764
2765         if ((s->session->master_key_length =
2766              SRP_generate_server_master_secret(s,
2767                                                s->session->master_key)) < 0) {
2768             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2769             goto err;
2770         }
2771
2772         p += i;
2773     } else
2774 #endif                          /* OPENSSL_NO_SRP */
2775     if (alg_k & SSL_kGOST) {
2776         int ret = 0;
2777         EVP_PKEY_CTX *pkey_ctx;
2778         EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2779         unsigned char premaster_secret[32], *start;
2780         size_t outlen = 32, inlen;
2781         unsigned long alg_a;
2782         int Ttag, Tclass;
2783         long Tlen;
2784
2785         /* Get our certificate private key */
2786         alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2787         if (alg_a & SSL_aGOST94)
2788             pk = s->cert->pkeys[SSL_PKEY_GOST94].privatekey;
2789         else if (alg_a & SSL_aGOST01)
2790             pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2791
2792         pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
2793         EVP_PKEY_decrypt_init(pkey_ctx);
2794         /*
2795          * If client certificate is present and is of the same type, maybe
2796          * use it for key exchange.  Don't mind errors from
2797          * EVP_PKEY_derive_set_peer, because it is completely valid to use a
2798          * client certificate for authorization only.
2799          */
2800         client_pub_pkey = X509_get_pubkey(s->session->peer);
2801         if (client_pub_pkey) {
2802             if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
2803                 ERR_clear_error();
2804         }
2805         /* Decrypt session key */
2806         if (ASN1_get_object
2807             ((const unsigned char **)&p, &Tlen, &Ttag, &Tclass,
2808              n) != V_ASN1_CONSTRUCTED || Ttag != V_ASN1_SEQUENCE
2809             || Tclass != V_ASN1_UNIVERSAL) {
2810             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2811                    SSL_R_DECRYPTION_FAILED);
2812             goto gerr;
2813         }
2814         start = p;
2815         inlen = Tlen;
2816         if (EVP_PKEY_decrypt
2817             (pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {
2818             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2819                    SSL_R_DECRYPTION_FAILED);
2820             goto gerr;
2821         }
2822         /* Generate master secret */
2823         s->session->master_key_length =
2824             s->method->ssl3_enc->generate_master_secret(s,
2825                                                         s->
2826                                                         session->master_key,
2827                                                         premaster_secret, 32);
2828         OPENSSL_cleanse(premaster_secret, sizeof(premaster_secret));
2829         if (s->session->master_key_length < 0) {
2830             al = SSL_AD_INTERNAL_ERROR;
2831             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2832             goto f_err;
2833         }
2834         /* Check if pubkey from client certificate was used */
2835         if (EVP_PKEY_CTX_ctrl
2836             (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
2837             ret = 2;
2838         else
2839             ret = 1;
2840  gerr:
2841         EVP_PKEY_free(client_pub_pkey);
2842         EVP_PKEY_CTX_free(pkey_ctx);
2843         if (ret)
2844             return ret;
2845         goto err;
2846     } else {
2847         al = SSL_AD_HANDSHAKE_FAILURE;
2848         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_UNKNOWN_CIPHER_TYPE);
2849         goto f_err;
2850     }
2851
2852     return (1);
2853  f_err:
2854     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2855 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_EC) || defined(OPENSSL_NO_SRP)
2856  err:
2857 #endif
2858 #ifndef OPENSSL_NO_EC
2859     EVP_PKEY_free(clnt_pub_pkey);
2860     EC_POINT_free(clnt_ecpoint);
2861     EC_KEY_free(srvr_ecdh);
2862     BN_CTX_free(bn_ctx);
2863 #endif
2864     s->state = SSL_ST_ERR;
2865     return (-1);
2866 }
2867
2868 int ssl3_get_cert_verify(SSL *s)
2869 {
2870     EVP_PKEY *pkey = NULL;
2871     unsigned char *p;
2872     int al, ok, ret = 0;
2873     long n;
2874     int type = 0, i, j;
2875     X509 *peer;
2876     const EVP_MD *md = NULL;
2877     EVP_MD_CTX mctx;
2878     EVP_MD_CTX_init(&mctx);
2879
2880     /*
2881      * We should only process a CertificateVerify message if we have received
2882      * a Certificate from the client. If so then |s->session->peer| will be non
2883      * NULL. In some instances a CertificateVerify message is not required even
2884      * if the peer has sent a Certificate (e.g. such as in the case of static
2885      * DH). In that case the ClientKeyExchange processing will skip the
2886      * CertificateVerify state so we should not arrive here.
2887      */
2888     if (s->session->peer == NULL) {
2889         ret = 1;
2890         goto end;
2891     }
2892
2893     n = s->method->ssl_get_message(s,
2894                                    SSL3_ST_SR_CERT_VRFY_A,
2895                                    SSL3_ST_SR_CERT_VRFY_B,
2896                                    SSL3_MT_CERTIFICATE_VERIFY,
2897                                    SSL3_RT_MAX_PLAIN_LENGTH, &ok);
2898
2899     if (!ok)
2900         return ((int)n);
2901
2902     peer = s->session->peer;
2903     pkey = X509_get_pubkey(peer);
2904     type = X509_certificate_type(peer, pkey);
2905
2906     if (!(type & EVP_PKT_SIGN)) {
2907         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2908                SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
2909         al = SSL_AD_ILLEGAL_PARAMETER;
2910         goto f_err;
2911     }
2912
2913     /* we now have a signature that we need to verify */
2914     p = (unsigned char *)s->init_msg;
2915     /* Check for broken implementations of GOST ciphersuites */
2916     /*
2917      * If key is GOST and n is exactly 64, it is bare signature without
2918      * length field
2919      */
2920     if (n == 64 && (pkey->type == NID_id_GostR3410_94 ||
2921                     pkey->type == NID_id_GostR3410_2001)) {
2922         i = 64;
2923     } else {
2924         if (SSL_USE_SIGALGS(s)) {
2925             int rv = tls12_check_peer_sigalg(&md, s, p, pkey);
2926             if (rv == -1) {
2927                 al = SSL_AD_INTERNAL_ERROR;
2928                 goto f_err;
2929             } else if (rv == 0) {
2930                 al = SSL_AD_DECODE_ERROR;
2931                 goto f_err;
2932             }
2933 #ifdef SSL_DEBUG
2934             fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
2935 #endif
2936             p += 2;
2937             n -= 2;
2938         }
2939         n2s(p, i);
2940         n -= 2;
2941         if (i > n) {
2942             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
2943             al = SSL_AD_DECODE_ERROR;
2944             goto f_err;
2945         }
2946     }
2947     j = EVP_PKEY_size(pkey);
2948     if ((i > j) || (n > j) || (n <= 0)) {
2949         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_WRONG_SIGNATURE_SIZE);
2950         al = SSL_AD_DECODE_ERROR;
2951         goto f_err;
2952     }
2953
2954     if (SSL_USE_SIGALGS(s)) {
2955         long hdatalen = 0;
2956         void *hdata;
2957         hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
2958         if (hdatalen <= 0) {
2959             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
2960             al = SSL_AD_INTERNAL_ERROR;
2961             goto f_err;
2962         }
2963 #ifdef SSL_DEBUG
2964         fprintf(stderr, "Using TLS 1.2 with client verify alg %s\n",
2965                 EVP_MD_name(md));
2966 #endif
2967         if (!EVP_VerifyInit_ex(&mctx, md, NULL)
2968             || !EVP_VerifyUpdate(&mctx, hdata, hdatalen)) {
2969             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_EVP_LIB);
2970             al = SSL_AD_INTERNAL_ERROR;
2971             goto f_err;
2972         }
2973
2974         if (EVP_VerifyFinal(&mctx, p, i, pkey) <= 0) {
2975             al = SSL_AD_DECRYPT_ERROR;
2976             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_SIGNATURE);
2977             goto f_err;
2978         }
2979     } else
2980 #ifndef OPENSSL_NO_RSA
2981     if (pkey->type == EVP_PKEY_RSA) {
2982         i = RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
2983                        MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH, p, i,
2984                        pkey->pkey.rsa);
2985         if (i < 0) {
2986             al = SSL_AD_DECRYPT_ERROR;
2987             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_RSA_DECRYPT);
2988             goto f_err;
2989         }
2990         if (i == 0) {
2991             al = SSL_AD_DECRYPT_ERROR;
2992             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_RSA_SIGNATURE);
2993             goto f_err;
2994         }
2995     } else
2996 #endif
2997 #ifndef OPENSSL_NO_DSA
2998     if (pkey->type == EVP_PKEY_DSA) {
2999         j = DSA_verify(pkey->save_type,
3000                        &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3001                        SHA_DIGEST_LENGTH, p, i, pkey->pkey.dsa);
3002         if (j <= 0) {
3003             /* bad signature */
3004             al = SSL_AD_DECRYPT_ERROR;
3005             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_DSA_SIGNATURE);
3006             goto f_err;
3007         }
3008     } else
3009 #endif
3010 #ifndef OPENSSL_NO_EC
3011     if (pkey->type == EVP_PKEY_EC) {
3012         j = ECDSA_verify(pkey->save_type,
3013                          &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3014                          SHA_DIGEST_LENGTH, p, i, pkey->pkey.ec);
3015         if (j <= 0) {
3016             /* bad signature */
3017             al = SSL_AD_DECRYPT_ERROR;
3018             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE);
3019             goto f_err;
3020         }
3021     } else
3022 #endif
3023     if (pkey->type == NID_id_GostR3410_94
3024             || pkey->type == NID_id_GostR3410_2001) {
3025         unsigned char signature[64];
3026         int idx;
3027         EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey, NULL);
3028         EVP_PKEY_verify_init(pctx);
3029         if (i != 64) {
3030             fprintf(stderr, "GOST signature length is %d", i);
3031         }
3032         for (idx = 0; idx < 64; idx++) {
3033             signature[63 - idx] = p[idx];
3034         }
3035         j = EVP_PKEY_verify(pctx, signature, 64, s->s3->tmp.cert_verify_md,
3036                             32);
3037         EVP_PKEY_CTX_free(pctx);
3038         if (j <= 0) {
3039             al = SSL_AD_DECRYPT_ERROR;
3040             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE);
3041             goto f_err;
3042         }
3043     } else {
3044         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
3045         al = SSL_AD_UNSUPPORTED_CERTIFICATE;
3046         goto f_err;
3047     }
3048
3049     ret = 1;
3050     if (0) {
3051  f_err:
3052         ssl3_send_alert(s, SSL3_AL_FATAL, al);
3053         s->state = SSL_ST_ERR;
3054     }
3055  end:
3056     BIO_free(s->s3->handshake_buffer);
3057     s->s3->handshake_buffer = NULL;
3058     s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE;
3059     EVP_MD_CTX_cleanup(&mctx);
3060     EVP_PKEY_free(pkey);
3061     return (ret);
3062 }
3063
3064 int ssl3_get_client_certificate(SSL *s)
3065 {
3066     int i, ok, al, ret = -1;
3067     X509 *x = NULL;
3068     unsigned long l, nc, llen, n;
3069     const unsigned char *p, *q;
3070     unsigned char *d;
3071     STACK_OF(X509) *sk = NULL;
3072
3073     n = s->method->ssl_get_message(s,
3074                                    SSL3_ST_SR_CERT_A,
3075                                    SSL3_ST_SR_CERT_B,
3076                                    -1, s->max_cert_list, &ok);
3077
3078     if (!ok)
3079         return ((int)n);
3080
3081     if (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) {
3082         if ((s->verify_mode & SSL_VERIFY_PEER) &&
3083             (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3084             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3085                    SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3086             al = SSL_AD_HANDSHAKE_FAILURE;
3087             goto f_err;
3088         }
3089         /*
3090          * If tls asked for a client cert, the client must return a 0 list
3091          */
3092         if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request) {
3093             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3094                    SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
3095             al = SSL_AD_UNEXPECTED_MESSAGE;
3096             goto f_err;
3097         }
3098         s->s3->tmp.reuse_message = 1;
3099         return (1);
3100     }
3101
3102     if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE) {
3103         al = SSL_AD_UNEXPECTED_MESSAGE;
3104         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, SSL_R_WRONG_MESSAGE_TYPE);
3105         goto f_err;
3106     }
3107     p = d = (unsigned char *)s->init_msg;
3108
3109     if ((sk = sk_X509_new_null()) == NULL) {
3110         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3111         goto done;
3112     }
3113
3114     n2l3(p, llen);
3115     if (llen + 3 != n) {
3116         al = SSL_AD_DECODE_ERROR;
3117         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
3118         goto f_err;
3119     }
3120     for (nc = 0; nc < llen;) {
3121         n2l3(p, l);
3122         if ((l + nc + 3) > llen) {
3123             al = SSL_AD_DECODE_ERROR;
3124             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3125                    SSL_R_CERT_LENGTH_MISMATCH);
3126             goto f_err;
3127         }
3128
3129         q = p;
3130         x = d2i_X509(NULL, &p, l);
3131         if (x == NULL) {
3132             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_ASN1_LIB);
3133             goto done;
3134         }
3135         if (p != (q + l)) {
3136             al = SSL_AD_DECODE_ERROR;
3137             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3138                    SSL_R_CERT_LENGTH_MISMATCH);
3139             goto f_err;
3140         }
3141         if (!sk_X509_push(sk, x)) {
3142             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3143             goto done;
3144         }
3145         x = NULL;
3146         nc += l + 3;
3147     }
3148
3149     if (sk_X509_num(sk) <= 0) {
3150         /* TLS does not mind 0 certs returned */
3151         if (s->version == SSL3_VERSION) {
3152             al = SSL_AD_HANDSHAKE_FAILURE;
3153             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3154                    SSL_R_NO_CERTIFICATES_RETURNED);
3155             goto f_err;
3156         }
3157         /* Fail for TLS only if we required a certificate */
3158         else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3159                  (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3160             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3161                    SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3162             al = SSL_AD_HANDSHAKE_FAILURE;
3163             goto f_err;
3164         }
3165         /* No client certificate so digest cached records */
3166         if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s)) {
3167             al = SSL_AD_INTERNAL_ERROR;
3168             goto f_err;
3169         }
3170     } else {
3171         EVP_PKEY *pkey;
3172         i = ssl_verify_cert_chain(s, sk);
3173         if (i <= 0) {
3174             al = ssl_verify_alarm_type(s->verify_result);
3175             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3176                    SSL_R_CERTIFICATE_VERIFY_FAILED);
3177             goto f_err;
3178         }
3179         if (i > 1) {
3180             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, i);
3181             al = SSL_AD_HANDSHAKE_FAILURE;
3182             goto f_err;
3183         }
3184         pkey = X509_get_pubkey(sk_X509_value(sk, 0));
3185         if (pkey == NULL) {
3186             al = SSL3_AD_HANDSHAKE_FAILURE;
3187             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3188                    SSL_R_UNKNOWN_CERTIFICATE_TYPE);
3189             goto f_err;
3190         }
3191         EVP_PKEY_free(pkey);
3192     }
3193
3194     X509_free(s->session->peer);
3195     s->session->peer = sk_X509_shift(sk);
3196     s->session->verify_result = s->verify_result;
3197
3198     /*
3199      * With the current implementation, sess_cert will always be NULL when we
3200      * arrive here.
3201      */
3202     if (s->session->sess_cert == NULL) {
3203         s->session->sess_cert = ssl_sess_cert_new();
3204         if (s->session->sess_cert == NULL) {
3205             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3206             goto done;
3207         }
3208     }
3209     sk_X509_pop_free(s->session->peer_chain, X509_free);
3210     s->session->peer_chain = sk;
3211     /*
3212      * Inconsistency alert: cert_chain does *not* include the peer's own
3213      * certificate, while we do include it in s3_clnt.c
3214      */
3215     sk = NULL;
3216     ret = 1;
3217     goto done;
3218
3219  f_err:
3220     ssl3_send_alert(s, SSL3_AL_FATAL, al);
3221  done:
3222     s->state = SSL_ST_ERR;
3223     X509_free(x);
3224     sk_X509_pop_free(sk, X509_free);
3225     return (ret);
3226 }
3227
3228 int ssl3_send_server_certificate(SSL *s)
3229 {
3230     CERT_PKEY *cpk;
3231
3232     if (s->state == SSL3_ST_SW_CERT_A) {
3233         cpk = ssl_get_server_send_pkey(s);
3234         if (cpk == NULL) {
3235             SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3236             s->state = SSL_ST_ERR;
3237             return (0);
3238         }
3239
3240         if (!ssl3_output_cert_chain(s, cpk)) {
3241             SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3242             s->state = SSL_ST_ERR;
3243             return (0);
3244         }
3245         s->state = SSL3_ST_SW_CERT_B;
3246     }
3247
3248     /* SSL3_ST_SW_CERT_B */
3249     return ssl_do_write(s);
3250 }
3251
3252 /* send a new session ticket (not necessarily for a new session) */
3253 int ssl3_send_newsession_ticket(SSL *s)
3254 {
3255     unsigned char *senc = NULL;
3256     EVP_CIPHER_CTX ctx;
3257     HMAC_CTX hctx;
3258
3259     if (s->state == SSL3_ST_SW_SESSION_TICKET_A) {
3260         unsigned char *p, *macstart;
3261         const unsigned char *const_p;
3262         int len, slen_full, slen;
3263         SSL_SESSION *sess;
3264         unsigned int hlen;
3265         SSL_CTX *tctx = s->initial_ctx;
3266         unsigned char iv[EVP_MAX_IV_LENGTH];
3267         unsigned char key_name[16];
3268
3269         /* get session encoding length */
3270         slen_full = i2d_SSL_SESSION(s->session, NULL);
3271         /*
3272          * Some length values are 16 bits, so forget it if session is too
3273          * long
3274          */
3275         if (slen_full == 0 || slen_full > 0xFF00) {
3276             s->state = SSL_ST_ERR;
3277             return -1;
3278         }
3279         senc = OPENSSL_malloc(slen_full);
3280         if (!senc) {
3281             s->state = SSL_ST_ERR;
3282             return -1;
3283         }
3284
3285         EVP_CIPHER_CTX_init(&ctx);
3286         HMAC_CTX_init(&hctx);
3287
3288         p = senc;
3289         if (!i2d_SSL_SESSION(s->session, &p))
3290             goto err;
3291
3292         /*
3293          * create a fresh copy (not shared with other threads) to clean up
3294          */
3295         const_p = senc;
3296         sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3297         if (sess == NULL)
3298             goto err;
3299         sess->session_id_length = 0; /* ID is irrelevant for the ticket */
3300
3301         slen = i2d_SSL_SESSION(sess, NULL);
3302         if (slen == 0 || slen > slen_full) { /* shouldn't ever happen */
3303             SSL_SESSION_free(sess);
3304             goto err;
3305         }
3306         p = senc;
3307         if (!i2d_SSL_SESSION(sess, &p)) {
3308             SSL_SESSION_free(sess);
3309             goto err;
3310         }
3311         SSL_SESSION_free(sess);
3312
3313         /*-
3314          * Grow buffer if need be: the length calculation is as
3315          * follows handshake_header_length +
3316          * 4 (ticket lifetime hint) + 2 (ticket length) +
3317          * 16 (key name) + max_iv_len (iv length) +
3318          * session_length + max_enc_block_size (max encrypted session
3319          * length) + max_md_size (HMAC).
3320          */
3321         if (!BUF_MEM_grow(s->init_buf,
3322                           SSL_HM_HEADER_LENGTH(s) + 22 + EVP_MAX_IV_LENGTH +
3323                           EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE + slen))
3324             goto err;
3325
3326         p = ssl_handshake_start(s);
3327         /*
3328          * Initialize HMAC and cipher contexts. If callback present it does
3329          * all the work otherwise use generated values from parent ctx.
3330          */
3331         if (tctx->tlsext_ticket_key_cb) {
3332             if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
3333                                            &hctx, 1) < 0)
3334                 goto err;
3335         } else {
3336             if (RAND_bytes(iv, 16) <= 0)
3337                 goto err;
3338             if (!EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3339                                     tctx->tlsext_tick_aes_key, iv))
3340                 goto err;
3341             if (!HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3342                               EVP_sha256(), NULL))
3343                 goto err;
3344             memcpy(key_name, tctx->tlsext_tick_key_name, 16);
3345         }
3346
3347         /*
3348          * Ticket lifetime hint (advisory only): We leave this unspecified
3349          * for resumed session (for simplicity), and guess that tickets for
3350          * new sessions will live as long as their sessions.
3351          */
3352         l2n(s->hit ? 0 : s->session->timeout, p);
3353
3354         /* Skip ticket length for now */
3355         p += 2;
3356         /* Output key name */
3357         macstart = p;
3358         memcpy(p, key_name, 16);
3359         p += 16;
3360         /* output IV */
3361         memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
3362         p += EVP_CIPHER_CTX_iv_length(&ctx);
3363         /* Encrypt session data */
3364         if (!EVP_EncryptUpdate(&ctx, p, &len, senc, slen))
3365             goto err;
3366         p += len;
3367         if (!EVP_EncryptFinal(&ctx, p, &len))
3368             goto err;
3369         p += len;
3370
3371         if (!HMAC_Update(&hctx, macstart, p - macstart))
3372             goto err;
3373         if (!HMAC_Final(&hctx, p, &hlen))
3374             goto err;
3375
3376         EVP_CIPHER_CTX_cleanup(&ctx);
3377         HMAC_CTX_cleanup(&hctx);
3378
3379         p += hlen;
3380         /* Now write out lengths: p points to end of data written */
3381         /* Total length */
3382         len = p - ssl_handshake_start(s);
3383         /* Skip ticket lifetime hint */
3384         p = ssl_handshake_start(s) + 4;
3385         s2n(len - 6, p);
3386         if (!ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len))
3387             goto err;
3388         s->state = SSL3_ST_SW_SESSION_TICKET_B;
3389         OPENSSL_free(senc);
3390     }
3391
3392     /* SSL3_ST_SW_SESSION_TICKET_B */
3393     return ssl_do_write(s);
3394  err:
3395     OPENSSL_free(senc);
3396     EVP_CIPHER_CTX_cleanup(&ctx);
3397     HMAC_CTX_cleanup(&hctx);
3398     s->state = SSL_ST_ERR;
3399     return -1;
3400 }
3401
3402 int ssl3_send_cert_status(SSL *s)
3403 {
3404     if (s->state == SSL3_ST_SW_CERT_STATUS_A) {
3405         unsigned char *p;
3406         /*-
3407          * Grow buffer if need be: the length calculation is as
3408          * follows 1 (message type) + 3 (message length) +
3409          * 1 (ocsp response type) + 3 (ocsp response length)
3410          * + (ocsp response)
3411          */
3412         if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen)) {
3413             s->state = SSL_ST_ERR;
3414             return -1;
3415         }
3416
3417         p = (unsigned char *)s->init_buf->data;
3418
3419         /* do the header */
3420         *(p++) = SSL3_MT_CERTIFICATE_STATUS;
3421         /* message length */
3422         l2n3(s->tlsext_ocsp_resplen + 4, p);
3423         /* status type */
3424         *(p++) = s->tlsext_status_type;
3425         /* length of OCSP response */
3426         l2n3(s->tlsext_ocsp_resplen, p);
3427         /* actual response */
3428         memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
3429         /* number of bytes to write */
3430         s->init_num = 8 + s->tlsext_ocsp_resplen;
3431         s->state = SSL3_ST_SW_CERT_STATUS_B;
3432         s->init_off = 0;
3433     }
3434
3435     /* SSL3_ST_SW_CERT_STATUS_B */
3436     return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
3437 }
3438
3439 #ifndef OPENSSL_NO_NEXTPROTONEG
3440 /*
3441  * ssl3_get_next_proto reads a Next Protocol Negotiation handshake message.
3442  * It sets the next_proto member in s if found
3443  */
3444 int ssl3_get_next_proto(SSL *s)
3445 {
3446     int ok;
3447     int proto_len, padding_len;
3448     long n;
3449     const unsigned char *p;
3450
3451     /*
3452      * Clients cannot send a NextProtocol message if we didn't see the
3453      * extension in their ClientHello
3454      */
3455     if (!s->s3->next_proto_neg_seen) {
3456         SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,
3457                SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
3458         s->state = SSL_ST_ERR;
3459         return -1;
3460     }
3461
3462     /* See the payload format below */
3463     n = s->method->ssl_get_message(s,
3464                                    SSL3_ST_SR_NEXT_PROTO_A,
3465                                    SSL3_ST_SR_NEXT_PROTO_B,
3466                                    SSL3_MT_NEXT_PROTO, 514, &ok);
3467
3468     if (!ok)
3469         return ((int)n);
3470
3471     /*
3472      * s->state doesn't reflect whether ChangeCipherSpec has been received in
3473      * this handshake, but s->s3->change_cipher_spec does (will be reset by
3474      * ssl3_get_finished).
3475      */
3476     if (!s->s3->change_cipher_spec) {
3477         SSLerr(SSL_F_SSL3_GET_NEXT_PROTO, SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS);
3478         s->state = SSL_ST_ERR;
3479         return -1;
3480     }
3481
3482     if (n < 2) {
3483         s->state = SSL_ST_ERR;
3484         return 0;               /* The body must be > 1 bytes long */
3485     }
3486
3487     p = (unsigned char *)s->init_msg;
3488
3489     /*-
3490      * The payload looks like:
3491      *   uint8 proto_len;
3492      *   uint8 proto[proto_len];
3493      *   uint8 padding_len;
3494      *   uint8 padding[padding_len];
3495      */
3496     proto_len = p[0];
3497     if (proto_len + 2 > s->init_num) {
3498         s->state = SSL_ST_ERR;
3499         return 0;
3500     }
3501     padding_len = p[proto_len + 1];
3502     if (proto_len + padding_len + 2 != s->init_num) {
3503         s->state = SSL_ST_ERR;
3504         return 0;
3505     }
3506
3507     s->next_proto_negotiated = OPENSSL_malloc(proto_len);
3508     if (!s->next_proto_negotiated) {
3509         SSLerr(SSL_F_SSL3_GET_NEXT_PROTO, ERR_R_MALLOC_FAILURE);
3510         s->state = SSL_ST_ERR;
3511         return 0;
3512     }
3513     memcpy(s->next_proto_negotiated, p + 1, proto_len);
3514     s->next_proto_negotiated_len = proto_len;
3515
3516     return 1;
3517 }
3518 #endif
3519
3520 #define SSLV2_CIPHER_LEN    3
3521
3522 STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list(SSL *s, unsigned char *p,
3523                                                int num,
3524                                                STACK_OF(SSL_CIPHER) **skp,
3525                                                int sslv2format)
3526 {
3527     const SSL_CIPHER *c;
3528     STACK_OF(SSL_CIPHER) *sk;
3529     int i, n;
3530
3531     if (s->s3)
3532         s->s3->send_connection_binding = 0;
3533
3534     if(sslv2format) {
3535         n = SSLV2_CIPHER_LEN;
3536     } else {
3537         n = ssl_put_cipher_by_char(s, NULL, NULL);
3538     }
3539     if (n == 0 || (num % n) != 0) {
3540         SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
3541                SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
3542         return (NULL);
3543     }
3544     if ((skp == NULL) || (*skp == NULL)) {
3545         sk = sk_SSL_CIPHER_new_null(); /* change perhaps later */
3546         if(sk == NULL) {
3547             SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
3548             return NULL;
3549         }
3550     } else {
3551         sk = *skp;
3552         sk_SSL_CIPHER_zero(sk);
3553     }
3554
3555     OPENSSL_free(s->s3->tmp.ciphers_raw);
3556     s->s3->tmp.ciphers_raw = BUF_memdup(p, num);
3557     if (s->s3->tmp.ciphers_raw == NULL) {
3558         SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
3559         goto err;
3560     }
3561     s->s3->tmp.ciphers_rawlen = (size_t)num;
3562
3563     for (i = 0; i < num; i += n) {
3564         /* Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV */
3565         if (s->s3 && (n != 3 || !p[0]) &&
3566             (p[n - 2] == ((SSL3_CK_SCSV >> 8) & 0xff)) &&
3567             (p[n - 1] == (SSL3_CK_SCSV & 0xff))) {
3568             /* SCSV fatal if renegotiating */
3569             if (s->renegotiate) {
3570                 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
3571                        SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING);
3572                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
3573                 goto err;
3574             }
3575             s->s3->send_connection_binding = 1;
3576             p += n;
3577 #ifdef OPENSSL_RI_DEBUG
3578             fprintf(stderr, "SCSV received by server\n");
3579 #endif
3580             continue;
3581         }
3582
3583         /* Check for TLS_FALLBACK_SCSV */
3584         if ((n != 3 || !p[0]) &&
3585             (p[n - 2] == ((SSL3_CK_FALLBACK_SCSV >> 8) & 0xff)) &&
3586             (p[n - 1] == (SSL3_CK_FALLBACK_SCSV & 0xff))) {
3587             /*
3588              * The SCSV indicates that the client previously tried a higher
3589              * version. Fail if the current version is an unexpected
3590              * downgrade.
3591              */
3592             if (!SSL_ctrl(s, SSL_CTRL_CHECK_PROTO_VERSION, 0, NULL)) {
3593                 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
3594                        SSL_R_INAPPROPRIATE_FALLBACK);
3595                 if (s->s3)
3596                     ssl3_send_alert(s, SSL3_AL_FATAL,
3597                                     SSL_AD_INAPPROPRIATE_FALLBACK);
3598                 goto err;
3599             }
3600             p += n;
3601             continue;
3602         }
3603
3604         if(sslv2format) {
3605             /*
3606              * We only support SSLv2 format ciphers in SSLv3+ using a
3607              * SSLv2 backward compatible ClientHello. In this case the first
3608              * byte is always 0 for SSLv3 compatible ciphers. Anything else
3609              * is an SSLv2 cipher and we ignore it
3610              */
3611             if(p[0] == 0)
3612                 c = ssl_get_cipher_by_char(s, &p[1]);
3613             else
3614                 c = NULL;
3615         } else {
3616             c = ssl_get_cipher_by_char(s, p);
3617         }
3618         p += n;
3619         if (c != NULL) {
3620             if (!sk_SSL_CIPHER_push(sk, c)) {
3621                 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
3622                 goto err;
3623             }
3624         }
3625     }
3626
3627     if (skp != NULL)
3628         *skp = sk;
3629     return (sk);
3630  err:
3631     if ((skp == NULL) || (*skp == NULL))
3632         sk_SSL_CIPHER_free(sk);
3633     return (NULL);
3634 }