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