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