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