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