3ff427650b9b2c9ade9f36d6f0f426aa72f6b221
[openssl.git] / ssl / statem / statem_clnt.c
1 /* ssl/statem/statem_clnt.c */
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 #include <stdio.h>
152 #include "../ssl_locl.h"
153 #include <openssl/buffer.h>
154 #include <openssl/rand.h>
155 #include <openssl/objects.h>
156 #include <openssl/evp.h>
157 #include <openssl/md5.h>
158 #ifndef OPENSSL_NO_DH
159 # include <openssl/dh.h>
160 #endif
161 #include <openssl/bn.h>
162 #ifndef OPENSSL_NO_ENGINE
163 # include <openssl/engine.h>
164 #endif
165
166 static int ssl_set_version(SSL *s);
167 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b);
168 static int ssl_cipher_list_to_bytes(SSL *s, STACK_OF(SSL_CIPHER) *sk,
169                                     unsigned char *p);
170
171 /*
172  * Work out what version we should be using for the initial ClientHello if
173  * the version is currently set to (D)TLS_ANY_VERSION.
174  * Returns 1 on success
175  * Returns 0 on error
176  */
177 static int ssl_set_version(SSL *s)
178 {
179     unsigned long mask, options = s->options;
180
181     if (s->method->version == TLS_ANY_VERSION) {
182         /*
183          * SSL_OP_NO_X disables all protocols above X *if* there are
184          * some protocols below X enabled. This is required in order
185          * to maintain "version capability" vector contiguous. So
186          * that if application wants to disable TLS1.0 in favour of
187          * TLS1>=1, it would be insufficient to pass SSL_NO_TLSv1, the
188          * answer is SSL_OP_NO_TLSv1|SSL_OP_NO_SSLv3.
189          */
190         mask = SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1
191 #if !defined(OPENSSL_NO_SSL3)
192             | SSL_OP_NO_SSLv3
193 #endif
194             ;
195 #if !defined(OPENSSL_NO_TLS1_2_CLIENT)
196         if (options & SSL_OP_NO_TLSv1_2) {
197             if ((options & mask) != mask) {
198                 s->version = TLS1_1_VERSION;
199             } else {
200                 SSLerr(SSL_F_SSL_SET_VERSION, SSL_R_NO_PROTOCOLS_AVAILABLE);
201                 return 0;
202             }
203         } else {
204             s->version = TLS1_2_VERSION;
205         }
206 #else
207         if ((options & mask) == mask) {
208             SSLerr(SSL_F_SSL_SET_VERSION, SSL_R_NO_PROTOCOLS_AVAILABLE);
209             return 0;
210         }
211         s->version = TLS1_1_VERSION;
212 #endif
213
214         mask &= ~SSL_OP_NO_TLSv1_1;
215         if ((options & SSL_OP_NO_TLSv1_1) && (options & mask) != mask)
216             s->version = TLS1_VERSION;
217         mask &= ~SSL_OP_NO_TLSv1;
218 #if !defined(OPENSSL_NO_SSL3)
219         if ((options & SSL_OP_NO_TLSv1) && (options & mask) != mask)
220             s->version = SSL3_VERSION;
221 #endif
222
223         if (s->version != TLS1_2_VERSION && tls1_suiteb(s)) {
224             SSLerr(SSL_F_SSL_SET_VERSION,
225                    SSL_R_ONLY_TLS_1_2_ALLOWED_IN_SUITEB_MODE);
226             return 0;
227         }
228
229         if (s->version == SSL3_VERSION && FIPS_mode()) {
230             SSLerr(SSL_F_SSL_SET_VERSION, SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE);
231             return 0;
232         }
233
234     } else if (s->method->version == DTLS_ANY_VERSION) {
235         /* Determine which DTLS version to use */
236         /* If DTLS 1.2 disabled correct the version number */
237         if (options & SSL_OP_NO_DTLSv1_2) {
238             if (tls1_suiteb(s)) {
239                 SSLerr(SSL_F_SSL_SET_VERSION,
240                        SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
241                 return 0;
242             }
243             /*
244              * Disabling all versions is silly: return an error.
245              */
246             if (options & SSL_OP_NO_DTLSv1) {
247                 SSLerr(SSL_F_SSL_SET_VERSION, SSL_R_WRONG_SSL_VERSION);
248                 return 0;
249             }
250             /*
251              * Update method so we don't use any DTLS 1.2 features.
252              */
253             s->method = DTLSv1_client_method();
254             s->version = DTLS1_VERSION;
255         } else {
256             /*
257              * We only support one version: update method
258              */
259             if (options & SSL_OP_NO_DTLSv1)
260                 s->method = DTLSv1_2_client_method();
261             s->version = DTLS1_2_VERSION;
262         }
263     }
264
265     s->client_version = s->version;
266
267     return 1;
268 }
269
270 int tls_construct_client_hello(SSL *s)
271 {
272     unsigned char *buf;
273     unsigned char *p, *d;
274     int i;
275     unsigned long l;
276     int al = 0;
277 #ifndef OPENSSL_NO_COMP
278     int j;
279     SSL_COMP *comp;
280 #endif
281     SSL_SESSION *sess = s->session;
282
283     buf = (unsigned char *)s->init_buf->data;
284
285     /* Work out what SSL/TLS/DTLS version to use */
286     if (ssl_set_version(s) == 0)
287         goto err;
288
289     if ((sess == NULL) || (sess->ssl_version != s->version) ||
290         /*
291          * In the case of EAP-FAST, we can have a pre-shared
292          * "ticket" without a session ID.
293          */
294         (!sess->session_id_length && !sess->tlsext_tick) ||
295         (sess->not_resumable)) {
296         if (!ssl_get_new_session(s, 0))
297             goto err;
298     }
299     /* else use the pre-loaded session */
300
301     p = s->s3->client_random;
302
303     /*
304      * for DTLS if client_random is initialized, reuse it, we are
305      * required to use same upon reply to HelloVerify
306      */
307     if (SSL_IS_DTLS(s)) {
308         size_t idx;
309         i = 1;
310         for (idx = 0; idx < sizeof(s->s3->client_random); idx++) {
311             if (p[idx]) {
312                 i = 0;
313                 break;
314             }
315         }
316     } else
317         i = 1;
318
319     if (i && ssl_fill_hello_random(s, 0, p,
320                                    sizeof(s->s3->client_random)) <= 0)
321         goto err;
322
323     /* Do the message type and length last */
324     d = p = ssl_handshake_start(s);
325
326     /*-
327      * version indicates the negotiated version: for example from
328      * an SSLv2/v3 compatible client hello). The client_version
329      * field is the maximum version we permit and it is also
330      * used in RSA encrypted premaster secrets. Some servers can
331      * choke if we initially report a higher version then
332      * renegotiate to a lower one in the premaster secret. This
333      * didn't happen with TLS 1.0 as most servers supported it
334      * but it can with TLS 1.1 or later if the server only supports
335      * 1.0.
336      *
337      * Possible scenario with previous logic:
338      *      1. Client hello indicates TLS 1.2
339      *      2. Server hello says TLS 1.0
340      *      3. RSA encrypted premaster secret uses 1.2.
341      *      4. Handhaked proceeds using TLS 1.0.
342      *      5. Server sends hello request to renegotiate.
343      *      6. Client hello indicates TLS v1.0 as we now
344      *         know that is maximum server supports.
345      *      7. Server chokes on RSA encrypted premaster secret
346      *         containing version 1.0.
347      *
348      * For interoperability it should be OK to always use the
349      * maximum version we support in client hello and then rely
350      * on the checking of version to ensure the servers isn't
351      * being inconsistent: for example initially negotiating with
352      * TLS 1.0 and renegotiating with TLS 1.2. We do this by using
353      * client_version in client hello and not resetting it to
354      * the negotiated version.
355      */
356     *(p++) = s->client_version >> 8;
357     *(p++) = s->client_version & 0xff;
358
359     /* Random stuff */
360     memcpy(p, s->s3->client_random, SSL3_RANDOM_SIZE);
361     p += SSL3_RANDOM_SIZE;
362
363     /* Session ID */
364     if (s->new_session)
365         i = 0;
366     else
367         i = s->session->session_id_length;
368     *(p++) = i;
369     if (i != 0) {
370         if (i > (int)sizeof(s->session->session_id)) {
371             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
372             goto err;
373         }
374         memcpy(p, s->session->session_id, i);
375         p += i;
376     }
377
378     /* cookie stuff for DTLS */
379     if (SSL_IS_DTLS(s)) {
380         if (s->d1->cookie_len > sizeof(s->d1->cookie)) {
381             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
382             goto err;
383         }
384         *(p++) = s->d1->cookie_len;
385         memcpy(p, s->d1->cookie, s->d1->cookie_len);
386         p += s->d1->cookie_len;
387     }
388
389     /* Ciphers supported */
390     i = ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s), &(p[2]));
391     if (i == 0) {
392         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, SSL_R_NO_CIPHERS_AVAILABLE);
393         goto err;
394     }
395 #ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH
396     /*
397      * Some servers hang if client hello > 256 bytes as hack workaround
398      * chop number of supported ciphers to keep it well below this if we
399      * use TLS v1.2
400      */
401     if (TLS1_get_version(s) >= TLS1_2_VERSION
402         && i > OPENSSL_MAX_TLS1_2_CIPHER_LENGTH)
403         i = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1;
404 #endif
405     s2n(i, p);
406     p += i;
407
408     /* COMPRESSION */
409 #ifdef OPENSSL_NO_COMP
410     *(p++) = 1;
411 #else
412
413     if (!ssl_allow_compression(s) || !s->ctx->comp_methods)
414         j = 0;
415     else
416         j = sk_SSL_COMP_num(s->ctx->comp_methods);
417     *(p++) = 1 + j;
418     for (i = 0; i < j; i++) {
419         comp = sk_SSL_COMP_value(s->ctx->comp_methods, i);
420         *(p++) = comp->id;
421     }
422 #endif
423     *(p++) = 0;             /* Add the NULL method */
424
425     /* TLS extensions */
426     if (ssl_prepare_clienthello_tlsext(s) <= 0) {
427         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
428         goto err;
429     }
430     if ((p =
431          ssl_add_clienthello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,
432                                     &al)) == NULL) {
433         ssl3_send_alert(s, SSL3_AL_FATAL, al);
434         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
435         goto err;
436     }
437
438     l = p - d;
439     if (!ssl_set_handshake_header(s, SSL3_MT_CLIENT_HELLO, l)) {
440         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
441         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
442         goto err;
443     }
444
445     return 1;
446  err:
447     statem_set_error(s);
448     return 0;
449 }
450
451 enum MSG_PROCESS_RETURN dtls_process_hello_verify(SSL *s, PACKET *pkt)
452 {
453     int al;
454     unsigned int cookie_len;
455     PACKET cookiepkt;
456
457     if (!PACKET_forward(pkt, 2)
458             || !PACKET_get_length_prefixed_1(pkt, &cookiepkt)) {
459         al = SSL_AD_DECODE_ERROR;
460         SSLerr(SSL_F_DTLS_PROCESS_HELLO_VERIFY, SSL_R_LENGTH_MISMATCH);
461         goto f_err;
462     }
463
464     cookie_len = PACKET_remaining(&cookiepkt);
465     if (cookie_len > sizeof(s->d1->cookie)) {
466         al = SSL_AD_ILLEGAL_PARAMETER;
467         SSLerr(SSL_F_DTLS_PROCESS_HELLO_VERIFY, SSL_R_LENGTH_TOO_LONG);
468         goto f_err;
469     }
470
471     if (!PACKET_copy_bytes(&cookiepkt, s->d1->cookie, cookie_len)) {
472         al = SSL_AD_DECODE_ERROR;
473         SSLerr(SSL_F_DTLS_PROCESS_HELLO_VERIFY, SSL_R_LENGTH_MISMATCH);
474         goto f_err;
475     }
476     s->d1->cookie_len = cookie_len;
477
478     return MSG_PROCESS_FINISHED_READING;
479  f_err:
480     ssl3_send_alert(s, SSL3_AL_FATAL, al);
481     statem_set_error(s);
482     return MSG_PROCESS_ERROR;
483 }
484
485 enum MSG_PROCESS_RETURN tls_process_server_hello(SSL *s, PACKET *pkt)
486 {
487     STACK_OF(SSL_CIPHER) *sk;
488     const SSL_CIPHER *c;
489     PACKET session_id;
490     size_t session_id_len;
491     unsigned char *cipherchars;
492     int i, al = SSL_AD_INTERNAL_ERROR;
493     unsigned int compression;
494 #ifndef OPENSSL_NO_COMP
495     SSL_COMP *comp;
496 #endif
497
498     if (s->method->version == TLS_ANY_VERSION) {
499         unsigned int sversion;
500
501         if (!PACKET_get_net_2(pkt, &sversion)) {
502             al = SSL_AD_DECODE_ERROR;
503             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
504             goto f_err;
505         }
506
507 #if TLS_MAX_VERSION != TLS1_2_VERSION
508 #error Code needs updating for new TLS version
509 #endif
510 #ifndef OPENSSL_NO_SSL3
511         if ((sversion == SSL3_VERSION) && !(s->options & SSL_OP_NO_SSLv3)) {
512             if (FIPS_mode()) {
513                 SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
514                        SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE);
515                 al = SSL_AD_PROTOCOL_VERSION;
516                 goto f_err;
517             }
518             s->method = SSLv3_client_method();
519         } else
520 #endif
521         if ((sversion == TLS1_VERSION) && !(s->options & SSL_OP_NO_TLSv1)) {
522             s->method = TLSv1_client_method();
523         } else if ((sversion == TLS1_1_VERSION) &&
524                    !(s->options & SSL_OP_NO_TLSv1_1)) {
525             s->method = TLSv1_1_client_method();
526         } else if ((sversion == TLS1_2_VERSION) &&
527                    !(s->options & SSL_OP_NO_TLSv1_2)) {
528             s->method = TLSv1_2_client_method();
529         } else {
530             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_UNSUPPORTED_PROTOCOL);
531             al = SSL_AD_PROTOCOL_VERSION;
532             goto f_err;
533         }
534         s->session->ssl_version = s->version = s->method->version;
535
536         if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL)) {
537             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_VERSION_TOO_LOW);
538             al = SSL_AD_PROTOCOL_VERSION;
539             goto f_err;
540         }
541     } else if (s->method->version == DTLS_ANY_VERSION) {
542         /* Work out correct protocol version to use */
543         unsigned int hversion;
544         int options;
545
546         if (!PACKET_get_net_2(pkt, &hversion)) {
547             al = SSL_AD_DECODE_ERROR;
548             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
549             goto f_err;
550         }
551
552         options = s->options;
553         if (hversion == DTLS1_2_VERSION && !(options & SSL_OP_NO_DTLSv1_2))
554             s->method = DTLSv1_2_client_method();
555         else if (tls1_suiteb(s)) {
556             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
557                    SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
558             s->version = hversion;
559             al = SSL_AD_PROTOCOL_VERSION;
560             goto f_err;
561         } else if (hversion == DTLS1_VERSION && !(options & SSL_OP_NO_DTLSv1))
562             s->method = DTLSv1_client_method();
563         else {
564             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_WRONG_SSL_VERSION);
565             s->version = hversion;
566             al = SSL_AD_PROTOCOL_VERSION;
567             goto f_err;
568         }
569         s->session->ssl_version = s->version = s->method->version;
570     } else {
571         unsigned char *vers;
572
573         if (!PACKET_get_bytes(pkt, &vers, 2)) {
574             al = SSL_AD_DECODE_ERROR;
575             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
576             goto f_err;
577         }
578         if ((vers[0] != (s->version >> 8))
579                 || (vers[1] != (s->version & 0xff))) {
580             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_WRONG_SSL_VERSION);
581             s->version = (s->version & 0xff00) | vers[1];
582             al = SSL_AD_PROTOCOL_VERSION;
583             goto f_err;
584         }
585     }
586
587     /* load the server hello data */
588     /* load the server random */
589     if (!PACKET_copy_bytes(pkt, s->s3->server_random, SSL3_RANDOM_SIZE)) {
590         al = SSL_AD_DECODE_ERROR;
591         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
592         goto f_err;
593     }
594
595     s->hit = 0;
596
597     /* Get the session-id. */
598     if (!PACKET_get_length_prefixed_1(pkt, &session_id)) {
599         al = SSL_AD_DECODE_ERROR;
600         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
601         goto f_err;
602     }
603     session_id_len = PACKET_remaining(&session_id);
604     if (session_id_len > sizeof s->session->session_id
605         || session_id_len > SSL3_SESSION_ID_SIZE) {
606         al = SSL_AD_ILLEGAL_PARAMETER;
607         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_SSL3_SESSION_ID_TOO_LONG);
608         goto f_err;
609     }
610
611     if (!PACKET_get_bytes(pkt, &cipherchars, TLS_CIPHER_LEN)) {
612         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
613         al = SSL_AD_DECODE_ERROR;
614         goto f_err;
615     }
616
617     /*
618      * Check if we can resume the session based on external pre-shared secret.
619      * EAP-FAST (RFC 4851) supports two types of session resumption.
620      * Resumption based on server-side state works with session IDs.
621      * Resumption based on pre-shared Protected Access Credentials (PACs)
622      * works by overriding the SessionTicket extension at the application
623      * layer, and does not send a session ID. (We do not know whether EAP-FAST
624      * servers would honour the session ID.) Therefore, the session ID alone
625      * is not a reliable indicator of session resumption, so we first check if
626      * we can resume, and later peek at the next handshake message to see if the
627      * server wants to resume.
628      */
629     if (s->version >= TLS1_VERSION && s->tls_session_secret_cb &&
630         s->session->tlsext_tick) {
631         SSL_CIPHER *pref_cipher = NULL;
632         s->session->master_key_length = sizeof(s->session->master_key);
633         if (s->tls_session_secret_cb(s, s->session->master_key,
634                                      &s->session->master_key_length,
635                                      NULL, &pref_cipher,
636                                      s->tls_session_secret_cb_arg)) {
637             s->session->cipher = pref_cipher ?
638                 pref_cipher : ssl_get_cipher_by_char(s, cipherchars);
639         } else {
640             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
641             al = SSL_AD_INTERNAL_ERROR;
642             goto f_err;
643         }
644     }
645
646     if (session_id_len != 0 && session_id_len == s->session->session_id_length
647         && memcmp(PACKET_data(&session_id), s->session->session_id,
648                   session_id_len) == 0) {
649         if (s->sid_ctx_length != s->session->sid_ctx_length
650             || memcmp(s->session->sid_ctx, s->sid_ctx, s->sid_ctx_length)) {
651             /* actually a client application bug */
652             al = SSL_AD_ILLEGAL_PARAMETER;
653             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
654                    SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
655             goto f_err;
656         }
657         s->hit = 1;
658     } else {
659         /*
660          * If we were trying for session-id reuse but the server
661          * didn't echo the ID, make a new SSL_SESSION.
662          * In the case of EAP-FAST and PAC, we do not send a session ID,
663          * so the PAC-based session secret is always preserved. It'll be
664          * overwritten if the server refuses resumption.
665          */
666         if (s->session->session_id_length > 0) {
667             if (!ssl_get_new_session(s, 0)) {
668                 goto f_err;
669             }
670         }
671
672         s->session->session_id_length = session_id_len;
673         /* session_id_len could be 0 */
674         memcpy(s->session->session_id, PACKET_data(&session_id),
675                session_id_len);
676     }
677
678     c = ssl_get_cipher_by_char(s, cipherchars);
679     if (c == NULL) {
680         /* unknown cipher */
681         al = SSL_AD_ILLEGAL_PARAMETER;
682         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_UNKNOWN_CIPHER_RETURNED);
683         goto f_err;
684     }
685     /* Set version disabled mask now we know version */
686     if (!SSL_USE_TLS1_2_CIPHERS(s))
687         s->s3->tmp.mask_ssl = SSL_TLSV1_2;
688     else
689         s->s3->tmp.mask_ssl = 0;
690     /*
691      * If it is a disabled cipher we didn't send it in client hello, so
692      * return an error.
693      */
694     if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_CHECK)) {
695         al = SSL_AD_ILLEGAL_PARAMETER;
696         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_WRONG_CIPHER_RETURNED);
697         goto f_err;
698     }
699
700     sk = ssl_get_ciphers_by_id(s);
701     i = sk_SSL_CIPHER_find(sk, c);
702     if (i < 0) {
703         /* we did not say we would use this cipher */
704         al = SSL_AD_ILLEGAL_PARAMETER;
705         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_WRONG_CIPHER_RETURNED);
706         goto f_err;
707     }
708
709     /*
710      * Depending on the session caching (internal/external), the cipher
711      * and/or cipher_id values may not be set. Make sure that cipher_id is
712      * set and use it for comparison.
713      */
714     if (s->session->cipher)
715         s->session->cipher_id = s->session->cipher->id;
716     if (s->hit && (s->session->cipher_id != c->id)) {
717         al = SSL_AD_ILLEGAL_PARAMETER;
718         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
719                SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
720         goto f_err;
721     }
722     s->s3->tmp.new_cipher = c;
723     /*
724      * Don't digest cached records if no sigalgs: we may need them for client
725      * authentication.
726      */
727     if (!SSL_USE_SIGALGS(s) && !ssl3_digest_cached_records(s, 0))
728         goto f_err;
729     /* lets get the compression algorithm */
730     /* COMPRESSION */
731     if (!PACKET_get_1(pkt, &compression)) {
732         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
733         al = SSL_AD_DECODE_ERROR;
734         goto f_err;
735     }
736 #ifdef OPENSSL_NO_COMP
737     if (compression != 0) {
738         al = SSL_AD_ILLEGAL_PARAMETER;
739         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
740                SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
741         goto f_err;
742     }
743     /*
744      * If compression is disabled we'd better not try to resume a session
745      * using compression.
746      */
747     if (s->session->compress_meth != 0) {
748         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
749         goto f_err;
750     }
751 #else
752     if (s->hit && compression != s->session->compress_meth) {
753         al = SSL_AD_ILLEGAL_PARAMETER;
754         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
755                SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED);
756         goto f_err;
757     }
758     if (compression == 0)
759         comp = NULL;
760     else if (!ssl_allow_compression(s)) {
761         al = SSL_AD_ILLEGAL_PARAMETER;
762         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_COMPRESSION_DISABLED);
763         goto f_err;
764     } else {
765         comp = ssl3_comp_find(s->ctx->comp_methods, compression);
766     }
767
768     if (compression != 0 && comp == NULL) {
769         al = SSL_AD_ILLEGAL_PARAMETER;
770         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
771                SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
772         goto f_err;
773     } else {
774         s->s3->tmp.new_compression = comp;
775     }
776 #endif
777
778     /* TLS extensions */
779     if (!ssl_parse_serverhello_tlsext(s, pkt)) {
780         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_PARSE_TLSEXT);
781         goto err;
782     }
783
784     if (PACKET_remaining(pkt) != 0) {
785         /* wrong packet length */
786         al = SSL_AD_DECODE_ERROR;
787         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_BAD_PACKET_LENGTH);
788         goto f_err;
789     }
790
791 #ifndef OPENSSL_NO_SCTP
792     if (SSL_IS_DTLS(s) && s->hit) {
793         unsigned char sctpauthkey[64];
794         char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
795
796         /*
797          * Add new shared key for SCTP-Auth, will be ignored if
798          * no SCTP used.
799          */
800         snprintf((char *)labelbuffer,
801                  sizeof(DTLS1_SCTP_AUTH_LABEL),
802                  DTLS1_SCTP_AUTH_LABEL);
803
804         if (SSL_export_keying_material(s, sctpauthkey,
805                                    sizeof(sctpauthkey),
806                                    labelbuffer,
807                                    sizeof(labelbuffer), NULL, 0,
808                                    0) <= 0)
809             goto err;
810
811         BIO_ctrl(SSL_get_wbio(s),
812                  BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
813                  sizeof(sctpauthkey), sctpauthkey);
814     }
815 #endif
816
817     return MSG_PROCESS_CONTINUE_READING;
818  f_err:
819     ssl3_send_alert(s, SSL3_AL_FATAL, al);
820  err:
821     statem_set_error(s);
822     return MSG_PROCESS_ERROR;
823 }
824
825 enum MSG_PROCESS_RETURN tls_process_server_certificate(SSL *s, PACKET *pkt)
826 {
827     int al, i, ret = MSG_PROCESS_ERROR, exp_idx;
828     unsigned long cert_list_len, cert_len;
829     X509 *x = NULL;
830     unsigned char *certstart, *certbytes;
831     STACK_OF(X509) *sk = NULL;
832     EVP_PKEY *pkey = NULL;
833
834     if ((sk = sk_X509_new_null()) == NULL) {
835         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, ERR_R_MALLOC_FAILURE);
836         goto err;
837     }
838
839     if (!PACKET_get_net_3(pkt, &cert_list_len)
840             || PACKET_remaining(pkt) != cert_list_len) {
841         al = SSL_AD_DECODE_ERROR;
842         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
843         goto f_err;
844     }
845     while (PACKET_remaining(pkt)) {
846         if (!PACKET_get_net_3(pkt, &cert_len)
847                 || !PACKET_get_bytes(pkt, &certbytes, cert_len)) {
848             al = SSL_AD_DECODE_ERROR;
849             SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
850                    SSL_R_CERT_LENGTH_MISMATCH);
851             goto f_err;
852         }
853
854         certstart = certbytes;
855         x = d2i_X509(NULL, (const unsigned char **)&certbytes, cert_len);
856         if (x == NULL) {
857             al = SSL_AD_BAD_CERTIFICATE;
858             SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, ERR_R_ASN1_LIB);
859             goto f_err;
860         }
861         if (certbytes != (certstart + cert_len)) {
862             al = SSL_AD_DECODE_ERROR;
863             SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
864                    SSL_R_CERT_LENGTH_MISMATCH);
865             goto f_err;
866         }
867         if (!sk_X509_push(sk, x)) {
868             SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, ERR_R_MALLOC_FAILURE);
869             goto err;
870         }
871         x = NULL;
872     }
873
874     i = ssl_verify_cert_chain(s, sk);
875     if (s->verify_mode != SSL_VERIFY_NONE && i <= 0) {
876         al = ssl_verify_alarm_type(s->verify_result);
877         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
878                SSL_R_CERTIFICATE_VERIFY_FAILED);
879         goto f_err;
880     }
881     ERR_clear_error();          /* but we keep s->verify_result */
882     if (i > 1) {
883         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, i);
884         al = SSL_AD_HANDSHAKE_FAILURE;
885         goto f_err;
886     }
887
888     s->session->peer_chain = sk;
889     /*
890      * Inconsistency alert: cert_chain does include the peer's certificate,
891      * which we don't include in s3_srvr.c
892      */
893     x = sk_X509_value(sk, 0);
894     sk = NULL;
895     /*
896      * VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end
897      */
898
899     pkey = X509_get_pubkey(x);
900
901     if (pkey == NULL || EVP_PKEY_missing_parameters(pkey)) {
902         x = NULL;
903         al = SSL3_AL_FATAL;
904         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
905                SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
906         goto f_err;
907     }
908
909     i = ssl_cert_type(x, pkey);
910     if (i < 0) {
911         x = NULL;
912         al = SSL3_AL_FATAL;
913         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
914                SSL_R_UNKNOWN_CERTIFICATE_TYPE);
915         goto f_err;
916     }
917
918     exp_idx = ssl_cipher_get_cert_index(s->s3->tmp.new_cipher);
919     if (exp_idx >= 0 && i != exp_idx) {
920         x = NULL;
921         al = SSL_AD_ILLEGAL_PARAMETER;
922         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
923                SSL_R_WRONG_CERTIFICATE_TYPE);
924         goto f_err;
925     }
926     s->session->peer_type = i;
927
928     X509_free(s->session->peer);
929     X509_up_ref(x);
930     s->session->peer = x;
931     s->session->verify_result = s->verify_result;
932
933     x = NULL;
934     ret = MSG_PROCESS_CONTINUE_READING;
935     goto done;
936
937  f_err:
938     ssl3_send_alert(s, SSL3_AL_FATAL, al);
939  err:
940     statem_set_error(s);
941  done:
942     EVP_PKEY_free(pkey);
943     X509_free(x);
944     sk_X509_pop_free(sk, X509_free);
945     return ret;
946 }
947
948 enum MSG_PROCESS_RETURN tls_process_key_exchange(SSL *s, PACKET *pkt)
949 {
950 #ifndef OPENSSL_NO_RSA
951     unsigned char *q, md_buf[EVP_MAX_MD_SIZE * 2];
952 #endif
953     EVP_MD_CTX md_ctx;
954     int al, j, verify_ret;
955     long alg_k, alg_a;
956     EVP_PKEY *pkey = NULL;
957     const EVP_MD *md = NULL;
958 #ifndef OPENSSL_NO_RSA
959     RSA *rsa = NULL;
960 #endif
961 #ifndef OPENSSL_NO_DH
962     DH *dh = NULL;
963 #endif
964 #ifndef OPENSSL_NO_EC
965     EC_KEY *ecdh = NULL;
966     BN_CTX *bn_ctx = NULL;
967     EC_POINT *srvr_ecpoint = NULL;
968     int curve_nid = 0;
969 #endif
970     PACKET save_param_start, signature;
971
972     EVP_MD_CTX_init(&md_ctx);
973
974     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
975
976     save_param_start = *pkt;
977
978 #ifndef OPENSSL_NO_RSA
979     RSA_free(s->s3->peer_rsa_tmp);
980     s->s3->peer_rsa_tmp = NULL;
981 #endif
982 #ifndef OPENSSL_NO_DH
983     DH_free(s->s3->peer_dh_tmp);
984     s->s3->peer_dh_tmp = NULL;
985 #endif
986 #ifndef OPENSSL_NO_EC
987     EC_KEY_free(s->s3->peer_ecdh_tmp);
988     s->s3->peer_ecdh_tmp = NULL;
989 #endif
990
991     alg_a = s->s3->tmp.new_cipher->algorithm_auth;
992
993     al = SSL_AD_DECODE_ERROR;
994
995 #ifndef OPENSSL_NO_PSK
996     /* PSK ciphersuites are preceded by an identity hint */
997     if (alg_k & SSL_PSK) {
998         PACKET psk_identity_hint;
999         if (!PACKET_get_length_prefixed_2(pkt, &psk_identity_hint)) {
1000             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
1001             goto f_err;
1002         }
1003
1004         /*
1005          * Store PSK identity hint for later use, hint is used in
1006          * ssl3_send_client_key_exchange.  Assume that the maximum length of
1007          * a PSK identity hint can be as long as the maximum length of a PSK
1008          * identity.
1009          */
1010         if (PACKET_remaining(&psk_identity_hint) > PSK_MAX_IDENTITY_LEN) {
1011             al = SSL_AD_HANDSHAKE_FAILURE;
1012             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG);
1013             goto f_err;
1014         }
1015
1016         if (!PACKET_strndup(&psk_identity_hint,
1017                             &s->session->psk_identity_hint)) {
1018             al = SSL_AD_INTERNAL_ERROR;
1019             goto f_err;
1020         }
1021     }
1022
1023     /* Nothing else to do for plain PSK or RSAPSK */
1024     if (alg_k & (SSL_kPSK | SSL_kRSAPSK)) {
1025     } else
1026 #endif                          /* !OPENSSL_NO_PSK */
1027 #ifndef OPENSSL_NO_SRP
1028     if (alg_k & SSL_kSRP) {
1029         PACKET prime, generator, salt, server_pub;
1030         if (!PACKET_get_length_prefixed_2(pkt, &prime)
1031             || !PACKET_get_length_prefixed_2(pkt, &generator)
1032             || !PACKET_get_length_prefixed_1(pkt, &salt)
1033             || !PACKET_get_length_prefixed_2(pkt, &server_pub)) {
1034             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
1035             goto f_err;
1036         }
1037
1038         if ((s->srp_ctx.N =
1039              BN_bin2bn(PACKET_data(&prime),
1040                        PACKET_remaining(&prime), NULL)) == NULL
1041             || (s->srp_ctx.g =
1042                 BN_bin2bn(PACKET_data(&generator),
1043                           PACKET_remaining(&generator), NULL)) == NULL
1044             || (s->srp_ctx.s =
1045                 BN_bin2bn(PACKET_data(&salt),
1046                           PACKET_remaining(&salt), NULL)) == NULL
1047             || (s->srp_ctx.B =
1048                 BN_bin2bn(PACKET_data(&server_pub),
1049                           PACKET_remaining(&server_pub), NULL)) == NULL) {
1050             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1051             goto err;
1052         }
1053
1054         if (!srp_verify_server_param(s, &al)) {
1055             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_BAD_SRP_PARAMETERS);
1056             goto f_err;
1057         }
1058
1059 /* We must check if there is a certificate */
1060         if (alg_a & (SSL_aRSA|SSL_aDSS))
1061             pkey = X509_get_pubkey(s->session->peer);
1062     } else
1063 #endif                          /* !OPENSSL_NO_SRP */
1064 #ifndef OPENSSL_NO_RSA
1065     if (alg_k & SSL_kRSA) {
1066         PACKET mod, exp;
1067         /* Temporary RSA keys only allowed in export ciphersuites */
1068         if (!SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)) {
1069             al = SSL_AD_UNEXPECTED_MESSAGE;
1070             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
1071             goto f_err;
1072         }
1073
1074         if (!PACKET_get_length_prefixed_2(pkt, &mod)
1075             || !PACKET_get_length_prefixed_2(pkt, &exp)) {
1076             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
1077             goto f_err;
1078         }
1079
1080         if ((rsa = RSA_new()) == NULL) {
1081             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1082             goto err;
1083         }
1084
1085         if ((rsa->n = BN_bin2bn(PACKET_data(&mod), PACKET_remaining(&mod),
1086                                 rsa->n)) == NULL
1087             || (rsa->e = BN_bin2bn(PACKET_data(&exp), PACKET_remaining(&exp),
1088                                    rsa->e)) == NULL) {
1089             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1090             goto err;
1091         }
1092
1093         /* this should be because we are using an export cipher */
1094         if (alg_a & SSL_aRSA)
1095             pkey = X509_get_pubkey(s->session->peer);
1096         else {
1097             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1098             goto err;
1099         }
1100
1101         if (EVP_PKEY_bits(pkey) <= SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {
1102             al = SSL_AD_UNEXPECTED_MESSAGE;
1103             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
1104             goto f_err;
1105         }
1106
1107         s->s3->peer_rsa_tmp = rsa;
1108         rsa = NULL;
1109     }
1110 #else                           /* OPENSSL_NO_RSA */
1111     if (0) ;
1112 #endif
1113 #ifndef OPENSSL_NO_DH
1114     else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
1115         PACKET prime, generator, pub_key;
1116
1117         if (!PACKET_get_length_prefixed_2(pkt, &prime)
1118             || !PACKET_get_length_prefixed_2(pkt, &generator)
1119             || !PACKET_get_length_prefixed_2(pkt, &pub_key)) {
1120             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
1121             goto f_err;
1122         }
1123
1124         if ((dh = DH_new()) == NULL) {
1125             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_DH_LIB);
1126             goto err;
1127         }
1128
1129         if ((dh->p = BN_bin2bn(PACKET_data(&prime),
1130                                PACKET_remaining(&prime), NULL)) == NULL
1131             || (dh->g = BN_bin2bn(PACKET_data(&generator),
1132                                   PACKET_remaining(&generator), NULL)) == NULL
1133             || (dh->pub_key =
1134                 BN_bin2bn(PACKET_data(&pub_key),
1135                           PACKET_remaining(&pub_key), NULL)) == NULL) {
1136             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1137             goto err;
1138         }
1139
1140         if (BN_is_zero(dh->p) || BN_is_zero(dh->g) || BN_is_zero(dh->pub_key)) {
1141             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_DH_VALUE);
1142             goto f_err;
1143         }
1144
1145         if (!ssl_security(s, SSL_SECOP_TMP_DH, DH_security_bits(dh), 0, dh)) {
1146             al = SSL_AD_HANDSHAKE_FAILURE;
1147             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_DH_KEY_TOO_SMALL);
1148             goto f_err;
1149         }
1150         if (alg_a & (SSL_aRSA|SSL_aDSS))
1151             pkey = X509_get_pubkey(s->session->peer);
1152         /* else anonymous DH, so no certificate or pkey. */
1153
1154         s->s3->peer_dh_tmp = dh;
1155         dh = NULL;
1156     }
1157 #endif                          /* !OPENSSL_NO_DH */
1158
1159 #ifndef OPENSSL_NO_EC
1160     else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
1161         EC_GROUP *ngroup;
1162         const EC_GROUP *group;
1163         PACKET encoded_pt;
1164         unsigned char *ecparams;
1165
1166         if ((ecdh = EC_KEY_new()) == NULL) {
1167             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1168             goto err;
1169         }
1170
1171         /*
1172          * Extract elliptic curve parameters and the server's ephemeral ECDH
1173          * public key. For now we only support named (not generic) curves and
1174          * ECParameters in this case is just three bytes.
1175          */
1176         if (!PACKET_get_bytes(pkt, &ecparams, 3)) {
1177             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1178             goto f_err;
1179         }
1180         /*
1181          * Check curve is one of our preferences, if not server has sent an
1182          * invalid curve. ECParameters is 3 bytes.
1183          */
1184         if (!tls1_check_curve(s, ecparams, 3)) {
1185             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_WRONG_CURVE);
1186             goto f_err;
1187         }
1188
1189         if ((curve_nid = tls1_ec_curve_id2nid(*(ecparams + 2))) == 0) {
1190             al = SSL_AD_INTERNAL_ERROR;
1191             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE,
1192                    SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
1193             goto f_err;
1194         }
1195
1196         ngroup = EC_GROUP_new_by_curve_name(curve_nid);
1197         if (ngroup == NULL) {
1198             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_EC_LIB);
1199             goto err;
1200         }
1201         if (EC_KEY_set_group(ecdh, ngroup) == 0) {
1202             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_EC_LIB);
1203             goto err;
1204         }
1205         EC_GROUP_free(ngroup);
1206
1207         group = EC_KEY_get0_group(ecdh);
1208
1209         if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1210             (EC_GROUP_get_degree(group) > 163)) {
1211             al = SSL_AD_EXPORT_RESTRICTION;
1212             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE,
1213                    SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1214             goto f_err;
1215         }
1216
1217         /* Next, get the encoded ECPoint */
1218         if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) ||
1219             ((bn_ctx = BN_CTX_new()) == NULL)) {
1220             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1221             goto err;
1222         }
1223
1224         if (!PACKET_get_length_prefixed_1(pkt, &encoded_pt)) {
1225             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
1226             goto f_err;
1227         }
1228
1229         if (EC_POINT_oct2point(group, srvr_ecpoint, PACKET_data(&encoded_pt),
1230                                PACKET_remaining(&encoded_pt), bn_ctx) == 0) {
1231             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_ECPOINT);
1232             goto f_err;
1233         }
1234
1235         /*
1236          * The ECC/TLS specification does not mention the use of DSA to sign
1237          * ECParameters in the server key exchange message. We do support RSA
1238          * and ECDSA.
1239          */
1240         if (0) ;
1241 # ifndef OPENSSL_NO_RSA
1242         else if (alg_a & SSL_aRSA)
1243             pkey = X509_get_pubkey(s->session->peer);
1244 # endif
1245 # ifndef OPENSSL_NO_EC
1246         else if (alg_a & SSL_aECDSA)
1247             pkey = X509_get_pubkey(s->session->peer);
1248 # endif
1249         /* else anonymous ECDH, so no certificate or pkey. */
1250         EC_KEY_set_public_key(ecdh, srvr_ecpoint);
1251         s->s3->peer_ecdh_tmp = ecdh;
1252         ecdh = NULL;
1253         BN_CTX_free(bn_ctx);
1254         bn_ctx = NULL;
1255         EC_POINT_free(srvr_ecpoint);
1256         srvr_ecpoint = NULL;
1257     } else if (alg_k) {
1258         al = SSL_AD_UNEXPECTED_MESSAGE;
1259         SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
1260         goto f_err;
1261     }
1262 #endif                          /* !OPENSSL_NO_EC */
1263
1264     /* if it was signed, check the signature */
1265     if (pkey != NULL) {
1266         PACKET params;
1267         /*
1268          * |pkt| now points to the beginning of the signature, so the difference
1269          * equals the length of the parameters.
1270          */
1271         if (!PACKET_get_sub_packet(&save_param_start, &params,
1272                                    PACKET_remaining(&save_param_start) -
1273                                    PACKET_remaining(pkt))) {
1274             al = SSL_AD_INTERNAL_ERROR;
1275             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1276             goto f_err;
1277         }
1278
1279         if (SSL_USE_SIGALGS(s)) {
1280             unsigned char *sigalgs;
1281             int rv;
1282             if (!PACKET_get_bytes(pkt, &sigalgs, 2)) {
1283                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1284                 goto f_err;
1285             }
1286             rv = tls12_check_peer_sigalg(&md, s, sigalgs, pkey);
1287             if (rv == -1)
1288                 goto err;
1289             else if (rv == 0) {
1290                 goto f_err;
1291             }
1292 #ifdef SSL_DEBUG
1293             fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
1294 #endif
1295         } else {
1296             md = EVP_sha1();
1297         }
1298
1299         if (!PACKET_get_length_prefixed_2(pkt, &signature)
1300             || PACKET_remaining(pkt) != 0) {
1301             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
1302             goto f_err;
1303         }
1304         j = EVP_PKEY_size(pkey);
1305         if (j < 0) {
1306             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1307             goto f_err;
1308         }
1309
1310         /*
1311          * Check signature length
1312          */
1313         if (PACKET_remaining(&signature) > (size_t)j) {
1314             /* wrong packet length */
1315             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_WRONG_SIGNATURE_LENGTH);
1316             goto f_err;
1317         }
1318 #ifndef OPENSSL_NO_RSA
1319         if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) {
1320             int num;
1321             unsigned int size;
1322
1323             j = 0;
1324             q = md_buf;
1325             for (num = 2; num > 0; num--) {
1326                 EVP_MD_CTX_set_flags(&md_ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
1327                 EVP_DigestInit_ex(&md_ctx, (num == 2)
1328                                   ? s->ctx->md5 : s->ctx->sha1, NULL);
1329                 EVP_DigestUpdate(&md_ctx, &(s->s3->client_random[0]),
1330                                  SSL3_RANDOM_SIZE);
1331                 EVP_DigestUpdate(&md_ctx, &(s->s3->server_random[0]),
1332                                  SSL3_RANDOM_SIZE);
1333                 EVP_DigestUpdate(&md_ctx, PACKET_data(&params),
1334                                  PACKET_remaining(&params));
1335                 EVP_DigestFinal_ex(&md_ctx, q, &size);
1336                 q += size;
1337                 j += size;
1338             }
1339             verify_ret =
1340                 RSA_verify(NID_md5_sha1, md_buf, j, PACKET_data(&signature),
1341                            PACKET_remaining(&signature), pkey->pkey.rsa);
1342             if (verify_ret < 0) {
1343                 al = SSL_AD_DECRYPT_ERROR;
1344                 SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_BAD_RSA_DECRYPT);
1345                 goto f_err;
1346             }
1347             if (verify_ret == 0) {
1348                 /* bad signature */
1349                 al = SSL_AD_DECRYPT_ERROR;
1350                 SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_BAD_SIGNATURE);
1351                 goto f_err;
1352             }
1353         } else
1354 #endif
1355         {
1356             EVP_VerifyInit_ex(&md_ctx, md, NULL);
1357             EVP_VerifyUpdate(&md_ctx, &(s->s3->client_random[0]),
1358                              SSL3_RANDOM_SIZE);
1359             EVP_VerifyUpdate(&md_ctx, &(s->s3->server_random[0]),
1360                              SSL3_RANDOM_SIZE);
1361             EVP_VerifyUpdate(&md_ctx, PACKET_data(&params),
1362                              PACKET_remaining(&params));
1363             if (EVP_VerifyFinal(&md_ctx, PACKET_data(&signature),
1364                                 PACKET_remaining(&signature), pkey) <= 0) {
1365                 /* bad signature */
1366                 al = SSL_AD_DECRYPT_ERROR;
1367                 SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_BAD_SIGNATURE);
1368                 goto f_err;
1369             }
1370         }
1371     } else {
1372         /* aNULL, aSRP or PSK do not need public keys */
1373         if (!(alg_a & (SSL_aNULL | SSL_aSRP)) && !(alg_k & SSL_PSK)) {
1374             /* Might be wrong key type, check it */
1375             if (ssl3_check_cert_and_algorithm(s))
1376                 /* Otherwise this shouldn't happen */
1377                 SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1378             goto err;
1379         }
1380         /* still data left over */
1381         if (PACKET_remaining(pkt) != 0) {
1382             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_EXTRA_DATA_IN_MESSAGE);
1383             goto f_err;
1384         }
1385     }
1386     EVP_PKEY_free(pkey);
1387     EVP_MD_CTX_cleanup(&md_ctx);
1388     return MSG_PROCESS_CONTINUE_READING;
1389  f_err:
1390     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1391  err:
1392     EVP_PKEY_free(pkey);
1393 #ifndef OPENSSL_NO_RSA
1394     RSA_free(rsa);
1395 #endif
1396 #ifndef OPENSSL_NO_DH
1397     DH_free(dh);
1398 #endif
1399 #ifndef OPENSSL_NO_EC
1400     BN_CTX_free(bn_ctx);
1401     EC_POINT_free(srvr_ecpoint);
1402     EC_KEY_free(ecdh);
1403 #endif
1404     EVP_MD_CTX_cleanup(&md_ctx);
1405     statem_set_error(s);
1406     return MSG_PROCESS_ERROR;
1407 }
1408
1409 enum MSG_PROCESS_RETURN tls_process_certificate_request(SSL *s, PACKET *pkt)
1410 {
1411     int ret = MSG_PROCESS_ERROR;
1412     unsigned int list_len, ctype_num, i, name_len;
1413     X509_NAME *xn = NULL;
1414     unsigned char *data;
1415     unsigned char *namestart, *namebytes;
1416     STACK_OF(X509_NAME) *ca_sk = NULL;
1417
1418     if ((ca_sk = sk_X509_NAME_new(ca_dn_cmp)) == NULL) {
1419         SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
1420         goto err;
1421     }
1422
1423     /* get the certificate types */
1424     if (!PACKET_get_1(pkt, &ctype_num)
1425             || !PACKET_get_bytes(pkt, &data, ctype_num)) {
1426         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1427         SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, SSL_R_LENGTH_MISMATCH);
1428         goto err;
1429     }
1430     OPENSSL_free(s->cert->ctypes);
1431     s->cert->ctypes = NULL;
1432     if (ctype_num > SSL3_CT_NUMBER) {
1433         /* If we exceed static buffer copy all to cert structure */
1434         s->cert->ctypes = OPENSSL_malloc(ctype_num);
1435         if (s->cert->ctypes == NULL) {
1436             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
1437             goto err;
1438         }
1439         memcpy(s->cert->ctypes, data, ctype_num);
1440         s->cert->ctype_num = (size_t)ctype_num;
1441         ctype_num = SSL3_CT_NUMBER;
1442     }
1443     for (i = 0; i < ctype_num; i++)
1444         s->s3->tmp.ctype[i] = data[i];
1445
1446     if (SSL_USE_SIGALGS(s)) {
1447         if (!PACKET_get_net_2(pkt, &list_len)
1448                 || !PACKET_get_bytes(pkt, &data, list_len)) {
1449             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1450             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST,
1451                    SSL_R_LENGTH_MISMATCH);
1452             goto err;
1453         }
1454
1455         /* Clear certificate digests and validity flags */
1456         for (i = 0; i < SSL_PKEY_NUM; i++) {
1457             s->s3->tmp.md[i] = NULL;
1458             s->s3->tmp.valid_flags[i] = 0;
1459         }
1460         if ((list_len & 1) || !tls1_save_sigalgs(s, data, list_len)) {
1461             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1462             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST,
1463                    SSL_R_SIGNATURE_ALGORITHMS_ERROR);
1464             goto err;
1465         }
1466         if (!tls1_process_sigalgs(s)) {
1467             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1468             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
1469             goto err;
1470         }
1471     }
1472
1473     /* get the CA RDNs */
1474     if (!PACKET_get_net_2(pkt, &list_len)
1475             || PACKET_remaining(pkt) != list_len) {
1476         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1477         SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, SSL_R_LENGTH_MISMATCH);
1478         goto err;
1479     }
1480
1481     while (PACKET_remaining(pkt)) {
1482         if (!PACKET_get_net_2(pkt, &name_len)
1483                 || !PACKET_get_bytes(pkt, &namebytes, name_len)) {
1484             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1485             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST,
1486                    SSL_R_LENGTH_MISMATCH);
1487             goto err;
1488         }
1489
1490         namestart = namebytes;
1491
1492         if ((xn = d2i_X509_NAME(NULL, (const unsigned char **)&namebytes,
1493                                 name_len)) == NULL) {
1494             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1495             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_ASN1_LIB);
1496             goto err;
1497         }
1498
1499         if (namebytes != (namestart + name_len)) {
1500             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1501             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST,
1502                    SSL_R_CA_DN_LENGTH_MISMATCH);
1503             goto err;
1504         }
1505         if (!sk_X509_NAME_push(ca_sk, xn)) {
1506             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
1507             goto err;
1508         }
1509     }
1510
1511     /* we should setup a certificate to return.... */
1512     s->s3->tmp.cert_req = 1;
1513     s->s3->tmp.ctype_num = ctype_num;
1514     sk_X509_NAME_pop_free(s->s3->tmp.ca_names, X509_NAME_free);
1515     s->s3->tmp.ca_names = ca_sk;
1516     ca_sk = NULL;
1517
1518     ret = MSG_PROCESS_CONTINUE_READING;
1519     goto done;
1520  err:
1521     statem_set_error(s);
1522  done:
1523     sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
1524     return ret;
1525 }
1526
1527 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
1528 {
1529     return (X509_NAME_cmp(*a, *b));
1530 }
1531
1532 enum MSG_PROCESS_RETURN tls_process_new_session_ticket(SSL *s, PACKET *pkt)
1533 {
1534     int al;
1535     unsigned int ticklen;
1536     unsigned long ticket_lifetime_hint;
1537
1538     if (!PACKET_get_net_4(pkt, &ticket_lifetime_hint)
1539             || !PACKET_get_net_2(pkt, &ticklen)
1540             || PACKET_remaining(pkt) != ticklen) {
1541         al = SSL_AD_DECODE_ERROR;
1542         SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
1543         goto f_err;
1544     }
1545
1546     /* Server is allowed to change its mind and send an empty ticket. */
1547     if (ticklen == 0)
1548         return 1;
1549
1550     if (s->session->session_id_length > 0) {
1551         int i = s->session_ctx->session_cache_mode;
1552         SSL_SESSION *new_sess;
1553         /*
1554          * We reused an existing session, so we need to replace it with a new
1555          * one
1556          */
1557         if (i & SSL_SESS_CACHE_CLIENT) {
1558             /*
1559              * Remove the old session from the cache
1560              */
1561             if (i & SSL_SESS_CACHE_NO_INTERNAL_STORE) {
1562                 if (s->session_ctx->remove_session_cb != NULL)
1563                     s->session_ctx->remove_session_cb(s->session_ctx,
1564                                                       s->session);
1565             } else {
1566                 /* We carry on if this fails */
1567                 SSL_CTX_remove_session(s->session_ctx, s->session);
1568             }
1569         }
1570
1571         if ((new_sess = ssl_session_dup(s->session, 0)) == 0) {
1572             al = SSL_AD_INTERNAL_ERROR;
1573             SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
1574             goto f_err;
1575         }
1576
1577         SSL_SESSION_free(s->session);
1578         s->session = new_sess;
1579     }
1580
1581     OPENSSL_free(s->session->tlsext_tick);
1582     s->session->tlsext_ticklen = 0;
1583
1584     s->session->tlsext_tick = OPENSSL_malloc(ticklen);
1585     if (!s->session->tlsext_tick) {
1586         SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
1587         goto err;
1588     }
1589     if (!PACKET_copy_bytes(pkt, s->session->tlsext_tick, ticklen)) {
1590         al = SSL_AD_DECODE_ERROR;
1591         SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
1592         goto f_err;
1593     }
1594
1595     s->session->tlsext_tick_lifetime_hint = ticket_lifetime_hint;
1596     s->session->tlsext_ticklen = ticklen;
1597     /*
1598      * There are two ways to detect a resumed ticket session. One is to set
1599      * an appropriate session ID and then the server must return a match in
1600      * ServerHello. This allows the normal client session ID matching to work
1601      * and we know much earlier that the ticket has been accepted. The
1602      * other way is to set zero length session ID when the ticket is
1603      * presented and rely on the handshake to determine session resumption.
1604      * We choose the former approach because this fits in with assumptions
1605      * elsewhere in OpenSSL. The session ID is set to the SHA256 (or SHA1 is
1606      * SHA256 is disabled) hash of the ticket.
1607      */
1608     EVP_Digest(s->session->tlsext_tick, ticklen,
1609                s->session->session_id, &s->session->session_id_length,
1610                EVP_sha256(), NULL);
1611     return MSG_PROCESS_CONTINUE_READING;
1612  f_err:
1613     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1614  err:
1615     statem_set_error(s);
1616     return MSG_PROCESS_ERROR;
1617 }
1618
1619 enum MSG_PROCESS_RETURN tls_process_cert_status(SSL *s, PACKET *pkt)
1620 {
1621     int al;
1622     unsigned long resplen;
1623     unsigned int type;
1624
1625     if (!PACKET_get_1(pkt, &type)
1626             || type != TLSEXT_STATUSTYPE_ocsp) {
1627         al = SSL_AD_DECODE_ERROR;
1628         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, SSL_R_UNSUPPORTED_STATUS_TYPE);
1629         goto f_err;
1630     }
1631     if (!PACKET_get_net_3(pkt, &resplen)
1632             || PACKET_remaining(pkt) != resplen) {
1633         al = SSL_AD_DECODE_ERROR;
1634         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, SSL_R_LENGTH_MISMATCH);
1635         goto f_err;
1636     }
1637     OPENSSL_free(s->tlsext_ocsp_resp);
1638     s->tlsext_ocsp_resp = OPENSSL_malloc(resplen);
1639     if (!s->tlsext_ocsp_resp) {
1640         al = SSL_AD_INTERNAL_ERROR;
1641         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, ERR_R_MALLOC_FAILURE);
1642         goto f_err;
1643     }
1644     if (!PACKET_copy_bytes(pkt, s->tlsext_ocsp_resp, resplen)) {
1645         al = SSL_AD_DECODE_ERROR;
1646         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, SSL_R_LENGTH_MISMATCH);
1647         goto f_err;
1648     }
1649     s->tlsext_ocsp_resplen = resplen;
1650     if (s->ctx->tlsext_status_cb) {
1651         int ret;
1652         ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
1653         if (ret == 0) {
1654             al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
1655             SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, SSL_R_INVALID_STATUS_RESPONSE);
1656             goto f_err;
1657         }
1658         if (ret < 0) {
1659             al = SSL_AD_INTERNAL_ERROR;
1660             SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, ERR_R_MALLOC_FAILURE);
1661             goto f_err;
1662         }
1663     }
1664     return MSG_PROCESS_CONTINUE_READING;
1665  f_err:
1666     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1667     statem_set_error(s);
1668     return MSG_PROCESS_ERROR;
1669 }
1670
1671 enum MSG_PROCESS_RETURN tls_process_server_done(SSL *s, PACKET *pkt)
1672 {
1673     if (PACKET_remaining(pkt) > 0) {
1674         /* should contain no data */
1675         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1676         SSLerr(SSL_F_TLS_PROCESS_SERVER_DONE, SSL_R_LENGTH_MISMATCH);
1677         statem_set_error(s);
1678         return MSG_PROCESS_ERROR;
1679     }
1680
1681 #ifndef OPENSSL_NO_SRP
1682     if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) {
1683         if (SRP_Calc_A_param(s) <= 0) {
1684             SSLerr(SSL_F_TLS_PROCESS_SERVER_DONE, SSL_R_SRP_A_CALC);
1685             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1686             statem_set_error(s);
1687             return MSG_PROCESS_ERROR;
1688         }
1689     }
1690 #endif
1691
1692 #ifndef OPENSSL_NO_SCTP
1693     /* Only applies to renegotiation */
1694     if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))
1695             && s->renegotiate != 0)
1696         return MSG_PROCESS_CONTINUE_PROCESSING;
1697     else
1698 #endif
1699         return MSG_PROCESS_FINISHED_READING;
1700 }
1701
1702 int tls_construct_client_key_exchange(SSL *s)
1703 {
1704     unsigned char *p;
1705     int n;
1706 #ifndef OPENSSL_NO_PSK
1707     size_t pskhdrlen = 0;
1708 #endif
1709     unsigned long alg_k;
1710 #ifndef OPENSSL_NO_RSA
1711     unsigned char *q;
1712     EVP_PKEY *pkey = NULL;
1713 #endif
1714 #ifndef OPENSSL_NO_EC
1715     EC_KEY *clnt_ecdh = NULL;
1716     const EC_POINT *srvr_ecpoint = NULL;
1717     EVP_PKEY *srvr_pub_pkey = NULL;
1718     unsigned char *encodedPoint = NULL;
1719     int encoded_pt_len = 0;
1720     BN_CTX *bn_ctx = NULL;
1721 #endif
1722     unsigned char *pms = NULL;
1723     size_t pmslen = 0;
1724     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1725
1726     p = ssl_handshake_start(s);
1727
1728
1729 #ifndef OPENSSL_NO_PSK
1730     if (alg_k & SSL_PSK) {
1731         int psk_err = 1;
1732         /*
1733          * The callback needs PSK_MAX_IDENTITY_LEN + 1 bytes to return a
1734          * \0-terminated identity. The last byte is for us for simulating
1735          * strnlen.
1736          */
1737         char identity[PSK_MAX_IDENTITY_LEN + 1];
1738         size_t identitylen;
1739         unsigned char psk[PSK_MAX_PSK_LEN];
1740         size_t psklen;
1741
1742         if (s->psk_client_callback == NULL) {
1743             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
1744                    SSL_R_PSK_NO_CLIENT_CB);
1745             goto err;
1746         }
1747
1748         memset(identity, 0, sizeof(identity));
1749
1750         psklen = s->psk_client_callback(s, s->session->psk_identity_hint,
1751                                         identity, sizeof(identity) - 1,
1752                                         psk, sizeof(psk));
1753
1754         if (psklen > PSK_MAX_PSK_LEN) {
1755             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
1756                    ERR_R_INTERNAL_ERROR);
1757             goto psk_err;
1758         } else if (psklen == 0) {
1759             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
1760                    SSL_R_PSK_IDENTITY_NOT_FOUND);
1761             goto psk_err;
1762         }
1763
1764         OPENSSL_free(s->s3->tmp.psk);
1765         s->s3->tmp.psk = BUF_memdup(psk, psklen);
1766         OPENSSL_cleanse(psk, psklen);
1767
1768         if (s->s3->tmp.psk == NULL) {
1769             OPENSSL_cleanse(identity, sizeof(identity));
1770             goto memerr;
1771         }
1772
1773         s->s3->tmp.psklen = psklen;
1774
1775         identitylen = strlen(identity);
1776         if (identitylen > PSK_MAX_IDENTITY_LEN) {
1777             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
1778                    ERR_R_INTERNAL_ERROR);
1779             goto psk_err;
1780         }
1781         OPENSSL_free(s->session->psk_identity);
1782         s->session->psk_identity = BUF_strdup(identity);
1783         if (s->session->psk_identity == NULL) {
1784             OPENSSL_cleanse(identity, sizeof(identity));
1785             goto memerr;
1786         }
1787
1788         s2n(identitylen, p);
1789         memcpy(p, identity, identitylen);
1790         pskhdrlen = 2 + identitylen;
1791         p += identitylen;
1792         psk_err = 0;
1793 psk_err:
1794         OPENSSL_cleanse(identity, sizeof(identity));
1795         if (psk_err != 0) {
1796             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1797             goto err;
1798         }
1799     }
1800     if (alg_k & SSL_kPSK) {
1801         n = 0;
1802     } else
1803 #endif
1804
1805     /* Fool emacs indentation */
1806     if (0) {
1807     }
1808 #ifndef OPENSSL_NO_RSA
1809     else if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
1810         RSA *rsa;
1811         pmslen = SSL_MAX_MASTER_KEY_LENGTH;
1812         pms = OPENSSL_malloc(pmslen);
1813         if (!pms)
1814             goto memerr;
1815
1816         if (s->session->peer == NULL) {
1817             /*
1818              * We should always have a server certificate with SSL_kRSA.
1819              */
1820             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
1821                    ERR_R_INTERNAL_ERROR);
1822             goto err;
1823         }
1824
1825         if (s->s3->peer_rsa_tmp != NULL)
1826             rsa = s->s3->peer_rsa_tmp;
1827         else {
1828             pkey = X509_get_pubkey(s->session->peer);
1829             if ((pkey == NULL) || (pkey->type != EVP_PKEY_RSA)
1830                 || (pkey->pkey.rsa == NULL)) {
1831                 SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
1832                        ERR_R_INTERNAL_ERROR);
1833                 EVP_PKEY_free(pkey);
1834                 goto err;
1835             }
1836             rsa = pkey->pkey.rsa;
1837             EVP_PKEY_free(pkey);
1838         }
1839
1840         pms[0] = s->client_version >> 8;
1841         pms[1] = s->client_version & 0xff;
1842         if (RAND_bytes(pms + 2, pmslen - 2) <= 0)
1843             goto err;
1844
1845         q = p;
1846         /* Fix buf for TLS and beyond */
1847         if (s->version > SSL3_VERSION)
1848             p += 2;
1849         n = RSA_public_encrypt(pmslen, pms, p, rsa, RSA_PKCS1_PADDING);
1850 # ifdef PKCS1_CHECK
1851         if (s->options & SSL_OP_PKCS1_CHECK_1)
1852             p[1]++;
1853         if (s->options & SSL_OP_PKCS1_CHECK_2)
1854             tmp_buf[0] = 0x70;
1855 # endif
1856         if (n <= 0) {
1857             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
1858                    SSL_R_BAD_RSA_ENCRYPT);
1859             goto err;
1860         }
1861
1862         /* Fix buf for TLS and beyond */
1863         if (s->version > SSL3_VERSION) {
1864             s2n(n, q);
1865             n += 2;
1866         }
1867     }
1868 #endif
1869 #ifndef OPENSSL_NO_DH
1870     else if (alg_k & (SSL_kDHE | SSL_kDHr | SSL_kDHd | SSL_kDHEPSK)) {
1871         DH *dh_srvr, *dh_clnt;
1872         if (s->s3->peer_dh_tmp != NULL)
1873             dh_srvr = s->s3->peer_dh_tmp;
1874         else {
1875             /* we get them from the cert */
1876             EVP_PKEY *spkey = NULL;
1877             dh_srvr = NULL;
1878             spkey = X509_get_pubkey(s->session->peer);
1879             if (spkey) {
1880                 dh_srvr = EVP_PKEY_get1_DH(spkey);
1881                 EVP_PKEY_free(spkey);
1882             }
1883             if (dh_srvr == NULL) {
1884                 SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
1885                        ERR_R_INTERNAL_ERROR);
1886                 goto err;
1887             }
1888         }
1889         if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY) {
1890             /* Use client certificate key */
1891             EVP_PKEY *clkey = s->cert->key->privatekey;
1892             dh_clnt = NULL;
1893             if (clkey)
1894                 dh_clnt = EVP_PKEY_get1_DH(clkey);
1895             if (dh_clnt == NULL) {
1896                 SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
1897                        ERR_R_INTERNAL_ERROR);
1898                 goto err;
1899             }
1900         } else {
1901             /* generate a new random key */
1902             if ((dh_clnt = DHparams_dup(dh_srvr)) == NULL) {
1903                 SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
1904                 goto err;
1905             }
1906             if (!DH_generate_key(dh_clnt)) {
1907                 SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
1908                 DH_free(dh_clnt);
1909                 goto err;
1910             }
1911         }
1912
1913         pmslen = DH_size(dh_clnt);
1914         pms = OPENSSL_malloc(pmslen);
1915         if (!pms)
1916             goto memerr;
1917
1918         /*
1919          * use the 'p' output buffer for the DH key, but make sure to
1920          * clear it out afterwards
1921          */
1922
1923         n = DH_compute_key(pms, dh_srvr->pub_key, dh_clnt);
1924         if (s->s3->peer_dh_tmp == NULL)
1925             DH_free(dh_srvr);
1926
1927         if (n <= 0) {
1928             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
1929             DH_free(dh_clnt);
1930             goto err;
1931         }
1932         pmslen = n;
1933
1934         if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY)
1935             n = 0;
1936         else {
1937             /* send off the data */
1938             n = BN_num_bytes(dh_clnt->pub_key);
1939             s2n(n, p);
1940             BN_bn2bin(dh_clnt->pub_key, p);
1941             n += 2;
1942         }
1943
1944         DH_free(dh_clnt);
1945     }
1946 #endif
1947
1948 #ifndef OPENSSL_NO_EC
1949     else if (alg_k & (SSL_kECDHE | SSL_kECDHr | SSL_kECDHe | SSL_kECDHEPSK)) {
1950         const EC_GROUP *srvr_group = NULL;
1951         EC_KEY *tkey;
1952         int ecdh_clnt_cert = 0;
1953         int field_size = 0;
1954         /*
1955          * Did we send out the client's ECDH share for use in premaster
1956          * computation as part of client certificate? If so, set
1957          * ecdh_clnt_cert to 1.
1958          */
1959         if ((alg_k & (SSL_kECDHr | SSL_kECDHe)) && (s->cert != NULL)) {
1960             /*-
1961              * XXX: For now, we do not support client
1962              * authentication using ECDH certificates.
1963              * To add such support, one needs to add
1964              * code that checks for appropriate
1965              * conditions and sets ecdh_clnt_cert to 1.
1966              * For example, the cert have an ECC
1967              * key on the same curve as the server's
1968              * and the key should be authorized for
1969              * key agreement.
1970              *
1971              * One also needs to add code in ssl3_connect
1972              * to skip sending the certificate verify
1973              * message.
1974              *
1975              * if ((s->cert->key->privatekey != NULL) &&
1976              *     (s->cert->key->privatekey->type ==
1977              *      EVP_PKEY_EC) && ...)
1978              * ecdh_clnt_cert = 1;
1979              */
1980         }
1981
1982         if (s->s3->peer_ecdh_tmp != NULL) {
1983             tkey = s->s3->peer_ecdh_tmp;
1984         } else {
1985             /* Get the Server Public Key from Cert */
1986             srvr_pub_pkey = X509_get_pubkey(s->session->peer);
1987             if ((srvr_pub_pkey == NULL)
1988                 || (srvr_pub_pkey->type != EVP_PKEY_EC)
1989                 || (srvr_pub_pkey->pkey.ec == NULL)) {
1990                 SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
1991                        ERR_R_INTERNAL_ERROR);
1992                 goto err;
1993             }
1994
1995             tkey = srvr_pub_pkey->pkey.ec;
1996         }
1997
1998         srvr_group = EC_KEY_get0_group(tkey);
1999         srvr_ecpoint = EC_KEY_get0_public_key(tkey);
2000
2001         if ((srvr_group == NULL) || (srvr_ecpoint == NULL)) {
2002             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2003                    ERR_R_INTERNAL_ERROR);
2004             goto err;
2005         }
2006
2007         if ((clnt_ecdh = EC_KEY_new()) == NULL) {
2008             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2009                    ERR_R_MALLOC_FAILURE);
2010             goto err;
2011         }
2012
2013         if (!EC_KEY_set_group(clnt_ecdh, srvr_group)) {
2014             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2015             goto err;
2016         }
2017         if (ecdh_clnt_cert) {
2018             /*
2019              * Reuse key info from our certificate We only need our
2020              * private key to perform the ECDH computation.
2021              */
2022             const BIGNUM *priv_key;
2023             tkey = s->cert->key->privatekey->pkey.ec;
2024             priv_key = EC_KEY_get0_private_key(tkey);
2025             if (priv_key == NULL) {
2026                 SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2027                        ERR_R_MALLOC_FAILURE);
2028                 goto err;
2029             }
2030             if (!EC_KEY_set_private_key(clnt_ecdh, priv_key)) {
2031                 SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2032                 goto err;
2033             }
2034         } else {
2035             /* Generate a new ECDH key pair */
2036             if (!(EC_KEY_generate_key(clnt_ecdh))) {
2037                 SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2038                        ERR_R_ECDH_LIB);
2039                 goto err;
2040             }
2041         }
2042
2043         /*
2044          * use the 'p' output buffer for the ECDH key, but make sure to
2045          * clear it out afterwards
2046          */
2047
2048         field_size = EC_GROUP_get_degree(srvr_group);
2049         if (field_size <= 0) {
2050             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2051             goto err;
2052         }
2053         pmslen = (field_size + 7) / 8;
2054         pms = OPENSSL_malloc(pmslen);
2055         if (!pms)
2056             goto memerr;
2057         n = ECDH_compute_key(pms, pmslen, srvr_ecpoint, clnt_ecdh, NULL);
2058         if (n <= 0 || pmslen != (size_t)n) {
2059             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2060             goto err;
2061         }
2062
2063         if (ecdh_clnt_cert) {
2064             /* Send empty client key exch message */
2065             n = 0;
2066         } else {
2067             /*
2068              * First check the size of encoding and allocate memory
2069              * accordingly.
2070              */
2071             encoded_pt_len =
2072                 EC_POINT_point2oct(srvr_group,
2073                                    EC_KEY_get0_public_key(clnt_ecdh),
2074                                    POINT_CONVERSION_UNCOMPRESSED,
2075                                    NULL, 0, NULL);
2076
2077             encodedPoint = (unsigned char *)
2078                 OPENSSL_malloc(encoded_pt_len * sizeof(unsigned char));
2079             bn_ctx = BN_CTX_new();
2080             if ((encodedPoint == NULL) || (bn_ctx == NULL)) {
2081                 SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2082                        ERR_R_MALLOC_FAILURE);
2083                 goto err;
2084             }
2085
2086             /* Encode the public key */
2087             n = EC_POINT_point2oct(srvr_group,
2088                                    EC_KEY_get0_public_key(clnt_ecdh),
2089                                    POINT_CONVERSION_UNCOMPRESSED,
2090                                    encodedPoint, encoded_pt_len, bn_ctx);
2091
2092             *p = n;         /* length of encoded point */
2093             /* Encoded point will be copied here */
2094             p += 1;
2095             /* copy the point */
2096             memcpy(p, encodedPoint, n);
2097             /* increment n to account for length field */
2098             n += 1;
2099         }
2100
2101         /* Free allocated memory */
2102         BN_CTX_free(bn_ctx);
2103         OPENSSL_free(encodedPoint);
2104         EC_KEY_free(clnt_ecdh);
2105         EVP_PKEY_free(srvr_pub_pkey);
2106     }
2107 #endif                          /* !OPENSSL_NO_EC */
2108     else if (alg_k & SSL_kGOST) {
2109         /* GOST key exchange message creation */
2110         EVP_PKEY_CTX *pkey_ctx;
2111         X509 *peer_cert;
2112         size_t msglen;
2113         unsigned int md_len;
2114         unsigned char shared_ukm[32], tmp[256];
2115         EVP_MD_CTX *ukm_hash;
2116         EVP_PKEY *pub_key;
2117
2118         pmslen = 32;
2119         pms = OPENSSL_malloc(pmslen);
2120         if (!pms)
2121             goto memerr;
2122
2123         /*
2124          * Get server sertificate PKEY and create ctx from it
2125          */
2126         peer_cert = s->session->peer;
2127         if (!peer_cert) {
2128             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2129                    SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
2130             goto err;
2131         }
2132
2133         pkey_ctx = EVP_PKEY_CTX_new(pub_key =
2134                                     X509_get_pubkey(peer_cert), NULL);
2135         /*
2136          * If we have send a certificate, and certificate key
2137          *
2138          * * parameters match those of server certificate, use
2139          * certificate key for key exchange
2140          */
2141
2142         /* Otherwise, generate ephemeral key pair */
2143
2144         EVP_PKEY_encrypt_init(pkey_ctx);
2145         /* Generate session key */
2146         if (RAND_bytes(pms, pmslen) <= 0) {
2147             EVP_PKEY_CTX_free(pkey_ctx);
2148             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2149                    ERR_R_INTERNAL_ERROR);
2150             goto err;
2151         };
2152         /*
2153          * If we have client certificate, use its secret as peer key
2154          */
2155         if (s->s3->tmp.cert_req && s->cert->key->privatekey) {
2156             if (EVP_PKEY_derive_set_peer
2157                 (pkey_ctx, s->cert->key->privatekey) <= 0) {
2158                 /*
2159                  * If there was an error - just ignore it. Ephemeral key
2160                  * * would be used
2161                  */
2162                 ERR_clear_error();
2163             }
2164         }
2165         /*
2166          * Compute shared IV and store it in algorithm-specific context
2167          * data
2168          */
2169         ukm_hash = EVP_MD_CTX_create();
2170         EVP_DigestInit(ukm_hash,
2171                        EVP_get_digestbynid(NID_id_GostR3411_94));
2172         EVP_DigestUpdate(ukm_hash, s->s3->client_random,
2173                          SSL3_RANDOM_SIZE);
2174         EVP_DigestUpdate(ukm_hash, s->s3->server_random,
2175                          SSL3_RANDOM_SIZE);
2176         EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len);
2177         EVP_MD_CTX_destroy(ukm_hash);
2178         if (EVP_PKEY_CTX_ctrl
2179             (pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT, EVP_PKEY_CTRL_SET_IV, 8,
2180              shared_ukm) < 0) {
2181             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2182                    SSL_R_LIBRARY_BUG);
2183             goto err;
2184         }
2185         /* Make GOST keytransport blob message */
2186         /*
2187          * Encapsulate it into sequence
2188          */
2189         *(p++) = V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED;
2190         msglen = 255;
2191         if (EVP_PKEY_encrypt(pkey_ctx, tmp, &msglen, pms, pmslen) < 0) {
2192             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2193                    SSL_R_LIBRARY_BUG);
2194             goto err;
2195         }
2196         if (msglen >= 0x80) {
2197             *(p++) = 0x81;
2198             *(p++) = msglen & 0xff;
2199             n = msglen + 3;
2200         } else {
2201             *(p++) = msglen & 0xff;
2202             n = msglen + 2;
2203         }
2204         memcpy(p, tmp, msglen);
2205         /* Check if pubkey from client certificate was used */
2206         if (EVP_PKEY_CTX_ctrl
2207             (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0) {
2208             /* Set flag "skip certificate verify" */
2209             s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
2210         }
2211         EVP_PKEY_CTX_free(pkey_ctx);
2212         EVP_PKEY_free(pub_key);
2213
2214     }
2215 #ifndef OPENSSL_NO_SRP
2216     else if (alg_k & SSL_kSRP) {
2217         if (s->srp_ctx.A != NULL) {
2218             /* send off the data */
2219             n = BN_num_bytes(s->srp_ctx.A);
2220             s2n(n, p);
2221             BN_bn2bin(s->srp_ctx.A, p);
2222             n += 2;
2223         } else {
2224             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2225                    ERR_R_INTERNAL_ERROR);
2226             goto err;
2227         }
2228         OPENSSL_free(s->session->srp_username);
2229         s->session->srp_username = BUF_strdup(s->srp_ctx.login);
2230         if (s->session->srp_username == NULL) {
2231             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2232                    ERR_R_MALLOC_FAILURE);
2233             goto err;
2234         }
2235     }
2236 #endif
2237     else {
2238         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2239         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2240         goto err;
2241     }
2242
2243 #ifndef OPENSSL_NO_PSK
2244     n += pskhdrlen;
2245 #endif
2246
2247     if (!ssl_set_handshake_header(s, SSL3_MT_CLIENT_KEY_EXCHANGE, n)) {
2248         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2249         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2250         goto err;
2251     }
2252
2253     s->s3->tmp.pms = pms;
2254     s->s3->tmp.pmslen = pmslen;
2255
2256     return 1;
2257  memerr:
2258     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2259     SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2260  err:
2261     OPENSSL_clear_free(pms, pmslen);
2262     s->s3->tmp.pms = NULL;
2263 #ifndef OPENSSL_NO_EC
2264     BN_CTX_free(bn_ctx);
2265     OPENSSL_free(encodedPoint);
2266     EC_KEY_free(clnt_ecdh);
2267     EVP_PKEY_free(srvr_pub_pkey);
2268 #endif
2269 #ifndef OPENSSL_NO_PSK
2270     OPENSSL_clear_free(s->s3->tmp.psk, s->s3->tmp.psklen);
2271     s->s3->tmp.psk = NULL;
2272 #endif
2273     statem_set_error(s);
2274     return 0;
2275 }
2276
2277 int tls_client_key_exchange_post_work(SSL *s)
2278 {
2279     unsigned char *pms = NULL;
2280     size_t pmslen = 0;
2281
2282 #ifndef OPENSSL_NO_SRP
2283     /* Check for SRP */
2284     if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) {
2285         if (!srp_generate_client_master_secret(s)) {
2286             SSLerr(SSL_F_TLS_CLIENT_KEY_EXCHANGE_POST_WORK,
2287                    ERR_R_INTERNAL_ERROR);
2288             goto err;
2289         }
2290         return 1;
2291     }
2292 #endif
2293     pms = s->s3->tmp.pms;
2294     pmslen = s->s3->tmp.pmslen;
2295
2296     if (pms == NULL && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
2297         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2298         SSLerr(SSL_F_TLS_CLIENT_KEY_EXCHANGE_POST_WORK, ERR_R_MALLOC_FAILURE);
2299         goto err;
2300     }
2301     if (!ssl_generate_master_secret(s, pms, pmslen, 1)) {
2302         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2303         SSLerr(SSL_F_TLS_CLIENT_KEY_EXCHANGE_POST_WORK, ERR_R_INTERNAL_ERROR);
2304         goto err;
2305     }
2306
2307 #ifndef OPENSSL_NO_SCTP
2308     if (SSL_IS_DTLS(s)) {
2309         unsigned char sctpauthkey[64];
2310         char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
2311
2312         /*
2313          * Add new shared key for SCTP-Auth, will be ignored if no SCTP
2314          * used.
2315          */
2316         snprintf((char *)labelbuffer, sizeof(DTLS1_SCTP_AUTH_LABEL),
2317                  DTLS1_SCTP_AUTH_LABEL);
2318
2319         if (SSL_export_keying_material(s, sctpauthkey,
2320                                    sizeof(sctpauthkey), labelbuffer,
2321                                    sizeof(labelbuffer), NULL, 0, 0) <= 0)
2322             goto err;
2323
2324         BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
2325                  sizeof(sctpauthkey), sctpauthkey);
2326     }
2327 #endif
2328
2329     return 1;
2330  err:
2331     OPENSSL_clear_free(pms, pmslen);
2332     s->s3->tmp.pms = NULL;
2333     return 0;
2334 }
2335
2336 int tls_construct_client_verify(SSL *s)
2337 {
2338     unsigned char *p;
2339     unsigned char data[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH];
2340     EVP_PKEY *pkey;
2341     EVP_PKEY_CTX *pctx = NULL;
2342     EVP_MD_CTX mctx;
2343     unsigned u = 0;
2344     unsigned long n;
2345     int j;
2346
2347     EVP_MD_CTX_init(&mctx);
2348
2349     p = ssl_handshake_start(s);
2350     pkey = s->cert->key->privatekey;
2351 /* Create context from key and test if sha1 is allowed as digest */
2352     pctx = EVP_PKEY_CTX_new(pkey, NULL);
2353     EVP_PKEY_sign_init(pctx);
2354     if (EVP_PKEY_CTX_set_signature_md(pctx, EVP_sha1()) > 0) {
2355         if (!SSL_USE_SIGALGS(s))
2356             s->method->ssl3_enc->cert_verify_mac(s,
2357                                                  NID_sha1,
2358                                                  &(data
2359                                                    [MD5_DIGEST_LENGTH]));
2360     } else {
2361         ERR_clear_error();
2362     }
2363     /*
2364      * For TLS v1.2 send signature algorithm and signature using agreed
2365      * digest and cached handshake records.
2366      */
2367     if (SSL_USE_SIGALGS(s)) {
2368         long hdatalen = 0;
2369         void *hdata;
2370         const EVP_MD *md = s->s3->tmp.md[s->cert->key - s->cert->pkeys];
2371         hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
2372         if (hdatalen <= 0 || !tls12_get_sigandhash(p, pkey, md)) {
2373             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
2374             goto err;
2375         }
2376         p += 2;
2377 #ifdef SSL_DEBUG
2378         fprintf(stderr, "Using TLS 1.2 with client alg %s\n",
2379                 EVP_MD_name(md));
2380 #endif
2381         if (!EVP_SignInit_ex(&mctx, md, NULL)
2382             || !EVP_SignUpdate(&mctx, hdata, hdatalen)
2383             || !EVP_SignFinal(&mctx, p + 2, &u, pkey)) {
2384             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_EVP_LIB);
2385             goto err;
2386         }
2387         s2n(u, p);
2388         n = u + 4;
2389         /* Digest cached records and discard handshake buffer */
2390         if (!ssl3_digest_cached_records(s, 0))
2391             goto err;
2392     } else
2393 #ifndef OPENSSL_NO_RSA
2394     if (pkey->type == EVP_PKEY_RSA) {
2395         s->method->ssl3_enc->cert_verify_mac(s, NID_md5, &(data[0]));
2396         if (RSA_sign(NID_md5_sha1, data,
2397                      MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH,
2398                      &(p[2]), &u, pkey->pkey.rsa) <= 0) {
2399             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_RSA_LIB);
2400             goto err;
2401         }
2402         s2n(u, p);
2403         n = u + 2;
2404     } else
2405 #endif
2406 #ifndef OPENSSL_NO_DSA
2407     if (pkey->type == EVP_PKEY_DSA) {
2408         if (!DSA_sign(pkey->save_type,
2409                       &(data[MD5_DIGEST_LENGTH]),
2410                       SHA_DIGEST_LENGTH, &(p[2]),
2411                       (unsigned int *)&j, pkey->pkey.dsa)) {
2412             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_DSA_LIB);
2413             goto err;
2414         }
2415         s2n(j, p);
2416         n = j + 2;
2417     } else
2418 #endif
2419 #ifndef OPENSSL_NO_EC
2420     if (pkey->type == EVP_PKEY_EC) {
2421         if (!ECDSA_sign(pkey->save_type,
2422                         &(data[MD5_DIGEST_LENGTH]),
2423                         SHA_DIGEST_LENGTH, &(p[2]),
2424                         (unsigned int *)&j, pkey->pkey.ec)) {
2425             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_ECDSA_LIB);
2426             goto err;
2427         }
2428         s2n(j, p);
2429         n = j + 2;
2430     } else
2431 #endif
2432     if (pkey->type == NID_id_GostR3410_2001) {
2433         unsigned char signbuf[64];
2434         int i;
2435         size_t sigsize = 64;
2436         s->method->ssl3_enc->cert_verify_mac(s,
2437                                              NID_id_GostR3411_94, data);
2438         if (EVP_PKEY_sign(pctx, signbuf, &sigsize, data, 32) <= 0) {
2439             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
2440             goto err;
2441         }
2442         for (i = 63, j = 0; i >= 0; j++, i--) {
2443             p[2 + j] = signbuf[i];
2444         }
2445         s2n(j, p);
2446         n = j + 2;
2447     } else {
2448         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
2449         goto err;
2450     }
2451     if (!ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_VERIFY, n)) {
2452         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
2453         goto err;
2454     }
2455
2456     EVP_MD_CTX_cleanup(&mctx);
2457     EVP_PKEY_CTX_free(pctx);
2458     return 1;
2459  err:
2460     EVP_MD_CTX_cleanup(&mctx);
2461     EVP_PKEY_CTX_free(pctx);
2462     return 0;
2463 }
2464
2465 /*
2466  * Check a certificate can be used for client authentication. Currently check
2467  * cert exists, if we have a suitable digest for TLS 1.2 if static DH client
2468  * certificates can be used and optionally checks suitability for Suite B.
2469  */
2470 static int ssl3_check_client_certificate(SSL *s)
2471 {
2472     unsigned long alg_k;
2473     if (!s->cert || !s->cert->key->x509 || !s->cert->key->privatekey)
2474         return 0;
2475     /* If no suitable signature algorithm can't use certificate */
2476     if (SSL_USE_SIGALGS(s) && !s->s3->tmp.md[s->cert->key - s->cert->pkeys])
2477         return 0;
2478     /*
2479      * If strict mode check suitability of chain before using it. This also
2480      * adjusts suite B digest if necessary.
2481      */
2482     if (s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT &&
2483         !tls1_check_chain(s, NULL, NULL, NULL, -2))
2484         return 0;
2485     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2486     /* See if we can use client certificate for fixed DH */
2487     if (alg_k & (SSL_kDHr | SSL_kDHd)) {
2488         int i = s->session->peer_type;
2489         EVP_PKEY *clkey = NULL, *spkey = NULL;
2490         clkey = s->cert->key->privatekey;
2491         /* If client key not DH assume it can be used */
2492         if (EVP_PKEY_id(clkey) != EVP_PKEY_DH)
2493             return 1;
2494         if (i >= 0)
2495             spkey = X509_get_pubkey(s->session->peer);
2496         if (spkey) {
2497             /* Compare server and client parameters */
2498             i = EVP_PKEY_cmp_parameters(clkey, spkey);
2499             EVP_PKEY_free(spkey);
2500             if (i != 1)
2501                 return 0;
2502         }
2503         s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
2504     }
2505     return 1;
2506 }
2507
2508 enum WORK_STATE tls_prepare_client_certificate(SSL *s, enum WORK_STATE wst)
2509 {
2510     X509 *x509 = NULL;
2511     EVP_PKEY *pkey = NULL;
2512     int i;
2513
2514     if (wst == WORK_MORE_A) {
2515         /* Let cert callback update client certificates if required */
2516         if (s->cert->cert_cb) {
2517             i = s->cert->cert_cb(s, s->cert->cert_cb_arg);
2518             if (i < 0) {
2519                 s->rwstate = SSL_X509_LOOKUP;
2520                 return WORK_MORE_A;
2521             }
2522             if (i == 0) {
2523                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2524                 statem_set_error(s);
2525                 return 0;
2526             }
2527             s->rwstate = SSL_NOTHING;
2528         }
2529         if (ssl3_check_client_certificate(s))
2530             return WORK_FINISHED_CONTINUE;
2531
2532         /* Fall through to WORK_MORE_B */
2533         wst = WORK_MORE_B;
2534     }
2535
2536     /* We need to get a client cert */
2537     if (wst == WORK_MORE_B) {
2538         /*
2539          * If we get an error, we need to ssl->rwstate=SSL_X509_LOOKUP;
2540          * return(-1); We then get retied later
2541          */
2542         i = ssl_do_client_cert_cb(s, &x509, &pkey);
2543         if (i < 0) {
2544             s->rwstate = SSL_X509_LOOKUP;
2545             return WORK_MORE_B;
2546         }
2547         s->rwstate = SSL_NOTHING;
2548         if ((i == 1) && (pkey != NULL) && (x509 != NULL)) {
2549             if (!SSL_use_certificate(s, x509) || !SSL_use_PrivateKey(s, pkey))
2550                 i = 0;
2551         } else if (i == 1) {
2552             i = 0;
2553             SSLerr(SSL_F_TLS_PREPARE_CLIENT_CERTIFICATE,
2554                    SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
2555         }
2556
2557         X509_free(x509);
2558         EVP_PKEY_free(pkey);
2559         if (i && !ssl3_check_client_certificate(s))
2560             i = 0;
2561         if (i == 0) {
2562             if (s->version == SSL3_VERSION) {
2563                 s->s3->tmp.cert_req = 0;
2564                 ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_CERTIFICATE);
2565                 return WORK_FINISHED_CONTINUE;
2566             } else {
2567                 s->s3->tmp.cert_req = 2;
2568                 if (!ssl3_digest_cached_records(s, 0)) {
2569                     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2570                     statem_set_error(s);
2571                     return 0;
2572                 }
2573             }
2574         }
2575
2576         return WORK_FINISHED_CONTINUE;
2577     }
2578
2579     /* Shouldn't ever get here */
2580     return WORK_ERROR;
2581 }
2582
2583 int tls_construct_client_certificate(SSL *s)
2584 {
2585     if (!ssl3_output_cert_chain(s,
2586                                 (s->s3->tmp.cert_req ==
2587                                  2) ? NULL : s->cert->key)) {
2588         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_CERTIFICATE, ERR_R_INTERNAL_ERROR);
2589         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2590         statem_set_error(s);
2591         return 0;
2592     }
2593
2594     return 1;
2595 }
2596
2597 #define has_bits(i,m)   (((i)&(m)) == (m))
2598
2599 int ssl3_check_cert_and_algorithm(SSL *s)
2600 {
2601     int i, idx;
2602     long alg_k, alg_a;
2603     EVP_PKEY *pkey = NULL;
2604     int pkey_bits;
2605 #ifndef OPENSSL_NO_RSA
2606     RSA *rsa;
2607 #endif
2608 #ifndef OPENSSL_NO_DH
2609     DH *dh;
2610 #endif
2611     int al = SSL_AD_HANDSHAKE_FAILURE;
2612
2613     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2614     alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2615
2616     /* we don't have a certificate */
2617     if ((alg_a & SSL_aNULL) || (alg_k & SSL_kPSK))
2618         return (1);
2619 #ifndef OPENSSL_NO_RSA
2620     rsa = s->s3->peer_rsa_tmp;
2621 #endif
2622 #ifndef OPENSSL_NO_DH
2623     dh = s->s3->peer_dh_tmp;
2624 #endif
2625
2626     /* This is the passed certificate */
2627
2628     idx = s->session->peer_type;
2629 #ifndef OPENSSL_NO_EC
2630     if (idx == SSL_PKEY_ECC) {
2631         if (ssl_check_srvr_ecc_cert_and_alg(s->session->peer, s) == 0) {
2632             /* check failed */
2633             SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_BAD_ECC_CERT);
2634             goto f_err;
2635         } else {
2636             return 1;
2637         }
2638     } else if (alg_a & SSL_aECDSA) {
2639         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
2640                SSL_R_MISSING_ECDSA_SIGNING_CERT);
2641         goto f_err;
2642     } else if (alg_k & (SSL_kECDHr | SSL_kECDHe)) {
2643         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_MISSING_ECDH_CERT);
2644         goto f_err;
2645     }
2646 #endif
2647     pkey = X509_get_pubkey(s->session->peer);
2648     pkey_bits = EVP_PKEY_bits(pkey);
2649     i = X509_certificate_type(s->session->peer, pkey);
2650     EVP_PKEY_free(pkey);
2651
2652     /* Check that we have a certificate if we require one */
2653     if ((alg_a & SSL_aRSA) && !has_bits(i, EVP_PK_RSA | EVP_PKT_SIGN)) {
2654         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
2655                SSL_R_MISSING_RSA_SIGNING_CERT);
2656         goto f_err;
2657     }
2658 #ifndef OPENSSL_NO_DSA
2659     else if ((alg_a & SSL_aDSS) && !has_bits(i, EVP_PK_DSA | EVP_PKT_SIGN)) {
2660         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
2661                SSL_R_MISSING_DSA_SIGNING_CERT);
2662         goto f_err;
2663     }
2664 #endif
2665 #ifndef OPENSSL_NO_RSA
2666     if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
2667         if (!SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
2668             !has_bits(i, EVP_PK_RSA | EVP_PKT_ENC)) {
2669             SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
2670                    SSL_R_MISSING_RSA_ENCRYPTING_CERT);
2671             goto f_err;
2672         } else if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)) {
2673             if (pkey_bits <= SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {
2674                 if (!has_bits(i, EVP_PK_RSA | EVP_PKT_ENC)) {
2675                     SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
2676                            SSL_R_MISSING_RSA_ENCRYPTING_CERT);
2677                     goto f_err;
2678                 }
2679                 if (rsa != NULL) {
2680                     /* server key exchange is not allowed. */
2681                     al = SSL_AD_INTERNAL_ERROR;
2682                     SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR);
2683                     goto f_err;
2684                 }
2685             }
2686         }
2687     }
2688 #endif
2689 #ifndef OPENSSL_NO_DH
2690     if ((alg_k & SSL_kDHE) && (dh == NULL)) {
2691         al = SSL_AD_INTERNAL_ERROR;
2692         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR);
2693         goto f_err;
2694     } else if ((alg_k & SSL_kDHr) && !SSL_USE_SIGALGS(s) &&
2695                !has_bits(i, EVP_PK_DH | EVP_PKS_RSA)) {
2696         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
2697                SSL_R_MISSING_DH_RSA_CERT);
2698         goto f_err;
2699     }
2700 # ifndef OPENSSL_NO_DSA
2701     else if ((alg_k & SSL_kDHd) && !SSL_USE_SIGALGS(s) &&
2702              !has_bits(i, EVP_PK_DH | EVP_PKS_DSA)) {
2703         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
2704                SSL_R_MISSING_DH_DSA_CERT);
2705         goto f_err;
2706     }
2707 # endif
2708 #endif
2709
2710     if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
2711         pkey_bits > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {
2712 #ifndef OPENSSL_NO_RSA
2713         if (alg_k & SSL_kRSA) {
2714             if (rsa == NULL) {
2715                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
2716                        SSL_R_MISSING_EXPORT_TMP_RSA_KEY);
2717                 goto f_err;
2718             } else if (RSA_bits(rsa) >
2719                 SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {
2720                 /* We have a temporary RSA key but it's too large. */
2721                 al = SSL_AD_EXPORT_RESTRICTION;
2722                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
2723                        SSL_R_MISSING_EXPORT_TMP_RSA_KEY);
2724                 goto f_err;
2725             }
2726         } else
2727 #endif
2728 #ifndef OPENSSL_NO_DH
2729         if (alg_k & SSL_kDHE) {
2730             if (DH_bits(dh) >
2731                 SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {
2732                 /* We have a temporary DH key but it's too large. */
2733                 al = SSL_AD_EXPORT_RESTRICTION;
2734                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
2735                        SSL_R_MISSING_EXPORT_TMP_DH_KEY);
2736                 goto f_err;
2737             }
2738         } else if (alg_k & (SSL_kDHr | SSL_kDHd)) {
2739             /* The cert should have had an export DH key. */
2740             al = SSL_AD_EXPORT_RESTRICTION;
2741             SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
2742                    SSL_R_MISSING_EXPORT_TMP_DH_KEY);
2743                 goto f_err;
2744         } else
2745 #endif
2746         {
2747             SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
2748                    SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
2749             goto f_err;
2750         }
2751     }
2752     return (1);
2753  f_err:
2754     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2755     return (0);
2756 }
2757
2758 #ifndef OPENSSL_NO_NEXTPROTONEG
2759 int tls_construct_next_proto(SSL *s)
2760 {
2761     unsigned int len, padding_len;
2762     unsigned char *d;
2763
2764     len = s->next_proto_negotiated_len;
2765     padding_len = 32 - ((len + 2) % 32);
2766     d = (unsigned char *)s->init_buf->data;
2767     d[4] = len;
2768     memcpy(d + 5, s->next_proto_negotiated, len);
2769     d[5 + len] = padding_len;
2770     memset(d + 6 + len, 0, padding_len);
2771     *(d++) = SSL3_MT_NEXT_PROTO;
2772     l2n3(2 + len + padding_len, d);
2773     s->init_num = 4 + 2 + len + padding_len;
2774     s->init_off = 0;
2775
2776     return 1;
2777 }
2778 #endif
2779
2780 int ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
2781 {
2782     int i = 0;
2783 #ifndef OPENSSL_NO_ENGINE
2784     if (s->ctx->client_cert_engine) {
2785         i = ENGINE_load_ssl_client_cert(s->ctx->client_cert_engine, s,
2786                                         SSL_get_client_CA_list(s),
2787                                         px509, ppkey, NULL, NULL, NULL);
2788         if (i != 0)
2789             return i;
2790     }
2791 #endif
2792     if (s->ctx->client_cert_cb)
2793         i = s->ctx->client_cert_cb(s, px509, ppkey);
2794     return i;
2795 }
2796
2797 int ssl_cipher_list_to_bytes(SSL *s, STACK_OF(SSL_CIPHER) *sk,
2798                              unsigned char *p)
2799 {
2800     int i, j = 0;
2801     SSL_CIPHER *c;
2802     unsigned char *q;
2803     int empty_reneg_info_scsv = !s->renegotiate;
2804     /* Set disabled masks for this session */
2805     ssl_set_client_disabled(s);
2806
2807     if (sk == NULL)
2808         return (0);
2809     q = p;
2810
2811     for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
2812         c = sk_SSL_CIPHER_value(sk, i);
2813         /* Skip disabled ciphers */
2814         if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_SUPPORTED))
2815             continue;
2816 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
2817         if (c->id == SSL3_CK_SCSV) {
2818             if (!empty_reneg_info_scsv)
2819                 continue;
2820             else
2821                 empty_reneg_info_scsv = 0;
2822         }
2823 #endif
2824         j = s->method->put_cipher_by_char(c, p);
2825         p += j;
2826     }
2827     /*
2828      * If p == q, no ciphers; caller indicates an error. Otherwise, add
2829      * applicable SCSVs.
2830      */
2831     if (p != q) {
2832         if (empty_reneg_info_scsv) {
2833             static SSL_CIPHER scsv = {
2834                 0, NULL, SSL3_CK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
2835             };
2836             j = s->method->put_cipher_by_char(&scsv, p);
2837             p += j;
2838 #ifdef OPENSSL_RI_DEBUG
2839             fprintf(stderr,
2840                     "TLS_EMPTY_RENEGOTIATION_INFO_SCSV sent by client\n");
2841 #endif
2842         }
2843         if (s->mode & SSL_MODE_SEND_FALLBACK_SCSV) {
2844             static SSL_CIPHER scsv = {
2845                 0, NULL, SSL3_CK_FALLBACK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
2846             };
2847             j = s->method->put_cipher_by_char(&scsv, p);
2848             p += j;
2849         }
2850     }
2851
2852     return (p - q);
2853 }