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