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