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