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