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