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