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