Make error reason for disallowed legacy sigalg more specific
[openssl.git] / ssl / statem / statem_clnt.c
1 /*
2  * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
4  * Copyright 2005 Nokia. All rights reserved.
5  *
6  * Licensed under the Apache License 2.0 (the "License").  You may not use
7  * this file except in compliance with the License.  You can obtain a copy
8  * in the file LICENSE in the source distribution or at
9  * https://www.openssl.org/source/license.html
10  */
11
12 #include <stdio.h>
13 #include <time.h>
14 #include <assert.h>
15 #include "../ssl_local.h"
16 #include "statem_local.h"
17 #include <openssl/buffer.h>
18 #include <openssl/rand.h>
19 #include <openssl/objects.h>
20 #include <openssl/evp.h>
21 #include <openssl/md5.h>
22 #include <openssl/dh.h>
23 #include <openssl/rsa.h>
24 #include <openssl/bn.h>
25 #include <openssl/engine.h>
26 #include <openssl/trace.h>
27 #include <openssl/core_names.h>
28 #include <openssl/param_build.h>
29 #include "internal/cryptlib.h"
30
31 static MSG_PROCESS_RETURN tls_process_as_hello_retry_request(SSL_CONNECTION *s,
32                                                              PACKET *pkt);
33 static MSG_PROCESS_RETURN tls_process_encrypted_extensions(SSL_CONNECTION *s,
34                                                            PACKET *pkt);
35
36 static ossl_inline int cert_req_allowed(SSL_CONNECTION *s);
37 static int key_exchange_expected(SSL_CONNECTION *s);
38 static int ssl_cipher_list_to_bytes(SSL_CONNECTION *s, STACK_OF(SSL_CIPHER) *sk,
39                                     WPACKET *pkt);
40
41 /*
42  * Is a CertificateRequest message allowed at the moment or not?
43  *
44  *  Return values are:
45  *  1: Yes
46  *  0: No
47  */
48 static ossl_inline int cert_req_allowed(SSL_CONNECTION *s)
49 {
50     /* TLS does not like anon-DH with client cert */
51     if ((s->version > SSL3_VERSION
52          && (s->s3.tmp.new_cipher->algorithm_auth & SSL_aNULL))
53         || (s->s3.tmp.new_cipher->algorithm_auth & (SSL_aSRP | SSL_aPSK)))
54         return 0;
55
56     return 1;
57 }
58
59 /*
60  * Should we expect the ServerKeyExchange message or not?
61  *
62  *  Return values are:
63  *  1: Yes
64  *  0: No
65  */
66 static int key_exchange_expected(SSL_CONNECTION *s)
67 {
68     long alg_k = s->s3.tmp.new_cipher->algorithm_mkey;
69
70     /*
71      * Can't skip server key exchange if this is an ephemeral
72      * ciphersuite or for SRP
73      */
74     if (alg_k & (SSL_kDHE | SSL_kECDHE | SSL_kDHEPSK | SSL_kECDHEPSK
75                  | SSL_kSRP)) {
76         return 1;
77     }
78
79     return 0;
80 }
81
82 /*
83  * ossl_statem_client_read_transition() encapsulates the logic for the allowed
84  * handshake state transitions when a TLS1.3 client is reading messages from the
85  * server. The message type that the server has sent is provided in |mt|. The
86  * current state is in |s->statem.hand_state|.
87  *
88  * Return values are 1 for success (transition allowed) and  0 on error
89  * (transition not allowed)
90  */
91 static int ossl_statem_client13_read_transition(SSL_CONNECTION *s, int mt)
92 {
93     OSSL_STATEM *st = &s->statem;
94
95     /*
96      * Note: There is no case for TLS_ST_CW_CLNT_HELLO, because we haven't
97      * yet negotiated TLSv1.3 at that point so that is handled by
98      * ossl_statem_client_read_transition()
99      */
100
101     switch (st->hand_state) {
102     default:
103         break;
104
105     case TLS_ST_CW_CLNT_HELLO:
106         /*
107          * This must a ClientHello following a HelloRetryRequest, so the only
108          * thing we can get now is a ServerHello.
109          */
110         if (mt == SSL3_MT_SERVER_HELLO) {
111             st->hand_state = TLS_ST_CR_SRVR_HELLO;
112             return 1;
113         }
114         break;
115
116     case TLS_ST_CR_SRVR_HELLO:
117         if (mt == SSL3_MT_ENCRYPTED_EXTENSIONS) {
118             st->hand_state = TLS_ST_CR_ENCRYPTED_EXTENSIONS;
119             return 1;
120         }
121         break;
122
123     case TLS_ST_CR_ENCRYPTED_EXTENSIONS:
124         if (s->hit) {
125             if (mt == SSL3_MT_FINISHED) {
126                 st->hand_state = TLS_ST_CR_FINISHED;
127                 return 1;
128             }
129         } else {
130             if (mt == SSL3_MT_CERTIFICATE_REQUEST) {
131                 st->hand_state = TLS_ST_CR_CERT_REQ;
132                 return 1;
133             }
134             if (mt == SSL3_MT_CERTIFICATE) {
135                 st->hand_state = TLS_ST_CR_CERT;
136                 return 1;
137             }
138 #ifndef OPENSSL_NO_COMP_ALG
139             if (mt == SSL3_MT_COMPRESSED_CERTIFICATE
140                     && s->ext.compress_certificate_sent) {
141                 st->hand_state = TLS_ST_CR_COMP_CERT;
142                 return 1;
143             }
144 #endif
145         }
146         break;
147
148     case TLS_ST_CR_CERT_REQ:
149         if (mt == SSL3_MT_CERTIFICATE) {
150             st->hand_state = TLS_ST_CR_CERT;
151             return 1;
152         }
153 #ifndef OPENSSL_NO_COMP_ALG
154         if (mt == SSL3_MT_COMPRESSED_CERTIFICATE
155                 && s->ext.compress_certificate_sent) {
156             st->hand_state = TLS_ST_CR_COMP_CERT;
157             return 1;
158         }
159 #endif
160         break;
161
162     case TLS_ST_CR_CERT:
163     case TLS_ST_CR_COMP_CERT:
164         if (mt == SSL3_MT_CERTIFICATE_VERIFY) {
165             st->hand_state = TLS_ST_CR_CERT_VRFY;
166             return 1;
167         }
168         break;
169
170     case TLS_ST_CR_CERT_VRFY:
171         if (mt == SSL3_MT_FINISHED) {
172             st->hand_state = TLS_ST_CR_FINISHED;
173             return 1;
174         }
175         break;
176
177     case TLS_ST_OK:
178         if (mt == SSL3_MT_NEWSESSION_TICKET) {
179             st->hand_state = TLS_ST_CR_SESSION_TICKET;
180             return 1;
181         }
182         if (mt == SSL3_MT_KEY_UPDATE) {
183             st->hand_state = TLS_ST_CR_KEY_UPDATE;
184             return 1;
185         }
186         if (mt == SSL3_MT_CERTIFICATE_REQUEST) {
187 #if DTLS_MAX_VERSION_INTERNAL != DTLS1_2_VERSION
188             /* Restore digest for PHA before adding message.*/
189 # error Internal DTLS version error
190 #endif
191             if (!SSL_CONNECTION_IS_DTLS(s)
192                 && s->post_handshake_auth == SSL_PHA_EXT_SENT) {
193                 s->post_handshake_auth = SSL_PHA_REQUESTED;
194                 /*
195                  * In TLS, this is called before the message is added to the
196                  * digest. In DTLS, this is expected to be called after adding
197                  * to the digest. Either move the digest restore, or add the
198                  * message here after the swap, or do it after the clientFinished?
199                  */
200                 if (!tls13_restore_handshake_digest_for_pha(s)) {
201                     /* SSLfatal() already called */
202                     return 0;
203                 }
204                 st->hand_state = TLS_ST_CR_CERT_REQ;
205                 return 1;
206             }
207         }
208         break;
209     }
210
211     /* No valid transition found */
212     return 0;
213 }
214
215 /*
216  * ossl_statem_client_read_transition() encapsulates the logic for the allowed
217  * handshake state transitions when the client is reading messages from the
218  * server. The message type that the server has sent is provided in |mt|. The
219  * current state is in |s->statem.hand_state|.
220  *
221  * Return values are 1 for success (transition allowed) and  0 on error
222  * (transition not allowed)
223  */
224 int ossl_statem_client_read_transition(SSL_CONNECTION *s, int mt)
225 {
226     OSSL_STATEM *st = &s->statem;
227     int ske_expected;
228
229     /*
230      * Note that after writing the first ClientHello we don't know what version
231      * we are going to negotiate yet, so we don't take this branch until later.
232      */
233     if (SSL_CONNECTION_IS_TLS13(s)) {
234         if (!ossl_statem_client13_read_transition(s, mt))
235             goto err;
236         return 1;
237     }
238
239     switch (st->hand_state) {
240     default:
241         break;
242
243     case TLS_ST_CW_CLNT_HELLO:
244         if (mt == SSL3_MT_SERVER_HELLO) {
245             st->hand_state = TLS_ST_CR_SRVR_HELLO;
246             return 1;
247         }
248
249         if (SSL_CONNECTION_IS_DTLS(s)) {
250             if (mt == DTLS1_MT_HELLO_VERIFY_REQUEST) {
251                 st->hand_state = DTLS_ST_CR_HELLO_VERIFY_REQUEST;
252                 return 1;
253             }
254         }
255         break;
256
257     case TLS_ST_EARLY_DATA:
258         /*
259          * We've not actually selected TLSv1.3 yet, but we have sent early
260          * data. The only thing allowed now is a ServerHello or a
261          * HelloRetryRequest.
262          */
263         if (mt == SSL3_MT_SERVER_HELLO) {
264             st->hand_state = TLS_ST_CR_SRVR_HELLO;
265             return 1;
266         }
267         break;
268
269     case TLS_ST_CR_SRVR_HELLO:
270         if (s->hit) {
271             if (s->ext.ticket_expected) {
272                 if (mt == SSL3_MT_NEWSESSION_TICKET) {
273                     st->hand_state = TLS_ST_CR_SESSION_TICKET;
274                     return 1;
275                 }
276             } else if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
277                 st->hand_state = TLS_ST_CR_CHANGE;
278                 return 1;
279             }
280         } else {
281             if (SSL_CONNECTION_IS_DTLS(s)
282                 && mt == DTLS1_MT_HELLO_VERIFY_REQUEST) {
283                 st->hand_state = DTLS_ST_CR_HELLO_VERIFY_REQUEST;
284                 return 1;
285             } else if (s->version >= TLS1_VERSION
286                        && s->ext.session_secret_cb != NULL
287                        && s->session->ext.tick != NULL
288                        && mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
289                 /*
290                  * Normally, we can tell if the server is resuming the session
291                  * from the session ID. EAP-FAST (RFC 4851), however, relies on
292                  * the next server message after the ServerHello to determine if
293                  * the server is resuming.
294                  */
295                 s->hit = 1;
296                 st->hand_state = TLS_ST_CR_CHANGE;
297                 return 1;
298             } else if (!(s->s3.tmp.new_cipher->algorithm_auth
299                          & (SSL_aNULL | SSL_aSRP | SSL_aPSK))) {
300                 if (mt == SSL3_MT_CERTIFICATE) {
301                     st->hand_state = TLS_ST_CR_CERT;
302                     return 1;
303                 }
304             } else {
305                 ske_expected = key_exchange_expected(s);
306                 /* SKE is optional for some PSK ciphersuites */
307                 if (ske_expected
308                     || ((s->s3.tmp.new_cipher->algorithm_mkey & SSL_PSK)
309                         && mt == SSL3_MT_SERVER_KEY_EXCHANGE)) {
310                     if (mt == SSL3_MT_SERVER_KEY_EXCHANGE) {
311                         st->hand_state = TLS_ST_CR_KEY_EXCH;
312                         return 1;
313                     }
314                 } else if (mt == SSL3_MT_CERTIFICATE_REQUEST
315                            && cert_req_allowed(s)) {
316                     st->hand_state = TLS_ST_CR_CERT_REQ;
317                     return 1;
318                 } else if (mt == SSL3_MT_SERVER_DONE) {
319                     st->hand_state = TLS_ST_CR_SRVR_DONE;
320                     return 1;
321                 }
322             }
323         }
324         break;
325
326     case TLS_ST_CR_CERT:
327     case TLS_ST_CR_COMP_CERT:
328         /*
329          * The CertificateStatus message is optional even if
330          * |ext.status_expected| is set
331          */
332         if (s->ext.status_expected && mt == SSL3_MT_CERTIFICATE_STATUS) {
333             st->hand_state = TLS_ST_CR_CERT_STATUS;
334             return 1;
335         }
336         /* Fall through */
337
338     case TLS_ST_CR_CERT_STATUS:
339         ske_expected = key_exchange_expected(s);
340         /* SKE is optional for some PSK ciphersuites */
341         if (ske_expected || ((s->s3.tmp.new_cipher->algorithm_mkey & SSL_PSK)
342                              && mt == SSL3_MT_SERVER_KEY_EXCHANGE)) {
343             if (mt == SSL3_MT_SERVER_KEY_EXCHANGE) {
344                 st->hand_state = TLS_ST_CR_KEY_EXCH;
345                 return 1;
346             }
347             goto err;
348         }
349         /* Fall through */
350
351     case TLS_ST_CR_KEY_EXCH:
352         if (mt == SSL3_MT_CERTIFICATE_REQUEST) {
353             if (cert_req_allowed(s)) {
354                 st->hand_state = TLS_ST_CR_CERT_REQ;
355                 return 1;
356             }
357             goto err;
358         }
359         /* Fall through */
360
361     case TLS_ST_CR_CERT_REQ:
362         if (mt == SSL3_MT_SERVER_DONE) {
363             st->hand_state = TLS_ST_CR_SRVR_DONE;
364             return 1;
365         }
366         break;
367
368     case TLS_ST_CW_FINISHED:
369         if (s->ext.ticket_expected) {
370             if (mt == SSL3_MT_NEWSESSION_TICKET) {
371                 st->hand_state = TLS_ST_CR_SESSION_TICKET;
372                 return 1;
373             }
374         } else if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
375             st->hand_state = TLS_ST_CR_CHANGE;
376             return 1;
377         }
378         break;
379
380     case TLS_ST_CR_SESSION_TICKET:
381         if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
382             st->hand_state = TLS_ST_CR_CHANGE;
383             return 1;
384         }
385         break;
386
387     case TLS_ST_CR_CHANGE:
388         if (mt == SSL3_MT_FINISHED) {
389             st->hand_state = TLS_ST_CR_FINISHED;
390             return 1;
391         }
392         break;
393
394     case TLS_ST_OK:
395         if (mt == SSL3_MT_HELLO_REQUEST) {
396             st->hand_state = TLS_ST_CR_HELLO_REQ;
397             return 1;
398         }
399         break;
400     }
401
402  err:
403     /* No valid transition found */
404     if (SSL_CONNECTION_IS_DTLS(s) && mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
405         BIO *rbio;
406
407         /*
408          * CCS messages don't have a message sequence number so this is probably
409          * because of an out-of-order CCS. We'll just drop it.
410          */
411         s->init_num = 0;
412         s->rwstate = SSL_READING;
413         rbio = SSL_get_rbio(SSL_CONNECTION_GET_SSL(s));
414         BIO_clear_retry_flags(rbio);
415         BIO_set_retry_read(rbio);
416         return 0;
417     }
418     SSLfatal(s, SSL3_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
419     return 0;
420 }
421
422 /*
423  * ossl_statem_client13_write_transition() works out what handshake state to
424  * move to next when the TLSv1.3 client is writing messages to be sent to the
425  * server.
426  */
427 static WRITE_TRAN ossl_statem_client13_write_transition(SSL_CONNECTION *s)
428 {
429     OSSL_STATEM *st = &s->statem;
430
431     /*
432      * Note: There are no cases for TLS_ST_BEFORE because we haven't negotiated
433      * TLSv1.3 yet at that point. They are handled by
434      * ossl_statem_client_write_transition().
435      */
436     switch (st->hand_state) {
437     default:
438         /* Shouldn't happen */
439         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
440         return WRITE_TRAN_ERROR;
441
442     case TLS_ST_CR_CERT_REQ:
443         if (s->post_handshake_auth == SSL_PHA_REQUESTED) {
444             if (s->ext.compress_certificate_from_peer[0] != TLSEXT_comp_cert_none)
445                 st->hand_state = TLS_ST_CW_COMP_CERT;
446             else
447                 st->hand_state = TLS_ST_CW_CERT;
448             return WRITE_TRAN_CONTINUE;
449         }
450         /*
451          * We should only get here if we received a CertificateRequest after
452          * we already sent close_notify
453          */
454         if (!ossl_assert((s->shutdown & SSL_SENT_SHUTDOWN) != 0)) {
455             /* Shouldn't happen - same as default case */
456             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
457             return WRITE_TRAN_ERROR;
458         }
459         st->hand_state = TLS_ST_OK;
460         return WRITE_TRAN_CONTINUE;
461
462     case TLS_ST_CR_FINISHED:
463         if (s->early_data_state == SSL_EARLY_DATA_WRITE_RETRY
464                 || s->early_data_state == SSL_EARLY_DATA_FINISHED_WRITING)
465             st->hand_state = TLS_ST_PENDING_EARLY_DATA_END;
466         else if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0
467                  && s->hello_retry_request == SSL_HRR_NONE)
468             st->hand_state = TLS_ST_CW_CHANGE;
469         else if (s->s3.tmp.cert_req == 0)
470             st->hand_state = TLS_ST_CW_FINISHED;
471         else if (s->ext.compress_certificate_from_peer[0] != TLSEXT_comp_cert_none)
472             st->hand_state = TLS_ST_CW_COMP_CERT;
473         else
474             st->hand_state = TLS_ST_CW_CERT;
475         return WRITE_TRAN_CONTINUE;
476
477     case TLS_ST_PENDING_EARLY_DATA_END:
478         if (s->ext.early_data == SSL_EARLY_DATA_ACCEPTED) {
479             st->hand_state = TLS_ST_CW_END_OF_EARLY_DATA;
480             return WRITE_TRAN_CONTINUE;
481         }
482         /* Fall through */
483
484     case TLS_ST_CW_END_OF_EARLY_DATA:
485     case TLS_ST_CW_CHANGE:
486         if (s->s3.tmp.cert_req == 0)
487             st->hand_state = TLS_ST_CW_FINISHED;
488         else if (s->ext.compress_certificate_from_peer[0] != TLSEXT_comp_cert_none)
489             st->hand_state = TLS_ST_CW_COMP_CERT;
490         else
491             st->hand_state = TLS_ST_CW_CERT;
492         return WRITE_TRAN_CONTINUE;
493
494     case TLS_ST_CW_COMP_CERT:
495     case TLS_ST_CW_CERT:
496         /* If a non-empty Certificate we also send CertificateVerify */
497         st->hand_state = (s->s3.tmp.cert_req == 1) ? TLS_ST_CW_CERT_VRFY
498                                                     : TLS_ST_CW_FINISHED;
499         return WRITE_TRAN_CONTINUE;
500
501     case TLS_ST_CW_CERT_VRFY:
502         st->hand_state = TLS_ST_CW_FINISHED;
503         return WRITE_TRAN_CONTINUE;
504
505     case TLS_ST_CR_KEY_UPDATE:
506     case TLS_ST_CW_KEY_UPDATE:
507     case TLS_ST_CR_SESSION_TICKET:
508     case TLS_ST_CW_FINISHED:
509         st->hand_state = TLS_ST_OK;
510         return WRITE_TRAN_CONTINUE;
511
512     case TLS_ST_OK:
513         if (s->key_update != SSL_KEY_UPDATE_NONE) {
514             st->hand_state = TLS_ST_CW_KEY_UPDATE;
515             return WRITE_TRAN_CONTINUE;
516         }
517
518         /* Try to read from the server instead */
519         return WRITE_TRAN_FINISHED;
520     }
521 }
522
523 /*
524  * ossl_statem_client_write_transition() works out what handshake state to
525  * move to next when the client is writing messages to be sent to the server.
526  */
527 WRITE_TRAN ossl_statem_client_write_transition(SSL_CONNECTION *s)
528 {
529     OSSL_STATEM *st = &s->statem;
530
531     /*
532      * Note that immediately before/after a ClientHello we don't know what
533      * version we are going to negotiate yet, so we don't take this branch until
534      * later
535      */
536     if (SSL_CONNECTION_IS_TLS13(s))
537         return ossl_statem_client13_write_transition(s);
538
539     switch (st->hand_state) {
540     default:
541         /* Shouldn't happen */
542         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
543         return WRITE_TRAN_ERROR;
544
545     case TLS_ST_OK:
546         if (!s->renegotiate) {
547             /*
548              * We haven't requested a renegotiation ourselves so we must have
549              * received a message from the server. Better read it.
550              */
551             return WRITE_TRAN_FINISHED;
552         }
553         /* Renegotiation */
554         /* fall thru */
555     case TLS_ST_BEFORE:
556         st->hand_state = TLS_ST_CW_CLNT_HELLO;
557         return WRITE_TRAN_CONTINUE;
558
559     case TLS_ST_CW_CLNT_HELLO:
560         if (s->early_data_state == SSL_EARLY_DATA_CONNECTING) {
561             /*
562              * We are assuming this is a TLSv1.3 connection, although we haven't
563              * actually selected a version yet.
564              */
565             if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0)
566                 st->hand_state = TLS_ST_CW_CHANGE;
567             else
568                 st->hand_state = TLS_ST_EARLY_DATA;
569             return WRITE_TRAN_CONTINUE;
570         }
571         /*
572          * No transition at the end of writing because we don't know what
573          * we will be sent
574          */
575         return WRITE_TRAN_FINISHED;
576
577     case TLS_ST_CR_SRVR_HELLO:
578         /*
579          * We only get here in TLSv1.3. We just received an HRR, so issue a
580          * CCS unless middlebox compat mode is off, or we already issued one
581          * because we did early data.
582          */
583         if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0
584                 && s->early_data_state != SSL_EARLY_DATA_FINISHED_WRITING)
585             st->hand_state = TLS_ST_CW_CHANGE;
586         else
587             st->hand_state = TLS_ST_CW_CLNT_HELLO;
588         return WRITE_TRAN_CONTINUE;
589
590     case TLS_ST_EARLY_DATA:
591         return WRITE_TRAN_FINISHED;
592
593     case DTLS_ST_CR_HELLO_VERIFY_REQUEST:
594         st->hand_state = TLS_ST_CW_CLNT_HELLO;
595         return WRITE_TRAN_CONTINUE;
596
597     case TLS_ST_CR_SRVR_DONE:
598         if (s->s3.tmp.cert_req)
599             st->hand_state = TLS_ST_CW_CERT;
600         else
601             st->hand_state = TLS_ST_CW_KEY_EXCH;
602         return WRITE_TRAN_CONTINUE;
603
604     case TLS_ST_CW_CERT:
605         st->hand_state = TLS_ST_CW_KEY_EXCH;
606         return WRITE_TRAN_CONTINUE;
607
608     case TLS_ST_CW_KEY_EXCH:
609         /*
610          * For TLS, cert_req is set to 2, so a cert chain of nothing is
611          * sent, but no verify packet is sent
612          */
613         /*
614          * XXX: For now, we do not support client authentication in ECDH
615          * cipher suites with ECDH (rather than ECDSA) certificates. We
616          * need to skip the certificate verify message when client's
617          * ECDH public key is sent inside the client certificate.
618          */
619         if (s->s3.tmp.cert_req == 1) {
620             st->hand_state = TLS_ST_CW_CERT_VRFY;
621         } else {
622             st->hand_state = TLS_ST_CW_CHANGE;
623         }
624         if (s->s3.flags & TLS1_FLAGS_SKIP_CERT_VERIFY) {
625             st->hand_state = TLS_ST_CW_CHANGE;
626         }
627         return WRITE_TRAN_CONTINUE;
628
629     case TLS_ST_CW_CERT_VRFY:
630         st->hand_state = TLS_ST_CW_CHANGE;
631         return WRITE_TRAN_CONTINUE;
632
633     case TLS_ST_CW_CHANGE:
634         if (s->hello_retry_request == SSL_HRR_PENDING) {
635             st->hand_state = TLS_ST_CW_CLNT_HELLO;
636         } else if (s->early_data_state == SSL_EARLY_DATA_CONNECTING) {
637             st->hand_state = TLS_ST_EARLY_DATA;
638         } else {
639 #if defined(OPENSSL_NO_NEXTPROTONEG)
640             st->hand_state = TLS_ST_CW_FINISHED;
641 #else
642             if (!SSL_CONNECTION_IS_DTLS(s) && s->s3.npn_seen)
643                 st->hand_state = TLS_ST_CW_NEXT_PROTO;
644             else
645                 st->hand_state = TLS_ST_CW_FINISHED;
646 #endif
647         }
648         return WRITE_TRAN_CONTINUE;
649
650 #if !defined(OPENSSL_NO_NEXTPROTONEG)
651     case TLS_ST_CW_NEXT_PROTO:
652         st->hand_state = TLS_ST_CW_FINISHED;
653         return WRITE_TRAN_CONTINUE;
654 #endif
655
656     case TLS_ST_CW_FINISHED:
657         if (s->hit) {
658             st->hand_state = TLS_ST_OK;
659             return WRITE_TRAN_CONTINUE;
660         } else {
661             return WRITE_TRAN_FINISHED;
662         }
663
664     case TLS_ST_CR_FINISHED:
665         if (s->hit) {
666             st->hand_state = TLS_ST_CW_CHANGE;
667             return WRITE_TRAN_CONTINUE;
668         } else {
669             st->hand_state = TLS_ST_OK;
670             return WRITE_TRAN_CONTINUE;
671         }
672
673     case TLS_ST_CR_HELLO_REQ:
674         /*
675          * If we can renegotiate now then do so, otherwise wait for a more
676          * convenient time.
677          */
678         if (ssl3_renegotiate_check(SSL_CONNECTION_GET_SSL(s), 1)) {
679             if (!tls_setup_handshake(s)) {
680                 /* SSLfatal() already called */
681                 return WRITE_TRAN_ERROR;
682             }
683             st->hand_state = TLS_ST_CW_CLNT_HELLO;
684             return WRITE_TRAN_CONTINUE;
685         }
686         st->hand_state = TLS_ST_OK;
687         return WRITE_TRAN_CONTINUE;
688     }
689 }
690
691 /*
692  * Perform any pre work that needs to be done prior to sending a message from
693  * the client to the server.
694  */
695 WORK_STATE ossl_statem_client_pre_work(SSL_CONNECTION *s, WORK_STATE wst)
696 {
697     OSSL_STATEM *st = &s->statem;
698
699     switch (st->hand_state) {
700     default:
701         /* No pre work to be done */
702         break;
703
704     case TLS_ST_CW_CLNT_HELLO:
705         s->shutdown = 0;
706         if (SSL_CONNECTION_IS_DTLS(s)) {
707             /* every DTLS ClientHello resets Finished MAC */
708             if (!ssl3_init_finished_mac(s)) {
709                 /* SSLfatal() already called */
710                 return WORK_ERROR;
711             }
712         } else if (s->ext.early_data == SSL_EARLY_DATA_REJECTED) {
713             /*
714              * This must be a second ClientHello after an HRR following an
715              * earlier rejected attempt to send early data. Since we were
716              * previously encrypting the early data we now need to reset the
717              * write record layer in order to write in plaintext again.
718              */
719             if (!ssl_set_new_record_layer(s,
720                                           TLS_ANY_VERSION,
721                                           OSSL_RECORD_DIRECTION_WRITE,
722                                           OSSL_RECORD_PROTECTION_LEVEL_NONE,
723                                           NULL, 0, NULL, 0, NULL,  0, NULL, 0,
724                                           NID_undef, NULL, NULL)) {
725                 /* SSLfatal already called */
726                 return WORK_ERROR;
727             }
728         }
729         break;
730
731     case TLS_ST_CW_CHANGE:
732         if (SSL_CONNECTION_IS_DTLS(s)) {
733             if (s->hit) {
734                 /*
735                  * We're into the last flight so we don't retransmit these
736                  * messages unless we need to.
737                  */
738                 st->use_timer = 0;
739             }
740 #ifndef OPENSSL_NO_SCTP
741             if (BIO_dgram_is_sctp(SSL_get_wbio(SSL_CONNECTION_GET_SSL(s)))) {
742                 /* Calls SSLfatal() as required */
743                 return dtls_wait_for_dry(s);
744             }
745 #endif
746         }
747         break;
748
749     case TLS_ST_PENDING_EARLY_DATA_END:
750         /*
751          * If we've been called by SSL_do_handshake()/SSL_write(), or we did not
752          * attempt to write early data before calling SSL_read() then we press
753          * on with the handshake. Otherwise we pause here.
754          */
755         if (s->early_data_state == SSL_EARLY_DATA_FINISHED_WRITING
756                 || s->early_data_state == SSL_EARLY_DATA_NONE)
757             return WORK_FINISHED_CONTINUE;
758         /* Fall through */
759
760     case TLS_ST_EARLY_DATA:
761         return tls_finish_handshake(s, wst, 0, 1);
762
763     case TLS_ST_OK:
764         /* Calls SSLfatal() as required */
765         return tls_finish_handshake(s, wst, 1, 1);
766     }
767
768     return WORK_FINISHED_CONTINUE;
769 }
770
771 /*
772  * Perform any work that needs to be done after sending a message from the
773  * client to the server.
774  */
775 WORK_STATE ossl_statem_client_post_work(SSL_CONNECTION *s, WORK_STATE wst)
776 {
777     OSSL_STATEM *st = &s->statem;
778     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
779
780     s->init_num = 0;
781
782     switch (st->hand_state) {
783     default:
784         /* No post work to be done */
785         break;
786
787     case TLS_ST_CW_CLNT_HELLO:
788         if (s->early_data_state == SSL_EARLY_DATA_CONNECTING
789                 && s->max_early_data > 0) {
790             /*
791              * We haven't selected TLSv1.3 yet so we don't call the change
792              * cipher state function associated with the SSL_METHOD. Instead
793              * we call tls13_change_cipher_state() directly.
794              */
795             if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) == 0) {
796                 if (!tls13_change_cipher_state(s,
797                             SSL3_CC_EARLY | SSL3_CHANGE_CIPHER_CLIENT_WRITE)) {
798                     /* SSLfatal() already called */
799                     return WORK_ERROR;
800                 }
801             }
802             /* else we're in compat mode so we delay flushing until after CCS */
803         } else if (!statem_flush(s)) {
804             return WORK_MORE_A;
805         }
806
807         if (SSL_CONNECTION_IS_DTLS(s)) {
808             /* Treat the next message as the first packet */
809             s->first_packet = 1;
810         }
811         break;
812
813     case TLS_ST_CW_KEY_EXCH:
814         if (tls_client_key_exchange_post_work(s) == 0) {
815             /* SSLfatal() already called */
816             return WORK_ERROR;
817         }
818         break;
819
820     case TLS_ST_CW_CHANGE:
821         if (SSL_CONNECTION_IS_TLS13(s)
822             || s->hello_retry_request == SSL_HRR_PENDING)
823             break;
824         if (s->early_data_state == SSL_EARLY_DATA_CONNECTING
825                     && s->max_early_data > 0) {
826             /*
827              * We haven't selected TLSv1.3 yet so we don't call the change
828              * cipher state function associated with the SSL_METHOD. Instead
829              * we call tls13_change_cipher_state() directly.
830              */
831             if (!tls13_change_cipher_state(s,
832                         SSL3_CC_EARLY | SSL3_CHANGE_CIPHER_CLIENT_WRITE))
833                 return WORK_ERROR;
834             break;
835         }
836         s->session->cipher = s->s3.tmp.new_cipher;
837 #ifdef OPENSSL_NO_COMP
838         s->session->compress_meth = 0;
839 #else
840         if (s->s3.tmp.new_compression == NULL)
841             s->session->compress_meth = 0;
842         else
843             s->session->compress_meth = s->s3.tmp.new_compression->id;
844 #endif
845         if (!ssl->method->ssl3_enc->setup_key_block(s)) {
846             /* SSLfatal() already called */
847             return WORK_ERROR;
848         }
849
850         if (!ssl->method->ssl3_enc->change_cipher_state(s,
851                                           SSL3_CHANGE_CIPHER_CLIENT_WRITE)) {
852             /* SSLfatal() already called */
853             return WORK_ERROR;
854         }
855
856         if (SSL_CONNECTION_IS_DTLS(s)) {
857 #ifndef OPENSSL_NO_SCTP
858             if (s->hit) {
859                 /*
860                  * Change to new shared key of SCTP-Auth, will be ignored if
861                  * no SCTP used.
862                  */
863                 BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
864                          0, NULL);
865             }
866 #endif
867
868             dtls1_increment_epoch(s, SSL3_CC_WRITE);
869         }
870         break;
871
872     case TLS_ST_CW_FINISHED:
873 #ifndef OPENSSL_NO_SCTP
874         if (wst == WORK_MORE_A && SSL_CONNECTION_IS_DTLS(s) && s->hit == 0) {
875             /*
876              * Change to new shared key of SCTP-Auth, will be ignored if
877              * no SCTP used.
878              */
879             BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
880                      0, NULL);
881         }
882 #endif
883         if (statem_flush(s) != 1)
884             return WORK_MORE_B;
885
886         if (SSL_CONNECTION_IS_TLS13(s)) {
887             if (!tls13_save_handshake_digest_for_pha(s)) {
888                 /* SSLfatal() already called */
889                 return WORK_ERROR;
890             }
891             if (s->post_handshake_auth != SSL_PHA_REQUESTED) {
892                 if (!ssl->method->ssl3_enc->change_cipher_state(s,
893                         SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_WRITE)) {
894                     /* SSLfatal() already called */
895                     return WORK_ERROR;
896                 }
897             }
898         }
899         break;
900
901     case TLS_ST_CW_KEY_UPDATE:
902         if (statem_flush(s) != 1)
903             return WORK_MORE_A;
904         if (!tls13_update_key(s, 1)) {
905             /* SSLfatal() already called */
906             return WORK_ERROR;
907         }
908         break;
909     }
910
911     return WORK_FINISHED_CONTINUE;
912 }
913
914 /*
915  * Get the message construction function and message type for sending from the
916  * client
917  *
918  * Valid return values are:
919  *   1: Success
920  *   0: Error
921  */
922 int ossl_statem_client_construct_message(SSL_CONNECTION *s,
923                                          confunc_f *confunc, int *mt)
924 {
925     OSSL_STATEM *st = &s->statem;
926
927     switch (st->hand_state) {
928     default:
929         /* Shouldn't happen */
930         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_HANDSHAKE_STATE);
931         return 0;
932
933     case TLS_ST_CW_CHANGE:
934         if (SSL_CONNECTION_IS_DTLS(s))
935             *confunc = dtls_construct_change_cipher_spec;
936         else
937             *confunc = tls_construct_change_cipher_spec;
938         *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
939         break;
940
941     case TLS_ST_CW_CLNT_HELLO:
942         *confunc = tls_construct_client_hello;
943         *mt = SSL3_MT_CLIENT_HELLO;
944         break;
945
946     case TLS_ST_CW_END_OF_EARLY_DATA:
947         *confunc = tls_construct_end_of_early_data;
948         *mt = SSL3_MT_END_OF_EARLY_DATA;
949         break;
950
951     case TLS_ST_PENDING_EARLY_DATA_END:
952         *confunc = NULL;
953         *mt = SSL3_MT_DUMMY;
954         break;
955
956     case TLS_ST_CW_CERT:
957         *confunc = tls_construct_client_certificate;
958         *mt = SSL3_MT_CERTIFICATE;
959         break;
960
961 #ifndef OPENSSL_NO_COMP_ALG
962     case TLS_ST_CW_COMP_CERT:
963         *confunc = tls_construct_client_compressed_certificate;
964         *mt = SSL3_MT_COMPRESSED_CERTIFICATE;
965         break;
966 #endif
967
968     case TLS_ST_CW_KEY_EXCH:
969         *confunc = tls_construct_client_key_exchange;
970         *mt = SSL3_MT_CLIENT_KEY_EXCHANGE;
971         break;
972
973     case TLS_ST_CW_CERT_VRFY:
974         *confunc = tls_construct_cert_verify;
975         *mt = SSL3_MT_CERTIFICATE_VERIFY;
976         break;
977
978 #if !defined(OPENSSL_NO_NEXTPROTONEG)
979     case TLS_ST_CW_NEXT_PROTO:
980         *confunc = tls_construct_next_proto;
981         *mt = SSL3_MT_NEXT_PROTO;
982         break;
983 #endif
984     case TLS_ST_CW_FINISHED:
985         *confunc = tls_construct_finished;
986         *mt = SSL3_MT_FINISHED;
987         break;
988
989     case TLS_ST_CW_KEY_UPDATE:
990         *confunc = tls_construct_key_update;
991         *mt = SSL3_MT_KEY_UPDATE;
992         break;
993     }
994
995     return 1;
996 }
997
998 /*
999  * Returns the maximum allowed length for the current message that we are
1000  * reading. Excludes the message header.
1001  */
1002 size_t ossl_statem_client_max_message_size(SSL_CONNECTION *s)
1003 {
1004     OSSL_STATEM *st = &s->statem;
1005
1006     switch (st->hand_state) {
1007     default:
1008         /* Shouldn't happen */
1009         return 0;
1010
1011     case TLS_ST_CR_SRVR_HELLO:
1012         return SERVER_HELLO_MAX_LENGTH;
1013
1014     case DTLS_ST_CR_HELLO_VERIFY_REQUEST:
1015         return HELLO_VERIFY_REQUEST_MAX_LENGTH;
1016
1017     case TLS_ST_CR_COMP_CERT:
1018     case TLS_ST_CR_CERT:
1019         return s->max_cert_list;
1020
1021     case TLS_ST_CR_CERT_VRFY:
1022         return SSL3_RT_MAX_PLAIN_LENGTH;
1023
1024     case TLS_ST_CR_CERT_STATUS:
1025         return SSL3_RT_MAX_PLAIN_LENGTH;
1026
1027     case TLS_ST_CR_KEY_EXCH:
1028         return SERVER_KEY_EXCH_MAX_LENGTH;
1029
1030     case TLS_ST_CR_CERT_REQ:
1031         /*
1032          * Set to s->max_cert_list for compatibility with previous releases. In
1033          * practice these messages can get quite long if servers are configured
1034          * to provide a long list of acceptable CAs
1035          */
1036         return s->max_cert_list;
1037
1038     case TLS_ST_CR_SRVR_DONE:
1039         return SERVER_HELLO_DONE_MAX_LENGTH;
1040
1041     case TLS_ST_CR_CHANGE:
1042         if (s->version == DTLS1_BAD_VER)
1043             return 3;
1044         return CCS_MAX_LENGTH;
1045
1046     case TLS_ST_CR_SESSION_TICKET:
1047         return (SSL_CONNECTION_IS_TLS13(s)) ? SESSION_TICKET_MAX_LENGTH_TLS13
1048                                             : SESSION_TICKET_MAX_LENGTH_TLS12;
1049
1050     case TLS_ST_CR_FINISHED:
1051         return FINISHED_MAX_LENGTH;
1052
1053     case TLS_ST_CR_ENCRYPTED_EXTENSIONS:
1054         return ENCRYPTED_EXTENSIONS_MAX_LENGTH;
1055
1056     case TLS_ST_CR_KEY_UPDATE:
1057         return KEY_UPDATE_MAX_LENGTH;
1058     }
1059 }
1060
1061 /*
1062  * Process a message that the client has received from the server.
1063  */
1064 MSG_PROCESS_RETURN ossl_statem_client_process_message(SSL_CONNECTION *s,
1065                                                       PACKET *pkt)
1066 {
1067     OSSL_STATEM *st = &s->statem;
1068
1069     switch (st->hand_state) {
1070     default:
1071         /* Shouldn't happen */
1072         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1073         return MSG_PROCESS_ERROR;
1074
1075     case TLS_ST_CR_SRVR_HELLO:
1076         return tls_process_server_hello(s, pkt);
1077
1078     case DTLS_ST_CR_HELLO_VERIFY_REQUEST:
1079         return dtls_process_hello_verify(s, pkt);
1080
1081     case TLS_ST_CR_CERT:
1082         return tls_process_server_certificate(s, pkt);
1083
1084 #ifndef OPENSSL_NO_COMP_ALG
1085     case TLS_ST_CR_COMP_CERT:
1086         return tls_process_server_compressed_certificate(s, pkt);
1087 #endif
1088
1089     case TLS_ST_CR_CERT_VRFY:
1090         return tls_process_cert_verify(s, pkt);
1091
1092     case TLS_ST_CR_CERT_STATUS:
1093         return tls_process_cert_status(s, pkt);
1094
1095     case TLS_ST_CR_KEY_EXCH:
1096         return tls_process_key_exchange(s, pkt);
1097
1098     case TLS_ST_CR_CERT_REQ:
1099         return tls_process_certificate_request(s, pkt);
1100
1101     case TLS_ST_CR_SRVR_DONE:
1102         return tls_process_server_done(s, pkt);
1103
1104     case TLS_ST_CR_CHANGE:
1105         return tls_process_change_cipher_spec(s, pkt);
1106
1107     case TLS_ST_CR_SESSION_TICKET:
1108         return tls_process_new_session_ticket(s, pkt);
1109
1110     case TLS_ST_CR_FINISHED:
1111         return tls_process_finished(s, pkt);
1112
1113     case TLS_ST_CR_HELLO_REQ:
1114         return tls_process_hello_req(s, pkt);
1115
1116     case TLS_ST_CR_ENCRYPTED_EXTENSIONS:
1117         return tls_process_encrypted_extensions(s, pkt);
1118
1119     case TLS_ST_CR_KEY_UPDATE:
1120         return tls_process_key_update(s, pkt);
1121     }
1122 }
1123
1124 /*
1125  * Perform any further processing required following the receipt of a message
1126  * from the server
1127  */
1128 WORK_STATE ossl_statem_client_post_process_message(SSL_CONNECTION *s,
1129                                                    WORK_STATE wst)
1130 {
1131     OSSL_STATEM *st = &s->statem;
1132
1133     switch (st->hand_state) {
1134     default:
1135         /* Shouldn't happen */
1136         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1137         return WORK_ERROR;
1138
1139     case TLS_ST_CR_CERT:
1140     case TLS_ST_CR_COMP_CERT:
1141         return tls_post_process_server_certificate(s, wst);
1142
1143     case TLS_ST_CR_CERT_VRFY:
1144     case TLS_ST_CR_CERT_REQ:
1145         return tls_prepare_client_certificate(s, wst);
1146     }
1147 }
1148
1149 CON_FUNC_RETURN tls_construct_client_hello(SSL_CONNECTION *s, WPACKET *pkt)
1150 {
1151     unsigned char *p;
1152     size_t sess_id_len;
1153     int i, protverr;
1154 #ifndef OPENSSL_NO_COMP
1155     SSL_COMP *comp;
1156 #endif
1157     SSL_SESSION *sess = s->session;
1158     unsigned char *session_id;
1159     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1160
1161     /* Work out what SSL/TLS/DTLS version to use */
1162     protverr = ssl_set_client_hello_version(s);
1163     if (protverr != 0) {
1164         SSLfatal(s, SSL_AD_INTERNAL_ERROR, protverr);
1165         return CON_FUNC_ERROR;
1166     }
1167
1168     if (sess == NULL
1169             || !ssl_version_supported(s, sess->ssl_version, NULL)
1170             || !SSL_SESSION_is_resumable(sess)) {
1171         if (s->hello_retry_request == SSL_HRR_NONE
1172                 && !ssl_get_new_session(s, 0)) {
1173             /* SSLfatal() already called */
1174             return CON_FUNC_ERROR;
1175         }
1176     }
1177     /* else use the pre-loaded session */
1178
1179     p = s->s3.client_random;
1180
1181     /*
1182      * for DTLS if client_random is initialized, reuse it, we are
1183      * required to use same upon reply to HelloVerify
1184      */
1185     if (SSL_CONNECTION_IS_DTLS(s)) {
1186         size_t idx;
1187         i = 1;
1188         for (idx = 0; idx < sizeof(s->s3.client_random); idx++) {
1189             if (p[idx]) {
1190                 i = 0;
1191                 break;
1192             }
1193         }
1194     } else {
1195         i = (s->hello_retry_request == SSL_HRR_NONE);
1196     }
1197
1198     if (i && ssl_fill_hello_random(s, 0, p, sizeof(s->s3.client_random),
1199                                    DOWNGRADE_NONE) <= 0) {
1200         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1201         return CON_FUNC_ERROR;
1202     }
1203
1204     /*-
1205      * version indicates the negotiated version: for example from
1206      * an SSLv2/v3 compatible client hello). The client_version
1207      * field is the maximum version we permit and it is also
1208      * used in RSA encrypted premaster secrets. Some servers can
1209      * choke if we initially report a higher version then
1210      * renegotiate to a lower one in the premaster secret. This
1211      * didn't happen with TLS 1.0 as most servers supported it
1212      * but it can with TLS 1.1 or later if the server only supports
1213      * 1.0.
1214      *
1215      * Possible scenario with previous logic:
1216      *      1. Client hello indicates TLS 1.2
1217      *      2. Server hello says TLS 1.0
1218      *      3. RSA encrypted premaster secret uses 1.2.
1219      *      4. Handshake proceeds using TLS 1.0.
1220      *      5. Server sends hello request to renegotiate.
1221      *      6. Client hello indicates TLS v1.0 as we now
1222      *         know that is maximum server supports.
1223      *      7. Server chokes on RSA encrypted premaster secret
1224      *         containing version 1.0.
1225      *
1226      * For interoperability it should be OK to always use the
1227      * maximum version we support in client hello and then rely
1228      * on the checking of version to ensure the servers isn't
1229      * being inconsistent: for example initially negotiating with
1230      * TLS 1.0 and renegotiating with TLS 1.2. We do this by using
1231      * client_version in client hello and not resetting it to
1232      * the negotiated version.
1233      *
1234      * For TLS 1.3 we always set the ClientHello version to 1.2 and rely on the
1235      * supported_versions extension for the real supported versions.
1236      */
1237     if (!WPACKET_put_bytes_u16(pkt, s->client_version)
1238             || !WPACKET_memcpy(pkt, s->s3.client_random, SSL3_RANDOM_SIZE)) {
1239         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1240         return CON_FUNC_ERROR;
1241     }
1242
1243     /* Session ID */
1244     session_id = s->session->session_id;
1245     if (s->new_session || s->session->ssl_version == TLS1_3_VERSION) {
1246         if (s->version == TLS1_3_VERSION
1247                 && (s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0) {
1248             sess_id_len = sizeof(s->tmp_session_id);
1249             s->tmp_session_id_len = sess_id_len;
1250             session_id = s->tmp_session_id;
1251             if (s->hello_retry_request == SSL_HRR_NONE
1252                     && RAND_bytes_ex(sctx->libctx, s->tmp_session_id,
1253                                      sess_id_len, 0) <= 0) {
1254                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1255                 return CON_FUNC_ERROR;
1256             }
1257         } else {
1258             sess_id_len = 0;
1259         }
1260     } else {
1261         assert(s->session->session_id_length <= sizeof(s->session->session_id));
1262         sess_id_len = s->session->session_id_length;
1263         if (s->version == TLS1_3_VERSION) {
1264             s->tmp_session_id_len = sess_id_len;
1265             memcpy(s->tmp_session_id, s->session->session_id, sess_id_len);
1266         }
1267     }
1268     if (!WPACKET_start_sub_packet_u8(pkt)
1269             || (sess_id_len != 0 && !WPACKET_memcpy(pkt, session_id,
1270                                                     sess_id_len))
1271             || !WPACKET_close(pkt)) {
1272         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1273         return CON_FUNC_ERROR;
1274     }
1275
1276     /* cookie stuff for DTLS */
1277     if (SSL_CONNECTION_IS_DTLS(s)) {
1278         if (s->d1->cookie_len > sizeof(s->d1->cookie)
1279                 || !WPACKET_sub_memcpy_u8(pkt, s->d1->cookie,
1280                                           s->d1->cookie_len)) {
1281             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1282             return CON_FUNC_ERROR;
1283         }
1284     }
1285
1286     /* Ciphers supported */
1287     if (!WPACKET_start_sub_packet_u16(pkt)) {
1288         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1289         return CON_FUNC_ERROR;
1290     }
1291
1292     if (!ssl_cipher_list_to_bytes(s, SSL_get_ciphers(SSL_CONNECTION_GET_SSL(s)),
1293                                   pkt)) {
1294         /* SSLfatal() already called */
1295         return CON_FUNC_ERROR;
1296     }
1297     if (!WPACKET_close(pkt)) {
1298         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1299         return CON_FUNC_ERROR;
1300     }
1301
1302     /* COMPRESSION */
1303     if (!WPACKET_start_sub_packet_u8(pkt)) {
1304         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1305         return CON_FUNC_ERROR;
1306     }
1307 #ifndef OPENSSL_NO_COMP
1308     if (ssl_allow_compression(s)
1309             && sctx->comp_methods
1310             && (SSL_CONNECTION_IS_DTLS(s)
1311                 || s->s3.tmp.max_ver < TLS1_3_VERSION)) {
1312         int compnum = sk_SSL_COMP_num(sctx->comp_methods);
1313         for (i = 0; i < compnum; i++) {
1314             comp = sk_SSL_COMP_value(sctx->comp_methods, i);
1315             if (!WPACKET_put_bytes_u8(pkt, comp->id)) {
1316                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1317                 return CON_FUNC_ERROR;
1318             }
1319         }
1320     }
1321 #endif
1322     /* Add the NULL method */
1323     if (!WPACKET_put_bytes_u8(pkt, 0) || !WPACKET_close(pkt)) {
1324         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1325         return CON_FUNC_ERROR;
1326     }
1327
1328     /* TLS extensions */
1329     if (!tls_construct_extensions(s, pkt, SSL_EXT_CLIENT_HELLO, NULL, 0)) {
1330         /* SSLfatal() already called */
1331         return CON_FUNC_ERROR;
1332     }
1333
1334     return CON_FUNC_SUCCESS;
1335 }
1336
1337 MSG_PROCESS_RETURN dtls_process_hello_verify(SSL_CONNECTION *s, PACKET *pkt)
1338 {
1339     size_t cookie_len;
1340     PACKET cookiepkt;
1341
1342     if (!PACKET_forward(pkt, 2)
1343         || !PACKET_get_length_prefixed_1(pkt, &cookiepkt)) {
1344         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1345         return MSG_PROCESS_ERROR;
1346     }
1347
1348     cookie_len = PACKET_remaining(&cookiepkt);
1349     if (cookie_len > sizeof(s->d1->cookie)) {
1350         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_LENGTH_TOO_LONG);
1351         return MSG_PROCESS_ERROR;
1352     }
1353
1354     if (!PACKET_copy_bytes(&cookiepkt, s->d1->cookie, cookie_len)) {
1355         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1356         return MSG_PROCESS_ERROR;
1357     }
1358     s->d1->cookie_len = cookie_len;
1359
1360     return MSG_PROCESS_FINISHED_READING;
1361 }
1362
1363 static int set_client_ciphersuite(SSL_CONNECTION *s,
1364                                   const unsigned char *cipherchars)
1365 {
1366     STACK_OF(SSL_CIPHER) *sk;
1367     const SSL_CIPHER *c;
1368     int i;
1369     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1370
1371     c = ssl_get_cipher_by_char(s, cipherchars, 0);
1372     if (c == NULL) {
1373         /* unknown cipher */
1374         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_CIPHER_RETURNED);
1375         return 0;
1376     }
1377     /*
1378      * If it is a disabled cipher we either didn't send it in client hello,
1379      * or it's not allowed for the selected protocol. So we return an error.
1380      */
1381     if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_CHECK, 1)) {
1382         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_CIPHER_RETURNED);
1383         return 0;
1384     }
1385
1386     sk = ssl_get_ciphers_by_id(s);
1387     i = sk_SSL_CIPHER_find(sk, c);
1388     if (i < 0) {
1389         /* we did not say we would use this cipher */
1390         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_CIPHER_RETURNED);
1391         return 0;
1392     }
1393
1394     if (SSL_CONNECTION_IS_TLS13(s) && s->s3.tmp.new_cipher != NULL
1395             && s->s3.tmp.new_cipher->id != c->id) {
1396         /* ServerHello selected a different ciphersuite to that in the HRR */
1397         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_CIPHER_RETURNED);
1398         return 0;
1399     }
1400
1401     /*
1402      * Depending on the session caching (internal/external), the cipher
1403      * and/or cipher_id values may not be set. Make sure that cipher_id is
1404      * set and use it for comparison.
1405      */
1406     if (s->session->cipher != NULL)
1407         s->session->cipher_id = s->session->cipher->id;
1408     if (s->hit && (s->session->cipher_id != c->id)) {
1409         if (SSL_CONNECTION_IS_TLS13(s)) {
1410             const EVP_MD *md = ssl_md(sctx, c->algorithm2);
1411
1412             /*
1413              * In TLSv1.3 it is valid for the server to select a different
1414              * ciphersuite as long as the hash is the same.
1415              */
1416             if (md == NULL
1417                     || md != ssl_md(sctx, s->session->cipher->algorithm2)) {
1418                 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1419                          SSL_R_CIPHERSUITE_DIGEST_HAS_CHANGED);
1420                 return 0;
1421             }
1422         } else {
1423             /*
1424              * Prior to TLSv1.3 resuming a session always meant using the same
1425              * ciphersuite.
1426              */
1427             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1428                      SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
1429             return 0;
1430         }
1431     }
1432     s->s3.tmp.new_cipher = c;
1433
1434     return 1;
1435 }
1436
1437 MSG_PROCESS_RETURN tls_process_server_hello(SSL_CONNECTION *s, PACKET *pkt)
1438 {
1439     PACKET session_id, extpkt;
1440     size_t session_id_len;
1441     const unsigned char *cipherchars;
1442     int hrr = 0;
1443     unsigned int compression;
1444     unsigned int sversion;
1445     unsigned int context;
1446     RAW_EXTENSION *extensions = NULL;
1447     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1448 #ifndef OPENSSL_NO_COMP
1449     SSL_COMP *comp;
1450 #endif
1451
1452     if (!PACKET_get_net_2(pkt, &sversion)) {
1453         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1454         goto err;
1455     }
1456
1457     /* load the server random */
1458     if (s->version == TLS1_3_VERSION
1459             && sversion == TLS1_2_VERSION
1460             && PACKET_remaining(pkt) >= SSL3_RANDOM_SIZE
1461             && memcmp(hrrrandom, PACKET_data(pkt), SSL3_RANDOM_SIZE) == 0) {
1462         if (s->hello_retry_request != SSL_HRR_NONE) {
1463             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
1464             goto err;
1465         }
1466         s->hello_retry_request = SSL_HRR_PENDING;
1467         /* Tell the record layer that we know we're going to get TLSv1.3 */
1468         if (!ssl_set_record_protocol_version(s, s->version)) {
1469             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1470             goto err;
1471         }
1472         hrr = 1;
1473         if (!PACKET_forward(pkt, SSL3_RANDOM_SIZE)) {
1474             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1475             goto err;
1476         }
1477     } else {
1478         if (!PACKET_copy_bytes(pkt, s->s3.server_random, SSL3_RANDOM_SIZE)) {
1479             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1480             goto err;
1481         }
1482     }
1483
1484     /* Get the session-id. */
1485     if (!PACKET_get_length_prefixed_1(pkt, &session_id)) {
1486         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1487         goto err;
1488     }
1489     session_id_len = PACKET_remaining(&session_id);
1490     if (session_id_len > sizeof(s->session->session_id)
1491         || session_id_len > SSL3_SESSION_ID_SIZE) {
1492         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_SSL3_SESSION_ID_TOO_LONG);
1493         goto err;
1494     }
1495
1496     if (!PACKET_get_bytes(pkt, &cipherchars, TLS_CIPHER_LEN)) {
1497         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1498         goto err;
1499     }
1500
1501     if (!PACKET_get_1(pkt, &compression)) {
1502         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1503         goto err;
1504     }
1505
1506     /* TLS extensions */
1507     if (PACKET_remaining(pkt) == 0 && !hrr) {
1508         PACKET_null_init(&extpkt);
1509     } else if (!PACKET_as_length_prefixed_2(pkt, &extpkt)
1510                || PACKET_remaining(pkt) != 0) {
1511         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_LENGTH);
1512         goto err;
1513     }
1514
1515     if (!hrr) {
1516         if (!tls_collect_extensions(s, &extpkt,
1517                                     SSL_EXT_TLS1_2_SERVER_HELLO
1518                                     | SSL_EXT_TLS1_3_SERVER_HELLO,
1519                                     &extensions, NULL, 1)) {
1520             /* SSLfatal() already called */
1521             goto err;
1522         }
1523
1524         if (!ssl_choose_client_version(s, sversion, extensions)) {
1525             /* SSLfatal() already called */
1526             goto err;
1527         }
1528     }
1529
1530     if (SSL_CONNECTION_IS_TLS13(s) || hrr) {
1531         if (compression != 0) {
1532             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1533                      SSL_R_INVALID_COMPRESSION_ALGORITHM);
1534             goto err;
1535         }
1536
1537         if (session_id_len != s->tmp_session_id_len
1538                 || memcmp(PACKET_data(&session_id), s->tmp_session_id,
1539                           session_id_len) != 0) {
1540             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_INVALID_SESSION_ID);
1541             goto err;
1542         }
1543     }
1544
1545     if (hrr) {
1546         if (!set_client_ciphersuite(s, cipherchars)) {
1547             /* SSLfatal() already called */
1548             goto err;
1549         }
1550
1551         return tls_process_as_hello_retry_request(s, &extpkt);
1552     }
1553
1554     /*
1555      * Now we have chosen the version we need to check again that the extensions
1556      * are appropriate for this version.
1557      */
1558     context = SSL_CONNECTION_IS_TLS13(s) ? SSL_EXT_TLS1_3_SERVER_HELLO
1559                                          : SSL_EXT_TLS1_2_SERVER_HELLO;
1560     if (!tls_validate_all_contexts(s, context, extensions)) {
1561         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_EXTENSION);
1562         goto err;
1563     }
1564
1565     s->hit = 0;
1566
1567     if (SSL_CONNECTION_IS_TLS13(s)) {
1568         /*
1569          * In TLSv1.3 a ServerHello message signals a key change so the end of
1570          * the message must be on a record boundary.
1571          */
1572         if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
1573             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1574                      SSL_R_NOT_ON_RECORD_BOUNDARY);
1575             goto err;
1576         }
1577
1578         /* This will set s->hit if we are resuming */
1579         if (!tls_parse_extension(s, TLSEXT_IDX_psk,
1580                                  SSL_EXT_TLS1_3_SERVER_HELLO,
1581                                  extensions, NULL, 0)) {
1582             /* SSLfatal() already called */
1583             goto err;
1584         }
1585     } else {
1586         /*
1587          * Check if we can resume the session based on external pre-shared
1588          * secret. EAP-FAST (RFC 4851) supports two types of session resumption.
1589          * Resumption based on server-side state works with session IDs.
1590          * Resumption based on pre-shared Protected Access Credentials (PACs)
1591          * works by overriding the SessionTicket extension at the application
1592          * layer, and does not send a session ID. (We do not know whether
1593          * EAP-FAST servers would honour the session ID.) Therefore, the session
1594          * ID alone is not a reliable indicator of session resumption, so we
1595          * first check if we can resume, and later peek at the next handshake
1596          * message to see if the server wants to resume.
1597          */
1598         if (s->version >= TLS1_VERSION
1599                 && s->ext.session_secret_cb != NULL && s->session->ext.tick) {
1600             const SSL_CIPHER *pref_cipher = NULL;
1601             /*
1602              * s->session->master_key_length is a size_t, but this is an int for
1603              * backwards compat reasons
1604              */
1605             int master_key_length;
1606
1607             master_key_length = sizeof(s->session->master_key);
1608             if (s->ext.session_secret_cb(ssl, s->session->master_key,
1609                                          &master_key_length,
1610                                          NULL, &pref_cipher,
1611                                          s->ext.session_secret_cb_arg)
1612                      && master_key_length > 0) {
1613                 s->session->master_key_length = master_key_length;
1614                 s->session->cipher = pref_cipher ?
1615                     pref_cipher : ssl_get_cipher_by_char(s, cipherchars, 0);
1616             } else {
1617                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1618                 goto err;
1619             }
1620         }
1621
1622         if (session_id_len != 0
1623                 && session_id_len == s->session->session_id_length
1624                 && memcmp(PACKET_data(&session_id), s->session->session_id,
1625                           session_id_len) == 0)
1626             s->hit = 1;
1627     }
1628
1629     if (s->hit) {
1630         if (s->sid_ctx_length != s->session->sid_ctx_length
1631                 || memcmp(s->session->sid_ctx, s->sid_ctx, s->sid_ctx_length)) {
1632             /* actually a client application bug */
1633             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1634                      SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
1635             goto err;
1636         }
1637     } else {
1638         /*
1639          * If we were trying for session-id reuse but the server
1640          * didn't resume, make a new SSL_SESSION.
1641          * In the case of EAP-FAST and PAC, we do not send a session ID,
1642          * so the PAC-based session secret is always preserved. It'll be
1643          * overwritten if the server refuses resumption.
1644          */
1645         if (s->session->session_id_length > 0) {
1646             ssl_tsan_counter(s->session_ctx, &s->session_ctx->stats.sess_miss);
1647             if (!ssl_get_new_session(s, 0)) {
1648                 /* SSLfatal() already called */
1649                 goto err;
1650             }
1651         }
1652
1653         s->session->ssl_version = s->version;
1654         /*
1655          * In TLSv1.2 and below we save the session id we were sent so we can
1656          * resume it later. In TLSv1.3 the session id we were sent is just an
1657          * echo of what we originally sent in the ClientHello and should not be
1658          * used for resumption.
1659          */
1660         if (!SSL_CONNECTION_IS_TLS13(s)) {
1661             s->session->session_id_length = session_id_len;
1662             /* session_id_len could be 0 */
1663             if (session_id_len > 0)
1664                 memcpy(s->session->session_id, PACKET_data(&session_id),
1665                        session_id_len);
1666         }
1667     }
1668
1669     /* Session version and negotiated protocol version should match */
1670     if (s->version != s->session->ssl_version) {
1671         SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
1672                  SSL_R_SSL_SESSION_VERSION_MISMATCH);
1673         goto err;
1674     }
1675     /*
1676      * Now that we know the version, update the check to see if it's an allowed
1677      * version.
1678      */
1679     s->s3.tmp.min_ver = s->version;
1680     s->s3.tmp.max_ver = s->version;
1681
1682     if (!set_client_ciphersuite(s, cipherchars)) {
1683         /* SSLfatal() already called */
1684         goto err;
1685     }
1686
1687 #ifdef OPENSSL_NO_COMP
1688     if (compression != 0) {
1689         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1690                  SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1691         goto err;
1692     }
1693     /*
1694      * If compression is disabled we'd better not try to resume a session
1695      * using compression.
1696      */
1697     if (s->session->compress_meth != 0) {
1698         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_INCONSISTENT_COMPRESSION);
1699         goto err;
1700     }
1701 #else
1702     if (s->hit && compression != s->session->compress_meth) {
1703         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1704                  SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED);
1705         goto err;
1706     }
1707     if (compression == 0)
1708         comp = NULL;
1709     else if (!ssl_allow_compression(s)) {
1710         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_COMPRESSION_DISABLED);
1711         goto err;
1712     } else {
1713         comp = ssl3_comp_find(SSL_CONNECTION_GET_CTX(s)->comp_methods,
1714                               compression);
1715     }
1716
1717     if (compression != 0 && comp == NULL) {
1718         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1719                  SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1720         goto err;
1721     } else {
1722         s->s3.tmp.new_compression = comp;
1723     }
1724 #endif
1725
1726     if (!tls_parse_all_extensions(s, context, extensions, NULL, 0, 1)) {
1727         /* SSLfatal() already called */
1728         goto err;
1729     }
1730
1731 #ifndef OPENSSL_NO_SCTP
1732     if (SSL_CONNECTION_IS_DTLS(s) && s->hit) {
1733         unsigned char sctpauthkey[64];
1734         char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
1735         size_t labellen;
1736
1737         /*
1738          * Add new shared key for SCTP-Auth, will be ignored if
1739          * no SCTP used.
1740          */
1741         memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
1742                sizeof(DTLS1_SCTP_AUTH_LABEL));
1743
1744         /* Don't include the terminating zero. */
1745         labellen = sizeof(labelbuffer) - 1;
1746         if (s->mode & SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG)
1747             labellen += 1;
1748
1749         if (SSL_export_keying_material(ssl, sctpauthkey,
1750                                        sizeof(sctpauthkey),
1751                                        labelbuffer,
1752                                        labellen, NULL, 0, 0) <= 0) {
1753             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1754             goto err;
1755         }
1756
1757         BIO_ctrl(SSL_get_wbio(ssl),
1758                  BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
1759                  sizeof(sctpauthkey), sctpauthkey);
1760     }
1761 #endif
1762
1763     /*
1764      * In TLSv1.3 we have some post-processing to change cipher state, otherwise
1765      * we're done with this message
1766      */
1767     if (SSL_CONNECTION_IS_TLS13(s)
1768             && (!ssl->method->ssl3_enc->setup_key_block(s)
1769                 || !ssl->method->ssl3_enc->change_cipher_state(s,
1770                     SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_READ))) {
1771         /* SSLfatal() already called */
1772         goto err;
1773     }
1774
1775     OPENSSL_free(extensions);
1776     return MSG_PROCESS_CONTINUE_READING;
1777  err:
1778     OPENSSL_free(extensions);
1779     return MSG_PROCESS_ERROR;
1780 }
1781
1782 static MSG_PROCESS_RETURN tls_process_as_hello_retry_request(SSL_CONNECTION *s,
1783                                                              PACKET *extpkt)
1784 {
1785     RAW_EXTENSION *extensions = NULL;
1786
1787     /*
1788      * If we were sending early_data then any alerts should not be sent using
1789      * the old wrlmethod.
1790      */
1791     if (s->early_data_state == SSL_EARLY_DATA_FINISHED_WRITING
1792             && !ssl_set_new_record_layer(s,
1793                                          TLS_ANY_VERSION,
1794                                          OSSL_RECORD_DIRECTION_WRITE,
1795                                          OSSL_RECORD_PROTECTION_LEVEL_NONE,
1796                                          NULL, 0, NULL, 0, NULL,  0, NULL, 0,
1797                                          NID_undef, NULL, NULL)) {
1798         /* SSLfatal already called */
1799         goto err;
1800     }
1801     /* We are definitely going to be using TLSv1.3 */
1802     s->rlayer.wrlmethod->set_protocol_version(s->rlayer.wrl, TLS1_3_VERSION);
1803
1804     if (!tls_collect_extensions(s, extpkt, SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST,
1805                                 &extensions, NULL, 1)
1806             || !tls_parse_all_extensions(s, SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST,
1807                                          extensions, NULL, 0, 1)) {
1808         /* SSLfatal() already called */
1809         goto err;
1810     }
1811
1812     OPENSSL_free(extensions);
1813     extensions = NULL;
1814
1815     if (s->ext.tls13_cookie_len == 0 && s->s3.tmp.pkey != NULL) {
1816         /*
1817          * We didn't receive a cookie or a new key_share so the next
1818          * ClientHello will not change
1819          */
1820         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_NO_CHANGE_FOLLOWING_HRR);
1821         goto err;
1822     }
1823
1824     /*
1825      * Re-initialise the Transcript Hash. We're going to prepopulate it with
1826      * a synthetic message_hash in place of ClientHello1.
1827      */
1828     if (!create_synthetic_message_hash(s, NULL, 0, NULL, 0)) {
1829         /* SSLfatal() already called */
1830         goto err;
1831     }
1832
1833     /*
1834      * Add this message to the Transcript Hash. Normally this is done
1835      * automatically prior to the message processing stage. However due to the
1836      * need to create the synthetic message hash, we defer that step until now
1837      * for HRR messages.
1838      */
1839     if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1840                                 s->init_num + SSL3_HM_HEADER_LENGTH)) {
1841         /* SSLfatal() already called */
1842         goto err;
1843     }
1844
1845     return MSG_PROCESS_FINISHED_READING;
1846  err:
1847     OPENSSL_free(extensions);
1848     return MSG_PROCESS_ERROR;
1849 }
1850
1851 /* prepare server cert verification by setting s->session->peer_chain from pkt */
1852 MSG_PROCESS_RETURN tls_process_server_certificate(SSL_CONNECTION *s,
1853                                                   PACKET *pkt)
1854 {
1855     unsigned long cert_list_len, cert_len;
1856     X509 *x = NULL;
1857     const unsigned char *certstart, *certbytes;
1858     size_t chainidx;
1859     unsigned int context = 0;
1860     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1861
1862     if ((s->session->peer_chain = sk_X509_new_null()) == NULL) {
1863         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
1864         goto err;
1865     }
1866
1867     if ((SSL_CONNECTION_IS_TLS13(s) && !PACKET_get_1(pkt, &context))
1868             || context != 0
1869             || !PACKET_get_net_3(pkt, &cert_list_len)
1870             || PACKET_remaining(pkt) != cert_list_len
1871             || PACKET_remaining(pkt) == 0) {
1872         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1873         goto err;
1874     }
1875     for (chainidx = 0; PACKET_remaining(pkt); chainidx++) {
1876         if (!PACKET_get_net_3(pkt, &cert_len)
1877             || !PACKET_get_bytes(pkt, &certbytes, cert_len)) {
1878             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CERT_LENGTH_MISMATCH);
1879             goto err;
1880         }
1881
1882         certstart = certbytes;
1883         x = X509_new_ex(sctx->libctx, sctx->propq);
1884         if (x == NULL) {
1885             SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_ASN1_LIB);
1886             goto err;
1887         }
1888         if (d2i_X509(&x, (const unsigned char **)&certbytes,
1889                      cert_len) == NULL) {
1890             SSLfatal(s, SSL_AD_BAD_CERTIFICATE, ERR_R_ASN1_LIB);
1891             goto err;
1892         }
1893
1894         if (certbytes != (certstart + cert_len)) {
1895             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CERT_LENGTH_MISMATCH);
1896             goto err;
1897         }
1898
1899         if (SSL_CONNECTION_IS_TLS13(s)) {
1900             RAW_EXTENSION *rawexts = NULL;
1901             PACKET extensions;
1902
1903             if (!PACKET_get_length_prefixed_2(pkt, &extensions)) {
1904                 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_LENGTH);
1905                 goto err;
1906             }
1907             if (!tls_collect_extensions(s, &extensions,
1908                                         SSL_EXT_TLS1_3_CERTIFICATE, &rawexts,
1909                                         NULL, chainidx == 0)
1910                 || !tls_parse_all_extensions(s, SSL_EXT_TLS1_3_CERTIFICATE,
1911                                              rawexts, x, chainidx,
1912                                              PACKET_remaining(pkt) == 0)) {
1913                 OPENSSL_free(rawexts);
1914                 /* SSLfatal already called */
1915                 goto err;
1916             }
1917             OPENSSL_free(rawexts);
1918         }
1919
1920         if (!sk_X509_push(s->session->peer_chain, x)) {
1921             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
1922             goto err;
1923         }
1924         x = NULL;
1925     }
1926     return MSG_PROCESS_CONTINUE_PROCESSING;
1927
1928  err:
1929     X509_free(x);
1930     OSSL_STACK_OF_X509_free(s->session->peer_chain);
1931     s->session->peer_chain = NULL;
1932     return MSG_PROCESS_ERROR;
1933 }
1934
1935 /*
1936  * Verify the s->session->peer_chain and check server cert type.
1937  * On success set s->session->peer and s->session->verify_result.
1938  * Else the peer certificate verification callback may request retry.
1939  */
1940 WORK_STATE tls_post_process_server_certificate(SSL_CONNECTION *s,
1941                                                WORK_STATE wst)
1942 {
1943     X509 *x;
1944     EVP_PKEY *pkey = NULL;
1945     const SSL_CERT_LOOKUP *clu;
1946     size_t certidx;
1947     int i;
1948
1949     if (s->rwstate == SSL_RETRY_VERIFY)
1950         s->rwstate = SSL_NOTHING;
1951     i = ssl_verify_cert_chain(s, s->session->peer_chain);
1952     if (i > 0 && s->rwstate == SSL_RETRY_VERIFY) {
1953         return WORK_MORE_A;
1954     }
1955     /*
1956      * The documented interface is that SSL_VERIFY_PEER should be set in order
1957      * for client side verification of the server certificate to take place.
1958      * However, historically the code has only checked that *any* flag is set
1959      * to cause server verification to take place. Use of the other flags makes
1960      * no sense in client mode. An attempt to clean up the semantics was
1961      * reverted because at least one application *only* set
1962      * SSL_VERIFY_FAIL_IF_NO_PEER_CERT. Prior to the clean up this still caused
1963      * server verification to take place, after the clean up it silently did
1964      * nothing. SSL_CTX_set_verify()/SSL_set_verify() cannot validate the flags
1965      * sent to them because they are void functions. Therefore, we now use the
1966      * (less clean) historic behaviour of performing validation if any flag is
1967      * set. The *documented* interface remains the same.
1968      */
1969     if (s->verify_mode != SSL_VERIFY_NONE && i <= 0) {
1970         SSLfatal(s, ssl_x509err2alert(s->verify_result),
1971                  SSL_R_CERTIFICATE_VERIFY_FAILED);
1972         return WORK_ERROR;
1973     }
1974     ERR_clear_error();          /* but we keep s->verify_result */
1975
1976     /*
1977      * Inconsistency alert: cert_chain does include the peer's certificate,
1978      * which we don't include in statem_srvr.c
1979      */
1980     x = sk_X509_value(s->session->peer_chain, 0);
1981
1982     pkey = X509_get0_pubkey(x);
1983
1984     if (pkey == NULL || EVP_PKEY_missing_parameters(pkey)) {
1985         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1986                  SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
1987         return WORK_ERROR;
1988     }
1989
1990     if ((clu = ssl_cert_lookup_by_pkey(pkey, &certidx)) == NULL) {
1991         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1992         return WORK_ERROR;
1993     }
1994     /*
1995      * Check certificate type is consistent with ciphersuite. For TLS 1.3
1996      * skip check since TLS 1.3 ciphersuites can be used with any certificate
1997      * type.
1998      */
1999     if (!SSL_CONNECTION_IS_TLS13(s)) {
2000         if ((clu->amask & s->s3.tmp.new_cipher->algorithm_auth) == 0) {
2001             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_CERTIFICATE_TYPE);
2002             return WORK_ERROR;
2003         }
2004     }
2005
2006     X509_free(s->session->peer);
2007     X509_up_ref(x);
2008     s->session->peer = x;
2009     s->session->verify_result = s->verify_result;
2010
2011     /* Save the current hash state for when we receive the CertificateVerify */
2012     if (SSL_CONNECTION_IS_TLS13(s)
2013             && !ssl_handshake_hash(s, s->cert_verify_hash,
2014                                    sizeof(s->cert_verify_hash),
2015                                    &s->cert_verify_hash_len)) {
2016         /* SSLfatal() already called */;
2017         return WORK_ERROR;
2018     }
2019     return WORK_FINISHED_CONTINUE;
2020 }
2021
2022 #ifndef OPENSSL_NO_COMP_ALG
2023 MSG_PROCESS_RETURN tls_process_server_compressed_certificate(SSL_CONNECTION *sc, PACKET *pkt)
2024 {
2025     MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
2026     PACKET tmppkt;
2027     BUF_MEM *buf = BUF_MEM_new();
2028
2029     if (tls13_process_compressed_certificate(sc, pkt, &tmppkt, buf) != MSG_PROCESS_ERROR)
2030         ret = tls_process_server_certificate(sc, &tmppkt);
2031
2032     BUF_MEM_free(buf);
2033     return ret;
2034 }
2035 #endif
2036
2037 static int tls_process_ske_psk_preamble(SSL_CONNECTION *s, PACKET *pkt)
2038 {
2039 #ifndef OPENSSL_NO_PSK
2040     PACKET psk_identity_hint;
2041
2042     /* PSK ciphersuites are preceded by an identity hint */
2043
2044     if (!PACKET_get_length_prefixed_2(pkt, &psk_identity_hint)) {
2045         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2046         return 0;
2047     }
2048
2049     /*
2050      * Store PSK identity hint for later use, hint is used in
2051      * tls_construct_client_key_exchange.  Assume that the maximum length of
2052      * a PSK identity hint can be as long as the maximum length of a PSK
2053      * identity.
2054      */
2055     if (PACKET_remaining(&psk_identity_hint) > PSK_MAX_IDENTITY_LEN) {
2056         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_DATA_LENGTH_TOO_LONG);
2057         return 0;
2058     }
2059
2060     if (PACKET_remaining(&psk_identity_hint) == 0) {
2061         OPENSSL_free(s->session->psk_identity_hint);
2062         s->session->psk_identity_hint = NULL;
2063     } else if (!PACKET_strndup(&psk_identity_hint,
2064                                &s->session->psk_identity_hint)) {
2065         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2066         return 0;
2067     }
2068
2069     return 1;
2070 #else
2071     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2072     return 0;
2073 #endif
2074 }
2075
2076 static int tls_process_ske_srp(SSL_CONNECTION *s, PACKET *pkt, EVP_PKEY **pkey)
2077 {
2078 #ifndef OPENSSL_NO_SRP
2079     PACKET prime, generator, salt, server_pub;
2080
2081     if (!PACKET_get_length_prefixed_2(pkt, &prime)
2082         || !PACKET_get_length_prefixed_2(pkt, &generator)
2083         || !PACKET_get_length_prefixed_1(pkt, &salt)
2084         || !PACKET_get_length_prefixed_2(pkt, &server_pub)) {
2085         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2086         return 0;
2087     }
2088
2089     if ((s->srp_ctx.N =
2090          BN_bin2bn(PACKET_data(&prime),
2091                    (int)PACKET_remaining(&prime), NULL)) == NULL
2092         || (s->srp_ctx.g =
2093             BN_bin2bn(PACKET_data(&generator),
2094                       (int)PACKET_remaining(&generator), NULL)) == NULL
2095         || (s->srp_ctx.s =
2096             BN_bin2bn(PACKET_data(&salt),
2097                       (int)PACKET_remaining(&salt), NULL)) == NULL
2098         || (s->srp_ctx.B =
2099             BN_bin2bn(PACKET_data(&server_pub),
2100                       (int)PACKET_remaining(&server_pub), NULL)) == NULL) {
2101         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BN_LIB);
2102         return 0;
2103     }
2104
2105     if (!srp_verify_server_param(s)) {
2106         /* SSLfatal() already called */
2107         return 0;
2108     }
2109
2110     /* We must check if there is a certificate */
2111     if (s->s3.tmp.new_cipher->algorithm_auth & (SSL_aRSA | SSL_aDSS))
2112         *pkey = X509_get0_pubkey(s->session->peer);
2113
2114     return 1;
2115 #else
2116     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2117     return 0;
2118 #endif
2119 }
2120
2121 static int tls_process_ske_dhe(SSL_CONNECTION *s, PACKET *pkt, EVP_PKEY **pkey)
2122 {
2123     PACKET prime, generator, pub_key;
2124     EVP_PKEY *peer_tmp = NULL;
2125     BIGNUM *p = NULL, *g = NULL, *bnpub_key = NULL;
2126     EVP_PKEY_CTX *pctx = NULL;
2127     OSSL_PARAM *params = NULL;
2128     OSSL_PARAM_BLD *tmpl = NULL;
2129     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
2130     int ret = 0;
2131
2132     if (!PACKET_get_length_prefixed_2(pkt, &prime)
2133         || !PACKET_get_length_prefixed_2(pkt, &generator)
2134         || !PACKET_get_length_prefixed_2(pkt, &pub_key)) {
2135         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2136         return 0;
2137     }
2138
2139     p = BN_bin2bn(PACKET_data(&prime), (int)PACKET_remaining(&prime), NULL);
2140     g = BN_bin2bn(PACKET_data(&generator), (int)PACKET_remaining(&generator),
2141                   NULL);
2142     bnpub_key = BN_bin2bn(PACKET_data(&pub_key),
2143                           (int)PACKET_remaining(&pub_key), NULL);
2144     if (p == NULL || g == NULL || bnpub_key == NULL) {
2145         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BN_LIB);
2146         goto err;
2147     }
2148
2149     tmpl = OSSL_PARAM_BLD_new();
2150     if (tmpl == NULL
2151             || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_P, p)
2152             || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_G, g)
2153             || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_PUB_KEY,
2154                                        bnpub_key)
2155             || (params = OSSL_PARAM_BLD_to_param(tmpl)) == NULL) {
2156         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2157         goto err;
2158     }
2159
2160     pctx = EVP_PKEY_CTX_new_from_name(sctx->libctx, "DH", sctx->propq);
2161     if (pctx == NULL) {
2162         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2163         goto err;
2164     }
2165     if (EVP_PKEY_fromdata_init(pctx) <= 0
2166             || EVP_PKEY_fromdata(pctx, &peer_tmp, EVP_PKEY_KEYPAIR, params) <= 0) {
2167         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_DH_VALUE);
2168         goto err;
2169     }
2170
2171     EVP_PKEY_CTX_free(pctx);
2172     pctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx, peer_tmp, sctx->propq);
2173     if (pctx == NULL
2174             /*
2175              * EVP_PKEY_param_check() will verify that the DH params are using
2176              * a safe prime. In this context, because we're using ephemeral DH,
2177              * we're ok with it not being a safe prime.
2178              * EVP_PKEY_param_check_quick() skips the safe prime check.
2179              */
2180             || EVP_PKEY_param_check_quick(pctx) != 1
2181             || EVP_PKEY_public_check(pctx) != 1) {
2182         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_DH_VALUE);
2183         goto err;
2184     }
2185
2186     if (!ssl_security(s, SSL_SECOP_TMP_DH,
2187                       EVP_PKEY_get_security_bits(peer_tmp),
2188                       0, peer_tmp)) {
2189         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_DH_KEY_TOO_SMALL);
2190         goto err;
2191     }
2192
2193     s->s3.peer_tmp = peer_tmp;
2194     peer_tmp = NULL;
2195
2196     /*
2197      * FIXME: This makes assumptions about which ciphersuites come with
2198      * public keys. We should have a less ad-hoc way of doing this
2199      */
2200     if (s->s3.tmp.new_cipher->algorithm_auth & (SSL_aRSA | SSL_aDSS))
2201         *pkey = X509_get0_pubkey(s->session->peer);
2202     /* else anonymous DH, so no certificate or pkey. */
2203
2204     ret = 1;
2205
2206  err:
2207     OSSL_PARAM_BLD_free(tmpl);
2208     OSSL_PARAM_free(params);
2209     EVP_PKEY_free(peer_tmp);
2210     EVP_PKEY_CTX_free(pctx);
2211     BN_free(p);
2212     BN_free(g);
2213     BN_free(bnpub_key);
2214
2215     return ret;
2216 }
2217
2218 static int tls_process_ske_ecdhe(SSL_CONNECTION *s, PACKET *pkt, EVP_PKEY **pkey)
2219 {
2220     PACKET encoded_pt;
2221     unsigned int curve_type, curve_id;
2222
2223     /*
2224      * Extract elliptic curve parameters and the server's ephemeral ECDH
2225      * public key. We only support named (not generic) curves and
2226      * ECParameters in this case is just three bytes.
2227      */
2228     if (!PACKET_get_1(pkt, &curve_type) || !PACKET_get_net_2(pkt, &curve_id)) {
2229         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
2230         return 0;
2231     }
2232     /*
2233      * Check curve is named curve type and one of our preferences, if not
2234      * server has sent an invalid curve.
2235      */
2236     if (curve_type != NAMED_CURVE_TYPE
2237             || !tls1_check_group_id(s, curve_id, 1)) {
2238         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_CURVE);
2239         return 0;
2240     }
2241
2242     if ((s->s3.peer_tmp = ssl_generate_param_group(s, curve_id)) == NULL) {
2243         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2244                  SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
2245         return 0;
2246     }
2247
2248     if (!PACKET_get_length_prefixed_1(pkt, &encoded_pt)) {
2249         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2250         return 0;
2251     }
2252
2253     if (EVP_PKEY_set1_encoded_public_key(s->s3.peer_tmp,
2254                                          PACKET_data(&encoded_pt),
2255                                          PACKET_remaining(&encoded_pt)) <= 0) {
2256         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_ECPOINT);
2257         return 0;
2258     }
2259
2260     /*
2261      * The ECC/TLS specification does not mention the use of DSA to sign
2262      * ECParameters in the server key exchange message. We do support RSA
2263      * and ECDSA.
2264      */
2265     if (s->s3.tmp.new_cipher->algorithm_auth & SSL_aECDSA)
2266         *pkey = X509_get0_pubkey(s->session->peer);
2267     else if (s->s3.tmp.new_cipher->algorithm_auth & SSL_aRSA)
2268         *pkey = X509_get0_pubkey(s->session->peer);
2269     /* else anonymous ECDH, so no certificate or pkey. */
2270
2271     /* Cache the agreed upon group in the SSL_SESSION */
2272     s->session->kex_group = curve_id;
2273     return 1;
2274 }
2275
2276 MSG_PROCESS_RETURN tls_process_key_exchange(SSL_CONNECTION *s, PACKET *pkt)
2277 {
2278     long alg_k;
2279     EVP_PKEY *pkey = NULL;
2280     EVP_MD_CTX *md_ctx = NULL;
2281     EVP_PKEY_CTX *pctx = NULL;
2282     PACKET save_param_start, signature;
2283     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
2284
2285     alg_k = s->s3.tmp.new_cipher->algorithm_mkey;
2286
2287     save_param_start = *pkt;
2288
2289     EVP_PKEY_free(s->s3.peer_tmp);
2290     s->s3.peer_tmp = NULL;
2291
2292     if (alg_k & SSL_PSK) {
2293         if (!tls_process_ske_psk_preamble(s, pkt)) {
2294             /* SSLfatal() already called */
2295             goto err;
2296         }
2297     }
2298
2299     /* Nothing else to do for plain PSK or RSAPSK */
2300     if (alg_k & (SSL_kPSK | SSL_kRSAPSK)) {
2301     } else if (alg_k & SSL_kSRP) {
2302         if (!tls_process_ske_srp(s, pkt, &pkey)) {
2303             /* SSLfatal() already called */
2304             goto err;
2305         }
2306     } else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
2307         if (!tls_process_ske_dhe(s, pkt, &pkey)) {
2308             /* SSLfatal() already called */
2309             goto err;
2310         }
2311     } else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
2312         if (!tls_process_ske_ecdhe(s, pkt, &pkey)) {
2313             /* SSLfatal() already called */
2314             goto err;
2315         }
2316     } else if (alg_k) {
2317         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
2318         goto err;
2319     }
2320
2321     /* if it was signed, check the signature */
2322     if (pkey != NULL) {
2323         PACKET params;
2324         const EVP_MD *md = NULL;
2325         unsigned char *tbs;
2326         size_t tbslen;
2327         int rv;
2328
2329         /*
2330          * |pkt| now points to the beginning of the signature, so the difference
2331          * equals the length of the parameters.
2332          */
2333         if (!PACKET_get_sub_packet(&save_param_start, &params,
2334                                    PACKET_remaining(&save_param_start) -
2335                                    PACKET_remaining(pkt))) {
2336             SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
2337             goto err;
2338         }
2339
2340         if (SSL_USE_SIGALGS(s)) {
2341             unsigned int sigalg;
2342
2343             if (!PACKET_get_net_2(pkt, &sigalg)) {
2344                 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
2345                 goto err;
2346             }
2347             if (tls12_check_peer_sigalg(s, sigalg, pkey) <=0) {
2348                 /* SSLfatal() already called */
2349                 goto err;
2350             }
2351         } else if (!tls1_set_peer_legacy_sigalg(s, pkey)) {
2352             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2353                      SSL_R_LEGACY_SIGALG_DISALLOWED_OR_UNSUPPORTED);
2354             goto err;
2355         }
2356
2357         if (!tls1_lookup_md(sctx, s->s3.tmp.peer_sigalg, &md)) {
2358             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2359                      SSL_R_NO_SUITABLE_DIGEST_ALGORITHM);
2360             goto err;
2361         }
2362         if (SSL_USE_SIGALGS(s))
2363             OSSL_TRACE1(TLS, "USING TLSv1.2 HASH %s\n",
2364                         md == NULL ? "n/a" : EVP_MD_get0_name(md));
2365
2366         if (!PACKET_get_length_prefixed_2(pkt, &signature)
2367             || PACKET_remaining(pkt) != 0) {
2368             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2369             goto err;
2370         }
2371
2372         md_ctx = EVP_MD_CTX_new();
2373         if (md_ctx == NULL) {
2374             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
2375             goto err;
2376         }
2377
2378         if (EVP_DigestVerifyInit_ex(md_ctx, &pctx,
2379                                     md == NULL ? NULL : EVP_MD_get0_name(md),
2380                                     sctx->libctx, sctx->propq, pkey,
2381                                     NULL) <= 0) {
2382             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
2383             goto err;
2384         }
2385         if (SSL_USE_PSS(s)) {
2386             if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
2387                 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
2388                                                 RSA_PSS_SALTLEN_DIGEST) <= 0) {
2389                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
2390                 goto err;
2391             }
2392         }
2393         tbslen = construct_key_exchange_tbs(s, &tbs, PACKET_data(&params),
2394                                             PACKET_remaining(&params));
2395         if (tbslen == 0) {
2396             /* SSLfatal() already called */
2397             goto err;
2398         }
2399
2400         rv = EVP_DigestVerify(md_ctx, PACKET_data(&signature),
2401                               PACKET_remaining(&signature), tbs, tbslen);
2402         OPENSSL_free(tbs);
2403         if (rv <= 0) {
2404             SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_BAD_SIGNATURE);
2405             goto err;
2406         }
2407         EVP_MD_CTX_free(md_ctx);
2408         md_ctx = NULL;
2409     } else {
2410         /* aNULL, aSRP or PSK do not need public keys */
2411         if (!(s->s3.tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP))
2412             && !(alg_k & SSL_PSK)) {
2413             /* Might be wrong key type, check it */
2414             if (ssl3_check_cert_and_algorithm(s)) {
2415                 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_DATA);
2416             }
2417             /* else this shouldn't happen, SSLfatal() already called */
2418             goto err;
2419         }
2420         /* still data left over */
2421         if (PACKET_remaining(pkt) != 0) {
2422             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_EXTRA_DATA_IN_MESSAGE);
2423             goto err;
2424         }
2425     }
2426
2427     return MSG_PROCESS_CONTINUE_READING;
2428  err:
2429     EVP_MD_CTX_free(md_ctx);
2430     return MSG_PROCESS_ERROR;
2431 }
2432
2433 MSG_PROCESS_RETURN tls_process_certificate_request(SSL_CONNECTION *s,
2434                                                    PACKET *pkt)
2435 {
2436     size_t i;
2437
2438     /* Clear certificate validity flags */
2439     for (i = 0; i < SSL_PKEY_NUM; i++)
2440         s->s3.tmp.valid_flags[i] = 0;
2441
2442     if (SSL_CONNECTION_IS_TLS13(s)) {
2443         PACKET reqctx, extensions;
2444         RAW_EXTENSION *rawexts = NULL;
2445
2446         if ((s->shutdown & SSL_SENT_SHUTDOWN) != 0) {
2447             /*
2448              * We already sent close_notify. This can only happen in TLSv1.3
2449              * post-handshake messages. We can't reasonably respond to this, so
2450              * we just ignore it
2451              */
2452             return MSG_PROCESS_FINISHED_READING;
2453         }
2454
2455         /* Free and zero certificate types: it is not present in TLS 1.3 */
2456         OPENSSL_free(s->s3.tmp.ctype);
2457         s->s3.tmp.ctype = NULL;
2458         s->s3.tmp.ctype_len = 0;
2459         OPENSSL_free(s->pha_context);
2460         s->pha_context = NULL;
2461         s->pha_context_len = 0;
2462
2463         if (!PACKET_get_length_prefixed_1(pkt, &reqctx) ||
2464             !PACKET_memdup(&reqctx, &s->pha_context, &s->pha_context_len)) {
2465             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2466             return MSG_PROCESS_ERROR;
2467         }
2468
2469         if (!PACKET_get_length_prefixed_2(pkt, &extensions)) {
2470             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_LENGTH);
2471             return MSG_PROCESS_ERROR;
2472         }
2473         if (!tls_collect_extensions(s, &extensions,
2474                                     SSL_EXT_TLS1_3_CERTIFICATE_REQUEST,
2475                                     &rawexts, NULL, 1)
2476             || !tls_parse_all_extensions(s, SSL_EXT_TLS1_3_CERTIFICATE_REQUEST,
2477                                          rawexts, NULL, 0, 1)) {
2478             /* SSLfatal() already called */
2479             OPENSSL_free(rawexts);
2480             return MSG_PROCESS_ERROR;
2481         }
2482         OPENSSL_free(rawexts);
2483         if (!tls1_process_sigalgs(s)) {
2484             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_LENGTH);
2485             return MSG_PROCESS_ERROR;
2486         }
2487     } else {
2488         PACKET ctypes;
2489
2490         /* get the certificate types */
2491         if (!PACKET_get_length_prefixed_1(pkt, &ctypes)) {
2492             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2493             return MSG_PROCESS_ERROR;
2494         }
2495
2496         if (!PACKET_memdup(&ctypes, &s->s3.tmp.ctype, &s->s3.tmp.ctype_len)) {
2497             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2498             return MSG_PROCESS_ERROR;
2499         }
2500
2501         if (SSL_USE_SIGALGS(s)) {
2502             PACKET sigalgs;
2503
2504             if (!PACKET_get_length_prefixed_2(pkt, &sigalgs)) {
2505                 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2506                 return MSG_PROCESS_ERROR;
2507             }
2508
2509             /*
2510              * Despite this being for certificates, preserve compatibility
2511              * with pre-TLS 1.3 and use the regular sigalgs field.
2512              */
2513             if (!tls1_save_sigalgs(s, &sigalgs, 0)) {
2514                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2515                          SSL_R_SIGNATURE_ALGORITHMS_ERROR);
2516                 return MSG_PROCESS_ERROR;
2517             }
2518             if (!tls1_process_sigalgs(s)) {
2519                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SSL_LIB);
2520                 return MSG_PROCESS_ERROR;
2521             }
2522         }
2523
2524         /* get the CA RDNs */
2525         if (!parse_ca_names(s, pkt)) {
2526             /* SSLfatal() already called */
2527             return MSG_PROCESS_ERROR;
2528         }
2529     }
2530
2531     if (PACKET_remaining(pkt) != 0) {
2532         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2533         return MSG_PROCESS_ERROR;
2534     }
2535
2536     /* we should setup a certificate to return.... */
2537     s->s3.tmp.cert_req = 1;
2538
2539     /*
2540      * In TLSv1.3 we don't prepare the client certificate yet. We wait until
2541      * after the CertificateVerify message has been received. This is because
2542      * in TLSv1.3 the CertificateRequest arrives before the Certificate message
2543      * but in TLSv1.2 it is the other way around. We want to make sure that
2544      * SSL_get1_peer_certificate() returns something sensible in
2545      * client_cert_cb.
2546      */
2547     if (SSL_CONNECTION_IS_TLS13(s)
2548         && s->post_handshake_auth != SSL_PHA_REQUESTED)
2549         return MSG_PROCESS_CONTINUE_READING;
2550
2551     return MSG_PROCESS_CONTINUE_PROCESSING;
2552 }
2553
2554 MSG_PROCESS_RETURN tls_process_new_session_ticket(SSL_CONNECTION *s,
2555                                                   PACKET *pkt)
2556 {
2557     unsigned int ticklen;
2558     unsigned long ticket_lifetime_hint, age_add = 0;
2559     unsigned int sess_len;
2560     RAW_EXTENSION *exts = NULL;
2561     PACKET nonce;
2562     EVP_MD *sha256 = NULL;
2563     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
2564
2565     PACKET_null_init(&nonce);
2566
2567     if (!PACKET_get_net_4(pkt, &ticket_lifetime_hint)
2568         || (SSL_CONNECTION_IS_TLS13(s)
2569             && (!PACKET_get_net_4(pkt, &age_add)
2570                 || !PACKET_get_length_prefixed_1(pkt, &nonce)))
2571         || !PACKET_get_net_2(pkt, &ticklen)
2572         || (SSL_CONNECTION_IS_TLS13(s) ? (ticklen == 0 
2573                                           || PACKET_remaining(pkt) < ticklen)
2574                                        : PACKET_remaining(pkt) != ticklen)) {
2575         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2576         goto err;
2577     }
2578
2579     /*
2580      * Server is allowed to change its mind (in <=TLSv1.2) and send an empty
2581      * ticket. We already checked this TLSv1.3 case above, so it should never
2582      * be 0 here in that instance
2583      */
2584     if (ticklen == 0)
2585         return MSG_PROCESS_CONTINUE_READING;
2586
2587     /*
2588      * Sessions must be immutable once they go into the session cache. Otherwise
2589      * we can get multi-thread problems. Therefore we don't "update" sessions,
2590      * we replace them with a duplicate. In TLSv1.3 we need to do this every
2591      * time a NewSessionTicket arrives because those messages arrive
2592      * post-handshake and the session may have already gone into the session
2593      * cache.
2594      */
2595     if (SSL_CONNECTION_IS_TLS13(s) || s->session->session_id_length > 0) {
2596         SSL_SESSION *new_sess;
2597
2598         /*
2599          * We reused an existing session, so we need to replace it with a new
2600          * one
2601          */
2602         if ((new_sess = ssl_session_dup(s->session, 0)) == 0) {
2603             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SSL_LIB);
2604             goto err;
2605         }
2606
2607         if ((s->session_ctx->session_cache_mode & SSL_SESS_CACHE_CLIENT) != 0
2608                 && !SSL_CONNECTION_IS_TLS13(s)) {
2609             /*
2610              * In TLSv1.2 and below the arrival of a new tickets signals that
2611              * any old ticket we were using is now out of date, so we remove the
2612              * old session from the cache. We carry on if this fails
2613              */
2614             SSL_CTX_remove_session(s->session_ctx, s->session);
2615         }
2616
2617         SSL_SESSION_free(s->session);
2618         s->session = new_sess;
2619     }
2620
2621     s->session->time = ossl_time_now();
2622     ssl_session_calculate_timeout(s->session);
2623
2624     OPENSSL_free(s->session->ext.tick);
2625     s->session->ext.tick = NULL;
2626     s->session->ext.ticklen = 0;
2627
2628     s->session->ext.tick = OPENSSL_malloc(ticklen);
2629     if (s->session->ext.tick == NULL) {
2630         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2631         goto err;
2632     }
2633     if (!PACKET_copy_bytes(pkt, s->session->ext.tick, ticklen)) {
2634         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2635         goto err;
2636     }
2637
2638     s->session->ext.tick_lifetime_hint = ticket_lifetime_hint;
2639     s->session->ext.tick_age_add = age_add;
2640     s->session->ext.ticklen = ticklen;
2641
2642     if (SSL_CONNECTION_IS_TLS13(s)) {
2643         PACKET extpkt;
2644
2645         if (!PACKET_as_length_prefixed_2(pkt, &extpkt)
2646                 || PACKET_remaining(pkt) != 0) {
2647             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2648             goto err;
2649         }
2650
2651         if (!tls_collect_extensions(s, &extpkt,
2652                                     SSL_EXT_TLS1_3_NEW_SESSION_TICKET, &exts,
2653                                     NULL, 1)
2654                 || !tls_parse_all_extensions(s,
2655                                              SSL_EXT_TLS1_3_NEW_SESSION_TICKET,
2656                                              exts, NULL, 0, 1)) {
2657             /* SSLfatal() already called */
2658             goto err;
2659         }
2660     }
2661
2662     /*
2663      * There are two ways to detect a resumed ticket session. One is to set
2664      * an appropriate session ID and then the server must return a match in
2665      * ServerHello. This allows the normal client session ID matching to work
2666      * and we know much earlier that the ticket has been accepted. The
2667      * other way is to set zero length session ID when the ticket is
2668      * presented and rely on the handshake to determine session resumption.
2669      * We choose the former approach because this fits in with assumptions
2670      * elsewhere in OpenSSL. The session ID is set to the SHA256 hash of the
2671      * ticket.
2672      */
2673     sha256 = EVP_MD_fetch(sctx->libctx, "SHA2-256", sctx->propq);
2674     if (sha256 == NULL) {
2675         /* Error is already recorded */
2676         SSLfatal_alert(s, SSL_AD_INTERNAL_ERROR);
2677         goto err;
2678     }
2679     /*
2680      * We use sess_len here because EVP_Digest expects an int
2681      * but s->session->session_id_length is a size_t
2682      */
2683     if (!EVP_Digest(s->session->ext.tick, ticklen,
2684                     s->session->session_id, &sess_len,
2685                     sha256, NULL)) {
2686         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
2687         goto err;
2688     }
2689     EVP_MD_free(sha256);
2690     sha256 = NULL;
2691     s->session->session_id_length = sess_len;
2692     s->session->not_resumable = 0;
2693
2694     /* This is a standalone message in TLSv1.3, so there is no more to read */
2695     if (SSL_CONNECTION_IS_TLS13(s)) {
2696         const EVP_MD *md = ssl_handshake_md(s);
2697         int hashleni = EVP_MD_get_size(md);
2698         size_t hashlen;
2699         static const unsigned char nonce_label[] = "resumption";
2700
2701         /* Ensure cast to size_t is safe */
2702         if (!ossl_assert(hashleni >= 0)) {
2703             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2704             goto err;
2705         }
2706         hashlen = (size_t)hashleni;
2707
2708         if (!tls13_hkdf_expand(s, md, s->resumption_master_secret,
2709                                nonce_label,
2710                                sizeof(nonce_label) - 1,
2711                                PACKET_data(&nonce),
2712                                PACKET_remaining(&nonce),
2713                                s->session->master_key,
2714                                hashlen, 1)) {
2715             /* SSLfatal() already called */
2716             goto err;
2717         }
2718         s->session->master_key_length = hashlen;
2719
2720         OPENSSL_free(exts);
2721         ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
2722         return MSG_PROCESS_FINISHED_READING;
2723     }
2724
2725     return MSG_PROCESS_CONTINUE_READING;
2726  err:
2727     EVP_MD_free(sha256);
2728     OPENSSL_free(exts);
2729     return MSG_PROCESS_ERROR;
2730 }
2731
2732 /*
2733  * In TLSv1.3 this is called from the extensions code, otherwise it is used to
2734  * parse a separate message. Returns 1 on success or 0 on failure
2735  */
2736 int tls_process_cert_status_body(SSL_CONNECTION *s, PACKET *pkt)
2737 {
2738     size_t resplen;
2739     unsigned int type;
2740
2741     if (!PACKET_get_1(pkt, &type)
2742         || type != TLSEXT_STATUSTYPE_ocsp) {
2743         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_UNSUPPORTED_STATUS_TYPE);
2744         return 0;
2745     }
2746     if (!PACKET_get_net_3_len(pkt, &resplen)
2747         || PACKET_remaining(pkt) != resplen) {
2748         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2749         return 0;
2750     }
2751     s->ext.ocsp.resp = OPENSSL_malloc(resplen);
2752     if (s->ext.ocsp.resp == NULL) {
2753         s->ext.ocsp.resp_len = 0;
2754         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2755         return 0;
2756     }
2757     s->ext.ocsp.resp_len = resplen;
2758     if (!PACKET_copy_bytes(pkt, s->ext.ocsp.resp, resplen)) {
2759         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2760         return 0;
2761     }
2762
2763     return 1;
2764 }
2765
2766
2767 MSG_PROCESS_RETURN tls_process_cert_status(SSL_CONNECTION *s, PACKET *pkt)
2768 {
2769     if (!tls_process_cert_status_body(s, pkt)) {
2770         /* SSLfatal() already called */
2771         return MSG_PROCESS_ERROR;
2772     }
2773
2774     return MSG_PROCESS_CONTINUE_READING;
2775 }
2776
2777 /*
2778  * Perform miscellaneous checks and processing after we have received the
2779  * server's initial flight. In TLS1.3 this is after the Server Finished message.
2780  * In <=TLS1.2 this is after the ServerDone message. Returns 1 on success or 0
2781  * on failure.
2782  */
2783 int tls_process_initial_server_flight(SSL_CONNECTION *s)
2784 {
2785     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
2786
2787     /*
2788      * at this point we check that we have the required stuff from
2789      * the server
2790      */
2791     if (!ssl3_check_cert_and_algorithm(s)) {
2792         /* SSLfatal() already called */
2793         return 0;
2794     }
2795
2796     /*
2797      * Call the ocsp status callback if needed. The |ext.ocsp.resp| and
2798      * |ext.ocsp.resp_len| values will be set if we actually received a status
2799      * message, or NULL and -1 otherwise
2800      */
2801     if (s->ext.status_type != TLSEXT_STATUSTYPE_nothing
2802             && sctx->ext.status_cb != NULL) {
2803         int ret = sctx->ext.status_cb(SSL_CONNECTION_GET_SSL(s),
2804                                       sctx->ext.status_arg);
2805
2806         if (ret == 0) {
2807             SSLfatal(s, SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE,
2808                      SSL_R_INVALID_STATUS_RESPONSE);
2809             return 0;
2810         }
2811         if (ret < 0) {
2812             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2813                      SSL_R_OCSP_CALLBACK_FAILURE);
2814             return 0;
2815         }
2816     }
2817 #ifndef OPENSSL_NO_CT
2818     if (s->ct_validation_callback != NULL) {
2819         /* Note we validate the SCTs whether or not we abort on error */
2820         if (!ssl_validate_ct(s) && (s->verify_mode & SSL_VERIFY_PEER)) {
2821             /* SSLfatal() already called */
2822             return 0;
2823         }
2824     }
2825 #endif
2826
2827     return 1;
2828 }
2829
2830 MSG_PROCESS_RETURN tls_process_server_done(SSL_CONNECTION *s, PACKET *pkt)
2831 {
2832     if (PACKET_remaining(pkt) > 0) {
2833         /* should contain no data */
2834         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2835         return MSG_PROCESS_ERROR;
2836     }
2837 #ifndef OPENSSL_NO_SRP
2838     if (s->s3.tmp.new_cipher->algorithm_mkey & SSL_kSRP) {
2839         if (ssl_srp_calc_a_param_intern(s) <= 0) {
2840             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_SRP_A_CALC);
2841             return MSG_PROCESS_ERROR;
2842         }
2843     }
2844 #endif
2845
2846     if (!tls_process_initial_server_flight(s)) {
2847         /* SSLfatal() already called */
2848         return MSG_PROCESS_ERROR;
2849     }
2850
2851     return MSG_PROCESS_FINISHED_READING;
2852 }
2853
2854 static int tls_construct_cke_psk_preamble(SSL_CONNECTION *s, WPACKET *pkt)
2855 {
2856 #ifndef OPENSSL_NO_PSK
2857     int ret = 0;
2858     /*
2859      * The callback needs PSK_MAX_IDENTITY_LEN + 1 bytes to return a
2860      * \0-terminated identity. The last byte is for us for simulating
2861      * strnlen.
2862      */
2863     char identity[PSK_MAX_IDENTITY_LEN + 1];
2864     size_t identitylen = 0;
2865     unsigned char psk[PSK_MAX_PSK_LEN];
2866     unsigned char *tmppsk = NULL;
2867     char *tmpidentity = NULL;
2868     size_t psklen = 0;
2869
2870     if (s->psk_client_callback == NULL) {
2871         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_PSK_NO_CLIENT_CB);
2872         goto err;
2873     }
2874
2875     memset(identity, 0, sizeof(identity));
2876
2877     psklen = s->psk_client_callback(SSL_CONNECTION_GET_SSL(s),
2878                                     s->session->psk_identity_hint,
2879                                     identity, sizeof(identity) - 1,
2880                                     psk, sizeof(psk));
2881
2882     if (psklen > PSK_MAX_PSK_LEN) {
2883         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, ERR_R_INTERNAL_ERROR);
2884         psklen = PSK_MAX_PSK_LEN;   /* Avoid overrunning the array on cleanse */
2885         goto err;
2886     } else if (psklen == 0) {
2887         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_PSK_IDENTITY_NOT_FOUND);
2888         goto err;
2889     }
2890
2891     identitylen = strlen(identity);
2892     if (identitylen > PSK_MAX_IDENTITY_LEN) {
2893         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2894         goto err;
2895     }
2896
2897     tmppsk = OPENSSL_memdup(psk, psklen);
2898     tmpidentity = OPENSSL_strdup(identity);
2899     if (tmppsk == NULL || tmpidentity == NULL) {
2900         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2901         goto err;
2902     }
2903
2904     OPENSSL_free(s->s3.tmp.psk);
2905     s->s3.tmp.psk = tmppsk;
2906     s->s3.tmp.psklen = psklen;
2907     tmppsk = NULL;
2908     OPENSSL_free(s->session->psk_identity);
2909     s->session->psk_identity = tmpidentity;
2910     tmpidentity = NULL;
2911
2912     if (!WPACKET_sub_memcpy_u16(pkt, identity, identitylen))  {
2913         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2914         goto err;
2915     }
2916
2917     ret = 1;
2918
2919  err:
2920     OPENSSL_cleanse(psk, psklen);
2921     OPENSSL_cleanse(identity, sizeof(identity));
2922     OPENSSL_clear_free(tmppsk, psklen);
2923     OPENSSL_clear_free(tmpidentity, identitylen);
2924
2925     return ret;
2926 #else
2927     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2928     return 0;
2929 #endif
2930 }
2931
2932 static int tls_construct_cke_rsa(SSL_CONNECTION *s, WPACKET *pkt)
2933 {
2934     unsigned char *encdata = NULL;
2935     EVP_PKEY *pkey = NULL;
2936     EVP_PKEY_CTX *pctx = NULL;
2937     size_t enclen;
2938     unsigned char *pms = NULL;
2939     size_t pmslen = 0;
2940     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
2941
2942     if (s->session->peer == NULL) {
2943         /*
2944          * We should always have a server certificate with SSL_kRSA.
2945          */
2946         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2947         return 0;
2948     }
2949
2950     pkey = X509_get0_pubkey(s->session->peer);
2951     if (!EVP_PKEY_is_a(pkey, "RSA")) {
2952         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2953         return 0;
2954     }
2955
2956     pmslen = SSL_MAX_MASTER_KEY_LENGTH;
2957     pms = OPENSSL_malloc(pmslen);
2958     if (pms == NULL) {
2959         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2960         return 0;
2961     }
2962
2963     pms[0] = s->client_version >> 8;
2964     pms[1] = s->client_version & 0xff;
2965     if (RAND_bytes_ex(sctx->libctx, pms + 2, pmslen - 2, 0) <= 0) {
2966         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_RAND_LIB);
2967         goto err;
2968     }
2969
2970     /* Fix buf for TLS and beyond */
2971     if (s->version > SSL3_VERSION && !WPACKET_start_sub_packet_u16(pkt)) {
2972         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2973         goto err;
2974     }
2975
2976     pctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx, pkey, sctx->propq);
2977     if (pctx == NULL || EVP_PKEY_encrypt_init(pctx) <= 0
2978         || EVP_PKEY_encrypt(pctx, NULL, &enclen, pms, pmslen) <= 0) {
2979         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
2980         goto err;
2981     }
2982     if (!WPACKET_allocate_bytes(pkt, enclen, &encdata)
2983             || EVP_PKEY_encrypt(pctx, encdata, &enclen, pms, pmslen) <= 0) {
2984         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_RSA_ENCRYPT);
2985         goto err;
2986     }
2987     EVP_PKEY_CTX_free(pctx);
2988     pctx = NULL;
2989
2990     /* Fix buf for TLS and beyond */
2991     if (s->version > SSL3_VERSION && !WPACKET_close(pkt)) {
2992         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2993         goto err;
2994     }
2995
2996     /* Log the premaster secret, if logging is enabled. */
2997     if (!ssl_log_rsa_client_key_exchange(s, encdata, enclen, pms, pmslen)) {
2998         /* SSLfatal() already called */
2999         goto err;
3000     }
3001
3002     s->s3.tmp.pms = pms;
3003     s->s3.tmp.pmslen = pmslen;
3004
3005     return 1;
3006  err:
3007     OPENSSL_clear_free(pms, pmslen);
3008     EVP_PKEY_CTX_free(pctx);
3009
3010     return 0;
3011 }
3012
3013 static int tls_construct_cke_dhe(SSL_CONNECTION *s, WPACKET *pkt)
3014 {
3015     EVP_PKEY *ckey = NULL, *skey = NULL;
3016     unsigned char *keybytes = NULL;
3017     int prime_len;
3018     unsigned char *encoded_pub = NULL;
3019     size_t encoded_pub_len, pad_len;
3020     int ret = 0;
3021
3022     skey = s->s3.peer_tmp;
3023     if (skey == NULL) {
3024         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3025         goto err;
3026     }
3027
3028     ckey = ssl_generate_pkey(s, skey);
3029     if (ckey == NULL) {
3030         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3031         goto err;
3032     }
3033
3034     if (ssl_derive(s, ckey, skey, 0) == 0) {
3035         /* SSLfatal() already called */
3036         goto err;
3037     }
3038
3039     /* send off the data */
3040
3041     /* Generate encoding of server key */
3042     encoded_pub_len = EVP_PKEY_get1_encoded_public_key(ckey, &encoded_pub);
3043     if (encoded_pub_len == 0) {
3044         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3045         EVP_PKEY_free(ckey);
3046         return EXT_RETURN_FAIL;
3047     }
3048
3049     /*
3050      * For interoperability with some versions of the Microsoft TLS
3051      * stack, we need to zero pad the DHE pub key to the same length
3052      * as the prime.
3053      */
3054     prime_len = EVP_PKEY_get_size(ckey);
3055     pad_len = prime_len - encoded_pub_len;
3056     if (pad_len > 0) {
3057         if (!WPACKET_sub_allocate_bytes_u16(pkt, pad_len, &keybytes)) {
3058             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3059             goto err;
3060         }
3061         memset(keybytes, 0, pad_len);
3062     }
3063
3064     if (!WPACKET_sub_memcpy_u16(pkt, encoded_pub, encoded_pub_len)) {
3065         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3066         goto err;
3067     }
3068
3069     ret = 1;
3070  err:
3071     OPENSSL_free(encoded_pub);
3072     EVP_PKEY_free(ckey);
3073     return ret;
3074 }
3075
3076 static int tls_construct_cke_ecdhe(SSL_CONNECTION *s, WPACKET *pkt)
3077 {
3078     unsigned char *encodedPoint = NULL;
3079     size_t encoded_pt_len = 0;
3080     EVP_PKEY *ckey = NULL, *skey = NULL;
3081     int ret = 0;
3082
3083     skey = s->s3.peer_tmp;
3084     if (skey == NULL) {
3085         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3086         return 0;
3087     }
3088
3089     ckey = ssl_generate_pkey(s, skey);
3090     if (ckey == NULL) {
3091         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SSL_LIB);
3092         goto err;
3093     }
3094
3095     if (ssl_derive(s, ckey, skey, 0) == 0) {
3096         /* SSLfatal() already called */
3097         goto err;
3098     }
3099
3100     /* Generate encoding of client key */
3101     encoded_pt_len = EVP_PKEY_get1_encoded_public_key(ckey, &encodedPoint);
3102
3103     if (encoded_pt_len == 0) {
3104         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EC_LIB);
3105         goto err;
3106     }
3107
3108     if (!WPACKET_sub_memcpy_u8(pkt, encodedPoint, encoded_pt_len)) {
3109         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3110         goto err;
3111     }
3112
3113     ret = 1;
3114  err:
3115     OPENSSL_free(encodedPoint);
3116     EVP_PKEY_free(ckey);
3117     return ret;
3118 }
3119
3120 static int tls_construct_cke_gost(SSL_CONNECTION *s, WPACKET *pkt)
3121 {
3122 #ifndef OPENSSL_NO_GOST
3123     /* GOST key exchange message creation */
3124     EVP_PKEY_CTX *pkey_ctx = NULL;
3125     X509 *peer_cert;
3126     size_t msglen;
3127     unsigned int md_len;
3128     unsigned char shared_ukm[32], tmp[256];
3129     EVP_MD_CTX *ukm_hash = NULL;
3130     int dgst_nid = NID_id_GostR3411_94;
3131     unsigned char *pms = NULL;
3132     size_t pmslen = 0;
3133     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
3134
3135     if ((s->s3.tmp.new_cipher->algorithm_auth & SSL_aGOST12) != 0)
3136         dgst_nid = NID_id_GostR3411_2012_256;
3137
3138     /*
3139      * Get server certificate PKEY and create ctx from it
3140      */
3141     peer_cert = s->session->peer;
3142     if (peer_cert == NULL) {
3143         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
3144                  SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
3145         return 0;
3146     }
3147
3148     pkey_ctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx,
3149                                           X509_get0_pubkey(peer_cert),
3150                                           sctx->propq);
3151     if (pkey_ctx == NULL) {
3152         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
3153         return 0;
3154     }
3155     /*
3156      * If we have send a certificate, and certificate key
3157      * parameters match those of server certificate, use
3158      * certificate key for key exchange
3159      */
3160
3161     /* Otherwise, generate ephemeral key pair */
3162     pmslen = 32;
3163     pms = OPENSSL_malloc(pmslen);
3164     if (pms == NULL) {
3165         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
3166         goto err;
3167     }
3168
3169     if (EVP_PKEY_encrypt_init(pkey_ctx) <= 0
3170         /* Generate session key
3171          */
3172         || RAND_bytes_ex(sctx->libctx, pms, pmslen, 0) <= 0) {
3173         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3174         goto err;
3175     };
3176     /*
3177      * Compute shared IV and store it in algorithm-specific context
3178      * data
3179      */
3180     ukm_hash = EVP_MD_CTX_new();
3181     if (ukm_hash == NULL
3182         || EVP_DigestInit(ukm_hash, EVP_get_digestbynid(dgst_nid)) <= 0
3183         || EVP_DigestUpdate(ukm_hash, s->s3.client_random,
3184                             SSL3_RANDOM_SIZE) <= 0
3185         || EVP_DigestUpdate(ukm_hash, s->s3.server_random,
3186                             SSL3_RANDOM_SIZE) <= 0
3187         || EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len) <= 0) {
3188         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3189         goto err;
3190     }
3191     EVP_MD_CTX_free(ukm_hash);
3192     ukm_hash = NULL;
3193     if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT,
3194                           EVP_PKEY_CTRL_SET_IV, 8, shared_ukm) <= 0) {
3195         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
3196         goto err;
3197     }
3198     /* Make GOST keytransport blob message */
3199     /*
3200      * Encapsulate it into sequence
3201      */
3202     msglen = 255;
3203     if (EVP_PKEY_encrypt(pkey_ctx, tmp, &msglen, pms, pmslen) <= 0) {
3204         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
3205         goto err;
3206     }
3207
3208     if (!WPACKET_put_bytes_u8(pkt, V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED)
3209             || (msglen >= 0x80 && !WPACKET_put_bytes_u8(pkt, 0x81))
3210             || !WPACKET_sub_memcpy_u8(pkt, tmp, msglen)) {
3211         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3212         goto err;
3213     }
3214
3215     EVP_PKEY_CTX_free(pkey_ctx);
3216     s->s3.tmp.pms = pms;
3217     s->s3.tmp.pmslen = pmslen;
3218
3219     return 1;
3220  err:
3221     EVP_PKEY_CTX_free(pkey_ctx);
3222     OPENSSL_clear_free(pms, pmslen);
3223     EVP_MD_CTX_free(ukm_hash);
3224     return 0;
3225 #else
3226     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3227     return 0;
3228 #endif
3229 }
3230
3231 #ifndef OPENSSL_NO_GOST
3232 int ossl_gost18_cke_cipher_nid(const SSL_CONNECTION *s)
3233 {
3234     if ((s->s3.tmp.new_cipher->algorithm_enc & SSL_MAGMA) != 0)
3235         return NID_magma_ctr;
3236     else if ((s->s3.tmp.new_cipher->algorithm_enc & SSL_KUZNYECHIK) != 0)
3237         return NID_kuznyechik_ctr;
3238
3239     return NID_undef;
3240 }
3241
3242 int ossl_gost_ukm(const SSL_CONNECTION *s, unsigned char *dgst_buf)
3243 {
3244     EVP_MD_CTX * hash = NULL;
3245     unsigned int md_len;
3246     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
3247     const EVP_MD *md = ssl_evp_md_fetch(sctx->libctx, NID_id_GostR3411_2012_256,
3248                                         sctx->propq);
3249
3250     if (md == NULL)
3251         return 0;
3252
3253     if ((hash = EVP_MD_CTX_new()) == NULL
3254         || EVP_DigestInit(hash, md) <= 0
3255         || EVP_DigestUpdate(hash, s->s3.client_random, SSL3_RANDOM_SIZE) <= 0
3256         || EVP_DigestUpdate(hash, s->s3.server_random, SSL3_RANDOM_SIZE) <= 0
3257         || EVP_DigestFinal_ex(hash, dgst_buf, &md_len) <= 0) {
3258         EVP_MD_CTX_free(hash);
3259         ssl_evp_md_free(md);
3260         return 0;
3261     }
3262
3263     EVP_MD_CTX_free(hash);
3264     ssl_evp_md_free(md);
3265     return 1;
3266 }
3267 #endif
3268
3269 static int tls_construct_cke_gost18(SSL_CONNECTION *s, WPACKET *pkt)
3270 {
3271 #ifndef OPENSSL_NO_GOST
3272     /* GOST 2018 key exchange message creation */
3273     unsigned char rnd_dgst[32];
3274     unsigned char *encdata = NULL;
3275     EVP_PKEY_CTX *pkey_ctx = NULL;
3276     X509 *peer_cert;
3277     unsigned char *pms = NULL;
3278     size_t pmslen = 0;
3279     size_t msglen;
3280     int cipher_nid = ossl_gost18_cke_cipher_nid(s);
3281     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
3282
3283     if (cipher_nid == NID_undef) {
3284         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3285         return 0;
3286     }
3287
3288     if (ossl_gost_ukm(s, rnd_dgst) <= 0) {
3289         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3290         goto err;
3291     }
3292
3293     /* Pre-master secret - random bytes */
3294     pmslen = 32;
3295     pms = OPENSSL_malloc(pmslen);
3296     if (pms == NULL) {
3297         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
3298         goto err;
3299     }
3300
3301     if (RAND_bytes_ex(sctx->libctx, pms, pmslen, 0) <= 0) {
3302         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3303         goto err;
3304     }
3305
3306      /* Get server certificate PKEY and create ctx from it */
3307     peer_cert = s->session->peer;
3308     if (peer_cert == NULL) {
3309         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
3310                  SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
3311         goto err;
3312     }
3313
3314     pkey_ctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx,
3315                                           X509_get0_pubkey(peer_cert),
3316                                           sctx->propq);
3317     if (pkey_ctx == NULL) {
3318         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
3319         goto err;
3320     }
3321
3322     if (EVP_PKEY_encrypt_init(pkey_ctx) <= 0) {
3323         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3324         goto err;
3325     };
3326
3327     /* Reuse EVP_PKEY_CTRL_SET_IV, make choice in engine code */
3328     if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT,
3329                           EVP_PKEY_CTRL_SET_IV, 32, rnd_dgst) <= 0) {
3330         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
3331         goto err;
3332     }
3333
3334     if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT,
3335                           EVP_PKEY_CTRL_CIPHER, cipher_nid, NULL) <= 0) {
3336         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
3337         goto err;
3338     }
3339
3340     if (EVP_PKEY_encrypt(pkey_ctx, NULL, &msglen, pms, pmslen) <= 0) {
3341         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
3342         goto err;
3343     }
3344
3345     if (!WPACKET_allocate_bytes(pkt, msglen, &encdata)
3346             || EVP_PKEY_encrypt(pkey_ctx, encdata, &msglen, pms, pmslen) <= 0) {
3347         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
3348         goto err;
3349     }
3350
3351     EVP_PKEY_CTX_free(pkey_ctx);
3352     pkey_ctx = NULL;
3353     s->s3.tmp.pms = pms;
3354     s->s3.tmp.pmslen = pmslen;
3355
3356     return 1;
3357  err:
3358     EVP_PKEY_CTX_free(pkey_ctx);
3359     OPENSSL_clear_free(pms, pmslen);
3360     return 0;
3361 #else
3362     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3363     return 0;
3364 #endif
3365 }
3366
3367 static int tls_construct_cke_srp(SSL_CONNECTION *s, WPACKET *pkt)
3368 {
3369 #ifndef OPENSSL_NO_SRP
3370     unsigned char *abytes = NULL;
3371
3372     if (s->srp_ctx.A == NULL
3373             || !WPACKET_sub_allocate_bytes_u16(pkt, BN_num_bytes(s->srp_ctx.A),
3374                                                &abytes)) {
3375         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3376         return 0;
3377     }
3378     BN_bn2bin(s->srp_ctx.A, abytes);
3379
3380     OPENSSL_free(s->session->srp_username);
3381     s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);
3382     if (s->session->srp_username == NULL) {
3383         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
3384         return 0;
3385     }
3386
3387     return 1;
3388 #else
3389     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3390     return 0;
3391 #endif
3392 }
3393
3394 CON_FUNC_RETURN tls_construct_client_key_exchange(SSL_CONNECTION *s,
3395                                                   WPACKET *pkt)
3396 {
3397     unsigned long alg_k;
3398
3399     alg_k = s->s3.tmp.new_cipher->algorithm_mkey;
3400
3401     /*
3402      * All of the construct functions below call SSLfatal() if necessary so
3403      * no need to do so here.
3404      */
3405     if ((alg_k & SSL_PSK)
3406         && !tls_construct_cke_psk_preamble(s, pkt))
3407         goto err;
3408
3409     if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
3410         if (!tls_construct_cke_rsa(s, pkt))
3411             goto err;
3412     } else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
3413         if (!tls_construct_cke_dhe(s, pkt))
3414             goto err;
3415     } else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
3416         if (!tls_construct_cke_ecdhe(s, pkt))
3417             goto err;
3418     } else if (alg_k & SSL_kGOST) {
3419         if (!tls_construct_cke_gost(s, pkt))
3420             goto err;
3421     } else if (alg_k & SSL_kGOST18) {
3422         if (!tls_construct_cke_gost18(s, pkt))
3423             goto err;
3424     } else if (alg_k & SSL_kSRP) {
3425         if (!tls_construct_cke_srp(s, pkt))
3426             goto err;
3427     } else if (!(alg_k & SSL_kPSK)) {
3428         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3429         goto err;
3430     }
3431
3432     return CON_FUNC_SUCCESS;
3433  err:
3434     OPENSSL_clear_free(s->s3.tmp.pms, s->s3.tmp.pmslen);
3435     s->s3.tmp.pms = NULL;
3436     s->s3.tmp.pmslen = 0;
3437 #ifndef OPENSSL_NO_PSK
3438     OPENSSL_clear_free(s->s3.tmp.psk, s->s3.tmp.psklen);
3439     s->s3.tmp.psk = NULL;
3440     s->s3.tmp.psklen = 0;
3441 #endif
3442     return CON_FUNC_ERROR;
3443 }
3444
3445 int tls_client_key_exchange_post_work(SSL_CONNECTION *s)
3446 {
3447     unsigned char *pms = NULL;
3448     size_t pmslen = 0;
3449
3450     pms = s->s3.tmp.pms;
3451     pmslen = s->s3.tmp.pmslen;
3452
3453 #ifndef OPENSSL_NO_SRP
3454     /* Check for SRP */
3455     if (s->s3.tmp.new_cipher->algorithm_mkey & SSL_kSRP) {
3456         if (!srp_generate_client_master_secret(s)) {
3457             /* SSLfatal() already called */
3458             goto err;
3459         }
3460         return 1;
3461     }
3462 #endif
3463
3464     if (pms == NULL && !(s->s3.tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
3465         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_PASSED_INVALID_ARGUMENT);
3466         goto err;
3467     }
3468     if (!ssl_generate_master_secret(s, pms, pmslen, 1)) {
3469         /* SSLfatal() already called */
3470         /* ssl_generate_master_secret frees the pms even on error */
3471         pms = NULL;
3472         pmslen = 0;
3473         goto err;
3474     }
3475     pms = NULL;
3476     pmslen = 0;
3477
3478 #ifndef OPENSSL_NO_SCTP
3479     if (SSL_CONNECTION_IS_DTLS(s)) {
3480         unsigned char sctpauthkey[64];
3481         char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
3482         size_t labellen;
3483         SSL *ssl = SSL_CONNECTION_GET_SSL(s);
3484
3485         /*
3486          * Add new shared key for SCTP-Auth, will be ignored if no SCTP
3487          * used.
3488          */
3489         memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
3490                sizeof(DTLS1_SCTP_AUTH_LABEL));
3491
3492         /* Don't include the terminating zero. */
3493         labellen = sizeof(labelbuffer) - 1;
3494         if (s->mode & SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG)
3495             labellen += 1;
3496
3497         if (SSL_export_keying_material(ssl, sctpauthkey,
3498                                        sizeof(sctpauthkey), labelbuffer,
3499                                        labellen, NULL, 0, 0) <= 0) {
3500             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3501             goto err;
3502         }
3503
3504         BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
3505                  sizeof(sctpauthkey), sctpauthkey);
3506     }
3507 #endif
3508
3509     return 1;
3510  err:
3511     OPENSSL_clear_free(pms, pmslen);
3512     s->s3.tmp.pms = NULL;
3513     s->s3.tmp.pmslen = 0;
3514     return 0;
3515 }
3516
3517 /*
3518  * Check a certificate can be used for client authentication. Currently check
3519  * cert exists, if we have a suitable digest for TLS 1.2 if static DH client
3520  * certificates can be used and optionally checks suitability for Suite B.
3521  */
3522 static int ssl3_check_client_certificate(SSL_CONNECTION *s)
3523 {
3524     /* If no suitable signature algorithm can't use certificate */
3525     if (!tls_choose_sigalg(s, 0) || s->s3.tmp.sigalg == NULL)
3526         return 0;
3527     /*
3528      * If strict mode check suitability of chain before using it. This also
3529      * adjusts suite B digest if necessary.
3530      */
3531     if (s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT &&
3532         !tls1_check_chain(s, NULL, NULL, NULL, -2))
3533         return 0;
3534     return 1;
3535 }
3536
3537 WORK_STATE tls_prepare_client_certificate(SSL_CONNECTION *s, WORK_STATE wst)
3538 {
3539     X509 *x509 = NULL;
3540     EVP_PKEY *pkey = NULL;
3541     int i;
3542     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
3543
3544     if (wst == WORK_MORE_A) {
3545         /* Let cert callback update client certificates if required */
3546         if (s->cert->cert_cb) {
3547             i = s->cert->cert_cb(ssl, s->cert->cert_cb_arg);
3548             if (i < 0) {
3549                 s->rwstate = SSL_X509_LOOKUP;
3550                 return WORK_MORE_A;
3551             }
3552             if (i == 0) {
3553                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_CALLBACK_FAILED);
3554                 return WORK_ERROR;
3555             }
3556             s->rwstate = SSL_NOTHING;
3557         }
3558         if (ssl3_check_client_certificate(s)) {
3559             if (s->post_handshake_auth == SSL_PHA_REQUESTED) {
3560                 return WORK_FINISHED_STOP;
3561             }
3562             return WORK_FINISHED_CONTINUE;
3563         }
3564
3565         /* Fall through to WORK_MORE_B */
3566         wst = WORK_MORE_B;
3567     }
3568
3569     /* We need to get a client cert */
3570     if (wst == WORK_MORE_B) {
3571         /*
3572          * If we get an error, we need to ssl->rwstate=SSL_X509_LOOKUP;
3573          * return(-1); We then get retied later
3574          */
3575         i = ssl_do_client_cert_cb(s, &x509, &pkey);
3576         if (i < 0) {
3577             s->rwstate = SSL_X509_LOOKUP;
3578             return WORK_MORE_B;
3579         }
3580         s->rwstate = SSL_NOTHING;
3581         if ((i == 1) && (pkey != NULL) && (x509 != NULL)) {
3582             if (!SSL_use_certificate(ssl, x509)
3583                 || !SSL_use_PrivateKey(ssl, pkey))
3584                 i = 0;
3585         } else if (i == 1) {
3586             i = 0;
3587             ERR_raise(ERR_LIB_SSL, SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
3588         }
3589
3590         X509_free(x509);
3591         EVP_PKEY_free(pkey);
3592         if (i && !ssl3_check_client_certificate(s))
3593             i = 0;
3594         if (i == 0) {
3595             if (s->version == SSL3_VERSION) {
3596                 s->s3.tmp.cert_req = 0;
3597                 ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_CERTIFICATE);
3598                 return WORK_FINISHED_CONTINUE;
3599             } else {
3600                 s->s3.tmp.cert_req = 2;
3601                 s->ext.compress_certificate_from_peer[0] = TLSEXT_comp_cert_none;
3602                 if (!ssl3_digest_cached_records(s, 0)) {
3603                     /* SSLfatal() already called */
3604                     return WORK_ERROR;
3605                 }
3606             }
3607         }
3608
3609         if (!SSL_CONNECTION_IS_TLS13(s)
3610                 || (s->options & SSL_OP_NO_TX_CERTIFICATE_COMPRESSION) != 0)
3611             s->ext.compress_certificate_from_peer[0] = TLSEXT_comp_cert_none;
3612
3613         if (s->post_handshake_auth == SSL_PHA_REQUESTED)
3614             return WORK_FINISHED_STOP;
3615         return WORK_FINISHED_CONTINUE;
3616     }
3617
3618     /* Shouldn't ever get here */
3619     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3620     return WORK_ERROR;
3621 }
3622
3623 CON_FUNC_RETURN tls_construct_client_certificate(SSL_CONNECTION *s,
3624                                                  WPACKET *pkt)
3625 {
3626     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
3627
3628     if (SSL_CONNECTION_IS_TLS13(s)) {
3629         if (s->pha_context == NULL) {
3630             /* no context available, add 0-length context */
3631             if (!WPACKET_put_bytes_u8(pkt, 0)) {
3632                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3633                 return CON_FUNC_ERROR;
3634             }
3635         } else if (!WPACKET_sub_memcpy_u8(pkt, s->pha_context, s->pha_context_len)) {
3636             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3637             return CON_FUNC_ERROR;
3638         }
3639     }
3640     if (!ssl3_output_cert_chain(s, pkt,
3641                                 (s->s3.tmp.cert_req == 2) ? NULL
3642                                                            : s->cert->key, 0)) {
3643         /* SSLfatal() already called */
3644         return CON_FUNC_ERROR;
3645     }
3646
3647     if (SSL_CONNECTION_IS_TLS13(s)
3648             && SSL_IS_FIRST_HANDSHAKE(s)
3649             && (!ssl->method->ssl3_enc->change_cipher_state(s,
3650                     SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE))) {
3651         /*
3652          * This is a fatal error, which leaves enc_write_ctx in an inconsistent
3653          * state and thus ssl3_send_alert may crash.
3654          */
3655         SSLfatal(s, SSL_AD_NO_ALERT, SSL_R_CANNOT_CHANGE_CIPHER);
3656         return CON_FUNC_ERROR;
3657     }
3658
3659     return CON_FUNC_SUCCESS;
3660 }
3661
3662 #ifndef OPENSSL_NO_COMP_ALG
3663 CON_FUNC_RETURN tls_construct_client_compressed_certificate(SSL_CONNECTION *sc,
3664                                                             WPACKET *pkt)
3665 {
3666     SSL *ssl = SSL_CONNECTION_GET_SSL(sc);
3667     WPACKET tmppkt;
3668     BUF_MEM *buf = NULL;
3669     size_t length;
3670     size_t max_length;
3671     COMP_METHOD *method;
3672     COMP_CTX *comp = NULL;
3673     int comp_len;
3674     int ret = 0;
3675     int alg = sc->ext.compress_certificate_from_peer[0];
3676
3677     /* Note that sc->s3.tmp.cert_req == 2 is checked in write transition */
3678
3679     if ((buf = BUF_MEM_new()) == NULL || !WPACKET_init(&tmppkt, buf))
3680         goto err;
3681
3682     /* Use the |tmppkt| for the to-be-compressed data */
3683     if (sc->pha_context == NULL) {
3684         /* no context available, add 0-length context */
3685         if (!WPACKET_put_bytes_u8(&tmppkt, 0))
3686             goto err;
3687     } else if (!WPACKET_sub_memcpy_u8(&tmppkt, sc->pha_context, sc->pha_context_len))
3688         goto err;
3689
3690     if (!ssl3_output_cert_chain(sc, &tmppkt, sc->cert->key, 0)) {
3691         /* SSLfatal() already called */
3692         goto out;
3693     }
3694
3695     /* continue with the real |pkt| */
3696     if (!WPACKET_put_bytes_u16(pkt, alg)
3697             || !WPACKET_get_total_written(&tmppkt, &length)
3698             || !WPACKET_put_bytes_u24(pkt, length))
3699         goto err;
3700
3701     switch (alg) {
3702     case TLSEXT_comp_cert_zlib:
3703         method = COMP_zlib_oneshot();
3704         break;
3705     case TLSEXT_comp_cert_brotli:
3706         method = COMP_brotli_oneshot();
3707         break;
3708     case TLSEXT_comp_cert_zstd:
3709         method = COMP_zstd_oneshot();
3710         break;
3711     default:
3712         goto err;
3713     }
3714     max_length = ossl_calculate_comp_expansion(alg, length);
3715
3716     if ((comp = COMP_CTX_new(method)) == NULL
3717             || !WPACKET_start_sub_packet_u24(pkt)
3718             || !WPACKET_reserve_bytes(pkt, max_length, NULL))
3719         goto err;
3720
3721     comp_len = COMP_compress_block(comp, WPACKET_get_curr(pkt), max_length,
3722                                    (unsigned char *)buf->data, length);
3723     if (comp_len <= 0)
3724         goto err;
3725
3726     if (!WPACKET_allocate_bytes(pkt, comp_len, NULL)
3727             || !WPACKET_close(pkt))
3728         goto err;
3729
3730     if (SSL_IS_FIRST_HANDSHAKE(sc)
3731             && (!ssl->method->ssl3_enc->change_cipher_state(sc,
3732                     SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE))) {
3733         /*
3734          * This is a fatal error, which leaves sc->enc_write_ctx in an
3735          * inconsistent state and thus ssl3_send_alert may crash.
3736          */
3737         SSLfatal(sc, SSL_AD_NO_ALERT, SSL_R_CANNOT_CHANGE_CIPHER);
3738         goto out;
3739     }
3740     ret = 1;
3741     goto out;
3742
3743  err:
3744     SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3745  out:
3746     if (buf != NULL) {
3747         /* If |buf| is NULL, then |tmppkt| could not have been initialized */
3748         WPACKET_cleanup(&tmppkt);
3749     }
3750     BUF_MEM_free(buf);
3751     COMP_CTX_free(comp);
3752     return ret;
3753 }
3754 #endif
3755
3756 int ssl3_check_cert_and_algorithm(SSL_CONNECTION *s)
3757 {
3758     const SSL_CERT_LOOKUP *clu;
3759     size_t idx;
3760     long alg_k, alg_a;
3761
3762     alg_k = s->s3.tmp.new_cipher->algorithm_mkey;
3763     alg_a = s->s3.tmp.new_cipher->algorithm_auth;
3764
3765     /* we don't have a certificate */
3766     if (!(alg_a & SSL_aCERT))
3767         return 1;
3768
3769     /* This is the passed certificate */
3770     clu = ssl_cert_lookup_by_pkey(X509_get0_pubkey(s->session->peer), &idx);
3771
3772     /* Check certificate is recognised and suitable for cipher */
3773     if (clu == NULL || (alg_a & clu->amask) == 0) {
3774         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_MISSING_SIGNING_CERT);
3775         return 0;
3776     }
3777
3778     if (clu->amask & SSL_aECDSA) {
3779         if (ssl_check_srvr_ecc_cert_and_alg(s->session->peer, s))
3780             return 1;
3781         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_BAD_ECC_CERT);
3782         return 0;
3783     }
3784
3785     if (alg_k & (SSL_kRSA | SSL_kRSAPSK) && idx != SSL_PKEY_RSA) {
3786         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
3787                  SSL_R_MISSING_RSA_ENCRYPTING_CERT);
3788         return 0;
3789     }
3790
3791     if ((alg_k & SSL_kDHE) && (s->s3.peer_tmp == NULL)) {
3792         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3793         return 0;
3794     }
3795
3796     return 1;
3797 }
3798
3799 #ifndef OPENSSL_NO_NEXTPROTONEG
3800 CON_FUNC_RETURN tls_construct_next_proto(SSL_CONNECTION *s, WPACKET *pkt)
3801 {
3802     size_t len, padding_len;
3803     unsigned char *padding = NULL;
3804
3805     len = s->ext.npn_len;
3806     padding_len = 32 - ((len + 2) % 32);
3807
3808     if (!WPACKET_sub_memcpy_u8(pkt, s->ext.npn, len)
3809             || !WPACKET_sub_allocate_bytes_u8(pkt, padding_len, &padding)) {
3810         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3811         return CON_FUNC_ERROR;
3812     }
3813
3814     memset(padding, 0, padding_len);
3815
3816     return CON_FUNC_SUCCESS;
3817 }
3818 #endif
3819
3820 MSG_PROCESS_RETURN tls_process_hello_req(SSL_CONNECTION *s, PACKET *pkt)
3821 {
3822     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
3823
3824     if (PACKET_remaining(pkt) > 0) {
3825         /* should contain no data */
3826         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
3827         return MSG_PROCESS_ERROR;
3828     }
3829
3830     if ((s->options & SSL_OP_NO_RENEGOTIATION)) {
3831         ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
3832         return MSG_PROCESS_FINISHED_READING;
3833     }
3834
3835     /*
3836      * This is a historical discrepancy (not in the RFC) maintained for
3837      * compatibility reasons. If a TLS client receives a HelloRequest it will
3838      * attempt an abbreviated handshake. However if a DTLS client receives a
3839      * HelloRequest it will do a full handshake. Either behaviour is reasonable
3840      * but doing one for TLS and another for DTLS is odd.
3841      */
3842     if (SSL_CONNECTION_IS_DTLS(s))
3843         SSL_renegotiate(ssl);
3844     else
3845         SSL_renegotiate_abbreviated(ssl);
3846
3847     return MSG_PROCESS_FINISHED_READING;
3848 }
3849
3850 static MSG_PROCESS_RETURN tls_process_encrypted_extensions(SSL_CONNECTION *s,
3851                                                            PACKET *pkt)
3852 {
3853     PACKET extensions;
3854     RAW_EXTENSION *rawexts = NULL;
3855
3856     if (!PACKET_as_length_prefixed_2(pkt, &extensions)
3857             || PACKET_remaining(pkt) != 0) {
3858         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
3859         goto err;
3860     }
3861
3862     if (!tls_collect_extensions(s, &extensions,
3863                                 SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS, &rawexts,
3864                                 NULL, 1)
3865             || !tls_parse_all_extensions(s, SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
3866                                          rawexts, NULL, 0, 1)) {
3867         /* SSLfatal() already called */
3868         goto err;
3869     }
3870
3871     OPENSSL_free(rawexts);
3872     return MSG_PROCESS_CONTINUE_READING;
3873
3874  err:
3875     OPENSSL_free(rawexts);
3876     return MSG_PROCESS_ERROR;
3877 }
3878
3879 int ssl_do_client_cert_cb(SSL_CONNECTION *s, X509 **px509, EVP_PKEY **ppkey)
3880 {
3881     int i = 0;
3882     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
3883
3884 #ifndef OPENSSL_NO_ENGINE
3885     if (sctx->client_cert_engine) {
3886         i = tls_engine_load_ssl_client_cert(s, px509, ppkey);
3887         if (i != 0)
3888             return i;
3889     }
3890 #endif
3891     if (sctx->client_cert_cb)
3892         i = sctx->client_cert_cb(SSL_CONNECTION_GET_SSL(s), px509, ppkey);
3893     return i;
3894 }
3895
3896 int ssl_cipher_list_to_bytes(SSL_CONNECTION *s, STACK_OF(SSL_CIPHER) *sk,
3897                              WPACKET *pkt)
3898 {
3899     int i;
3900     size_t totlen = 0, len, maxlen, maxverok = 0;
3901     int empty_reneg_info_scsv = !s->renegotiate;
3902     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
3903
3904     /* Set disabled masks for this session */
3905     if (!ssl_set_client_disabled(s)) {
3906         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_NO_PROTOCOLS_AVAILABLE);
3907         return 0;
3908     }
3909
3910     if (sk == NULL) {
3911         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3912         return 0;
3913     }
3914
3915 #ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH
3916 # if OPENSSL_MAX_TLS1_2_CIPHER_LENGTH < 6
3917 #  error Max cipher length too short
3918 # endif
3919     /*
3920      * Some servers hang if client hello > 256 bytes as hack workaround
3921      * chop number of supported ciphers to keep it well below this if we
3922      * use TLS v1.2
3923      */
3924     if (TLS1_get_version(ssl) >= TLS1_2_VERSION)
3925         maxlen = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1;
3926     else
3927 #endif
3928         /* Maximum length that can be stored in 2 bytes. Length must be even */
3929         maxlen = 0xfffe;
3930
3931     if (empty_reneg_info_scsv)
3932         maxlen -= 2;
3933     if (s->mode & SSL_MODE_SEND_FALLBACK_SCSV)
3934         maxlen -= 2;
3935
3936     for (i = 0; i < sk_SSL_CIPHER_num(sk) && totlen < maxlen; i++) {
3937         const SSL_CIPHER *c;
3938
3939         c = sk_SSL_CIPHER_value(sk, i);
3940         /* Skip disabled ciphers */
3941         if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_SUPPORTED, 0))
3942             continue;
3943
3944         if (!ssl->method->put_cipher_by_char(c, pkt, &len)) {
3945             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3946             return 0;
3947         }
3948
3949         /* Sanity check that the maximum version we offer has ciphers enabled */
3950         if (!maxverok) {
3951             if (SSL_CONNECTION_IS_DTLS(s)) {
3952                 if (DTLS_VERSION_GE(c->max_dtls, s->s3.tmp.max_ver)
3953                         && DTLS_VERSION_LE(c->min_dtls, s->s3.tmp.max_ver))
3954                     maxverok = 1;
3955             } else {
3956                 if (c->max_tls >= s->s3.tmp.max_ver
3957                         && c->min_tls <= s->s3.tmp.max_ver)
3958                     maxverok = 1;
3959             }
3960         }
3961
3962         totlen += len;
3963     }
3964
3965     if (totlen == 0 || !maxverok) {
3966         const char *maxvertext =
3967             !maxverok
3968             ? "No ciphers enabled for max supported SSL/TLS version"
3969             : NULL;
3970
3971         SSLfatal_data(s, SSL_AD_INTERNAL_ERROR, SSL_R_NO_CIPHERS_AVAILABLE,
3972                       maxvertext);
3973         return 0;
3974     }
3975
3976     if (totlen != 0) {
3977         if (empty_reneg_info_scsv) {
3978             static SSL_CIPHER scsv = {
3979                 0, NULL, NULL, SSL3_CK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
3980             };
3981             if (!ssl->method->put_cipher_by_char(&scsv, pkt, &len)) {
3982                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3983                 return 0;
3984             }
3985         }
3986         if (s->mode & SSL_MODE_SEND_FALLBACK_SCSV) {
3987             static SSL_CIPHER scsv = {
3988                 0, NULL, NULL, SSL3_CK_FALLBACK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
3989             };
3990             if (!ssl->method->put_cipher_by_char(&scsv, pkt, &len)) {
3991                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3992                 return 0;
3993             }
3994         }
3995     }
3996
3997     return 1;
3998 }
3999
4000 CON_FUNC_RETURN tls_construct_end_of_early_data(SSL_CONNECTION *s, WPACKET *pkt)
4001 {
4002     if (s->early_data_state != SSL_EARLY_DATA_WRITE_RETRY
4003             && s->early_data_state != SSL_EARLY_DATA_FINISHED_WRITING) {
4004         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
4005         return CON_FUNC_ERROR;
4006     }
4007
4008     s->early_data_state = SSL_EARLY_DATA_FINISHED_WRITING;
4009     return CON_FUNC_SUCCESS;
4010 }