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