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