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