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