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