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