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