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