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