be3148df0f7db1cb0231a52836291f48768e8eca
[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 MSG_PROCESS_RETURN tls_process_server_done(SSL *s, PACKET *pkt)
2190 {
2191     if (PACKET_remaining(pkt) > 0) {
2192         /* should contain no data */
2193         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2194         SSLerr(SSL_F_TLS_PROCESS_SERVER_DONE, SSL_R_LENGTH_MISMATCH);
2195         ossl_statem_set_error(s);
2196         return MSG_PROCESS_ERROR;
2197     }
2198 #ifndef OPENSSL_NO_SRP
2199     if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) {
2200         if (SRP_Calc_A_param(s) <= 0) {
2201             SSLerr(SSL_F_TLS_PROCESS_SERVER_DONE, SSL_R_SRP_A_CALC);
2202             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2203             ossl_statem_set_error(s);
2204             return MSG_PROCESS_ERROR;
2205         }
2206     }
2207 #endif
2208
2209     /*
2210      * at this point we check that we have the required stuff from
2211      * the server
2212      */
2213     if (!ssl3_check_cert_and_algorithm(s)) {
2214         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2215         ossl_statem_set_error(s);
2216         return MSG_PROCESS_ERROR;
2217     }
2218
2219     /*
2220      * Call the ocsp status callback if needed. The |tlsext_ocsp_resp| and
2221      * |tlsext_ocsp_resplen| values will be set if we actually received a status
2222      * message, or NULL and -1 otherwise
2223      */
2224     if (s->tlsext_status_type != -1 && s->ctx->tlsext_status_cb != NULL) {
2225         int ret;
2226         ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
2227         if (ret == 0) {
2228             ssl3_send_alert(s, SSL3_AL_FATAL,
2229                             SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE);
2230             SSLerr(SSL_F_TLS_PROCESS_SERVER_DONE,
2231                    SSL_R_INVALID_STATUS_RESPONSE);
2232             return MSG_PROCESS_ERROR;
2233         }
2234         if (ret < 0) {
2235             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2236             SSLerr(SSL_F_TLS_PROCESS_SERVER_DONE, ERR_R_MALLOC_FAILURE);
2237             return MSG_PROCESS_ERROR;
2238         }
2239     }
2240 #ifndef OPENSSL_NO_CT
2241     if (s->ct_validation_callback != NULL) {
2242         /* Note we validate the SCTs whether or not we abort on error */
2243         if (!ssl_validate_ct(s) && (s->verify_mode & SSL_VERIFY_PEER)) {
2244             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2245             return MSG_PROCESS_ERROR;
2246         }
2247     }
2248 #endif
2249
2250 #ifndef OPENSSL_NO_SCTP
2251     /* Only applies to renegotiation */
2252     if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))
2253         && s->renegotiate != 0)
2254         return MSG_PROCESS_CONTINUE_PROCESSING;
2255     else
2256 #endif
2257         return MSG_PROCESS_FINISHED_READING;
2258 }
2259
2260 static int tls_construct_cke_psk_preamble(SSL *s, WPACKET *pkt, int *al)
2261 {
2262 #ifndef OPENSSL_NO_PSK
2263     int ret = 0;
2264     /*
2265      * The callback needs PSK_MAX_IDENTITY_LEN + 1 bytes to return a
2266      * \0-terminated identity. The last byte is for us for simulating
2267      * strnlen.
2268      */
2269     char identity[PSK_MAX_IDENTITY_LEN + 1];
2270     size_t identitylen = 0;
2271     unsigned char psk[PSK_MAX_PSK_LEN];
2272     unsigned char *tmppsk = NULL;
2273     char *tmpidentity = NULL;
2274     size_t psklen = 0;
2275
2276     if (s->psk_client_callback == NULL) {
2277         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_PSK_PREAMBLE, SSL_R_PSK_NO_CLIENT_CB);
2278         *al = SSL_AD_INTERNAL_ERROR;
2279         goto err;
2280     }
2281
2282     memset(identity, 0, sizeof(identity));
2283
2284     psklen = s->psk_client_callback(s, s->session->psk_identity_hint,
2285                                     identity, sizeof(identity) - 1,
2286                                     psk, sizeof(psk));
2287
2288     if (psklen > PSK_MAX_PSK_LEN) {
2289         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
2290         *al = SSL_AD_HANDSHAKE_FAILURE;
2291         goto err;
2292     } else if (psklen == 0) {
2293         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_PSK_PREAMBLE,
2294                SSL_R_PSK_IDENTITY_NOT_FOUND);
2295         *al = SSL_AD_HANDSHAKE_FAILURE;
2296         goto err;
2297     }
2298
2299     identitylen = strlen(identity);
2300     if (identitylen > PSK_MAX_IDENTITY_LEN) {
2301         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
2302         *al = SSL_AD_HANDSHAKE_FAILURE;
2303         goto err;
2304     }
2305
2306     tmppsk = OPENSSL_memdup(psk, psklen);
2307     tmpidentity = OPENSSL_strdup(identity);
2308     if (tmppsk == NULL || tmpidentity == NULL) {
2309         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_PSK_PREAMBLE, ERR_R_MALLOC_FAILURE);
2310         *al = SSL_AD_INTERNAL_ERROR;
2311         goto err;
2312     }
2313
2314     OPENSSL_free(s->s3->tmp.psk);
2315     s->s3->tmp.psk = tmppsk;
2316     s->s3->tmp.psklen = psklen;
2317     tmppsk = NULL;
2318     OPENSSL_free(s->session->psk_identity);
2319     s->session->psk_identity = tmpidentity;
2320     tmpidentity = NULL;
2321
2322     if (!WPACKET_sub_memcpy_u16(pkt, identity, identitylen))  {
2323         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
2324         *al = SSL_AD_INTERNAL_ERROR;
2325         goto err;
2326     }
2327
2328     ret = 1;
2329
2330  err:
2331     OPENSSL_cleanse(psk, psklen);
2332     OPENSSL_cleanse(identity, sizeof(identity));
2333     OPENSSL_clear_free(tmppsk, psklen);
2334     OPENSSL_clear_free(tmpidentity, identitylen);
2335
2336     return ret;
2337 #else
2338     SSLerr(SSL_F_TLS_CONSTRUCT_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
2339     *al = SSL_AD_INTERNAL_ERROR;
2340     return 0;
2341 #endif
2342 }
2343
2344 static int tls_construct_cke_rsa(SSL *s, WPACKET *pkt, int *al)
2345 {
2346 #ifndef OPENSSL_NO_RSA
2347     unsigned char *encdata = NULL;
2348     EVP_PKEY *pkey = NULL;
2349     EVP_PKEY_CTX *pctx = NULL;
2350     size_t enclen;
2351     unsigned char *pms = NULL;
2352     size_t pmslen = 0;
2353
2354     if (s->session->peer == NULL) {
2355         /*
2356          * We should always have a server certificate with SSL_kRSA.
2357          */
2358         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_RSA, ERR_R_INTERNAL_ERROR);
2359         return 0;
2360     }
2361
2362     pkey = X509_get0_pubkey(s->session->peer);
2363     if (EVP_PKEY_get0_RSA(pkey) == NULL) {
2364         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_RSA, ERR_R_INTERNAL_ERROR);
2365         return 0;
2366     }
2367
2368     pmslen = SSL_MAX_MASTER_KEY_LENGTH;
2369     pms = OPENSSL_malloc(pmslen);
2370     if (pms == NULL) {
2371         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_RSA, ERR_R_MALLOC_FAILURE);
2372         *al = SSL_AD_INTERNAL_ERROR;
2373         return 0;
2374     }
2375
2376     pms[0] = s->client_version >> 8;
2377     pms[1] = s->client_version & 0xff;
2378     /* TODO(size_t): Convert this function */
2379     if (RAND_bytes(pms + 2, (int)(pmslen - 2)) <= 0) {
2380         goto err;
2381     }
2382
2383     /* Fix buf for TLS and beyond */
2384     if (s->version > SSL3_VERSION && !WPACKET_start_sub_packet_u16(pkt)) {
2385         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_RSA, ERR_R_INTERNAL_ERROR);
2386         goto err;
2387     }
2388     pctx = EVP_PKEY_CTX_new(pkey, NULL);
2389     if (pctx == NULL || EVP_PKEY_encrypt_init(pctx) <= 0
2390         || EVP_PKEY_encrypt(pctx, NULL, &enclen, pms, pmslen) <= 0) {
2391         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_RSA, ERR_R_EVP_LIB);
2392         goto err;
2393     }
2394     if (!WPACKET_allocate_bytes(pkt, enclen, &encdata)
2395             || EVP_PKEY_encrypt(pctx, encdata, &enclen, pms, pmslen) <= 0) {
2396         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_RSA, SSL_R_BAD_RSA_ENCRYPT);
2397         goto err;
2398     }
2399     EVP_PKEY_CTX_free(pctx);
2400     pctx = NULL;
2401 # ifdef PKCS1_CHECK
2402     if (s->options & SSL_OP_PKCS1_CHECK_1)
2403         (*p)[1]++;
2404     if (s->options & SSL_OP_PKCS1_CHECK_2)
2405         tmp_buf[0] = 0x70;
2406 # endif
2407
2408     /* Fix buf for TLS and beyond */
2409     if (s->version > SSL3_VERSION && !WPACKET_close(pkt)) {
2410         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_RSA, ERR_R_INTERNAL_ERROR);
2411         goto err;
2412     }
2413
2414     s->s3->tmp.pms = pms;
2415     s->s3->tmp.pmslen = pmslen;
2416
2417     return 1;
2418  err:
2419     OPENSSL_clear_free(pms, pmslen);
2420     EVP_PKEY_CTX_free(pctx);
2421
2422     return 0;
2423 #else
2424     SSLerr(SSL_F_TLS_CONSTRUCT_CKE_RSA, ERR_R_INTERNAL_ERROR);
2425     *al = SSL_AD_INTERNAL_ERROR;
2426     return 0;
2427 #endif
2428 }
2429
2430 static int tls_construct_cke_dhe(SSL *s, WPACKET *pkt, int *al)
2431 {
2432 #ifndef OPENSSL_NO_DH
2433     DH *dh_clnt = NULL;
2434     const BIGNUM *pub_key;
2435     EVP_PKEY *ckey = NULL, *skey = NULL;
2436     unsigned char *keybytes = NULL;
2437
2438     skey = s->s3->peer_tmp;
2439     if (skey == NULL)
2440         goto err;
2441
2442     ckey = ssl_generate_pkey(skey);
2443     dh_clnt = EVP_PKEY_get0_DH(ckey);
2444
2445     if (dh_clnt == NULL || ssl_derive(s, ckey, skey, 0) == 0)
2446         goto err;
2447
2448     /* send off the data */
2449     DH_get0_key(dh_clnt, &pub_key, NULL);
2450     if (!WPACKET_sub_allocate_bytes_u16(pkt, BN_num_bytes(pub_key), &keybytes))
2451         goto err;
2452
2453     BN_bn2bin(pub_key, keybytes);
2454     EVP_PKEY_free(ckey);
2455
2456     return 1;
2457  err:
2458     EVP_PKEY_free(ckey);
2459 #endif
2460     SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR);
2461     *al = SSL_AD_INTERNAL_ERROR;
2462     return 0;
2463 }
2464
2465 static int tls_construct_cke_ecdhe(SSL *s, WPACKET *pkt, int *al)
2466 {
2467 #ifndef OPENSSL_NO_EC
2468     unsigned char *encodedPoint = NULL;
2469     size_t encoded_pt_len = 0;
2470     EVP_PKEY *ckey = NULL, *skey = NULL;
2471     int ret = 0;
2472
2473     skey = s->s3->peer_tmp;
2474     if (skey == NULL) {
2475         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR);
2476         return 0;
2477     }
2478
2479     ckey = ssl_generate_pkey(skey);
2480
2481     if (ssl_derive(s, ckey, skey, 0) == 0) {
2482         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_EVP_LIB);
2483         goto err;
2484     }
2485
2486     /* Generate encoding of client key */
2487     encoded_pt_len = EVP_PKEY_get1_tls_encodedpoint(ckey, &encodedPoint);
2488
2489     if (encoded_pt_len == 0) {
2490         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_EC_LIB);
2491         goto err;
2492     }
2493
2494     if (!WPACKET_sub_memcpy_u8(pkt, encodedPoint, encoded_pt_len)) {
2495         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR);
2496         goto err;
2497     }
2498
2499     ret = 1;
2500  err:
2501     OPENSSL_free(encodedPoint);
2502     EVP_PKEY_free(ckey);
2503     return ret;
2504 #else
2505     SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR);
2506     *al = SSL_AD_INTERNAL_ERROR;
2507     return 0;
2508 #endif
2509 }
2510
2511 static int tls_construct_cke_gost(SSL *s, WPACKET *pkt, int *al)
2512 {
2513 #ifndef OPENSSL_NO_GOST
2514     /* GOST key exchange message creation */
2515     EVP_PKEY_CTX *pkey_ctx = NULL;
2516     X509 *peer_cert;
2517     size_t msglen;
2518     unsigned int md_len;
2519     unsigned char shared_ukm[32], tmp[256];
2520     EVP_MD_CTX *ukm_hash = NULL;
2521     int dgst_nid = NID_id_GostR3411_94;
2522     unsigned char *pms = NULL;
2523     size_t pmslen = 0;
2524
2525     if ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aGOST12) != 0)
2526         dgst_nid = NID_id_GostR3411_2012_256;
2527
2528     /*
2529      * Get server sertificate PKEY and create ctx from it
2530      */
2531     peer_cert = s->session->peer;
2532     if (!peer_cert) {
2533         *al = SSL_AD_HANDSHAKE_FAILURE;
2534         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST,
2535                SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
2536         return 0;
2537     }
2538
2539     pkey_ctx = EVP_PKEY_CTX_new(X509_get0_pubkey(peer_cert), NULL);
2540     if (pkey_ctx == NULL) {
2541         *al = SSL_AD_INTERNAL_ERROR;
2542         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, ERR_R_MALLOC_FAILURE);
2543         return 0;
2544     }
2545     /*
2546      * If we have send a certificate, and certificate key
2547      * parameters match those of server certificate, use
2548      * certificate key for key exchange
2549      */
2550
2551     /* Otherwise, generate ephemeral key pair */
2552     pmslen = 32;
2553     pms = OPENSSL_malloc(pmslen);
2554     if (pms == NULL) {
2555         *al = SSL_AD_INTERNAL_ERROR;
2556         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, ERR_R_MALLOC_FAILURE);
2557         goto err;
2558     }
2559
2560     if (EVP_PKEY_encrypt_init(pkey_ctx) <= 0
2561         /* Generate session key
2562          * TODO(size_t): Convert this function
2563          */
2564         || RAND_bytes(pms, (int)pmslen) <= 0) {
2565         *al = SSL_AD_INTERNAL_ERROR;
2566         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, ERR_R_INTERNAL_ERROR);
2567         goto err;
2568     };
2569     /*
2570      * Compute shared IV and store it in algorithm-specific context
2571      * data
2572      */
2573     ukm_hash = EVP_MD_CTX_new();
2574     if (ukm_hash == NULL
2575         || EVP_DigestInit(ukm_hash, EVP_get_digestbynid(dgst_nid)) <= 0
2576         || EVP_DigestUpdate(ukm_hash, s->s3->client_random,
2577                             SSL3_RANDOM_SIZE) <= 0
2578         || EVP_DigestUpdate(ukm_hash, s->s3->server_random,
2579                             SSL3_RANDOM_SIZE) <= 0
2580         || EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len) <= 0) {
2581         *al = SSL_AD_INTERNAL_ERROR;
2582         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, ERR_R_INTERNAL_ERROR);
2583         goto err;
2584     }
2585     EVP_MD_CTX_free(ukm_hash);
2586     ukm_hash = NULL;
2587     if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT,
2588                           EVP_PKEY_CTRL_SET_IV, 8, shared_ukm) < 0) {
2589         *al = SSL_AD_INTERNAL_ERROR;
2590         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, SSL_R_LIBRARY_BUG);
2591         goto err;
2592     }
2593     /* Make GOST keytransport blob message */
2594     /*
2595      * Encapsulate it into sequence
2596      */
2597     msglen = 255;
2598     if (EVP_PKEY_encrypt(pkey_ctx, tmp, &msglen, pms, pmslen) <= 0) {
2599         *al = SSL_AD_INTERNAL_ERROR;
2600         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, SSL_R_LIBRARY_BUG);
2601         goto err;
2602     }
2603
2604     if (!WPACKET_put_bytes_u8(pkt, V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED)
2605             || (msglen >= 0x80 && !WPACKET_put_bytes_u8(pkt, 0x81))
2606             || !WPACKET_sub_memcpy_u8(pkt, tmp, msglen)) {
2607         *al = SSL_AD_INTERNAL_ERROR;
2608         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, ERR_R_INTERNAL_ERROR);
2609         goto err;
2610     }
2611
2612     EVP_PKEY_CTX_free(pkey_ctx);
2613     s->s3->tmp.pms = pms;
2614     s->s3->tmp.pmslen = pmslen;
2615
2616     return 1;
2617  err:
2618     EVP_PKEY_CTX_free(pkey_ctx);
2619     OPENSSL_clear_free(pms, pmslen);
2620     EVP_MD_CTX_free(ukm_hash);
2621     return 0;
2622 #else
2623     SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, ERR_R_INTERNAL_ERROR);
2624     *al = SSL_AD_INTERNAL_ERROR;
2625     return 0;
2626 #endif
2627 }
2628
2629 static int tls_construct_cke_srp(SSL *s, WPACKET *pkt, int *al)
2630 {
2631 #ifndef OPENSSL_NO_SRP
2632     unsigned char *abytes = NULL;
2633
2634     if (s->srp_ctx.A == NULL
2635             || !WPACKET_sub_allocate_bytes_u16(pkt, BN_num_bytes(s->srp_ctx.A),
2636                                                &abytes)) {
2637         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_SRP, ERR_R_INTERNAL_ERROR);
2638         return 0;
2639     }
2640     BN_bn2bin(s->srp_ctx.A, abytes);
2641
2642     OPENSSL_free(s->session->srp_username);
2643     s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);
2644     if (s->session->srp_username == NULL) {
2645         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_SRP, ERR_R_MALLOC_FAILURE);
2646         return 0;
2647     }
2648
2649     return 1;
2650 #else
2651     SSLerr(SSL_F_TLS_CONSTRUCT_CKE_SRP, ERR_R_INTERNAL_ERROR);
2652     *al = SSL_AD_INTERNAL_ERROR;
2653     return 0;
2654 #endif
2655 }
2656
2657 int tls_construct_client_key_exchange(SSL *s, WPACKET *pkt)
2658 {
2659     unsigned long alg_k;
2660     int al = -1;
2661
2662     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2663
2664     if ((alg_k & SSL_PSK)
2665         && !tls_construct_cke_psk_preamble(s, pkt, &al))
2666         goto err;
2667
2668     if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
2669         if (!tls_construct_cke_rsa(s, pkt, &al))
2670             goto err;
2671     } else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
2672         if (!tls_construct_cke_dhe(s, pkt, &al))
2673             goto err;
2674     } else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
2675         if (!tls_construct_cke_ecdhe(s, pkt, &al))
2676             goto err;
2677     } else if (alg_k & SSL_kGOST) {
2678         if (!tls_construct_cke_gost(s, pkt, &al))
2679             goto err;
2680     } else if (alg_k & SSL_kSRP) {
2681         if (!tls_construct_cke_srp(s, pkt, &al))
2682             goto err;
2683     } else if (!(alg_k & SSL_kPSK)) {
2684         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2685         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2686         goto err;
2687     }
2688
2689     return 1;
2690  err:
2691     if (al != -1)
2692         ssl3_send_alert(s, SSL3_AL_FATAL, al);
2693     OPENSSL_clear_free(s->s3->tmp.pms, s->s3->tmp.pmslen);
2694     s->s3->tmp.pms = NULL;
2695 #ifndef OPENSSL_NO_PSK
2696     OPENSSL_clear_free(s->s3->tmp.psk, s->s3->tmp.psklen);
2697     s->s3->tmp.psk = NULL;
2698 #endif
2699     return 0;
2700 }
2701
2702 int tls_client_key_exchange_post_work(SSL *s)
2703 {
2704     unsigned char *pms = NULL;
2705     size_t pmslen = 0;
2706
2707     pms = s->s3->tmp.pms;
2708     pmslen = s->s3->tmp.pmslen;
2709
2710 #ifndef OPENSSL_NO_SRP
2711     /* Check for SRP */
2712     if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) {
2713         if (!srp_generate_client_master_secret(s)) {
2714             SSLerr(SSL_F_TLS_CLIENT_KEY_EXCHANGE_POST_WORK,
2715                    ERR_R_INTERNAL_ERROR);
2716             goto err;
2717         }
2718         return 1;
2719     }
2720 #endif
2721
2722     if (pms == NULL && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
2723         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2724         SSLerr(SSL_F_TLS_CLIENT_KEY_EXCHANGE_POST_WORK, ERR_R_MALLOC_FAILURE);
2725         goto err;
2726     }
2727     if (!ssl_generate_master_secret(s, pms, pmslen, 1)) {
2728         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2729         SSLerr(SSL_F_TLS_CLIENT_KEY_EXCHANGE_POST_WORK, ERR_R_INTERNAL_ERROR);
2730         /* ssl_generate_master_secret frees the pms even on error */
2731         pms = NULL;
2732         pmslen = 0;
2733         goto err;
2734     }
2735     pms = NULL;
2736     pmslen = 0;
2737
2738 #ifndef OPENSSL_NO_SCTP
2739     if (SSL_IS_DTLS(s)) {
2740         unsigned char sctpauthkey[64];
2741         char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
2742
2743         /*
2744          * Add new shared key for SCTP-Auth, will be ignored if no SCTP
2745          * used.
2746          */
2747         memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
2748                sizeof(DTLS1_SCTP_AUTH_LABEL));
2749
2750         if (SSL_export_keying_material(s, sctpauthkey,
2751                                        sizeof(sctpauthkey), labelbuffer,
2752                                        sizeof(labelbuffer), NULL, 0, 0) <= 0)
2753             goto err;
2754
2755         BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
2756                  sizeof(sctpauthkey), sctpauthkey);
2757     }
2758 #endif
2759
2760     return 1;
2761  err:
2762     OPENSSL_clear_free(pms, pmslen);
2763     s->s3->tmp.pms = NULL;
2764     return 0;
2765 }
2766
2767 int tls_construct_client_verify(SSL *s, WPACKET *pkt)
2768 {
2769     EVP_PKEY *pkey;
2770     const EVP_MD *md = s->s3->tmp.md[s->cert->key - s->cert->pkeys];
2771     EVP_MD_CTX *mctx = NULL;
2772     unsigned u = 0;
2773     long hdatalen = 0;
2774     void *hdata;
2775     unsigned char *sig = NULL;
2776
2777     mctx = EVP_MD_CTX_new();
2778     if (mctx == NULL) {
2779         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_MALLOC_FAILURE);
2780         goto err;
2781     }
2782     pkey = s->cert->key->privatekey;
2783
2784     hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
2785     if (hdatalen <= 0) {
2786         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
2787         goto err;
2788     }
2789
2790     if (SSL_USE_SIGALGS(s)&& !tls12_get_sigandhash(pkt, pkey, md)) {
2791         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
2792         goto err;
2793     }
2794 #ifdef SSL_DEBUG
2795     fprintf(stderr, "Using client alg %s\n", EVP_MD_name(md));
2796 #endif
2797     sig = OPENSSL_malloc(EVP_PKEY_size(pkey));
2798     if (sig == NULL) {
2799         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_MALLOC_FAILURE);
2800         goto err;
2801     }
2802     if (!EVP_SignInit_ex(mctx, md, NULL)
2803         || !EVP_SignUpdate(mctx, hdata, hdatalen)
2804         || (s->version == SSL3_VERSION
2805             && !EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
2806                                 (int)s->session->master_key_length,
2807                                 s->session->master_key))
2808         || !EVP_SignFinal(mctx, sig, &u, pkey)) {
2809         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_EVP_LIB);
2810         goto err;
2811     }
2812 #ifndef OPENSSL_NO_GOST
2813     {
2814         int pktype = EVP_PKEY_id(pkey);
2815         if (pktype == NID_id_GostR3410_2001
2816             || pktype == NID_id_GostR3410_2012_256
2817             || pktype == NID_id_GostR3410_2012_512)
2818             BUF_reverse(sig, NULL, u);
2819     }
2820 #endif
2821
2822     if (!WPACKET_sub_memcpy_u16(pkt, sig, u)) {
2823         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
2824         goto err;
2825     }
2826
2827     /* Digest cached records and discard handshake buffer */
2828     if (!ssl3_digest_cached_records(s, 0))
2829         goto err;
2830
2831     OPENSSL_free(sig);
2832     EVP_MD_CTX_free(mctx);
2833     return 1;
2834  err:
2835     OPENSSL_free(sig);
2836     EVP_MD_CTX_free(mctx);
2837     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2838     return 0;
2839 }
2840
2841 /*
2842  * Check a certificate can be used for client authentication. Currently check
2843  * cert exists, if we have a suitable digest for TLS 1.2 if static DH client
2844  * certificates can be used and optionally checks suitability for Suite B.
2845  */
2846 static int ssl3_check_client_certificate(SSL *s)
2847 {
2848     if (!s->cert || !s->cert->key->x509 || !s->cert->key->privatekey)
2849         return 0;
2850     /* If no suitable signature algorithm can't use certificate */
2851     if (SSL_USE_SIGALGS(s) && !s->s3->tmp.md[s->cert->key - s->cert->pkeys])
2852         return 0;
2853     /*
2854      * If strict mode check suitability of chain before using it. This also
2855      * adjusts suite B digest if necessary.
2856      */
2857     if (s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT &&
2858         !tls1_check_chain(s, NULL, NULL, NULL, -2))
2859         return 0;
2860     return 1;
2861 }
2862
2863 WORK_STATE tls_prepare_client_certificate(SSL *s, WORK_STATE wst)
2864 {
2865     X509 *x509 = NULL;
2866     EVP_PKEY *pkey = NULL;
2867     int i;
2868
2869     if (wst == WORK_MORE_A) {
2870         /* Let cert callback update client certificates if required */
2871         if (s->cert->cert_cb) {
2872             i = s->cert->cert_cb(s, s->cert->cert_cb_arg);
2873             if (i < 0) {
2874                 s->rwstate = SSL_X509_LOOKUP;
2875                 return WORK_MORE_A;
2876             }
2877             if (i == 0) {
2878                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2879                 ossl_statem_set_error(s);
2880                 return 0;
2881             }
2882             s->rwstate = SSL_NOTHING;
2883         }
2884         if (ssl3_check_client_certificate(s))
2885             return WORK_FINISHED_CONTINUE;
2886
2887         /* Fall through to WORK_MORE_B */
2888         wst = WORK_MORE_B;
2889     }
2890
2891     /* We need to get a client cert */
2892     if (wst == WORK_MORE_B) {
2893         /*
2894          * If we get an error, we need to ssl->rwstate=SSL_X509_LOOKUP;
2895          * return(-1); We then get retied later
2896          */
2897         i = ssl_do_client_cert_cb(s, &x509, &pkey);
2898         if (i < 0) {
2899             s->rwstate = SSL_X509_LOOKUP;
2900             return WORK_MORE_B;
2901         }
2902         s->rwstate = SSL_NOTHING;
2903         if ((i == 1) && (pkey != NULL) && (x509 != NULL)) {
2904             if (!SSL_use_certificate(s, x509) || !SSL_use_PrivateKey(s, pkey))
2905                 i = 0;
2906         } else if (i == 1) {
2907             i = 0;
2908             SSLerr(SSL_F_TLS_PREPARE_CLIENT_CERTIFICATE,
2909                    SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
2910         }
2911
2912         X509_free(x509);
2913         EVP_PKEY_free(pkey);
2914         if (i && !ssl3_check_client_certificate(s))
2915             i = 0;
2916         if (i == 0) {
2917             if (s->version == SSL3_VERSION) {
2918                 s->s3->tmp.cert_req = 0;
2919                 ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_CERTIFICATE);
2920                 return WORK_FINISHED_CONTINUE;
2921             } else {
2922                 s->s3->tmp.cert_req = 2;
2923                 if (!ssl3_digest_cached_records(s, 0)) {
2924                     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2925                     ossl_statem_set_error(s);
2926                     return 0;
2927                 }
2928             }
2929         }
2930
2931         return WORK_FINISHED_CONTINUE;
2932     }
2933
2934     /* Shouldn't ever get here */
2935     return WORK_ERROR;
2936 }
2937
2938 int tls_construct_client_certificate(SSL *s, WPACKET *pkt)
2939 {
2940     if (!ssl3_output_cert_chain(s, pkt,
2941                                (s->s3->tmp.cert_req == 2) ? NULL
2942                                                           : s->cert->key)) {
2943         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_CERTIFICATE, ERR_R_INTERNAL_ERROR);
2944         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2945         return 0;
2946     }
2947
2948     return 1;
2949 }
2950
2951 #define has_bits(i,m)   (((i)&(m)) == (m))
2952
2953 int ssl3_check_cert_and_algorithm(SSL *s)
2954 {
2955     int i;
2956 #ifndef OPENSSL_NO_EC
2957     int idx;
2958 #endif
2959     long alg_k, alg_a;
2960     EVP_PKEY *pkey = NULL;
2961     int al = SSL_AD_HANDSHAKE_FAILURE;
2962
2963     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2964     alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2965
2966     /* we don't have a certificate */
2967     if ((alg_a & SSL_aNULL) || (alg_k & SSL_kPSK))
2968         return (1);
2969
2970     /* This is the passed certificate */
2971
2972 #ifndef OPENSSL_NO_EC
2973     idx = s->session->peer_type;
2974     if (idx == SSL_PKEY_ECC) {
2975         if (ssl_check_srvr_ecc_cert_and_alg(s->session->peer, s) == 0) {
2976             /* check failed */
2977             SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_BAD_ECC_CERT);
2978             goto f_err;
2979         } else {
2980             return 1;
2981         }
2982     } else if (alg_a & SSL_aECDSA) {
2983         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
2984                SSL_R_MISSING_ECDSA_SIGNING_CERT);
2985         goto f_err;
2986     }
2987 #endif
2988     pkey = X509_get0_pubkey(s->session->peer);
2989     i = X509_certificate_type(s->session->peer, pkey);
2990
2991     /* Check that we have a certificate if we require one */
2992     if ((alg_a & SSL_aRSA) && !has_bits(i, EVP_PK_RSA | EVP_PKT_SIGN)) {
2993         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
2994                SSL_R_MISSING_RSA_SIGNING_CERT);
2995         goto f_err;
2996     }
2997 #ifndef OPENSSL_NO_DSA
2998     else if ((alg_a & SSL_aDSS) && !has_bits(i, EVP_PK_DSA | EVP_PKT_SIGN)) {
2999         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3000                SSL_R_MISSING_DSA_SIGNING_CERT);
3001         goto f_err;
3002     }
3003 #endif
3004 #ifndef OPENSSL_NO_RSA
3005     if (alg_k & (SSL_kRSA | SSL_kRSAPSK) &&
3006         !has_bits(i, EVP_PK_RSA | EVP_PKT_ENC)) {
3007         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3008                SSL_R_MISSING_RSA_ENCRYPTING_CERT);
3009         goto f_err;
3010     }
3011 #endif
3012 #ifndef OPENSSL_NO_DH
3013     if ((alg_k & SSL_kDHE) && (s->s3->peer_tmp == NULL)) {
3014         al = SSL_AD_INTERNAL_ERROR;
3015         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR);
3016         goto f_err;
3017     }
3018 #endif
3019
3020     return (1);
3021  f_err:
3022     ssl3_send_alert(s, SSL3_AL_FATAL, al);
3023     return (0);
3024 }
3025
3026 #ifndef OPENSSL_NO_NEXTPROTONEG
3027 int tls_construct_next_proto(SSL *s, WPACKET *pkt)
3028 {
3029     size_t len, padding_len;
3030     unsigned char *padding = NULL;
3031
3032     len = s->next_proto_negotiated_len;
3033     padding_len = 32 - ((len + 2) % 32);
3034
3035     if (!WPACKET_sub_memcpy_u8(pkt, s->next_proto_negotiated, len)
3036             || !WPACKET_sub_allocate_bytes_u8(pkt, padding_len, &padding)) {
3037         SSLerr(SSL_F_TLS_CONSTRUCT_NEXT_PROTO, ERR_R_INTERNAL_ERROR);
3038         goto err;
3039     }
3040
3041     memset(padding, 0, padding_len);
3042
3043     return 1;
3044  err:
3045     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
3046     return 0;
3047 }
3048 #endif
3049
3050 int ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
3051 {
3052     int i = 0;
3053 #ifndef OPENSSL_NO_ENGINE
3054     if (s->ctx->client_cert_engine) {
3055         i = ENGINE_load_ssl_client_cert(s->ctx->client_cert_engine, s,
3056                                         SSL_get_client_CA_list(s),
3057                                         px509, ppkey, NULL, NULL, NULL);
3058         if (i != 0)
3059             return i;
3060     }
3061 #endif
3062     if (s->ctx->client_cert_cb)
3063         i = s->ctx->client_cert_cb(s, px509, ppkey);
3064     return i;
3065 }
3066
3067 int ssl_cipher_list_to_bytes(SSL *s, STACK_OF(SSL_CIPHER) *sk, WPACKET *pkt)
3068 {
3069     int i;
3070     size_t totlen = 0, len, maxlen;
3071     int empty_reneg_info_scsv = !s->renegotiate;
3072     /* Set disabled masks for this session */
3073     ssl_set_client_disabled(s);
3074
3075     if (sk == NULL)
3076         return (0);
3077
3078 #ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH
3079 # if OPENSSL_MAX_TLS1_2_CIPHER_LENGTH < 6
3080 #  error Max cipher length too short
3081 # endif
3082     /*
3083      * Some servers hang if client hello > 256 bytes as hack workaround
3084      * chop number of supported ciphers to keep it well below this if we
3085      * use TLS v1.2
3086      */
3087     if (TLS1_get_version(s) >= TLS1_2_VERSION)
3088         maxlen = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1;
3089     else
3090 #endif
3091         /* Maximum length that can be stored in 2 bytes. Length must be even */
3092         maxlen = 0xfffe;
3093
3094     if (empty_reneg_info_scsv)
3095         maxlen -= 2;
3096     if (s->mode & SSL_MODE_SEND_FALLBACK_SCSV)
3097         maxlen -= 2;
3098
3099     for (i = 0; i < sk_SSL_CIPHER_num(sk) && totlen < maxlen; i++) {
3100         const SSL_CIPHER *c;
3101
3102         c = sk_SSL_CIPHER_value(sk, i);
3103         /* Skip disabled ciphers */
3104         if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_SUPPORTED))
3105             continue;
3106
3107         if (!s->method->put_cipher_by_char(c, pkt, &len)) {
3108             SSLerr(SSL_F_SSL_CIPHER_LIST_TO_BYTES, ERR_R_INTERNAL_ERROR);
3109             return 0;
3110         }
3111
3112         totlen += len;
3113     }
3114
3115     if (totlen == 0) {
3116         SSLerr(SSL_F_SSL_CIPHER_LIST_TO_BYTES, SSL_R_NO_CIPHERS_AVAILABLE);
3117         return 0;
3118     }
3119
3120     if (totlen != 0) {
3121         if (empty_reneg_info_scsv) {
3122             static SSL_CIPHER scsv = {
3123                 0, NULL, SSL3_CK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
3124             };
3125             if (!s->method->put_cipher_by_char(&scsv, pkt, &len)) {
3126                 SSLerr(SSL_F_SSL_CIPHER_LIST_TO_BYTES, ERR_R_INTERNAL_ERROR);
3127                 return 0;
3128             }
3129         }
3130         if (s->mode & SSL_MODE_SEND_FALLBACK_SCSV) {
3131             static SSL_CIPHER scsv = {
3132                 0, NULL, SSL3_CK_FALLBACK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
3133             };
3134             if (!s->method->put_cipher_by_char(&scsv, pkt, &len)) {
3135                 SSLerr(SSL_F_SSL_CIPHER_LIST_TO_BYTES, ERR_R_INTERNAL_ERROR);
3136                 return 0;
3137             }
3138         }
3139     }
3140
3141     return 1;
3142 }