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