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