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