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