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