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