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