9ac992197f485d8ddbe7eb2a7afb2b472decc836
[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 inline int cert_req_allowed(SSL *s);
168 static int key_exchange_expected(SSL *s);
169 static int ssl_set_version(SSL *s);
170 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b);
171 static int ssl_cipher_list_to_bytes(SSL *s, STACK_OF(SSL_CIPHER) *sk,
172                                     unsigned char *p);
173
174
175 /*
176  * Is a CertificateRequest message allowed at the moment or not?
177  *
178  *  Return values are:
179  *  1: Yes
180  *  0: No
181  */
182 static inline int cert_req_allowed(SSL *s)
183 {
184     /* TLS does not like anon-DH with client cert */
185     if ((s->version > SSL3_VERSION
186                 && (s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL))
187             || (s->s3->tmp.new_cipher->algorithm_auth & (SSL_aSRP | SSL_aPSK)))
188         return 0;
189
190     return 1;
191 }
192
193 /*
194  * Should we expect the ServerKeyExchange message or not?
195  *
196  *  Return values are:
197  *  1: Yes
198  *  0: No
199  * -1: Error
200  */
201 static int key_exchange_expected(SSL *s)
202 {
203     long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
204
205     /*
206      * Can't skip server key exchange if this is an ephemeral
207      * ciphersuite or for SRP
208      */
209     if (alg_k & (SSL_kDHE | SSL_kECDHE | SSL_kDHEPSK | SSL_kECDHEPSK
210                  | SSL_kSRP)) {
211         return 1;
212     }
213
214     return 0;
215 }
216
217 /*
218  * ossl_statem_client_read_transition() encapsulates the logic for the allowed
219  * handshake state transitions when the client is reading messages from the
220  * server. The message type that the server has sent is provided in |mt|. The
221  * current state is in |s->statem.hand_state|.
222  *
223  *  Return values are:
224  *  1: Success (transition allowed)
225  *  0: Error (transition not allowed)
226  */
227 int ossl_statem_client_read_transition(SSL *s, int mt)
228 {
229     OSSL_STATEM *st = &s->statem;
230     int ske_expected;
231
232     switch(st->hand_state) {
233     case TLS_ST_CW_CLNT_HELLO:
234         if (mt == SSL3_MT_SERVER_HELLO) {
235             st->hand_state = TLS_ST_CR_SRVR_HELLO;
236             return 1;
237         }
238
239         if (SSL_IS_DTLS(s)) {
240             if (mt == DTLS1_MT_HELLO_VERIFY_REQUEST) {
241                 st->hand_state = DTLS_ST_CR_HELLO_VERIFY_REQUEST;
242                 return 1;
243             }
244         }
245         break;
246
247     case TLS_ST_CR_SRVR_HELLO:
248         if (s->hit) {
249             if (s->tlsext_ticket_expected) {
250                 if (mt == SSL3_MT_NEWSESSION_TICKET) {
251                     st->hand_state = TLS_ST_CR_SESSION_TICKET;
252                     return 1;
253                 }
254             } else if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
255                 st->hand_state = TLS_ST_CR_CHANGE;
256                 return 1;
257             }
258         } else {
259             if (SSL_IS_DTLS(s) && mt == DTLS1_MT_HELLO_VERIFY_REQUEST) {
260                 st->hand_state = DTLS_ST_CR_HELLO_VERIFY_REQUEST;
261                 return 1;
262             } else if (s->version >= TLS1_VERSION
263                     && s->tls_session_secret_cb != NULL
264                     && s->session->tlsext_tick != NULL
265                     && mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
266                 /*
267                  * Normally, we can tell if the server is resuming the session
268                  * from the session ID. EAP-FAST (RFC 4851), however, relies on
269                  * the next server message after the ServerHello to determine if
270                  * the server is resuming.
271                  */
272                 s->hit = 1;
273                 st->hand_state = TLS_ST_CR_CHANGE;
274                 return 1;
275             } else if (!(s->s3->tmp.new_cipher->algorithm_auth
276                         & (SSL_aNULL | SSL_aSRP | SSL_aPSK))) {
277                 if (mt == SSL3_MT_CERTIFICATE) {
278                     st->hand_state = TLS_ST_CR_CERT;
279                     return 1;
280                 }
281             } else {
282                 ske_expected = key_exchange_expected(s);
283                 if (ske_expected < 0)
284                     return 0;
285                 /* SKE is optional for some PSK ciphersuites */
286                 if (ske_expected
287                         || ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_PSK)
288                             && mt == SSL3_MT_SERVER_KEY_EXCHANGE)) {
289                     if (mt == SSL3_MT_SERVER_KEY_EXCHANGE) {
290                         st->hand_state = TLS_ST_CR_KEY_EXCH;
291                         return 1;
292                     }
293                 } else if (mt == SSL3_MT_CERTIFICATE_REQUEST
294                             && cert_req_allowed(s)) {
295                         st->hand_state = TLS_ST_CR_CERT_REQ;
296                         return 1;
297                 } else if (mt == SSL3_MT_SERVER_DONE) {
298                         st->hand_state = TLS_ST_CR_SRVR_DONE;
299                         return 1;
300                 }
301             }
302         }
303         break;
304
305     case TLS_ST_CR_CERT:
306         if (s->tlsext_status_expected) {
307             if (mt == SSL3_MT_CERTIFICATE_STATUS) {
308                 st->hand_state = TLS_ST_CR_CERT_STATUS;
309                 return 1;
310             }
311             return 0;
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             return SSL3_RT_MAX_PLAIN_LENGTH;
699
700         case TLS_ST_CR_SRVR_DONE:
701             return SERVER_HELLO_DONE_MAX_LENGTH;
702
703         case TLS_ST_CR_CHANGE:
704             return CCS_MAX_LENGTH;
705
706         case TLS_ST_CR_SESSION_TICKET:
707             return SSL3_RT_MAX_PLAIN_LENGTH;
708
709         case TLS_ST_CR_FINISHED:
710             return FINISHED_MAX_LENGTH;
711
712         default:
713             /* Shouldn't happen */
714             break;
715     }
716
717     return 0;
718 }
719
720 /*
721  * Process a message that the client has been received from the server.
722  */
723 MSG_PROCESS_RETURN ossl_statem_client_process_message(SSL *s, PACKET *pkt)
724 {
725     OSSL_STATEM *st = &s->statem;
726
727     switch(st->hand_state) {
728         case TLS_ST_CR_SRVR_HELLO:
729             return tls_process_server_hello(s, pkt);
730
731         case DTLS_ST_CR_HELLO_VERIFY_REQUEST:
732             return dtls_process_hello_verify(s, pkt);
733
734         case TLS_ST_CR_CERT:
735             return tls_process_server_certificate(s, pkt);
736
737         case TLS_ST_CR_CERT_STATUS:
738             return tls_process_cert_status(s, pkt);
739
740         case TLS_ST_CR_KEY_EXCH:
741             return tls_process_key_exchange(s, pkt);
742
743         case TLS_ST_CR_CERT_REQ:
744             return tls_process_certificate_request(s, pkt);
745
746         case TLS_ST_CR_SRVR_DONE:
747             return tls_process_server_done(s, pkt);
748
749         case TLS_ST_CR_CHANGE:
750             return tls_process_change_cipher_spec(s, pkt);
751
752         case TLS_ST_CR_SESSION_TICKET:
753             return tls_process_new_session_ticket(s, pkt);
754
755         case TLS_ST_CR_FINISHED:
756             return tls_process_finished(s, pkt);
757
758         default:
759             /* Shouldn't happen */
760             break;
761     }
762
763     return MSG_PROCESS_ERROR;
764 }
765
766 /*
767  * Perform any further processing required following the receipt of a message
768  * from the server
769  */
770 WORK_STATE ossl_statem_client_post_process_message(SSL *s, WORK_STATE wst)
771 {
772     OSSL_STATEM *st = &s->statem;
773
774     switch(st->hand_state) {
775 #ifndef OPENSSL_NO_SCTP
776     case TLS_ST_CR_SRVR_DONE:
777         /* We only get here if we are using SCTP and we are renegotiating */
778         if (BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
779             s->s3->in_read_app_data = 2;
780             s->rwstate = SSL_READING;
781             BIO_clear_retry_flags(SSL_get_rbio(s));
782             BIO_set_retry_read(SSL_get_rbio(s));
783             ossl_statem_set_sctp_read_sock(s, 1);
784             return WORK_MORE_A;
785         }
786         ossl_statem_set_sctp_read_sock(s, 0);
787         return WORK_FINISHED_STOP;
788 #endif
789
790     default:
791         break;
792     }
793
794     /* Shouldn't happen */
795     return WORK_ERROR;
796 }
797
798 /*
799  * Work out what version we should be using for the initial ClientHello if
800  * the version is currently set to (D)TLS_ANY_VERSION.
801  * Returns 1 on success
802  * Returns 0 on error
803  */
804 static int ssl_set_version(SSL *s)
805 {
806     unsigned long mask, options = s->options;
807
808     if (s->method->version == TLS_ANY_VERSION) {
809         /*
810          * SSL_OP_NO_X disables all protocols above X *if* there are
811          * some protocols below X enabled. This is required in order
812          * to maintain "version capability" vector contiguous. So
813          * that if application wants to disable TLS1.0 in favour of
814          * TLS1>=1, it would be insufficient to pass SSL_NO_TLSv1, the
815          * answer is SSL_OP_NO_TLSv1|SSL_OP_NO_SSLv3.
816          */
817         mask = SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1
818 #if !defined(OPENSSL_NO_SSL3)
819             | SSL_OP_NO_SSLv3
820 #endif
821             ;
822 #if !defined(OPENSSL_NO_TLS1_2_CLIENT)
823         if (options & SSL_OP_NO_TLSv1_2) {
824             if ((options & mask) != mask) {
825                 s->version = TLS1_1_VERSION;
826             } else {
827                 SSLerr(SSL_F_SSL_SET_VERSION, SSL_R_NO_PROTOCOLS_AVAILABLE);
828                 return 0;
829             }
830         } else {
831             s->version = TLS1_2_VERSION;
832         }
833 #else
834         if ((options & mask) == mask) {
835             SSLerr(SSL_F_SSL_SET_VERSION, SSL_R_NO_PROTOCOLS_AVAILABLE);
836             return 0;
837         }
838         s->version = TLS1_1_VERSION;
839 #endif
840
841         mask &= ~SSL_OP_NO_TLSv1_1;
842         if ((options & SSL_OP_NO_TLSv1_1) && (options & mask) != mask)
843             s->version = TLS1_VERSION;
844         mask &= ~SSL_OP_NO_TLSv1;
845 #if !defined(OPENSSL_NO_SSL3)
846         if ((options & SSL_OP_NO_TLSv1) && (options & mask) != mask)
847             s->version = SSL3_VERSION;
848 #endif
849
850         if (s->version != TLS1_2_VERSION && tls1_suiteb(s)) {
851             SSLerr(SSL_F_SSL_SET_VERSION,
852                    SSL_R_ONLY_TLS_1_2_ALLOWED_IN_SUITEB_MODE);
853             return 0;
854         }
855
856         if (s->version == SSL3_VERSION && FIPS_mode()) {
857             SSLerr(SSL_F_SSL_SET_VERSION, SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE);
858             return 0;
859         }
860
861     } else if (s->method->version == DTLS_ANY_VERSION) {
862         /* Determine which DTLS version to use */
863         /* If DTLS 1.2 disabled correct the version number */
864         if (options & SSL_OP_NO_DTLSv1_2) {
865             if (tls1_suiteb(s)) {
866                 SSLerr(SSL_F_SSL_SET_VERSION,
867                        SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
868                 return 0;
869             }
870             /*
871              * Disabling all versions is silly: return an error.
872              */
873             if (options & SSL_OP_NO_DTLSv1) {
874                 SSLerr(SSL_F_SSL_SET_VERSION, SSL_R_WRONG_SSL_VERSION);
875                 return 0;
876             }
877             /*
878              * Update method so we don't use any DTLS 1.2 features.
879              */
880             s->method = DTLSv1_client_method();
881             s->version = DTLS1_VERSION;
882         } else {
883             /*
884              * We only support one version: update method
885              */
886             if (options & SSL_OP_NO_DTLSv1)
887                 s->method = DTLSv1_2_client_method();
888             s->version = DTLS1_2_VERSION;
889         }
890     }
891
892     s->client_version = s->version;
893
894     return 1;
895 }
896
897 int tls_construct_client_hello(SSL *s)
898 {
899     unsigned char *buf;
900     unsigned char *p, *d;
901     int i;
902     unsigned long l;
903     int al = 0;
904 #ifndef OPENSSL_NO_COMP
905     int j;
906     SSL_COMP *comp;
907 #endif
908     SSL_SESSION *sess = s->session;
909
910     buf = (unsigned char *)s->init_buf->data;
911
912     /* Work out what SSL/TLS/DTLS version to use */
913     if (ssl_set_version(s) == 0)
914         goto err;
915
916     if ((sess == NULL) || (sess->ssl_version != s->version) ||
917         /*
918          * In the case of EAP-FAST, we can have a pre-shared
919          * "ticket" without a session ID.
920          */
921         (!sess->session_id_length && !sess->tlsext_tick) ||
922         (sess->not_resumable)) {
923         if (!ssl_get_new_session(s, 0))
924             goto err;
925     }
926     /* else use the pre-loaded session */
927
928     p = s->s3->client_random;
929
930     /*
931      * for DTLS if client_random is initialized, reuse it, we are
932      * required to use same upon reply to HelloVerify
933      */
934     if (SSL_IS_DTLS(s)) {
935         size_t idx;
936         i = 1;
937         for (idx = 0; idx < sizeof(s->s3->client_random); idx++) {
938             if (p[idx]) {
939                 i = 0;
940                 break;
941             }
942         }
943     } else
944         i = 1;
945
946     if (i && ssl_fill_hello_random(s, 0, p,
947                                    sizeof(s->s3->client_random)) <= 0)
948         goto err;
949
950     /* Do the message type and length last */
951     d = p = ssl_handshake_start(s);
952
953     /*-
954      * version indicates the negotiated version: for example from
955      * an SSLv2/v3 compatible client hello). The client_version
956      * field is the maximum version we permit and it is also
957      * used in RSA encrypted premaster secrets. Some servers can
958      * choke if we initially report a higher version then
959      * renegotiate to a lower one in the premaster secret. This
960      * didn't happen with TLS 1.0 as most servers supported it
961      * but it can with TLS 1.1 or later if the server only supports
962      * 1.0.
963      *
964      * Possible scenario with previous logic:
965      *      1. Client hello indicates TLS 1.2
966      *      2. Server hello says TLS 1.0
967      *      3. RSA encrypted premaster secret uses 1.2.
968      *      4. Handhaked proceeds using TLS 1.0.
969      *      5. Server sends hello request to renegotiate.
970      *      6. Client hello indicates TLS v1.0 as we now
971      *         know that is maximum server supports.
972      *      7. Server chokes on RSA encrypted premaster secret
973      *         containing version 1.0.
974      *
975      * For interoperability it should be OK to always use the
976      * maximum version we support in client hello and then rely
977      * on the checking of version to ensure the servers isn't
978      * being inconsistent: for example initially negotiating with
979      * TLS 1.0 and renegotiating with TLS 1.2. We do this by using
980      * client_version in client hello and not resetting it to
981      * the negotiated version.
982      */
983     *(p++) = s->client_version >> 8;
984     *(p++) = s->client_version & 0xff;
985
986     /* Random stuff */
987     memcpy(p, s->s3->client_random, SSL3_RANDOM_SIZE);
988     p += SSL3_RANDOM_SIZE;
989
990     /* Session ID */
991     if (s->new_session)
992         i = 0;
993     else
994         i = s->session->session_id_length;
995     *(p++) = i;
996     if (i != 0) {
997         if (i > (int)sizeof(s->session->session_id)) {
998             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
999             goto err;
1000         }
1001         memcpy(p, s->session->session_id, i);
1002         p += i;
1003     }
1004
1005     /* cookie stuff for DTLS */
1006     if (SSL_IS_DTLS(s)) {
1007         if (s->d1->cookie_len > sizeof(s->d1->cookie)) {
1008             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1009             goto err;
1010         }
1011         *(p++) = s->d1->cookie_len;
1012         memcpy(p, s->d1->cookie, s->d1->cookie_len);
1013         p += s->d1->cookie_len;
1014     }
1015
1016     /* Ciphers supported */
1017     i = ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s), &(p[2]));
1018     if (i == 0) {
1019         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, SSL_R_NO_CIPHERS_AVAILABLE);
1020         goto err;
1021     }
1022 #ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH
1023     /*
1024      * Some servers hang if client hello > 256 bytes as hack workaround
1025      * chop number of supported ciphers to keep it well below this if we
1026      * use TLS v1.2
1027      */
1028     if (TLS1_get_version(s) >= TLS1_2_VERSION
1029         && i > OPENSSL_MAX_TLS1_2_CIPHER_LENGTH)
1030         i = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1;
1031 #endif
1032     s2n(i, p);
1033     p += i;
1034
1035     /* COMPRESSION */
1036 #ifdef OPENSSL_NO_COMP
1037     *(p++) = 1;
1038 #else
1039
1040     if (!ssl_allow_compression(s) || !s->ctx->comp_methods)
1041         j = 0;
1042     else
1043         j = sk_SSL_COMP_num(s->ctx->comp_methods);
1044     *(p++) = 1 + j;
1045     for (i = 0; i < j; i++) {
1046         comp = sk_SSL_COMP_value(s->ctx->comp_methods, i);
1047         *(p++) = comp->id;
1048     }
1049 #endif
1050     *(p++) = 0;             /* Add the NULL method */
1051
1052     /* TLS extensions */
1053     if (ssl_prepare_clienthello_tlsext(s) <= 0) {
1054         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1055         goto err;
1056     }
1057     if ((p =
1058          ssl_add_clienthello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,
1059                                     &al)) == NULL) {
1060         ssl3_send_alert(s, SSL3_AL_FATAL, al);
1061         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1062         goto err;
1063     }
1064
1065     l = p - d;
1066     if (!ssl_set_handshake_header(s, SSL3_MT_CLIENT_HELLO, l)) {
1067         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1068         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1069         goto err;
1070     }
1071
1072     return 1;
1073  err:
1074     ossl_statem_set_error(s);
1075     return 0;
1076 }
1077
1078 MSG_PROCESS_RETURN dtls_process_hello_verify(SSL *s, PACKET *pkt)
1079 {
1080     int al;
1081     unsigned int cookie_len;
1082     PACKET cookiepkt;
1083
1084     if (!PACKET_forward(pkt, 2)
1085             || !PACKET_get_length_prefixed_1(pkt, &cookiepkt)) {
1086         al = SSL_AD_DECODE_ERROR;
1087         SSLerr(SSL_F_DTLS_PROCESS_HELLO_VERIFY, SSL_R_LENGTH_MISMATCH);
1088         goto f_err;
1089     }
1090
1091     cookie_len = PACKET_remaining(&cookiepkt);
1092     if (cookie_len > sizeof(s->d1->cookie)) {
1093         al = SSL_AD_ILLEGAL_PARAMETER;
1094         SSLerr(SSL_F_DTLS_PROCESS_HELLO_VERIFY, SSL_R_LENGTH_TOO_LONG);
1095         goto f_err;
1096     }
1097
1098     if (!PACKET_copy_bytes(&cookiepkt, s->d1->cookie, cookie_len)) {
1099         al = SSL_AD_DECODE_ERROR;
1100         SSLerr(SSL_F_DTLS_PROCESS_HELLO_VERIFY, SSL_R_LENGTH_MISMATCH);
1101         goto f_err;
1102     }
1103     s->d1->cookie_len = cookie_len;
1104
1105     return MSG_PROCESS_FINISHED_READING;
1106  f_err:
1107     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1108     ossl_statem_set_error(s);
1109     return MSG_PROCESS_ERROR;
1110 }
1111
1112 MSG_PROCESS_RETURN tls_process_server_hello(SSL *s, PACKET *pkt)
1113 {
1114     STACK_OF(SSL_CIPHER) *sk;
1115     const SSL_CIPHER *c;
1116     PACKET session_id;
1117     size_t session_id_len;
1118     unsigned char *cipherchars;
1119     int i, al = SSL_AD_INTERNAL_ERROR;
1120     unsigned int compression;
1121 #ifndef OPENSSL_NO_COMP
1122     SSL_COMP *comp;
1123 #endif
1124
1125     if (s->method->version == TLS_ANY_VERSION) {
1126         unsigned int sversion;
1127
1128         if (!PACKET_get_net_2(pkt, &sversion)) {
1129             al = SSL_AD_DECODE_ERROR;
1130             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
1131             goto f_err;
1132         }
1133
1134 #if TLS_MAX_VERSION != TLS1_2_VERSION
1135 #error Code needs updating for new TLS version
1136 #endif
1137 #ifndef OPENSSL_NO_SSL3
1138         if ((sversion == SSL3_VERSION) && !(s->options & SSL_OP_NO_SSLv3)) {
1139             if (FIPS_mode()) {
1140                 SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1141                        SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE);
1142                 al = SSL_AD_PROTOCOL_VERSION;
1143                 goto f_err;
1144             }
1145             s->method = SSLv3_client_method();
1146         } else
1147 #endif
1148         if ((sversion == TLS1_VERSION) && !(s->options & SSL_OP_NO_TLSv1)) {
1149             s->method = TLSv1_client_method();
1150         } else if ((sversion == TLS1_1_VERSION) &&
1151                    !(s->options & SSL_OP_NO_TLSv1_1)) {
1152             s->method = TLSv1_1_client_method();
1153         } else if ((sversion == TLS1_2_VERSION) &&
1154                    !(s->options & SSL_OP_NO_TLSv1_2)) {
1155             s->method = TLSv1_2_client_method();
1156         } else {
1157             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_UNSUPPORTED_PROTOCOL);
1158             al = SSL_AD_PROTOCOL_VERSION;
1159             goto f_err;
1160         }
1161         s->session->ssl_version = s->version = s->method->version;
1162
1163         if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL)) {
1164             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_VERSION_TOO_LOW);
1165             al = SSL_AD_PROTOCOL_VERSION;
1166             goto f_err;
1167         }
1168     } else if (s->method->version == DTLS_ANY_VERSION) {
1169         /* Work out correct protocol version to use */
1170         unsigned int hversion;
1171         int options;
1172
1173         if (!PACKET_get_net_2(pkt, &hversion)) {
1174             al = SSL_AD_DECODE_ERROR;
1175             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
1176             goto f_err;
1177         }
1178
1179         options = s->options;
1180         if (hversion == DTLS1_2_VERSION && !(options & SSL_OP_NO_DTLSv1_2))
1181             s->method = DTLSv1_2_client_method();
1182         else if (tls1_suiteb(s)) {
1183             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1184                    SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
1185             s->version = hversion;
1186             al = SSL_AD_PROTOCOL_VERSION;
1187             goto f_err;
1188         } else if (hversion == DTLS1_VERSION && !(options & SSL_OP_NO_DTLSv1))
1189             s->method = DTLSv1_client_method();
1190         else {
1191             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_WRONG_SSL_VERSION);
1192             s->version = hversion;
1193             al = SSL_AD_PROTOCOL_VERSION;
1194             goto f_err;
1195         }
1196         s->session->ssl_version = s->version = s->method->version;
1197     } else {
1198         unsigned char *vers;
1199
1200         if (!PACKET_get_bytes(pkt, &vers, 2)) {
1201             al = SSL_AD_DECODE_ERROR;
1202             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
1203             goto f_err;
1204         }
1205         if ((vers[0] != (s->version >> 8))
1206                 || (vers[1] != (s->version & 0xff))) {
1207             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_WRONG_SSL_VERSION);
1208             s->version = (s->version & 0xff00) | vers[1];
1209             al = SSL_AD_PROTOCOL_VERSION;
1210             goto f_err;
1211         }
1212     }
1213
1214     /* load the server hello data */
1215     /* load the server random */
1216     if (!PACKET_copy_bytes(pkt, s->s3->server_random, SSL3_RANDOM_SIZE)) {
1217         al = SSL_AD_DECODE_ERROR;
1218         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
1219         goto f_err;
1220     }
1221
1222     s->hit = 0;
1223
1224     /* Get the session-id. */
1225     if (!PACKET_get_length_prefixed_1(pkt, &session_id)) {
1226         al = SSL_AD_DECODE_ERROR;
1227         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
1228         goto f_err;
1229     }
1230     session_id_len = PACKET_remaining(&session_id);
1231     if (session_id_len > sizeof s->session->session_id
1232         || session_id_len > SSL3_SESSION_ID_SIZE) {
1233         al = SSL_AD_ILLEGAL_PARAMETER;
1234         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_SSL3_SESSION_ID_TOO_LONG);
1235         goto f_err;
1236     }
1237
1238     if (!PACKET_get_bytes(pkt, &cipherchars, TLS_CIPHER_LEN)) {
1239         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
1240         al = SSL_AD_DECODE_ERROR;
1241         goto f_err;
1242     }
1243
1244     /*
1245      * Check if we can resume the session based on external pre-shared secret.
1246      * EAP-FAST (RFC 4851) supports two types of session resumption.
1247      * Resumption based on server-side state works with session IDs.
1248      * Resumption based on pre-shared Protected Access Credentials (PACs)
1249      * works by overriding the SessionTicket extension at the application
1250      * layer, and does not send a session ID. (We do not know whether EAP-FAST
1251      * servers would honour the session ID.) Therefore, the session ID alone
1252      * is not a reliable indicator of session resumption, so we first check if
1253      * we can resume, and later peek at the next handshake message to see if the
1254      * server wants to resume.
1255      */
1256     if (s->version >= TLS1_VERSION && s->tls_session_secret_cb &&
1257         s->session->tlsext_tick) {
1258         SSL_CIPHER *pref_cipher = NULL;
1259         s->session->master_key_length = sizeof(s->session->master_key);
1260         if (s->tls_session_secret_cb(s, s->session->master_key,
1261                                      &s->session->master_key_length,
1262                                      NULL, &pref_cipher,
1263                                      s->tls_session_secret_cb_arg)) {
1264             s->session->cipher = pref_cipher ?
1265                 pref_cipher : ssl_get_cipher_by_char(s, cipherchars);
1266         } else {
1267             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1268             al = SSL_AD_INTERNAL_ERROR;
1269             goto f_err;
1270         }
1271     }
1272
1273     if (session_id_len != 0 && session_id_len == s->session->session_id_length
1274         && memcmp(PACKET_data(&session_id), s->session->session_id,
1275                   session_id_len) == 0) {
1276         if (s->sid_ctx_length != s->session->sid_ctx_length
1277             || memcmp(s->session->sid_ctx, s->sid_ctx, s->sid_ctx_length)) {
1278             /* actually a client application bug */
1279             al = SSL_AD_ILLEGAL_PARAMETER;
1280             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1281                    SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
1282             goto f_err;
1283         }
1284         s->hit = 1;
1285     } else {
1286         /*
1287          * If we were trying for session-id reuse but the server
1288          * didn't echo the ID, make a new SSL_SESSION.
1289          * In the case of EAP-FAST and PAC, we do not send a session ID,
1290          * so the PAC-based session secret is always preserved. It'll be
1291          * overwritten if the server refuses resumption.
1292          */
1293         if (s->session->session_id_length > 0) {
1294             if (!ssl_get_new_session(s, 0)) {
1295                 goto f_err;
1296             }
1297         }
1298
1299         s->session->session_id_length = session_id_len;
1300         /* session_id_len could be 0 */
1301         memcpy(s->session->session_id, PACKET_data(&session_id),
1302                session_id_len);
1303     }
1304
1305     c = ssl_get_cipher_by_char(s, cipherchars);
1306     if (c == NULL) {
1307         /* unknown cipher */
1308         al = SSL_AD_ILLEGAL_PARAMETER;
1309         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_UNKNOWN_CIPHER_RETURNED);
1310         goto f_err;
1311     }
1312     /* Set version disabled mask now we know version */
1313     if (!SSL_USE_TLS1_2_CIPHERS(s))
1314         s->s3->tmp.mask_ssl = SSL_TLSV1_2;
1315     else
1316         s->s3->tmp.mask_ssl = 0;
1317     /* Skip TLS v1.0 ciphersuites if SSLv3 */
1318     if ((c->algorithm_ssl & SSL_TLSV1) && s->version == SSL3_VERSION)
1319         s->s3->tmp.mask_ssl |= SSL_TLSV1;
1320     /*
1321      * If it is a disabled cipher we didn't send it in client hello, so
1322      * return an error.
1323      */
1324     if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_CHECK)) {
1325         al = SSL_AD_ILLEGAL_PARAMETER;
1326         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_WRONG_CIPHER_RETURNED);
1327         goto f_err;
1328     }
1329
1330     sk = ssl_get_ciphers_by_id(s);
1331     i = sk_SSL_CIPHER_find(sk, c);
1332     if (i < 0) {
1333         /* we did not say we would use this cipher */
1334         al = SSL_AD_ILLEGAL_PARAMETER;
1335         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_WRONG_CIPHER_RETURNED);
1336         goto f_err;
1337     }
1338
1339     /*
1340      * Depending on the session caching (internal/external), the cipher
1341      * and/or cipher_id values may not be set. Make sure that cipher_id is
1342      * set and use it for comparison.
1343      */
1344     if (s->session->cipher)
1345         s->session->cipher_id = s->session->cipher->id;
1346     if (s->hit && (s->session->cipher_id != c->id)) {
1347         al = SSL_AD_ILLEGAL_PARAMETER;
1348         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1349                SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
1350         goto f_err;
1351     }
1352     s->s3->tmp.new_cipher = c;
1353     /* lets get the compression algorithm */
1354     /* COMPRESSION */
1355     if (!PACKET_get_1(pkt, &compression)) {
1356         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
1357         al = SSL_AD_DECODE_ERROR;
1358         goto f_err;
1359     }
1360 #ifdef OPENSSL_NO_COMP
1361     if (compression != 0) {
1362         al = SSL_AD_ILLEGAL_PARAMETER;
1363         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1364                SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1365         goto f_err;
1366     }
1367     /*
1368      * If compression is disabled we'd better not try to resume a session
1369      * using compression.
1370      */
1371     if (s->session->compress_meth != 0) {
1372         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
1373         goto f_err;
1374     }
1375 #else
1376     if (s->hit && compression != s->session->compress_meth) {
1377         al = SSL_AD_ILLEGAL_PARAMETER;
1378         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1379                SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED);
1380         goto f_err;
1381     }
1382     if (compression == 0)
1383         comp = NULL;
1384     else if (!ssl_allow_compression(s)) {
1385         al = SSL_AD_ILLEGAL_PARAMETER;
1386         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_COMPRESSION_DISABLED);
1387         goto f_err;
1388     } else {
1389         comp = ssl3_comp_find(s->ctx->comp_methods, compression);
1390     }
1391
1392     if (compression != 0 && comp == NULL) {
1393         al = SSL_AD_ILLEGAL_PARAMETER;
1394         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1395                SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1396         goto f_err;
1397     } else {
1398         s->s3->tmp.new_compression = comp;
1399     }
1400 #endif
1401
1402     /* TLS extensions */
1403     if (!ssl_parse_serverhello_tlsext(s, pkt)) {
1404         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_PARSE_TLSEXT);
1405         goto err;
1406     }
1407
1408     if (PACKET_remaining(pkt) != 0) {
1409         /* wrong packet length */
1410         al = SSL_AD_DECODE_ERROR;
1411         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_BAD_PACKET_LENGTH);
1412         goto f_err;
1413     }
1414
1415 #ifndef OPENSSL_NO_SCTP
1416     if (SSL_IS_DTLS(s) && s->hit) {
1417         unsigned char sctpauthkey[64];
1418         char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
1419
1420         /*
1421          * Add new shared key for SCTP-Auth, will be ignored if
1422          * no SCTP used.
1423          */
1424         memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
1425                sizeof(DTLS1_SCTP_AUTH_LABEL));
1426
1427         if (SSL_export_keying_material(s, sctpauthkey,
1428                                    sizeof(sctpauthkey),
1429                                    labelbuffer,
1430                                    sizeof(labelbuffer), NULL, 0,
1431                                    0) <= 0)
1432             goto err;
1433
1434         BIO_ctrl(SSL_get_wbio(s),
1435                  BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
1436                  sizeof(sctpauthkey), sctpauthkey);
1437     }
1438 #endif
1439
1440     return MSG_PROCESS_CONTINUE_READING;
1441  f_err:
1442     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1443  err:
1444     ossl_statem_set_error(s);
1445     return MSG_PROCESS_ERROR;
1446 }
1447
1448 MSG_PROCESS_RETURN tls_process_server_certificate(SSL *s, PACKET *pkt)
1449 {
1450     int al, i, ret = MSG_PROCESS_ERROR, exp_idx;
1451     unsigned long cert_list_len, cert_len;
1452     X509 *x = NULL;
1453     unsigned char *certstart, *certbytes;
1454     STACK_OF(X509) *sk = NULL;
1455     EVP_PKEY *pkey = NULL;
1456
1457     if ((sk = sk_X509_new_null()) == NULL) {
1458         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, ERR_R_MALLOC_FAILURE);
1459         goto err;
1460     }
1461
1462     if (!PACKET_get_net_3(pkt, &cert_list_len)
1463             || PACKET_remaining(pkt) != cert_list_len) {
1464         al = SSL_AD_DECODE_ERROR;
1465         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
1466         goto f_err;
1467     }
1468     while (PACKET_remaining(pkt)) {
1469         if (!PACKET_get_net_3(pkt, &cert_len)
1470                 || !PACKET_get_bytes(pkt, &certbytes, cert_len)) {
1471             al = SSL_AD_DECODE_ERROR;
1472             SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1473                    SSL_R_CERT_LENGTH_MISMATCH);
1474             goto f_err;
1475         }
1476
1477         certstart = certbytes;
1478         x = d2i_X509(NULL, (const unsigned char **)&certbytes, cert_len);
1479         if (x == NULL) {
1480             al = SSL_AD_BAD_CERTIFICATE;
1481             SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, ERR_R_ASN1_LIB);
1482             goto f_err;
1483         }
1484         if (certbytes != (certstart + cert_len)) {
1485             al = SSL_AD_DECODE_ERROR;
1486             SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1487                    SSL_R_CERT_LENGTH_MISMATCH);
1488             goto f_err;
1489         }
1490         if (!sk_X509_push(sk, x)) {
1491             SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, ERR_R_MALLOC_FAILURE);
1492             goto err;
1493         }
1494         x = NULL;
1495     }
1496
1497     i = ssl_verify_cert_chain(s, sk);
1498     if (s->verify_mode != SSL_VERIFY_NONE && i <= 0) {
1499         al = ssl_verify_alarm_type(s->verify_result);
1500         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1501                SSL_R_CERTIFICATE_VERIFY_FAILED);
1502         goto f_err;
1503     }
1504     ERR_clear_error();          /* but we keep s->verify_result */
1505     if (i > 1) {
1506         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, i);
1507         al = SSL_AD_HANDSHAKE_FAILURE;
1508         goto f_err;
1509     }
1510
1511     s->session->peer_chain = sk;
1512     /*
1513      * Inconsistency alert: cert_chain does include the peer's certificate,
1514      * which we don't include in s3_srvr.c
1515      */
1516     x = sk_X509_value(sk, 0);
1517     sk = NULL;
1518     /*
1519      * VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end
1520      */
1521
1522     pkey = X509_get_pubkey(x);
1523
1524     if (pkey == NULL || EVP_PKEY_missing_parameters(pkey)) {
1525         x = NULL;
1526         al = SSL3_AL_FATAL;
1527         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1528                SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
1529         goto f_err;
1530     }
1531
1532     i = ssl_cert_type(x, pkey);
1533     if (i < 0) {
1534         x = NULL;
1535         al = SSL3_AL_FATAL;
1536         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1537                SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1538         goto f_err;
1539     }
1540
1541     exp_idx = ssl_cipher_get_cert_index(s->s3->tmp.new_cipher);
1542     if (exp_idx >= 0 && i != exp_idx
1543             && (exp_idx != SSL_PKEY_GOST_EC ||
1544                 (i != SSL_PKEY_GOST12_512 && i != SSL_PKEY_GOST12_256
1545                  && i != SSL_PKEY_GOST01))) {
1546         x = NULL;
1547         al = SSL_AD_ILLEGAL_PARAMETER;
1548         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1549                SSL_R_WRONG_CERTIFICATE_TYPE);
1550         goto f_err;
1551     }
1552     s->session->peer_type = i;
1553
1554     X509_free(s->session->peer);
1555     X509_up_ref(x);
1556     s->session->peer = x;
1557     s->session->verify_result = s->verify_result;
1558
1559     x = NULL;
1560     ret = MSG_PROCESS_CONTINUE_READING;
1561     goto done;
1562
1563  f_err:
1564     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1565  err:
1566     ossl_statem_set_error(s);
1567  done:
1568     EVP_PKEY_free(pkey);
1569     X509_free(x);
1570     sk_X509_pop_free(sk, X509_free);
1571     return ret;
1572 }
1573
1574 MSG_PROCESS_RETURN tls_process_key_exchange(SSL *s, PACKET *pkt)
1575 {
1576     EVP_MD_CTX md_ctx;
1577     int al, j;
1578     long alg_k, alg_a;
1579     EVP_PKEY *pkey = NULL;
1580     const EVP_MD *md = NULL;
1581 #ifndef OPENSSL_NO_RSA
1582     RSA *rsa = NULL;
1583 #endif
1584 #ifndef OPENSSL_NO_DH
1585     DH *dh = NULL;
1586 #endif
1587 #ifndef OPENSSL_NO_EC
1588     EC_KEY *ecdh = NULL;
1589     BN_CTX *bn_ctx = NULL;
1590     EC_POINT *srvr_ecpoint = NULL;
1591     int curve_nid = 0;
1592 #endif
1593     PACKET save_param_start, signature;
1594
1595     EVP_MD_CTX_init(&md_ctx);
1596
1597     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1598
1599     save_param_start = *pkt;
1600
1601 #ifndef OPENSSL_NO_DH
1602     DH_free(s->s3->peer_dh_tmp);
1603     s->s3->peer_dh_tmp = NULL;
1604 #endif
1605 #ifndef OPENSSL_NO_EC
1606     EC_KEY_free(s->s3->peer_ecdh_tmp);
1607     s->s3->peer_ecdh_tmp = NULL;
1608 #endif
1609
1610     alg_a = s->s3->tmp.new_cipher->algorithm_auth;
1611
1612     al = SSL_AD_DECODE_ERROR;
1613
1614 #ifndef OPENSSL_NO_PSK
1615     /* PSK ciphersuites are preceded by an identity hint */
1616     if (alg_k & SSL_PSK) {
1617         PACKET psk_identity_hint;
1618         if (!PACKET_get_length_prefixed_2(pkt, &psk_identity_hint)) {
1619             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
1620             goto f_err;
1621         }
1622
1623         /*
1624          * Store PSK identity hint for later use, hint is used in
1625          * ssl3_send_client_key_exchange.  Assume that the maximum length of
1626          * a PSK identity hint can be as long as the maximum length of a PSK
1627          * identity.
1628          */
1629         if (PACKET_remaining(&psk_identity_hint) > PSK_MAX_IDENTITY_LEN) {
1630             al = SSL_AD_HANDSHAKE_FAILURE;
1631             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG);
1632             goto f_err;
1633         }
1634
1635         if (PACKET_remaining(&psk_identity_hint) == 0) {
1636             OPENSSL_free(s->session->psk_identity_hint);
1637             s->session->psk_identity_hint = NULL;
1638         } else if (!PACKET_strndup(&psk_identity_hint,
1639                             &s->session->psk_identity_hint)) {
1640             al = SSL_AD_INTERNAL_ERROR;
1641             goto f_err;
1642         }
1643     }
1644
1645     /* Nothing else to do for plain PSK or RSAPSK */
1646     if (alg_k & (SSL_kPSK | SSL_kRSAPSK)) {
1647     } else
1648 #endif                          /* !OPENSSL_NO_PSK */
1649 #ifndef OPENSSL_NO_SRP
1650     if (alg_k & SSL_kSRP) {
1651         PACKET prime, generator, salt, server_pub;
1652         if (!PACKET_get_length_prefixed_2(pkt, &prime)
1653             || !PACKET_get_length_prefixed_2(pkt, &generator)
1654             || !PACKET_get_length_prefixed_1(pkt, &salt)
1655             || !PACKET_get_length_prefixed_2(pkt, &server_pub)) {
1656             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
1657             goto f_err;
1658         }
1659
1660         if ((s->srp_ctx.N =
1661              BN_bin2bn(PACKET_data(&prime),
1662                        PACKET_remaining(&prime), NULL)) == NULL
1663             || (s->srp_ctx.g =
1664                 BN_bin2bn(PACKET_data(&generator),
1665                           PACKET_remaining(&generator), NULL)) == NULL
1666             || (s->srp_ctx.s =
1667                 BN_bin2bn(PACKET_data(&salt),
1668                           PACKET_remaining(&salt), NULL)) == NULL
1669             || (s->srp_ctx.B =
1670                 BN_bin2bn(PACKET_data(&server_pub),
1671                           PACKET_remaining(&server_pub), NULL)) == NULL) {
1672             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_BN_LIB);
1673             goto err;
1674         }
1675
1676         if (!srp_verify_server_param(s, &al)) {
1677             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_BAD_SRP_PARAMETERS);
1678             goto f_err;
1679         }
1680
1681 /* We must check if there is a certificate */
1682         if (alg_a & (SSL_aRSA|SSL_aDSS))
1683             pkey = X509_get_pubkey(s->session->peer);
1684     }
1685 #endif                          /* !OPENSSL_NO_SRP */
1686 #ifndef OPENSSL_NO_DH
1687     else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
1688         PACKET prime, generator, pub_key;
1689
1690         if (!PACKET_get_length_prefixed_2(pkt, &prime)
1691             || !PACKET_get_length_prefixed_2(pkt, &generator)
1692             || !PACKET_get_length_prefixed_2(pkt, &pub_key)) {
1693             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
1694             goto f_err;
1695         }
1696
1697         if ((dh = DH_new()) == NULL) {
1698             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_DH_LIB);
1699             goto err;
1700         }
1701
1702         if ((dh->p = BN_bin2bn(PACKET_data(&prime),
1703                                PACKET_remaining(&prime), NULL)) == NULL
1704             || (dh->g = BN_bin2bn(PACKET_data(&generator),
1705                                   PACKET_remaining(&generator), NULL)) == NULL
1706             || (dh->pub_key =
1707                 BN_bin2bn(PACKET_data(&pub_key),
1708                           PACKET_remaining(&pub_key), NULL)) == NULL) {
1709             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_BN_LIB);
1710             goto err;
1711         }
1712
1713         if (BN_is_zero(dh->p) || BN_is_zero(dh->g) || BN_is_zero(dh->pub_key)) {
1714             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_BAD_DH_VALUE);
1715             goto f_err;
1716         }
1717
1718         if (!ssl_security(s, SSL_SECOP_TMP_DH, DH_security_bits(dh), 0, dh)) {
1719             al = SSL_AD_HANDSHAKE_FAILURE;
1720             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_DH_KEY_TOO_SMALL);
1721             goto f_err;
1722         }
1723         if (alg_a & (SSL_aRSA|SSL_aDSS))
1724             pkey = X509_get_pubkey(s->session->peer);
1725         /* else anonymous DH, so no certificate or pkey. */
1726
1727         s->s3->peer_dh_tmp = dh;
1728         dh = NULL;
1729     }
1730 #endif                          /* !OPENSSL_NO_DH */
1731
1732 #ifndef OPENSSL_NO_EC
1733     else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
1734         EC_GROUP *ngroup;
1735         const EC_GROUP *group;
1736         PACKET encoded_pt;
1737         unsigned char *ecparams;
1738
1739         if ((ecdh = EC_KEY_new()) == NULL) {
1740             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1741             goto err;
1742         }
1743
1744         /*
1745          * Extract elliptic curve parameters and the server's ephemeral ECDH
1746          * public key. For now we only support named (not generic) curves and
1747          * ECParameters in this case is just three bytes.
1748          */
1749         if (!PACKET_get_bytes(pkt, &ecparams, 3)) {
1750             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1751             goto f_err;
1752         }
1753         /*
1754          * Check curve is one of our preferences, if not server has sent an
1755          * invalid curve. ECParameters is 3 bytes.
1756          */
1757         if (!tls1_check_curve(s, ecparams, 3)) {
1758             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_WRONG_CURVE);
1759             goto f_err;
1760         }
1761
1762         if ((curve_nid = tls1_ec_curve_id2nid(*(ecparams + 2))) == 0) {
1763             al = SSL_AD_INTERNAL_ERROR;
1764             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE,
1765                    SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
1766             goto f_err;
1767         }
1768
1769         ngroup = EC_GROUP_new_by_curve_name(curve_nid);
1770         if (ngroup == NULL) {
1771             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_EC_LIB);
1772             goto err;
1773         }
1774         if (EC_KEY_set_group(ecdh, ngroup) == 0) {
1775             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_EC_LIB);
1776             goto err;
1777         }
1778         EC_GROUP_free(ngroup);
1779
1780         group = EC_KEY_get0_group(ecdh);
1781
1782         /* Next, get the encoded ECPoint */
1783         if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) ||
1784             ((bn_ctx = BN_CTX_new()) == NULL)) {
1785             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1786             goto err;
1787         }
1788
1789         if (!PACKET_get_length_prefixed_1(pkt, &encoded_pt)) {
1790             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
1791             goto f_err;
1792         }
1793
1794         if (EC_POINT_oct2point(group, srvr_ecpoint, PACKET_data(&encoded_pt),
1795                                PACKET_remaining(&encoded_pt), bn_ctx) == 0) {
1796             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_BAD_ECPOINT);
1797             goto f_err;
1798         }
1799
1800         /*
1801          * The ECC/TLS specification does not mention the use of DSA to sign
1802          * ECParameters in the server key exchange message. We do support RSA
1803          * and ECDSA.
1804          */
1805         if (0) ;
1806 # ifndef OPENSSL_NO_RSA
1807         else if (alg_a & SSL_aRSA)
1808             pkey = X509_get_pubkey(s->session->peer);
1809 # endif
1810 # ifndef OPENSSL_NO_EC
1811         else if (alg_a & SSL_aECDSA)
1812             pkey = X509_get_pubkey(s->session->peer);
1813 # endif
1814         /* else anonymous ECDH, so no certificate or pkey. */
1815         EC_KEY_set_public_key(ecdh, srvr_ecpoint);
1816         s->s3->peer_ecdh_tmp = ecdh;
1817         ecdh = NULL;
1818         BN_CTX_free(bn_ctx);
1819         bn_ctx = NULL;
1820         EC_POINT_free(srvr_ecpoint);
1821         srvr_ecpoint = NULL;
1822     } else if (alg_k) {
1823         al = SSL_AD_UNEXPECTED_MESSAGE;
1824         SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
1825         goto f_err;
1826     }
1827 #endif                          /* !OPENSSL_NO_EC */
1828
1829     /* if it was signed, check the signature */
1830     if (pkey != NULL) {
1831         PACKET params;
1832         /*
1833          * |pkt| now points to the beginning of the signature, so the difference
1834          * equals the length of the parameters.
1835          */
1836         if (!PACKET_get_sub_packet(&save_param_start, &params,
1837                                    PACKET_remaining(&save_param_start) -
1838                                    PACKET_remaining(pkt))) {
1839             al = SSL_AD_INTERNAL_ERROR;
1840             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1841             goto f_err;
1842         }
1843
1844         if (SSL_USE_SIGALGS(s)) {
1845             unsigned char *sigalgs;
1846             int rv;
1847             if (!PACKET_get_bytes(pkt, &sigalgs, 2)) {
1848                 SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1849                 goto f_err;
1850             }
1851             rv = tls12_check_peer_sigalg(&md, s, sigalgs, pkey);
1852             if (rv == -1)
1853                 goto err;
1854             else if (rv == 0) {
1855                 goto f_err;
1856             }
1857 #ifdef SSL_DEBUG
1858             fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
1859 #endif
1860         } else if (pkey->type == EVP_PKEY_RSA) {
1861             md = EVP_md5_sha1();
1862         } else {
1863             md = EVP_sha1();
1864         }
1865
1866         if (!PACKET_get_length_prefixed_2(pkt, &signature)
1867             || PACKET_remaining(pkt) != 0) {
1868             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
1869             goto f_err;
1870         }
1871         j = EVP_PKEY_size(pkey);
1872         if (j < 0) {
1873             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1874             goto f_err;
1875         }
1876
1877         /*
1878          * Check signature length
1879          */
1880         if (PACKET_remaining(&signature) > (size_t)j) {
1881             /* wrong packet length */
1882             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_WRONG_SIGNATURE_LENGTH);
1883             goto f_err;
1884         }
1885         if (EVP_VerifyInit_ex(&md_ctx, md, NULL) <= 0
1886                 || EVP_VerifyUpdate(&md_ctx, &(s->s3->client_random[0]),
1887                                     SSL3_RANDOM_SIZE) <= 0
1888                 || EVP_VerifyUpdate(&md_ctx, &(s->s3->server_random[0]),
1889                                     SSL3_RANDOM_SIZE) <= 0
1890                 || EVP_VerifyUpdate(&md_ctx, PACKET_data(&params),
1891                                     PACKET_remaining(&params)) <= 0) {
1892             al = SSL_AD_INTERNAL_ERROR;
1893             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_EVP_LIB);
1894             goto f_err;
1895         }
1896         if (EVP_VerifyFinal(&md_ctx, PACKET_data(&signature),
1897                             PACKET_remaining(&signature), pkey) <= 0) {
1898             /* bad signature */
1899             al = SSL_AD_DECRYPT_ERROR;
1900             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_BAD_SIGNATURE);
1901             goto f_err;
1902         }
1903     } else {
1904         /* aNULL, aSRP or PSK do not need public keys */
1905         if (!(alg_a & (SSL_aNULL | SSL_aSRP)) && !(alg_k & SSL_PSK)) {
1906             /* Might be wrong key type, check it */
1907             if (ssl3_check_cert_and_algorithm(s))
1908                 /* Otherwise this shouldn't happen */
1909                 SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1910             goto err;
1911         }
1912         /* still data left over */
1913         if (PACKET_remaining(pkt) != 0) {
1914             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_EXTRA_DATA_IN_MESSAGE);
1915             goto f_err;
1916         }
1917     }
1918     EVP_PKEY_free(pkey);
1919     EVP_MD_CTX_cleanup(&md_ctx);
1920     return MSG_PROCESS_CONTINUE_READING;
1921  f_err:
1922     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1923  err:
1924     EVP_PKEY_free(pkey);
1925 #ifndef OPENSSL_NO_RSA
1926     RSA_free(rsa);
1927 #endif
1928 #ifndef OPENSSL_NO_DH
1929     DH_free(dh);
1930 #endif
1931 #ifndef OPENSSL_NO_EC
1932     BN_CTX_free(bn_ctx);
1933     EC_POINT_free(srvr_ecpoint);
1934     EC_KEY_free(ecdh);
1935 #endif
1936     EVP_MD_CTX_cleanup(&md_ctx);
1937     ossl_statem_set_error(s);
1938     return MSG_PROCESS_ERROR;
1939 }
1940
1941 MSG_PROCESS_RETURN tls_process_certificate_request(SSL *s, PACKET *pkt)
1942 {
1943     int ret = MSG_PROCESS_ERROR;
1944     unsigned int list_len, ctype_num, i, name_len;
1945     X509_NAME *xn = NULL;
1946     unsigned char *data;
1947     unsigned char *namestart, *namebytes;
1948     STACK_OF(X509_NAME) *ca_sk = NULL;
1949
1950     if ((ca_sk = sk_X509_NAME_new(ca_dn_cmp)) == NULL) {
1951         SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
1952         goto err;
1953     }
1954
1955     /* get the certificate types */
1956     if (!PACKET_get_1(pkt, &ctype_num)
1957             || !PACKET_get_bytes(pkt, &data, ctype_num)) {
1958         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1959         SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, SSL_R_LENGTH_MISMATCH);
1960         goto err;
1961     }
1962     OPENSSL_free(s->cert->ctypes);
1963     s->cert->ctypes = NULL;
1964     if (ctype_num > SSL3_CT_NUMBER) {
1965         /* If we exceed static buffer copy all to cert structure */
1966         s->cert->ctypes = OPENSSL_malloc(ctype_num);
1967         if (s->cert->ctypes == NULL) {
1968             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
1969             goto err;
1970         }
1971         memcpy(s->cert->ctypes, data, ctype_num);
1972         s->cert->ctype_num = (size_t)ctype_num;
1973         ctype_num = SSL3_CT_NUMBER;
1974     }
1975     for (i = 0; i < ctype_num; i++)
1976         s->s3->tmp.ctype[i] = data[i];
1977
1978     if (SSL_USE_SIGALGS(s)) {
1979         if (!PACKET_get_net_2(pkt, &list_len)
1980                 || !PACKET_get_bytes(pkt, &data, list_len)) {
1981             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1982             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST,
1983                    SSL_R_LENGTH_MISMATCH);
1984             goto err;
1985         }
1986
1987         /* Clear certificate digests and validity flags */
1988         for (i = 0; i < SSL_PKEY_NUM; i++) {
1989             s->s3->tmp.md[i] = NULL;
1990             s->s3->tmp.valid_flags[i] = 0;
1991         }
1992         if ((list_len & 1) || !tls1_save_sigalgs(s, data, list_len)) {
1993             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1994             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST,
1995                    SSL_R_SIGNATURE_ALGORITHMS_ERROR);
1996             goto err;
1997         }
1998         if (!tls1_process_sigalgs(s)) {
1999             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2000             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
2001             goto err;
2002         }
2003     } else {
2004         ssl_set_default_md(s);
2005     }
2006
2007     /* get the CA RDNs */
2008     if (!PACKET_get_net_2(pkt, &list_len)
2009             || PACKET_remaining(pkt) != list_len) {
2010         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2011         SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, SSL_R_LENGTH_MISMATCH);
2012         goto err;
2013     }
2014
2015     while (PACKET_remaining(pkt)) {
2016         if (!PACKET_get_net_2(pkt, &name_len)
2017                 || !PACKET_get_bytes(pkt, &namebytes, name_len)) {
2018             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2019             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST,
2020                    SSL_R_LENGTH_MISMATCH);
2021             goto err;
2022         }
2023
2024         namestart = namebytes;
2025
2026         if ((xn = d2i_X509_NAME(NULL, (const unsigned char **)&namebytes,
2027                                 name_len)) == NULL) {
2028             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2029             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_ASN1_LIB);
2030             goto err;
2031         }
2032
2033         if (namebytes != (namestart + name_len)) {
2034             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2035             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST,
2036                    SSL_R_CA_DN_LENGTH_MISMATCH);
2037             goto err;
2038         }
2039         if (!sk_X509_NAME_push(ca_sk, xn)) {
2040             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
2041             goto err;
2042         }
2043     }
2044
2045     /* we should setup a certificate to return.... */
2046     s->s3->tmp.cert_req = 1;
2047     s->s3->tmp.ctype_num = ctype_num;
2048     sk_X509_NAME_pop_free(s->s3->tmp.ca_names, X509_NAME_free);
2049     s->s3->tmp.ca_names = ca_sk;
2050     ca_sk = NULL;
2051
2052     ret = MSG_PROCESS_CONTINUE_READING;
2053     goto done;
2054  err:
2055     ossl_statem_set_error(s);
2056  done:
2057     sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
2058     return ret;
2059 }
2060
2061 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
2062 {
2063     return (X509_NAME_cmp(*a, *b));
2064 }
2065
2066 MSG_PROCESS_RETURN tls_process_new_session_ticket(SSL *s, PACKET *pkt)
2067 {
2068     int al;
2069     unsigned int ticklen;
2070     unsigned long ticket_lifetime_hint;
2071
2072     if (!PACKET_get_net_4(pkt, &ticket_lifetime_hint)
2073             || !PACKET_get_net_2(pkt, &ticklen)
2074             || PACKET_remaining(pkt) != ticklen) {
2075         al = SSL_AD_DECODE_ERROR;
2076         SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
2077         goto f_err;
2078     }
2079
2080     /* Server is allowed to change its mind and send an empty ticket. */
2081     if (ticklen == 0)
2082         return MSG_PROCESS_CONTINUE_READING;
2083
2084     if (s->session->session_id_length > 0) {
2085         int i = s->session_ctx->session_cache_mode;
2086         SSL_SESSION *new_sess;
2087         /*
2088          * We reused an existing session, so we need to replace it with a new
2089          * one
2090          */
2091         if (i & SSL_SESS_CACHE_CLIENT) {
2092             /*
2093              * Remove the old session from the cache
2094              */
2095             if (i & SSL_SESS_CACHE_NO_INTERNAL_STORE) {
2096                 if (s->session_ctx->remove_session_cb != NULL)
2097                     s->session_ctx->remove_session_cb(s->session_ctx,
2098                                                       s->session);
2099             } else {
2100                 /* We carry on if this fails */
2101                 SSL_CTX_remove_session(s->session_ctx, s->session);
2102             }
2103         }
2104
2105         if ((new_sess = ssl_session_dup(s->session, 0)) == 0) {
2106             al = SSL_AD_INTERNAL_ERROR;
2107             SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
2108             goto f_err;
2109         }
2110
2111         SSL_SESSION_free(s->session);
2112         s->session = new_sess;
2113     }
2114
2115     OPENSSL_free(s->session->tlsext_tick);
2116     s->session->tlsext_ticklen = 0;
2117
2118     s->session->tlsext_tick = OPENSSL_malloc(ticklen);
2119     if (s->session->tlsext_tick == NULL) {
2120         SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
2121         goto err;
2122     }
2123     if (!PACKET_copy_bytes(pkt, s->session->tlsext_tick, ticklen)) {
2124         al = SSL_AD_DECODE_ERROR;
2125         SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
2126         goto f_err;
2127     }
2128
2129     s->session->tlsext_tick_lifetime_hint = ticket_lifetime_hint;
2130     s->session->tlsext_ticklen = ticklen;
2131     /*
2132      * There are two ways to detect a resumed ticket session. One is to set
2133      * an appropriate session ID and then the server must return a match in
2134      * ServerHello. This allows the normal client session ID matching to work
2135      * and we know much earlier that the ticket has been accepted. The
2136      * other way is to set zero length session ID when the ticket is
2137      * presented and rely on the handshake to determine session resumption.
2138      * We choose the former approach because this fits in with assumptions
2139      * elsewhere in OpenSSL. The session ID is set to the SHA256 (or SHA1 is
2140      * SHA256 is disabled) hash of the ticket.
2141      */
2142     EVP_Digest(s->session->tlsext_tick, ticklen,
2143                s->session->session_id, &s->session->session_id_length,
2144                EVP_sha256(), NULL);
2145     return MSG_PROCESS_CONTINUE_READING;
2146  f_err:
2147     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2148  err:
2149     ossl_statem_set_error(s);
2150     return MSG_PROCESS_ERROR;
2151 }
2152
2153 MSG_PROCESS_RETURN tls_process_cert_status(SSL *s, PACKET *pkt)
2154 {
2155     int al;
2156     unsigned long resplen;
2157     unsigned int type;
2158
2159     if (!PACKET_get_1(pkt, &type)
2160             || type != TLSEXT_STATUSTYPE_ocsp) {
2161         al = SSL_AD_DECODE_ERROR;
2162         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, SSL_R_UNSUPPORTED_STATUS_TYPE);
2163         goto f_err;
2164     }
2165     if (!PACKET_get_net_3(pkt, &resplen)
2166             || PACKET_remaining(pkt) != resplen) {
2167         al = SSL_AD_DECODE_ERROR;
2168         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, SSL_R_LENGTH_MISMATCH);
2169         goto f_err;
2170     }
2171     OPENSSL_free(s->tlsext_ocsp_resp);
2172     s->tlsext_ocsp_resp = OPENSSL_malloc(resplen);
2173     if (s->tlsext_ocsp_resp == NULL) {
2174         al = SSL_AD_INTERNAL_ERROR;
2175         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, ERR_R_MALLOC_FAILURE);
2176         goto f_err;
2177     }
2178     if (!PACKET_copy_bytes(pkt, s->tlsext_ocsp_resp, resplen)) {
2179         al = SSL_AD_DECODE_ERROR;
2180         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, SSL_R_LENGTH_MISMATCH);
2181         goto f_err;
2182     }
2183     s->tlsext_ocsp_resplen = resplen;
2184     if (s->ctx->tlsext_status_cb) {
2185         int ret;
2186         ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
2187         if (ret == 0) {
2188             al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
2189             SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, SSL_R_INVALID_STATUS_RESPONSE);
2190             goto f_err;
2191         }
2192         if (ret < 0) {
2193             al = SSL_AD_INTERNAL_ERROR;
2194             SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, ERR_R_MALLOC_FAILURE);
2195             goto f_err;
2196         }
2197     }
2198     return MSG_PROCESS_CONTINUE_READING;
2199  f_err:
2200     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2201     ossl_statem_set_error(s);
2202     return MSG_PROCESS_ERROR;
2203 }
2204
2205 MSG_PROCESS_RETURN tls_process_server_done(SSL *s, PACKET *pkt)
2206 {
2207     if (PACKET_remaining(pkt) > 0) {
2208         /* should contain no data */
2209         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2210         SSLerr(SSL_F_TLS_PROCESS_SERVER_DONE, SSL_R_LENGTH_MISMATCH);
2211         ossl_statem_set_error(s);
2212         return MSG_PROCESS_ERROR;
2213     }
2214
2215 #ifndef OPENSSL_NO_SRP
2216     if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) {
2217         if (SRP_Calc_A_param(s) <= 0) {
2218             SSLerr(SSL_F_TLS_PROCESS_SERVER_DONE, SSL_R_SRP_A_CALC);
2219             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2220             ossl_statem_set_error(s);
2221             return MSG_PROCESS_ERROR;
2222         }
2223     }
2224 #endif
2225
2226     /*
2227      * at this point we check that we have the required stuff from
2228      * the server
2229      */
2230     if (!ssl3_check_cert_and_algorithm(s)) {
2231         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2232         ossl_statem_set_error(s);
2233         return MSG_PROCESS_ERROR;
2234     }
2235
2236 #ifndef OPENSSL_NO_SCTP
2237     /* Only applies to renegotiation */
2238     if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))
2239             && s->renegotiate != 0)
2240         return MSG_PROCESS_CONTINUE_PROCESSING;
2241     else
2242 #endif
2243         return MSG_PROCESS_FINISHED_READING;
2244 }
2245
2246 int tls_construct_client_key_exchange(SSL *s)
2247 {
2248     unsigned char *p;
2249     int n;
2250 #ifndef OPENSSL_NO_PSK
2251     size_t pskhdrlen = 0;
2252 #endif
2253     unsigned long alg_k;
2254 #ifndef OPENSSL_NO_RSA
2255     unsigned char *q;
2256     EVP_PKEY *pkey = NULL;
2257 #endif
2258 #ifndef OPENSSL_NO_EC
2259     EC_KEY *clnt_ecdh = NULL;
2260     const EC_POINT *srvr_ecpoint = NULL;
2261     EVP_PKEY *srvr_pub_pkey = NULL;
2262     unsigned char *encodedPoint = NULL;
2263     int encoded_pt_len = 0;
2264     BN_CTX *bn_ctx = NULL;
2265 #endif
2266     unsigned char *pms = NULL;
2267     size_t pmslen = 0;
2268     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2269
2270     p = ssl_handshake_start(s);
2271
2272
2273 #ifndef OPENSSL_NO_PSK
2274     if (alg_k & SSL_PSK) {
2275         int psk_err = 1;
2276         /*
2277          * The callback needs PSK_MAX_IDENTITY_LEN + 1 bytes to return a
2278          * \0-terminated identity. The last byte is for us for simulating
2279          * strnlen.
2280          */
2281         char identity[PSK_MAX_IDENTITY_LEN + 1];
2282         size_t identitylen;
2283         unsigned char psk[PSK_MAX_PSK_LEN];
2284         size_t psklen;
2285
2286         if (s->psk_client_callback == NULL) {
2287             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2288                    SSL_R_PSK_NO_CLIENT_CB);
2289             goto err;
2290         }
2291
2292         memset(identity, 0, sizeof(identity));
2293
2294         psklen = s->psk_client_callback(s, s->session->psk_identity_hint,
2295                                         identity, sizeof(identity) - 1,
2296                                         psk, sizeof(psk));
2297
2298         if (psklen > PSK_MAX_PSK_LEN) {
2299             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2300                    ERR_R_INTERNAL_ERROR);
2301             goto psk_err;
2302         } else if (psklen == 0) {
2303             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2304                    SSL_R_PSK_IDENTITY_NOT_FOUND);
2305             goto psk_err;
2306         }
2307
2308         OPENSSL_free(s->s3->tmp.psk);
2309         s->s3->tmp.psk = BUF_memdup(psk, psklen);
2310         OPENSSL_cleanse(psk, psklen);
2311
2312         if (s->s3->tmp.psk == NULL) {
2313             OPENSSL_cleanse(identity, sizeof(identity));
2314             goto memerr;
2315         }
2316
2317         s->s3->tmp.psklen = psklen;
2318
2319         identitylen = strlen(identity);
2320         if (identitylen > PSK_MAX_IDENTITY_LEN) {
2321             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2322                    ERR_R_INTERNAL_ERROR);
2323             goto psk_err;
2324         }
2325         OPENSSL_free(s->session->psk_identity);
2326         s->session->psk_identity = BUF_strdup(identity);
2327         if (s->session->psk_identity == NULL) {
2328             OPENSSL_cleanse(identity, sizeof(identity));
2329             goto memerr;
2330         }
2331
2332         s2n(identitylen, p);
2333         memcpy(p, identity, identitylen);
2334         pskhdrlen = 2 + identitylen;
2335         p += identitylen;
2336         psk_err = 0;
2337 psk_err:
2338         OPENSSL_cleanse(identity, sizeof(identity));
2339         if (psk_err != 0) {
2340             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2341             goto err;
2342         }
2343     }
2344     if (alg_k & SSL_kPSK) {
2345         n = 0;
2346     } else
2347 #endif
2348
2349     /* Fool emacs indentation */
2350     if (0) {
2351     }
2352 #ifndef OPENSSL_NO_RSA
2353     else if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
2354         RSA *rsa;
2355         pmslen = SSL_MAX_MASTER_KEY_LENGTH;
2356         pms = OPENSSL_malloc(pmslen);
2357         if (pms == NULL)
2358             goto memerr;
2359
2360         if (s->session->peer == NULL) {
2361             /*
2362              * We should always have a server certificate with SSL_kRSA.
2363              */
2364             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2365                    ERR_R_INTERNAL_ERROR);
2366             goto err;
2367         }
2368
2369         pkey = X509_get_pubkey(s->session->peer);
2370         if ((pkey == NULL) || (pkey->type != EVP_PKEY_RSA)
2371             || (pkey->pkey.rsa == NULL)) {
2372             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2373                    ERR_R_INTERNAL_ERROR);
2374             EVP_PKEY_free(pkey);
2375             goto err;
2376         }
2377         rsa = pkey->pkey.rsa;
2378         EVP_PKEY_free(pkey);
2379
2380         pms[0] = s->client_version >> 8;
2381         pms[1] = s->client_version & 0xff;
2382         if (RAND_bytes(pms + 2, pmslen - 2) <= 0)
2383             goto err;
2384
2385         q = p;
2386         /* Fix buf for TLS and beyond */
2387         if (s->version > SSL3_VERSION)
2388             p += 2;
2389         n = RSA_public_encrypt(pmslen, pms, p, rsa, RSA_PKCS1_PADDING);
2390 # ifdef PKCS1_CHECK
2391         if (s->options & SSL_OP_PKCS1_CHECK_1)
2392             p[1]++;
2393         if (s->options & SSL_OP_PKCS1_CHECK_2)
2394             tmp_buf[0] = 0x70;
2395 # endif
2396         if (n <= 0) {
2397             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2398                    SSL_R_BAD_RSA_ENCRYPT);
2399             goto err;
2400         }
2401
2402         /* Fix buf for TLS and beyond */
2403         if (s->version > SSL3_VERSION) {
2404             s2n(n, q);
2405             n += 2;
2406         }
2407     }
2408 #endif
2409 #ifndef OPENSSL_NO_DH
2410     else if (alg_k & (SSL_kDHE | SSL_kDHr | SSL_kDHd | SSL_kDHEPSK)) {
2411         DH *dh_srvr, *dh_clnt;
2412         if (s->s3->peer_dh_tmp != NULL)
2413             dh_srvr = s->s3->peer_dh_tmp;
2414         else {
2415             /* we get them from the cert */
2416             EVP_PKEY *spkey = NULL;
2417             dh_srvr = NULL;
2418             spkey = X509_get_pubkey(s->session->peer);
2419             if (spkey) {
2420                 dh_srvr = EVP_PKEY_get1_DH(spkey);
2421                 EVP_PKEY_free(spkey);
2422             }
2423             if (dh_srvr == NULL) {
2424                 SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2425                        ERR_R_INTERNAL_ERROR);
2426                 goto err;
2427             }
2428         }
2429         if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY) {
2430             /* Use client certificate key */
2431             EVP_PKEY *clkey = s->cert->key->privatekey;
2432             dh_clnt = NULL;
2433             if (clkey)
2434                 dh_clnt = EVP_PKEY_get1_DH(clkey);
2435             if (dh_clnt == NULL) {
2436                 SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2437                        ERR_R_INTERNAL_ERROR);
2438                 goto err;
2439             }
2440         } else {
2441             /* generate a new random key */
2442             if ((dh_clnt = DHparams_dup(dh_srvr)) == NULL) {
2443                 SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
2444                 goto err;
2445             }
2446             if (!DH_generate_key(dh_clnt)) {
2447                 SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
2448                 DH_free(dh_clnt);
2449                 goto err;
2450             }
2451         }
2452
2453         pmslen = DH_size(dh_clnt);
2454         pms = OPENSSL_malloc(pmslen);
2455         if (pms == NULL)
2456             goto memerr;
2457
2458         /*
2459          * use the 'p' output buffer for the DH key, but make sure to
2460          * clear it out afterwards
2461          */
2462
2463         n = DH_compute_key(pms, dh_srvr->pub_key, dh_clnt);
2464         if (s->s3->peer_dh_tmp == NULL)
2465             DH_free(dh_srvr);
2466
2467         if (n <= 0) {
2468             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
2469             DH_free(dh_clnt);
2470             goto err;
2471         }
2472         pmslen = n;
2473
2474         if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY)
2475             n = 0;
2476         else {
2477             /* send off the data */
2478             n = BN_num_bytes(dh_clnt->pub_key);
2479             s2n(n, p);
2480             BN_bn2bin(dh_clnt->pub_key, p);
2481             n += 2;
2482         }
2483
2484         DH_free(dh_clnt);
2485     }
2486 #endif
2487
2488 #ifndef OPENSSL_NO_EC
2489     else if (alg_k & (SSL_kECDHE | SSL_kECDHr | SSL_kECDHe | SSL_kECDHEPSK)) {
2490         const EC_GROUP *srvr_group = NULL;
2491         EC_KEY *tkey;
2492         int ecdh_clnt_cert = 0;
2493         int field_size = 0;
2494         /*
2495          * Did we send out the client's ECDH share for use in premaster
2496          * computation as part of client certificate? If so, set
2497          * ecdh_clnt_cert to 1.
2498          */
2499         if ((alg_k & (SSL_kECDHr | SSL_kECDHe)) && (s->cert != NULL)) {
2500             /*-
2501              * XXX: For now, we do not support client
2502              * authentication using ECDH certificates.
2503              * To add such support, one needs to add
2504              * code that checks for appropriate
2505              * conditions and sets ecdh_clnt_cert to 1.
2506              * For example, the cert have an ECC
2507              * key on the same curve as the server's
2508              * and the key should be authorized for
2509              * key agreement.
2510              *
2511              * One also needs to add code in ssl3_connect
2512              * to skip sending the certificate verify
2513              * message.
2514              *
2515              * if ((s->cert->key->privatekey != NULL) &&
2516              *     (s->cert->key->privatekey->type ==
2517              *      EVP_PKEY_EC) && ...)
2518              * ecdh_clnt_cert = 1;
2519              */
2520         }
2521
2522         if (s->s3->peer_ecdh_tmp != NULL) {
2523             tkey = s->s3->peer_ecdh_tmp;
2524         } else {
2525             /* Get the Server Public Key from Cert */
2526             srvr_pub_pkey = X509_get_pubkey(s->session->peer);
2527             if ((srvr_pub_pkey == NULL)
2528                 || (srvr_pub_pkey->type != EVP_PKEY_EC)
2529                 || (srvr_pub_pkey->pkey.ec == NULL)) {
2530                 SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2531                        ERR_R_INTERNAL_ERROR);
2532                 goto err;
2533             }
2534
2535             tkey = srvr_pub_pkey->pkey.ec;
2536         }
2537
2538         srvr_group = EC_KEY_get0_group(tkey);
2539         srvr_ecpoint = EC_KEY_get0_public_key(tkey);
2540
2541         if ((srvr_group == NULL) || (srvr_ecpoint == NULL)) {
2542             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2543                    ERR_R_INTERNAL_ERROR);
2544             goto err;
2545         }
2546
2547         if ((clnt_ecdh = EC_KEY_new()) == NULL) {
2548             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2549                    ERR_R_MALLOC_FAILURE);
2550             goto err;
2551         }
2552
2553         if (!EC_KEY_set_group(clnt_ecdh, srvr_group)) {
2554             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2555             goto err;
2556         }
2557         if (ecdh_clnt_cert) {
2558             /*
2559              * Reuse key info from our certificate We only need our
2560              * private key to perform the ECDH computation.
2561              */
2562             const BIGNUM *priv_key;
2563             tkey = s->cert->key->privatekey->pkey.ec;
2564             priv_key = EC_KEY_get0_private_key(tkey);
2565             if (priv_key == NULL) {
2566                 SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2567                        ERR_R_MALLOC_FAILURE);
2568                 goto err;
2569             }
2570             if (!EC_KEY_set_private_key(clnt_ecdh, priv_key)) {
2571                 SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2572                 goto err;
2573             }
2574         } else {
2575             /* Generate a new ECDH key pair */
2576             if (!(EC_KEY_generate_key(clnt_ecdh))) {
2577                 SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2578                        ERR_R_ECDH_LIB);
2579                 goto err;
2580             }
2581         }
2582
2583         /*
2584          * use the 'p' output buffer for the ECDH key, but make sure to
2585          * clear it out afterwards
2586          */
2587
2588         field_size = EC_GROUP_get_degree(srvr_group);
2589         if (field_size <= 0) {
2590             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2591             goto err;
2592         }
2593         pmslen = (field_size + 7) / 8;
2594         pms = OPENSSL_malloc(pmslen);
2595         if (pms == NULL)
2596             goto memerr;
2597         n = ECDH_compute_key(pms, pmslen, srvr_ecpoint, clnt_ecdh, NULL);
2598         if (n <= 0 || pmslen != (size_t)n) {
2599             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2600             goto err;
2601         }
2602
2603         if (ecdh_clnt_cert) {
2604             /* Send empty client key exch message */
2605             n = 0;
2606         } else {
2607             /*
2608              * First check the size of encoding and allocate memory
2609              * accordingly.
2610              */
2611             encoded_pt_len =
2612                 EC_POINT_point2oct(srvr_group,
2613                                    EC_KEY_get0_public_key(clnt_ecdh),
2614                                    POINT_CONVERSION_UNCOMPRESSED,
2615                                    NULL, 0, NULL);
2616
2617             encodedPoint = (unsigned char *)
2618                 OPENSSL_malloc(encoded_pt_len * sizeof(unsigned char));
2619             bn_ctx = BN_CTX_new();
2620             if ((encodedPoint == NULL) || (bn_ctx == NULL)) {
2621                 SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2622                        ERR_R_MALLOC_FAILURE);
2623                 goto err;
2624             }
2625
2626             /* Encode the public key */
2627             n = EC_POINT_point2oct(srvr_group,
2628                                    EC_KEY_get0_public_key(clnt_ecdh),
2629                                    POINT_CONVERSION_UNCOMPRESSED,
2630                                    encodedPoint, encoded_pt_len, bn_ctx);
2631
2632             *p = n;         /* length of encoded point */
2633             /* Encoded point will be copied here */
2634             p += 1;
2635             /* copy the point */
2636             memcpy(p, encodedPoint, n);
2637             /* increment n to account for length field */
2638             n += 1;
2639         }
2640
2641         /* Free allocated memory */
2642         BN_CTX_free(bn_ctx);
2643         OPENSSL_free(encodedPoint);
2644         EC_KEY_free(clnt_ecdh);
2645         EVP_PKEY_free(srvr_pub_pkey);
2646     }
2647 #endif                          /* !OPENSSL_NO_EC */
2648 #ifndef OPENSSL_NO_GOST
2649     else if (alg_k & SSL_kGOST) {
2650         /* GOST key exchange message creation */
2651         EVP_PKEY_CTX *pkey_ctx;
2652         X509 *peer_cert;
2653         size_t msglen;
2654         unsigned int md_len;
2655         unsigned char shared_ukm[32], tmp[256];
2656         EVP_MD_CTX *ukm_hash;
2657         EVP_PKEY *pub_key;
2658         int dgst_nid = NID_id_GostR3411_94;
2659         if ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aGOST12) != 0)
2660             dgst_nid = NID_id_GostR3411_2012_256;
2661
2662
2663         pmslen = 32;
2664         pms = OPENSSL_malloc(pmslen);
2665         if (pms == NULL)
2666             goto memerr;
2667
2668         /*
2669          * Get server sertificate PKEY and create ctx from it
2670          */
2671         peer_cert = s->session->peer;
2672         if (!peer_cert) {
2673             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2674                    SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
2675             goto err;
2676         }
2677
2678         pkey_ctx = EVP_PKEY_CTX_new(pub_key =
2679                                     X509_get_pubkey(peer_cert), NULL);
2680         if (pkey_ctx == NULL) {
2681             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2682                    ERR_R_MALLOC_FAILURE);
2683             goto err;
2684         }
2685         /*
2686          * If we have send a certificate, and certificate key
2687          * parameters match those of server certificate, use
2688          * certificate key for key exchange
2689          */
2690
2691         /* Otherwise, generate ephemeral key pair */
2692
2693         if (pkey_ctx == NULL
2694                 || EVP_PKEY_encrypt_init(pkey_ctx) <= 0
2695                 /* Generate session key */
2696                 || RAND_bytes(pms, pmslen) <= 0) {
2697             EVP_PKEY_CTX_free(pkey_ctx);
2698             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2699                    ERR_R_INTERNAL_ERROR);
2700             goto err;
2701         };
2702         /*
2703          * If we have client certificate, use its secret as peer key
2704          */
2705         if (s->s3->tmp.cert_req && s->cert->key->privatekey) {
2706             if (EVP_PKEY_derive_set_peer
2707                 (pkey_ctx, s->cert->key->privatekey) <= 0) {
2708                 /*
2709                  * If there was an error - just ignore it. Ephemeral key
2710                  * * would be used
2711                  */
2712                 ERR_clear_error();
2713             }
2714         }
2715         /*
2716          * Compute shared IV and store it in algorithm-specific context
2717          * data
2718          */
2719         ukm_hash = EVP_MD_CTX_create();
2720         if (EVP_DigestInit(ukm_hash,
2721                            EVP_get_digestbynid(dgst_nid)) <= 0
2722                 || EVP_DigestUpdate(ukm_hash, s->s3->client_random,
2723                                     SSL3_RANDOM_SIZE) <= 0
2724                 || EVP_DigestUpdate(ukm_hash, s->s3->server_random,
2725                                     SSL3_RANDOM_SIZE) <= 0
2726                 || EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len) <= 0) {
2727             EVP_MD_CTX_destroy(ukm_hash);
2728             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2729                    ERR_R_INTERNAL_ERROR);
2730             goto err;
2731         }
2732         EVP_MD_CTX_destroy(ukm_hash);
2733         if (EVP_PKEY_CTX_ctrl
2734             (pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT, EVP_PKEY_CTRL_SET_IV, 8,
2735              shared_ukm) < 0) {
2736             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2737                    SSL_R_LIBRARY_BUG);
2738             goto err;
2739         }
2740         /* Make GOST keytransport blob message */
2741         /*
2742          * Encapsulate it into sequence
2743          */
2744         *(p++) = V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED;
2745         msglen = 255;
2746         if (EVP_PKEY_encrypt(pkey_ctx, tmp, &msglen, pms, pmslen) <= 0) {
2747             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2748                    SSL_R_LIBRARY_BUG);
2749             goto err;
2750         }
2751         if (msglen >= 0x80) {
2752             *(p++) = 0x81;
2753             *(p++) = msglen & 0xff;
2754             n = msglen + 3;
2755         } else {
2756             *(p++) = msglen & 0xff;
2757             n = msglen + 2;
2758         }
2759         memcpy(p, tmp, msglen);
2760         /* Check if pubkey from client certificate was used */
2761         if (EVP_PKEY_CTX_ctrl
2762             (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0) {
2763             /* Set flag "skip certificate verify" */
2764             s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
2765         }
2766         EVP_PKEY_CTX_free(pkey_ctx);
2767         EVP_PKEY_free(pub_key);
2768
2769     }
2770 #endif
2771 #ifndef OPENSSL_NO_SRP
2772     else if (alg_k & SSL_kSRP) {
2773         if (s->srp_ctx.A != NULL) {
2774             /* send off the data */
2775             n = BN_num_bytes(s->srp_ctx.A);
2776             s2n(n, p);
2777             BN_bn2bin(s->srp_ctx.A, p);
2778             n += 2;
2779         } else {
2780             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2781                    ERR_R_INTERNAL_ERROR);
2782             goto err;
2783         }
2784         OPENSSL_free(s->session->srp_username);
2785         s->session->srp_username = BUF_strdup(s->srp_ctx.login);
2786         if (s->session->srp_username == NULL) {
2787             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2788                    ERR_R_MALLOC_FAILURE);
2789             goto err;
2790         }
2791     }
2792 #endif
2793     else {
2794         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2795         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2796         goto err;
2797     }
2798
2799 #ifndef OPENSSL_NO_PSK
2800     n += pskhdrlen;
2801 #endif
2802
2803     if (!ssl_set_handshake_header(s, SSL3_MT_CLIENT_KEY_EXCHANGE, n)) {
2804         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2805         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2806         goto err;
2807     }
2808
2809     s->s3->tmp.pms = pms;
2810     s->s3->tmp.pmslen = pmslen;
2811
2812     return 1;
2813  memerr:
2814     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2815     SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2816  err:
2817     OPENSSL_clear_free(pms, pmslen);
2818     s->s3->tmp.pms = NULL;
2819 #ifndef OPENSSL_NO_EC
2820     BN_CTX_free(bn_ctx);
2821     OPENSSL_free(encodedPoint);
2822     EC_KEY_free(clnt_ecdh);
2823     EVP_PKEY_free(srvr_pub_pkey);
2824 #endif
2825 #ifndef OPENSSL_NO_PSK
2826     OPENSSL_clear_free(s->s3->tmp.psk, s->s3->tmp.psklen);
2827     s->s3->tmp.psk = NULL;
2828 #endif
2829     ossl_statem_set_error(s);
2830     return 0;
2831 }
2832
2833 int tls_client_key_exchange_post_work(SSL *s)
2834 {
2835     unsigned char *pms = NULL;
2836     size_t pmslen = 0;
2837
2838 #ifndef OPENSSL_NO_SRP
2839     /* Check for SRP */
2840     if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) {
2841         if (!srp_generate_client_master_secret(s)) {
2842             SSLerr(SSL_F_TLS_CLIENT_KEY_EXCHANGE_POST_WORK,
2843                    ERR_R_INTERNAL_ERROR);
2844             goto err;
2845         }
2846         return 1;
2847     }
2848 #endif
2849     pms = s->s3->tmp.pms;
2850     pmslen = s->s3->tmp.pmslen;
2851
2852     if (pms == NULL && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
2853         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2854         SSLerr(SSL_F_TLS_CLIENT_KEY_EXCHANGE_POST_WORK, ERR_R_MALLOC_FAILURE);
2855         goto err;
2856     }
2857     if (!ssl_generate_master_secret(s, pms, pmslen, 1)) {
2858         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2859         SSLerr(SSL_F_TLS_CLIENT_KEY_EXCHANGE_POST_WORK, ERR_R_INTERNAL_ERROR);
2860         goto err;
2861     }
2862
2863 #ifndef OPENSSL_NO_SCTP
2864     if (SSL_IS_DTLS(s)) {
2865         unsigned char sctpauthkey[64];
2866         char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
2867
2868         /*
2869          * Add new shared key for SCTP-Auth, will be ignored if no SCTP
2870          * used.
2871          */
2872         memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
2873                sizeof(DTLS1_SCTP_AUTH_LABEL));
2874
2875         if (SSL_export_keying_material(s, sctpauthkey,
2876                                    sizeof(sctpauthkey), labelbuffer,
2877                                    sizeof(labelbuffer), NULL, 0, 0) <= 0)
2878             goto err;
2879
2880         BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
2881                  sizeof(sctpauthkey), sctpauthkey);
2882     }
2883 #endif
2884
2885     return 1;
2886  err:
2887     OPENSSL_clear_free(pms, pmslen);
2888     s->s3->tmp.pms = NULL;
2889     return 0;
2890 }
2891
2892 int tls_construct_client_verify(SSL *s)
2893 {
2894     unsigned char *p;
2895     EVP_PKEY *pkey;
2896     const EVP_MD *md = s->s3->tmp.md[s->cert->key - s->cert->pkeys];
2897     EVP_MD_CTX mctx;
2898     unsigned u = 0;
2899     unsigned long n = 0;
2900     long hdatalen = 0;
2901     void *hdata;
2902
2903     EVP_MD_CTX_init(&mctx);
2904
2905     p = ssl_handshake_start(s);
2906     pkey = s->cert->key->privatekey;
2907
2908     hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
2909     if (hdatalen <= 0) {
2910         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
2911         goto err;
2912     }
2913     if (SSL_USE_SIGALGS(s)) {
2914         if (!tls12_get_sigandhash(p, pkey, md)) {
2915             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
2916             goto err;
2917         }
2918         p += 2;
2919         n = 2;
2920     }
2921 #ifdef SSL_DEBUG
2922     fprintf(stderr, "Using client alg %s\n", EVP_MD_name(md));
2923 #endif
2924     if (!EVP_SignInit_ex(&mctx, md, NULL)
2925         || !EVP_SignUpdate(&mctx, hdata, hdatalen)
2926         || (s->version == SSL3_VERSION
2927             && !EVP_MD_CTX_ctrl(&mctx, EVP_CTRL_SSL3_MASTER_SECRET,
2928                                 s->session->master_key_length,
2929                                 s->session->master_key))
2930         || !EVP_SignFinal(&mctx, p + 2, &u, pkey)) {
2931         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_EVP_LIB);
2932         goto err;
2933     }
2934 #ifndef OPENSSL_NO_GOST
2935     if (pkey->type == NID_id_GostR3410_2001
2936             || pkey->type == NID_id_GostR3410_2012_256
2937             || pkey->type == NID_id_GostR3410_2012_512) {
2938         BUF_reverse(p + 2, NULL, u);
2939     }
2940 #endif
2941
2942     s2n(u, p);
2943     n += u + 2;
2944     /* Digest cached records and discard handshake buffer */
2945     if (!ssl3_digest_cached_records(s, 0))
2946         goto err;
2947     if (!ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_VERIFY, n)) {
2948         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
2949         goto err;
2950     }
2951
2952     EVP_MD_CTX_cleanup(&mctx);
2953     return 1;
2954  err:
2955     EVP_MD_CTX_cleanup(&mctx);
2956     return 0;
2957 }
2958
2959 /*
2960  * Check a certificate can be used for client authentication. Currently check
2961  * cert exists, if we have a suitable digest for TLS 1.2 if static DH client
2962  * certificates can be used and optionally checks suitability for Suite B.
2963  */
2964 static int ssl3_check_client_certificate(SSL *s)
2965 {
2966     unsigned long alg_k;
2967     if (!s->cert || !s->cert->key->x509 || !s->cert->key->privatekey)
2968         return 0;
2969     /* If no suitable signature algorithm can't use certificate */
2970     if (SSL_USE_SIGALGS(s) && !s->s3->tmp.md[s->cert->key - s->cert->pkeys])
2971         return 0;
2972     /*
2973      * If strict mode check suitability of chain before using it. This also
2974      * adjusts suite B digest if necessary.
2975      */
2976     if (s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT &&
2977         !tls1_check_chain(s, NULL, NULL, NULL, -2))
2978         return 0;
2979     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2980     /* See if we can use client certificate for fixed DH */
2981     if (alg_k & (SSL_kDHr | SSL_kDHd)) {
2982         int i = s->session->peer_type;
2983         EVP_PKEY *clkey = NULL, *spkey = NULL;
2984         clkey = s->cert->key->privatekey;
2985         /* If client key not DH assume it can be used */
2986         if (EVP_PKEY_id(clkey) != EVP_PKEY_DH)
2987             return 1;
2988         if (i >= 0)
2989             spkey = X509_get_pubkey(s->session->peer);
2990         if (spkey) {
2991             /* Compare server and client parameters */
2992             i = EVP_PKEY_cmp_parameters(clkey, spkey);
2993             EVP_PKEY_free(spkey);
2994             if (i != 1)
2995                 return 0;
2996         }
2997         s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
2998     }
2999     return 1;
3000 }
3001
3002 WORK_STATE tls_prepare_client_certificate(SSL *s, WORK_STATE wst)
3003 {
3004     X509 *x509 = NULL;
3005     EVP_PKEY *pkey = NULL;
3006     int i;
3007
3008     if (wst == WORK_MORE_A) {
3009         /* Let cert callback update client certificates if required */
3010         if (s->cert->cert_cb) {
3011             i = s->cert->cert_cb(s, s->cert->cert_cb_arg);
3012             if (i < 0) {
3013                 s->rwstate = SSL_X509_LOOKUP;
3014                 return WORK_MORE_A;
3015             }
3016             if (i == 0) {
3017                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
3018                 ossl_statem_set_error(s);
3019                 return 0;
3020             }
3021             s->rwstate = SSL_NOTHING;
3022         }
3023         if (ssl3_check_client_certificate(s))
3024             return WORK_FINISHED_CONTINUE;
3025
3026         /* Fall through to WORK_MORE_B */
3027         wst = WORK_MORE_B;
3028     }
3029
3030     /* We need to get a client cert */
3031     if (wst == WORK_MORE_B) {
3032         /*
3033          * If we get an error, we need to ssl->rwstate=SSL_X509_LOOKUP;
3034          * return(-1); We then get retied later
3035          */
3036         i = ssl_do_client_cert_cb(s, &x509, &pkey);
3037         if (i < 0) {
3038             s->rwstate = SSL_X509_LOOKUP;
3039             return WORK_MORE_B;
3040         }
3041         s->rwstate = SSL_NOTHING;
3042         if ((i == 1) && (pkey != NULL) && (x509 != NULL)) {
3043             if (!SSL_use_certificate(s, x509) || !SSL_use_PrivateKey(s, pkey))
3044                 i = 0;
3045         } else if (i == 1) {
3046             i = 0;
3047             SSLerr(SSL_F_TLS_PREPARE_CLIENT_CERTIFICATE,
3048                    SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
3049         }
3050
3051         X509_free(x509);
3052         EVP_PKEY_free(pkey);
3053         if (i && !ssl3_check_client_certificate(s))
3054             i = 0;
3055         if (i == 0) {
3056             if (s->version == SSL3_VERSION) {
3057                 s->s3->tmp.cert_req = 0;
3058                 ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_CERTIFICATE);
3059                 return WORK_FINISHED_CONTINUE;
3060             } else {
3061                 s->s3->tmp.cert_req = 2;
3062                 if (!ssl3_digest_cached_records(s, 0)) {
3063                     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
3064                     ossl_statem_set_error(s);
3065                     return 0;
3066                 }
3067             }
3068         }
3069
3070         return WORK_FINISHED_CONTINUE;
3071     }
3072
3073     /* Shouldn't ever get here */
3074     return WORK_ERROR;
3075 }
3076
3077 int tls_construct_client_certificate(SSL *s)
3078 {
3079     if (!ssl3_output_cert_chain(s,
3080                                 (s->s3->tmp.cert_req ==
3081                                  2) ? NULL : s->cert->key)) {
3082         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3083         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
3084         ossl_statem_set_error(s);
3085         return 0;
3086     }
3087
3088     return 1;
3089 }
3090
3091 #define has_bits(i,m)   (((i)&(m)) == (m))
3092
3093 int ssl3_check_cert_and_algorithm(SSL *s)
3094 {
3095     int i, idx;
3096     long alg_k, alg_a;
3097     EVP_PKEY *pkey = NULL;
3098 #ifndef OPENSSL_NO_DH
3099     DH *dh;
3100 #endif
3101     int al = SSL_AD_HANDSHAKE_FAILURE;
3102
3103     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
3104     alg_a = s->s3->tmp.new_cipher->algorithm_auth;
3105
3106     /* we don't have a certificate */
3107     if ((alg_a & SSL_aNULL) || (alg_k & SSL_kPSK))
3108         return (1);
3109 #ifndef OPENSSL_NO_DH
3110     dh = s->s3->peer_dh_tmp;
3111 #endif
3112
3113     /* This is the passed certificate */
3114
3115     idx = s->session->peer_type;
3116 #ifndef OPENSSL_NO_EC
3117     if (idx == SSL_PKEY_ECC) {
3118         if (ssl_check_srvr_ecc_cert_and_alg(s->session->peer, s) == 0) {
3119             /* check failed */
3120             SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_BAD_ECC_CERT);
3121             goto f_err;
3122         } else {
3123             return 1;
3124         }
3125     } else if (alg_a & SSL_aECDSA) {
3126         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3127                SSL_R_MISSING_ECDSA_SIGNING_CERT);
3128         goto f_err;
3129     } else if (alg_k & (SSL_kECDHr | SSL_kECDHe)) {
3130         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_MISSING_ECDH_CERT);
3131         goto f_err;
3132     }
3133 #endif
3134     pkey = X509_get_pubkey(s->session->peer);
3135     i = X509_certificate_type(s->session->peer, pkey);
3136     EVP_PKEY_free(pkey);
3137
3138     /* Check that we have a certificate if we require one */
3139     if ((alg_a & SSL_aRSA) && !has_bits(i, EVP_PK_RSA | EVP_PKT_SIGN)) {
3140         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3141                SSL_R_MISSING_RSA_SIGNING_CERT);
3142         goto f_err;
3143     }
3144 #ifndef OPENSSL_NO_DSA
3145     else if ((alg_a & SSL_aDSS) && !has_bits(i, EVP_PK_DSA | EVP_PKT_SIGN)) {
3146         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3147                SSL_R_MISSING_DSA_SIGNING_CERT);
3148         goto f_err;
3149     }
3150 #endif
3151 #ifndef OPENSSL_NO_RSA
3152     if (alg_k & (SSL_kRSA | SSL_kRSAPSK) &&
3153         !has_bits(i, EVP_PK_RSA | EVP_PKT_ENC)) {
3154         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3155                SSL_R_MISSING_RSA_ENCRYPTING_CERT);
3156         goto f_err;
3157     }
3158 #endif
3159 #ifndef OPENSSL_NO_DH
3160     if ((alg_k & SSL_kDHE) && (dh == NULL)) {
3161         al = SSL_AD_INTERNAL_ERROR;
3162         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR);
3163         goto f_err;
3164     } else if ((alg_k & SSL_kDHr) && !SSL_USE_SIGALGS(s) &&
3165                !has_bits(i, EVP_PK_DH | EVP_PKS_RSA)) {
3166         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3167                SSL_R_MISSING_DH_RSA_CERT);
3168         goto f_err;
3169     }
3170 # ifndef OPENSSL_NO_DSA
3171     else if ((alg_k & SSL_kDHd) && !SSL_USE_SIGALGS(s) &&
3172              !has_bits(i, EVP_PK_DH | EVP_PKS_DSA)) {
3173         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3174                SSL_R_MISSING_DH_DSA_CERT);
3175         goto f_err;
3176     }
3177 # endif
3178 #endif
3179
3180     return (1);
3181  f_err:
3182     ssl3_send_alert(s, SSL3_AL_FATAL, al);
3183     return (0);
3184 }
3185
3186 #ifndef OPENSSL_NO_NEXTPROTONEG
3187 int tls_construct_next_proto(SSL *s)
3188 {
3189     unsigned int len, padding_len;
3190     unsigned char *d;
3191
3192     len = s->next_proto_negotiated_len;
3193     padding_len = 32 - ((len + 2) % 32);
3194     d = (unsigned char *)s->init_buf->data;
3195     d[4] = len;
3196     memcpy(d + 5, s->next_proto_negotiated, len);
3197     d[5 + len] = padding_len;
3198     memset(d + 6 + len, 0, padding_len);
3199     *(d++) = SSL3_MT_NEXT_PROTO;
3200     l2n3(2 + len + padding_len, d);
3201     s->init_num = 4 + 2 + len + padding_len;
3202     s->init_off = 0;
3203
3204     return 1;
3205 }
3206 #endif
3207
3208 int ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
3209 {
3210     int i = 0;
3211 #ifndef OPENSSL_NO_ENGINE
3212     if (s->ctx->client_cert_engine) {
3213         i = ENGINE_load_ssl_client_cert(s->ctx->client_cert_engine, s,
3214                                         SSL_get_client_CA_list(s),
3215                                         px509, ppkey, NULL, NULL, NULL);
3216         if (i != 0)
3217             return i;
3218     }
3219 #endif
3220     if (s->ctx->client_cert_cb)
3221         i = s->ctx->client_cert_cb(s, px509, ppkey);
3222     return i;
3223 }
3224
3225 int ssl_cipher_list_to_bytes(SSL *s, STACK_OF(SSL_CIPHER) *sk,
3226                              unsigned char *p)
3227 {
3228     int i, j = 0;
3229     SSL_CIPHER *c;
3230     unsigned char *q;
3231     int empty_reneg_info_scsv = !s->renegotiate;
3232     /* Set disabled masks for this session */
3233     ssl_set_client_disabled(s);
3234
3235     if (sk == NULL)
3236         return (0);
3237     q = p;
3238
3239     for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3240         c = sk_SSL_CIPHER_value(sk, i);
3241         /* Skip disabled ciphers */
3242         if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_SUPPORTED))
3243             continue;
3244 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
3245         if (c->id == SSL3_CK_SCSV) {
3246             if (!empty_reneg_info_scsv)
3247                 continue;
3248             else
3249                 empty_reneg_info_scsv = 0;
3250         }
3251 #endif
3252         j = s->method->put_cipher_by_char(c, p);
3253         p += j;
3254     }
3255     /*
3256      * If p == q, no ciphers; caller indicates an error. Otherwise, add
3257      * applicable SCSVs.
3258      */
3259     if (p != q) {
3260         if (empty_reneg_info_scsv) {
3261             static SSL_CIPHER scsv = {
3262                 0, NULL, SSL3_CK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
3263             };
3264             j = s->method->put_cipher_by_char(&scsv, p);
3265             p += j;
3266 #ifdef OPENSSL_RI_DEBUG
3267             fprintf(stderr,
3268                     "TLS_EMPTY_RENEGOTIATION_INFO_SCSV sent by client\n");
3269 #endif
3270         }
3271         if (s->mode & SSL_MODE_SEND_FALLBACK_SCSV) {
3272             static SSL_CIPHER scsv = {
3273                 0, NULL, SSL3_CK_FALLBACK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
3274             };
3275             j = s->method->put_cipher_by_char(&scsv, p);
3276             p += j;
3277         }
3278     }
3279
3280     return (p - q);
3281 }