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