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