444222328288b29a3548ed8db83f7ae93f28c433
[openssl.git] / ssl / s3_srvr.c
1 /* ssl/s3_srvr.c -*- mode:C; c-file-style: "eay" -*- */
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
152 #include <stdio.h>
153 #include "ssl_locl.h"
154 #include "internal/constant_time_locl.h"
155 #include <openssl/buffer.h>
156 #include <openssl/rand.h>
157 #include <openssl/objects.h>
158 #include <openssl/evp.h>
159 #include <openssl/hmac.h>
160 #include <openssl/x509.h>
161 #ifndef OPENSSL_NO_DH
162 # include <openssl/dh.h>
163 #endif
164 #include <openssl/bn.h>
165 #include <openssl/md5.h>
166
167 static STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list(SSL *s,
168                                                       PACKET *cipher_suites,
169                                                       STACK_OF(SSL_CIPHER) **skp,
170                                                       int sslv2format, int *al);
171
172 #ifndef OPENSSL_NO_SRP
173 static int ssl_check_srp_ext_ClientHello(SSL *s, int *al)
174 {
175     int ret = SSL_ERROR_NONE;
176
177     *al = SSL_AD_UNRECOGNIZED_NAME;
178
179     if ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) &&
180         (s->srp_ctx.TLS_ext_srp_username_callback != NULL)) {
181         if (s->srp_ctx.login == NULL) {
182             /*
183              * RFC 5054 says SHOULD reject, we do so if There is no srp
184              * login name
185              */
186             ret = SSL3_AL_FATAL;
187             *al = SSL_AD_UNKNOWN_PSK_IDENTITY;
188         } else {
189             ret = SSL_srp_server_param_with_username(s, al);
190         }
191     }
192     return ret;
193 }
194 #endif
195
196 int tls_construct_hello_request(SSL *s)
197 {
198     if (!ssl_set_handshake_header(s, SSL3_MT_HELLO_REQUEST, 0)) {
199         SSLerr(SSL_F_TLS_CONSTRUCT_HELLO_REQUEST, ERR_R_INTERNAL_ERROR);
200         statem_set_error(s);
201         return 0;
202     }
203
204     return 1;
205 }
206
207 enum MSG_PROCESS_RETURN tls_process_client_hello(SSL *s, PACKET *pkt)
208 {
209     int i, al = SSL_AD_INTERNAL_ERROR;
210     unsigned int j, complen = 0;
211     unsigned long id;
212     SSL_CIPHER *c;
213 #ifndef OPENSSL_NO_COMP
214     SSL_COMP *comp = NULL;
215 #endif
216     STACK_OF(SSL_CIPHER) *ciphers = NULL;
217     int protverr = 1;
218     /* |cookie| will only be initialized for DTLS. */
219     PACKET session_id, cipher_suites, compression, extensions, cookie;
220     int is_v2_record;
221
222     is_v2_record = RECORD_LAYER_is_sslv2_record(&s->rlayer);
223
224     PACKET_null_init(&cookie);
225     /* First lets get s->client_version set correctly */
226     if (is_v2_record) {
227         unsigned int version;
228         unsigned int mt;
229         /*-
230          * An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2
231          * header is sent directly on the wire, not wrapped as a TLS
232          * record. Our record layer just processes the message length and passes
233          * the rest right through. Its format is:
234          * Byte  Content
235          * 0-1   msg_length - decoded by the record layer
236          * 2     msg_type - s->init_msg points here
237          * 3-4   version
238          * 5-6   cipher_spec_length
239          * 7-8   session_id_length
240          * 9-10  challenge_length
241          * ...   ...
242          */
243
244         if (!PACKET_get_1(pkt, &mt)
245                 || mt != SSL2_MT_CLIENT_HELLO) {
246             /*
247              * Should never happen. We should have tested this in the record
248              * layer in order to have determined that this is a SSLv2 record
249              * in the first place
250              */
251             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
252             goto err;
253         }
254
255         if (!PACKET_get_net_2(pkt, &version)) {
256             /* No protocol version supplied! */
257             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
258             goto err;
259         }
260         if (version == 0x0002) {
261             /* This is real SSLv2. We don't support it. */
262             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
263             goto err;
264         } else if ((version & 0xff00) == (SSL3_VERSION_MAJOR << 8)) {
265             /* SSLv3/TLS */
266             s->client_version = version;
267         } else {
268             /* No idea what protocol this is */
269             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
270             goto err;
271         }
272     } else {
273         /*
274          * use version from inside client hello, not from record header (may
275          * differ: see RFC 2246, Appendix E, second paragraph)
276          */
277         if(!PACKET_get_net_2(pkt, (unsigned int *)&s->client_version)) {
278             al = SSL_AD_DECODE_ERROR;
279             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
280             goto f_err;
281         }
282     }
283
284     /* Do SSL/TLS version negotiation if applicable */
285     if (!SSL_IS_DTLS(s)) {
286         if (s->version != TLS_ANY_VERSION) {
287             if (s->client_version >= s->version) {
288                 protverr = 0;
289             }
290         } else if (s->client_version >= SSL3_VERSION) {
291             switch(s->client_version) {
292             default:
293             case TLS1_2_VERSION:
294                 if(!(s->options & SSL_OP_NO_TLSv1_2)) {
295                     s->version = TLS1_2_VERSION;
296                     s->method = TLSv1_2_server_method();
297                     protverr = 0;
298                     break;
299                 }
300                 /* Deliberately fall through */
301             case TLS1_1_VERSION:
302                 if(!(s->options & SSL_OP_NO_TLSv1_1)) {
303                     s->version = TLS1_1_VERSION;
304                     s->method = TLSv1_1_server_method();
305                     protverr = 0;
306                     break;
307                 }
308                 /* Deliberately fall through */
309             case TLS1_VERSION:
310                 if(!(s->options & SSL_OP_NO_TLSv1)) {
311                     s->version = TLS1_VERSION;
312                     s->method = TLSv1_server_method();
313                     protverr = 0;
314                     break;
315                 }
316                 /* Deliberately fall through */
317             case SSL3_VERSION:
318 #ifndef OPENSSL_NO_SSL3
319                 if(!(s->options & SSL_OP_NO_SSLv3)) {
320                     s->version = SSL3_VERSION;
321                     s->method = SSLv3_server_method();
322                     protverr = 0;
323                     break;
324                 }
325 #else
326                 break;
327 #endif
328             }
329         }
330     } else if (s->client_version <= s->version
331                 || s->method->version == DTLS_ANY_VERSION) {
332         /*
333          * For DTLS we just check versions are potentially compatible. Version
334          * negotiation comes later.
335          */
336         protverr = 0;
337     }
338
339     if (protverr) {
340         SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
341         if ((!s->enc_write_ctx && !s->write_hash)) {
342             /*
343              * similar to ssl3_get_record, send alert using remote version
344              * number
345              */
346             s->version = s->client_version;
347         }
348         al = SSL_AD_PROTOCOL_VERSION;
349         goto f_err;
350     }
351
352     /* Parse the message and load client random. */
353     if (is_v2_record) {
354         /*
355          * Handle an SSLv2 backwards compatible ClientHello
356          * Note, this is only for SSLv3+ using the backward compatible format.
357          * Real SSLv2 is not supported, and is rejected above.
358          */
359         unsigned int cipher_len, session_id_len, challenge_len;
360         PACKET challenge;
361
362         if (!PACKET_get_net_2(pkt, &cipher_len)
363                 || !PACKET_get_net_2(pkt, &session_id_len)
364                 || !PACKET_get_net_2(pkt, &challenge_len)) {
365             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
366                    SSL_R_RECORD_LENGTH_MISMATCH);
367             al = SSL_AD_DECODE_ERROR;
368             goto f_err;
369         }
370
371         if (!PACKET_get_sub_packet(pkt, &cipher_suites, cipher_len)
372             || !PACKET_get_sub_packet(pkt, &session_id, session_id_len)
373             || !PACKET_get_sub_packet(pkt, &challenge, challenge_len)
374             /* No extensions. */
375             || PACKET_remaining(pkt) != 0) {
376             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_RECORD_LENGTH_MISMATCH);
377             al = SSL_AD_DECODE_ERROR;
378             goto f_err;
379         }
380
381         /* Load the client random */
382         challenge_len = challenge_len > SSL3_RANDOM_SIZE ? SSL3_RANDOM_SIZE :
383             challenge_len;
384         memset(s->s3->client_random, 0, SSL3_RANDOM_SIZE);
385         if (!PACKET_copy_bytes(&challenge,
386                                s->s3->client_random + SSL3_RANDOM_SIZE -
387                                challenge_len, challenge_len)) {
388             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
389             al = SSL_AD_INTERNAL_ERROR;
390             goto f_err;
391         }
392
393         PACKET_null_init(&compression);
394         PACKET_null_init(&extensions);
395     } else {
396         /* Regular ClientHello. */
397         if (!PACKET_copy_bytes(pkt, s->s3->client_random, SSL3_RANDOM_SIZE)
398             || !PACKET_get_length_prefixed_1(pkt, &session_id)) {
399             al = SSL_AD_DECODE_ERROR;
400             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
401             goto f_err;
402         }
403
404         if (SSL_IS_DTLS(s)) {
405             if (!PACKET_get_length_prefixed_1(pkt, &cookie)) {
406                 al = SSL_AD_DECODE_ERROR;
407                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
408                 goto f_err;
409             }
410             /*
411              * If we require cookies and this ClientHello doesn't contain one,
412              * just return since we do not want to allocate any memory yet.
413              * So check cookie length...
414              */
415             if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
416                 if (PACKET_remaining(&cookie) == 0)
417                 return 1;
418             }
419         }
420
421         if (!PACKET_get_length_prefixed_2(pkt, &cipher_suites)
422             || !PACKET_get_length_prefixed_1(pkt, &compression)) {
423                 al = SSL_AD_DECODE_ERROR;
424                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
425                 goto f_err;
426         }
427         /* Could be empty. */
428         extensions = *pkt;
429     }
430
431     s->hit = 0;
432
433     /*
434      * We don't allow resumption in a backwards compatible ClientHello.
435      * TODO(openssl-team): in TLS1.1+, session_id MUST be empty.
436      *
437      * Versions before 0.9.7 always allow clients to resume sessions in
438      * renegotiation. 0.9.7 and later allow this by default, but optionally
439      * ignore resumption requests with flag
440      * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
441      * than a change to default behavior so that applications relying on
442      * this for security won't even compile against older library versions).
443      * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
444      * request renegotiation but not a new session (s->new_session remains
445      * unset): for servers, this essentially just means that the
446      * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be
447      * ignored.
448      */
449     if (is_v2_record ||
450         (s->new_session &&
451          (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
452         if (!ssl_get_new_session(s, 1))
453             goto err;
454     } else {
455         i = ssl_get_prev_session(s, &extensions, &session_id);
456         /*
457          * Only resume if the session's version matches the negotiated
458          * version.
459          * RFC 5246 does not provide much useful advice on resumption
460          * with a different protocol version. It doesn't forbid it but
461          * the sanity of such behaviour would be questionable.
462          * In practice, clients do not accept a version mismatch and
463          * will abort the handshake with an error.
464          */
465         if (i == 1 && s->version == s->session->ssl_version) {
466             /* previous session */
467             s->hit = 1;
468         } else if (i == -1) {
469             goto err;
470         } else {
471             /* i == 0 */
472             if (!ssl_get_new_session(s, 1))
473                 goto err;
474         }
475     }
476
477     if (SSL_IS_DTLS(s)) {
478         /* Empty cookie was already handled above by returning early. */
479         if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
480             if (s->ctx->app_verify_cookie_cb != NULL) {
481                 if (s->ctx->app_verify_cookie_cb(s, PACKET_data(&cookie),
482                                                  PACKET_remaining(&cookie)) == 0) {
483                     al = SSL_AD_HANDSHAKE_FAILURE;
484                     SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
485                            SSL_R_COOKIE_MISMATCH);
486                     goto f_err;
487                     /* else cookie verification succeeded */
488                 }
489             /* default verification */
490             } else if (!PACKET_equal(&cookie, s->d1->cookie,
491                                      s->d1->cookie_len)) {
492                 al = SSL_AD_HANDSHAKE_FAILURE;
493                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
494                 goto f_err;
495             }
496             s->d1->cookie_verified = 1;
497         }
498         if (s->method->version == DTLS_ANY_VERSION) {
499             /* Select version to use */
500             if (s->client_version <= DTLS1_2_VERSION &&
501                 !(s->options & SSL_OP_NO_DTLSv1_2)) {
502                 s->version = DTLS1_2_VERSION;
503                 s->method = DTLSv1_2_server_method();
504             } else if (tls1_suiteb(s)) {
505                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
506                        SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
507                 s->version = s->client_version;
508                 al = SSL_AD_PROTOCOL_VERSION;
509                 goto f_err;
510             } else if (s->client_version <= DTLS1_VERSION &&
511                        !(s->options & SSL_OP_NO_DTLSv1)) {
512                 s->version = DTLS1_VERSION;
513                 s->method = DTLSv1_server_method();
514             } else {
515                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
516                        SSL_R_WRONG_VERSION_NUMBER);
517                 s->version = s->client_version;
518                 al = SSL_AD_PROTOCOL_VERSION;
519                 goto f_err;
520             }
521             s->session->ssl_version = s->version;
522         }
523     }
524
525     if (ssl_bytes_to_cipher_list(s, &cipher_suites, &(ciphers),
526                                  is_v2_record, &al) == NULL) {
527         goto f_err;
528     }
529
530     /* If it is a hit, check that the cipher is in the list */
531     if (s->hit) {
532         j = 0;
533         id = s->session->cipher->id;
534
535 #ifdef CIPHER_DEBUG
536         fprintf(stderr, "client sent %d ciphers\n",
537                 sk_SSL_CIPHER_num(ciphers));
538 #endif
539         for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
540             c = sk_SSL_CIPHER_value(ciphers, i);
541 #ifdef CIPHER_DEBUG
542             fprintf(stderr, "client [%2d of %2d]:%s\n",
543                     i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
544 #endif
545             if (c->id == id) {
546                 j = 1;
547                 break;
548             }
549         }
550         if (j == 0) {
551             /*
552              * we need to have the cipher in the cipher list if we are asked
553              * to reuse it
554              */
555             al = SSL_AD_ILLEGAL_PARAMETER;
556             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
557                    SSL_R_REQUIRED_CIPHER_MISSING);
558             goto f_err;
559         }
560     }
561
562     complen = PACKET_remaining(&compression);
563     for (j = 0; j < complen; j++) {
564         if (PACKET_data(&compression)[j] == 0)
565             break;
566     }
567
568     if (j >= complen) {
569         /* no compress */
570         al = SSL_AD_DECODE_ERROR;
571         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED);
572         goto f_err;
573     }
574     
575     /* TLS extensions */
576     if (s->version >= SSL3_VERSION) {
577         if (!ssl_parse_clienthello_tlsext(s, &extensions)) {
578             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_PARSE_TLSEXT);
579             goto err;
580         }
581     }
582
583     /*
584      * Check if we want to use external pre-shared secret for this handshake
585      * for not reused session only. We need to generate server_random before
586      * calling tls_session_secret_cb in order to allow SessionTicket
587      * processing to use it in key derivation.
588      */
589     {
590         unsigned char *pos;
591         pos = s->s3->server_random;
592         if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0) {
593             goto f_err;
594         }
595     }
596
597     if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb) {
598         SSL_CIPHER *pref_cipher = NULL;
599
600         s->session->master_key_length = sizeof(s->session->master_key);
601         if (s->tls_session_secret_cb(s, s->session->master_key,
602                                      &s->session->master_key_length, ciphers,
603                                      &pref_cipher,
604                                      s->tls_session_secret_cb_arg)) {
605             s->hit = 1;
606             s->session->ciphers = ciphers;
607             s->session->verify_result = X509_V_OK;
608
609             ciphers = NULL;
610
611             /* check if some cipher was preferred by call back */
612             pref_cipher =
613                 pref_cipher ? pref_cipher : ssl3_choose_cipher(s,
614                                                                s->
615                                                                session->ciphers,
616                                                                SSL_get_ciphers
617                                                                (s));
618             if (pref_cipher == NULL) {
619                 al = SSL_AD_HANDSHAKE_FAILURE;
620                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
621                 goto f_err;
622             }
623
624             s->session->cipher = pref_cipher;
625             sk_SSL_CIPHER_free(s->cipher_list);
626             s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
627             sk_SSL_CIPHER_free(s->cipher_list_by_id);
628             s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
629         }
630     }
631
632     /*
633      * Worst case, we will use the NULL compression, but if we have other
634      * options, we will now look for them.  We have complen-1 compression
635      * algorithms from the client, starting at q.
636      */
637     s->s3->tmp.new_compression = NULL;
638 #ifndef OPENSSL_NO_COMP
639     /* This only happens if we have a cache hit */
640     if (s->session->compress_meth != 0) {
641         int m, comp_id = s->session->compress_meth;
642         unsigned int k;
643         /* Perform sanity checks on resumed compression algorithm */
644         /* Can't disable compression */
645         if (!ssl_allow_compression(s)) {
646             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
647                    SSL_R_INCONSISTENT_COMPRESSION);
648             goto f_err;
649         }
650         /* Look for resumed compression method */
651         for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) {
652             comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
653             if (comp_id == comp->id) {
654                 s->s3->tmp.new_compression = comp;
655                 break;
656             }
657         }
658         if (s->s3->tmp.new_compression == NULL) {
659             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
660                    SSL_R_INVALID_COMPRESSION_ALGORITHM);
661             goto f_err;
662         }
663         /* Look for resumed method in compression list */
664         for (k = 0; k < complen; k++) {
665             if (PACKET_data(&compression)[k] == comp_id)
666                 break;
667         }
668         if (k >= complen) {
669             al = SSL_AD_ILLEGAL_PARAMETER;
670             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
671                    SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING);
672             goto f_err;
673         }
674     } else if (s->hit)
675         comp = NULL;
676     else if (ssl_allow_compression(s) && s->ctx->comp_methods) {
677         /* See if we have a match */
678         int m, nn, v, done = 0;
679         unsigned int o;
680
681         nn = sk_SSL_COMP_num(s->ctx->comp_methods);
682         for (m = 0; m < nn; m++) {
683             comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
684             v = comp->id;
685             for (o = 0; o < complen; o++) {
686                 if (v == PACKET_data(&compression)[o]) {
687                     done = 1;
688                     break;
689                 }
690             }
691             if (done)
692                 break;
693         }
694         if (done)
695             s->s3->tmp.new_compression = comp;
696         else
697             comp = NULL;
698     }
699 #else
700     /*
701      * If compression is disabled we'd better not try to resume a session
702      * using compression.
703      */
704     if (s->session->compress_meth != 0) {
705         SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
706         goto f_err;
707     }
708 #endif
709
710     /*
711      * Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher
712      */
713
714     if (!s->hit) {
715 #ifdef OPENSSL_NO_COMP
716         s->session->compress_meth = 0;
717 #else
718         s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
719 #endif
720         sk_SSL_CIPHER_free(s->session->ciphers);
721         s->session->ciphers = ciphers;
722         if (ciphers == NULL) {
723             al = SSL_AD_INTERNAL_ERROR;
724             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
725             goto f_err;
726         }
727         ciphers = NULL;
728         if (!tls1_set_server_sigalgs(s)) {
729             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
730             goto err;
731         }
732     }
733
734     sk_SSL_CIPHER_free(ciphers);
735     return MSG_PROCESS_CONTINUE_PROCESSING;
736  f_err:
737     ssl3_send_alert(s, SSL3_AL_FATAL, al);
738  err:
739     statem_set_error(s);
740
741     sk_SSL_CIPHER_free(ciphers);
742     return MSG_PROCESS_ERROR;
743
744 }
745
746 enum WORK_STATE tls_post_process_client_hello(SSL *s, enum WORK_STATE wst)
747 {
748     int al;
749     SSL_CIPHER *cipher;
750
751     if (wst == WORK_MORE_A) {
752         if (!s->hit) {
753             /* Let cert callback update server certificates if required */
754             if (s->cert->cert_cb) {
755                 int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
756                 if (rv == 0) {
757                     al = SSL_AD_INTERNAL_ERROR;
758                     SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO, SSL_R_CERT_CB_ERROR);
759                     goto f_err;
760                 }
761                 if (rv < 0) {
762                     s->rwstate = SSL_X509_LOOKUP;
763                     return WORK_MORE_A;
764                 }
765                 s->rwstate = SSL_NOTHING;
766             }
767             cipher = ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
768
769             if (cipher == NULL) {
770                 al = SSL_AD_HANDSHAKE_FAILURE;
771                 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
772                 goto f_err;
773             }
774             s->s3->tmp.new_cipher = cipher;
775             /* check whether we should disable session resumption */
776             if (s->not_resumable_session_cb != NULL)
777                 s->session->not_resumable = s->not_resumable_session_cb(s,
778                     ((cipher->algorithm_mkey & (SSL_kDHE | SSL_kECDHE)) != 0));
779             if (s->session->not_resumable)
780                 /* do not send a session ticket */
781                 s->tlsext_ticket_expected = 0;
782         } else {
783             /* Session-id reuse */
784             s->s3->tmp.new_cipher = s->session->cipher;
785         }
786
787         if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER)) {
788             if (!ssl3_digest_cached_records(s, 0))
789                 goto f_err;
790         }
791
792         /*-
793          * we now have the following setup.
794          * client_random
795          * cipher_list          - our prefered list of ciphers
796          * ciphers              - the clients prefered list of ciphers
797          * compression          - basically ignored right now
798          * ssl version is set   - sslv3
799          * s->session           - The ssl session has been setup.
800          * s->hit               - session reuse flag
801          * s->s3->tmp.new_cipher- the new cipher to use.
802          */
803
804         /* Handles TLS extensions that we couldn't check earlier */
805         if (s->version >= SSL3_VERSION) {
806             if (ssl_check_clienthello_tlsext_late(s) <= 0) {
807                 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
808                 goto f_err;
809             }
810         }
811
812         wst = WORK_MORE_B;
813     }
814 #ifndef OPENSSL_NO_SRP
815     if (wst == WORK_MORE_B) {
816         int ret;
817         if ((ret = ssl_check_srp_ext_ClientHello(s, &al)) < 0) {
818             /*
819              * callback indicates further work to be done
820              */
821             s->rwstate = SSL_X509_LOOKUP;
822             return WORK_MORE_B;
823         }
824         if (ret != SSL_ERROR_NONE) {
825             /*
826              * This is not really an error but the only means to for
827              * a client to detect whether srp is supported.
828              */
829             if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)
830                 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
831                            SSL_R_CLIENTHELLO_TLSEXT);
832             goto f_err;
833         }
834     }
835 #endif
836     s->renegotiate = 2;
837
838     return WORK_FINISHED_STOP;
839  f_err:
840     ssl3_send_alert(s, SSL3_AL_FATAL, al);
841     statem_set_error(s);
842     return WORK_ERROR;
843 }
844
845 int tls_construct_server_hello(SSL *s)
846 {
847     unsigned char *buf;
848     unsigned char *p, *d;
849     int i, sl;
850     int al = 0;
851     unsigned long l;
852
853     buf = (unsigned char *)s->init_buf->data;
854
855     /* Do the message type and length last */
856     d = p = ssl_handshake_start(s);
857
858     *(p++) = s->version >> 8;
859     *(p++) = s->version & 0xff;
860
861     /*
862      * Random stuff. Filling of the server_random takes place in
863      * tls_process_client_hello()
864      */
865     memcpy(p, s->s3->server_random, SSL3_RANDOM_SIZE);
866     p += SSL3_RANDOM_SIZE;
867
868     /*-
869      * There are several cases for the session ID to send
870      * back in the server hello:
871      * - For session reuse from the session cache,
872      *   we send back the old session ID.
873      * - If stateless session reuse (using a session ticket)
874      *   is successful, we send back the client's "session ID"
875      *   (which doesn't actually identify the session).
876      * - If it is a new session, we send back the new
877      *   session ID.
878      * - However, if we want the new session to be single-use,
879      *   we send back a 0-length session ID.
880      * s->hit is non-zero in either case of session reuse,
881      * so the following won't overwrite an ID that we're supposed
882      * to send back.
883      */
884     if (s->session->not_resumable ||
885         (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
886          && !s->hit))
887         s->session->session_id_length = 0;
888
889     sl = s->session->session_id_length;
890     if (sl > (int)sizeof(s->session->session_id)) {
891         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
892         statem_set_error(s);
893         return 0;
894     }
895     *(p++) = sl;
896     memcpy(p, s->session->session_id, sl);
897     p += sl;
898
899     /* put the cipher */
900     i = ssl3_put_cipher_by_char(s->s3->tmp.new_cipher, p);
901     p += i;
902
903     /* put the compression method */
904 #ifdef OPENSSL_NO_COMP
905     *(p++) = 0;
906 #else
907     if (s->s3->tmp.new_compression == NULL)
908         *(p++) = 0;
909     else
910         *(p++) = s->s3->tmp.new_compression->id;
911 #endif
912
913     if (ssl_prepare_serverhello_tlsext(s) <= 0) {
914         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, SSL_R_SERVERHELLO_TLSEXT);
915         statem_set_error(s);
916         return 0;
917     }
918     if ((p =
919          ssl_add_serverhello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,
920                                     &al)) == NULL) {
921         ssl3_send_alert(s, SSL3_AL_FATAL, al);
922         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
923         statem_set_error(s);
924         return 0;
925     }
926
927     /* do the header */
928     l = (p - d);
929     if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l)) {
930         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
931         statem_set_error(s);
932         return 0;
933     }
934
935     return 1;
936 }
937
938 int tls_construct_server_done(SSL *s)
939 {
940     if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0)) {
941         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_DONE, ERR_R_INTERNAL_ERROR);
942         statem_set_error(s);
943         return 0;
944     }
945
946     if (!s->s3->tmp.cert_request) {
947         if (!ssl3_digest_cached_records(s, 0)) {
948             statem_set_error(s);
949         }
950     }
951
952     return 1;
953 }
954
955 int tls_construct_server_key_exchange(SSL *s)
956 {
957 #ifndef OPENSSL_NO_RSA
958     unsigned char *q;
959     int j, num;
960     RSA *rsa;
961     unsigned char md_buf[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH];
962     unsigned int u;
963 #endif
964 #ifndef OPENSSL_NO_DH
965     DH *dh = NULL, *dhp;
966 #endif
967 #ifndef OPENSSL_NO_EC
968     EC_KEY *ecdh = NULL, *ecdhp;
969     unsigned char *encodedPoint = NULL;
970     int encodedlen = 0;
971     int curve_id = 0;
972     BN_CTX *bn_ctx = NULL;
973 #endif
974     EVP_PKEY *pkey;
975     const EVP_MD *md = NULL;
976     unsigned char *p, *d;
977     int al, i;
978     unsigned long type;
979     int n;
980     CERT *cert;
981     BIGNUM *r[4];
982     int nr[4], kn;
983     BUF_MEM *buf;
984     EVP_MD_CTX md_ctx;
985
986     EVP_MD_CTX_init(&md_ctx);
987
988     type = s->s3->tmp.new_cipher->algorithm_mkey;
989     cert = s->cert;
990
991     buf = s->init_buf;
992
993     r[0] = r[1] = r[2] = r[3] = NULL;
994     n = 0;
995 #ifndef OPENSSL_NO_PSK
996     if (type & SSL_PSK) {
997         /*
998          * reserve size for record length and PSK identity hint
999          */
1000         n += 2;
1001         if (s->cert->psk_identity_hint)
1002             n += strlen(s->cert->psk_identity_hint);
1003     }
1004     /* Plain PSK or RSAPSK nothing to do */
1005     if (type & (SSL_kPSK | SSL_kRSAPSK)) {
1006     } else
1007 #endif                          /* !OPENSSL_NO_PSK */
1008 #ifndef OPENSSL_NO_RSA
1009     if (type & SSL_kRSA) {
1010         rsa = cert->rsa_tmp;
1011         if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL)) {
1012             rsa = s->cert->rsa_tmp_cb(s,
1013                                       SSL_C_IS_EXPORT(s->s3->
1014                                                       tmp.new_cipher),
1015                                       SSL_C_EXPORT_PKEYLENGTH(s->s3->
1016                                                               tmp.new_cipher));
1017             if (rsa == NULL) {
1018                 al = SSL_AD_HANDSHAKE_FAILURE;
1019                 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1020                        SSL_R_ERROR_GENERATING_TMP_RSA_KEY);
1021                 goto f_err;
1022             }
1023             RSA_up_ref(rsa);
1024             cert->rsa_tmp = rsa;
1025         }
1026         if (rsa == NULL) {
1027             al = SSL_AD_HANDSHAKE_FAILURE;
1028             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1029                    SSL_R_MISSING_TMP_RSA_KEY);
1030             goto f_err;
1031         }
1032         r[0] = rsa->n;
1033         r[1] = rsa->e;
1034         s->s3->tmp.use_rsa_tmp = 1;
1035     } else
1036 #endif
1037 #ifndef OPENSSL_NO_DH
1038     if (type & (SSL_kDHE | SSL_kDHEPSK)) {
1039         if (s->cert->dh_tmp_auto) {
1040             dhp = ssl_get_auto_dh(s);
1041             if (dhp == NULL) {
1042                 al = SSL_AD_INTERNAL_ERROR;
1043                 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1044                        ERR_R_INTERNAL_ERROR);
1045                 goto f_err;
1046             }
1047         } else
1048             dhp = cert->dh_tmp;
1049         if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1050             dhp = s->cert->dh_tmp_cb(s,
1051                                      SSL_C_IS_EXPORT(s->s3->
1052                                                      tmp.new_cipher),
1053                                      SSL_C_EXPORT_PKEYLENGTH(s->s3->
1054                                                              tmp.new_cipher));
1055         if (dhp == NULL) {
1056             al = SSL_AD_HANDSHAKE_FAILURE;
1057             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1058                    SSL_R_MISSING_TMP_DH_KEY);
1059             goto f_err;
1060         }
1061         if (!ssl_security(s, SSL_SECOP_TMP_DH,
1062                           DH_security_bits(dhp), 0, dhp)) {
1063             al = SSL_AD_HANDSHAKE_FAILURE;
1064             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1065                    SSL_R_DH_KEY_TOO_SMALL);
1066             goto f_err;
1067         }
1068         if (s->s3->tmp.dh != NULL) {
1069             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1070                    ERR_R_INTERNAL_ERROR);
1071             goto err;
1072         }
1073
1074         if (s->cert->dh_tmp_auto)
1075             dh = dhp;
1076         else if ((dh = DHparams_dup(dhp)) == NULL) {
1077             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1078             goto err;
1079         }
1080
1081         s->s3->tmp.dh = dh;
1082         if ((dhp->pub_key == NULL ||
1083              dhp->priv_key == NULL ||
1084              (s->options & SSL_OP_SINGLE_DH_USE))) {
1085             if (!DH_generate_key(dh)) {
1086                 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1087                 goto err;
1088             }
1089         } else {
1090             dh->pub_key = BN_dup(dhp->pub_key);
1091             dh->priv_key = BN_dup(dhp->priv_key);
1092             if ((dh->pub_key == NULL) || (dh->priv_key == NULL)) {
1093                 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1094                 goto err;
1095             }
1096         }
1097         r[0] = dh->p;
1098         r[1] = dh->g;
1099         r[2] = dh->pub_key;
1100     } else
1101 #endif
1102 #ifndef OPENSSL_NO_EC
1103     if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
1104         const EC_GROUP *group;
1105
1106         ecdhp = cert->ecdh_tmp;
1107         if (s->cert->ecdh_tmp_auto) {
1108             /* Get NID of appropriate shared curve */
1109             int nid = tls1_shared_curve(s, -2);
1110             if (nid != NID_undef)
1111                 ecdhp = EC_KEY_new_by_curve_name(nid);
1112         } else if ((ecdhp == NULL) && s->cert->ecdh_tmp_cb) {
1113             ecdhp = s->cert->ecdh_tmp_cb(s,
1114                                          SSL_C_IS_EXPORT(s->s3->
1115                                                          tmp.new_cipher),
1116                                          SSL_C_EXPORT_PKEYLENGTH(s->
1117                                                                  s3->tmp.new_cipher));
1118         }
1119         if (ecdhp == NULL) {
1120             al = SSL_AD_HANDSHAKE_FAILURE;
1121             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1122                    SSL_R_MISSING_TMP_ECDH_KEY);
1123             goto f_err;
1124         }
1125
1126         if (s->s3->tmp.ecdh != NULL) {
1127             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1128                    ERR_R_INTERNAL_ERROR);
1129             goto err;
1130         }
1131
1132         /* Duplicate the ECDH structure. */
1133         if (ecdhp == NULL) {
1134             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1135             goto err;
1136         }
1137         if (s->cert->ecdh_tmp_auto)
1138             ecdh = ecdhp;
1139         else if ((ecdh = EC_KEY_dup(ecdhp)) == NULL) {
1140             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1141             goto err;
1142         }
1143
1144         s->s3->tmp.ecdh = ecdh;
1145         if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1146             (EC_KEY_get0_private_key(ecdh) == NULL) ||
1147             (s->options & SSL_OP_SINGLE_ECDH_USE)) {
1148             if (!EC_KEY_generate_key(ecdh)) {
1149                 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1150                        ERR_R_ECDH_LIB);
1151                 goto err;
1152             }
1153         }
1154
1155         if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1156             (EC_KEY_get0_public_key(ecdh) == NULL) ||
1157             (EC_KEY_get0_private_key(ecdh) == NULL)) {
1158             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1159             goto err;
1160         }
1161
1162         if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1163             (EC_GROUP_get_degree(group) > 163)) {
1164             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1165                    SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1166             goto err;
1167         }
1168
1169         /*
1170          * XXX: For now, we only support ephemeral ECDH keys over named
1171          * (not generic) curves. For supported named curves, curve_id is
1172          * non-zero.
1173          */
1174         if ((curve_id =
1175              tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group)))
1176             == 0) {
1177             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1178                    SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1179             goto err;
1180         }
1181
1182         /*
1183          * Encode the public key. First check the size of encoding and
1184          * allocate memory accordingly.
1185          */
1186         encodedlen = EC_POINT_point2oct(group,
1187                                         EC_KEY_get0_public_key(ecdh),
1188                                         POINT_CONVERSION_UNCOMPRESSED,
1189                                         NULL, 0, NULL);
1190
1191         encodedPoint = (unsigned char *)
1192             OPENSSL_malloc(encodedlen * sizeof(unsigned char));
1193         bn_ctx = BN_CTX_new();
1194         if ((encodedPoint == NULL) || (bn_ctx == NULL)) {
1195             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1196                    ERR_R_MALLOC_FAILURE);
1197             goto err;
1198         }
1199
1200         encodedlen = EC_POINT_point2oct(group,
1201                                         EC_KEY_get0_public_key(ecdh),
1202                                         POINT_CONVERSION_UNCOMPRESSED,
1203                                         encodedPoint, encodedlen, bn_ctx);
1204
1205         if (encodedlen == 0) {
1206             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1207             goto err;
1208         }
1209
1210         BN_CTX_free(bn_ctx);
1211         bn_ctx = NULL;
1212
1213         /*
1214          * XXX: For now, we only support named (not generic) curves in
1215          * ECDH ephemeral key exchanges. In this situation, we need four
1216          * additional bytes to encode the entire ServerECDHParams
1217          * structure.
1218          */
1219         n += 4 + encodedlen;
1220
1221         /*
1222          * We'll generate the serverKeyExchange message explicitly so we
1223          * can set these to NULLs
1224          */
1225         r[0] = NULL;
1226         r[1] = NULL;
1227         r[2] = NULL;
1228         r[3] = NULL;
1229     } else
1230 #endif                          /* !OPENSSL_NO_EC */
1231 #ifndef OPENSSL_NO_SRP
1232     if (type & SSL_kSRP) {
1233         if ((s->srp_ctx.N == NULL) ||
1234             (s->srp_ctx.g == NULL) ||
1235             (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
1236             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1237                    SSL_R_MISSING_SRP_PARAM);
1238             goto err;
1239         }
1240         r[0] = s->srp_ctx.N;
1241         r[1] = s->srp_ctx.g;
1242         r[2] = s->srp_ctx.s;
1243         r[3] = s->srp_ctx.B;
1244     } else
1245 #endif
1246     {
1247         al = SSL_AD_HANDSHAKE_FAILURE;
1248         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1249                SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1250         goto f_err;
1251     }
1252     for (i = 0; i < 4 && r[i] != NULL; i++) {
1253         nr[i] = BN_num_bytes(r[i]);
1254 #ifndef OPENSSL_NO_SRP
1255         if ((i == 2) && (type & SSL_kSRP))
1256             n += 1 + nr[i];
1257         else
1258 #endif
1259             n += 2 + nr[i];
1260     }
1261
1262     if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aSRP))
1263         && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_PSK)) {
1264         if ((pkey = ssl_get_sign_pkey(s, s->s3->tmp.new_cipher, &md))
1265             == NULL) {
1266             al = SSL_AD_DECODE_ERROR;
1267             goto f_err;
1268         }
1269         kn = EVP_PKEY_size(pkey);
1270     } else {
1271         pkey = NULL;
1272         kn = 0;
1273     }
1274
1275     if (!BUF_MEM_grow_clean(buf, n + SSL_HM_HEADER_LENGTH(s) + kn)) {
1276         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_LIB_BUF);
1277         goto err;
1278     }
1279     d = p = ssl_handshake_start(s);
1280
1281 #ifndef OPENSSL_NO_PSK
1282     if (type & SSL_PSK) {
1283         /* copy PSK identity hint */
1284         if (s->cert->psk_identity_hint) {
1285             s2n(strlen(s->cert->psk_identity_hint), p);
1286             strncpy((char *)p, s->cert->psk_identity_hint,
1287                     strlen(s->cert->psk_identity_hint));
1288             p += strlen(s->cert->psk_identity_hint);
1289         } else {
1290             s2n(0, p);
1291         }
1292     }
1293 #endif
1294
1295     for (i = 0; i < 4 && r[i] != NULL; i++) {
1296 #ifndef OPENSSL_NO_SRP
1297         if ((i == 2) && (type & SSL_kSRP)) {
1298             *p = nr[i];
1299             p++;
1300         } else
1301 #endif
1302             s2n(nr[i], p);
1303         BN_bn2bin(r[i], p);
1304         p += nr[i];
1305     }
1306
1307 #ifndef OPENSSL_NO_EC
1308     if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
1309         /*
1310          * XXX: For now, we only support named (not generic) curves. In
1311          * this situation, the serverKeyExchange message has: [1 byte
1312          * CurveType], [2 byte CurveName] [1 byte length of encoded
1313          * point], followed by the actual encoded point itself
1314          */
1315         *p = NAMED_CURVE_TYPE;
1316         p += 1;
1317         *p = 0;
1318         p += 1;
1319         *p = curve_id;
1320         p += 1;
1321         *p = encodedlen;
1322         p += 1;
1323         memcpy(p, encodedPoint, encodedlen);
1324         OPENSSL_free(encodedPoint);
1325         encodedPoint = NULL;
1326         p += encodedlen;
1327     }
1328 #endif
1329
1330     /* not anonymous */
1331     if (pkey != NULL) {
1332         /*
1333          * n is the length of the params, they start at &(d[4]) and p
1334          * points to the space at the end.
1335          */
1336 #ifndef OPENSSL_NO_RSA
1337         if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) {
1338             q = md_buf;
1339             j = 0;
1340             for (num = 2; num > 0; num--) {
1341                 EVP_MD_CTX_set_flags(&md_ctx,
1342                                      EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
1343                 EVP_DigestInit_ex(&md_ctx, (num == 2)
1344                                   ? s->ctx->md5 : s->ctx->sha1, NULL);
1345                 EVP_DigestUpdate(&md_ctx, &(s->s3->client_random[0]),
1346                                  SSL3_RANDOM_SIZE);
1347                 EVP_DigestUpdate(&md_ctx, &(s->s3->server_random[0]),
1348                                  SSL3_RANDOM_SIZE);
1349                 EVP_DigestUpdate(&md_ctx, d, n);
1350                 EVP_DigestFinal_ex(&md_ctx, q, (unsigned int *)&i);
1351                 q += i;
1352                 j += i;
1353             }
1354             if (RSA_sign(NID_md5_sha1, md_buf, j,
1355                          &(p[2]), &u, pkey->pkey.rsa) <= 0) {
1356                 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_LIB_RSA);
1357                 goto err;
1358             }
1359             s2n(u, p);
1360             n += u + 2;
1361         } else
1362 #endif
1363         if (md) {
1364             /* send signature algorithm */
1365             if (SSL_USE_SIGALGS(s)) {
1366                 if (!tls12_get_sigandhash(p, pkey, md)) {
1367                     /* Should never happen */
1368                     al = SSL_AD_INTERNAL_ERROR;
1369                     SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1370                            ERR_R_INTERNAL_ERROR);
1371                     goto f_err;
1372                 }
1373                 p += 2;
1374             }
1375 #ifdef SSL_DEBUG
1376             fprintf(stderr, "Using hash %s\n", EVP_MD_name(md));
1377 #endif
1378             EVP_SignInit_ex(&md_ctx, md, NULL);
1379             EVP_SignUpdate(&md_ctx, &(s->s3->client_random[0]),
1380                            SSL3_RANDOM_SIZE);
1381             EVP_SignUpdate(&md_ctx, &(s->s3->server_random[0]),
1382                            SSL3_RANDOM_SIZE);
1383             EVP_SignUpdate(&md_ctx, d, n);
1384             if (!EVP_SignFinal(&md_ctx, &(p[2]),
1385                                (unsigned int *)&i, pkey)) {
1386                 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_LIB_EVP);
1387                 goto err;
1388             }
1389             s2n(i, p);
1390             n += i + 2;
1391             if (SSL_USE_SIGALGS(s))
1392                 n += 2;
1393         } else {
1394             /* Is this error check actually needed? */
1395             al = SSL_AD_HANDSHAKE_FAILURE;
1396             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1397                    SSL_R_UNKNOWN_PKEY_TYPE);
1398             goto f_err;
1399         }
1400     }
1401
1402     if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n)) {
1403         al = SSL_AD_HANDSHAKE_FAILURE;
1404         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1405         goto f_err;
1406     }
1407
1408     EVP_MD_CTX_cleanup(&md_ctx);
1409     return 1;
1410  f_err:
1411     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1412  err:
1413 #ifndef OPENSSL_NO_EC
1414     OPENSSL_free(encodedPoint);
1415     BN_CTX_free(bn_ctx);
1416 #endif
1417     EVP_MD_CTX_cleanup(&md_ctx);
1418     statem_set_error(s);
1419     return 0;
1420 }
1421
1422 int tls_construct_certificate_request(SSL *s)
1423 {
1424     unsigned char *p, *d;
1425     int i, j, nl, off, n;
1426     STACK_OF(X509_NAME) *sk = NULL;
1427     X509_NAME *name;
1428     BUF_MEM *buf;
1429
1430     buf = s->init_buf;
1431
1432     d = p = ssl_handshake_start(s);
1433
1434     /* get the list of acceptable cert types */
1435     p++;
1436     n = ssl3_get_req_cert_type(s, p);
1437     d[0] = n;
1438     p += n;
1439     n++;
1440
1441     if (SSL_USE_SIGALGS(s)) {
1442         const unsigned char *psigs;
1443         unsigned char *etmp = p;
1444         nl = tls12_get_psigalgs(s, &psigs);
1445         /* Skip over length for now */
1446         p += 2;
1447         nl = tls12_copy_sigalgs(s, p, psigs, nl);
1448         /* Now fill in length */
1449         s2n(nl, etmp);
1450         p += nl;
1451         n += nl + 2;
1452     }
1453
1454     off = n;
1455     p += 2;
1456     n += 2;
1457
1458     sk = SSL_get_client_CA_list(s);
1459     nl = 0;
1460     if (sk != NULL) {
1461         for (i = 0; i < sk_X509_NAME_num(sk); i++) {
1462             name = sk_X509_NAME_value(sk, i);
1463             j = i2d_X509_NAME(name, NULL);
1464             if (!BUF_MEM_grow_clean
1465                 (buf, SSL_HM_HEADER_LENGTH(s) + n + j + 2)) {
1466                 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
1467                        ERR_R_BUF_LIB);
1468                 goto err;
1469             }
1470             p = ssl_handshake_start(s) + n;
1471             s2n(j, p);
1472             i2d_X509_NAME(name, &p);
1473             n += 2 + j;
1474             nl += 2 + j;
1475         }
1476     }
1477     /* else no CA names */
1478     p = ssl_handshake_start(s) + off;
1479     s2n(nl, p);
1480
1481     if (!ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n)) {
1482         SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR);
1483         goto err;
1484     }
1485
1486     s->s3->tmp.cert_request = 1;
1487
1488     return 1;
1489  err:
1490     statem_set_error(s);
1491     return 0;
1492 }
1493
1494 enum MSG_PROCESS_RETURN tls_process_client_key_exchange(SSL *s, PACKET *pkt)
1495 {
1496     int al;
1497     unsigned int i;
1498     unsigned long alg_k;
1499 #ifndef OPENSSL_NO_RSA
1500     RSA *rsa = NULL;
1501     EVP_PKEY *pkey = NULL;
1502 #endif
1503 #ifndef OPENSSL_NO_DH
1504     BIGNUM *pub = NULL;
1505     DH *dh_srvr, *dh_clnt = NULL;
1506 #endif
1507 #ifndef OPENSSL_NO_EC
1508     EC_KEY *srvr_ecdh = NULL;
1509     EVP_PKEY *clnt_pub_pkey = NULL;
1510     EC_POINT *clnt_ecpoint = NULL;
1511     BN_CTX *bn_ctx = NULL;
1512 #endif
1513     PACKET enc_premaster;
1514     unsigned char *data, *rsa_decrypt = NULL;
1515
1516     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1517
1518 #ifndef OPENSSL_NO_PSK
1519     /* For PSK parse and retrieve identity, obtain PSK key */
1520     if (alg_k & SSL_PSK) {
1521         unsigned char psk[PSK_MAX_PSK_LEN];
1522         size_t psklen;
1523         PACKET psk_identity;
1524
1525         if (!PACKET_get_length_prefixed_2(pkt, &psk_identity)) {
1526             al = SSL_AD_DECODE_ERROR;
1527             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
1528             goto f_err;
1529         }
1530         if (PACKET_remaining(&psk_identity) > PSK_MAX_IDENTITY_LEN) {
1531             al = SSL_AD_DECODE_ERROR;
1532             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
1533                    SSL_R_DATA_LENGTH_TOO_LONG);
1534             goto f_err;
1535         }
1536         if (s->psk_server_callback == NULL) {
1537             al = SSL_AD_INTERNAL_ERROR;
1538             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
1539                    SSL_R_PSK_NO_SERVER_CB);
1540             goto f_err;
1541         }
1542
1543         if (!PACKET_strndup(&psk_identity, &s->session->psk_identity)) {
1544             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1545             al = SSL_AD_INTERNAL_ERROR;
1546             goto f_err;
1547         }
1548
1549         psklen = s->psk_server_callback(s, s->session->psk_identity,
1550                                          psk, sizeof(psk));
1551
1552         if (psklen > PSK_MAX_PSK_LEN) {
1553             al = SSL_AD_INTERNAL_ERROR;
1554             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1555             goto f_err;
1556         } else if (psklen == 0) {
1557             /*
1558              * PSK related to the given identity not found
1559              */
1560             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
1561                    SSL_R_PSK_IDENTITY_NOT_FOUND);
1562             al = SSL_AD_UNKNOWN_PSK_IDENTITY;
1563             goto f_err;
1564         }
1565
1566         OPENSSL_free(s->s3->tmp.psk);
1567         s->s3->tmp.psk = BUF_memdup(psk, psklen);
1568         OPENSSL_cleanse(psk, psklen);
1569
1570         if (s->s3->tmp.psk == NULL) {
1571             al = SSL_AD_INTERNAL_ERROR;
1572             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1573             goto f_err;
1574         }
1575
1576         s->s3->tmp.psklen = psklen;
1577     }
1578     if (alg_k & SSL_kPSK) {
1579         /* Identity extracted earlier: should be nothing left */
1580         if (PACKET_remaining(pkt) != 0) {
1581             al = SSL_AD_HANDSHAKE_FAILURE;
1582             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
1583             goto f_err;
1584         }
1585         /* PSK handled by ssl_generate_master_secret */
1586         if (!ssl_generate_master_secret(s, NULL, 0, 0)) {
1587             al = SSL_AD_INTERNAL_ERROR;
1588             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1589             goto f_err;
1590         }
1591     } else
1592 #endif
1593 #ifndef OPENSSL_NO_RSA
1594     if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
1595         unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
1596         int decrypt_len;
1597         unsigned char decrypt_good, version_good;
1598         size_t j;
1599
1600         /* FIX THIS UP EAY EAY EAY EAY */
1601         if (s->s3->tmp.use_rsa_tmp) {
1602             if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
1603                 rsa = s->cert->rsa_tmp;
1604             /*
1605              * Don't do a callback because rsa_tmp should be sent already
1606              */
1607             if (rsa == NULL) {
1608                 al = SSL_AD_HANDSHAKE_FAILURE;
1609                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
1610                        SSL_R_MISSING_TMP_RSA_PKEY);
1611                 goto f_err;
1612
1613             }
1614         } else {
1615             pkey = s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
1616             if ((pkey == NULL) ||
1617                 (pkey->type != EVP_PKEY_RSA) || (pkey->pkey.rsa == NULL)) {
1618                 al = SSL_AD_HANDSHAKE_FAILURE;
1619                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
1620                        SSL_R_MISSING_RSA_CERTIFICATE);
1621                 goto f_err;
1622             }
1623             rsa = pkey->pkey.rsa;
1624         }
1625
1626         /* SSLv3 and pre-standard DTLS omit the length bytes. */
1627         if (s->version == SSL3_VERSION || s->version == DTLS1_BAD_VER) {
1628             enc_premaster = *pkt;
1629         } else {
1630             PACKET orig = *pkt;
1631             if (!PACKET_get_length_prefixed_2(pkt, &enc_premaster)
1632                 || PACKET_remaining(pkt) != 0) {
1633                 /* Try SSLv3 behaviour for TLS. */
1634                 if (s->options & SSL_OP_TLS_D5_BUG) {
1635                     enc_premaster = orig;
1636                 } else {
1637                     al = SSL_AD_DECODE_ERROR;
1638                     SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
1639                     goto f_err;
1640                 }
1641             }
1642         }
1643
1644         /*
1645          * We want to be sure that the plaintext buffer size makes it safe to
1646          * iterate over the entire size of a premaster secret
1647          * (SSL_MAX_MASTER_KEY_LENGTH). Reject overly short RSA keys because
1648          * their ciphertext cannot accommodate a premaster secret anyway.
1649          */
1650         if (RSA_size(rsa) < SSL_MAX_MASTER_KEY_LENGTH) {
1651             al = SSL_AD_INTERNAL_ERROR;
1652             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1653                    RSA_R_KEY_SIZE_TOO_SMALL);
1654             goto f_err;
1655         }
1656
1657         rsa_decrypt = OPENSSL_malloc(RSA_size(rsa));
1658         if (rsa_decrypt == NULL) {
1659             al = SSL_AD_INTERNAL_ERROR;
1660             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1661             goto f_err;
1662         }
1663
1664         /*
1665          * We must not leak whether a decryption failure occurs because of
1666          * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
1667          * section 7.4.7.1). The code follows that advice of the TLS RFC and
1668          * generates a random premaster secret for the case that the decrypt
1669          * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
1670          */
1671
1672         if (RAND_bytes(rand_premaster_secret,
1673                        sizeof(rand_premaster_secret)) <= 0) {
1674             goto err;
1675         }
1676
1677         decrypt_len = RSA_private_decrypt(PACKET_remaining(&enc_premaster),
1678                                           PACKET_data(&enc_premaster),
1679                                           rsa_decrypt, rsa, RSA_PKCS1_PADDING);
1680         ERR_clear_error();
1681
1682         /*
1683          * decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH. decrypt_good will
1684          * be 0xff if so and zero otherwise.
1685          */
1686         decrypt_good =
1687             constant_time_eq_int_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH);
1688
1689         /*
1690          * If the version in the decrypted pre-master secret is correct then
1691          * version_good will be 0xff, otherwise it'll be zero. The
1692          * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
1693          * (http://eprint.iacr.org/2003/052/) exploits the version number
1694          * check as a "bad version oracle". Thus version checks are done in
1695          * constant time and are treated like any other decryption error.
1696          */
1697         version_good =
1698             constant_time_eq_8(rsa_decrypt[0],
1699                                (unsigned)(s->client_version >> 8));
1700         version_good &=
1701             constant_time_eq_8(rsa_decrypt[1],
1702                                (unsigned)(s->client_version & 0xff));
1703
1704         /*
1705          * The premaster secret must contain the same version number as the
1706          * ClientHello to detect version rollback attacks (strangely, the
1707          * protocol does not offer such protection for DH ciphersuites).
1708          * However, buggy clients exist that send the negotiated protocol
1709          * version instead if the server does not support the requested
1710          * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
1711          * clients.
1712          */
1713         if (s->options & SSL_OP_TLS_ROLLBACK_BUG) {
1714             unsigned char workaround_good;
1715             workaround_good =
1716                 constant_time_eq_8(rsa_decrypt[0], (unsigned)(s->version >> 8));
1717             workaround_good &=
1718                 constant_time_eq_8(rsa_decrypt[1],
1719                                    (unsigned)(s->version & 0xff));
1720             version_good |= workaround_good;
1721         }
1722
1723         /*
1724          * Both decryption and version must be good for decrypt_good to
1725          * remain non-zero (0xff).
1726          */
1727         decrypt_good &= version_good;
1728
1729         /*
1730          * Now copy rand_premaster_secret over from p using
1731          * decrypt_good_mask. If decryption failed, then p does not
1732          * contain valid plaintext, however, a check above guarantees
1733          * it is still sufficiently large to read from.
1734          */
1735         for (j = 0; j < sizeof(rand_premaster_secret); j++) {
1736             rsa_decrypt[j] =
1737                 constant_time_select_8(decrypt_good, rsa_decrypt[j],
1738                                        rand_premaster_secret[j]);
1739         }
1740
1741         if (!ssl_generate_master_secret(s, rsa_decrypt,
1742                                         sizeof(rand_premaster_secret), 0)) {
1743             al = SSL_AD_INTERNAL_ERROR;
1744             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1745             goto f_err;
1746         }
1747         OPENSSL_free(rsa_decrypt);
1748         rsa_decrypt = NULL;
1749     } else
1750 #endif
1751 #ifndef OPENSSL_NO_DH
1752     if (alg_k & (SSL_kDHE | SSL_kDHr | SSL_kDHd | SSL_kDHEPSK)) {
1753         int idx = -1;
1754         EVP_PKEY *skey = NULL;
1755         PACKET bookmark = *pkt;
1756         unsigned char shared[(OPENSSL_DH_MAX_MODULUS_BITS + 7) / 8];
1757
1758         if (!PACKET_get_net_2(pkt, &i)) {
1759             if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
1760                 al = SSL_AD_HANDSHAKE_FAILURE;
1761                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
1762                        SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
1763                 goto f_err;
1764             }
1765             i = 0;
1766         }
1767         if (PACKET_remaining(pkt) != i) {
1768             if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG)) {
1769                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
1770                        SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
1771                 goto err;
1772             } else {
1773                 *pkt = bookmark;
1774                 i = PACKET_remaining(pkt);
1775             }
1776         }
1777         if (alg_k & SSL_kDHr)
1778             idx = SSL_PKEY_DH_RSA;
1779         else if (alg_k & SSL_kDHd)
1780             idx = SSL_PKEY_DH_DSA;
1781         if (idx >= 0) {
1782             skey = s->cert->pkeys[idx].privatekey;
1783             if ((skey == NULL) ||
1784                 (skey->type != EVP_PKEY_DH) || (skey->pkey.dh == NULL)) {
1785                 al = SSL_AD_HANDSHAKE_FAILURE;
1786                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
1787                        SSL_R_MISSING_RSA_CERTIFICATE);
1788                 goto f_err;
1789             }
1790             dh_srvr = skey->pkey.dh;
1791         } else if (s->s3->tmp.dh == NULL) {
1792             al = SSL_AD_HANDSHAKE_FAILURE;
1793             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
1794                    SSL_R_MISSING_TMP_DH_KEY);
1795             goto f_err;
1796         } else
1797             dh_srvr = s->s3->tmp.dh;
1798
1799         if (PACKET_remaining(pkt) == 0L) {
1800             /* Get pubkey from cert */
1801             EVP_PKEY *clkey = X509_get_pubkey(s->session->peer);
1802             if (clkey) {
1803                 if (EVP_PKEY_cmp_parameters(clkey, skey) == 1)
1804                     dh_clnt = EVP_PKEY_get1_DH(clkey);
1805             }
1806             if (dh_clnt == NULL) {
1807                 al = SSL_AD_HANDSHAKE_FAILURE;
1808                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
1809                        SSL_R_MISSING_TMP_DH_KEY);
1810                 goto f_err;
1811             }
1812             EVP_PKEY_free(clkey);
1813             pub = dh_clnt->pub_key;
1814         } else {
1815             if (!PACKET_get_bytes(pkt, &data, i)) {
1816                 /* We already checked we have enough data */
1817                 al = SSL_AD_INTERNAL_ERROR;
1818                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
1819                        ERR_R_INTERNAL_ERROR);
1820                 goto f_err;
1821             }
1822             pub = BN_bin2bn(data, i, NULL);
1823         }
1824         if (pub == NULL) {
1825             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_BN_LIB);
1826             goto err;
1827         }
1828
1829         i = DH_compute_key(shared, pub, dh_srvr);
1830
1831         if (i <= 0) {
1832             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
1833             BN_clear_free(pub);
1834             goto err;
1835         }
1836
1837         DH_free(s->s3->tmp.dh);
1838         s->s3->tmp.dh = NULL;
1839         if (dh_clnt)
1840             DH_free(dh_clnt);
1841         else
1842             BN_clear_free(pub);
1843         pub = NULL;
1844         if (!ssl_generate_master_secret(s, shared, i, 0)) {
1845             al = SSL_AD_INTERNAL_ERROR;
1846             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1847             goto f_err;
1848         }
1849         if (dh_clnt) {
1850             s->no_cert_verify = 1;
1851             return MSG_PROCESS_CONTINUE_PROCESSING;
1852         }
1853     } else
1854 #endif
1855
1856 #ifndef OPENSSL_NO_EC
1857     if (alg_k & (SSL_kECDHE | SSL_kECDHr | SSL_kECDHe | SSL_kECDHEPSK)) {
1858         int field_size = 0;
1859         const EC_KEY *tkey;
1860         const EC_GROUP *group;
1861         const BIGNUM *priv_key;
1862         unsigned char *shared;
1863
1864         /* initialize structures for server's ECDH key pair */
1865         if ((srvr_ecdh = EC_KEY_new()) == NULL) {
1866             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1867             goto err;
1868         }
1869
1870         /* Let's get server private key and group information */
1871         if (alg_k & (SSL_kECDHr | SSL_kECDHe)) {
1872             /* use the certificate */
1873             tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec;
1874         } else {
1875             /*
1876              * use the ephermeral values we saved when generating the
1877              * ServerKeyExchange msg.
1878              */
1879             tkey = s->s3->tmp.ecdh;
1880         }
1881
1882         group = EC_KEY_get0_group(tkey);
1883         priv_key = EC_KEY_get0_private_key(tkey);
1884
1885         if (!EC_KEY_set_group(srvr_ecdh, group) ||
1886             !EC_KEY_set_private_key(srvr_ecdh, priv_key)) {
1887             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
1888             goto err;
1889         }
1890
1891         /* Let's get client's public key */
1892         if ((clnt_ecpoint = EC_POINT_new(group)) == NULL) {
1893             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1894             goto err;
1895         }
1896
1897         if (PACKET_remaining(pkt) == 0L) {
1898             /* Client Publickey was in Client Certificate */
1899
1900             if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
1901                 al = SSL_AD_HANDSHAKE_FAILURE;
1902                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
1903                        SSL_R_MISSING_TMP_ECDH_KEY);
1904                 goto f_err;
1905             }
1906             if (((clnt_pub_pkey = X509_get_pubkey(s->session->peer))
1907                  == NULL) || (clnt_pub_pkey->type != EVP_PKEY_EC)) {
1908                 /*
1909                  * XXX: For now, we do not support client authentication
1910                  * using ECDH certificates so this branch (n == 0L) of the
1911                  * code is never executed. When that support is added, we
1912                  * ought to ensure the key received in the certificate is
1913                  * authorized for key agreement. ECDH_compute_key implicitly
1914                  * checks that the two ECDH shares are for the same group.
1915                  */
1916                 al = SSL_AD_HANDSHAKE_FAILURE;
1917                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
1918                        SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
1919                 goto f_err;
1920             }
1921
1922             if (EC_POINT_copy(clnt_ecpoint,
1923                               EC_KEY_get0_public_key(clnt_pub_pkey->
1924                                                      pkey.ec)) == 0) {
1925                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
1926                 goto err;
1927             }
1928             s->no_cert_verify = 1;
1929         } else {
1930             /*
1931              * Get client's public key from encoded point in the
1932              * ClientKeyExchange message.
1933              */
1934             if ((bn_ctx = BN_CTX_new()) == NULL) {
1935                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
1936                        ERR_R_MALLOC_FAILURE);
1937                 goto err;
1938             }
1939
1940             /* Get encoded point length */
1941             if (!PACKET_get_1(pkt, &i)) {
1942                 al = SSL_AD_DECODE_ERROR;
1943                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
1944                        SSL_R_LENGTH_MISMATCH);
1945                 goto f_err;
1946             }
1947             if (!PACKET_get_bytes(pkt, &data, i)
1948                     || PACKET_remaining(pkt) != 0) {
1949                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
1950                 goto err;
1951             }
1952             if (EC_POINT_oct2point(group, clnt_ecpoint, data, i, bn_ctx) == 0) {
1953                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
1954                 goto err;
1955             }
1956         }
1957
1958         /* Compute the shared pre-master secret */
1959         field_size = EC_GROUP_get_degree(group);
1960         if (field_size <= 0) {
1961             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1962             goto err;
1963         }
1964         shared = OPENSSL_malloc((field_size + 7) / 8);
1965         if (shared == NULL) {
1966             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1967             goto err;
1968         }
1969         i = ECDH_compute_key(shared, (field_size + 7) / 8, clnt_ecpoint,
1970                              srvr_ecdh, NULL);
1971         if (i <= 0) {
1972             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1973             OPENSSL_free(shared);
1974             goto err;
1975         }
1976
1977         EVP_PKEY_free(clnt_pub_pkey);
1978         EC_POINT_free(clnt_ecpoint);
1979         EC_KEY_free(srvr_ecdh);
1980         BN_CTX_free(bn_ctx);
1981         EC_KEY_free(s->s3->tmp.ecdh);
1982         s->s3->tmp.ecdh = NULL;
1983
1984         if (!ssl_generate_master_secret(s, shared, i, 1)) {
1985             al = SSL_AD_INTERNAL_ERROR;
1986             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1987             goto f_err;
1988         }
1989         return MSG_PROCESS_CONTINUE_PROCESSING;
1990     } else
1991 #endif
1992 #ifndef OPENSSL_NO_SRP
1993     if (alg_k & SSL_kSRP) {
1994         if (!PACKET_get_net_2(pkt, &i)
1995                 || !PACKET_get_bytes(pkt, &data, i)) {
1996             al = SSL_AD_DECODE_ERROR;
1997             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_BAD_SRP_A_LENGTH);
1998             goto f_err;
1999         }
2000         if ((s->srp_ctx.A = BN_bin2bn(data, i, NULL)) == NULL) {
2001             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_BN_LIB);
2002             goto err;
2003         }
2004         if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0
2005             || BN_is_zero(s->srp_ctx.A)) {
2006             al = SSL_AD_ILLEGAL_PARAMETER;
2007             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2008                    SSL_R_BAD_SRP_PARAMETERS);
2009             goto f_err;
2010         }
2011         OPENSSL_free(s->session->srp_username);
2012         s->session->srp_username = BUF_strdup(s->srp_ctx.login);
2013         if (s->session->srp_username == NULL) {
2014             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2015             goto err;
2016         }
2017
2018         if (!srp_generate_server_master_secret(s)) {
2019             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2020             goto err;
2021         }
2022     } else
2023 #endif                          /* OPENSSL_NO_SRP */
2024     if (alg_k & SSL_kGOST) {
2025         EVP_PKEY_CTX *pkey_ctx;
2026         EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2027         unsigned char premaster_secret[32], *start;
2028         size_t outlen = 32, inlen;
2029         unsigned long alg_a;
2030         int Ttag, Tclass;
2031         long Tlen;
2032         long sess_key_len;
2033
2034         /* Get our certificate private key */
2035         alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2036         if (alg_a & SSL_aGOST01)
2037             pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2038
2039         pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
2040         EVP_PKEY_decrypt_init(pkey_ctx);
2041         /*
2042          * If client certificate is present and is of the same type, maybe
2043          * use it for key exchange.  Don't mind errors from
2044          * EVP_PKEY_derive_set_peer, because it is completely valid to use a
2045          * client certificate for authorization only.
2046          */
2047         client_pub_pkey = X509_get_pubkey(s->session->peer);
2048         if (client_pub_pkey) {
2049             if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
2050                 ERR_clear_error();
2051         }
2052         /* Decrypt session key */
2053         sess_key_len = PACKET_remaining(pkt);
2054         if (!PACKET_get_bytes(pkt, &data, sess_key_len)) {
2055             al = SSL_AD_INTERNAL_ERROR;
2056             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2057             goto f_err;
2058         }
2059         if (ASN1_get_object ((const unsigned char **)&data, &Tlen, &Ttag,
2060                              &Tclass, sess_key_len) != V_ASN1_CONSTRUCTED
2061             || Ttag != V_ASN1_SEQUENCE
2062             || Tclass != V_ASN1_UNIVERSAL) {
2063             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2064                    SSL_R_DECRYPTION_FAILED);
2065             goto gerr;
2066         }
2067         start = data;
2068         inlen = Tlen;
2069         if (EVP_PKEY_decrypt
2070             (pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {
2071             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2072                    SSL_R_DECRYPTION_FAILED);
2073             goto gerr;
2074         }
2075         /* Generate master secret */
2076         if (!ssl_generate_master_secret(s, premaster_secret,
2077                                         sizeof(premaster_secret), 0)) {
2078             al = SSL_AD_INTERNAL_ERROR;
2079             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2080             goto f_err;
2081         }
2082         /* Check if pubkey from client certificate was used */
2083         if (EVP_PKEY_CTX_ctrl
2084             (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
2085             s->no_cert_verify = 1;
2086
2087         EVP_PKEY_free(client_pub_pkey);
2088         EVP_PKEY_CTX_free(pkey_ctx);
2089         return MSG_PROCESS_CONTINUE_PROCESSING;
2090  gerr:
2091         EVP_PKEY_free(client_pub_pkey);
2092         EVP_PKEY_CTX_free(pkey_ctx);
2093         goto err;
2094     } else {
2095         al = SSL_AD_HANDSHAKE_FAILURE;
2096         SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_UNKNOWN_CIPHER_TYPE);
2097         goto f_err;
2098     }
2099
2100     return MSG_PROCESS_CONTINUE_PROCESSING;
2101  f_err:
2102     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2103 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_EC) || defined(OPENSSL_NO_SRP)
2104  err:
2105 #endif
2106 #ifndef OPENSSL_NO_EC
2107     EVP_PKEY_free(clnt_pub_pkey);
2108     EC_POINT_free(clnt_ecpoint);
2109     EC_KEY_free(srvr_ecdh);
2110     BN_CTX_free(bn_ctx);
2111     OPENSSL_free(rsa_decrypt);
2112 #endif
2113 #ifndef OPENSSL_NO_PSK
2114     OPENSSL_clear_free(s->s3->tmp.psk, s->s3->tmp.psklen);
2115     s->s3->tmp.psk = NULL;
2116 #endif
2117     statem_set_error(s);
2118     return MSG_PROCESS_ERROR;
2119 }
2120
2121 enum WORK_STATE tls_post_process_client_key_exchange(SSL *s,
2122                                                       enum WORK_STATE wst)
2123 {
2124 #ifndef OPENSSL_NO_SCTP
2125     if (wst == WORK_MORE_A) {
2126         if (SSL_IS_DTLS(s)) {
2127             unsigned char sctpauthkey[64];
2128             char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
2129             /*
2130              * Add new shared key for SCTP-Auth, will be ignored if no SCTP
2131              * used.
2132              */
2133             snprintf((char *)labelbuffer, sizeof(DTLS1_SCTP_AUTH_LABEL),
2134                      DTLS1_SCTP_AUTH_LABEL);
2135
2136             if (SSL_export_keying_material(s, sctpauthkey,
2137                                        sizeof(sctpauthkey), labelbuffer,
2138                                        sizeof(labelbuffer), NULL, 0, 0) <= 0) {
2139                 statem_set_error(s);
2140                 return WORK_ERROR;;
2141             }
2142
2143             BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
2144                      sizeof(sctpauthkey), sctpauthkey);
2145         }
2146         wst = WORK_MORE_B;
2147     }
2148
2149     if ((wst == WORK_MORE_B)
2150             /* Is this SCTP? */
2151             && BIO_dgram_is_sctp(SSL_get_wbio(s))
2152             /* Are we renegotiating? */
2153             && s->renegotiate
2154             /* Are we going to skip the CertificateVerify? */
2155             && (s->session->peer == NULL || s->no_cert_verify)
2156             && BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
2157         s->s3->in_read_app_data = 2;
2158         s->rwstate = SSL_READING;
2159         BIO_clear_retry_flags(SSL_get_rbio(s));
2160         BIO_set_retry_read(SSL_get_rbio(s));
2161         statem_set_sctp_read_sock(s, 1);
2162         return WORK_MORE_B;
2163     } else {
2164         statem_set_sctp_read_sock(s, 0);
2165     }
2166 #endif
2167
2168     if (s->no_cert_verify) {
2169         /* No certificate verify so we no longer need the handshake_buffer */
2170         BIO_free(s->s3->handshake_buffer);
2171         return WORK_FINISHED_CONTINUE;
2172     } else if (SSL_USE_SIGALGS(s)) {
2173         if (!s->session->peer) {
2174             /* No peer certificate so we no longer need the handshake_buffer */
2175             BIO_free(s->s3->handshake_buffer);
2176             return WORK_FINISHED_CONTINUE;
2177         }
2178         if (!s->s3->handshake_buffer) {
2179             SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_KEY_EXCHANGE,
2180                    ERR_R_INTERNAL_ERROR);
2181             statem_set_error(s);
2182             return WORK_ERROR;
2183         }
2184         /*
2185          * For sigalgs freeze the handshake buffer. If we support
2186          * extms we've done this already so this is a no-op
2187          */
2188         if (!ssl3_digest_cached_records(s, 1)) {
2189             statem_set_error(s);
2190             return WORK_ERROR;
2191         }
2192     } else {
2193         int offset = 0;
2194         int dgst_num;
2195
2196         /*
2197          * We need to get hashes here so if there is a client cert,
2198          * it can be verified FIXME - digest processing for
2199          * CertificateVerify should be generalized. But it is next
2200          * step
2201          */
2202         if (!ssl3_digest_cached_records(s, 0)) {
2203             statem_set_error(s);
2204             return WORK_ERROR;
2205         }
2206         for (dgst_num = 0; dgst_num < SSL_MAX_DIGEST; dgst_num++) {
2207             if (s->s3->handshake_dgst[dgst_num]) {
2208                 int dgst_size;
2209
2210                 s->method->ssl3_enc->cert_verify_mac(s,
2211                                                      EVP_MD_CTX_type
2212                                                      (s->
2213                                                       s3->handshake_dgst
2214                                                       [dgst_num]),
2215                                                      &(s->s3->
2216                                                        tmp.cert_verify_md
2217                                                        [offset]));
2218                 dgst_size =
2219                     EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]);
2220                 if (dgst_size < 0) {
2221                     statem_set_error(s);
2222                 return WORK_ERROR;
2223                 }
2224                 offset += dgst_size;
2225             }
2226         }
2227     }
2228
2229     return WORK_FINISHED_CONTINUE;
2230 }
2231
2232 enum MSG_PROCESS_RETURN tls_process_cert_verify(SSL *s, PACKET *pkt)
2233 {
2234     EVP_PKEY *pkey = NULL;
2235     unsigned char *sig, *data;
2236     int al, ret = MSG_PROCESS_ERROR;
2237     int type = 0, i, j;
2238     unsigned int len;
2239     X509 *peer;
2240     const EVP_MD *md = NULL;
2241     EVP_MD_CTX mctx;
2242     EVP_MD_CTX_init(&mctx);
2243
2244     peer = s->session->peer;
2245     pkey = X509_get_pubkey(peer);
2246     type = X509_certificate_type(peer, pkey);
2247
2248     if (!(type & EVP_PKT_SIGN)) {
2249         SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY,
2250                SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
2251         al = SSL_AD_ILLEGAL_PARAMETER;
2252         goto f_err;
2253     }
2254
2255     /* Check for broken implementations of GOST ciphersuites */
2256     /*
2257      * If key is GOST and n is exactly 64, it is bare signature without
2258      * length field
2259      */
2260     if (PACKET_remaining(pkt) == 64 && pkey->type == NID_id_GostR3410_2001) {
2261         len = 64;
2262     } else {
2263         if (SSL_USE_SIGALGS(s)) {
2264             int rv;
2265
2266             if (!PACKET_get_bytes(pkt, &sig, 2)) {
2267                 al = SSL_AD_DECODE_ERROR;
2268                 goto f_err;
2269             }
2270             rv = tls12_check_peer_sigalg(&md, s, sig, pkey);
2271             if (rv == -1) {
2272                 al = SSL_AD_INTERNAL_ERROR;
2273                 goto f_err;
2274             } else if (rv == 0) {
2275                 al = SSL_AD_DECODE_ERROR;
2276                 goto f_err;
2277             }
2278 #ifdef SSL_DEBUG
2279             fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
2280 #endif
2281         }
2282         if (!PACKET_get_net_2(pkt, &len)) {
2283             SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
2284             al = SSL_AD_DECODE_ERROR;
2285             goto f_err;
2286         }
2287     }
2288     j = EVP_PKEY_size(pkey);
2289     if (((int)len > j) || ((int)PACKET_remaining(pkt) > j)
2290             || (PACKET_remaining(pkt) == 0)) {
2291         SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_WRONG_SIGNATURE_SIZE);
2292         al = SSL_AD_DECODE_ERROR;
2293         goto f_err;
2294     }
2295     if (!PACKET_get_bytes(pkt, &data, len)) {
2296         SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
2297         al = SSL_AD_DECODE_ERROR;
2298         goto f_err;
2299     }
2300
2301     if (SSL_USE_SIGALGS(s)) {
2302         long hdatalen = 0;
2303         void *hdata;
2304         hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
2305         if (hdatalen <= 0) {
2306             SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
2307             al = SSL_AD_INTERNAL_ERROR;
2308             goto f_err;
2309         }
2310 #ifdef SSL_DEBUG
2311         fprintf(stderr, "Using TLS 1.2 with client verify alg %s\n",
2312                 EVP_MD_name(md));
2313 #endif
2314         if (!EVP_VerifyInit_ex(&mctx, md, NULL)
2315             || !EVP_VerifyUpdate(&mctx, hdata, hdatalen)) {
2316             SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
2317             al = SSL_AD_INTERNAL_ERROR;
2318             goto f_err;
2319         }
2320
2321         if (EVP_VerifyFinal(&mctx, data, len, pkey) <= 0) {
2322             al = SSL_AD_DECRYPT_ERROR;
2323             SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_BAD_SIGNATURE);
2324             goto f_err;
2325         }
2326     } else
2327 #ifndef OPENSSL_NO_RSA
2328     if (pkey->type == EVP_PKEY_RSA) {
2329         i = RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
2330                        MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH, data, len,
2331                        pkey->pkey.rsa);
2332         if (i < 0) {
2333             al = SSL_AD_DECRYPT_ERROR;
2334             SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_BAD_RSA_DECRYPT);
2335             goto f_err;
2336         }
2337         if (i == 0) {
2338             al = SSL_AD_DECRYPT_ERROR;
2339             SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_BAD_RSA_SIGNATURE);
2340             goto f_err;
2341         }
2342     } else
2343 #endif
2344 #ifndef OPENSSL_NO_DSA
2345     if (pkey->type == EVP_PKEY_DSA) {
2346         j = DSA_verify(pkey->save_type,
2347                        &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
2348                        SHA_DIGEST_LENGTH, data, len, pkey->pkey.dsa);
2349         if (j <= 0) {
2350             /* bad signature */
2351             al = SSL_AD_DECRYPT_ERROR;
2352             SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_BAD_DSA_SIGNATURE);
2353             goto f_err;
2354         }
2355     } else
2356 #endif
2357 #ifndef OPENSSL_NO_EC
2358     if (pkey->type == EVP_PKEY_EC) {
2359         j = ECDSA_verify(pkey->save_type,
2360                          &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
2361                          SHA_DIGEST_LENGTH, data, len, pkey->pkey.ec);
2362         if (j <= 0) {
2363             /* bad signature */
2364             al = SSL_AD_DECRYPT_ERROR;
2365             SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE);
2366             goto f_err;
2367         }
2368     } else
2369 #endif
2370     if (pkey->type == NID_id_GostR3410_2001) {
2371         unsigned char signature[64];
2372         int idx;
2373         EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey, NULL);
2374         EVP_PKEY_verify_init(pctx);
2375         if (len != 64) {
2376             fprintf(stderr, "GOST signature length is %d", len);
2377         }
2378         for (idx = 0; idx < 64; idx++) {
2379             signature[63 - idx] = data[idx];
2380         }
2381         j = EVP_PKEY_verify(pctx, signature, 64, s->s3->tmp.cert_verify_md,
2382                             32);
2383         EVP_PKEY_CTX_free(pctx);
2384         if (j <= 0) {
2385             al = SSL_AD_DECRYPT_ERROR;
2386             SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE);
2387             goto f_err;
2388         }
2389     } else {
2390         SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
2391         al = SSL_AD_UNSUPPORTED_CERTIFICATE;
2392         goto f_err;
2393     }
2394
2395     ret = MSG_PROCESS_CONTINUE_PROCESSING;
2396     if (0) {
2397  f_err:
2398         ssl3_send_alert(s, SSL3_AL_FATAL, al);
2399         statem_set_error(s);
2400     }
2401     BIO_free(s->s3->handshake_buffer);
2402     s->s3->handshake_buffer = NULL;
2403     EVP_MD_CTX_cleanup(&mctx);
2404     EVP_PKEY_free(pkey);
2405     return ret;
2406 }
2407
2408 enum MSG_PROCESS_RETURN tls_process_client_certificate(SSL *s, PACKET *pkt)
2409 {
2410     int i, al, ret = MSG_PROCESS_ERROR;
2411     X509 *x = NULL;
2412     unsigned long l, llen;
2413     const unsigned char *certstart;
2414     unsigned char *certbytes;
2415     STACK_OF(X509) *sk = NULL;
2416     PACKET spkt;
2417
2418     if ((sk = sk_X509_new_null()) == NULL) {
2419         SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
2420         goto f_err;
2421     }
2422
2423     if (!PACKET_get_net_3(pkt, &llen)
2424             || !PACKET_get_sub_packet(pkt, &spkt, llen)
2425             || PACKET_remaining(pkt) != 0) {
2426         al = SSL_AD_DECODE_ERROR;
2427         SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
2428         goto f_err;
2429     }
2430
2431     while (PACKET_remaining(&spkt) > 0) {
2432         if (!PACKET_get_net_3(&spkt, &l)
2433                 || !PACKET_get_bytes(&spkt, &certbytes, l)) {
2434             al = SSL_AD_DECODE_ERROR;
2435             SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
2436                    SSL_R_CERT_LENGTH_MISMATCH);
2437             goto f_err;
2438         }
2439
2440         certstart = certbytes;
2441         x = d2i_X509(NULL, (const unsigned char **)&certbytes, l);
2442         if (x == NULL) {
2443             SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_ASN1_LIB);
2444             goto f_err;
2445         }
2446         if (certbytes != (certstart + l)) {
2447             al = SSL_AD_DECODE_ERROR;
2448             SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
2449                    SSL_R_CERT_LENGTH_MISMATCH);
2450             goto f_err;
2451         }
2452         if (!sk_X509_push(sk, x)) {
2453             SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
2454             goto f_err;
2455         }
2456         x = NULL;
2457     }
2458
2459     if (sk_X509_num(sk) <= 0) {
2460         /* TLS does not mind 0 certs returned */
2461         if (s->version == SSL3_VERSION) {
2462             al = SSL_AD_HANDSHAKE_FAILURE;
2463             SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
2464                    SSL_R_NO_CERTIFICATES_RETURNED);
2465             goto f_err;
2466         }
2467         /* Fail for TLS only if we required a certificate */
2468         else if ((s->verify_mode & SSL_VERIFY_PEER) &&
2469                  (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
2470             SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
2471                    SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2472             al = SSL_AD_HANDSHAKE_FAILURE;
2473             goto f_err;
2474         }
2475         /* No client certificate so digest cached records */
2476         if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s, 0)) {
2477             al = SSL_AD_INTERNAL_ERROR;
2478             goto f_err;
2479         }
2480     } else {
2481         EVP_PKEY *pkey;
2482         i = ssl_verify_cert_chain(s, sk);
2483         if (i <= 0) {
2484             al = ssl_verify_alarm_type(s->verify_result);
2485             SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
2486                    SSL_R_CERTIFICATE_VERIFY_FAILED);
2487             goto f_err;
2488         }
2489         if (i > 1) {
2490             SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, i);
2491             al = SSL_AD_HANDSHAKE_FAILURE;
2492             goto f_err;
2493         }
2494         pkey = X509_get_pubkey(sk_X509_value(sk, 0));
2495         if (pkey == NULL) {
2496             al = SSL3_AD_HANDSHAKE_FAILURE;
2497             SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
2498                    SSL_R_UNKNOWN_CERTIFICATE_TYPE);
2499             goto f_err;
2500         }
2501         EVP_PKEY_free(pkey);
2502     }
2503
2504     X509_free(s->session->peer);
2505     s->session->peer = sk_X509_shift(sk);
2506     s->session->verify_result = s->verify_result;
2507
2508     sk_X509_pop_free(s->session->peer_chain, X509_free);
2509     s->session->peer_chain = sk;
2510     /*
2511      * Inconsistency alert: cert_chain does *not* include the peer's own
2512      * certificate, while we do include it in s3_clnt.c
2513      */
2514     sk = NULL;
2515     ret = MSG_PROCESS_CONTINUE_READING;
2516     goto done;
2517
2518  f_err:
2519     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2520     statem_set_error(s);
2521  done:
2522     X509_free(x);
2523     sk_X509_pop_free(sk, X509_free);
2524     return ret;
2525 }
2526
2527 int tls_construct_server_certificate(SSL *s)
2528 {
2529     CERT_PKEY *cpk;
2530
2531     cpk = ssl_get_server_send_pkey(s);
2532     if (cpk == NULL) {
2533         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
2534         statem_set_error(s);
2535         return 0;
2536     }
2537
2538     if (!ssl3_output_cert_chain(s, cpk)) {
2539         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
2540         statem_set_error(s);
2541         return 0;
2542     }
2543
2544     return 1;
2545 }
2546
2547 int tls_construct_new_session_ticket(SSL *s)
2548 {
2549     unsigned char *senc = NULL;
2550     EVP_CIPHER_CTX ctx;
2551     HMAC_CTX hctx;
2552     unsigned char *p, *macstart;
2553     const unsigned char *const_p;
2554     int len, slen_full, slen;
2555     SSL_SESSION *sess;
2556     unsigned int hlen;
2557     SSL_CTX *tctx = s->initial_ctx;
2558     unsigned char iv[EVP_MAX_IV_LENGTH];
2559     unsigned char key_name[16];
2560
2561     /* get session encoding length */
2562     slen_full = i2d_SSL_SESSION(s->session, NULL);
2563     /*
2564      * Some length values are 16 bits, so forget it if session is too
2565      * long
2566      */
2567     if (slen_full == 0 || slen_full > 0xFF00) {
2568         statem_set_error(s);
2569         return 0;
2570     }
2571     senc = OPENSSL_malloc(slen_full);
2572     if (!senc) {
2573         statem_set_error(s);
2574         return 0;
2575     }
2576
2577     EVP_CIPHER_CTX_init(&ctx);
2578     HMAC_CTX_init(&hctx);
2579
2580     p = senc;
2581     if (!i2d_SSL_SESSION(s->session, &p))
2582         goto err;
2583
2584     /*
2585      * create a fresh copy (not shared with other threads) to clean up
2586      */
2587     const_p = senc;
2588     sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
2589     if (sess == NULL)
2590         goto err;
2591     sess->session_id_length = 0; /* ID is irrelevant for the ticket */
2592
2593     slen = i2d_SSL_SESSION(sess, NULL);
2594     if (slen == 0 || slen > slen_full) { /* shouldn't ever happen */
2595         SSL_SESSION_free(sess);
2596         goto err;
2597     }
2598     p = senc;
2599     if (!i2d_SSL_SESSION(sess, &p)) {
2600         SSL_SESSION_free(sess);
2601         goto err;
2602     }
2603     SSL_SESSION_free(sess);
2604
2605     /*-
2606      * Grow buffer if need be: the length calculation is as
2607      * follows handshake_header_length +
2608      * 4 (ticket lifetime hint) + 2 (ticket length) +
2609      * 16 (key name) + max_iv_len (iv length) +
2610      * session_length + max_enc_block_size (max encrypted session
2611      * length) + max_md_size (HMAC).
2612      */
2613     if (!BUF_MEM_grow(s->init_buf,
2614                       SSL_HM_HEADER_LENGTH(s) + 22 + EVP_MAX_IV_LENGTH +
2615                       EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE + slen))
2616         goto err;
2617
2618     p = ssl_handshake_start(s);
2619     /*
2620      * Initialize HMAC and cipher contexts. If callback present it does
2621      * all the work otherwise use generated values from parent ctx.
2622      */
2623     if (tctx->tlsext_ticket_key_cb) {
2624         if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
2625                                        &hctx, 1) < 0)
2626             goto err;
2627     } else {
2628         if (RAND_bytes(iv, 16) <= 0)
2629             goto err;
2630         if (!EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
2631                                 tctx->tlsext_tick_aes_key, iv))
2632             goto err;
2633         if (!HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
2634                           EVP_sha256(), NULL))
2635             goto err;
2636         memcpy(key_name, tctx->tlsext_tick_key_name, 16);
2637     }
2638
2639     /*
2640      * Ticket lifetime hint (advisory only): We leave this unspecified
2641      * for resumed session (for simplicity), and guess that tickets for
2642      * new sessions will live as long as their sessions.
2643      */
2644     l2n(s->hit ? 0 : s->session->timeout, p);
2645
2646     /* Skip ticket length for now */
2647     p += 2;
2648     /* Output key name */
2649     macstart = p;
2650     memcpy(p, key_name, 16);
2651     p += 16;
2652     /* output IV */
2653     memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
2654     p += EVP_CIPHER_CTX_iv_length(&ctx);
2655     /* Encrypt session data */
2656     if (!EVP_EncryptUpdate(&ctx, p, &len, senc, slen))
2657         goto err;
2658     p += len;
2659     if (!EVP_EncryptFinal(&ctx, p, &len))
2660         goto err;
2661     p += len;
2662
2663     if (!HMAC_Update(&hctx, macstart, p - macstart))
2664         goto err;
2665     if (!HMAC_Final(&hctx, p, &hlen))
2666         goto err;
2667
2668     EVP_CIPHER_CTX_cleanup(&ctx);
2669     HMAC_CTX_cleanup(&hctx);
2670
2671     p += hlen;
2672     /* Now write out lengths: p points to end of data written */
2673     /* Total length */
2674     len = p - ssl_handshake_start(s);
2675     /* Skip ticket lifetime hint */
2676     p = ssl_handshake_start(s) + 4;
2677     s2n(len - 6, p);
2678     if (!ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len))
2679         goto err;
2680     OPENSSL_free(senc);
2681
2682     return 1;
2683  err:
2684     OPENSSL_free(senc);
2685     EVP_CIPHER_CTX_cleanup(&ctx);
2686     HMAC_CTX_cleanup(&hctx);
2687     statem_set_error(s);
2688     return 0;
2689 }
2690
2691 int tls_construct_cert_status(SSL *s)
2692 {
2693     unsigned char *p;
2694     /*-
2695      * Grow buffer if need be: the length calculation is as
2696      * follows 1 (message type) + 3 (message length) +
2697      * 1 (ocsp response type) + 3 (ocsp response length)
2698      * + (ocsp response)
2699      */
2700     if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen)) {
2701         statem_set_error(s);
2702         return 0;
2703     }
2704
2705     p = (unsigned char *)s->init_buf->data;
2706
2707     /* do the header */
2708     *(p++) = SSL3_MT_CERTIFICATE_STATUS;
2709     /* message length */
2710     l2n3(s->tlsext_ocsp_resplen + 4, p);
2711     /* status type */
2712     *(p++) = s->tlsext_status_type;
2713     /* length of OCSP response */
2714     l2n3(s->tlsext_ocsp_resplen, p);
2715     /* actual response */
2716     memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
2717     /* number of bytes to write */
2718     s->init_num = 8 + s->tlsext_ocsp_resplen;
2719     s->init_off = 0;
2720
2721     return 1;
2722 }
2723
2724 #ifndef OPENSSL_NO_NEXTPROTONEG
2725 /*
2726  * tls_process_next_proto reads a Next Protocol Negotiation handshake message.
2727  * It sets the next_proto member in s if found
2728  */
2729 enum MSG_PROCESS_RETURN tls_process_next_proto(SSL *s, PACKET *pkt)
2730 {
2731     PACKET next_proto, padding;
2732     size_t next_proto_len;
2733
2734     /*-
2735      * The payload looks like:
2736      *   uint8 proto_len;
2737      *   uint8 proto[proto_len];
2738      *   uint8 padding_len;
2739      *   uint8 padding[padding_len];
2740      */
2741     if (!PACKET_get_length_prefixed_1(pkt, &next_proto)
2742         || !PACKET_get_length_prefixed_1(pkt, &padding)
2743         || PACKET_remaining(pkt) > 0) {
2744         SSLerr(SSL_F_TLS_PROCESS_NEXT_PROTO, SSL_R_LENGTH_MISMATCH);
2745         goto err;
2746     }
2747
2748     if (!PACKET_memdup(&next_proto, &s->next_proto_negotiated,
2749                        &next_proto_len)) {
2750         s->next_proto_negotiated_len = 0;
2751         goto err;
2752     }
2753
2754     s->next_proto_negotiated_len = (unsigned char)next_proto_len;
2755
2756     return MSG_PROCESS_CONTINUE_READING;
2757 err:
2758     statem_set_error(s);
2759     return MSG_PROCESS_ERROR;
2760 }
2761 #endif
2762
2763 #define SSLV2_CIPHER_LEN    3
2764
2765 STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list(SSL *s,
2766                                                PACKET *cipher_suites,
2767                                                STACK_OF(SSL_CIPHER) **skp,
2768                                                int sslv2format, int *al
2769                                                )
2770 {
2771     const SSL_CIPHER *c;
2772     STACK_OF(SSL_CIPHER) *sk;
2773     int n;
2774     /* 3 = SSLV2_CIPHER_LEN > TLS_CIPHER_LEN = 2. */
2775     unsigned char cipher[SSLV2_CIPHER_LEN];
2776
2777     s->s3->send_connection_binding = 0;
2778
2779     n = sslv2format ? SSLV2_CIPHER_LEN : TLS_CIPHER_LEN;
2780
2781     if (PACKET_remaining(cipher_suites) == 0) {
2782         SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, SSL_R_NO_CIPHERS_SPECIFIED);
2783         *al = SSL_AD_ILLEGAL_PARAMETER;
2784         return NULL;
2785     }
2786
2787     if (PACKET_remaining(cipher_suites) % n != 0) {
2788         SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
2789                SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
2790         *al = SSL_AD_DECODE_ERROR;
2791         return NULL;
2792     }
2793
2794     if ((skp == NULL) || (*skp == NULL)) {
2795         sk = sk_SSL_CIPHER_new_null(); /* change perhaps later */
2796         if(sk == NULL) {
2797             SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
2798             *al = SSL_AD_INTERNAL_ERROR;
2799             return NULL;
2800         }
2801     } else {
2802         sk = *skp;
2803         sk_SSL_CIPHER_zero(sk);
2804     }
2805
2806     if (!PACKET_memdup(cipher_suites, &s->s3->tmp.ciphers_raw,
2807                        &s->s3->tmp.ciphers_rawlen)) {
2808         *al = SSL_AD_INTERNAL_ERROR;
2809         goto err;
2810     }
2811
2812     while (PACKET_copy_bytes(cipher_suites, cipher, n)) {
2813         /*
2814          * SSLv3 ciphers wrapped in an SSLv2-compatible ClientHello have the
2815          * first byte set to zero, while true SSLv2 ciphers have a non-zero
2816          * first byte. We don't support any true SSLv2 ciphers, so skip them.
2817          */
2818         if (sslv2format && cipher[0] != '\0')
2819                 continue;
2820
2821         /* Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV */
2822         if ((cipher[n - 2] == ((SSL3_CK_SCSV >> 8) & 0xff)) &&
2823             (cipher[n - 1] == (SSL3_CK_SCSV & 0xff))) {
2824             /* SCSV fatal if renegotiating */
2825             if (s->renegotiate) {
2826                 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
2827                        SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING);
2828                 *al = SSL_AD_HANDSHAKE_FAILURE;
2829                 goto err;
2830             }
2831             s->s3->send_connection_binding = 1;
2832 #ifdef OPENSSL_RI_DEBUG
2833             fprintf(stderr, "SCSV received by server\n");
2834 #endif
2835             continue;
2836         }
2837
2838         /* Check for TLS_FALLBACK_SCSV */
2839         if ((cipher[n - 2] == ((SSL3_CK_FALLBACK_SCSV >> 8) & 0xff)) &&
2840             (cipher[n - 1] == (SSL3_CK_FALLBACK_SCSV & 0xff))) {
2841             /*
2842              * The SCSV indicates that the client previously tried a higher
2843              * version. Fail if the current version is an unexpected
2844              * downgrade.
2845              */
2846             if (!SSL_ctrl(s, SSL_CTRL_CHECK_PROTO_VERSION, 0, NULL)) {
2847                 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
2848                        SSL_R_INAPPROPRIATE_FALLBACK);
2849                 *al = SSL_AD_INAPPROPRIATE_FALLBACK;
2850                 goto err;
2851             }
2852             continue;
2853         }
2854
2855         /* For SSLv2-compat, ignore leading 0-byte. */
2856         c = ssl_get_cipher_by_char(s, sslv2format ? &cipher[1] : cipher);
2857         if (c != NULL) {
2858             if (!sk_SSL_CIPHER_push(sk, c)) {
2859                 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
2860                 *al = SSL_AD_INTERNAL_ERROR;
2861                 goto err;
2862             }
2863         }
2864     }
2865     if (PACKET_remaining(cipher_suites) > 0) {
2866         *al = SSL_AD_INTERNAL_ERROR;
2867         SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_INTERNAL_ERROR);
2868         goto err;
2869     }
2870
2871     if (skp != NULL)
2872         *skp = sk;
2873     return (sk);
2874  err:
2875     if ((skp == NULL) || (*skp == NULL))
2876         sk_SSL_CIPHER_free(sk);
2877     return NULL;
2878 }