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