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