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