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