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