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