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