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