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