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