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