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