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