Move init of the WPACKET into write_state_machine()
[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
517     switch (st->hand_state) {
518     default:
519         /* Shouldn't happen */
520         return 0;
521
522     case TLS_ST_CW_CLNT_HELLO:
523         return tls_construct_client_hello(s, pkt);
524
525     case TLS_ST_CW_CERT:
526         return tls_construct_client_certificate(s, pkt);
527
528     case TLS_ST_CW_KEY_EXCH:
529         return tls_construct_client_key_exchange(s, pkt);
530
531     case TLS_ST_CW_CERT_VRFY:
532         return tls_construct_client_verify(s, pkt);
533
534     case TLS_ST_CW_CHANGE:
535         if (SSL_IS_DTLS(s))
536             return dtls_construct_change_cipher_spec(s, pkt);
537         else
538             return tls_construct_change_cipher_spec(s, pkt);
539
540 #if !defined(OPENSSL_NO_NEXTPROTONEG)
541     case TLS_ST_CW_NEXT_PROTO:
542         return tls_construct_next_proto(s, pkt);
543 #endif
544     case TLS_ST_CW_FINISHED:
545         return tls_construct_finished(s, pkt,
546                                       s->method->
547                                       ssl3_enc->client_finished_label,
548                                       s->method->
549                                       ssl3_enc->client_finished_label_len);
550     }
551 }
552
553 /*
554  * Returns the maximum allowed length for the current message that we are
555  * reading. Excludes the message header.
556  */
557 unsigned long ossl_statem_client_max_message_size(SSL *s)
558 {
559     OSSL_STATEM *st = &s->statem;
560
561     switch (st->hand_state) {
562     default:
563         /* Shouldn't happen */
564         return 0;
565
566     case TLS_ST_CR_SRVR_HELLO:
567         return SERVER_HELLO_MAX_LENGTH;
568
569     case DTLS_ST_CR_HELLO_VERIFY_REQUEST:
570         return HELLO_VERIFY_REQUEST_MAX_LENGTH;
571
572     case TLS_ST_CR_CERT:
573         return s->max_cert_list;
574
575     case TLS_ST_CR_CERT_STATUS:
576         return SSL3_RT_MAX_PLAIN_LENGTH;
577
578     case TLS_ST_CR_KEY_EXCH:
579         return SERVER_KEY_EXCH_MAX_LENGTH;
580
581     case TLS_ST_CR_CERT_REQ:
582         /*
583          * Set to s->max_cert_list for compatibility with previous releases. In
584          * practice these messages can get quite long if servers are configured
585          * to provide a long list of acceptable CAs
586          */
587         return s->max_cert_list;
588
589     case TLS_ST_CR_SRVR_DONE:
590         return SERVER_HELLO_DONE_MAX_LENGTH;
591
592     case TLS_ST_CR_CHANGE:
593         if (s->version == DTLS1_BAD_VER)
594             return 3;
595         return CCS_MAX_LENGTH;
596
597     case TLS_ST_CR_SESSION_TICKET:
598         return SSL3_RT_MAX_PLAIN_LENGTH;
599
600     case TLS_ST_CR_FINISHED:
601         return FINISHED_MAX_LENGTH;
602     }
603 }
604
605 /*
606  * Process a message that the client has been received from the server.
607  */
608 MSG_PROCESS_RETURN ossl_statem_client_process_message(SSL *s, PACKET *pkt)
609 {
610     OSSL_STATEM *st = &s->statem;
611
612     switch (st->hand_state) {
613     default:
614         /* Shouldn't happen */
615         return MSG_PROCESS_ERROR;
616
617     case TLS_ST_CR_SRVR_HELLO:
618         return tls_process_server_hello(s, pkt);
619
620     case DTLS_ST_CR_HELLO_VERIFY_REQUEST:
621         return dtls_process_hello_verify(s, pkt);
622
623     case TLS_ST_CR_CERT:
624         return tls_process_server_certificate(s, pkt);
625
626     case TLS_ST_CR_CERT_STATUS:
627         return tls_process_cert_status(s, pkt);
628
629     case TLS_ST_CR_KEY_EXCH:
630         return tls_process_key_exchange(s, pkt);
631
632     case TLS_ST_CR_CERT_REQ:
633         return tls_process_certificate_request(s, pkt);
634
635     case TLS_ST_CR_SRVR_DONE:
636         return tls_process_server_done(s, pkt);
637
638     case TLS_ST_CR_CHANGE:
639         return tls_process_change_cipher_spec(s, pkt);
640
641     case TLS_ST_CR_SESSION_TICKET:
642         return tls_process_new_session_ticket(s, pkt);
643
644     case TLS_ST_CR_FINISHED:
645         return tls_process_finished(s, pkt);
646     }
647 }
648
649 /*
650  * Perform any further processing required following the receipt of a message
651  * from the server
652  */
653 WORK_STATE ossl_statem_client_post_process_message(SSL *s, WORK_STATE wst)
654 {
655     OSSL_STATEM *st = &s->statem;
656
657     switch (st->hand_state) {
658     default:
659         /* Shouldn't happen */
660         return WORK_ERROR;
661
662     case TLS_ST_CR_CERT_REQ:
663         return tls_prepare_client_certificate(s, wst);
664
665 #ifndef OPENSSL_NO_SCTP
666     case TLS_ST_CR_SRVR_DONE:
667         /* We only get here if we are using SCTP and we are renegotiating */
668         if (BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
669             s->s3->in_read_app_data = 2;
670             s->rwstate = SSL_READING;
671             BIO_clear_retry_flags(SSL_get_rbio(s));
672             BIO_set_retry_read(SSL_get_rbio(s));
673             ossl_statem_set_sctp_read_sock(s, 1);
674             return WORK_MORE_A;
675         }
676         ossl_statem_set_sctp_read_sock(s, 0);
677         return WORK_FINISHED_STOP;
678 #endif
679     }
680 }
681
682 int tls_construct_client_hello(SSL *s, WPACKET *pkt)
683 {
684     unsigned char *p;
685     int i;
686     int protverr;
687     int al = SSL_AD_HANDSHAKE_FAILURE;
688 #ifndef OPENSSL_NO_COMP
689     SSL_COMP *comp;
690 #endif
691     SSL_SESSION *sess = s->session;
692
693     if (!WPACKET_set_max_size(pkt, SSL3_RT_MAX_PLAIN_LENGTH)) {
694         /* Should not happen */
695         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
696         return 0;
697     }
698
699     /* Work out what SSL/TLS/DTLS version to use */
700     protverr = ssl_set_client_hello_version(s);
701     if (protverr != 0) {
702         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, protverr);
703         return 0;
704     }
705
706     if ((sess == NULL) || !ssl_version_supported(s, sess->ssl_version) ||
707         /*
708          * In the case of EAP-FAST, we can have a pre-shared
709          * "ticket" without a session ID.
710          */
711         (!sess->session_id_length && !sess->tlsext_tick) ||
712         (sess->not_resumable)) {
713         if (!ssl_get_new_session(s, 0))
714             return 0;
715     }
716     /* else use the pre-loaded session */
717
718     p = s->s3->client_random;
719
720     /*
721      * for DTLS if client_random is initialized, reuse it, we are
722      * required to use same upon reply to HelloVerify
723      */
724     if (SSL_IS_DTLS(s)) {
725         size_t idx;
726         i = 1;
727         for (idx = 0; idx < sizeof(s->s3->client_random); idx++) {
728             if (p[idx]) {
729                 i = 0;
730                 break;
731             }
732         }
733     } else
734         i = 1;
735
736     if (i && ssl_fill_hello_random(s, 0, p, sizeof(s->s3->client_random)) <= 0)
737         return 0;
738
739     if (!ssl_set_handshake_header(s, pkt, SSL3_MT_CLIENT_HELLO)) {
740         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
741         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
742         return 0;
743     }
744
745     /*-
746      * version indicates the negotiated version: for example from
747      * an SSLv2/v3 compatible client hello). The client_version
748      * field is the maximum version we permit and it is also
749      * used in RSA encrypted premaster secrets. Some servers can
750      * choke if we initially report a higher version then
751      * renegotiate to a lower one in the premaster secret. This
752      * didn't happen with TLS 1.0 as most servers supported it
753      * but it can with TLS 1.1 or later if the server only supports
754      * 1.0.
755      *
756      * Possible scenario with previous logic:
757      *      1. Client hello indicates TLS 1.2
758      *      2. Server hello says TLS 1.0
759      *      3. RSA encrypted premaster secret uses 1.2.
760      *      4. Handshake proceeds using TLS 1.0.
761      *      5. Server sends hello request to renegotiate.
762      *      6. Client hello indicates TLS v1.0 as we now
763      *         know that is maximum server supports.
764      *      7. Server chokes on RSA encrypted premaster secret
765      *         containing version 1.0.
766      *
767      * For interoperability it should be OK to always use the
768      * maximum version we support in client hello and then rely
769      * on the checking of version to ensure the servers isn't
770      * being inconsistent: for example initially negotiating with
771      * TLS 1.0 and renegotiating with TLS 1.2. We do this by using
772      * client_version in client hello and not resetting it to
773      * the negotiated version.
774      */
775     if (!WPACKET_put_bytes_u16(pkt, s->client_version)
776             || !WPACKET_memcpy(pkt, s->s3->client_random, SSL3_RANDOM_SIZE)) {
777         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
778         return 0;
779     }
780
781     /* Session ID */
782     if (s->new_session)
783         i = 0;
784     else
785         i = s->session->session_id_length;
786     if (i > (int)sizeof(s->session->session_id)
787             || !WPACKET_start_sub_packet_u8(pkt)
788             || (i != 0 && !WPACKET_memcpy(pkt, s->session->session_id, i))
789             || !WPACKET_close(pkt)) {
790         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
791         return 0;
792     }
793
794     /* cookie stuff for DTLS */
795     if (SSL_IS_DTLS(s)) {
796         if (s->d1->cookie_len > sizeof(s->d1->cookie)
797                 || !WPACKET_sub_memcpy_u8(pkt, s->d1->cookie,
798                                           s->d1->cookie_len)) {
799             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
800             return 0;
801         }
802     }
803
804     /* Ciphers supported */
805     if (!WPACKET_start_sub_packet_u16(pkt)) {
806         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
807         return 0;
808     }
809     /* ssl_cipher_list_to_bytes() raises SSLerr if appropriate */
810     if (!ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s), pkt))
811         return 0;
812     if (!WPACKET_close(pkt)) {
813         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
814         return 0;
815     }
816
817     /* COMPRESSION */
818     if (!WPACKET_start_sub_packet_u8(pkt)) {
819         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
820         return 0;
821     }
822 #ifndef OPENSSL_NO_COMP
823     if (ssl_allow_compression(s) && s->ctx->comp_methods) {
824         int compnum = sk_SSL_COMP_num(s->ctx->comp_methods);
825         for (i = 0; i < compnum; i++) {
826             comp = sk_SSL_COMP_value(s->ctx->comp_methods, i);
827             if (!WPACKET_put_bytes_u8(pkt, comp->id)) {
828                 SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
829                 return 0;
830             }
831         }
832     }
833 #endif
834     /* Add the NULL method */
835     if (!WPACKET_put_bytes_u8(pkt, 0) || !WPACKET_close(pkt)) {
836         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
837         return 0;
838     }
839
840     /* TLS extensions */
841     if (ssl_prepare_clienthello_tlsext(s) <= 0) {
842         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
843         return 0;
844     }
845     if (!WPACKET_start_sub_packet_u16(pkt)
846                /*
847                 * If extensions are of zero length then we don't even add the
848                 * extensions length bytes
849                 */
850             || !WPACKET_set_flags(pkt, WPACKET_FLAGS_ABANDON_ON_ZERO_LENGTH)
851             || !ssl_add_clienthello_tlsext(s, pkt, &al)
852             || !WPACKET_close(pkt)) {
853         ssl3_send_alert(s, SSL3_AL_FATAL, al);
854         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
855         return 0;
856     }
857
858     if (!ssl_close_construct_packet(s, pkt)) {
859         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
860         return 0;
861     }
862
863     return 1;
864 }
865
866 MSG_PROCESS_RETURN dtls_process_hello_verify(SSL *s, PACKET *pkt)
867 {
868     int al;
869     unsigned int cookie_len;
870     PACKET cookiepkt;
871
872     if (!PACKET_forward(pkt, 2)
873         || !PACKET_get_length_prefixed_1(pkt, &cookiepkt)) {
874         al = SSL_AD_DECODE_ERROR;
875         SSLerr(SSL_F_DTLS_PROCESS_HELLO_VERIFY, SSL_R_LENGTH_MISMATCH);
876         goto f_err;
877     }
878
879     cookie_len = PACKET_remaining(&cookiepkt);
880     if (cookie_len > sizeof(s->d1->cookie)) {
881         al = SSL_AD_ILLEGAL_PARAMETER;
882         SSLerr(SSL_F_DTLS_PROCESS_HELLO_VERIFY, SSL_R_LENGTH_TOO_LONG);
883         goto f_err;
884     }
885
886     if (!PACKET_copy_bytes(&cookiepkt, s->d1->cookie, cookie_len)) {
887         al = SSL_AD_DECODE_ERROR;
888         SSLerr(SSL_F_DTLS_PROCESS_HELLO_VERIFY, SSL_R_LENGTH_MISMATCH);
889         goto f_err;
890     }
891     s->d1->cookie_len = cookie_len;
892
893     return MSG_PROCESS_FINISHED_READING;
894  f_err:
895     ssl3_send_alert(s, SSL3_AL_FATAL, al);
896     ossl_statem_set_error(s);
897     return MSG_PROCESS_ERROR;
898 }
899
900 MSG_PROCESS_RETURN tls_process_server_hello(SSL *s, PACKET *pkt)
901 {
902     STACK_OF(SSL_CIPHER) *sk;
903     const SSL_CIPHER *c;
904     PACKET session_id;
905     size_t session_id_len;
906     const unsigned char *cipherchars;
907     int i, al = SSL_AD_INTERNAL_ERROR;
908     unsigned int compression;
909     unsigned int sversion;
910     int protverr;
911 #ifndef OPENSSL_NO_COMP
912     SSL_COMP *comp;
913 #endif
914
915     if (!PACKET_get_net_2(pkt, &sversion)) {
916         al = SSL_AD_DECODE_ERROR;
917         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
918         goto f_err;
919     }
920
921     protverr = ssl_choose_client_version(s, sversion);
922     if (protverr != 0) {
923         al = SSL_AD_PROTOCOL_VERSION;
924         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, protverr);
925         goto f_err;
926     }
927
928     /* load the server hello data */
929     /* load the server random */
930     if (!PACKET_copy_bytes(pkt, s->s3->server_random, SSL3_RANDOM_SIZE)) {
931         al = SSL_AD_DECODE_ERROR;
932         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
933         goto f_err;
934     }
935
936     s->hit = 0;
937
938     /* Get the session-id. */
939     if (!PACKET_get_length_prefixed_1(pkt, &session_id)) {
940         al = SSL_AD_DECODE_ERROR;
941         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
942         goto f_err;
943     }
944     session_id_len = PACKET_remaining(&session_id);
945     if (session_id_len > sizeof s->session->session_id
946         || session_id_len > SSL3_SESSION_ID_SIZE) {
947         al = SSL_AD_ILLEGAL_PARAMETER;
948         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_SSL3_SESSION_ID_TOO_LONG);
949         goto f_err;
950     }
951
952     if (!PACKET_get_bytes(pkt, &cipherchars, TLS_CIPHER_LEN)) {
953         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
954         al = SSL_AD_DECODE_ERROR;
955         goto f_err;
956     }
957
958     /*
959      * Check if we can resume the session based on external pre-shared secret.
960      * EAP-FAST (RFC 4851) supports two types of session resumption.
961      * Resumption based on server-side state works with session IDs.
962      * Resumption based on pre-shared Protected Access Credentials (PACs)
963      * works by overriding the SessionTicket extension at the application
964      * layer, and does not send a session ID. (We do not know whether EAP-FAST
965      * servers would honour the session ID.) Therefore, the session ID alone
966      * is not a reliable indicator of session resumption, so we first check if
967      * we can resume, and later peek at the next handshake message to see if the
968      * server wants to resume.
969      */
970     if (s->version >= TLS1_VERSION && s->tls_session_secret_cb &&
971         s->session->tlsext_tick) {
972         const SSL_CIPHER *pref_cipher = NULL;
973         s->session->master_key_length = sizeof(s->session->master_key);
974         if (s->tls_session_secret_cb(s, s->session->master_key,
975                                      &s->session->master_key_length,
976                                      NULL, &pref_cipher,
977                                      s->tls_session_secret_cb_arg)) {
978             s->session->cipher = pref_cipher ?
979                 pref_cipher : ssl_get_cipher_by_char(s, cipherchars);
980         } else {
981             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
982             al = SSL_AD_INTERNAL_ERROR;
983             goto f_err;
984         }
985     }
986
987     if (session_id_len != 0 && session_id_len == s->session->session_id_length
988         && memcmp(PACKET_data(&session_id), s->session->session_id,
989                   session_id_len) == 0) {
990         if (s->sid_ctx_length != s->session->sid_ctx_length
991             || memcmp(s->session->sid_ctx, s->sid_ctx, s->sid_ctx_length)) {
992             /* actually a client application bug */
993             al = SSL_AD_ILLEGAL_PARAMETER;
994             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
995                    SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
996             goto f_err;
997         }
998         s->hit = 1;
999     } else {
1000         /*
1001          * If we were trying for session-id reuse but the server
1002          * didn't echo the ID, make a new SSL_SESSION.
1003          * In the case of EAP-FAST and PAC, we do not send a session ID,
1004          * so the PAC-based session secret is always preserved. It'll be
1005          * overwritten if the server refuses resumption.
1006          */
1007         if (s->session->session_id_length > 0) {
1008             s->ctx->stats.sess_miss++;
1009             if (!ssl_get_new_session(s, 0)) {
1010                 goto f_err;
1011             }
1012         }
1013
1014         s->session->ssl_version = s->version;
1015         s->session->session_id_length = session_id_len;
1016         /* session_id_len could be 0 */
1017         memcpy(s->session->session_id, PACKET_data(&session_id),
1018                session_id_len);
1019     }
1020
1021     /* Session version and negotiated protocol version should match */
1022     if (s->version != s->session->ssl_version) {
1023         al = SSL_AD_PROTOCOL_VERSION;
1024
1025         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1026                SSL_R_SSL_SESSION_VERSION_MISMATCH);
1027         goto f_err;
1028     }
1029
1030     c = ssl_get_cipher_by_char(s, cipherchars);
1031     if (c == NULL) {
1032         /* unknown cipher */
1033         al = SSL_AD_ILLEGAL_PARAMETER;
1034         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_UNKNOWN_CIPHER_RETURNED);
1035         goto f_err;
1036     }
1037     /*
1038      * Now that we know the version, update the check to see if it's an allowed
1039      * version.
1040      */
1041     s->s3->tmp.min_ver = s->version;
1042     s->s3->tmp.max_ver = s->version;
1043     /*
1044      * If it is a disabled cipher we either didn't send it in client hello,
1045      * or it's not allowed for the selected protocol. So we return an error.
1046      */
1047     if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_CHECK)) {
1048         al = SSL_AD_ILLEGAL_PARAMETER;
1049         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_WRONG_CIPHER_RETURNED);
1050         goto f_err;
1051     }
1052
1053     sk = ssl_get_ciphers_by_id(s);
1054     i = sk_SSL_CIPHER_find(sk, c);
1055     if (i < 0) {
1056         /* we did not say we would use this cipher */
1057         al = SSL_AD_ILLEGAL_PARAMETER;
1058         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_WRONG_CIPHER_RETURNED);
1059         goto f_err;
1060     }
1061
1062     /*
1063      * Depending on the session caching (internal/external), the cipher
1064      * and/or cipher_id values may not be set. Make sure that cipher_id is
1065      * set and use it for comparison.
1066      */
1067     if (s->session->cipher)
1068         s->session->cipher_id = s->session->cipher->id;
1069     if (s->hit && (s->session->cipher_id != c->id)) {
1070         al = SSL_AD_ILLEGAL_PARAMETER;
1071         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1072                SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
1073         goto f_err;
1074     }
1075     s->s3->tmp.new_cipher = c;
1076     /* lets get the compression algorithm */
1077     /* COMPRESSION */
1078     if (!PACKET_get_1(pkt, &compression)) {
1079         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
1080         al = SSL_AD_DECODE_ERROR;
1081         goto f_err;
1082     }
1083 #ifdef OPENSSL_NO_COMP
1084     if (compression != 0) {
1085         al = SSL_AD_ILLEGAL_PARAMETER;
1086         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1087                SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1088         goto f_err;
1089     }
1090     /*
1091      * If compression is disabled we'd better not try to resume a session
1092      * using compression.
1093      */
1094     if (s->session->compress_meth != 0) {
1095         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
1096         goto f_err;
1097     }
1098 #else
1099     if (s->hit && compression != s->session->compress_meth) {
1100         al = SSL_AD_ILLEGAL_PARAMETER;
1101         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1102                SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED);
1103         goto f_err;
1104     }
1105     if (compression == 0)
1106         comp = NULL;
1107     else if (!ssl_allow_compression(s)) {
1108         al = SSL_AD_ILLEGAL_PARAMETER;
1109         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_COMPRESSION_DISABLED);
1110         goto f_err;
1111     } else {
1112         comp = ssl3_comp_find(s->ctx->comp_methods, compression);
1113     }
1114
1115     if (compression != 0 && comp == NULL) {
1116         al = SSL_AD_ILLEGAL_PARAMETER;
1117         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1118                SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1119         goto f_err;
1120     } else {
1121         s->s3->tmp.new_compression = comp;
1122     }
1123 #endif
1124
1125     /* TLS extensions */
1126     if (!ssl_parse_serverhello_tlsext(s, pkt)) {
1127         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_PARSE_TLSEXT);
1128         goto err;
1129     }
1130
1131     if (PACKET_remaining(pkt) != 0) {
1132         /* wrong packet length */
1133         al = SSL_AD_DECODE_ERROR;
1134         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_BAD_PACKET_LENGTH);
1135         goto f_err;
1136     }
1137 #ifndef OPENSSL_NO_SCTP
1138     if (SSL_IS_DTLS(s) && s->hit) {
1139         unsigned char sctpauthkey[64];
1140         char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
1141
1142         /*
1143          * Add new shared key for SCTP-Auth, will be ignored if
1144          * no SCTP used.
1145          */
1146         memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
1147                sizeof(DTLS1_SCTP_AUTH_LABEL));
1148
1149         if (SSL_export_keying_material(s, sctpauthkey,
1150                                        sizeof(sctpauthkey),
1151                                        labelbuffer,
1152                                        sizeof(labelbuffer), NULL, 0, 0) <= 0)
1153             goto err;
1154
1155         BIO_ctrl(SSL_get_wbio(s),
1156                  BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
1157                  sizeof(sctpauthkey), sctpauthkey);
1158     }
1159 #endif
1160
1161     return MSG_PROCESS_CONTINUE_READING;
1162  f_err:
1163     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1164  err:
1165     ossl_statem_set_error(s);
1166     return MSG_PROCESS_ERROR;
1167 }
1168
1169 MSG_PROCESS_RETURN tls_process_server_certificate(SSL *s, PACKET *pkt)
1170 {
1171     int al, i, ret = MSG_PROCESS_ERROR, exp_idx;
1172     unsigned long cert_list_len, cert_len;
1173     X509 *x = NULL;
1174     const unsigned char *certstart, *certbytes;
1175     STACK_OF(X509) *sk = NULL;
1176     EVP_PKEY *pkey = NULL;
1177
1178     if ((sk = sk_X509_new_null()) == NULL) {
1179         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, ERR_R_MALLOC_FAILURE);
1180         goto err;
1181     }
1182
1183     if (!PACKET_get_net_3(pkt, &cert_list_len)
1184         || PACKET_remaining(pkt) != cert_list_len) {
1185         al = SSL_AD_DECODE_ERROR;
1186         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
1187         goto f_err;
1188     }
1189     while (PACKET_remaining(pkt)) {
1190         if (!PACKET_get_net_3(pkt, &cert_len)
1191             || !PACKET_get_bytes(pkt, &certbytes, cert_len)) {
1192             al = SSL_AD_DECODE_ERROR;
1193             SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1194                    SSL_R_CERT_LENGTH_MISMATCH);
1195             goto f_err;
1196         }
1197
1198         certstart = certbytes;
1199         x = d2i_X509(NULL, (const unsigned char **)&certbytes, cert_len);
1200         if (x == NULL) {
1201             al = SSL_AD_BAD_CERTIFICATE;
1202             SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, ERR_R_ASN1_LIB);
1203             goto f_err;
1204         }
1205         if (certbytes != (certstart + cert_len)) {
1206             al = SSL_AD_DECODE_ERROR;
1207             SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1208                    SSL_R_CERT_LENGTH_MISMATCH);
1209             goto f_err;
1210         }
1211         if (!sk_X509_push(sk, x)) {
1212             SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, ERR_R_MALLOC_FAILURE);
1213             goto err;
1214         }
1215         x = NULL;
1216     }
1217
1218     i = ssl_verify_cert_chain(s, sk);
1219     if ((s->verify_mode & SSL_VERIFY_PEER) && i <= 0) {
1220         al = ssl_verify_alarm_type(s->verify_result);
1221         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1222                SSL_R_CERTIFICATE_VERIFY_FAILED);
1223         goto f_err;
1224     }
1225     ERR_clear_error();          /* but we keep s->verify_result */
1226     if (i > 1) {
1227         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, i);
1228         al = SSL_AD_HANDSHAKE_FAILURE;
1229         goto f_err;
1230     }
1231
1232     s->session->peer_chain = sk;
1233     /*
1234      * Inconsistency alert: cert_chain does include the peer's certificate,
1235      * which we don't include in statem_srvr.c
1236      */
1237     x = sk_X509_value(sk, 0);
1238     sk = NULL;
1239     /*
1240      * VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end
1241      */
1242
1243     pkey = X509_get0_pubkey(x);
1244
1245     if (pkey == NULL || EVP_PKEY_missing_parameters(pkey)) {
1246         x = NULL;
1247         al = SSL3_AL_FATAL;
1248         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1249                SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
1250         goto f_err;
1251     }
1252
1253     i = ssl_cert_type(x, pkey);
1254     if (i < 0) {
1255         x = NULL;
1256         al = SSL3_AL_FATAL;
1257         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1258                SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1259         goto f_err;
1260     }
1261
1262     exp_idx = ssl_cipher_get_cert_index(s->s3->tmp.new_cipher);
1263     if (exp_idx >= 0 && i != exp_idx
1264         && (exp_idx != SSL_PKEY_GOST_EC ||
1265             (i != SSL_PKEY_GOST12_512 && i != SSL_PKEY_GOST12_256
1266              && i != SSL_PKEY_GOST01))) {
1267         x = NULL;
1268         al = SSL_AD_ILLEGAL_PARAMETER;
1269         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1270                SSL_R_WRONG_CERTIFICATE_TYPE);
1271         goto f_err;
1272     }
1273     s->session->peer_type = i;
1274
1275     X509_free(s->session->peer);
1276     X509_up_ref(x);
1277     s->session->peer = x;
1278     s->session->verify_result = s->verify_result;
1279
1280     x = NULL;
1281     ret = MSG_PROCESS_CONTINUE_READING;
1282     goto done;
1283
1284  f_err:
1285     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1286  err:
1287     ossl_statem_set_error(s);
1288  done:
1289     X509_free(x);
1290     sk_X509_pop_free(sk, X509_free);
1291     return ret;
1292 }
1293
1294 static int tls_process_ske_psk_preamble(SSL *s, PACKET *pkt, int *al)
1295 {
1296 #ifndef OPENSSL_NO_PSK
1297     PACKET psk_identity_hint;
1298
1299     /* PSK ciphersuites are preceded by an identity hint */
1300
1301     if (!PACKET_get_length_prefixed_2(pkt, &psk_identity_hint)) {
1302         *al = SSL_AD_DECODE_ERROR;
1303         SSLerr(SSL_F_TLS_PROCESS_SKE_PSK_PREAMBLE, SSL_R_LENGTH_MISMATCH);
1304         return 0;
1305     }
1306
1307     /*
1308      * Store PSK identity hint for later use, hint is used in
1309      * tls_construct_client_key_exchange.  Assume that the maximum length of
1310      * a PSK identity hint can be as long as the maximum length of a PSK
1311      * identity.
1312      */
1313     if (PACKET_remaining(&psk_identity_hint) > PSK_MAX_IDENTITY_LEN) {
1314         *al = SSL_AD_HANDSHAKE_FAILURE;
1315         SSLerr(SSL_F_TLS_PROCESS_SKE_PSK_PREAMBLE, SSL_R_DATA_LENGTH_TOO_LONG);
1316         return 0;
1317     }
1318
1319     if (PACKET_remaining(&psk_identity_hint) == 0) {
1320         OPENSSL_free(s->session->psk_identity_hint);
1321         s->session->psk_identity_hint = NULL;
1322     } else if (!PACKET_strndup(&psk_identity_hint,
1323                                &s->session->psk_identity_hint)) {
1324         *al = SSL_AD_INTERNAL_ERROR;
1325         return 0;
1326     }
1327
1328     return 1;
1329 #else
1330     SSLerr(SSL_F_TLS_PROCESS_SKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
1331     *al = SSL_AD_INTERNAL_ERROR;
1332     return 0;
1333 #endif
1334 }
1335
1336 static int tls_process_ske_srp(SSL *s, PACKET *pkt, EVP_PKEY **pkey, int *al)
1337 {
1338 #ifndef OPENSSL_NO_SRP
1339     PACKET prime, generator, salt, server_pub;
1340
1341     if (!PACKET_get_length_prefixed_2(pkt, &prime)
1342         || !PACKET_get_length_prefixed_2(pkt, &generator)
1343         || !PACKET_get_length_prefixed_1(pkt, &salt)
1344         || !PACKET_get_length_prefixed_2(pkt, &server_pub)) {
1345         *al = SSL_AD_DECODE_ERROR;
1346         SSLerr(SSL_F_TLS_PROCESS_SKE_SRP, SSL_R_LENGTH_MISMATCH);
1347         return 0;
1348     }
1349
1350     if ((s->srp_ctx.N =
1351          BN_bin2bn(PACKET_data(&prime),
1352                    PACKET_remaining(&prime), NULL)) == NULL
1353         || (s->srp_ctx.g =
1354             BN_bin2bn(PACKET_data(&generator),
1355                       PACKET_remaining(&generator), NULL)) == NULL
1356         || (s->srp_ctx.s =
1357             BN_bin2bn(PACKET_data(&salt),
1358                       PACKET_remaining(&salt), NULL)) == NULL
1359         || (s->srp_ctx.B =
1360             BN_bin2bn(PACKET_data(&server_pub),
1361                       PACKET_remaining(&server_pub), NULL)) == NULL) {
1362         *al = SSL_AD_INTERNAL_ERROR;
1363         SSLerr(SSL_F_TLS_PROCESS_SKE_SRP, ERR_R_BN_LIB);
1364         return 0;
1365     }
1366
1367     if (!srp_verify_server_param(s, al)) {
1368         *al = SSL_AD_DECODE_ERROR;
1369         SSLerr(SSL_F_TLS_PROCESS_SKE_SRP, SSL_R_BAD_SRP_PARAMETERS);
1370         return 0;
1371     }
1372
1373     /* We must check if there is a certificate */
1374     if (s->s3->tmp.new_cipher->algorithm_auth & (SSL_aRSA | SSL_aDSS))
1375         *pkey = X509_get0_pubkey(s->session->peer);
1376
1377     return 1;
1378 #else
1379     SSLerr(SSL_F_TLS_PROCESS_SKE_SRP, ERR_R_INTERNAL_ERROR);
1380     *al = SSL_AD_INTERNAL_ERROR;
1381     return 0;
1382 #endif
1383 }
1384
1385 static int tls_process_ske_dhe(SSL *s, PACKET *pkt, EVP_PKEY **pkey, int *al)
1386 {
1387 #ifndef OPENSSL_NO_DH
1388     PACKET prime, generator, pub_key;
1389     EVP_PKEY *peer_tmp = NULL;
1390
1391     DH *dh = NULL;
1392     BIGNUM *p = NULL, *g = NULL, *bnpub_key = NULL;
1393
1394     if (!PACKET_get_length_prefixed_2(pkt, &prime)
1395         || !PACKET_get_length_prefixed_2(pkt, &generator)
1396         || !PACKET_get_length_prefixed_2(pkt, &pub_key)) {
1397         *al = SSL_AD_DECODE_ERROR;
1398         SSLerr(SSL_F_TLS_PROCESS_SKE_DHE, SSL_R_LENGTH_MISMATCH);
1399         return 0;
1400     }
1401
1402     peer_tmp = EVP_PKEY_new();
1403     dh = DH_new();
1404
1405     if (peer_tmp == NULL || dh == NULL) {
1406         *al = SSL_AD_INTERNAL_ERROR;
1407         SSLerr(SSL_F_TLS_PROCESS_SKE_DHE, ERR_R_MALLOC_FAILURE);
1408         goto err;
1409     }
1410
1411     p = BN_bin2bn(PACKET_data(&prime), PACKET_remaining(&prime), NULL);
1412     g = BN_bin2bn(PACKET_data(&generator), PACKET_remaining(&generator), NULL);
1413     bnpub_key = BN_bin2bn(PACKET_data(&pub_key), PACKET_remaining(&pub_key),
1414                           NULL);
1415     if (p == NULL || g == NULL || bnpub_key == NULL) {
1416         *al = SSL_AD_INTERNAL_ERROR;
1417         SSLerr(SSL_F_TLS_PROCESS_SKE_DHE, ERR_R_BN_LIB);
1418         goto err;
1419     }
1420
1421     if (BN_is_zero(p) || BN_is_zero(g) || BN_is_zero(bnpub_key)) {
1422         *al = SSL_AD_DECODE_ERROR;
1423         SSLerr(SSL_F_TLS_PROCESS_SKE_DHE, SSL_R_BAD_DH_VALUE);
1424         goto err;
1425     }
1426
1427     if (!DH_set0_pqg(dh, p, NULL, g)) {
1428         *al = SSL_AD_INTERNAL_ERROR;
1429         SSLerr(SSL_F_TLS_PROCESS_SKE_DHE, ERR_R_BN_LIB);
1430         goto err;
1431     }
1432     p = g = NULL;
1433
1434     if (!DH_set0_key(dh, bnpub_key, NULL)) {
1435         *al = SSL_AD_INTERNAL_ERROR;
1436         SSLerr(SSL_F_TLS_PROCESS_SKE_DHE, ERR_R_BN_LIB);
1437         goto err;
1438     }
1439     bnpub_key = NULL;
1440
1441     if (!ssl_security(s, SSL_SECOP_TMP_DH, DH_security_bits(dh), 0, dh)) {
1442         *al = SSL_AD_HANDSHAKE_FAILURE;
1443         SSLerr(SSL_F_TLS_PROCESS_SKE_DHE, SSL_R_DH_KEY_TOO_SMALL);
1444         goto err;
1445     }
1446
1447     if (EVP_PKEY_assign_DH(peer_tmp, dh) == 0) {
1448         *al = SSL_AD_INTERNAL_ERROR;
1449         SSLerr(SSL_F_TLS_PROCESS_SKE_DHE, ERR_R_EVP_LIB);
1450         goto err;
1451     }
1452
1453     s->s3->peer_tmp = peer_tmp;
1454
1455     /*
1456      * FIXME: This makes assumptions about which ciphersuites come with
1457      * public keys. We should have a less ad-hoc way of doing this
1458      */
1459     if (s->s3->tmp.new_cipher->algorithm_auth & (SSL_aRSA | SSL_aDSS))
1460         *pkey = X509_get0_pubkey(s->session->peer);
1461     /* else anonymous DH, so no certificate or pkey. */
1462
1463     return 1;
1464
1465  err:
1466     BN_free(p);
1467     BN_free(g);
1468     BN_free(bnpub_key);
1469     DH_free(dh);
1470     EVP_PKEY_free(peer_tmp);
1471
1472     return 0;
1473 #else
1474     SSLerr(SSL_F_TLS_PROCESS_SKE_DHE, ERR_R_INTERNAL_ERROR);
1475     *al = SSL_AD_INTERNAL_ERROR;
1476     return 0;
1477 #endif
1478 }
1479
1480 static int tls_process_ske_ecdhe(SSL *s, PACKET *pkt, EVP_PKEY **pkey, int *al)
1481 {
1482 #ifndef OPENSSL_NO_EC
1483     PACKET encoded_pt;
1484     const unsigned char *ecparams;
1485     int curve_nid;
1486     unsigned int curve_flags;
1487     EVP_PKEY_CTX *pctx = NULL;
1488
1489     /*
1490      * Extract elliptic curve parameters and the server's ephemeral ECDH
1491      * public key. For now we only support named (not generic) curves and
1492      * ECParameters in this case is just three bytes.
1493      */
1494     if (!PACKET_get_bytes(pkt, &ecparams, 3)) {
1495         *al = SSL_AD_DECODE_ERROR;
1496         SSLerr(SSL_F_TLS_PROCESS_SKE_ECDHE, SSL_R_LENGTH_TOO_SHORT);
1497         return 0;
1498     }
1499     /*
1500      * Check curve is one of our preferences, if not server has sent an
1501      * invalid curve. ECParameters is 3 bytes.
1502      */
1503     if (!tls1_check_curve(s, ecparams, 3)) {
1504         *al = SSL_AD_DECODE_ERROR;
1505         SSLerr(SSL_F_TLS_PROCESS_SKE_ECDHE, SSL_R_WRONG_CURVE);
1506         return 0;
1507     }
1508
1509     curve_nid = tls1_ec_curve_id2nid(*(ecparams + 2), &curve_flags);
1510
1511     if (curve_nid == 0) {
1512         *al = SSL_AD_INTERNAL_ERROR;
1513         SSLerr(SSL_F_TLS_PROCESS_SKE_ECDHE,
1514                SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
1515         return 0;
1516     }
1517
1518     if ((curve_flags & TLS_CURVE_TYPE) == TLS_CURVE_CUSTOM) {
1519         EVP_PKEY *key = EVP_PKEY_new();
1520
1521         if (key == NULL || !EVP_PKEY_set_type(key, curve_nid)) {
1522             *al = SSL_AD_INTERNAL_ERROR;
1523             SSLerr(SSL_F_TLS_PROCESS_SKE_ECDHE, ERR_R_EVP_LIB);
1524             EVP_PKEY_free(key);
1525             return 0;
1526         }
1527         s->s3->peer_tmp = key;
1528     } else {
1529         /* Set up EVP_PKEY with named curve as parameters */
1530         pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL);
1531         if (pctx == NULL
1532             || EVP_PKEY_paramgen_init(pctx) <= 0
1533             || EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx, curve_nid) <= 0
1534             || EVP_PKEY_paramgen(pctx, &s->s3->peer_tmp) <= 0) {
1535             *al = SSL_AD_INTERNAL_ERROR;
1536             SSLerr(SSL_F_TLS_PROCESS_SKE_ECDHE, ERR_R_EVP_LIB);
1537             EVP_PKEY_CTX_free(pctx);
1538             return 0;
1539         }
1540         EVP_PKEY_CTX_free(pctx);
1541         pctx = NULL;
1542     }
1543
1544     if (!PACKET_get_length_prefixed_1(pkt, &encoded_pt)) {
1545         *al = SSL_AD_DECODE_ERROR;
1546         SSLerr(SSL_F_TLS_PROCESS_SKE_ECDHE, SSL_R_LENGTH_MISMATCH);
1547         return 0;
1548     }
1549
1550     if (!EVP_PKEY_set1_tls_encodedpoint(s->s3->peer_tmp,
1551                                         PACKET_data(&encoded_pt),
1552                                         PACKET_remaining(&encoded_pt))) {
1553         *al = SSL_AD_DECODE_ERROR;
1554         SSLerr(SSL_F_TLS_PROCESS_SKE_ECDHE, SSL_R_BAD_ECPOINT);
1555         return 0;
1556     }
1557
1558     /*
1559      * The ECC/TLS specification does not mention the use of DSA to sign
1560      * ECParameters in the server key exchange message. We do support RSA
1561      * and ECDSA.
1562      */
1563     if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aECDSA)
1564         *pkey = X509_get0_pubkey(s->session->peer);
1565     else if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aRSA)
1566         *pkey = X509_get0_pubkey(s->session->peer);
1567     /* else anonymous ECDH, so no certificate or pkey. */
1568
1569     return 1;
1570 #else
1571     SSLerr(SSL_F_TLS_PROCESS_SKE_ECDHE, ERR_R_INTERNAL_ERROR);
1572     *al = SSL_AD_INTERNAL_ERROR;
1573     return 0;
1574 #endif
1575 }
1576
1577 MSG_PROCESS_RETURN tls_process_key_exchange(SSL *s, PACKET *pkt)
1578 {
1579     int al = -1;
1580     long alg_k;
1581     EVP_PKEY *pkey = NULL;
1582     PACKET save_param_start, signature;
1583
1584     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1585
1586     save_param_start = *pkt;
1587
1588 #if !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)
1589     EVP_PKEY_free(s->s3->peer_tmp);
1590     s->s3->peer_tmp = NULL;
1591 #endif
1592
1593     if (alg_k & SSL_PSK) {
1594         if (!tls_process_ske_psk_preamble(s, pkt, &al))
1595             goto err;
1596     }
1597
1598     /* Nothing else to do for plain PSK or RSAPSK */
1599     if (alg_k & (SSL_kPSK | SSL_kRSAPSK)) {
1600     } else if (alg_k & SSL_kSRP) {
1601         if (!tls_process_ske_srp(s, pkt, &pkey, &al))
1602             goto err;
1603     } else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
1604         if (!tls_process_ske_dhe(s, pkt, &pkey, &al))
1605             goto err;
1606     } else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
1607         if (!tls_process_ske_ecdhe(s, pkt, &pkey, &al))
1608             goto err;
1609     } else if (alg_k) {
1610         al = SSL_AD_UNEXPECTED_MESSAGE;
1611         SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
1612         goto err;
1613     }
1614
1615     /* if it was signed, check the signature */
1616     if (pkey != NULL) {
1617         PACKET params;
1618         int maxsig;
1619         const EVP_MD *md = NULL;
1620         EVP_MD_CTX *md_ctx;
1621
1622         /*
1623          * |pkt| now points to the beginning of the signature, so the difference
1624          * equals the length of the parameters.
1625          */
1626         if (!PACKET_get_sub_packet(&save_param_start, &params,
1627                                    PACKET_remaining(&save_param_start) -
1628                                    PACKET_remaining(pkt))) {
1629             al = SSL_AD_INTERNAL_ERROR;
1630             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1631             goto err;
1632         }
1633
1634         if (SSL_USE_SIGALGS(s)) {
1635             const unsigned char *sigalgs;
1636             int rv;
1637             if (!PACKET_get_bytes(pkt, &sigalgs, 2)) {
1638                 al = SSL_AD_DECODE_ERROR;
1639                 SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1640                 goto err;
1641             }
1642             rv = tls12_check_peer_sigalg(&md, s, sigalgs, pkey);
1643             if (rv == -1) {
1644                 al = SSL_AD_INTERNAL_ERROR;
1645                 goto err;
1646             } else if (rv == 0) {
1647                 al = SSL_AD_DECODE_ERROR;
1648                 goto err;
1649             }
1650 #ifdef SSL_DEBUG
1651             fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
1652 #endif
1653         } else if (EVP_PKEY_id(pkey) == EVP_PKEY_RSA) {
1654             md = EVP_md5_sha1();
1655         } else {
1656             md = EVP_sha1();
1657         }
1658
1659         if (!PACKET_get_length_prefixed_2(pkt, &signature)
1660             || PACKET_remaining(pkt) != 0) {
1661             al = SSL_AD_DECODE_ERROR;
1662             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
1663             goto err;
1664         }
1665         maxsig = EVP_PKEY_size(pkey);
1666         if (maxsig < 0) {
1667             al = SSL_AD_INTERNAL_ERROR;
1668             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1669             goto err;
1670         }
1671
1672         /*
1673          * Check signature length
1674          */
1675         if (PACKET_remaining(&signature) > (size_t)maxsig) {
1676             /* wrong packet length */
1677             al = SSL_AD_DECODE_ERROR;
1678             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE,
1679                    SSL_R_WRONG_SIGNATURE_LENGTH);
1680             goto err;
1681         }
1682
1683         md_ctx = EVP_MD_CTX_new();
1684         if (md_ctx == NULL) {
1685             al = SSL_AD_INTERNAL_ERROR;
1686             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1687             goto err;
1688         }
1689
1690         if (EVP_VerifyInit_ex(md_ctx, md, NULL) <= 0
1691             || EVP_VerifyUpdate(md_ctx, &(s->s3->client_random[0]),
1692                                 SSL3_RANDOM_SIZE) <= 0
1693             || EVP_VerifyUpdate(md_ctx, &(s->s3->server_random[0]),
1694                                 SSL3_RANDOM_SIZE) <= 0
1695             || EVP_VerifyUpdate(md_ctx, PACKET_data(&params),
1696                                 PACKET_remaining(&params)) <= 0) {
1697             EVP_MD_CTX_free(md_ctx);
1698             al = SSL_AD_INTERNAL_ERROR;
1699             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_EVP_LIB);
1700             goto err;
1701         }
1702         if (EVP_VerifyFinal(md_ctx, PACKET_data(&signature),
1703                             PACKET_remaining(&signature), pkey) <= 0) {
1704             /* bad signature */
1705             EVP_MD_CTX_free(md_ctx);
1706             al = SSL_AD_DECRYPT_ERROR;
1707             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_BAD_SIGNATURE);
1708             goto err;
1709         }
1710         EVP_MD_CTX_free(md_ctx);
1711     } else {
1712         /* aNULL, aSRP or PSK do not need public keys */
1713         if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP))
1714             && !(alg_k & SSL_PSK)) {
1715             /* Might be wrong key type, check it */
1716             if (ssl3_check_cert_and_algorithm(s)) {
1717                 /* Otherwise this shouldn't happen */
1718                 al = SSL_AD_INTERNAL_ERROR;
1719                 SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1720             } else {
1721                 al = SSL_AD_DECODE_ERROR;
1722             }
1723             goto err;
1724         }
1725         /* still data left over */
1726         if (PACKET_remaining(pkt) != 0) {
1727             al = SSL_AD_DECODE_ERROR;
1728             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_EXTRA_DATA_IN_MESSAGE);
1729             goto err;
1730         }
1731     }
1732
1733     return MSG_PROCESS_CONTINUE_READING;
1734  err:
1735     if (al != -1)
1736         ssl3_send_alert(s, SSL3_AL_FATAL, al);
1737     ossl_statem_set_error(s);
1738     return MSG_PROCESS_ERROR;
1739 }
1740
1741 MSG_PROCESS_RETURN tls_process_certificate_request(SSL *s, PACKET *pkt)
1742 {
1743     int ret = MSG_PROCESS_ERROR;
1744     unsigned int list_len, ctype_num, i, name_len;
1745     X509_NAME *xn = NULL;
1746     const unsigned char *data;
1747     const unsigned char *namestart, *namebytes;
1748     STACK_OF(X509_NAME) *ca_sk = NULL;
1749
1750     if ((ca_sk = sk_X509_NAME_new(ca_dn_cmp)) == NULL) {
1751         SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
1752         goto err;
1753     }
1754
1755     /* get the certificate types */
1756     if (!PACKET_get_1(pkt, &ctype_num)
1757         || !PACKET_get_bytes(pkt, &data, ctype_num)) {
1758         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1759         SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, SSL_R_LENGTH_MISMATCH);
1760         goto err;
1761     }
1762     OPENSSL_free(s->cert->ctypes);
1763     s->cert->ctypes = NULL;
1764     if (ctype_num > SSL3_CT_NUMBER) {
1765         /* If we exceed static buffer copy all to cert structure */
1766         s->cert->ctypes = OPENSSL_malloc(ctype_num);
1767         if (s->cert->ctypes == NULL) {
1768             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
1769             goto err;
1770         }
1771         memcpy(s->cert->ctypes, data, ctype_num);
1772         s->cert->ctype_num = (size_t)ctype_num;
1773         ctype_num = SSL3_CT_NUMBER;
1774     }
1775     for (i = 0; i < ctype_num; i++)
1776         s->s3->tmp.ctype[i] = data[i];
1777
1778     if (SSL_USE_SIGALGS(s)) {
1779         if (!PACKET_get_net_2(pkt, &list_len)
1780             || !PACKET_get_bytes(pkt, &data, list_len)) {
1781             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1782             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST,
1783                    SSL_R_LENGTH_MISMATCH);
1784             goto err;
1785         }
1786
1787         /* Clear certificate digests and validity flags */
1788         for (i = 0; i < SSL_PKEY_NUM; i++) {
1789             s->s3->tmp.md[i] = NULL;
1790             s->s3->tmp.valid_flags[i] = 0;
1791         }
1792         if ((list_len & 1) || !tls1_save_sigalgs(s, data, list_len)) {
1793             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1794             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST,
1795                    SSL_R_SIGNATURE_ALGORITHMS_ERROR);
1796             goto err;
1797         }
1798         if (!tls1_process_sigalgs(s)) {
1799             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1800             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
1801             goto err;
1802         }
1803     } else {
1804         ssl_set_default_md(s);
1805     }
1806
1807     /* get the CA RDNs */
1808     if (!PACKET_get_net_2(pkt, &list_len)
1809         || PACKET_remaining(pkt) != list_len) {
1810         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1811         SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, SSL_R_LENGTH_MISMATCH);
1812         goto err;
1813     }
1814
1815     while (PACKET_remaining(pkt)) {
1816         if (!PACKET_get_net_2(pkt, &name_len)
1817             || !PACKET_get_bytes(pkt, &namebytes, name_len)) {
1818             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1819             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST,
1820                    SSL_R_LENGTH_MISMATCH);
1821             goto err;
1822         }
1823
1824         namestart = namebytes;
1825
1826         if ((xn = d2i_X509_NAME(NULL, (const unsigned char **)&namebytes,
1827                                 name_len)) == NULL) {
1828             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1829             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_ASN1_LIB);
1830             goto err;
1831         }
1832
1833         if (namebytes != (namestart + name_len)) {
1834             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1835             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST,
1836                    SSL_R_CA_DN_LENGTH_MISMATCH);
1837             goto err;
1838         }
1839         if (!sk_X509_NAME_push(ca_sk, xn)) {
1840             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
1841             goto err;
1842         }
1843         xn = NULL;
1844     }
1845
1846     /* we should setup a certificate to return.... */
1847     s->s3->tmp.cert_req = 1;
1848     s->s3->tmp.ctype_num = ctype_num;
1849     sk_X509_NAME_pop_free(s->s3->tmp.ca_names, X509_NAME_free);
1850     s->s3->tmp.ca_names = ca_sk;
1851     ca_sk = NULL;
1852
1853     ret = MSG_PROCESS_CONTINUE_PROCESSING;
1854     goto done;
1855  err:
1856     ossl_statem_set_error(s);
1857  done:
1858     X509_NAME_free(xn);
1859     sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
1860     return ret;
1861 }
1862
1863 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
1864 {
1865     return (X509_NAME_cmp(*a, *b));
1866 }
1867
1868 MSG_PROCESS_RETURN tls_process_new_session_ticket(SSL *s, PACKET *pkt)
1869 {
1870     int al;
1871     unsigned int ticklen;
1872     unsigned long ticket_lifetime_hint;
1873
1874     if (!PACKET_get_net_4(pkt, &ticket_lifetime_hint)
1875         || !PACKET_get_net_2(pkt, &ticklen)
1876         || PACKET_remaining(pkt) != ticklen) {
1877         al = SSL_AD_DECODE_ERROR;
1878         SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
1879         goto f_err;
1880     }
1881
1882     /* Server is allowed to change its mind and send an empty ticket. */
1883     if (ticklen == 0)
1884         return MSG_PROCESS_CONTINUE_READING;
1885
1886     if (s->session->session_id_length > 0) {
1887         int i = s->session_ctx->session_cache_mode;
1888         SSL_SESSION *new_sess;
1889         /*
1890          * We reused an existing session, so we need to replace it with a new
1891          * one
1892          */
1893         if (i & SSL_SESS_CACHE_CLIENT) {
1894             /*
1895              * Remove the old session from the cache. We carry on if this fails
1896              */
1897             SSL_CTX_remove_session(s->session_ctx, s->session);
1898         }
1899
1900         if ((new_sess = ssl_session_dup(s->session, 0)) == 0) {
1901             al = SSL_AD_INTERNAL_ERROR;
1902             SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
1903             goto f_err;
1904         }
1905
1906         SSL_SESSION_free(s->session);
1907         s->session = new_sess;
1908     }
1909
1910     OPENSSL_free(s->session->tlsext_tick);
1911     s->session->tlsext_ticklen = 0;
1912
1913     s->session->tlsext_tick = OPENSSL_malloc(ticklen);
1914     if (s->session->tlsext_tick == NULL) {
1915         SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
1916         goto err;
1917     }
1918     if (!PACKET_copy_bytes(pkt, s->session->tlsext_tick, ticklen)) {
1919         al = SSL_AD_DECODE_ERROR;
1920         SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
1921         goto f_err;
1922     }
1923
1924     s->session->tlsext_tick_lifetime_hint = ticket_lifetime_hint;
1925     s->session->tlsext_ticklen = ticklen;
1926     /*
1927      * There are two ways to detect a resumed ticket session. One is to set
1928      * an appropriate session ID and then the server must return a match in
1929      * ServerHello. This allows the normal client session ID matching to work
1930      * and we know much earlier that the ticket has been accepted. The
1931      * other way is to set zero length session ID when the ticket is
1932      * presented and rely on the handshake to determine session resumption.
1933      * We choose the former approach because this fits in with assumptions
1934      * elsewhere in OpenSSL. The session ID is set to the SHA256 (or SHA1 is
1935      * SHA256 is disabled) hash of the ticket.
1936      */
1937     if (!EVP_Digest(s->session->tlsext_tick, ticklen,
1938                     s->session->session_id, &s->session->session_id_length,
1939                     EVP_sha256(), NULL)) {
1940         SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, ERR_R_EVP_LIB);
1941         goto err;
1942     }
1943     return MSG_PROCESS_CONTINUE_READING;
1944  f_err:
1945     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1946  err:
1947     ossl_statem_set_error(s);
1948     return MSG_PROCESS_ERROR;
1949 }
1950
1951 MSG_PROCESS_RETURN tls_process_cert_status(SSL *s, PACKET *pkt)
1952 {
1953     int al;
1954     unsigned long resplen;
1955     unsigned int type;
1956
1957     if (!PACKET_get_1(pkt, &type)
1958         || type != TLSEXT_STATUSTYPE_ocsp) {
1959         al = SSL_AD_DECODE_ERROR;
1960         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, SSL_R_UNSUPPORTED_STATUS_TYPE);
1961         goto f_err;
1962     }
1963     if (!PACKET_get_net_3(pkt, &resplen)
1964         || PACKET_remaining(pkt) != resplen) {
1965         al = SSL_AD_DECODE_ERROR;
1966         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, SSL_R_LENGTH_MISMATCH);
1967         goto f_err;
1968     }
1969     s->tlsext_ocsp_resp = OPENSSL_malloc(resplen);
1970     if (s->tlsext_ocsp_resp == NULL) {
1971         al = SSL_AD_INTERNAL_ERROR;
1972         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, ERR_R_MALLOC_FAILURE);
1973         goto f_err;
1974     }
1975     if (!PACKET_copy_bytes(pkt, s->tlsext_ocsp_resp, resplen)) {
1976         al = SSL_AD_DECODE_ERROR;
1977         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, SSL_R_LENGTH_MISMATCH);
1978         goto f_err;
1979     }
1980     s->tlsext_ocsp_resplen = resplen;
1981     return MSG_PROCESS_CONTINUE_READING;
1982  f_err:
1983     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1984     ossl_statem_set_error(s);
1985     return MSG_PROCESS_ERROR;
1986 }
1987
1988 MSG_PROCESS_RETURN tls_process_server_done(SSL *s, PACKET *pkt)
1989 {
1990     if (PACKET_remaining(pkt) > 0) {
1991         /* should contain no data */
1992         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1993         SSLerr(SSL_F_TLS_PROCESS_SERVER_DONE, SSL_R_LENGTH_MISMATCH);
1994         ossl_statem_set_error(s);
1995         return MSG_PROCESS_ERROR;
1996     }
1997 #ifndef OPENSSL_NO_SRP
1998     if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) {
1999         if (SRP_Calc_A_param(s) <= 0) {
2000             SSLerr(SSL_F_TLS_PROCESS_SERVER_DONE, SSL_R_SRP_A_CALC);
2001             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2002             ossl_statem_set_error(s);
2003             return MSG_PROCESS_ERROR;
2004         }
2005     }
2006 #endif
2007
2008     /*
2009      * at this point we check that we have the required stuff from
2010      * the server
2011      */
2012     if (!ssl3_check_cert_and_algorithm(s)) {
2013         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2014         ossl_statem_set_error(s);
2015         return MSG_PROCESS_ERROR;
2016     }
2017
2018     /*
2019      * Call the ocsp status callback if needed. The |tlsext_ocsp_resp| and
2020      * |tlsext_ocsp_resplen| values will be set if we actually received a status
2021      * message, or NULL and -1 otherwise
2022      */
2023     if (s->tlsext_status_type != -1 && s->ctx->tlsext_status_cb != NULL) {
2024         int ret;
2025         ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
2026         if (ret == 0) {
2027             ssl3_send_alert(s, SSL3_AL_FATAL,
2028                             SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE);
2029             SSLerr(SSL_F_TLS_PROCESS_SERVER_DONE,
2030                    SSL_R_INVALID_STATUS_RESPONSE);
2031             return MSG_PROCESS_ERROR;
2032         }
2033         if (ret < 0) {
2034             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2035             SSLerr(SSL_F_TLS_PROCESS_SERVER_DONE, ERR_R_MALLOC_FAILURE);
2036             return MSG_PROCESS_ERROR;
2037         }
2038     }
2039 #ifndef OPENSSL_NO_CT
2040     if (s->ct_validation_callback != NULL) {
2041         /* Note we validate the SCTs whether or not we abort on error */
2042         if (!ssl_validate_ct(s) && (s->verify_mode & SSL_VERIFY_PEER)) {
2043             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2044             return MSG_PROCESS_ERROR;
2045         }
2046     }
2047 #endif
2048
2049 #ifndef OPENSSL_NO_SCTP
2050     /* Only applies to renegotiation */
2051     if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))
2052         && s->renegotiate != 0)
2053         return MSG_PROCESS_CONTINUE_PROCESSING;
2054     else
2055 #endif
2056         return MSG_PROCESS_FINISHED_READING;
2057 }
2058
2059 static int tls_construct_cke_psk_preamble(SSL *s, WPACKET *pkt, int *al)
2060 {
2061 #ifndef OPENSSL_NO_PSK
2062     int ret = 0;
2063     /*
2064      * The callback needs PSK_MAX_IDENTITY_LEN + 1 bytes to return a
2065      * \0-terminated identity. The last byte is for us for simulating
2066      * strnlen.
2067      */
2068     char identity[PSK_MAX_IDENTITY_LEN + 1];
2069     size_t identitylen = 0;
2070     unsigned char psk[PSK_MAX_PSK_LEN];
2071     unsigned char *tmppsk = NULL;
2072     char *tmpidentity = NULL;
2073     size_t psklen = 0;
2074
2075     if (s->psk_client_callback == NULL) {
2076         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_PSK_PREAMBLE, SSL_R_PSK_NO_CLIENT_CB);
2077         *al = SSL_AD_INTERNAL_ERROR;
2078         goto err;
2079     }
2080
2081     memset(identity, 0, sizeof(identity));
2082
2083     psklen = s->psk_client_callback(s, s->session->psk_identity_hint,
2084                                     identity, sizeof(identity) - 1,
2085                                     psk, sizeof(psk));
2086
2087     if (psklen > PSK_MAX_PSK_LEN) {
2088         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
2089         *al = SSL_AD_HANDSHAKE_FAILURE;
2090         goto err;
2091     } else if (psklen == 0) {
2092         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_PSK_PREAMBLE,
2093                SSL_R_PSK_IDENTITY_NOT_FOUND);
2094         *al = SSL_AD_HANDSHAKE_FAILURE;
2095         goto err;
2096     }
2097
2098     identitylen = strlen(identity);
2099     if (identitylen > PSK_MAX_IDENTITY_LEN) {
2100         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
2101         *al = SSL_AD_HANDSHAKE_FAILURE;
2102         goto err;
2103     }
2104
2105     tmppsk = OPENSSL_memdup(psk, psklen);
2106     tmpidentity = OPENSSL_strdup(identity);
2107     if (tmppsk == NULL || tmpidentity == NULL) {
2108         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_PSK_PREAMBLE, ERR_R_MALLOC_FAILURE);
2109         *al = SSL_AD_INTERNAL_ERROR;
2110         goto err;
2111     }
2112
2113     OPENSSL_free(s->s3->tmp.psk);
2114     s->s3->tmp.psk = tmppsk;
2115     s->s3->tmp.psklen = psklen;
2116     tmppsk = NULL;
2117     OPENSSL_free(s->session->psk_identity);
2118     s->session->psk_identity = tmpidentity;
2119     tmpidentity = NULL;
2120
2121     if (!WPACKET_sub_memcpy_u16(pkt, identity, identitylen))  {
2122         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
2123         *al = SSL_AD_INTERNAL_ERROR;
2124         goto err;
2125     }
2126
2127     ret = 1;
2128
2129  err:
2130     OPENSSL_cleanse(psk, psklen);
2131     OPENSSL_cleanse(identity, sizeof(identity));
2132     OPENSSL_clear_free(tmppsk, psklen);
2133     OPENSSL_clear_free(tmpidentity, identitylen);
2134
2135     return ret;
2136 #else
2137     SSLerr(SSL_F_TLS_CONSTRUCT_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
2138     *al = SSL_AD_INTERNAL_ERROR;
2139     return 0;
2140 #endif
2141 }
2142
2143 static int tls_construct_cke_rsa(SSL *s, WPACKET *pkt, int *al)
2144 {
2145 #ifndef OPENSSL_NO_RSA
2146     unsigned char *encdata = NULL;
2147     EVP_PKEY *pkey = NULL;
2148     EVP_PKEY_CTX *pctx = NULL;
2149     size_t enclen;
2150     unsigned char *pms = NULL;
2151     size_t pmslen = 0;
2152
2153     if (s->session->peer == NULL) {
2154         /*
2155          * We should always have a server certificate with SSL_kRSA.
2156          */
2157         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_RSA, ERR_R_INTERNAL_ERROR);
2158         return 0;
2159     }
2160
2161     pkey = X509_get0_pubkey(s->session->peer);
2162     if (EVP_PKEY_get0_RSA(pkey) == NULL) {
2163         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_RSA, ERR_R_INTERNAL_ERROR);
2164         return 0;
2165     }
2166
2167     pmslen = SSL_MAX_MASTER_KEY_LENGTH;
2168     pms = OPENSSL_malloc(pmslen);
2169     if (pms == NULL) {
2170         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_RSA, ERR_R_MALLOC_FAILURE);
2171         *al = SSL_AD_INTERNAL_ERROR;
2172         return 0;
2173     }
2174
2175     pms[0] = s->client_version >> 8;
2176     pms[1] = s->client_version & 0xff;
2177     if (RAND_bytes(pms + 2, pmslen - 2) <= 0) {
2178         goto err;
2179     }
2180
2181     /* Fix buf for TLS and beyond */
2182     if (s->version > SSL3_VERSION && !WPACKET_start_sub_packet_u16(pkt)) {
2183         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_RSA, ERR_R_INTERNAL_ERROR);
2184         goto err;
2185     }
2186     pctx = EVP_PKEY_CTX_new(pkey, NULL);
2187     if (pctx == NULL || EVP_PKEY_encrypt_init(pctx) <= 0
2188         || EVP_PKEY_encrypt(pctx, NULL, &enclen, pms, pmslen) <= 0) {
2189         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_RSA, ERR_R_EVP_LIB);
2190         goto err;
2191     }
2192     if (!WPACKET_allocate_bytes(pkt, enclen, &encdata)
2193             || EVP_PKEY_encrypt(pctx, encdata, &enclen, pms, pmslen) <= 0) {
2194         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_RSA, SSL_R_BAD_RSA_ENCRYPT);
2195         goto err;
2196     }
2197     EVP_PKEY_CTX_free(pctx);
2198     pctx = NULL;
2199 # ifdef PKCS1_CHECK
2200     if (s->options & SSL_OP_PKCS1_CHECK_1)
2201         (*p)[1]++;
2202     if (s->options & SSL_OP_PKCS1_CHECK_2)
2203         tmp_buf[0] = 0x70;
2204 # endif
2205
2206     /* Fix buf for TLS and beyond */
2207     if (s->version > SSL3_VERSION && !WPACKET_close(pkt)) {
2208         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_RSA, ERR_R_INTERNAL_ERROR);
2209         goto err;
2210     }
2211
2212     s->s3->tmp.pms = pms;
2213     s->s3->tmp.pmslen = pmslen;
2214
2215     return 1;
2216  err:
2217     OPENSSL_clear_free(pms, pmslen);
2218     EVP_PKEY_CTX_free(pctx);
2219
2220     return 0;
2221 #else
2222     SSLerr(SSL_F_TLS_CONSTRUCT_CKE_RSA, ERR_R_INTERNAL_ERROR);
2223     *al = SSL_AD_INTERNAL_ERROR;
2224     return 0;
2225 #endif
2226 }
2227
2228 static int tls_construct_cke_dhe(SSL *s, WPACKET *pkt, int *al)
2229 {
2230 #ifndef OPENSSL_NO_DH
2231     DH *dh_clnt = NULL;
2232     const BIGNUM *pub_key;
2233     EVP_PKEY *ckey = NULL, *skey = NULL;
2234     unsigned char *keybytes = NULL;
2235
2236     skey = s->s3->peer_tmp;
2237     if (skey == NULL)
2238         goto err;
2239
2240     ckey = ssl_generate_pkey(skey);
2241     dh_clnt = EVP_PKEY_get0_DH(ckey);
2242
2243     if (dh_clnt == NULL || ssl_derive(s, ckey, skey) == 0)
2244         goto err;
2245
2246     /* send off the data */
2247     DH_get0_key(dh_clnt, &pub_key, NULL);
2248     if (!WPACKET_sub_allocate_bytes_u16(pkt, BN_num_bytes(pub_key), &keybytes))
2249         goto err;
2250
2251     BN_bn2bin(pub_key, keybytes);
2252     EVP_PKEY_free(ckey);
2253
2254     return 1;
2255  err:
2256     EVP_PKEY_free(ckey);
2257 #endif
2258     SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR);
2259     *al = SSL_AD_INTERNAL_ERROR;
2260     return 0;
2261 }
2262
2263 static int tls_construct_cke_ecdhe(SSL *s, WPACKET *pkt, int *al)
2264 {
2265 #ifndef OPENSSL_NO_EC
2266     unsigned char *encodedPoint = NULL;
2267     int encoded_pt_len = 0;
2268     EVP_PKEY *ckey = NULL, *skey = NULL;
2269     int ret = 0;
2270
2271     skey = s->s3->peer_tmp;
2272     if (skey == NULL) {
2273         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR);
2274         return 0;
2275     }
2276
2277     ckey = ssl_generate_pkey(skey);
2278
2279     if (ssl_derive(s, ckey, skey) == 0) {
2280         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_EVP_LIB);
2281         goto err;
2282     }
2283
2284     /* Generate encoding of client key */
2285     encoded_pt_len = EVP_PKEY_get1_tls_encodedpoint(ckey, &encodedPoint);
2286
2287     if (encoded_pt_len == 0) {
2288         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_EC_LIB);
2289         goto err;
2290     }
2291
2292     if (!WPACKET_sub_memcpy_u8(pkt, encodedPoint, encoded_pt_len)) {
2293         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR);
2294         goto err;
2295     }
2296
2297     ret = 1;
2298  err:
2299     OPENSSL_free(encodedPoint);
2300     EVP_PKEY_free(ckey);
2301     return ret;
2302 #else
2303     SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR);
2304     *al = SSL_AD_INTERNAL_ERROR;
2305     return 0;
2306 #endif
2307 }
2308
2309 static int tls_construct_cke_gost(SSL *s, WPACKET *pkt, int *al)
2310 {
2311 #ifndef OPENSSL_NO_GOST
2312     /* GOST key exchange message creation */
2313     EVP_PKEY_CTX *pkey_ctx = NULL;
2314     X509 *peer_cert;
2315     size_t msglen;
2316     unsigned int md_len;
2317     unsigned char shared_ukm[32], tmp[256];
2318     EVP_MD_CTX *ukm_hash = NULL;
2319     int dgst_nid = NID_id_GostR3411_94;
2320     unsigned char *pms = NULL;
2321     size_t pmslen = 0;
2322
2323     if ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aGOST12) != 0)
2324         dgst_nid = NID_id_GostR3411_2012_256;
2325
2326     /*
2327      * Get server sertificate PKEY and create ctx from it
2328      */
2329     peer_cert = s->session->peer;
2330     if (!peer_cert) {
2331         *al = SSL_AD_HANDSHAKE_FAILURE;
2332         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST,
2333                SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
2334         return 0;
2335     }
2336
2337     pkey_ctx = EVP_PKEY_CTX_new(X509_get0_pubkey(peer_cert), NULL);
2338     if (pkey_ctx == NULL) {
2339         *al = SSL_AD_INTERNAL_ERROR;
2340         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, ERR_R_MALLOC_FAILURE);
2341         return 0;
2342     }
2343     /*
2344      * If we have send a certificate, and certificate key
2345      * parameters match those of server certificate, use
2346      * certificate key for key exchange
2347      */
2348
2349     /* Otherwise, generate ephemeral key pair */
2350     pmslen = 32;
2351     pms = OPENSSL_malloc(pmslen);
2352     if (pms == NULL) {
2353         *al = SSL_AD_INTERNAL_ERROR;
2354         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, ERR_R_MALLOC_FAILURE);
2355         goto err;
2356     }
2357
2358     if (EVP_PKEY_encrypt_init(pkey_ctx) <= 0
2359         /* Generate session key */
2360         || RAND_bytes(pms, pmslen) <= 0) {
2361         *al = SSL_AD_INTERNAL_ERROR;
2362         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, ERR_R_INTERNAL_ERROR);
2363         goto err;
2364     };
2365     /*
2366      * Compute shared IV and store it in algorithm-specific context
2367      * data
2368      */
2369     ukm_hash = EVP_MD_CTX_new();
2370     if (ukm_hash == NULL
2371         || EVP_DigestInit(ukm_hash, EVP_get_digestbynid(dgst_nid)) <= 0
2372         || EVP_DigestUpdate(ukm_hash, s->s3->client_random,
2373                             SSL3_RANDOM_SIZE) <= 0
2374         || EVP_DigestUpdate(ukm_hash, s->s3->server_random,
2375                             SSL3_RANDOM_SIZE) <= 0
2376         || EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len) <= 0) {
2377         *al = SSL_AD_INTERNAL_ERROR;
2378         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, ERR_R_INTERNAL_ERROR);
2379         goto err;
2380     }
2381     EVP_MD_CTX_free(ukm_hash);
2382     ukm_hash = NULL;
2383     if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT,
2384                           EVP_PKEY_CTRL_SET_IV, 8, shared_ukm) < 0) {
2385         *al = SSL_AD_INTERNAL_ERROR;
2386         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, SSL_R_LIBRARY_BUG);
2387         goto err;
2388     }
2389     /* Make GOST keytransport blob message */
2390     /*
2391      * Encapsulate it into sequence
2392      */
2393     msglen = 255;
2394     if (EVP_PKEY_encrypt(pkey_ctx, tmp, &msglen, pms, pmslen) <= 0) {
2395         *al = SSL_AD_INTERNAL_ERROR;
2396         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, SSL_R_LIBRARY_BUG);
2397         goto err;
2398     }
2399
2400     if (!WPACKET_put_bytes_u8(pkt, V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED)
2401             || (msglen >= 0x80 && !WPACKET_put_bytes_u8(pkt, 0x81))
2402             || !WPACKET_sub_memcpy_u8(pkt, tmp, msglen)) {
2403         *al = SSL_AD_INTERNAL_ERROR;
2404         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, ERR_R_INTERNAL_ERROR);
2405         goto err;
2406     }
2407
2408     EVP_PKEY_CTX_free(pkey_ctx);
2409     s->s3->tmp.pms = pms;
2410     s->s3->tmp.pmslen = pmslen;
2411
2412     return 1;
2413  err:
2414     EVP_PKEY_CTX_free(pkey_ctx);
2415     OPENSSL_clear_free(pms, pmslen);
2416     EVP_MD_CTX_free(ukm_hash);
2417     return 0;
2418 #else
2419     SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, ERR_R_INTERNAL_ERROR);
2420     *al = SSL_AD_INTERNAL_ERROR;
2421     return 0;
2422 #endif
2423 }
2424
2425 static int tls_construct_cke_srp(SSL *s, WPACKET *pkt, int *al)
2426 {
2427 #ifndef OPENSSL_NO_SRP
2428     unsigned char *abytes = NULL;
2429
2430     if (s->srp_ctx.A == NULL
2431             || !WPACKET_sub_allocate_bytes_u16(pkt, BN_num_bytes(s->srp_ctx.A),
2432                                                &abytes)) {
2433         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_SRP, ERR_R_INTERNAL_ERROR);
2434         return 0;
2435     }
2436     BN_bn2bin(s->srp_ctx.A, abytes);
2437
2438     OPENSSL_free(s->session->srp_username);
2439     s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);
2440     if (s->session->srp_username == NULL) {
2441         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_SRP, ERR_R_MALLOC_FAILURE);
2442         return 0;
2443     }
2444
2445     return 1;
2446 #else
2447     SSLerr(SSL_F_TLS_CONSTRUCT_CKE_SRP, ERR_R_INTERNAL_ERROR);
2448     *al = SSL_AD_INTERNAL_ERROR;
2449     return 0;
2450 #endif
2451 }
2452
2453 int tls_construct_client_key_exchange(SSL *s, WPACKET *pkt)
2454 {
2455     unsigned long alg_k;
2456     int al = -1;
2457
2458     if (!ssl_set_handshake_header(s, pkt, SSL3_MT_CLIENT_KEY_EXCHANGE)) {
2459         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2460         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2461         goto err;
2462     }
2463
2464     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2465
2466     if ((alg_k & SSL_PSK)
2467         && !tls_construct_cke_psk_preamble(s, pkt, &al))
2468         goto err;
2469
2470     if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
2471         if (!tls_construct_cke_rsa(s, pkt, &al))
2472             goto err;
2473     } else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
2474         if (!tls_construct_cke_dhe(s, pkt, &al))
2475             goto err;
2476     } else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
2477         if (!tls_construct_cke_ecdhe(s, pkt, &al))
2478             goto err;
2479     } else if (alg_k & SSL_kGOST) {
2480         if (!tls_construct_cke_gost(s, pkt, &al))
2481             goto err;
2482     } else if (alg_k & SSL_kSRP) {
2483         if (!tls_construct_cke_srp(s, pkt, &al))
2484             goto err;
2485     } else if (!(alg_k & SSL_kPSK)) {
2486         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2487         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2488         goto err;
2489     }
2490
2491     if (!ssl_close_construct_packet(s, pkt)) {
2492         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2493         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2494         goto err;
2495     }
2496
2497     return 1;
2498  err:
2499     if (al != -1)
2500         ssl3_send_alert(s, SSL3_AL_FATAL, al);
2501     OPENSSL_clear_free(s->s3->tmp.pms, s->s3->tmp.pmslen);
2502     s->s3->tmp.pms = NULL;
2503 #ifndef OPENSSL_NO_PSK
2504     OPENSSL_clear_free(s->s3->tmp.psk, s->s3->tmp.psklen);
2505     s->s3->tmp.psk = NULL;
2506 #endif
2507     return 0;
2508 }
2509
2510 int tls_client_key_exchange_post_work(SSL *s)
2511 {
2512     unsigned char *pms = NULL;
2513     size_t pmslen = 0;
2514
2515     pms = s->s3->tmp.pms;
2516     pmslen = s->s3->tmp.pmslen;
2517
2518 #ifndef OPENSSL_NO_SRP
2519     /* Check for SRP */
2520     if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) {
2521         if (!srp_generate_client_master_secret(s)) {
2522             SSLerr(SSL_F_TLS_CLIENT_KEY_EXCHANGE_POST_WORK,
2523                    ERR_R_INTERNAL_ERROR);
2524             goto err;
2525         }
2526         return 1;
2527     }
2528 #endif
2529
2530     if (pms == NULL && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
2531         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2532         SSLerr(SSL_F_TLS_CLIENT_KEY_EXCHANGE_POST_WORK, ERR_R_MALLOC_FAILURE);
2533         goto err;
2534     }
2535     if (!ssl_generate_master_secret(s, pms, pmslen, 1)) {
2536         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2537         SSLerr(SSL_F_TLS_CLIENT_KEY_EXCHANGE_POST_WORK, ERR_R_INTERNAL_ERROR);
2538         /* ssl_generate_master_secret frees the pms even on error */
2539         pms = NULL;
2540         pmslen = 0;
2541         goto err;
2542     }
2543     pms = NULL;
2544     pmslen = 0;
2545
2546 #ifndef OPENSSL_NO_SCTP
2547     if (SSL_IS_DTLS(s)) {
2548         unsigned char sctpauthkey[64];
2549         char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
2550
2551         /*
2552          * Add new shared key for SCTP-Auth, will be ignored if no SCTP
2553          * used.
2554          */
2555         memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
2556                sizeof(DTLS1_SCTP_AUTH_LABEL));
2557
2558         if (SSL_export_keying_material(s, sctpauthkey,
2559                                        sizeof(sctpauthkey), labelbuffer,
2560                                        sizeof(labelbuffer), NULL, 0, 0) <= 0)
2561             goto err;
2562
2563         BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
2564                  sizeof(sctpauthkey), sctpauthkey);
2565     }
2566 #endif
2567
2568     return 1;
2569  err:
2570     OPENSSL_clear_free(pms, pmslen);
2571     s->s3->tmp.pms = NULL;
2572     return 0;
2573 }
2574
2575 int tls_construct_client_verify(SSL *s, WPACKET *pkt)
2576 {
2577     EVP_PKEY *pkey;
2578     const EVP_MD *md = s->s3->tmp.md[s->cert->key - s->cert->pkeys];
2579     EVP_MD_CTX *mctx = NULL;
2580     unsigned u = 0;
2581     long hdatalen = 0;
2582     void *hdata;
2583     unsigned char *sig = NULL;
2584
2585     if (!ssl_set_handshake_header(s, pkt, SSL3_MT_CERTIFICATE_VERIFY)) {
2586         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
2587         goto err;
2588     }
2589
2590     mctx = EVP_MD_CTX_new();
2591     if (mctx == NULL) {
2592         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_MALLOC_FAILURE);
2593         goto err;
2594     }
2595     pkey = s->cert->key->privatekey;
2596
2597     hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
2598     if (hdatalen <= 0) {
2599         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
2600         goto err;
2601     }
2602     if (SSL_USE_SIGALGS(s)&& !tls12_get_sigandhash(pkt, pkey, md)) {
2603         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
2604         goto err;
2605     }
2606 #ifdef SSL_DEBUG
2607     fprintf(stderr, "Using client alg %s\n", EVP_MD_name(md));
2608 #endif
2609     sig = OPENSSL_malloc(EVP_PKEY_size(pkey));
2610     if (sig == NULL) {
2611         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_MALLOC_FAILURE);
2612         goto err;
2613     }
2614     if (!EVP_SignInit_ex(mctx, md, NULL)
2615         || !EVP_SignUpdate(mctx, hdata, hdatalen)
2616         || (s->version == SSL3_VERSION
2617             && !EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
2618                                 s->session->master_key_length,
2619                                 s->session->master_key))
2620         || !EVP_SignFinal(mctx, sig, &u, pkey)) {
2621         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_EVP_LIB);
2622         goto err;
2623     }
2624 #ifndef OPENSSL_NO_GOST
2625     {
2626         int pktype = EVP_PKEY_id(pkey);
2627         if (pktype == NID_id_GostR3410_2001
2628             || pktype == NID_id_GostR3410_2012_256
2629             || pktype == NID_id_GostR3410_2012_512)
2630             BUF_reverse(sig, NULL, u);
2631     }
2632 #endif
2633
2634     if (!WPACKET_sub_memcpy_u16(pkt, sig, u)) {
2635         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
2636         goto err;
2637     }
2638
2639     /* Digest cached records and discard handshake buffer */
2640     if (!ssl3_digest_cached_records(s, 0))
2641         goto err;
2642
2643     if (!ssl_close_construct_packet(s, pkt)) {
2644         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
2645         goto err;
2646     }
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     if (!ssl_set_handshake_header(s, pkt, SSL3_MT_NEXT_PROTO)) {
2850         SSLerr(SSL_F_TLS_CONSTRUCT_NEXT_PROTO, ERR_R_INTERNAL_ERROR);
2851         goto err;
2852     }
2853
2854     len = s->next_proto_negotiated_len;
2855     padding_len = 32 - ((len + 2) % 32);
2856
2857     if (!WPACKET_sub_memcpy_u8(pkt, s->next_proto_negotiated, len)
2858             || !WPACKET_sub_allocate_bytes_u8(pkt, padding_len, &padding)) {
2859         SSLerr(SSL_F_TLS_CONSTRUCT_NEXT_PROTO, ERR_R_INTERNAL_ERROR);
2860         goto err;
2861     }
2862
2863     memset(padding, 0, padding_len);
2864
2865     if (!ssl_close_construct_packet(s, pkt)) {
2866         SSLerr(SSL_F_TLS_CONSTRUCT_NEXT_PROTO, ERR_R_INTERNAL_ERROR);
2867         goto err;
2868     }
2869
2870     return 1;
2871  err:
2872     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2873     return 0;
2874 }
2875 #endif
2876
2877 int ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
2878 {
2879     int i = 0;
2880 #ifndef OPENSSL_NO_ENGINE
2881     if (s->ctx->client_cert_engine) {
2882         i = ENGINE_load_ssl_client_cert(s->ctx->client_cert_engine, s,
2883                                         SSL_get_client_CA_list(s),
2884                                         px509, ppkey, NULL, NULL, NULL);
2885         if (i != 0)
2886             return i;
2887     }
2888 #endif
2889     if (s->ctx->client_cert_cb)
2890         i = s->ctx->client_cert_cb(s, px509, ppkey);
2891     return i;
2892 }
2893
2894 int ssl_cipher_list_to_bytes(SSL *s, STACK_OF(SSL_CIPHER) *sk, WPACKET *pkt)
2895 {
2896     int i;
2897     size_t totlen = 0, len, maxlen;
2898     int empty_reneg_info_scsv = !s->renegotiate;
2899     /* Set disabled masks for this session */
2900     ssl_set_client_disabled(s);
2901
2902     if (sk == NULL)
2903         return (0);
2904
2905 #ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH
2906 # if OPENSSL_MAX_TLS1_2_CIPHER_LENGTH < 6
2907 #  error Max cipher length too short
2908 # endif
2909     /*
2910      * Some servers hang if client hello > 256 bytes as hack workaround
2911      * chop number of supported ciphers to keep it well below this if we
2912      * use TLS v1.2
2913      */
2914     if (TLS1_get_version(s) >= TLS1_2_VERSION)
2915         maxlen = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1;
2916     else
2917 #endif
2918         /* Maximum length that can be stored in 2 bytes. Length must be even */
2919         maxlen = 0xfffe;
2920
2921     if (empty_reneg_info_scsv)
2922         maxlen -= 2;
2923     if (s->mode & SSL_MODE_SEND_FALLBACK_SCSV)
2924         maxlen -= 2;
2925
2926     for (i = 0; i < sk_SSL_CIPHER_num(sk) && totlen < maxlen; i++) {
2927         const SSL_CIPHER *c;
2928
2929         c = sk_SSL_CIPHER_value(sk, i);
2930         /* Skip disabled ciphers */
2931         if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_SUPPORTED))
2932             continue;
2933
2934         if (!s->method->put_cipher_by_char(c, pkt, &len)) {
2935             SSLerr(SSL_F_SSL_CIPHER_LIST_TO_BYTES, ERR_R_INTERNAL_ERROR);
2936             return 0;
2937         }
2938
2939         totlen += len;
2940     }
2941
2942     if (totlen == 0) {
2943         SSLerr(SSL_F_SSL_CIPHER_LIST_TO_BYTES, SSL_R_NO_CIPHERS_AVAILABLE);
2944         return 0;
2945     }
2946
2947     if (totlen != 0) {
2948         if (empty_reneg_info_scsv) {
2949             static SSL_CIPHER scsv = {
2950                 0, NULL, SSL3_CK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
2951             };
2952             if (!s->method->put_cipher_by_char(&scsv, pkt, &len)) {
2953                 SSLerr(SSL_F_SSL_CIPHER_LIST_TO_BYTES, ERR_R_INTERNAL_ERROR);
2954                 return 0;
2955             }
2956         }
2957         if (s->mode & SSL_MODE_SEND_FALLBACK_SCSV) {
2958             static SSL_CIPHER scsv = {
2959                 0, NULL, SSL3_CK_FALLBACK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
2960             };
2961             if (!s->method->put_cipher_by_char(&scsv, pkt, &len)) {
2962                 SSLerr(SSL_F_SSL_CIPHER_LIST_TO_BYTES, ERR_R_INTERNAL_ERROR);
2963                 return 0;
2964             }
2965         }
2966     }
2967
2968     return 1;
2969 }