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