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