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