GH886: CONNECT should use HTTP/1.1
[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     /*
1147      * Now that we know the version, update the check to see if it's an allowed
1148      * version.
1149      */
1150     s->s3->tmp.min_ver = s->version;
1151     s->s3->tmp.max_ver = s->version;
1152     /*
1153      * If it is a disabled cipher we either didn't send it in client hello,
1154      * or it's not allowed for the selected protocol. So we return an error.
1155      */
1156     if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_CHECK)) {
1157         al = SSL_AD_ILLEGAL_PARAMETER;
1158         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_WRONG_CIPHER_RETURNED);
1159         goto f_err;
1160     }
1161
1162     sk = ssl_get_ciphers_by_id(s);
1163     i = sk_SSL_CIPHER_find(sk, c);
1164     if (i < 0) {
1165         /* we did not say we would use this cipher */
1166         al = SSL_AD_ILLEGAL_PARAMETER;
1167         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_WRONG_CIPHER_RETURNED);
1168         goto f_err;
1169     }
1170
1171     /*
1172      * Depending on the session caching (internal/external), the cipher
1173      * and/or cipher_id values may not be set. Make sure that cipher_id is
1174      * set and use it for comparison.
1175      */
1176     if (s->session->cipher)
1177         s->session->cipher_id = s->session->cipher->id;
1178     if (s->hit && (s->session->cipher_id != c->id)) {
1179         al = SSL_AD_ILLEGAL_PARAMETER;
1180         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1181                SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
1182         goto f_err;
1183     }
1184     s->s3->tmp.new_cipher = c;
1185     /* lets get the compression algorithm */
1186     /* COMPRESSION */
1187     if (!PACKET_get_1(pkt, &compression)) {
1188         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
1189         al = SSL_AD_DECODE_ERROR;
1190         goto f_err;
1191     }
1192 #ifdef OPENSSL_NO_COMP
1193     if (compression != 0) {
1194         al = SSL_AD_ILLEGAL_PARAMETER;
1195         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1196                SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1197         goto f_err;
1198     }
1199     /*
1200      * If compression is disabled we'd better not try to resume a session
1201      * using compression.
1202      */
1203     if (s->session->compress_meth != 0) {
1204         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
1205         goto f_err;
1206     }
1207 #else
1208     if (s->hit && compression != s->session->compress_meth) {
1209         al = SSL_AD_ILLEGAL_PARAMETER;
1210         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1211                SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED);
1212         goto f_err;
1213     }
1214     if (compression == 0)
1215         comp = NULL;
1216     else if (!ssl_allow_compression(s)) {
1217         al = SSL_AD_ILLEGAL_PARAMETER;
1218         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_COMPRESSION_DISABLED);
1219         goto f_err;
1220     } else {
1221         comp = ssl3_comp_find(s->ctx->comp_methods, compression);
1222     }
1223
1224     if (compression != 0 && comp == NULL) {
1225         al = SSL_AD_ILLEGAL_PARAMETER;
1226         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1227                SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1228         goto f_err;
1229     } else {
1230         s->s3->tmp.new_compression = comp;
1231     }
1232 #endif
1233
1234     /* TLS extensions */
1235     if (!ssl_parse_serverhello_tlsext(s, pkt)) {
1236         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_PARSE_TLSEXT);
1237         goto err;
1238     }
1239
1240     if (PACKET_remaining(pkt) != 0) {
1241         /* wrong packet length */
1242         al = SSL_AD_DECODE_ERROR;
1243         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_BAD_PACKET_LENGTH);
1244         goto f_err;
1245     }
1246
1247 #ifndef OPENSSL_NO_SCTP
1248     if (SSL_IS_DTLS(s) && s->hit) {
1249         unsigned char sctpauthkey[64];
1250         char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
1251
1252         /*
1253          * Add new shared key for SCTP-Auth, will be ignored if
1254          * no SCTP used.
1255          */
1256         memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
1257                sizeof(DTLS1_SCTP_AUTH_LABEL));
1258
1259         if (SSL_export_keying_material(s, sctpauthkey,
1260                                    sizeof(sctpauthkey),
1261                                    labelbuffer,
1262                                    sizeof(labelbuffer), NULL, 0,
1263                                    0) <= 0)
1264             goto err;
1265
1266         BIO_ctrl(SSL_get_wbio(s),
1267                  BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
1268                  sizeof(sctpauthkey), sctpauthkey);
1269     }
1270 #endif
1271
1272     return MSG_PROCESS_CONTINUE_READING;
1273  f_err:
1274     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1275  err:
1276     ossl_statem_set_error(s);
1277     return MSG_PROCESS_ERROR;
1278 }
1279
1280 MSG_PROCESS_RETURN tls_process_server_certificate(SSL *s, PACKET *pkt)
1281 {
1282     int al, i, ret = MSG_PROCESS_ERROR, exp_idx;
1283     unsigned long cert_list_len, cert_len;
1284     X509 *x = NULL;
1285     const unsigned char *certstart, *certbytes;
1286     STACK_OF(X509) *sk = NULL;
1287     EVP_PKEY *pkey = NULL;
1288
1289     if ((sk = sk_X509_new_null()) == NULL) {
1290         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, ERR_R_MALLOC_FAILURE);
1291         goto err;
1292     }
1293
1294     if (!PACKET_get_net_3(pkt, &cert_list_len)
1295             || PACKET_remaining(pkt) != cert_list_len) {
1296         al = SSL_AD_DECODE_ERROR;
1297         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
1298         goto f_err;
1299     }
1300     while (PACKET_remaining(pkt)) {
1301         if (!PACKET_get_net_3(pkt, &cert_len)
1302                 || !PACKET_get_bytes(pkt, &certbytes, cert_len)) {
1303             al = SSL_AD_DECODE_ERROR;
1304             SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1305                    SSL_R_CERT_LENGTH_MISMATCH);
1306             goto f_err;
1307         }
1308
1309         certstart = certbytes;
1310         x = d2i_X509(NULL, (const unsigned char **)&certbytes, cert_len);
1311         if (x == NULL) {
1312             al = SSL_AD_BAD_CERTIFICATE;
1313             SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, ERR_R_ASN1_LIB);
1314             goto f_err;
1315         }
1316         if (certbytes != (certstart + cert_len)) {
1317             al = SSL_AD_DECODE_ERROR;
1318             SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1319                    SSL_R_CERT_LENGTH_MISMATCH);
1320             goto f_err;
1321         }
1322         if (!sk_X509_push(sk, x)) {
1323             SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, ERR_R_MALLOC_FAILURE);
1324             goto err;
1325         }
1326         x = NULL;
1327     }
1328
1329     i = ssl_verify_cert_chain(s, sk);
1330     if (s->verify_mode != SSL_VERIFY_NONE && i <= 0) {
1331         al = ssl_verify_alarm_type(s->verify_result);
1332         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1333                SSL_R_CERTIFICATE_VERIFY_FAILED);
1334         goto f_err;
1335     }
1336     ERR_clear_error();          /* but we keep s->verify_result */
1337     if (i > 1) {
1338         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, i);
1339         al = SSL_AD_HANDSHAKE_FAILURE;
1340         goto f_err;
1341     }
1342
1343     s->session->peer_chain = sk;
1344     /*
1345      * Inconsistency alert: cert_chain does include the peer's certificate,
1346      * which we don't include in s3_srvr.c
1347      */
1348     x = sk_X509_value(sk, 0);
1349     sk = NULL;
1350     /*
1351      * VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end
1352      */
1353
1354     pkey = X509_get0_pubkey(x);
1355
1356     if (pkey == NULL || EVP_PKEY_missing_parameters(pkey)) {
1357         x = NULL;
1358         al = SSL3_AL_FATAL;
1359         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1360                SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
1361         goto f_err;
1362     }
1363
1364     i = ssl_cert_type(x, pkey);
1365     if (i < 0) {
1366         x = NULL;
1367         al = SSL3_AL_FATAL;
1368         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1369                SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1370         goto f_err;
1371     }
1372
1373     exp_idx = ssl_cipher_get_cert_index(s->s3->tmp.new_cipher);
1374     if (exp_idx >= 0 && i != exp_idx
1375             && (exp_idx != SSL_PKEY_GOST_EC ||
1376                 (i != SSL_PKEY_GOST12_512 && i != SSL_PKEY_GOST12_256
1377                  && i != SSL_PKEY_GOST01))) {
1378         x = NULL;
1379         al = SSL_AD_ILLEGAL_PARAMETER;
1380         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1381                SSL_R_WRONG_CERTIFICATE_TYPE);
1382         goto f_err;
1383     }
1384     s->session->peer_type = i;
1385
1386     X509_free(s->session->peer);
1387     X509_up_ref(x);
1388     s->session->peer = x;
1389     s->session->verify_result = s->verify_result;
1390
1391     x = NULL;
1392     ret = MSG_PROCESS_CONTINUE_READING;
1393     goto done;
1394
1395  f_err:
1396     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1397  err:
1398     ossl_statem_set_error(s);
1399  done:
1400     X509_free(x);
1401     sk_X509_pop_free(sk, X509_free);
1402     return ret;
1403 }
1404
1405 MSG_PROCESS_RETURN tls_process_key_exchange(SSL *s, PACKET *pkt)
1406 {
1407     EVP_MD_CTX *md_ctx;
1408     int al, j;
1409     long alg_k, alg_a;
1410     EVP_PKEY *pkey = NULL;
1411     const EVP_MD *md = NULL;
1412 #ifndef OPENSSL_NO_RSA
1413     RSA *rsa = NULL;
1414 #endif
1415 #ifndef OPENSSL_NO_EC
1416     EVP_PKEY_CTX *pctx = NULL;
1417 #endif
1418     PACKET save_param_start, signature;
1419
1420     md_ctx = EVP_MD_CTX_new();
1421     if (md_ctx == NULL) {
1422         al = SSL_AD_INTERNAL_ERROR;
1423         SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1424         goto f_err;
1425     }
1426
1427     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1428
1429     save_param_start = *pkt;
1430
1431 #if !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)
1432     EVP_PKEY_free(s->s3->peer_tmp);
1433     s->s3->peer_tmp = NULL;
1434 #endif
1435
1436     alg_a = s->s3->tmp.new_cipher->algorithm_auth;
1437
1438     al = SSL_AD_DECODE_ERROR;
1439
1440 #ifndef OPENSSL_NO_PSK
1441     /* PSK ciphersuites are preceded by an identity hint */
1442     if (alg_k & SSL_PSK) {
1443         PACKET psk_identity_hint;
1444         if (!PACKET_get_length_prefixed_2(pkt, &psk_identity_hint)) {
1445             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
1446             goto f_err;
1447         }
1448
1449         /*
1450          * Store PSK identity hint for later use, hint is used in
1451          * ssl3_send_client_key_exchange.  Assume that the maximum length of
1452          * a PSK identity hint can be as long as the maximum length of a PSK
1453          * identity.
1454          */
1455         if (PACKET_remaining(&psk_identity_hint) > PSK_MAX_IDENTITY_LEN) {
1456             al = SSL_AD_HANDSHAKE_FAILURE;
1457             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG);
1458             goto f_err;
1459         }
1460
1461         if (PACKET_remaining(&psk_identity_hint) == 0) {
1462             OPENSSL_free(s->session->psk_identity_hint);
1463             s->session->psk_identity_hint = NULL;
1464         } else if (!PACKET_strndup(&psk_identity_hint,
1465                             &s->session->psk_identity_hint)) {
1466             al = SSL_AD_INTERNAL_ERROR;
1467             goto f_err;
1468         }
1469     }
1470
1471     /* Nothing else to do for plain PSK or RSAPSK */
1472     if (alg_k & (SSL_kPSK | SSL_kRSAPSK)) {
1473     } else
1474 #endif                          /* !OPENSSL_NO_PSK */
1475     /*
1476      * Dummy "if" to ensure sane C code in the event of various OPENSSL_NO_*
1477      * options
1478      */
1479     if (0) {
1480     }
1481 #ifndef OPENSSL_NO_SRP
1482     else if (alg_k & SSL_kSRP) {
1483         PACKET prime, generator, salt, server_pub;
1484         if (!PACKET_get_length_prefixed_2(pkt, &prime)
1485             || !PACKET_get_length_prefixed_2(pkt, &generator)
1486             || !PACKET_get_length_prefixed_1(pkt, &salt)
1487             || !PACKET_get_length_prefixed_2(pkt, &server_pub)) {
1488             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
1489             goto f_err;
1490         }
1491
1492         if ((s->srp_ctx.N =
1493              BN_bin2bn(PACKET_data(&prime),
1494                        PACKET_remaining(&prime), NULL)) == NULL
1495             || (s->srp_ctx.g =
1496                 BN_bin2bn(PACKET_data(&generator),
1497                           PACKET_remaining(&generator), NULL)) == NULL
1498             || (s->srp_ctx.s =
1499                 BN_bin2bn(PACKET_data(&salt),
1500                           PACKET_remaining(&salt), NULL)) == NULL
1501             || (s->srp_ctx.B =
1502                 BN_bin2bn(PACKET_data(&server_pub),
1503                           PACKET_remaining(&server_pub), NULL)) == NULL) {
1504             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_BN_LIB);
1505             goto err;
1506         }
1507
1508         if (!srp_verify_server_param(s, &al)) {
1509             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_BAD_SRP_PARAMETERS);
1510             goto f_err;
1511         }
1512
1513 /* We must check if there is a certificate */
1514         if (alg_a & (SSL_aRSA|SSL_aDSS))
1515             pkey = X509_get0_pubkey(s->session->peer);
1516     }
1517 #endif                          /* !OPENSSL_NO_SRP */
1518 #ifndef OPENSSL_NO_DH
1519     else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
1520         PACKET prime, generator, pub_key;
1521
1522         DH *dh;
1523
1524         if (!PACKET_get_length_prefixed_2(pkt, &prime)
1525             || !PACKET_get_length_prefixed_2(pkt, &generator)
1526             || !PACKET_get_length_prefixed_2(pkt, &pub_key)) {
1527             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
1528             goto f_err;
1529         }
1530
1531         s->s3->peer_tmp = EVP_PKEY_new();
1532         dh = DH_new();
1533
1534         if (s->s3->peer_tmp == NULL || dh == NULL) {
1535             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1536             DH_free(dh);
1537             goto err;
1538         }
1539
1540         if (EVP_PKEY_assign_DH(s->s3->peer_tmp, dh) == 0) {
1541             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_EVP_LIB);
1542             DH_free(dh);
1543             goto err;
1544         }
1545
1546         if ((dh->p = BN_bin2bn(PACKET_data(&prime),
1547                                PACKET_remaining(&prime), NULL)) == NULL
1548             || (dh->g = BN_bin2bn(PACKET_data(&generator),
1549                                   PACKET_remaining(&generator), NULL)) == NULL
1550             || (dh->pub_key =
1551                 BN_bin2bn(PACKET_data(&pub_key),
1552                           PACKET_remaining(&pub_key), NULL)) == NULL) {
1553             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_BN_LIB);
1554             goto err;
1555         }
1556
1557         if (BN_is_zero(dh->p) || BN_is_zero(dh->g) || BN_is_zero(dh->pub_key)) {
1558             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_BAD_DH_VALUE);
1559             goto f_err;
1560         }
1561
1562         if (!ssl_security(s, SSL_SECOP_TMP_DH, DH_security_bits(dh), 0, dh)) {
1563             al = SSL_AD_HANDSHAKE_FAILURE;
1564             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_DH_KEY_TOO_SMALL);
1565             goto f_err;
1566         }
1567         if (alg_a & (SSL_aRSA|SSL_aDSS))
1568             pkey = X509_get0_pubkey(s->session->peer);
1569         /* else anonymous DH, so no certificate or pkey. */
1570     }
1571 #endif                          /* !OPENSSL_NO_DH */
1572
1573 #ifndef OPENSSL_NO_EC
1574     else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
1575         PACKET encoded_pt;
1576         const unsigned char *ecparams;
1577         int curve_nid;
1578
1579         /*
1580          * Extract elliptic curve parameters and the server's ephemeral ECDH
1581          * public key. For now we only support named (not generic) curves and
1582          * ECParameters in this case is just three bytes.
1583          */
1584         if (!PACKET_get_bytes(pkt, &ecparams, 3)) {
1585             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1586             goto f_err;
1587         }
1588         /*
1589          * Check curve is one of our preferences, if not server has sent an
1590          * invalid curve. ECParameters is 3 bytes.
1591          */
1592         if (!tls1_check_curve(s, ecparams, 3)) {
1593             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_WRONG_CURVE);
1594             goto f_err;
1595         }
1596
1597         curve_nid = tls1_ec_curve_id2nid(*(ecparams + 2));
1598         if (curve_nid  == 0) {
1599             al = SSL_AD_INTERNAL_ERROR;
1600             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE,
1601                    SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
1602             goto f_err;
1603         }
1604
1605         /* Set up EVP_PKEY with named curve as parameters */
1606         pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL);
1607         if (pctx == NULL
1608             || EVP_PKEY_paramgen_init(pctx) <= 0
1609             || EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx, curve_nid) <= 0
1610             || EVP_PKEY_paramgen(pctx, &s->s3->peer_tmp) <= 0) {
1611             al = SSL_AD_INTERNAL_ERROR;
1612             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_EVP_LIB);
1613             goto f_err;
1614         }
1615         EVP_PKEY_CTX_free(pctx);
1616         pctx = NULL;
1617
1618         if (!PACKET_get_length_prefixed_1(pkt, &encoded_pt)) {
1619             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
1620             goto f_err;
1621         }
1622
1623         if (EC_KEY_oct2key(EVP_PKEY_get0_EC_KEY(s->s3->peer_tmp),
1624                            PACKET_data(&encoded_pt),
1625                            PACKET_remaining(&encoded_pt), NULL) == 0) {
1626             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_BAD_ECPOINT);
1627             goto f_err;
1628         }
1629
1630         /*
1631          * The ECC/TLS specification does not mention the use of DSA to sign
1632          * ECParameters in the server key exchange message. We do support RSA
1633          * and ECDSA.
1634          */
1635         if (0) ;
1636 # ifndef OPENSSL_NO_RSA
1637         else if (alg_a & SSL_aRSA)
1638             pkey = X509_get0_pubkey(s->session->peer);
1639 # endif
1640 # ifndef OPENSSL_NO_EC
1641         else if (alg_a & SSL_aECDSA)
1642             pkey = X509_get0_pubkey(s->session->peer);
1643 # endif
1644         /* else anonymous ECDH, so no certificate or pkey. */
1645     } else if (alg_k) {
1646         al = SSL_AD_UNEXPECTED_MESSAGE;
1647         SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
1648         goto f_err;
1649     }
1650 #endif                          /* !OPENSSL_NO_EC */
1651
1652     /* if it was signed, check the signature */
1653     if (pkey != NULL) {
1654         PACKET params;
1655         /*
1656          * |pkt| now points to the beginning of the signature, so the difference
1657          * equals the length of the parameters.
1658          */
1659         if (!PACKET_get_sub_packet(&save_param_start, &params,
1660                                    PACKET_remaining(&save_param_start) -
1661                                    PACKET_remaining(pkt))) {
1662             al = SSL_AD_INTERNAL_ERROR;
1663             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1664             goto f_err;
1665         }
1666
1667         if (SSL_USE_SIGALGS(s)) {
1668             const unsigned char *sigalgs;
1669             int rv;
1670             if (!PACKET_get_bytes(pkt, &sigalgs, 2)) {
1671                 SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1672                 goto f_err;
1673             }
1674             rv = tls12_check_peer_sigalg(&md, s, sigalgs, pkey);
1675             if (rv == -1)
1676                 goto err;
1677             else if (rv == 0) {
1678                 goto f_err;
1679             }
1680 #ifdef SSL_DEBUG
1681             fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
1682 #endif
1683         } else if (EVP_PKEY_id(pkey) == EVP_PKEY_RSA) {
1684             md = EVP_md5_sha1();
1685         } else {
1686             md = EVP_sha1();
1687         }
1688
1689         if (!PACKET_get_length_prefixed_2(pkt, &signature)
1690             || PACKET_remaining(pkt) != 0) {
1691             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
1692             goto f_err;
1693         }
1694         j = EVP_PKEY_size(pkey);
1695         if (j < 0) {
1696             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1697             goto f_err;
1698         }
1699
1700         /*
1701          * Check signature length
1702          */
1703         if (PACKET_remaining(&signature) > (size_t)j) {
1704             /* wrong packet length */
1705             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_WRONG_SIGNATURE_LENGTH);
1706             goto f_err;
1707         }
1708         if (EVP_VerifyInit_ex(md_ctx, md, NULL) <= 0
1709                 || EVP_VerifyUpdate(md_ctx, &(s->s3->client_random[0]),
1710                                     SSL3_RANDOM_SIZE) <= 0
1711                 || EVP_VerifyUpdate(md_ctx, &(s->s3->server_random[0]),
1712                                     SSL3_RANDOM_SIZE) <= 0
1713                 || EVP_VerifyUpdate(md_ctx, PACKET_data(&params),
1714                                     PACKET_remaining(&params)) <= 0) {
1715             al = SSL_AD_INTERNAL_ERROR;
1716             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_EVP_LIB);
1717             goto f_err;
1718         }
1719         if (EVP_VerifyFinal(md_ctx, PACKET_data(&signature),
1720                             PACKET_remaining(&signature), pkey) <= 0) {
1721             /* bad signature */
1722             al = SSL_AD_DECRYPT_ERROR;
1723             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_BAD_SIGNATURE);
1724             goto f_err;
1725         }
1726     } else {
1727         /* aNULL, aSRP or PSK do not need public keys */
1728         if (!(alg_a & (SSL_aNULL | SSL_aSRP)) && !(alg_k & SSL_PSK)) {
1729             /* Might be wrong key type, check it */
1730             if (ssl3_check_cert_and_algorithm(s))
1731                 /* Otherwise this shouldn't happen */
1732                 SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1733             goto err;
1734         }
1735         /* still data left over */
1736         if (PACKET_remaining(pkt) != 0) {
1737             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_EXTRA_DATA_IN_MESSAGE);
1738             goto f_err;
1739         }
1740     }
1741     EVP_MD_CTX_free(md_ctx);
1742     return MSG_PROCESS_CONTINUE_READING;
1743  f_err:
1744     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1745  err:
1746 #ifndef OPENSSL_NO_RSA
1747     RSA_free(rsa);
1748 #endif
1749 #ifndef OPENSSL_NO_EC
1750     EVP_PKEY_CTX_free(pctx);
1751 #endif
1752     EVP_MD_CTX_free(md_ctx);
1753     ossl_statem_set_error(s);
1754     return MSG_PROCESS_ERROR;
1755 }
1756
1757 MSG_PROCESS_RETURN tls_process_certificate_request(SSL *s, PACKET *pkt)
1758 {
1759     int ret = MSG_PROCESS_ERROR;
1760     unsigned int list_len, ctype_num, i, name_len;
1761     X509_NAME *xn = NULL;
1762     const unsigned char *data;
1763     const unsigned char *namestart, *namebytes;
1764     STACK_OF(X509_NAME) *ca_sk = NULL;
1765
1766     if ((ca_sk = sk_X509_NAME_new(ca_dn_cmp)) == NULL) {
1767         SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
1768         goto err;
1769     }
1770
1771     /* get the certificate types */
1772     if (!PACKET_get_1(pkt, &ctype_num)
1773             || !PACKET_get_bytes(pkt, &data, ctype_num)) {
1774         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1775         SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, SSL_R_LENGTH_MISMATCH);
1776         goto err;
1777     }
1778     OPENSSL_free(s->cert->ctypes);
1779     s->cert->ctypes = NULL;
1780     if (ctype_num > SSL3_CT_NUMBER) {
1781         /* If we exceed static buffer copy all to cert structure */
1782         s->cert->ctypes = OPENSSL_malloc(ctype_num);
1783         if (s->cert->ctypes == NULL) {
1784             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
1785             goto err;
1786         }
1787         memcpy(s->cert->ctypes, data, ctype_num);
1788         s->cert->ctype_num = (size_t)ctype_num;
1789         ctype_num = SSL3_CT_NUMBER;
1790     }
1791     for (i = 0; i < ctype_num; i++)
1792         s->s3->tmp.ctype[i] = data[i];
1793
1794     if (SSL_USE_SIGALGS(s)) {
1795         if (!PACKET_get_net_2(pkt, &list_len)
1796                 || !PACKET_get_bytes(pkt, &data, list_len)) {
1797             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1798             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST,
1799                    SSL_R_LENGTH_MISMATCH);
1800             goto err;
1801         }
1802
1803         /* Clear certificate digests and validity flags */
1804         for (i = 0; i < SSL_PKEY_NUM; i++) {
1805             s->s3->tmp.md[i] = NULL;
1806             s->s3->tmp.valid_flags[i] = 0;
1807         }
1808         if ((list_len & 1) || !tls1_save_sigalgs(s, data, list_len)) {
1809             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1810             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST,
1811                    SSL_R_SIGNATURE_ALGORITHMS_ERROR);
1812             goto err;
1813         }
1814         if (!tls1_process_sigalgs(s)) {
1815             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1816             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
1817             goto err;
1818         }
1819     } else {
1820         ssl_set_default_md(s);
1821     }
1822
1823     /* get the CA RDNs */
1824     if (!PACKET_get_net_2(pkt, &list_len)
1825             || PACKET_remaining(pkt) != list_len) {
1826         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1827         SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, SSL_R_LENGTH_MISMATCH);
1828         goto err;
1829     }
1830
1831     while (PACKET_remaining(pkt)) {
1832         if (!PACKET_get_net_2(pkt, &name_len)
1833                 || !PACKET_get_bytes(pkt, &namebytes, name_len)) {
1834             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1835             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST,
1836                    SSL_R_LENGTH_MISMATCH);
1837             goto err;
1838         }
1839
1840         namestart = namebytes;
1841
1842         if ((xn = d2i_X509_NAME(NULL, (const unsigned char **)&namebytes,
1843                                 name_len)) == NULL) {
1844             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1845             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_ASN1_LIB);
1846             goto err;
1847         }
1848
1849         if (namebytes != (namestart + name_len)) {
1850             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1851             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST,
1852                    SSL_R_CA_DN_LENGTH_MISMATCH);
1853             goto err;
1854         }
1855         if (!sk_X509_NAME_push(ca_sk, xn)) {
1856             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
1857             goto err;
1858         }
1859     }
1860
1861     /* we should setup a certificate to return.... */
1862     s->s3->tmp.cert_req = 1;
1863     s->s3->tmp.ctype_num = ctype_num;
1864     sk_X509_NAME_pop_free(s->s3->tmp.ca_names, X509_NAME_free);
1865     s->s3->tmp.ca_names = ca_sk;
1866     ca_sk = NULL;
1867
1868     ret = MSG_PROCESS_CONTINUE_READING;
1869     goto done;
1870  err:
1871     ossl_statem_set_error(s);
1872  done:
1873     sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
1874     return ret;
1875 }
1876
1877 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
1878 {
1879     return (X509_NAME_cmp(*a, *b));
1880 }
1881
1882 MSG_PROCESS_RETURN tls_process_new_session_ticket(SSL *s, PACKET *pkt)
1883 {
1884     int al;
1885     unsigned int ticklen;
1886     unsigned long ticket_lifetime_hint;
1887
1888     if (!PACKET_get_net_4(pkt, &ticket_lifetime_hint)
1889             || !PACKET_get_net_2(pkt, &ticklen)
1890             || PACKET_remaining(pkt) != ticklen) {
1891         al = SSL_AD_DECODE_ERROR;
1892         SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
1893         goto f_err;
1894     }
1895
1896     /* Server is allowed to change its mind and send an empty ticket. */
1897     if (ticklen == 0)
1898         return MSG_PROCESS_CONTINUE_READING;
1899
1900     if (s->session->session_id_length > 0) {
1901         int i = s->session_ctx->session_cache_mode;
1902         SSL_SESSION *new_sess;
1903         /*
1904          * We reused an existing session, so we need to replace it with a new
1905          * one
1906          */
1907         if (i & SSL_SESS_CACHE_CLIENT) {
1908             /*
1909              * Remove the old session from the cache
1910              */
1911             if (i & SSL_SESS_CACHE_NO_INTERNAL_STORE) {
1912                 if (s->session_ctx->remove_session_cb != NULL)
1913                     s->session_ctx->remove_session_cb(s->session_ctx,
1914                                                       s->session);
1915             } else {
1916                 /* We carry on if this fails */
1917                 SSL_CTX_remove_session(s->session_ctx, s->session);
1918             }
1919         }
1920
1921         if ((new_sess = ssl_session_dup(s->session, 0)) == 0) {
1922             al = SSL_AD_INTERNAL_ERROR;
1923             SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
1924             goto f_err;
1925         }
1926
1927         SSL_SESSION_free(s->session);
1928         s->session = new_sess;
1929     }
1930
1931     OPENSSL_free(s->session->tlsext_tick);
1932     s->session->tlsext_ticklen = 0;
1933
1934     s->session->tlsext_tick = OPENSSL_malloc(ticklen);
1935     if (s->session->tlsext_tick == NULL) {
1936         SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
1937         goto err;
1938     }
1939     if (!PACKET_copy_bytes(pkt, s->session->tlsext_tick, ticklen)) {
1940         al = SSL_AD_DECODE_ERROR;
1941         SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
1942         goto f_err;
1943     }
1944
1945     s->session->tlsext_tick_lifetime_hint = ticket_lifetime_hint;
1946     s->session->tlsext_ticklen = ticklen;
1947     /*
1948      * There are two ways to detect a resumed ticket session. One is to set
1949      * an appropriate session ID and then the server must return a match in
1950      * ServerHello. This allows the normal client session ID matching to work
1951      * and we know much earlier that the ticket has been accepted. The
1952      * other way is to set zero length session ID when the ticket is
1953      * presented and rely on the handshake to determine session resumption.
1954      * We choose the former approach because this fits in with assumptions
1955      * elsewhere in OpenSSL. The session ID is set to the SHA256 (or SHA1 is
1956      * SHA256 is disabled) hash of the ticket.
1957      */
1958     EVP_Digest(s->session->tlsext_tick, ticklen,
1959                s->session->session_id, &s->session->session_id_length,
1960                EVP_sha256(), NULL);
1961     return MSG_PROCESS_CONTINUE_READING;
1962  f_err:
1963     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1964  err:
1965     ossl_statem_set_error(s);
1966     return MSG_PROCESS_ERROR;
1967 }
1968
1969 MSG_PROCESS_RETURN tls_process_cert_status(SSL *s, PACKET *pkt)
1970 {
1971     int al;
1972     unsigned long resplen;
1973     unsigned int type;
1974
1975     if (!PACKET_get_1(pkt, &type)
1976             || type != TLSEXT_STATUSTYPE_ocsp) {
1977         al = SSL_AD_DECODE_ERROR;
1978         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, SSL_R_UNSUPPORTED_STATUS_TYPE);
1979         goto f_err;
1980     }
1981     if (!PACKET_get_net_3(pkt, &resplen)
1982             || PACKET_remaining(pkt) != resplen) {
1983         al = SSL_AD_DECODE_ERROR;
1984         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, SSL_R_LENGTH_MISMATCH);
1985         goto f_err;
1986     }
1987     s->tlsext_ocsp_resp = OPENSSL_malloc(resplen);
1988     if (s->tlsext_ocsp_resp == NULL) {
1989         al = SSL_AD_INTERNAL_ERROR;
1990         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, ERR_R_MALLOC_FAILURE);
1991         goto f_err;
1992     }
1993     if (!PACKET_copy_bytes(pkt, s->tlsext_ocsp_resp, resplen)) {
1994         al = SSL_AD_DECODE_ERROR;
1995         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, SSL_R_LENGTH_MISMATCH);
1996         goto f_err;
1997     }
1998     s->tlsext_ocsp_resplen = resplen;
1999     return MSG_PROCESS_CONTINUE_READING;
2000  f_err:
2001     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2002     ossl_statem_set_error(s);
2003     return MSG_PROCESS_ERROR;
2004 }
2005
2006 MSG_PROCESS_RETURN tls_process_server_done(SSL *s, PACKET *pkt)
2007 {
2008     if (PACKET_remaining(pkt) > 0) {
2009         /* should contain no data */
2010         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2011         SSLerr(SSL_F_TLS_PROCESS_SERVER_DONE, SSL_R_LENGTH_MISMATCH);
2012         ossl_statem_set_error(s);
2013         return MSG_PROCESS_ERROR;
2014     }
2015
2016 #ifndef OPENSSL_NO_SRP
2017     if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) {
2018         if (SRP_Calc_A_param(s) <= 0) {
2019             SSLerr(SSL_F_TLS_PROCESS_SERVER_DONE, SSL_R_SRP_A_CALC);
2020             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2021             ossl_statem_set_error(s);
2022             return MSG_PROCESS_ERROR;
2023         }
2024     }
2025 #endif
2026
2027     /*
2028      * at this point we check that we have the required stuff from
2029      * the server
2030      */
2031     if (!ssl3_check_cert_and_algorithm(s)) {
2032         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2033         ossl_statem_set_error(s);
2034         return MSG_PROCESS_ERROR;
2035     }
2036
2037     /*
2038      * Call the ocsp status callback if needed. The |tlsext_ocsp_resp| and
2039      * |tlsext_ocsp_resplen| values will be set if we actually received a status
2040      * message, or NULL and -1 otherwise
2041      */
2042     if (s->tlsext_status_type != -1 && s->ctx->tlsext_status_cb != NULL) {
2043         int ret;
2044         ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
2045         if (ret == 0) {
2046             ssl3_send_alert(s, SSL3_AL_FATAL,
2047                             SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE);
2048             SSLerr(SSL_F_TLS_PROCESS_SERVER_DONE,
2049                    SSL_R_INVALID_STATUS_RESPONSE);
2050             return MSG_PROCESS_ERROR;
2051         }
2052         if (ret < 0) {
2053             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2054             SSLerr(SSL_F_TLS_PROCESS_SERVER_DONE, ERR_R_MALLOC_FAILURE);
2055             return MSG_PROCESS_ERROR;
2056         }
2057     }
2058
2059 #ifndef OPENSSL_NO_CT
2060     if (s->ct_validation_callback != NULL) {
2061         if (!ssl_validate_ct(s)) {
2062             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2063             return MSG_PROCESS_ERROR;
2064         }
2065     }
2066 #endif
2067
2068 #ifndef OPENSSL_NO_SCTP
2069     /* Only applies to renegotiation */
2070     if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))
2071             && s->renegotiate != 0)
2072         return MSG_PROCESS_CONTINUE_PROCESSING;
2073     else
2074 #endif
2075         return MSG_PROCESS_FINISHED_READING;
2076 }
2077
2078 int tls_construct_client_key_exchange(SSL *s)
2079 {
2080     unsigned char *p;
2081     int n;
2082 #ifndef OPENSSL_NO_PSK
2083     size_t pskhdrlen = 0;
2084 #endif
2085     unsigned long alg_k;
2086 #ifndef OPENSSL_NO_RSA
2087     unsigned char *q;
2088     EVP_PKEY *pkey = NULL;
2089     EVP_PKEY_CTX *pctx = NULL;
2090 #endif
2091 #if !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)
2092     EVP_PKEY *ckey = NULL, *skey = NULL;
2093 #endif
2094 #ifndef OPENSSL_NO_EC
2095     unsigned char *encodedPoint = NULL;
2096     int encoded_pt_len = 0;
2097 #endif
2098     unsigned char *pms = NULL;
2099     size_t pmslen = 0;
2100     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2101
2102     p = ssl_handshake_start(s);
2103
2104
2105 #ifndef OPENSSL_NO_PSK
2106     if (alg_k & SSL_PSK) {
2107         int psk_err = 1;
2108         /*
2109          * The callback needs PSK_MAX_IDENTITY_LEN + 1 bytes to return a
2110          * \0-terminated identity. The last byte is for us for simulating
2111          * strnlen.
2112          */
2113         char identity[PSK_MAX_IDENTITY_LEN + 1];
2114         size_t identitylen;
2115         unsigned char psk[PSK_MAX_PSK_LEN];
2116         size_t psklen;
2117
2118         if (s->psk_client_callback == NULL) {
2119             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2120                    SSL_R_PSK_NO_CLIENT_CB);
2121             goto err;
2122         }
2123
2124         memset(identity, 0, sizeof(identity));
2125
2126         psklen = s->psk_client_callback(s, s->session->psk_identity_hint,
2127                                         identity, sizeof(identity) - 1,
2128                                         psk, sizeof(psk));
2129
2130         if (psklen > PSK_MAX_PSK_LEN) {
2131             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2132                    ERR_R_INTERNAL_ERROR);
2133             goto psk_err;
2134         } else if (psklen == 0) {
2135             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2136                    SSL_R_PSK_IDENTITY_NOT_FOUND);
2137             goto psk_err;
2138         }
2139         OPENSSL_free(s->s3->tmp.psk);
2140         s->s3->tmp.psk = OPENSSL_memdup(psk, psklen);
2141         OPENSSL_cleanse(psk, psklen);
2142
2143         if (s->s3->tmp.psk == NULL) {
2144             OPENSSL_cleanse(identity, sizeof(identity));
2145             goto memerr;
2146         }
2147
2148         s->s3->tmp.psklen = psklen;
2149         identitylen = strlen(identity);
2150         if (identitylen > PSK_MAX_IDENTITY_LEN) {
2151             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2152                    ERR_R_INTERNAL_ERROR);
2153             goto psk_err;
2154         }
2155         OPENSSL_free(s->session->psk_identity);
2156         s->session->psk_identity = OPENSSL_strdup(identity);
2157         if (s->session->psk_identity == NULL) {
2158             OPENSSL_cleanse(identity, sizeof(identity));
2159             goto memerr;
2160         }
2161
2162         s2n(identitylen, p);
2163         memcpy(p, identity, identitylen);
2164         pskhdrlen = 2 + identitylen;
2165         p += identitylen;
2166         psk_err = 0;
2167 psk_err:
2168         OPENSSL_cleanse(identity, sizeof(identity));
2169         if (psk_err != 0) {
2170             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2171             goto err;
2172         }
2173     }
2174     if (alg_k & SSL_kPSK) {
2175         n = 0;
2176     } else
2177 #endif
2178
2179     /* Fool emacs indentation */
2180     if (0) {
2181     }
2182 #ifndef OPENSSL_NO_RSA
2183     else if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
2184         size_t enclen;
2185         pmslen = SSL_MAX_MASTER_KEY_LENGTH;
2186         pms = OPENSSL_malloc(pmslen);
2187         if (pms == NULL)
2188             goto memerr;
2189
2190         if (s->session->peer == NULL) {
2191             /*
2192              * We should always have a server certificate with SSL_kRSA.
2193              */
2194             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2195                    ERR_R_INTERNAL_ERROR);
2196             goto err;
2197         }
2198
2199         pkey = X509_get0_pubkey(s->session->peer);
2200         if (EVP_PKEY_get0_RSA(pkey) == NULL) {
2201             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2202                    ERR_R_INTERNAL_ERROR);
2203             goto err;
2204         }
2205
2206         pms[0] = s->client_version >> 8;
2207         pms[1] = s->client_version & 0xff;
2208         if (RAND_bytes(pms + 2, pmslen - 2) <= 0)
2209             goto err;
2210
2211         q = p;
2212         /* Fix buf for TLS and beyond */
2213         if (s->version > SSL3_VERSION)
2214             p += 2;
2215         pctx = EVP_PKEY_CTX_new(pkey, NULL);
2216         if (pctx == NULL || EVP_PKEY_encrypt_init(pctx) <= 0
2217             || EVP_PKEY_encrypt(pctx, NULL, &enclen, pms, pmslen) <= 0) {
2218             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2219                    ERR_R_EVP_LIB);
2220             goto err;
2221         }
2222         if (EVP_PKEY_encrypt(pctx, p, &enclen, pms, pmslen) <= 0) {
2223             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2224                    SSL_R_BAD_RSA_ENCRYPT);
2225             goto err;
2226         }
2227         n = enclen;
2228         EVP_PKEY_CTX_free(pctx);
2229         pctx = NULL;
2230 # ifdef PKCS1_CHECK
2231         if (s->options & SSL_OP_PKCS1_CHECK_1)
2232             p[1]++;
2233         if (s->options & SSL_OP_PKCS1_CHECK_2)
2234             tmp_buf[0] = 0x70;
2235 # endif
2236
2237         /* Fix buf for TLS and beyond */
2238         if (s->version > SSL3_VERSION) {
2239             s2n(n, q);
2240             n += 2;
2241         }
2242     }
2243 #endif
2244 #ifndef OPENSSL_NO_DH
2245     else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
2246         DH *dh_clnt = NULL;
2247         skey = s->s3->peer_tmp;
2248         if (skey == NULL) {
2249             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2250                    ERR_R_INTERNAL_ERROR);
2251             goto err;
2252         }
2253         ckey = ssl_generate_pkey(skey, NID_undef);
2254         dh_clnt = EVP_PKEY_get0_DH(ckey);
2255
2256         if (dh_clnt == NULL || ssl_derive(s, ckey, skey) == 0) {
2257             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2258                    ERR_R_INTERNAL_ERROR);
2259             goto err;
2260         }
2261
2262
2263         /* send off the data */
2264         n = BN_num_bytes(dh_clnt->pub_key);
2265         s2n(n, p);
2266         BN_bn2bin(dh_clnt->pub_key, p);
2267         n += 2;
2268         EVP_PKEY_free(ckey);
2269         ckey = NULL;
2270     }
2271 #endif
2272
2273 #ifndef OPENSSL_NO_EC
2274     else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
2275
2276         skey = s->s3->peer_tmp;
2277         if ((skey == NULL) || EVP_PKEY_get0_EC_KEY(skey) == NULL) {
2278             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2279                        ERR_R_INTERNAL_ERROR);
2280             goto err;
2281             }
2282
2283         ckey = ssl_generate_pkey(skey, NID_undef);
2284
2285         if (ssl_derive(s, ckey, skey) == 0) {
2286             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_EVP_LIB);
2287             goto err;
2288         }
2289
2290         /* Generate encoding of client key */
2291         encoded_pt_len = EC_KEY_key2buf(EVP_PKEY_get0_EC_KEY(ckey),
2292                                         POINT_CONVERSION_UNCOMPRESSED,
2293                                         &encodedPoint, NULL);
2294
2295         if (encoded_pt_len == 0) {
2296             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2297             goto err;
2298         }
2299
2300         EVP_PKEY_free(ckey);
2301         ckey = NULL;
2302
2303         n = encoded_pt_len;
2304
2305         *p = n;         /* length of encoded point */
2306         /* Encoded point will be copied here */
2307         p += 1;
2308         /* copy the point */
2309         memcpy(p, encodedPoint, n);
2310         /* increment n to account for length field */
2311         n += 1;
2312
2313         /* Free allocated memory */
2314         OPENSSL_free(encodedPoint);
2315     }
2316 #endif                          /* !OPENSSL_NO_EC */
2317 #ifndef OPENSSL_NO_GOST
2318     else if (alg_k & SSL_kGOST) {
2319         /* GOST key exchange message creation */
2320         EVP_PKEY_CTX *pkey_ctx;
2321         X509 *peer_cert;
2322         size_t msglen;
2323         unsigned int md_len;
2324         unsigned char shared_ukm[32], tmp[256];
2325         EVP_MD_CTX *ukm_hash;
2326         int dgst_nid = NID_id_GostR3411_94;
2327         if ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aGOST12) != 0)
2328             dgst_nid = NID_id_GostR3411_2012_256;
2329
2330
2331         pmslen = 32;
2332         pms = OPENSSL_malloc(pmslen);
2333         if (pms == NULL)
2334             goto memerr;
2335
2336         /*
2337          * Get server sertificate PKEY and create ctx from it
2338          */
2339         peer_cert = s->session->peer;
2340         if (!peer_cert) {
2341             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2342                    SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
2343             goto err;
2344         }
2345
2346         pkey_ctx = EVP_PKEY_CTX_new(X509_get0_pubkey(peer_cert), NULL);
2347         if (pkey_ctx == NULL) {
2348             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2349                    ERR_R_MALLOC_FAILURE);
2350             goto err;
2351         }
2352         /*
2353          * If we have send a certificate, and certificate key
2354          * parameters match those of server certificate, use
2355          * certificate key for key exchange
2356          */
2357
2358         /* Otherwise, generate ephemeral key pair */
2359
2360         if (pkey_ctx == NULL
2361                 || EVP_PKEY_encrypt_init(pkey_ctx) <= 0
2362                 /* Generate session key */
2363                 || RAND_bytes(pms, pmslen) <= 0) {
2364             EVP_PKEY_CTX_free(pkey_ctx);
2365             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2366                    ERR_R_INTERNAL_ERROR);
2367             goto err;
2368         };
2369         /*
2370          * If we have client certificate, use its secret as peer key
2371          */
2372         if (s->s3->tmp.cert_req && s->cert->key->privatekey) {
2373             if (EVP_PKEY_derive_set_peer
2374                 (pkey_ctx, s->cert->key->privatekey) <= 0) {
2375                 /*
2376                  * If there was an error - just ignore it. Ephemeral key
2377                  * * would be used
2378                  */
2379                 ERR_clear_error();
2380             }
2381         }
2382         /*
2383          * Compute shared IV and store it in algorithm-specific context
2384          * data
2385          */
2386         ukm_hash = EVP_MD_CTX_new();
2387         if (EVP_DigestInit(ukm_hash,
2388                            EVP_get_digestbynid(dgst_nid)) <= 0
2389                 || EVP_DigestUpdate(ukm_hash, s->s3->client_random,
2390                                     SSL3_RANDOM_SIZE) <= 0
2391                 || EVP_DigestUpdate(ukm_hash, s->s3->server_random,
2392                                     SSL3_RANDOM_SIZE) <= 0
2393                 || EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len) <= 0) {
2394             EVP_MD_CTX_free(ukm_hash);
2395             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2396                    ERR_R_INTERNAL_ERROR);
2397             goto err;
2398         }
2399         EVP_MD_CTX_free(ukm_hash);
2400         if (EVP_PKEY_CTX_ctrl
2401             (pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT, EVP_PKEY_CTRL_SET_IV, 8,
2402              shared_ukm) < 0) {
2403             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2404                    SSL_R_LIBRARY_BUG);
2405             goto err;
2406         }
2407         /* Make GOST keytransport blob message */
2408         /*
2409          * Encapsulate it into sequence
2410          */
2411         *(p++) = V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED;
2412         msglen = 255;
2413         if (EVP_PKEY_encrypt(pkey_ctx, tmp, &msglen, pms, pmslen) <= 0) {
2414             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2415                    SSL_R_LIBRARY_BUG);
2416             goto err;
2417         }
2418         if (msglen >= 0x80) {
2419             *(p++) = 0x81;
2420             *(p++) = msglen & 0xff;
2421             n = msglen + 3;
2422         } else {
2423             *(p++) = msglen & 0xff;
2424             n = msglen + 2;
2425         }
2426         memcpy(p, tmp, msglen);
2427         /* Check if pubkey from client certificate was used */
2428         if (EVP_PKEY_CTX_ctrl
2429             (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0) {
2430             /* Set flag "skip certificate verify" */
2431             s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
2432         }
2433         EVP_PKEY_CTX_free(pkey_ctx);
2434
2435     }
2436 #endif
2437 #ifndef OPENSSL_NO_SRP
2438     else if (alg_k & SSL_kSRP) {
2439         if (s->srp_ctx.A != NULL) {
2440             /* send off the data */
2441             n = BN_num_bytes(s->srp_ctx.A);
2442             s2n(n, p);
2443             BN_bn2bin(s->srp_ctx.A, p);
2444             n += 2;
2445         } else {
2446             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2447                    ERR_R_INTERNAL_ERROR);
2448             goto err;
2449         }
2450         OPENSSL_free(s->session->srp_username);
2451         s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);
2452         if (s->session->srp_username == NULL) {
2453             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2454                    ERR_R_MALLOC_FAILURE);
2455             goto err;
2456         }
2457     }
2458 #endif
2459     else {
2460         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2461         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2462         goto err;
2463     }
2464
2465 #ifndef OPENSSL_NO_PSK
2466     n += pskhdrlen;
2467 #endif
2468
2469     if (!ssl_set_handshake_header(s, SSL3_MT_CLIENT_KEY_EXCHANGE, n)) {
2470         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2471         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2472         goto err;
2473     }
2474
2475     if (pms != NULL) {
2476         s->s3->tmp.pms = pms;
2477         s->s3->tmp.pmslen = pmslen;
2478     }
2479
2480     return 1;
2481  memerr:
2482     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2483     SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2484  err:
2485     OPENSSL_clear_free(pms, pmslen);
2486     s->s3->tmp.pms = NULL;
2487 #ifndef OPENSSL_NO_RSA
2488     EVP_PKEY_CTX_free(pctx);
2489 #endif
2490 #ifndef OPENSSL_NO_EC
2491     OPENSSL_free(encodedPoint);
2492 #endif
2493 #if !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)
2494     EVP_PKEY_free(ckey);
2495 #endif
2496 #ifndef OPENSSL_NO_PSK
2497     OPENSSL_clear_free(s->s3->tmp.psk, s->s3->tmp.psklen);
2498     s->s3->tmp.psk = NULL;
2499 #endif
2500     ossl_statem_set_error(s);
2501     return 0;
2502 }
2503
2504 int tls_client_key_exchange_post_work(SSL *s)
2505 {
2506     unsigned char *pms = NULL;
2507     size_t pmslen = 0;
2508
2509 #ifndef OPENSSL_NO_SRP
2510     /* Check for SRP */
2511     if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) {
2512         if (!srp_generate_client_master_secret(s)) {
2513             SSLerr(SSL_F_TLS_CLIENT_KEY_EXCHANGE_POST_WORK,
2514                    ERR_R_INTERNAL_ERROR);
2515             goto err;
2516         }
2517         return 1;
2518     }
2519 #endif
2520     pms = s->s3->tmp.pms;
2521     pmslen = s->s3->tmp.pmslen;
2522
2523     if (pms == NULL && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
2524         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2525         SSLerr(SSL_F_TLS_CLIENT_KEY_EXCHANGE_POST_WORK, ERR_R_MALLOC_FAILURE);
2526         goto err;
2527     }
2528     if (!ssl_generate_master_secret(s, pms, pmslen, 1)) {
2529         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2530         SSLerr(SSL_F_TLS_CLIENT_KEY_EXCHANGE_POST_WORK, ERR_R_INTERNAL_ERROR);
2531         goto err;
2532     }
2533
2534 #ifndef OPENSSL_NO_SCTP
2535     if (SSL_IS_DTLS(s)) {
2536         unsigned char sctpauthkey[64];
2537         char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
2538
2539         /*
2540          * Add new shared key for SCTP-Auth, will be ignored if no SCTP
2541          * used.
2542          */
2543         memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
2544                sizeof(DTLS1_SCTP_AUTH_LABEL));
2545
2546         if (SSL_export_keying_material(s, sctpauthkey,
2547                                    sizeof(sctpauthkey), labelbuffer,
2548                                    sizeof(labelbuffer), NULL, 0, 0) <= 0)
2549             goto err;
2550
2551         BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
2552                  sizeof(sctpauthkey), sctpauthkey);
2553     }
2554 #endif
2555
2556     return 1;
2557  err:
2558     OPENSSL_clear_free(pms, pmslen);
2559     s->s3->tmp.pms = NULL;
2560     return 0;
2561 }
2562
2563 int tls_construct_client_verify(SSL *s)
2564 {
2565     unsigned char *p;
2566     EVP_PKEY *pkey;
2567     const EVP_MD *md = s->s3->tmp.md[s->cert->key - s->cert->pkeys];
2568     EVP_MD_CTX *mctx;
2569     unsigned u = 0;
2570     unsigned long n = 0;
2571     long hdatalen = 0;
2572     void *hdata;
2573
2574     mctx = EVP_MD_CTX_new();
2575     if (mctx == NULL) {
2576         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_MALLOC_FAILURE);
2577         goto err;
2578     }
2579
2580     p = ssl_handshake_start(s);
2581     pkey = s->cert->key->privatekey;
2582
2583     hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
2584     if (hdatalen <= 0) {
2585         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
2586         goto err;
2587     }
2588     if (SSL_USE_SIGALGS(s)) {
2589         if (!tls12_get_sigandhash(p, pkey, md)) {
2590             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
2591             goto err;
2592         }
2593         p += 2;
2594         n = 2;
2595     }
2596 #ifdef SSL_DEBUG
2597     fprintf(stderr, "Using client alg %s\n", EVP_MD_name(md));
2598 #endif
2599     if (!EVP_SignInit_ex(mctx, md, NULL)
2600         || !EVP_SignUpdate(mctx, hdata, hdatalen)
2601         || (s->version == SSL3_VERSION
2602             && !EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
2603                                 s->session->master_key_length,
2604                                 s->session->master_key))
2605         || !EVP_SignFinal(mctx, p + 2, &u, pkey)) {
2606         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_EVP_LIB);
2607         goto err;
2608     }
2609 #ifndef OPENSSL_NO_GOST
2610     {
2611         int pktype = EVP_PKEY_id(pkey);
2612         if (pktype == NID_id_GostR3410_2001
2613             || pktype == NID_id_GostR3410_2012_256
2614             || pktype == NID_id_GostR3410_2012_512)
2615             BUF_reverse(p + 2, NULL, u);
2616     }
2617 #endif
2618
2619     s2n(u, p);
2620     n += u + 2;
2621     /* Digest cached records and discard handshake buffer */
2622     if (!ssl3_digest_cached_records(s, 0))
2623         goto err;
2624     if (!ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_VERIFY, n)) {
2625         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
2626         goto err;
2627     }
2628
2629     EVP_MD_CTX_free(mctx);
2630     return 1;
2631  err:
2632     EVP_MD_CTX_free(mctx);
2633     return 0;
2634 }
2635
2636 /*
2637  * Check a certificate can be used for client authentication. Currently check
2638  * cert exists, if we have a suitable digest for TLS 1.2 if static DH client
2639  * certificates can be used and optionally checks suitability for Suite B.
2640  */
2641 static int ssl3_check_client_certificate(SSL *s)
2642 {
2643     if (!s->cert || !s->cert->key->x509 || !s->cert->key->privatekey)
2644         return 0;
2645     /* If no suitable signature algorithm can't use certificate */
2646     if (SSL_USE_SIGALGS(s) && !s->s3->tmp.md[s->cert->key - s->cert->pkeys])
2647         return 0;
2648     /*
2649      * If strict mode check suitability of chain before using it. This also
2650      * adjusts suite B digest if necessary.
2651      */
2652     if (s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT &&
2653         !tls1_check_chain(s, NULL, NULL, NULL, -2))
2654         return 0;
2655     return 1;
2656 }
2657
2658 WORK_STATE tls_prepare_client_certificate(SSL *s, WORK_STATE wst)
2659 {
2660     X509 *x509 = NULL;
2661     EVP_PKEY *pkey = NULL;
2662     int i;
2663
2664     if (wst == WORK_MORE_A) {
2665         /* Let cert callback update client certificates if required */
2666         if (s->cert->cert_cb) {
2667             i = s->cert->cert_cb(s, s->cert->cert_cb_arg);
2668             if (i < 0) {
2669                 s->rwstate = SSL_X509_LOOKUP;
2670                 return WORK_MORE_A;
2671             }
2672             if (i == 0) {
2673                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2674                 ossl_statem_set_error(s);
2675                 return 0;
2676             }
2677             s->rwstate = SSL_NOTHING;
2678         }
2679         if (ssl3_check_client_certificate(s))
2680             return WORK_FINISHED_CONTINUE;
2681
2682         /* Fall through to WORK_MORE_B */
2683         wst = WORK_MORE_B;
2684     }
2685
2686     /* We need to get a client cert */
2687     if (wst == WORK_MORE_B) {
2688         /*
2689          * If we get an error, we need to ssl->rwstate=SSL_X509_LOOKUP;
2690          * return(-1); We then get retied later
2691          */
2692         i = ssl_do_client_cert_cb(s, &x509, &pkey);
2693         if (i < 0) {
2694             s->rwstate = SSL_X509_LOOKUP;
2695             return WORK_MORE_B;
2696         }
2697         s->rwstate = SSL_NOTHING;
2698         if ((i == 1) && (pkey != NULL) && (x509 != NULL)) {
2699             if (!SSL_use_certificate(s, x509) || !SSL_use_PrivateKey(s, pkey))
2700                 i = 0;
2701         } else if (i == 1) {
2702             i = 0;
2703             SSLerr(SSL_F_TLS_PREPARE_CLIENT_CERTIFICATE,
2704                    SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
2705         }
2706
2707         X509_free(x509);
2708         EVP_PKEY_free(pkey);
2709         if (i && !ssl3_check_client_certificate(s))
2710             i = 0;
2711         if (i == 0) {
2712             if (s->version == SSL3_VERSION) {
2713                 s->s3->tmp.cert_req = 0;
2714                 ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_CERTIFICATE);
2715                 return WORK_FINISHED_CONTINUE;
2716             } else {
2717                 s->s3->tmp.cert_req = 2;
2718                 if (!ssl3_digest_cached_records(s, 0)) {
2719                     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2720                     ossl_statem_set_error(s);
2721                     return 0;
2722                 }
2723             }
2724         }
2725
2726         return WORK_FINISHED_CONTINUE;
2727     }
2728
2729     /* Shouldn't ever get here */
2730     return WORK_ERROR;
2731 }
2732
2733 int tls_construct_client_certificate(SSL *s)
2734 {
2735     if (!ssl3_output_cert_chain(s,
2736                                 (s->s3->tmp.cert_req ==
2737                                  2) ? NULL : s->cert->key)) {
2738         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_CERTIFICATE, ERR_R_INTERNAL_ERROR);
2739         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2740         ossl_statem_set_error(s);
2741         return 0;
2742     }
2743
2744     return 1;
2745 }
2746
2747 #define has_bits(i,m)   (((i)&(m)) == (m))
2748
2749 int ssl3_check_cert_and_algorithm(SSL *s)
2750 {
2751     int i;
2752 #ifndef OPENSSL_NO_EC
2753     int idx;
2754 #endif
2755     long alg_k, alg_a;
2756     EVP_PKEY *pkey = NULL;
2757     int al = SSL_AD_HANDSHAKE_FAILURE;
2758
2759     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2760     alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2761
2762     /* we don't have a certificate */
2763     if ((alg_a & SSL_aNULL) || (alg_k & SSL_kPSK))
2764         return (1);
2765
2766     /* This is the passed certificate */
2767
2768 #ifndef OPENSSL_NO_EC
2769     idx = s->session->peer_type;
2770     if (idx == SSL_PKEY_ECC) {
2771         if (ssl_check_srvr_ecc_cert_and_alg(s->session->peer, s) == 0) {
2772             /* check failed */
2773             SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_BAD_ECC_CERT);
2774             goto f_err;
2775         } else {
2776             return 1;
2777         }
2778     } else if (alg_a & SSL_aECDSA) {
2779         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
2780                SSL_R_MISSING_ECDSA_SIGNING_CERT);
2781         goto f_err;
2782     }
2783 #endif
2784     pkey = X509_get0_pubkey(s->session->peer);
2785     i = X509_certificate_type(s->session->peer, pkey);
2786
2787     /* Check that we have a certificate if we require one */
2788     if ((alg_a & SSL_aRSA) && !has_bits(i, EVP_PK_RSA | EVP_PKT_SIGN)) {
2789         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
2790                SSL_R_MISSING_RSA_SIGNING_CERT);
2791         goto f_err;
2792     }
2793 #ifndef OPENSSL_NO_DSA
2794     else if ((alg_a & SSL_aDSS) && !has_bits(i, EVP_PK_DSA | EVP_PKT_SIGN)) {
2795         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
2796                SSL_R_MISSING_DSA_SIGNING_CERT);
2797         goto f_err;
2798     }
2799 #endif
2800 #ifndef OPENSSL_NO_RSA
2801     if (alg_k & (SSL_kRSA | SSL_kRSAPSK) &&
2802         !has_bits(i, EVP_PK_RSA | EVP_PKT_ENC)) {
2803         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
2804                SSL_R_MISSING_RSA_ENCRYPTING_CERT);
2805         goto f_err;
2806     }
2807 #endif
2808 #ifndef OPENSSL_NO_DH
2809     if ((alg_k & SSL_kDHE) && (s->s3->peer_tmp == NULL)) {
2810         al = SSL_AD_INTERNAL_ERROR;
2811         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR);
2812         goto f_err;
2813     }
2814 #endif
2815
2816     return (1);
2817  f_err:
2818     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2819     return (0);
2820 }
2821
2822 #ifndef OPENSSL_NO_NEXTPROTONEG
2823 int tls_construct_next_proto(SSL *s)
2824 {
2825     unsigned int len, padding_len;
2826     unsigned char *d;
2827
2828     len = s->next_proto_negotiated_len;
2829     padding_len = 32 - ((len + 2) % 32);
2830     d = (unsigned char *)s->init_buf->data;
2831     d[4] = len;
2832     memcpy(d + 5, s->next_proto_negotiated, len);
2833     d[5 + len] = padding_len;
2834     memset(d + 6 + len, 0, padding_len);
2835     *(d++) = SSL3_MT_NEXT_PROTO;
2836     l2n3(2 + len + padding_len, d);
2837     s->init_num = 4 + 2 + len + padding_len;
2838     s->init_off = 0;
2839
2840     return 1;
2841 }
2842 #endif
2843
2844 int ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
2845 {
2846     int i = 0;
2847 #ifndef OPENSSL_NO_ENGINE
2848     if (s->ctx->client_cert_engine) {
2849         i = ENGINE_load_ssl_client_cert(s->ctx->client_cert_engine, s,
2850                                         SSL_get_client_CA_list(s),
2851                                         px509, ppkey, NULL, NULL, NULL);
2852         if (i != 0)
2853             return i;
2854     }
2855 #endif
2856     if (s->ctx->client_cert_cb)
2857         i = s->ctx->client_cert_cb(s, px509, ppkey);
2858     return i;
2859 }
2860
2861 int ssl_cipher_list_to_bytes(SSL *s, STACK_OF(SSL_CIPHER) *sk,
2862                              unsigned char *p)
2863 {
2864     int i, j = 0;
2865     const SSL_CIPHER *c;
2866     unsigned char *q;
2867     int empty_reneg_info_scsv = !s->renegotiate;
2868     /* Set disabled masks for this session */
2869     ssl_set_client_disabled(s);
2870
2871     if (sk == NULL)
2872         return (0);
2873     q = p;
2874
2875     for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
2876         c = sk_SSL_CIPHER_value(sk, i);
2877         /* Skip disabled ciphers */
2878         if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_SUPPORTED))
2879             continue;
2880         j = s->method->put_cipher_by_char(c, p);
2881         p += j;
2882     }
2883     /*
2884      * If p == q, no ciphers; caller indicates an error. Otherwise, add
2885      * applicable SCSVs.
2886      */
2887     if (p != q) {
2888         if (empty_reneg_info_scsv) {
2889             static SSL_CIPHER scsv = {
2890                 0, NULL, SSL3_CK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
2891             };
2892             j = s->method->put_cipher_by_char(&scsv, p);
2893             p += j;
2894         }
2895         if (s->mode & SSL_MODE_SEND_FALLBACK_SCSV) {
2896             static SSL_CIPHER scsv = {
2897                 0, NULL, SSL3_CK_FALLBACK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
2898             };
2899             j = s->method->put_cipher_by_char(&scsv, p);
2900             p += j;
2901         }
2902     }
2903
2904     return (p - q);
2905 }