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