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