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