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