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