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