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