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