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