Move declaration of i into blocks where it is used.
[openssl.git] / ssl / statem / statem_clnt.c
1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57 /* ====================================================================
58  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
59  *
60  * Redistribution and use in source and binary forms, with or without
61  * modification, are permitted provided that the following conditions
62  * are met:
63  *
64  * 1. Redistributions of source code must retain the above copyright
65  *    notice, this list of conditions and the following disclaimer.
66  *
67  * 2. Redistributions in binary form must reproduce the above copyright
68  *    notice, this list of conditions and the following disclaimer in
69  *    the documentation and/or other materials provided with the
70  *    distribution.
71  *
72  * 3. All advertising materials mentioning features or use of this
73  *    software must display the following acknowledgment:
74  *    "This product includes software developed by the OpenSSL Project
75  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76  *
77  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78  *    endorse or promote products derived from this software without
79  *    prior written permission. For written permission, please contact
80  *    openssl-core@openssl.org.
81  *
82  * 5. Products derived from this software may not be called "OpenSSL"
83  *    nor may "OpenSSL" appear in their names without prior written
84  *    permission of the OpenSSL Project.
85  *
86  * 6. Redistributions of any form whatsoever must retain the following
87  *    acknowledgment:
88  *    "This product includes software developed by the OpenSSL Project
89  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90  *
91  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
95  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102  * OF THE POSSIBILITY OF SUCH DAMAGE.
103  * ====================================================================
104  *
105  * This product includes cryptographic software written by Eric Young
106  * (eay@cryptsoft.com).  This product includes software written by Tim
107  * Hudson (tjh@cryptsoft.com).
108  *
109  */
110 /* ====================================================================
111  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
112  *
113  * Portions of the attached software ("Contribution") are developed by
114  * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
115  *
116  * The Contribution is licensed pursuant to the OpenSSL open source
117  * license provided above.
118  *
119  * ECC cipher suite support in OpenSSL originally written by
120  * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
121  *
122  */
123 /* ====================================================================
124  * Copyright 2005 Nokia. All rights reserved.
125  *
126  * The portions of the attached software ("Contribution") is developed by
127  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
128  * license.
129  *
130  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
131  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
132  * support (see RFC 4279) to OpenSSL.
133  *
134  * No patent licenses or other rights except those expressly stated in
135  * the OpenSSL open source license shall be deemed granted or received
136  * expressly, by implication, estoppel, or otherwise.
137  *
138  * No assurances are provided by Nokia that the Contribution does not
139  * infringe the patent or other intellectual property rights of any third
140  * party or that the license provides you with all the necessary rights
141  * to make use of the Contribution.
142  *
143  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
144  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
145  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
146  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
147  * OTHERWISE.
148  */
149
150 #include <stdio.h>
151 #include "../ssl_locl.h"
152 #include "statem_locl.h"
153 #include <openssl/buffer.h>
154 #include <openssl/rand.h>
155 #include <openssl/objects.h>
156 #include <openssl/evp.h>
157 #include <openssl/md5.h>
158 #include <openssl/dh.h>
159 #include <openssl/bn.h>
160 #include <openssl/engine.h>
161
162 static ossl_inline int cert_req_allowed(SSL *s);
163 static int key_exchange_expected(SSL *s);
164 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b);
165 static int ssl_cipher_list_to_bytes(SSL *s, STACK_OF(SSL_CIPHER) *sk,
166                                     unsigned char *p);
167
168
169 /*
170  * Is a CertificateRequest message allowed at the moment or not?
171  *
172  *  Return values are:
173  *  1: Yes
174  *  0: No
175  */
176 static ossl_inline int cert_req_allowed(SSL *s)
177 {
178     /* TLS does not like anon-DH with client cert */
179     if ((s->version > SSL3_VERSION
180                 && (s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL))
181             || (s->s3->tmp.new_cipher->algorithm_auth & (SSL_aSRP | SSL_aPSK)))
182         return 0;
183
184     return 1;
185 }
186
187 /*
188  * Should we expect the ServerKeyExchange message or not?
189  *
190  *  Return values are:
191  *  1: Yes
192  *  0: No
193  * -1: Error
194  */
195 static int key_exchange_expected(SSL *s)
196 {
197     long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
198
199     /*
200      * Can't skip server key exchange if this is an ephemeral
201      * ciphersuite or for SRP
202      */
203     if (alg_k & (SSL_kDHE | SSL_kECDHE | SSL_kDHEPSK | SSL_kECDHEPSK
204                  | SSL_kSRP)) {
205         return 1;
206     }
207
208     return 0;
209 }
210
211 /*
212  * ossl_statem_client_read_transition() encapsulates the logic for the allowed
213  * handshake state transitions when the client is reading messages from the
214  * server. The message type that the server has sent is provided in |mt|. The
215  * current state is in |s->statem.hand_state|.
216  *
217  *  Return values are:
218  *  1: Success (transition allowed)
219  *  0: Error (transition not allowed)
220  */
221 int ossl_statem_client_read_transition(SSL *s, int mt)
222 {
223     OSSL_STATEM *st = &s->statem;
224     int ske_expected;
225
226     switch(st->hand_state) {
227     case TLS_ST_CW_CLNT_HELLO:
228         if (mt == SSL3_MT_SERVER_HELLO) {
229             st->hand_state = TLS_ST_CR_SRVR_HELLO;
230             return 1;
231         }
232
233         if (SSL_IS_DTLS(s)) {
234             if (mt == DTLS1_MT_HELLO_VERIFY_REQUEST) {
235                 st->hand_state = DTLS_ST_CR_HELLO_VERIFY_REQUEST;
236                 return 1;
237             }
238         }
239         break;
240
241     case TLS_ST_CR_SRVR_HELLO:
242         if (s->hit) {
243             if (s->tlsext_ticket_expected) {
244                 if (mt == SSL3_MT_NEWSESSION_TICKET) {
245                     st->hand_state = TLS_ST_CR_SESSION_TICKET;
246                     return 1;
247                 }
248             } else if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
249                 st->hand_state = TLS_ST_CR_CHANGE;
250                 return 1;
251             }
252         } else {
253             if (SSL_IS_DTLS(s) && mt == DTLS1_MT_HELLO_VERIFY_REQUEST) {
254                 st->hand_state = DTLS_ST_CR_HELLO_VERIFY_REQUEST;
255                 return 1;
256             } else if (s->version >= TLS1_VERSION
257                     && s->tls_session_secret_cb != NULL
258                     && s->session->tlsext_tick != NULL
259                     && mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
260                 /*
261                  * Normally, we can tell if the server is resuming the session
262                  * from the session ID. EAP-FAST (RFC 4851), however, relies on
263                  * the next server message after the ServerHello to determine if
264                  * the server is resuming.
265                  */
266                 s->hit = 1;
267                 st->hand_state = TLS_ST_CR_CHANGE;
268                 return 1;
269             } else if (!(s->s3->tmp.new_cipher->algorithm_auth
270                         & (SSL_aNULL | SSL_aSRP | SSL_aPSK))) {
271                 if (mt == SSL3_MT_CERTIFICATE) {
272                     st->hand_state = TLS_ST_CR_CERT;
273                     return 1;
274                 }
275             } else {
276                 ske_expected = key_exchange_expected(s);
277                 if (ske_expected < 0)
278                     return 0;
279                 /* SKE is optional for some PSK ciphersuites */
280                 if (ske_expected
281                         || ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_PSK)
282                             && mt == SSL3_MT_SERVER_KEY_EXCHANGE)) {
283                     if (mt == SSL3_MT_SERVER_KEY_EXCHANGE) {
284                         st->hand_state = TLS_ST_CR_KEY_EXCH;
285                         return 1;
286                     }
287                 } else if (mt == SSL3_MT_CERTIFICATE_REQUEST
288                             && cert_req_allowed(s)) {
289                         st->hand_state = TLS_ST_CR_CERT_REQ;
290                         return 1;
291                 } else if (mt == SSL3_MT_SERVER_DONE) {
292                         st->hand_state = TLS_ST_CR_SRVR_DONE;
293                         return 1;
294                 }
295             }
296         }
297         break;
298
299     case TLS_ST_CR_CERT:
300         /*
301          * The CertificateStatus message is optional even if
302          * |tlsext_status_expected| is set
303          */
304         if (s->tlsext_status_expected && mt == SSL3_MT_CERTIFICATE_STATUS) {
305             st->hand_state = TLS_ST_CR_CERT_STATUS;
306             return 1;
307         }
308         /* Fall through */
309
310     case TLS_ST_CR_CERT_STATUS:
311         ske_expected = key_exchange_expected(s);
312         if (ske_expected < 0)
313             return 0;
314         /* SKE is optional for some PSK ciphersuites */
315         if (ske_expected
316                 || ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_PSK)
317                     && mt == SSL3_MT_SERVER_KEY_EXCHANGE)) {
318             if (mt == SSL3_MT_SERVER_KEY_EXCHANGE) {
319                 st->hand_state = TLS_ST_CR_KEY_EXCH;
320                 return 1;
321             }
322             return 0;
323         }
324         /* Fall through */
325
326     case TLS_ST_CR_KEY_EXCH:
327         if (mt == SSL3_MT_CERTIFICATE_REQUEST) {
328             if (cert_req_allowed(s)) {
329                 st->hand_state = TLS_ST_CR_CERT_REQ;
330                 return 1;
331             }
332             return 0;
333         }
334         /* Fall through */
335
336     case TLS_ST_CR_CERT_REQ:
337         if (mt == SSL3_MT_SERVER_DONE) {
338             st->hand_state = TLS_ST_CR_SRVR_DONE;
339             return 1;
340         }
341         break;
342
343     case TLS_ST_CW_FINISHED:
344         if (mt == SSL3_MT_NEWSESSION_TICKET && s->tlsext_ticket_expected) {
345             st->hand_state = TLS_ST_CR_SESSION_TICKET;
346             return 1;
347         } else if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
348             st->hand_state = TLS_ST_CR_CHANGE;
349             return 1;
350         }
351         break;
352
353     case TLS_ST_CR_SESSION_TICKET:
354         if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
355             st->hand_state = TLS_ST_CR_CHANGE;
356             return 1;
357         }
358         break;
359
360     case TLS_ST_CR_CHANGE:
361         if (mt == SSL3_MT_FINISHED) {
362             st->hand_state = TLS_ST_CR_FINISHED;
363             return 1;
364         }
365         break;
366
367     default:
368         break;
369     }
370
371     /* No valid transition found */
372     return 0;
373 }
374
375 /*
376  * client_write_transition() works out what handshake state to move to next
377  * when the client is writing messages to be sent to the server.
378  */
379 WRITE_TRAN ossl_statem_client_write_transition(SSL *s)
380 {
381     OSSL_STATEM *st = &s->statem;
382
383     switch(st->hand_state) {
384         case TLS_ST_OK:
385             /* Renegotiation - fall through */
386         case TLS_ST_BEFORE:
387             st->hand_state = TLS_ST_CW_CLNT_HELLO;
388             return WRITE_TRAN_CONTINUE;
389
390         case TLS_ST_CW_CLNT_HELLO:
391             /*
392              * No transition at the end of writing because we don't know what
393              * we will be sent
394              */
395             return WRITE_TRAN_FINISHED;
396
397         case DTLS_ST_CR_HELLO_VERIFY_REQUEST:
398             st->hand_state = TLS_ST_CW_CLNT_HELLO;
399             return WRITE_TRAN_CONTINUE;
400
401         case TLS_ST_CR_SRVR_DONE:
402             if (s->s3->tmp.cert_req)
403                 st->hand_state = TLS_ST_CW_CERT;
404             else
405                 st->hand_state = TLS_ST_CW_KEY_EXCH;
406             return WRITE_TRAN_CONTINUE;
407
408         case TLS_ST_CW_CERT:
409             st->hand_state = TLS_ST_CW_KEY_EXCH;
410             return WRITE_TRAN_CONTINUE;
411
412         case TLS_ST_CW_KEY_EXCH:
413             /*
414              * For TLS, cert_req is set to 2, so a cert chain of nothing is
415              * sent, but no verify packet is sent
416              */
417             /*
418              * XXX: For now, we do not support client authentication in ECDH
419              * cipher suites with ECDH (rather than ECDSA) certificates. We
420              * need to skip the certificate verify message when client's
421              * ECDH public key is sent inside the client certificate.
422              */
423             if (s->s3->tmp.cert_req == 1) {
424                 st->hand_state = TLS_ST_CW_CERT_VRFY;
425             } else {
426                 st->hand_state = TLS_ST_CW_CHANGE;
427             }
428             if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY) {
429                 st->hand_state = TLS_ST_CW_CHANGE;
430             }
431             return WRITE_TRAN_CONTINUE;
432
433         case TLS_ST_CW_CERT_VRFY:
434             st->hand_state = TLS_ST_CW_CHANGE;
435             return WRITE_TRAN_CONTINUE;
436
437         case TLS_ST_CW_CHANGE:
438 #if defined(OPENSSL_NO_NEXTPROTONEG)
439             st->hand_state = TLS_ST_CW_FINISHED;
440 #else
441             if (!SSL_IS_DTLS(s) && s->s3->next_proto_neg_seen)
442                 st->hand_state = TLS_ST_CW_NEXT_PROTO;
443             else
444                 st->hand_state = TLS_ST_CW_FINISHED;
445 #endif
446             return WRITE_TRAN_CONTINUE;
447
448 #if !defined(OPENSSL_NO_NEXTPROTONEG)
449         case TLS_ST_CW_NEXT_PROTO:
450             st->hand_state = TLS_ST_CW_FINISHED;
451             return WRITE_TRAN_CONTINUE;
452 #endif
453
454         case TLS_ST_CW_FINISHED:
455             if (s->hit) {
456                 st->hand_state = TLS_ST_OK;
457                 ossl_statem_set_in_init(s, 0);
458                 return WRITE_TRAN_CONTINUE;
459             } else {
460                 return WRITE_TRAN_FINISHED;
461             }
462
463         case TLS_ST_CR_FINISHED:
464             if (s->hit) {
465                 st->hand_state = TLS_ST_CW_CHANGE;
466                 return WRITE_TRAN_CONTINUE;
467             } else {
468                 st->hand_state = TLS_ST_OK;
469                 ossl_statem_set_in_init(s, 0);
470                 return WRITE_TRAN_CONTINUE;
471             }
472
473         default:
474             /* Shouldn't happen */
475             return WRITE_TRAN_ERROR;
476     }
477 }
478
479 /*
480  * Perform any pre work that needs to be done prior to sending a message from
481  * the client to the server.
482  */
483 WORK_STATE ossl_statem_client_pre_work(SSL *s, WORK_STATE wst)
484 {
485     OSSL_STATEM *st = &s->statem;
486
487     switch(st->hand_state) {
488     case TLS_ST_CW_CLNT_HELLO:
489         s->shutdown = 0;
490         if (SSL_IS_DTLS(s)) {
491             /* every DTLS ClientHello resets Finished MAC */
492             ssl3_init_finished_mac(s);
493         }
494         break;
495
496     case TLS_ST_CW_CERT:
497         return tls_prepare_client_certificate(s, wst);
498
499     case TLS_ST_CW_CHANGE:
500         if (SSL_IS_DTLS(s)) {
501             if (s->hit) {
502                 /*
503                  * We're into the last flight so we don't retransmit these
504                  * messages unless we need to.
505                  */
506                 st->use_timer = 0;
507             }
508 #ifndef OPENSSL_NO_SCTP
509             if (BIO_dgram_is_sctp(SSL_get_wbio(s)))
510                 return dtls_wait_for_dry(s);
511 #endif
512         }
513         return WORK_FINISHED_CONTINUE;
514
515     case TLS_ST_OK:
516         return tls_finish_handshake(s, wst);
517
518     default:
519         /* No pre work to be done */
520         break;
521     }
522
523     return WORK_FINISHED_CONTINUE;
524 }
525
526 /*
527  * Perform any work that needs to be done after sending a message from the
528  * client to the server.
529  */
530 WORK_STATE ossl_statem_client_post_work(SSL *s, WORK_STATE wst)
531 {
532     OSSL_STATEM *st = &s->statem;
533
534     s->init_num = 0;
535
536     switch(st->hand_state) {
537     case TLS_ST_CW_CLNT_HELLO:
538         if (SSL_IS_DTLS(s) && s->d1->cookie_len > 0 && statem_flush(s) != 1)
539             return WORK_MORE_A;
540 #ifndef OPENSSL_NO_SCTP
541         /* Disable buffering for SCTP */
542         if (!SSL_IS_DTLS(s) || !BIO_dgram_is_sctp(SSL_get_wbio(s))) {
543 #endif
544             /*
545              * turn on buffering for the next lot of output
546              */
547             if (s->bbio != s->wbio)
548                 s->wbio = BIO_push(s->bbio, s->wbio);
549 #ifndef OPENSSL_NO_SCTP
550             }
551 #endif
552         if (SSL_IS_DTLS(s)) {
553             /* Treat the next message as the first packet */
554             s->first_packet = 1;
555         }
556         break;
557
558     case TLS_ST_CW_KEY_EXCH:
559         if (tls_client_key_exchange_post_work(s) == 0)
560             return WORK_ERROR;
561         break;
562
563     case TLS_ST_CW_CHANGE:
564         s->session->cipher = s->s3->tmp.new_cipher;
565 #ifdef OPENSSL_NO_COMP
566         s->session->compress_meth = 0;
567 #else
568         if (s->s3->tmp.new_compression == NULL)
569             s->session->compress_meth = 0;
570         else
571             s->session->compress_meth = s->s3->tmp.new_compression->id;
572 #endif
573         if (!s->method->ssl3_enc->setup_key_block(s))
574             return WORK_ERROR;
575
576         if (!s->method->ssl3_enc->change_cipher_state(s,
577                                                       SSL3_CHANGE_CIPHER_CLIENT_WRITE))
578             return WORK_ERROR;
579
580         if (SSL_IS_DTLS(s)) {
581 #ifndef OPENSSL_NO_SCTP
582             if (s->hit) {
583                 /*
584                  * Change to new shared key of SCTP-Auth, will be ignored if
585                  * no SCTP used.
586                  */
587                 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
588                          0, NULL);
589             }
590 #endif
591
592             dtls1_reset_seq_numbers(s, SSL3_CC_WRITE);
593         }
594         break;
595
596     case TLS_ST_CW_FINISHED:
597 #ifndef OPENSSL_NO_SCTP
598         if (wst == WORK_MORE_A && SSL_IS_DTLS(s) && s->hit == 0) {
599             /*
600              * Change to new shared key of SCTP-Auth, will be ignored if
601              * no SCTP used.
602              */
603             BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
604                      0, NULL);
605         }
606 #endif
607         if (statem_flush(s) != 1)
608             return WORK_MORE_B;
609         break;
610
611     default:
612         /* No post work to be done */
613         break;
614     }
615
616     return WORK_FINISHED_CONTINUE;
617 }
618
619 /*
620  * Construct a message to be sent from the client to the server.
621  *
622  * Valid return values are:
623  *   1: Success
624  *   0: Error
625  */
626 int ossl_statem_client_construct_message(SSL *s)
627 {
628     OSSL_STATEM *st = &s->statem;
629
630     switch(st->hand_state) {
631     case TLS_ST_CW_CLNT_HELLO:
632         return tls_construct_client_hello(s);
633
634     case TLS_ST_CW_CERT:
635         return tls_construct_client_certificate(s);
636
637     case TLS_ST_CW_KEY_EXCH:
638         return tls_construct_client_key_exchange(s);
639
640     case TLS_ST_CW_CERT_VRFY:
641         return tls_construct_client_verify(s);
642
643     case TLS_ST_CW_CHANGE:
644         if (SSL_IS_DTLS(s))
645             return dtls_construct_change_cipher_spec(s);
646         else
647             return tls_construct_change_cipher_spec(s);
648
649 #if !defined(OPENSSL_NO_NEXTPROTONEG)
650     case TLS_ST_CW_NEXT_PROTO:
651         return tls_construct_next_proto(s);
652 #endif
653     case TLS_ST_CW_FINISHED:
654         return tls_construct_finished(s,
655                                       s->method->
656                                       ssl3_enc->client_finished_label,
657                                       s->method->
658                                       ssl3_enc->client_finished_label_len);
659
660     default:
661         /* Shouldn't happen */
662         break;
663     }
664
665     return 0;
666 }
667
668 /*
669  * Returns the maximum allowed length for the current message that we are
670  * reading. Excludes the message header.
671  */
672 unsigned long ossl_statem_client_max_message_size(SSL *s)
673 {
674     OSSL_STATEM *st = &s->statem;
675
676     switch(st->hand_state) {
677         case TLS_ST_CR_SRVR_HELLO:
678             return SERVER_HELLO_MAX_LENGTH;
679
680         case DTLS_ST_CR_HELLO_VERIFY_REQUEST:
681             return HELLO_VERIFY_REQUEST_MAX_LENGTH;
682
683         case TLS_ST_CR_CERT:
684             return s->max_cert_list;
685
686         case TLS_ST_CR_CERT_STATUS:
687             return SSL3_RT_MAX_PLAIN_LENGTH;
688
689         case TLS_ST_CR_KEY_EXCH:
690             return SERVER_KEY_EXCH_MAX_LENGTH;
691
692         case TLS_ST_CR_CERT_REQ:
693             /* Set to s->max_cert_list for compatibility with previous releases.
694              * In practice these messages can get quite long if servers are
695              * configured to provide a long list of acceptable CAs
696              */
697             return s->max_cert_list;
698
699         case TLS_ST_CR_SRVR_DONE:
700             return SERVER_HELLO_DONE_MAX_LENGTH;
701
702         case TLS_ST_CR_CHANGE:
703             return CCS_MAX_LENGTH;
704
705         case TLS_ST_CR_SESSION_TICKET:
706             return SSL3_RT_MAX_PLAIN_LENGTH;
707
708         case TLS_ST_CR_FINISHED:
709             return FINISHED_MAX_LENGTH;
710
711         default:
712             /* Shouldn't happen */
713             break;
714     }
715
716     return 0;
717 }
718
719 /*
720  * Process a message that the client has been received from the server.
721  */
722 MSG_PROCESS_RETURN ossl_statem_client_process_message(SSL *s, PACKET *pkt)
723 {
724     OSSL_STATEM *st = &s->statem;
725
726     switch(st->hand_state) {
727         case TLS_ST_CR_SRVR_HELLO:
728             return tls_process_server_hello(s, pkt);
729
730         case DTLS_ST_CR_HELLO_VERIFY_REQUEST:
731             return dtls_process_hello_verify(s, pkt);
732
733         case TLS_ST_CR_CERT:
734             return tls_process_server_certificate(s, pkt);
735
736         case TLS_ST_CR_CERT_STATUS:
737             return tls_process_cert_status(s, pkt);
738
739         case TLS_ST_CR_KEY_EXCH:
740             return tls_process_key_exchange(s, pkt);
741
742         case TLS_ST_CR_CERT_REQ:
743             return tls_process_certificate_request(s, pkt);
744
745         case TLS_ST_CR_SRVR_DONE:
746             return tls_process_server_done(s, pkt);
747
748         case TLS_ST_CR_CHANGE:
749             return tls_process_change_cipher_spec(s, pkt);
750
751         case TLS_ST_CR_SESSION_TICKET:
752             return tls_process_new_session_ticket(s, pkt);
753
754         case TLS_ST_CR_FINISHED:
755             return tls_process_finished(s, pkt);
756
757         default:
758             /* Shouldn't happen */
759             break;
760     }
761
762     return MSG_PROCESS_ERROR;
763 }
764
765 /*
766  * Perform any further processing required following the receipt of a message
767  * from the server
768  */
769 WORK_STATE ossl_statem_client_post_process_message(SSL *s, WORK_STATE wst)
770 {
771     OSSL_STATEM *st = &s->statem;
772
773     switch(st->hand_state) {
774 #ifndef OPENSSL_NO_SCTP
775     case TLS_ST_CR_SRVR_DONE:
776         /* We only get here if we are using SCTP and we are renegotiating */
777         if (BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
778             s->s3->in_read_app_data = 2;
779             s->rwstate = SSL_READING;
780             BIO_clear_retry_flags(SSL_get_rbio(s));
781             BIO_set_retry_read(SSL_get_rbio(s));
782             ossl_statem_set_sctp_read_sock(s, 1);
783             return WORK_MORE_A;
784         }
785         ossl_statem_set_sctp_read_sock(s, 0);
786         return WORK_FINISHED_STOP;
787 #endif
788
789     default:
790         break;
791     }
792
793     /* Shouldn't happen */
794     return WORK_ERROR;
795 }
796
797 int tls_construct_client_hello(SSL *s)
798 {
799     unsigned char *buf;
800     unsigned char *p, *d;
801     int i;
802     int protverr;
803     unsigned long l;
804     int al = 0;
805 #ifndef OPENSSL_NO_COMP
806     int j;
807     SSL_COMP *comp;
808 #endif
809     SSL_SESSION *sess = s->session;
810
811     buf = (unsigned char *)s->init_buf->data;
812
813     /* Work out what SSL/TLS/DTLS version to use */
814     protverr = ssl_set_client_hello_version(s);
815     if (protverr != 0) {
816         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, protverr);
817         goto err;
818     }
819
820     if ((sess == NULL) || (sess->ssl_version != s->version) ||
821         /*
822          * In the case of EAP-FAST, we can have a pre-shared
823          * "ticket" without a session ID.
824          */
825         (!sess->session_id_length && !sess->tlsext_tick) ||
826         (sess->not_resumable)) {
827         if (!ssl_get_new_session(s, 0))
828             goto err;
829     }
830     /* else use the pre-loaded session */
831
832     p = s->s3->client_random;
833
834     /*
835      * for DTLS if client_random is initialized, reuse it, we are
836      * required to use same upon reply to HelloVerify
837      */
838     if (SSL_IS_DTLS(s)) {
839         size_t idx;
840         i = 1;
841         for (idx = 0; idx < sizeof(s->s3->client_random); idx++) {
842             if (p[idx]) {
843                 i = 0;
844                 break;
845             }
846         }
847     } else
848         i = 1;
849
850     if (i && ssl_fill_hello_random(s, 0, p,
851                                    sizeof(s->s3->client_random)) <= 0)
852         goto err;
853
854     /* Do the message type and length last */
855     d = p = ssl_handshake_start(s);
856
857     /*-
858      * version indicates the negotiated version: for example from
859      * an SSLv2/v3 compatible client hello). The client_version
860      * field is the maximum version we permit and it is also
861      * used in RSA encrypted premaster secrets. Some servers can
862      * choke if we initially report a higher version then
863      * renegotiate to a lower one in the premaster secret. This
864      * didn't happen with TLS 1.0 as most servers supported it
865      * but it can with TLS 1.1 or later if the server only supports
866      * 1.0.
867      *
868      * Possible scenario with previous logic:
869      *      1. Client hello indicates TLS 1.2
870      *      2. Server hello says TLS 1.0
871      *      3. RSA encrypted premaster secret uses 1.2.
872      *      4. Handhaked proceeds using TLS 1.0.
873      *      5. Server sends hello request to renegotiate.
874      *      6. Client hello indicates TLS v1.0 as we now
875      *         know that is maximum server supports.
876      *      7. Server chokes on RSA encrypted premaster secret
877      *         containing version 1.0.
878      *
879      * For interoperability it should be OK to always use the
880      * maximum version we support in client hello and then rely
881      * on the checking of version to ensure the servers isn't
882      * being inconsistent: for example initially negotiating with
883      * TLS 1.0 and renegotiating with TLS 1.2. We do this by using
884      * client_version in client hello and not resetting it to
885      * the negotiated version.
886      */
887     *(p++) = s->client_version >> 8;
888     *(p++) = s->client_version & 0xff;
889
890     /* Random stuff */
891     memcpy(p, s->s3->client_random, SSL3_RANDOM_SIZE);
892     p += SSL3_RANDOM_SIZE;
893
894     /* Session ID */
895     if (s->new_session)
896         i = 0;
897     else
898         i = s->session->session_id_length;
899     *(p++) = i;
900     if (i != 0) {
901         if (i > (int)sizeof(s->session->session_id)) {
902             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
903             goto err;
904         }
905         memcpy(p, s->session->session_id, i);
906         p += i;
907     }
908
909     /* cookie stuff for DTLS */
910     if (SSL_IS_DTLS(s)) {
911         if (s->d1->cookie_len > sizeof(s->d1->cookie)) {
912             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
913             goto err;
914         }
915         *(p++) = s->d1->cookie_len;
916         memcpy(p, s->d1->cookie, s->d1->cookie_len);
917         p += s->d1->cookie_len;
918     }
919
920     /* Ciphers supported */
921     i = ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s), &(p[2]));
922     if (i == 0) {
923         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, SSL_R_NO_CIPHERS_AVAILABLE);
924         goto err;
925     }
926 #ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH
927     /*
928      * Some servers hang if client hello > 256 bytes as hack workaround
929      * chop number of supported ciphers to keep it well below this if we
930      * use TLS v1.2
931      */
932     if (TLS1_get_version(s) >= TLS1_2_VERSION
933         && i > OPENSSL_MAX_TLS1_2_CIPHER_LENGTH)
934         i = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1;
935 #endif
936     s2n(i, p);
937     p += i;
938
939     /* COMPRESSION */
940 #ifdef OPENSSL_NO_COMP
941     *(p++) = 1;
942 #else
943
944     if (!ssl_allow_compression(s) || !s->ctx->comp_methods)
945         j = 0;
946     else
947         j = sk_SSL_COMP_num(s->ctx->comp_methods);
948     *(p++) = 1 + j;
949     for (i = 0; i < j; i++) {
950         comp = sk_SSL_COMP_value(s->ctx->comp_methods, i);
951         *(p++) = comp->id;
952     }
953 #endif
954     *(p++) = 0;             /* Add the NULL method */
955
956     /* TLS extensions */
957     if (ssl_prepare_clienthello_tlsext(s) <= 0) {
958         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
959         goto err;
960     }
961     if ((p =
962          ssl_add_clienthello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,
963                                     &al)) == NULL) {
964         ssl3_send_alert(s, SSL3_AL_FATAL, al);
965         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
966         goto err;
967     }
968
969     l = p - d;
970     if (!ssl_set_handshake_header(s, SSL3_MT_CLIENT_HELLO, l)) {
971         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
972         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
973         goto err;
974     }
975
976     return 1;
977  err:
978     ossl_statem_set_error(s);
979     return 0;
980 }
981
982 MSG_PROCESS_RETURN dtls_process_hello_verify(SSL *s, PACKET *pkt)
983 {
984     int al;
985     unsigned int cookie_len;
986     PACKET cookiepkt;
987
988     if (!PACKET_forward(pkt, 2)
989             || !PACKET_get_length_prefixed_1(pkt, &cookiepkt)) {
990         al = SSL_AD_DECODE_ERROR;
991         SSLerr(SSL_F_DTLS_PROCESS_HELLO_VERIFY, SSL_R_LENGTH_MISMATCH);
992         goto f_err;
993     }
994
995     cookie_len = PACKET_remaining(&cookiepkt);
996     if (cookie_len > sizeof(s->d1->cookie)) {
997         al = SSL_AD_ILLEGAL_PARAMETER;
998         SSLerr(SSL_F_DTLS_PROCESS_HELLO_VERIFY, SSL_R_LENGTH_TOO_LONG);
999         goto f_err;
1000     }
1001
1002     if (!PACKET_copy_bytes(&cookiepkt, s->d1->cookie, cookie_len)) {
1003         al = SSL_AD_DECODE_ERROR;
1004         SSLerr(SSL_F_DTLS_PROCESS_HELLO_VERIFY, SSL_R_LENGTH_MISMATCH);
1005         goto f_err;
1006     }
1007     s->d1->cookie_len = cookie_len;
1008
1009     return MSG_PROCESS_FINISHED_READING;
1010  f_err:
1011     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1012     ossl_statem_set_error(s);
1013     return MSG_PROCESS_ERROR;
1014 }
1015
1016 MSG_PROCESS_RETURN tls_process_server_hello(SSL *s, PACKET *pkt)
1017 {
1018     STACK_OF(SSL_CIPHER) *sk;
1019     const SSL_CIPHER *c;
1020     PACKET session_id;
1021     size_t session_id_len;
1022     const unsigned char *cipherchars;
1023     int i, al = SSL_AD_INTERNAL_ERROR;
1024     unsigned int compression;
1025     unsigned int sversion;
1026     int protverr;
1027 #ifndef OPENSSL_NO_COMP
1028     SSL_COMP *comp;
1029 #endif
1030
1031     if (!PACKET_get_net_2(pkt, &sversion)) {
1032         al = SSL_AD_DECODE_ERROR;
1033         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
1034         goto f_err;
1035     }
1036
1037     protverr = ssl_choose_client_version(s, sversion);
1038     if (protverr != 0) {
1039         al = SSL_AD_PROTOCOL_VERSION;
1040         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, protverr);
1041         goto f_err;
1042     }
1043
1044     /* load the server hello data */
1045     /* load the server random */
1046     if (!PACKET_copy_bytes(pkt, s->s3->server_random, SSL3_RANDOM_SIZE)) {
1047         al = SSL_AD_DECODE_ERROR;
1048         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
1049         goto f_err;
1050     }
1051
1052     s->hit = 0;
1053
1054     /* Get the session-id. */
1055     if (!PACKET_get_length_prefixed_1(pkt, &session_id)) {
1056         al = SSL_AD_DECODE_ERROR;
1057         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
1058         goto f_err;
1059     }
1060     session_id_len = PACKET_remaining(&session_id);
1061     if (session_id_len > sizeof s->session->session_id
1062         || session_id_len > SSL3_SESSION_ID_SIZE) {
1063         al = SSL_AD_ILLEGAL_PARAMETER;
1064         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_SSL3_SESSION_ID_TOO_LONG);
1065         goto f_err;
1066     }
1067
1068     if (!PACKET_get_bytes(pkt, &cipherchars, TLS_CIPHER_LEN)) {
1069         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
1070         al = SSL_AD_DECODE_ERROR;
1071         goto f_err;
1072     }
1073
1074     /*
1075      * Check if we can resume the session based on external pre-shared secret.
1076      * EAP-FAST (RFC 4851) supports two types of session resumption.
1077      * Resumption based on server-side state works with session IDs.
1078      * Resumption based on pre-shared Protected Access Credentials (PACs)
1079      * works by overriding the SessionTicket extension at the application
1080      * layer, and does not send a session ID. (We do not know whether EAP-FAST
1081      * servers would honour the session ID.) Therefore, the session ID alone
1082      * is not a reliable indicator of session resumption, so we first check if
1083      * we can resume, and later peek at the next handshake message to see if the
1084      * server wants to resume.
1085      */
1086     if (s->version >= TLS1_VERSION && s->tls_session_secret_cb &&
1087         s->session->tlsext_tick) {
1088         const SSL_CIPHER *pref_cipher = NULL;
1089         s->session->master_key_length = sizeof(s->session->master_key);
1090         if (s->tls_session_secret_cb(s, s->session->master_key,
1091                                      &s->session->master_key_length,
1092                                      NULL, &pref_cipher,
1093                                      s->tls_session_secret_cb_arg)) {
1094             s->session->cipher = pref_cipher ?
1095                 pref_cipher : ssl_get_cipher_by_char(s, cipherchars);
1096         } else {
1097             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1098             al = SSL_AD_INTERNAL_ERROR;
1099             goto f_err;
1100         }
1101     }
1102
1103     if (session_id_len != 0 && session_id_len == s->session->session_id_length
1104         && memcmp(PACKET_data(&session_id), s->session->session_id,
1105                   session_id_len) == 0) {
1106         if (s->sid_ctx_length != s->session->sid_ctx_length
1107             || memcmp(s->session->sid_ctx, s->sid_ctx, s->sid_ctx_length)) {
1108             /* actually a client application bug */
1109             al = SSL_AD_ILLEGAL_PARAMETER;
1110             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1111                    SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
1112             goto f_err;
1113         }
1114         s->hit = 1;
1115     } else {
1116         /*
1117          * If we were trying for session-id reuse but the server
1118          * didn't echo the ID, make a new SSL_SESSION.
1119          * In the case of EAP-FAST and PAC, we do not send a session ID,
1120          * so the PAC-based session secret is always preserved. It'll be
1121          * overwritten if the server refuses resumption.
1122          */
1123         if (s->session->session_id_length > 0) {
1124             if (!ssl_get_new_session(s, 0)) {
1125                 goto f_err;
1126             }
1127         }
1128
1129         s->session->session_id_length = session_id_len;
1130         /* session_id_len could be 0 */
1131         memcpy(s->session->session_id, PACKET_data(&session_id),
1132                session_id_len);
1133     }
1134
1135     c = ssl_get_cipher_by_char(s, cipherchars);
1136     if (c == NULL) {
1137         /* unknown cipher */
1138         al = SSL_AD_ILLEGAL_PARAMETER;
1139         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_UNKNOWN_CIPHER_RETURNED);
1140         goto f_err;
1141     }
1142     /*
1143      * Now that we know the version, update the check to see if it's an allowed
1144      * version.
1145      */
1146     s->s3->tmp.min_ver = s->version;
1147     s->s3->tmp.max_ver = s->version;
1148     /*
1149      * If it is a disabled cipher we either didn't send it in client hello,
1150      * or it's not allowed for the selected protocol. So we return an error.
1151      */
1152     if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_CHECK)) {
1153         al = SSL_AD_ILLEGAL_PARAMETER;
1154         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_WRONG_CIPHER_RETURNED);
1155         goto f_err;
1156     }
1157
1158     sk = ssl_get_ciphers_by_id(s);
1159     i = sk_SSL_CIPHER_find(sk, c);
1160     if (i < 0) {
1161         /* we did not say we would use this cipher */
1162         al = SSL_AD_ILLEGAL_PARAMETER;
1163         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_WRONG_CIPHER_RETURNED);
1164         goto f_err;
1165     }
1166
1167     /*
1168      * Depending on the session caching (internal/external), the cipher
1169      * and/or cipher_id values may not be set. Make sure that cipher_id is
1170      * set and use it for comparison.
1171      */
1172     if (s->session->cipher)
1173         s->session->cipher_id = s->session->cipher->id;
1174     if (s->hit && (s->session->cipher_id != c->id)) {
1175         al = SSL_AD_ILLEGAL_PARAMETER;
1176         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1177                SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
1178         goto f_err;
1179     }
1180     s->s3->tmp.new_cipher = c;
1181     /* lets get the compression algorithm */
1182     /* COMPRESSION */
1183     if (!PACKET_get_1(pkt, &compression)) {
1184         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
1185         al = SSL_AD_DECODE_ERROR;
1186         goto f_err;
1187     }
1188 #ifdef OPENSSL_NO_COMP
1189     if (compression != 0) {
1190         al = SSL_AD_ILLEGAL_PARAMETER;
1191         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1192                SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1193         goto f_err;
1194     }
1195     /*
1196      * If compression is disabled we'd better not try to resume a session
1197      * using compression.
1198      */
1199     if (s->session->compress_meth != 0) {
1200         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
1201         goto f_err;
1202     }
1203 #else
1204     if (s->hit && compression != s->session->compress_meth) {
1205         al = SSL_AD_ILLEGAL_PARAMETER;
1206         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1207                SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED);
1208         goto f_err;
1209     }
1210     if (compression == 0)
1211         comp = NULL;
1212     else if (!ssl_allow_compression(s)) {
1213         al = SSL_AD_ILLEGAL_PARAMETER;
1214         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_COMPRESSION_DISABLED);
1215         goto f_err;
1216     } else {
1217         comp = ssl3_comp_find(s->ctx->comp_methods, compression);
1218     }
1219
1220     if (compression != 0 && comp == NULL) {
1221         al = SSL_AD_ILLEGAL_PARAMETER;
1222         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1223                SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1224         goto f_err;
1225     } else {
1226         s->s3->tmp.new_compression = comp;
1227     }
1228 #endif
1229
1230     /* TLS extensions */
1231     if (!ssl_parse_serverhello_tlsext(s, pkt)) {
1232         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_PARSE_TLSEXT);
1233         goto err;
1234     }
1235
1236     if (PACKET_remaining(pkt) != 0) {
1237         /* wrong packet length */
1238         al = SSL_AD_DECODE_ERROR;
1239         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_BAD_PACKET_LENGTH);
1240         goto f_err;
1241     }
1242
1243 #ifndef OPENSSL_NO_SCTP
1244     if (SSL_IS_DTLS(s) && s->hit) {
1245         unsigned char sctpauthkey[64];
1246         char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
1247
1248         /*
1249          * Add new shared key for SCTP-Auth, will be ignored if
1250          * no SCTP used.
1251          */
1252         memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
1253                sizeof(DTLS1_SCTP_AUTH_LABEL));
1254
1255         if (SSL_export_keying_material(s, sctpauthkey,
1256                                    sizeof(sctpauthkey),
1257                                    labelbuffer,
1258                                    sizeof(labelbuffer), NULL, 0,
1259                                    0) <= 0)
1260             goto err;
1261
1262         BIO_ctrl(SSL_get_wbio(s),
1263                  BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
1264                  sizeof(sctpauthkey), sctpauthkey);
1265     }
1266 #endif
1267
1268     return MSG_PROCESS_CONTINUE_READING;
1269  f_err:
1270     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1271  err:
1272     ossl_statem_set_error(s);
1273     return MSG_PROCESS_ERROR;
1274 }
1275
1276 MSG_PROCESS_RETURN tls_process_server_certificate(SSL *s, PACKET *pkt)
1277 {
1278     int al, i, ret = MSG_PROCESS_ERROR, exp_idx;
1279     unsigned long cert_list_len, cert_len;
1280     X509 *x = NULL;
1281     const unsigned char *certstart, *certbytes;
1282     STACK_OF(X509) *sk = NULL;
1283     EVP_PKEY *pkey = NULL;
1284
1285     if ((sk = sk_X509_new_null()) == NULL) {
1286         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, ERR_R_MALLOC_FAILURE);
1287         goto err;
1288     }
1289
1290     if (!PACKET_get_net_3(pkt, &cert_list_len)
1291             || PACKET_remaining(pkt) != cert_list_len) {
1292         al = SSL_AD_DECODE_ERROR;
1293         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
1294         goto f_err;
1295     }
1296     while (PACKET_remaining(pkt)) {
1297         if (!PACKET_get_net_3(pkt, &cert_len)
1298                 || !PACKET_get_bytes(pkt, &certbytes, cert_len)) {
1299             al = SSL_AD_DECODE_ERROR;
1300             SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1301                    SSL_R_CERT_LENGTH_MISMATCH);
1302             goto f_err;
1303         }
1304
1305         certstart = certbytes;
1306         x = d2i_X509(NULL, (const unsigned char **)&certbytes, cert_len);
1307         if (x == NULL) {
1308             al = SSL_AD_BAD_CERTIFICATE;
1309             SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, ERR_R_ASN1_LIB);
1310             goto f_err;
1311         }
1312         if (certbytes != (certstart + cert_len)) {
1313             al = SSL_AD_DECODE_ERROR;
1314             SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1315                    SSL_R_CERT_LENGTH_MISMATCH);
1316             goto f_err;
1317         }
1318         if (!sk_X509_push(sk, x)) {
1319             SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, ERR_R_MALLOC_FAILURE);
1320             goto err;
1321         }
1322         x = NULL;
1323     }
1324
1325     i = ssl_verify_cert_chain(s, sk);
1326     if (s->verify_mode != SSL_VERIFY_NONE && i <= 0) {
1327         al = ssl_verify_alarm_type(s->verify_result);
1328         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1329                SSL_R_CERTIFICATE_VERIFY_FAILED);
1330         goto f_err;
1331     }
1332     ERR_clear_error();          /* but we keep s->verify_result */
1333     if (i > 1) {
1334         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, i);
1335         al = SSL_AD_HANDSHAKE_FAILURE;
1336         goto f_err;
1337     }
1338
1339     s->session->peer_chain = sk;
1340     /*
1341      * Inconsistency alert: cert_chain does include the peer's certificate,
1342      * which we don't include in s3_srvr.c
1343      */
1344     x = sk_X509_value(sk, 0);
1345     sk = NULL;
1346     /*
1347      * VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end
1348      */
1349
1350     pkey = X509_get0_pubkey(x);
1351
1352     if (pkey == NULL || EVP_PKEY_missing_parameters(pkey)) {
1353         x = NULL;
1354         al = SSL3_AL_FATAL;
1355         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1356                SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
1357         goto f_err;
1358     }
1359
1360     i = ssl_cert_type(x, pkey);
1361     if (i < 0) {
1362         x = NULL;
1363         al = SSL3_AL_FATAL;
1364         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1365                SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1366         goto f_err;
1367     }
1368
1369     exp_idx = ssl_cipher_get_cert_index(s->s3->tmp.new_cipher);
1370     if (exp_idx >= 0 && i != exp_idx
1371             && (exp_idx != SSL_PKEY_GOST_EC ||
1372                 (i != SSL_PKEY_GOST12_512 && i != SSL_PKEY_GOST12_256
1373                  && i != SSL_PKEY_GOST01))) {
1374         x = NULL;
1375         al = SSL_AD_ILLEGAL_PARAMETER;
1376         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1377                SSL_R_WRONG_CERTIFICATE_TYPE);
1378         goto f_err;
1379     }
1380     s->session->peer_type = i;
1381
1382     X509_free(s->session->peer);
1383     X509_up_ref(x);
1384     s->session->peer = x;
1385     s->session->verify_result = s->verify_result;
1386
1387     x = NULL;
1388     ret = MSG_PROCESS_CONTINUE_READING;
1389     goto done;
1390
1391  f_err:
1392     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1393  err:
1394     ossl_statem_set_error(s);
1395  done:
1396     X509_free(x);
1397     sk_X509_pop_free(sk, X509_free);
1398     return ret;
1399 }
1400
1401 MSG_PROCESS_RETURN tls_process_key_exchange(SSL *s, PACKET *pkt)
1402 {
1403     EVP_MD_CTX *md_ctx;
1404     int al, j;
1405     long alg_k, alg_a;
1406     EVP_PKEY *pkey = NULL;
1407     const EVP_MD *md = NULL;
1408 #ifndef OPENSSL_NO_RSA
1409     RSA *rsa = NULL;
1410 #endif
1411 #ifndef OPENSSL_NO_EC
1412     EVP_PKEY_CTX *pctx = NULL;
1413 #endif
1414     PACKET save_param_start, signature;
1415
1416     md_ctx = EVP_MD_CTX_new();
1417     if (md_ctx == NULL) {
1418         al = SSL_AD_INTERNAL_ERROR;
1419         SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1420         goto f_err;
1421     }
1422
1423     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1424
1425     save_param_start = *pkt;
1426
1427 #if !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)
1428     EVP_PKEY_free(s->s3->peer_tmp);
1429     s->s3->peer_tmp = NULL;
1430 #endif
1431
1432     alg_a = s->s3->tmp.new_cipher->algorithm_auth;
1433
1434     al = SSL_AD_DECODE_ERROR;
1435
1436 #ifndef OPENSSL_NO_PSK
1437     /* PSK ciphersuites are preceded by an identity hint */
1438     if (alg_k & SSL_PSK) {
1439         PACKET psk_identity_hint;
1440         if (!PACKET_get_length_prefixed_2(pkt, &psk_identity_hint)) {
1441             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
1442             goto f_err;
1443         }
1444
1445         /*
1446          * Store PSK identity hint for later use, hint is used in
1447          * ssl3_send_client_key_exchange.  Assume that the maximum length of
1448          * a PSK identity hint can be as long as the maximum length of a PSK
1449          * identity.
1450          */
1451         if (PACKET_remaining(&psk_identity_hint) > PSK_MAX_IDENTITY_LEN) {
1452             al = SSL_AD_HANDSHAKE_FAILURE;
1453             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG);
1454             goto f_err;
1455         }
1456
1457         if (PACKET_remaining(&psk_identity_hint) == 0) {
1458             OPENSSL_free(s->session->psk_identity_hint);
1459             s->session->psk_identity_hint = NULL;
1460         } else if (!PACKET_strndup(&psk_identity_hint,
1461                             &s->session->psk_identity_hint)) {
1462             al = SSL_AD_INTERNAL_ERROR;
1463             goto f_err;
1464         }
1465     }
1466
1467     /* Nothing else to do for plain PSK or RSAPSK */
1468     if (alg_k & (SSL_kPSK | SSL_kRSAPSK)) {
1469     } else
1470 #endif                          /* !OPENSSL_NO_PSK */
1471     /*
1472      * Dummy "if" to ensure sane C code in the event of various OPENSSL_NO_*
1473      * options
1474      */
1475     if (0) {
1476     }
1477 #ifndef OPENSSL_NO_SRP
1478     else if (alg_k & SSL_kSRP) {
1479         PACKET prime, generator, salt, server_pub;
1480         if (!PACKET_get_length_prefixed_2(pkt, &prime)
1481             || !PACKET_get_length_prefixed_2(pkt, &generator)
1482             || !PACKET_get_length_prefixed_1(pkt, &salt)
1483             || !PACKET_get_length_prefixed_2(pkt, &server_pub)) {
1484             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
1485             goto f_err;
1486         }
1487
1488         if ((s->srp_ctx.N =
1489              BN_bin2bn(PACKET_data(&prime),
1490                        PACKET_remaining(&prime), NULL)) == NULL
1491             || (s->srp_ctx.g =
1492                 BN_bin2bn(PACKET_data(&generator),
1493                           PACKET_remaining(&generator), NULL)) == NULL
1494             || (s->srp_ctx.s =
1495                 BN_bin2bn(PACKET_data(&salt),
1496                           PACKET_remaining(&salt), NULL)) == NULL
1497             || (s->srp_ctx.B =
1498                 BN_bin2bn(PACKET_data(&server_pub),
1499                           PACKET_remaining(&server_pub), NULL)) == NULL) {
1500             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_BN_LIB);
1501             goto err;
1502         }
1503
1504         if (!srp_verify_server_param(s, &al)) {
1505             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_BAD_SRP_PARAMETERS);
1506             goto f_err;
1507         }
1508
1509 /* We must check if there is a certificate */
1510         if (alg_a & (SSL_aRSA|SSL_aDSS))
1511             pkey = X509_get0_pubkey(s->session->peer);
1512     }
1513 #endif                          /* !OPENSSL_NO_SRP */
1514 #ifndef OPENSSL_NO_DH
1515     else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
1516         PACKET prime, generator, pub_key;
1517
1518         DH *dh;
1519
1520         if (!PACKET_get_length_prefixed_2(pkt, &prime)
1521             || !PACKET_get_length_prefixed_2(pkt, &generator)
1522             || !PACKET_get_length_prefixed_2(pkt, &pub_key)) {
1523             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
1524             goto f_err;
1525         }
1526
1527         s->s3->peer_tmp = EVP_PKEY_new();
1528         dh = DH_new();
1529
1530         if (s->s3->peer_tmp == NULL || dh == NULL) {
1531             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1532             DH_free(dh);
1533             goto err;
1534         }
1535
1536         if (EVP_PKEY_assign_DH(s->s3->peer_tmp, dh) == 0) {
1537             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_EVP_LIB);
1538             DH_free(dh);
1539             goto err;
1540         }
1541
1542         if ((dh->p = BN_bin2bn(PACKET_data(&prime),
1543                                PACKET_remaining(&prime), NULL)) == NULL
1544             || (dh->g = BN_bin2bn(PACKET_data(&generator),
1545                                   PACKET_remaining(&generator), NULL)) == NULL
1546             || (dh->pub_key =
1547                 BN_bin2bn(PACKET_data(&pub_key),
1548                           PACKET_remaining(&pub_key), NULL)) == NULL) {
1549             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_BN_LIB);
1550             goto err;
1551         }
1552
1553         if (BN_is_zero(dh->p) || BN_is_zero(dh->g) || BN_is_zero(dh->pub_key)) {
1554             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_BAD_DH_VALUE);
1555             goto f_err;
1556         }
1557
1558         if (!ssl_security(s, SSL_SECOP_TMP_DH, DH_security_bits(dh), 0, dh)) {
1559             al = SSL_AD_HANDSHAKE_FAILURE;
1560             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_DH_KEY_TOO_SMALL);
1561             goto f_err;
1562         }
1563         if (alg_a & (SSL_aRSA|SSL_aDSS))
1564             pkey = X509_get0_pubkey(s->session->peer);
1565         /* else anonymous DH, so no certificate or pkey. */
1566     }
1567 #endif                          /* !OPENSSL_NO_DH */
1568
1569 #ifndef OPENSSL_NO_EC
1570     else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
1571         PACKET encoded_pt;
1572         const unsigned char *ecparams;
1573         int curve_nid;
1574
1575         /*
1576          * Extract elliptic curve parameters and the server's ephemeral ECDH
1577          * public key. For now we only support named (not generic) curves and
1578          * ECParameters in this case is just three bytes.
1579          */
1580         if (!PACKET_get_bytes(pkt, &ecparams, 3)) {
1581             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1582             goto f_err;
1583         }
1584         /*
1585          * Check curve is one of our preferences, if not server has sent an
1586          * invalid curve. ECParameters is 3 bytes.
1587          */
1588         if (!tls1_check_curve(s, ecparams, 3)) {
1589             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_WRONG_CURVE);
1590             goto f_err;
1591         }
1592
1593         curve_nid = tls1_ec_curve_id2nid(*(ecparams + 2));
1594         if (curve_nid  == 0) {
1595             al = SSL_AD_INTERNAL_ERROR;
1596             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE,
1597                    SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
1598             goto f_err;
1599         }
1600
1601         /* Set up EVP_PKEY with named curve as parameters */
1602         pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL);
1603         if (pctx == NULL
1604             || EVP_PKEY_paramgen_init(pctx) <= 0
1605             || EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx, curve_nid) <= 0
1606             || EVP_PKEY_paramgen(pctx, &s->s3->peer_tmp) <= 0) {
1607             al = SSL_AD_INTERNAL_ERROR;
1608             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_EVP_LIB);
1609             goto f_err;
1610         }
1611         EVP_PKEY_CTX_free(pctx);
1612         pctx = NULL;
1613
1614         if (!PACKET_get_length_prefixed_1(pkt, &encoded_pt)) {
1615             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
1616             goto f_err;
1617         }
1618
1619         if (EC_KEY_oct2key(EVP_PKEY_get0_EC_KEY(s->s3->peer_tmp),
1620                            PACKET_data(&encoded_pt),
1621                            PACKET_remaining(&encoded_pt), NULL) == 0) {
1622             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_BAD_ECPOINT);
1623             goto f_err;
1624         }
1625
1626         /*
1627          * The ECC/TLS specification does not mention the use of DSA to sign
1628          * ECParameters in the server key exchange message. We do support RSA
1629          * and ECDSA.
1630          */
1631         if (0) ;
1632 # ifndef OPENSSL_NO_RSA
1633         else if (alg_a & SSL_aRSA)
1634             pkey = X509_get0_pubkey(s->session->peer);
1635 # endif
1636 # ifndef OPENSSL_NO_EC
1637         else if (alg_a & SSL_aECDSA)
1638             pkey = X509_get0_pubkey(s->session->peer);
1639 # endif
1640         /* else anonymous ECDH, so no certificate or pkey. */
1641     } else if (alg_k) {
1642         al = SSL_AD_UNEXPECTED_MESSAGE;
1643         SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
1644         goto f_err;
1645     }
1646 #endif                          /* !OPENSSL_NO_EC */
1647
1648     /* if it was signed, check the signature */
1649     if (pkey != NULL) {
1650         PACKET params;
1651         /*
1652          * |pkt| now points to the beginning of the signature, so the difference
1653          * equals the length of the parameters.
1654          */
1655         if (!PACKET_get_sub_packet(&save_param_start, &params,
1656                                    PACKET_remaining(&save_param_start) -
1657                                    PACKET_remaining(pkt))) {
1658             al = SSL_AD_INTERNAL_ERROR;
1659             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1660             goto f_err;
1661         }
1662
1663         if (SSL_USE_SIGALGS(s)) {
1664             const unsigned char *sigalgs;
1665             int rv;
1666             if (!PACKET_get_bytes(pkt, &sigalgs, 2)) {
1667                 SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1668                 goto f_err;
1669             }
1670             rv = tls12_check_peer_sigalg(&md, s, sigalgs, pkey);
1671             if (rv == -1)
1672                 goto err;
1673             else if (rv == 0) {
1674                 goto f_err;
1675             }
1676 #ifdef SSL_DEBUG
1677             fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
1678 #endif
1679         } else if (EVP_PKEY_id(pkey) == EVP_PKEY_RSA) {
1680             md = EVP_md5_sha1();
1681         } else {
1682             md = EVP_sha1();
1683         }
1684
1685         if (!PACKET_get_length_prefixed_2(pkt, &signature)
1686             || PACKET_remaining(pkt) != 0) {
1687             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
1688             goto f_err;
1689         }
1690         j = EVP_PKEY_size(pkey);
1691         if (j < 0) {
1692             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1693             goto f_err;
1694         }
1695
1696         /*
1697          * Check signature length
1698          */
1699         if (PACKET_remaining(&signature) > (size_t)j) {
1700             /* wrong packet length */
1701             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_WRONG_SIGNATURE_LENGTH);
1702             goto f_err;
1703         }
1704         if (EVP_VerifyInit_ex(md_ctx, md, NULL) <= 0
1705                 || EVP_VerifyUpdate(md_ctx, &(s->s3->client_random[0]),
1706                                     SSL3_RANDOM_SIZE) <= 0
1707                 || EVP_VerifyUpdate(md_ctx, &(s->s3->server_random[0]),
1708                                     SSL3_RANDOM_SIZE) <= 0
1709                 || EVP_VerifyUpdate(md_ctx, PACKET_data(&params),
1710                                     PACKET_remaining(&params)) <= 0) {
1711             al = SSL_AD_INTERNAL_ERROR;
1712             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_EVP_LIB);
1713             goto f_err;
1714         }
1715         if (EVP_VerifyFinal(md_ctx, PACKET_data(&signature),
1716                             PACKET_remaining(&signature), pkey) <= 0) {
1717             /* bad signature */
1718             al = SSL_AD_DECRYPT_ERROR;
1719             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_BAD_SIGNATURE);
1720             goto f_err;
1721         }
1722     } else {
1723         /* aNULL, aSRP or PSK do not need public keys */
1724         if (!(alg_a & (SSL_aNULL | SSL_aSRP)) && !(alg_k & SSL_PSK)) {
1725             /* Might be wrong key type, check it */
1726             if (ssl3_check_cert_and_algorithm(s))
1727                 /* Otherwise this shouldn't happen */
1728                 SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1729             goto err;
1730         }
1731         /* still data left over */
1732         if (PACKET_remaining(pkt) != 0) {
1733             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_EXTRA_DATA_IN_MESSAGE);
1734             goto f_err;
1735         }
1736     }
1737     EVP_MD_CTX_free(md_ctx);
1738     return MSG_PROCESS_CONTINUE_READING;
1739  f_err:
1740     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1741  err:
1742 #ifndef OPENSSL_NO_RSA
1743     RSA_free(rsa);
1744 #endif
1745 #ifndef OPENSSL_NO_EC
1746     EVP_PKEY_CTX_free(pctx);
1747 #endif
1748     EVP_MD_CTX_free(md_ctx);
1749     ossl_statem_set_error(s);
1750     return MSG_PROCESS_ERROR;
1751 }
1752
1753 MSG_PROCESS_RETURN tls_process_certificate_request(SSL *s, PACKET *pkt)
1754 {
1755     int ret = MSG_PROCESS_ERROR;
1756     unsigned int list_len, ctype_num, i, name_len;
1757     X509_NAME *xn = NULL;
1758     const unsigned char *data;
1759     const unsigned char *namestart, *namebytes;
1760     STACK_OF(X509_NAME) *ca_sk = NULL;
1761
1762     if ((ca_sk = sk_X509_NAME_new(ca_dn_cmp)) == NULL) {
1763         SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
1764         goto err;
1765     }
1766
1767     /* get the certificate types */
1768     if (!PACKET_get_1(pkt, &ctype_num)
1769             || !PACKET_get_bytes(pkt, &data, ctype_num)) {
1770         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1771         SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, SSL_R_LENGTH_MISMATCH);
1772         goto err;
1773     }
1774     OPENSSL_free(s->cert->ctypes);
1775     s->cert->ctypes = NULL;
1776     if (ctype_num > SSL3_CT_NUMBER) {
1777         /* If we exceed static buffer copy all to cert structure */
1778         s->cert->ctypes = OPENSSL_malloc(ctype_num);
1779         if (s->cert->ctypes == NULL) {
1780             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
1781             goto err;
1782         }
1783         memcpy(s->cert->ctypes, data, ctype_num);
1784         s->cert->ctype_num = (size_t)ctype_num;
1785         ctype_num = SSL3_CT_NUMBER;
1786     }
1787     for (i = 0; i < ctype_num; i++)
1788         s->s3->tmp.ctype[i] = data[i];
1789
1790     if (SSL_USE_SIGALGS(s)) {
1791         if (!PACKET_get_net_2(pkt, &list_len)
1792                 || !PACKET_get_bytes(pkt, &data, list_len)) {
1793             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1794             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST,
1795                    SSL_R_LENGTH_MISMATCH);
1796             goto err;
1797         }
1798
1799         /* Clear certificate digests and validity flags */
1800         for (i = 0; i < SSL_PKEY_NUM; i++) {
1801             s->s3->tmp.md[i] = NULL;
1802             s->s3->tmp.valid_flags[i] = 0;
1803         }
1804         if ((list_len & 1) || !tls1_save_sigalgs(s, data, list_len)) {
1805             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1806             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST,
1807                    SSL_R_SIGNATURE_ALGORITHMS_ERROR);
1808             goto err;
1809         }
1810         if (!tls1_process_sigalgs(s)) {
1811             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1812             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
1813             goto err;
1814         }
1815     } else {
1816         ssl_set_default_md(s);
1817     }
1818
1819     /* get the CA RDNs */
1820     if (!PACKET_get_net_2(pkt, &list_len)
1821             || PACKET_remaining(pkt) != list_len) {
1822         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1823         SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, SSL_R_LENGTH_MISMATCH);
1824         goto err;
1825     }
1826
1827     while (PACKET_remaining(pkt)) {
1828         if (!PACKET_get_net_2(pkt, &name_len)
1829                 || !PACKET_get_bytes(pkt, &namebytes, name_len)) {
1830             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1831             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST,
1832                    SSL_R_LENGTH_MISMATCH);
1833             goto err;
1834         }
1835
1836         namestart = namebytes;
1837
1838         if ((xn = d2i_X509_NAME(NULL, (const unsigned char **)&namebytes,
1839                                 name_len)) == NULL) {
1840             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1841             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_ASN1_LIB);
1842             goto err;
1843         }
1844
1845         if (namebytes != (namestart + name_len)) {
1846             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1847             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST,
1848                    SSL_R_CA_DN_LENGTH_MISMATCH);
1849             goto err;
1850         }
1851         if (!sk_X509_NAME_push(ca_sk, xn)) {
1852             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
1853             goto err;
1854         }
1855     }
1856
1857     /* we should setup a certificate to return.... */
1858     s->s3->tmp.cert_req = 1;
1859     s->s3->tmp.ctype_num = ctype_num;
1860     sk_X509_NAME_pop_free(s->s3->tmp.ca_names, X509_NAME_free);
1861     s->s3->tmp.ca_names = ca_sk;
1862     ca_sk = NULL;
1863
1864     ret = MSG_PROCESS_CONTINUE_READING;
1865     goto done;
1866  err:
1867     ossl_statem_set_error(s);
1868  done:
1869     sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
1870     return ret;
1871 }
1872
1873 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
1874 {
1875     return (X509_NAME_cmp(*a, *b));
1876 }
1877
1878 MSG_PROCESS_RETURN tls_process_new_session_ticket(SSL *s, PACKET *pkt)
1879 {
1880     int al;
1881     unsigned int ticklen;
1882     unsigned long ticket_lifetime_hint;
1883
1884     if (!PACKET_get_net_4(pkt, &ticket_lifetime_hint)
1885             || !PACKET_get_net_2(pkt, &ticklen)
1886             || PACKET_remaining(pkt) != ticklen) {
1887         al = SSL_AD_DECODE_ERROR;
1888         SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
1889         goto f_err;
1890     }
1891
1892     /* Server is allowed to change its mind and send an empty ticket. */
1893     if (ticklen == 0)
1894         return MSG_PROCESS_CONTINUE_READING;
1895
1896     if (s->session->session_id_length > 0) {
1897         int i = s->session_ctx->session_cache_mode;
1898         SSL_SESSION *new_sess;
1899         /*
1900          * We reused an existing session, so we need to replace it with a new
1901          * one
1902          */
1903         if (i & SSL_SESS_CACHE_CLIENT) {
1904             /*
1905              * Remove the old session from the cache
1906              */
1907             if (i & SSL_SESS_CACHE_NO_INTERNAL_STORE) {
1908                 if (s->session_ctx->remove_session_cb != NULL)
1909                     s->session_ctx->remove_session_cb(s->session_ctx,
1910                                                       s->session);
1911             } else {
1912                 /* We carry on if this fails */
1913                 SSL_CTX_remove_session(s->session_ctx, s->session);
1914             }
1915         }
1916
1917         if ((new_sess = ssl_session_dup(s->session, 0)) == 0) {
1918             al = SSL_AD_INTERNAL_ERROR;
1919             SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
1920             goto f_err;
1921         }
1922
1923         SSL_SESSION_free(s->session);
1924         s->session = new_sess;
1925     }
1926
1927     OPENSSL_free(s->session->tlsext_tick);
1928     s->session->tlsext_ticklen = 0;
1929
1930     s->session->tlsext_tick = OPENSSL_malloc(ticklen);
1931     if (s->session->tlsext_tick == NULL) {
1932         SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
1933         goto err;
1934     }
1935     if (!PACKET_copy_bytes(pkt, s->session->tlsext_tick, ticklen)) {
1936         al = SSL_AD_DECODE_ERROR;
1937         SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
1938         goto f_err;
1939     }
1940
1941     s->session->tlsext_tick_lifetime_hint = ticket_lifetime_hint;
1942     s->session->tlsext_ticklen = ticklen;
1943     /*
1944      * There are two ways to detect a resumed ticket session. One is to set
1945      * an appropriate session ID and then the server must return a match in
1946      * ServerHello. This allows the normal client session ID matching to work
1947      * and we know much earlier that the ticket has been accepted. The
1948      * other way is to set zero length session ID when the ticket is
1949      * presented and rely on the handshake to determine session resumption.
1950      * We choose the former approach because this fits in with assumptions
1951      * elsewhere in OpenSSL. The session ID is set to the SHA256 (or SHA1 is
1952      * SHA256 is disabled) hash of the ticket.
1953      */
1954     EVP_Digest(s->session->tlsext_tick, ticklen,
1955                s->session->session_id, &s->session->session_id_length,
1956                EVP_sha256(), NULL);
1957     return MSG_PROCESS_CONTINUE_READING;
1958  f_err:
1959     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1960  err:
1961     ossl_statem_set_error(s);
1962     return MSG_PROCESS_ERROR;
1963 }
1964
1965 MSG_PROCESS_RETURN tls_process_cert_status(SSL *s, PACKET *pkt)
1966 {
1967     int al;
1968     unsigned long resplen;
1969     unsigned int type;
1970
1971     if (!PACKET_get_1(pkt, &type)
1972             || type != TLSEXT_STATUSTYPE_ocsp) {
1973         al = SSL_AD_DECODE_ERROR;
1974         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, SSL_R_UNSUPPORTED_STATUS_TYPE);
1975         goto f_err;
1976     }
1977     if (!PACKET_get_net_3(pkt, &resplen)
1978             || PACKET_remaining(pkt) != resplen) {
1979         al = SSL_AD_DECODE_ERROR;
1980         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, SSL_R_LENGTH_MISMATCH);
1981         goto f_err;
1982     }
1983     s->tlsext_ocsp_resp = OPENSSL_malloc(resplen);
1984     if (s->tlsext_ocsp_resp == NULL) {
1985         al = SSL_AD_INTERNAL_ERROR;
1986         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, ERR_R_MALLOC_FAILURE);
1987         goto f_err;
1988     }
1989     if (!PACKET_copy_bytes(pkt, s->tlsext_ocsp_resp, resplen)) {
1990         al = SSL_AD_DECODE_ERROR;
1991         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, SSL_R_LENGTH_MISMATCH);
1992         goto f_err;
1993     }
1994     s->tlsext_ocsp_resplen = resplen;
1995     return MSG_PROCESS_CONTINUE_READING;
1996  f_err:
1997     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1998     ossl_statem_set_error(s);
1999     return MSG_PROCESS_ERROR;
2000 }
2001
2002 MSG_PROCESS_RETURN tls_process_server_done(SSL *s, PACKET *pkt)
2003 {
2004     if (PACKET_remaining(pkt) > 0) {
2005         /* should contain no data */
2006         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2007         SSLerr(SSL_F_TLS_PROCESS_SERVER_DONE, SSL_R_LENGTH_MISMATCH);
2008         ossl_statem_set_error(s);
2009         return MSG_PROCESS_ERROR;
2010     }
2011
2012 #ifndef OPENSSL_NO_SRP
2013     if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) {
2014         if (SRP_Calc_A_param(s) <= 0) {
2015             SSLerr(SSL_F_TLS_PROCESS_SERVER_DONE, SSL_R_SRP_A_CALC);
2016             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2017             ossl_statem_set_error(s);
2018             return MSG_PROCESS_ERROR;
2019         }
2020     }
2021 #endif
2022
2023     /*
2024      * at this point we check that we have the required stuff from
2025      * the server
2026      */
2027     if (!ssl3_check_cert_and_algorithm(s)) {
2028         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2029         ossl_statem_set_error(s);
2030         return MSG_PROCESS_ERROR;
2031     }
2032
2033     /*
2034      * Call the ocsp status callback if needed. The |tlsext_ocsp_resp| and
2035      * |tlsext_ocsp_resplen| values will be set if we actually received a status
2036      * message, or NULL and -1 otherwise
2037      */
2038     if (s->tlsext_status_type != -1 && s->ctx->tlsext_status_cb != NULL) {
2039         int ret;
2040         ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
2041         if (ret == 0) {
2042             ssl3_send_alert(s, SSL3_AL_FATAL,
2043                             SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE);
2044             SSLerr(SSL_F_TLS_PROCESS_SERVER_DONE,
2045                    SSL_R_INVALID_STATUS_RESPONSE);
2046             return MSG_PROCESS_ERROR;
2047         }
2048         if (ret < 0) {
2049             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2050             SSLerr(SSL_F_TLS_PROCESS_SERVER_DONE, ERR_R_MALLOC_FAILURE);
2051             return MSG_PROCESS_ERROR;
2052         }
2053     }
2054
2055 #ifndef OPENSSL_NO_CT
2056     if (s->ct_validation_callback != NULL) {
2057         if (!ssl_validate_ct(s)) {
2058             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2059             return MSG_PROCESS_ERROR;
2060         }
2061     }
2062 #endif
2063
2064 #ifndef OPENSSL_NO_SCTP
2065     /* Only applies to renegotiation */
2066     if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))
2067             && s->renegotiate != 0)
2068         return MSG_PROCESS_CONTINUE_PROCESSING;
2069     else
2070 #endif
2071         return MSG_PROCESS_FINISHED_READING;
2072 }
2073
2074 int tls_construct_client_key_exchange(SSL *s)
2075 {
2076     unsigned char *p;
2077     int n;
2078 #ifndef OPENSSL_NO_PSK
2079     size_t pskhdrlen = 0;
2080 #endif
2081     unsigned long alg_k;
2082 #ifndef OPENSSL_NO_RSA
2083     unsigned char *q;
2084     EVP_PKEY *pkey = NULL;
2085     EVP_PKEY_CTX *pctx = NULL;
2086 #endif
2087 #if !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)
2088     EVP_PKEY *ckey = NULL, *skey = NULL;
2089 #endif
2090 #ifndef OPENSSL_NO_EC
2091     unsigned char *encodedPoint = NULL;
2092     int encoded_pt_len = 0;
2093 #endif
2094     unsigned char *pms = NULL;
2095     size_t pmslen = 0;
2096     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2097
2098     p = ssl_handshake_start(s);
2099
2100
2101 #ifndef OPENSSL_NO_PSK
2102     if (alg_k & SSL_PSK) {
2103         int psk_err = 1;
2104         /*
2105          * The callback needs PSK_MAX_IDENTITY_LEN + 1 bytes to return a
2106          * \0-terminated identity. The last byte is for us for simulating
2107          * strnlen.
2108          */
2109         char identity[PSK_MAX_IDENTITY_LEN + 1];
2110         size_t identitylen;
2111         unsigned char psk[PSK_MAX_PSK_LEN];
2112         size_t psklen;
2113
2114         if (s->psk_client_callback == NULL) {
2115             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2116                    SSL_R_PSK_NO_CLIENT_CB);
2117             goto err;
2118         }
2119
2120         memset(identity, 0, sizeof(identity));
2121
2122         psklen = s->psk_client_callback(s, s->session->psk_identity_hint,
2123                                         identity, sizeof(identity) - 1,
2124                                         psk, sizeof(psk));
2125
2126         if (psklen > PSK_MAX_PSK_LEN) {
2127             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2128                    ERR_R_INTERNAL_ERROR);
2129             goto psk_err;
2130         } else if (psklen == 0) {
2131             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2132                    SSL_R_PSK_IDENTITY_NOT_FOUND);
2133             goto psk_err;
2134         }
2135         OPENSSL_free(s->s3->tmp.psk);
2136         s->s3->tmp.psk = OPENSSL_memdup(psk, psklen);
2137         OPENSSL_cleanse(psk, psklen);
2138
2139         if (s->s3->tmp.psk == NULL) {
2140             OPENSSL_cleanse(identity, sizeof(identity));
2141             goto memerr;
2142         }
2143
2144         s->s3->tmp.psklen = psklen;
2145         identitylen = strlen(identity);
2146         if (identitylen > PSK_MAX_IDENTITY_LEN) {
2147             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2148                    ERR_R_INTERNAL_ERROR);
2149             goto psk_err;
2150         }
2151         OPENSSL_free(s->session->psk_identity);
2152         s->session->psk_identity = OPENSSL_strdup(identity);
2153         if (s->session->psk_identity == NULL) {
2154             OPENSSL_cleanse(identity, sizeof(identity));
2155             goto memerr;
2156         }
2157
2158         s2n(identitylen, p);
2159         memcpy(p, identity, identitylen);
2160         pskhdrlen = 2 + identitylen;
2161         p += identitylen;
2162         psk_err = 0;
2163 psk_err:
2164         OPENSSL_cleanse(identity, sizeof(identity));
2165         if (psk_err != 0) {
2166             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2167             goto err;
2168         }
2169     }
2170     if (alg_k & SSL_kPSK) {
2171         n = 0;
2172     } else
2173 #endif
2174
2175     /* Fool emacs indentation */
2176     if (0) {
2177     }
2178 #ifndef OPENSSL_NO_RSA
2179     else if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
2180         size_t enclen;
2181         pmslen = SSL_MAX_MASTER_KEY_LENGTH;
2182         pms = OPENSSL_malloc(pmslen);
2183         if (pms == NULL)
2184             goto memerr;
2185
2186         if (s->session->peer == NULL) {
2187             /*
2188              * We should always have a server certificate with SSL_kRSA.
2189              */
2190             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2191                    ERR_R_INTERNAL_ERROR);
2192             goto err;
2193         }
2194
2195         pkey = X509_get0_pubkey(s->session->peer);
2196         if (EVP_PKEY_get0_RSA(pkey) == NULL) {
2197             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2198                    ERR_R_INTERNAL_ERROR);
2199             goto err;
2200         }
2201
2202         pms[0] = s->client_version >> 8;
2203         pms[1] = s->client_version & 0xff;
2204         if (RAND_bytes(pms + 2, pmslen - 2) <= 0)
2205             goto err;
2206
2207         q = p;
2208         /* Fix buf for TLS and beyond */
2209         if (s->version > SSL3_VERSION)
2210             p += 2;
2211         pctx = EVP_PKEY_CTX_new(pkey, NULL);
2212         if (pctx == NULL || EVP_PKEY_encrypt_init(pctx) <= 0
2213             || EVP_PKEY_encrypt(pctx, NULL, &enclen, pms, pmslen) <= 0) {
2214             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2215                    ERR_R_EVP_LIB);
2216             goto err;
2217         }
2218         if (EVP_PKEY_encrypt(pctx, p, &enclen, pms, pmslen) <= 0) {
2219             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2220                    SSL_R_BAD_RSA_ENCRYPT);
2221             goto err;
2222         }
2223         n = enclen;
2224         EVP_PKEY_CTX_free(pctx);
2225         pctx = NULL;
2226 # ifdef PKCS1_CHECK
2227         if (s->options & SSL_OP_PKCS1_CHECK_1)
2228             p[1]++;
2229         if (s->options & SSL_OP_PKCS1_CHECK_2)
2230             tmp_buf[0] = 0x70;
2231 # endif
2232
2233         /* Fix buf for TLS and beyond */
2234         if (s->version > SSL3_VERSION) {
2235             s2n(n, q);
2236             n += 2;
2237         }
2238     }
2239 #endif
2240 #ifndef OPENSSL_NO_DH
2241     else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
2242         DH *dh_clnt = NULL;
2243         skey = s->s3->peer_tmp;
2244         if (skey == NULL) {
2245             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2246                    ERR_R_INTERNAL_ERROR);
2247             goto err;
2248         }
2249         ckey = ssl_generate_pkey(skey, NID_undef);
2250         dh_clnt = EVP_PKEY_get0_DH(ckey);
2251
2252         if (dh_clnt == NULL || ssl_derive(s, ckey, skey) == 0) {
2253             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2254                    ERR_R_INTERNAL_ERROR);
2255             goto err;
2256         }
2257
2258
2259         /* send off the data */
2260         n = BN_num_bytes(dh_clnt->pub_key);
2261         s2n(n, p);
2262         BN_bn2bin(dh_clnt->pub_key, p);
2263         n += 2;
2264         EVP_PKEY_free(ckey);
2265         ckey = NULL;
2266     }
2267 #endif
2268
2269 #ifndef OPENSSL_NO_EC
2270     else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
2271
2272         skey = s->s3->peer_tmp;
2273         if ((skey == NULL) || EVP_PKEY_get0_EC_KEY(skey) == NULL) {
2274             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2275                        ERR_R_INTERNAL_ERROR);
2276             goto err;
2277             }
2278
2279         ckey = ssl_generate_pkey(skey, NID_undef);
2280
2281         if (ssl_derive(s, ckey, skey) == 0) {
2282             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_EVP_LIB);
2283             goto err;
2284         }
2285
2286         /* Generate encoding of client key */
2287         encoded_pt_len = EC_KEY_key2buf(EVP_PKEY_get0_EC_KEY(ckey),
2288                                         POINT_CONVERSION_UNCOMPRESSED,
2289                                         &encodedPoint, NULL);
2290
2291         if (encoded_pt_len == 0) {
2292             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2293             goto err;
2294         }
2295
2296         EVP_PKEY_free(ckey);
2297         ckey = NULL;
2298
2299         n = encoded_pt_len;
2300
2301         *p = n;         /* length of encoded point */
2302         /* Encoded point will be copied here */
2303         p += 1;
2304         /* copy the point */
2305         memcpy(p, encodedPoint, n);
2306         /* increment n to account for length field */
2307         n += 1;
2308
2309         /* Free allocated memory */
2310         OPENSSL_free(encodedPoint);
2311     }
2312 #endif                          /* !OPENSSL_NO_EC */
2313 #ifndef OPENSSL_NO_GOST
2314     else if (alg_k & SSL_kGOST) {
2315         /* GOST key exchange message creation */
2316         EVP_PKEY_CTX *pkey_ctx;
2317         X509 *peer_cert;
2318         size_t msglen;
2319         unsigned int md_len;
2320         unsigned char shared_ukm[32], tmp[256];
2321         EVP_MD_CTX *ukm_hash;
2322         int dgst_nid = NID_id_GostR3411_94;
2323         if ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aGOST12) != 0)
2324             dgst_nid = NID_id_GostR3411_2012_256;
2325
2326
2327         pmslen = 32;
2328         pms = OPENSSL_malloc(pmslen);
2329         if (pms == NULL)
2330             goto memerr;
2331
2332         /*
2333          * Get server sertificate PKEY and create ctx from it
2334          */
2335         peer_cert = s->session->peer;
2336         if (!peer_cert) {
2337             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2338                    SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
2339             goto err;
2340         }
2341
2342         pkey_ctx = EVP_PKEY_CTX_new(X509_get0_pubkey(peer_cert), NULL);
2343         if (pkey_ctx == NULL) {
2344             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2345                    ERR_R_MALLOC_FAILURE);
2346             goto err;
2347         }
2348         /*
2349          * If we have send a certificate, and certificate key
2350          * parameters match those of server certificate, use
2351          * certificate key for key exchange
2352          */
2353
2354         /* Otherwise, generate ephemeral key pair */
2355
2356         if (pkey_ctx == NULL
2357                 || EVP_PKEY_encrypt_init(pkey_ctx) <= 0
2358                 /* Generate session key */
2359                 || RAND_bytes(pms, pmslen) <= 0) {
2360             EVP_PKEY_CTX_free(pkey_ctx);
2361             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2362                    ERR_R_INTERNAL_ERROR);
2363             goto err;
2364         };
2365         /*
2366          * If we have client certificate, use its secret as peer key
2367          */
2368         if (s->s3->tmp.cert_req && s->cert->key->privatekey) {
2369             if (EVP_PKEY_derive_set_peer
2370                 (pkey_ctx, s->cert->key->privatekey) <= 0) {
2371                 /*
2372                  * If there was an error - just ignore it. Ephemeral key
2373                  * * would be used
2374                  */
2375                 ERR_clear_error();
2376             }
2377         }
2378         /*
2379          * Compute shared IV and store it in algorithm-specific context
2380          * data
2381          */
2382         ukm_hash = EVP_MD_CTX_new();
2383         if (EVP_DigestInit(ukm_hash,
2384                            EVP_get_digestbynid(dgst_nid)) <= 0
2385                 || EVP_DigestUpdate(ukm_hash, s->s3->client_random,
2386                                     SSL3_RANDOM_SIZE) <= 0
2387                 || EVP_DigestUpdate(ukm_hash, s->s3->server_random,
2388                                     SSL3_RANDOM_SIZE) <= 0
2389                 || EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len) <= 0) {
2390             EVP_MD_CTX_free(ukm_hash);
2391             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2392                    ERR_R_INTERNAL_ERROR);
2393             goto err;
2394         }
2395         EVP_MD_CTX_free(ukm_hash);
2396         if (EVP_PKEY_CTX_ctrl
2397             (pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT, EVP_PKEY_CTRL_SET_IV, 8,
2398              shared_ukm) < 0) {
2399             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2400                    SSL_R_LIBRARY_BUG);
2401             goto err;
2402         }
2403         /* Make GOST keytransport blob message */
2404         /*
2405          * Encapsulate it into sequence
2406          */
2407         *(p++) = V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED;
2408         msglen = 255;
2409         if (EVP_PKEY_encrypt(pkey_ctx, tmp, &msglen, pms, pmslen) <= 0) {
2410             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2411                    SSL_R_LIBRARY_BUG);
2412             goto err;
2413         }
2414         if (msglen >= 0x80) {
2415             *(p++) = 0x81;
2416             *(p++) = msglen & 0xff;
2417             n = msglen + 3;
2418         } else {
2419             *(p++) = msglen & 0xff;
2420             n = msglen + 2;
2421         }
2422         memcpy(p, tmp, msglen);
2423         /* Check if pubkey from client certificate was used */
2424         if (EVP_PKEY_CTX_ctrl
2425             (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0) {
2426             /* Set flag "skip certificate verify" */
2427             s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
2428         }
2429         EVP_PKEY_CTX_free(pkey_ctx);
2430
2431     }
2432 #endif
2433 #ifndef OPENSSL_NO_SRP
2434     else if (alg_k & SSL_kSRP) {
2435         if (s->srp_ctx.A != NULL) {
2436             /* send off the data */
2437             n = BN_num_bytes(s->srp_ctx.A);
2438             s2n(n, p);
2439             BN_bn2bin(s->srp_ctx.A, p);
2440             n += 2;
2441         } else {
2442             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2443                    ERR_R_INTERNAL_ERROR);
2444             goto err;
2445         }
2446         OPENSSL_free(s->session->srp_username);
2447         s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);
2448         if (s->session->srp_username == NULL) {
2449             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2450                    ERR_R_MALLOC_FAILURE);
2451             goto err;
2452         }
2453     }
2454 #endif
2455     else {
2456         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2457         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2458         goto err;
2459     }
2460
2461 #ifndef OPENSSL_NO_PSK
2462     n += pskhdrlen;
2463 #endif
2464
2465     if (!ssl_set_handshake_header(s, SSL3_MT_CLIENT_KEY_EXCHANGE, n)) {
2466         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2467         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2468         goto err;
2469     }
2470
2471     if (pms != NULL) {
2472         s->s3->tmp.pms = pms;
2473         s->s3->tmp.pmslen = pmslen;
2474     }
2475
2476     return 1;
2477  memerr:
2478     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2479     SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2480  err:
2481     OPENSSL_clear_free(pms, pmslen);
2482     s->s3->tmp.pms = NULL;
2483 #ifndef OPENSSL_NO_RSA
2484     EVP_PKEY_CTX_free(pctx);
2485 #endif
2486 #ifndef OPENSSL_NO_EC
2487     OPENSSL_free(encodedPoint);
2488 #endif
2489 #if !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)
2490     EVP_PKEY_free(ckey);
2491 #endif
2492 #ifndef OPENSSL_NO_PSK
2493     OPENSSL_clear_free(s->s3->tmp.psk, s->s3->tmp.psklen);
2494     s->s3->tmp.psk = NULL;
2495 #endif
2496     ossl_statem_set_error(s);
2497     return 0;
2498 }
2499
2500 int tls_client_key_exchange_post_work(SSL *s)
2501 {
2502     unsigned char *pms = NULL;
2503     size_t pmslen = 0;
2504
2505 #ifndef OPENSSL_NO_SRP
2506     /* Check for SRP */
2507     if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) {
2508         if (!srp_generate_client_master_secret(s)) {
2509             SSLerr(SSL_F_TLS_CLIENT_KEY_EXCHANGE_POST_WORK,
2510                    ERR_R_INTERNAL_ERROR);
2511             goto err;
2512         }
2513         return 1;
2514     }
2515 #endif
2516     pms = s->s3->tmp.pms;
2517     pmslen = s->s3->tmp.pmslen;
2518
2519     if (pms == NULL && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
2520         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2521         SSLerr(SSL_F_TLS_CLIENT_KEY_EXCHANGE_POST_WORK, ERR_R_MALLOC_FAILURE);
2522         goto err;
2523     }
2524     if (!ssl_generate_master_secret(s, pms, pmslen, 1)) {
2525         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2526         SSLerr(SSL_F_TLS_CLIENT_KEY_EXCHANGE_POST_WORK, ERR_R_INTERNAL_ERROR);
2527         goto err;
2528     }
2529
2530 #ifndef OPENSSL_NO_SCTP
2531     if (SSL_IS_DTLS(s)) {
2532         unsigned char sctpauthkey[64];
2533         char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
2534
2535         /*
2536          * Add new shared key for SCTP-Auth, will be ignored if no SCTP
2537          * used.
2538          */
2539         memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
2540                sizeof(DTLS1_SCTP_AUTH_LABEL));
2541
2542         if (SSL_export_keying_material(s, sctpauthkey,
2543                                    sizeof(sctpauthkey), labelbuffer,
2544                                    sizeof(labelbuffer), NULL, 0, 0) <= 0)
2545             goto err;
2546
2547         BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
2548                  sizeof(sctpauthkey), sctpauthkey);
2549     }
2550 #endif
2551
2552     return 1;
2553  err:
2554     OPENSSL_clear_free(pms, pmslen);
2555     s->s3->tmp.pms = NULL;
2556     return 0;
2557 }
2558
2559 int tls_construct_client_verify(SSL *s)
2560 {
2561     unsigned char *p;
2562     EVP_PKEY *pkey;
2563     const EVP_MD *md = s->s3->tmp.md[s->cert->key - s->cert->pkeys];
2564     EVP_MD_CTX *mctx;
2565     unsigned u = 0;
2566     unsigned long n = 0;
2567     long hdatalen = 0;
2568     void *hdata;
2569
2570     mctx = EVP_MD_CTX_new();
2571     if (mctx == NULL) {
2572         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_MALLOC_FAILURE);
2573         goto err;
2574     }
2575
2576     p = ssl_handshake_start(s);
2577     pkey = s->cert->key->privatekey;
2578
2579     hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
2580     if (hdatalen <= 0) {
2581         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
2582         goto err;
2583     }
2584     if (SSL_USE_SIGALGS(s)) {
2585         if (!tls12_get_sigandhash(p, pkey, md)) {
2586             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
2587             goto err;
2588         }
2589         p += 2;
2590         n = 2;
2591     }
2592 #ifdef SSL_DEBUG
2593     fprintf(stderr, "Using client alg %s\n", EVP_MD_name(md));
2594 #endif
2595     if (!EVP_SignInit_ex(mctx, md, NULL)
2596         || !EVP_SignUpdate(mctx, hdata, hdatalen)
2597         || (s->version == SSL3_VERSION
2598             && !EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
2599                                 s->session->master_key_length,
2600                                 s->session->master_key))
2601         || !EVP_SignFinal(mctx, p + 2, &u, pkey)) {
2602         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_EVP_LIB);
2603         goto err;
2604     }
2605 #ifndef OPENSSL_NO_GOST
2606     {
2607         int pktype = EVP_PKEY_id(pkey);
2608         if (pktype == NID_id_GostR3410_2001
2609             || pktype == NID_id_GostR3410_2012_256
2610             || pktype == NID_id_GostR3410_2012_512)
2611             BUF_reverse(p + 2, NULL, u);
2612     }
2613 #endif
2614
2615     s2n(u, p);
2616     n += u + 2;
2617     /* Digest cached records and discard handshake buffer */
2618     if (!ssl3_digest_cached_records(s, 0))
2619         goto err;
2620     if (!ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_VERIFY, n)) {
2621         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
2622         goto err;
2623     }
2624
2625     EVP_MD_CTX_free(mctx);
2626     return 1;
2627  err:
2628     EVP_MD_CTX_free(mctx);
2629     return 0;
2630 }
2631
2632 /*
2633  * Check a certificate can be used for client authentication. Currently check
2634  * cert exists, if we have a suitable digest for TLS 1.2 if static DH client
2635  * certificates can be used and optionally checks suitability for Suite B.
2636  */
2637 static int ssl3_check_client_certificate(SSL *s)
2638 {
2639     if (!s->cert || !s->cert->key->x509 || !s->cert->key->privatekey)
2640         return 0;
2641     /* If no suitable signature algorithm can't use certificate */
2642     if (SSL_USE_SIGALGS(s) && !s->s3->tmp.md[s->cert->key - s->cert->pkeys])
2643         return 0;
2644     /*
2645      * If strict mode check suitability of chain before using it. This also
2646      * adjusts suite B digest if necessary.
2647      */
2648     if (s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT &&
2649         !tls1_check_chain(s, NULL, NULL, NULL, -2))
2650         return 0;
2651     return 1;
2652 }
2653
2654 WORK_STATE tls_prepare_client_certificate(SSL *s, WORK_STATE wst)
2655 {
2656     X509 *x509 = NULL;
2657     EVP_PKEY *pkey = NULL;
2658     int i;
2659
2660     if (wst == WORK_MORE_A) {
2661         /* Let cert callback update client certificates if required */
2662         if (s->cert->cert_cb) {
2663             i = s->cert->cert_cb(s, s->cert->cert_cb_arg);
2664             if (i < 0) {
2665                 s->rwstate = SSL_X509_LOOKUP;
2666                 return WORK_MORE_A;
2667             }
2668             if (i == 0) {
2669                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2670                 ossl_statem_set_error(s);
2671                 return 0;
2672             }
2673             s->rwstate = SSL_NOTHING;
2674         }
2675         if (ssl3_check_client_certificate(s))
2676             return WORK_FINISHED_CONTINUE;
2677
2678         /* Fall through to WORK_MORE_B */
2679         wst = WORK_MORE_B;
2680     }
2681
2682     /* We need to get a client cert */
2683     if (wst == WORK_MORE_B) {
2684         /*
2685          * If we get an error, we need to ssl->rwstate=SSL_X509_LOOKUP;
2686          * return(-1); We then get retied later
2687          */
2688         i = ssl_do_client_cert_cb(s, &x509, &pkey);
2689         if (i < 0) {
2690             s->rwstate = SSL_X509_LOOKUP;
2691             return WORK_MORE_B;
2692         }
2693         s->rwstate = SSL_NOTHING;
2694         if ((i == 1) && (pkey != NULL) && (x509 != NULL)) {
2695             if (!SSL_use_certificate(s, x509) || !SSL_use_PrivateKey(s, pkey))
2696                 i = 0;
2697         } else if (i == 1) {
2698             i = 0;
2699             SSLerr(SSL_F_TLS_PREPARE_CLIENT_CERTIFICATE,
2700                    SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
2701         }
2702
2703         X509_free(x509);
2704         EVP_PKEY_free(pkey);
2705         if (i && !ssl3_check_client_certificate(s))
2706             i = 0;
2707         if (i == 0) {
2708             if (s->version == SSL3_VERSION) {
2709                 s->s3->tmp.cert_req = 0;
2710                 ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_CERTIFICATE);
2711                 return WORK_FINISHED_CONTINUE;
2712             } else {
2713                 s->s3->tmp.cert_req = 2;
2714                 if (!ssl3_digest_cached_records(s, 0)) {
2715                     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2716                     ossl_statem_set_error(s);
2717                     return 0;
2718                 }
2719             }
2720         }
2721
2722         return WORK_FINISHED_CONTINUE;
2723     }
2724
2725     /* Shouldn't ever get here */
2726     return WORK_ERROR;
2727 }
2728
2729 int tls_construct_client_certificate(SSL *s)
2730 {
2731     if (!ssl3_output_cert_chain(s,
2732                                 (s->s3->tmp.cert_req ==
2733                                  2) ? NULL : s->cert->key)) {
2734         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_CERTIFICATE, ERR_R_INTERNAL_ERROR);
2735         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2736         ossl_statem_set_error(s);
2737         return 0;
2738     }
2739
2740     return 1;
2741 }
2742
2743 #define has_bits(i,m)   (((i)&(m)) == (m))
2744
2745 int ssl3_check_cert_and_algorithm(SSL *s)
2746 {
2747     int i;
2748 #ifndef OPENSSL_NO_EC
2749     int idx;
2750 #endif
2751     long alg_k, alg_a;
2752     EVP_PKEY *pkey = NULL;
2753     int al = SSL_AD_HANDSHAKE_FAILURE;
2754
2755     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2756     alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2757
2758     /* we don't have a certificate */
2759     if ((alg_a & SSL_aNULL) || (alg_k & SSL_kPSK))
2760         return (1);
2761
2762     /* This is the passed certificate */
2763
2764 #ifndef OPENSSL_NO_EC
2765     idx = s->session->peer_type;
2766     if (idx == SSL_PKEY_ECC) {
2767         if (ssl_check_srvr_ecc_cert_and_alg(s->session->peer, s) == 0) {
2768             /* check failed */
2769             SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_BAD_ECC_CERT);
2770             goto f_err;
2771         } else {
2772             return 1;
2773         }
2774     } else if (alg_a & SSL_aECDSA) {
2775         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
2776                SSL_R_MISSING_ECDSA_SIGNING_CERT);
2777         goto f_err;
2778     }
2779 #endif
2780     pkey = X509_get0_pubkey(s->session->peer);
2781     i = X509_certificate_type(s->session->peer, pkey);
2782
2783     /* Check that we have a certificate if we require one */
2784     if ((alg_a & SSL_aRSA) && !has_bits(i, EVP_PK_RSA | EVP_PKT_SIGN)) {
2785         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
2786                SSL_R_MISSING_RSA_SIGNING_CERT);
2787         goto f_err;
2788     }
2789 #ifndef OPENSSL_NO_DSA
2790     else if ((alg_a & SSL_aDSS) && !has_bits(i, EVP_PK_DSA | EVP_PKT_SIGN)) {
2791         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
2792                SSL_R_MISSING_DSA_SIGNING_CERT);
2793         goto f_err;
2794     }
2795 #endif
2796 #ifndef OPENSSL_NO_RSA
2797     if (alg_k & (SSL_kRSA | SSL_kRSAPSK) &&
2798         !has_bits(i, EVP_PK_RSA | EVP_PKT_ENC)) {
2799         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
2800                SSL_R_MISSING_RSA_ENCRYPTING_CERT);
2801         goto f_err;
2802     }
2803 #endif
2804 #ifndef OPENSSL_NO_DH
2805     if ((alg_k & SSL_kDHE) && (s->s3->peer_tmp == NULL)) {
2806         al = SSL_AD_INTERNAL_ERROR;
2807         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR);
2808         goto f_err;
2809     }
2810 #endif
2811
2812     return (1);
2813  f_err:
2814     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2815     return (0);
2816 }
2817
2818 #ifndef OPENSSL_NO_NEXTPROTONEG
2819 int tls_construct_next_proto(SSL *s)
2820 {
2821     unsigned int len, padding_len;
2822     unsigned char *d;
2823
2824     len = s->next_proto_negotiated_len;
2825     padding_len = 32 - ((len + 2) % 32);
2826     d = (unsigned char *)s->init_buf->data;
2827     d[4] = len;
2828     memcpy(d + 5, s->next_proto_negotiated, len);
2829     d[5 + len] = padding_len;
2830     memset(d + 6 + len, 0, padding_len);
2831     *(d++) = SSL3_MT_NEXT_PROTO;
2832     l2n3(2 + len + padding_len, d);
2833     s->init_num = 4 + 2 + len + padding_len;
2834     s->init_off = 0;
2835
2836     return 1;
2837 }
2838 #endif
2839
2840 int ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
2841 {
2842     int i = 0;
2843 #ifndef OPENSSL_NO_ENGINE
2844     if (s->ctx->client_cert_engine) {
2845         i = ENGINE_load_ssl_client_cert(s->ctx->client_cert_engine, s,
2846                                         SSL_get_client_CA_list(s),
2847                                         px509, ppkey, NULL, NULL, NULL);
2848         if (i != 0)
2849             return i;
2850     }
2851 #endif
2852     if (s->ctx->client_cert_cb)
2853         i = s->ctx->client_cert_cb(s, px509, ppkey);
2854     return i;
2855 }
2856
2857 int ssl_cipher_list_to_bytes(SSL *s, STACK_OF(SSL_CIPHER) *sk,
2858                              unsigned char *p)
2859 {
2860     int i, j = 0;
2861     const SSL_CIPHER *c;
2862     unsigned char *q;
2863     int empty_reneg_info_scsv = !s->renegotiate;
2864     /* Set disabled masks for this session */
2865     ssl_set_client_disabled(s);
2866
2867     if (sk == NULL)
2868         return (0);
2869     q = p;
2870
2871     for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
2872         c = sk_SSL_CIPHER_value(sk, i);
2873         /* Skip disabled ciphers */
2874         if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_SUPPORTED))
2875             continue;
2876         j = s->method->put_cipher_by_char(c, p);
2877         p += j;
2878     }
2879     /*
2880      * If p == q, no ciphers; caller indicates an error. Otherwise, add
2881      * applicable SCSVs.
2882      */
2883     if (p != q) {
2884         if (empty_reneg_info_scsv) {
2885             static SSL_CIPHER scsv = {
2886                 0, NULL, SSL3_CK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
2887             };
2888             j = s->method->put_cipher_by_char(&scsv, p);
2889             p += j;
2890         }
2891         if (s->mode & SSL_MODE_SEND_FALLBACK_SCSV) {
2892             static SSL_CIPHER scsv = {
2893                 0, NULL, SSL3_CK_FALLBACK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
2894             };
2895             j = s->method->put_cipher_by_char(&scsv, p);
2896             p += j;
2897         }
2898     }
2899
2900     return (p - q);
2901 }