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