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