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