Fix error when server does not send CertificateStatus message
[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             return SSL3_RT_MAX_PLAIN_LENGTH;
700
701         case TLS_ST_CR_SRVR_DONE:
702             return SERVER_HELLO_DONE_MAX_LENGTH;
703
704         case TLS_ST_CR_CHANGE:
705             return CCS_MAX_LENGTH;
706
707         case TLS_ST_CR_SESSION_TICKET:
708             return SSL3_RT_MAX_PLAIN_LENGTH;
709
710         case TLS_ST_CR_FINISHED:
711             return FINISHED_MAX_LENGTH;
712
713         default:
714             /* Shouldn't happen */
715             break;
716     }
717
718     return 0;
719 }
720
721 /*
722  * Process a message that the client has been received from the server.
723  */
724 MSG_PROCESS_RETURN ossl_statem_client_process_message(SSL *s, PACKET *pkt)
725 {
726     OSSL_STATEM *st = &s->statem;
727
728     switch(st->hand_state) {
729         case TLS_ST_CR_SRVR_HELLO:
730             return tls_process_server_hello(s, pkt);
731
732         case DTLS_ST_CR_HELLO_VERIFY_REQUEST:
733             return dtls_process_hello_verify(s, pkt);
734
735         case TLS_ST_CR_CERT:
736             return tls_process_server_certificate(s, pkt);
737
738         case TLS_ST_CR_CERT_STATUS:
739             return tls_process_cert_status(s, pkt);
740
741         case TLS_ST_CR_KEY_EXCH:
742             return tls_process_key_exchange(s, pkt);
743
744         case TLS_ST_CR_CERT_REQ:
745             return tls_process_certificate_request(s, pkt);
746
747         case TLS_ST_CR_SRVR_DONE:
748             return tls_process_server_done(s, pkt);
749
750         case TLS_ST_CR_CHANGE:
751             return tls_process_change_cipher_spec(s, pkt);
752
753         case TLS_ST_CR_SESSION_TICKET:
754             return tls_process_new_session_ticket(s, pkt);
755
756         case TLS_ST_CR_FINISHED:
757             return tls_process_finished(s, pkt);
758
759         default:
760             /* Shouldn't happen */
761             break;
762     }
763
764     return MSG_PROCESS_ERROR;
765 }
766
767 /*
768  * Perform any further processing required following the receipt of a message
769  * from the server
770  */
771 WORK_STATE ossl_statem_client_post_process_message(SSL *s, WORK_STATE wst)
772 {
773     OSSL_STATEM *st = &s->statem;
774
775     switch(st->hand_state) {
776 #ifndef OPENSSL_NO_SCTP
777     case TLS_ST_CR_SRVR_DONE:
778         /* We only get here if we are using SCTP and we are renegotiating */
779         if (BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
780             s->s3->in_read_app_data = 2;
781             s->rwstate = SSL_READING;
782             BIO_clear_retry_flags(SSL_get_rbio(s));
783             BIO_set_retry_read(SSL_get_rbio(s));
784             ossl_statem_set_sctp_read_sock(s, 1);
785             return WORK_MORE_A;
786         }
787         ossl_statem_set_sctp_read_sock(s, 0);
788         return WORK_FINISHED_STOP;
789 #endif
790
791     default:
792         break;
793     }
794
795     /* Shouldn't happen */
796     return WORK_ERROR;
797 }
798
799 /*
800  * Work out what version we should be using for the initial ClientHello if
801  * the version is currently set to (D)TLS_ANY_VERSION.
802  * Returns 1 on success
803  * Returns 0 on error
804  */
805 static int ssl_set_version(SSL *s)
806 {
807     unsigned long mask, options = s->options;
808
809     if (s->method->version == TLS_ANY_VERSION) {
810         /*
811          * SSL_OP_NO_X disables all protocols above X *if* there are
812          * some protocols below X enabled. This is required in order
813          * to maintain "version capability" vector contiguous. So
814          * that if application wants to disable TLS1.0 in favour of
815          * TLS1>=1, it would be insufficient to pass SSL_NO_TLSv1, the
816          * answer is SSL_OP_NO_TLSv1|SSL_OP_NO_SSLv3.
817          */
818         mask = SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1
819 #if !defined(OPENSSL_NO_SSL3)
820             | SSL_OP_NO_SSLv3
821 #endif
822             ;
823 #if !defined(OPENSSL_NO_TLS1_2_CLIENT)
824         if (options & SSL_OP_NO_TLSv1_2) {
825             if ((options & mask) != mask) {
826                 s->version = TLS1_1_VERSION;
827             } else {
828                 SSLerr(SSL_F_SSL_SET_VERSION, SSL_R_NO_PROTOCOLS_AVAILABLE);
829                 return 0;
830             }
831         } else {
832             s->version = TLS1_2_VERSION;
833         }
834 #else
835         if ((options & mask) == mask) {
836             SSLerr(SSL_F_SSL_SET_VERSION, SSL_R_NO_PROTOCOLS_AVAILABLE);
837             return 0;
838         }
839         s->version = TLS1_1_VERSION;
840 #endif
841
842         mask &= ~SSL_OP_NO_TLSv1_1;
843         if ((options & SSL_OP_NO_TLSv1_1) && (options & mask) != mask)
844             s->version = TLS1_VERSION;
845         mask &= ~SSL_OP_NO_TLSv1;
846 #if !defined(OPENSSL_NO_SSL3)
847         if ((options & SSL_OP_NO_TLSv1) && (options & mask) != mask)
848             s->version = SSL3_VERSION;
849 #endif
850
851         if (s->version != TLS1_2_VERSION && tls1_suiteb(s)) {
852             SSLerr(SSL_F_SSL_SET_VERSION,
853                    SSL_R_ONLY_TLS_1_2_ALLOWED_IN_SUITEB_MODE);
854             return 0;
855         }
856
857         if (s->version == SSL3_VERSION && FIPS_mode()) {
858             SSLerr(SSL_F_SSL_SET_VERSION, SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE);
859             return 0;
860         }
861
862     } else if (s->method->version == DTLS_ANY_VERSION) {
863         /* Determine which DTLS version to use */
864         /* If DTLS 1.2 disabled correct the version number */
865         if (options & SSL_OP_NO_DTLSv1_2) {
866             if (tls1_suiteb(s)) {
867                 SSLerr(SSL_F_SSL_SET_VERSION,
868                        SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
869                 return 0;
870             }
871             /*
872              * Disabling all versions is silly: return an error.
873              */
874             if (options & SSL_OP_NO_DTLSv1) {
875                 SSLerr(SSL_F_SSL_SET_VERSION, SSL_R_WRONG_SSL_VERSION);
876                 return 0;
877             }
878             /*
879              * Update method so we don't use any DTLS 1.2 features.
880              */
881             s->method = DTLSv1_client_method();
882             s->version = DTLS1_VERSION;
883         } else {
884             /*
885              * We only support one version: update method
886              */
887             if (options & SSL_OP_NO_DTLSv1)
888                 s->method = DTLSv1_2_client_method();
889             s->version = DTLS1_2_VERSION;
890         }
891     }
892
893     s->client_version = s->version;
894
895     return 1;
896 }
897
898 int tls_construct_client_hello(SSL *s)
899 {
900     unsigned char *buf;
901     unsigned char *p, *d;
902     int i;
903     unsigned long l;
904     int al = 0;
905 #ifndef OPENSSL_NO_COMP
906     int j;
907     SSL_COMP *comp;
908 #endif
909     SSL_SESSION *sess = s->session;
910
911     buf = (unsigned char *)s->init_buf->data;
912
913     /* Work out what SSL/TLS/DTLS version to use */
914     if (ssl_set_version(s) == 0)
915         goto err;
916
917     if ((sess == NULL) || (sess->ssl_version != s->version) ||
918         /*
919          * In the case of EAP-FAST, we can have a pre-shared
920          * "ticket" without a session ID.
921          */
922         (!sess->session_id_length && !sess->tlsext_tick) ||
923         (sess->not_resumable)) {
924         if (!ssl_get_new_session(s, 0))
925             goto err;
926     }
927     /* else use the pre-loaded session */
928
929     p = s->s3->client_random;
930
931     /*
932      * for DTLS if client_random is initialized, reuse it, we are
933      * required to use same upon reply to HelloVerify
934      */
935     if (SSL_IS_DTLS(s)) {
936         size_t idx;
937         i = 1;
938         for (idx = 0; idx < sizeof(s->s3->client_random); idx++) {
939             if (p[idx]) {
940                 i = 0;
941                 break;
942             }
943         }
944     } else
945         i = 1;
946
947     if (i && ssl_fill_hello_random(s, 0, p,
948                                    sizeof(s->s3->client_random)) <= 0)
949         goto err;
950
951     /* Do the message type and length last */
952     d = p = ssl_handshake_start(s);
953
954     /*-
955      * version indicates the negotiated version: for example from
956      * an SSLv2/v3 compatible client hello). The client_version
957      * field is the maximum version we permit and it is also
958      * used in RSA encrypted premaster secrets. Some servers can
959      * choke if we initially report a higher version then
960      * renegotiate to a lower one in the premaster secret. This
961      * didn't happen with TLS 1.0 as most servers supported it
962      * but it can with TLS 1.1 or later if the server only supports
963      * 1.0.
964      *
965      * Possible scenario with previous logic:
966      *      1. Client hello indicates TLS 1.2
967      *      2. Server hello says TLS 1.0
968      *      3. RSA encrypted premaster secret uses 1.2.
969      *      4. Handhaked proceeds using TLS 1.0.
970      *      5. Server sends hello request to renegotiate.
971      *      6. Client hello indicates TLS v1.0 as we now
972      *         know that is maximum server supports.
973      *      7. Server chokes on RSA encrypted premaster secret
974      *         containing version 1.0.
975      *
976      * For interoperability it should be OK to always use the
977      * maximum version we support in client hello and then rely
978      * on the checking of version to ensure the servers isn't
979      * being inconsistent: for example initially negotiating with
980      * TLS 1.0 and renegotiating with TLS 1.2. We do this by using
981      * client_version in client hello and not resetting it to
982      * the negotiated version.
983      */
984     *(p++) = s->client_version >> 8;
985     *(p++) = s->client_version & 0xff;
986
987     /* Random stuff */
988     memcpy(p, s->s3->client_random, SSL3_RANDOM_SIZE);
989     p += SSL3_RANDOM_SIZE;
990
991     /* Session ID */
992     if (s->new_session)
993         i = 0;
994     else
995         i = s->session->session_id_length;
996     *(p++) = i;
997     if (i != 0) {
998         if (i > (int)sizeof(s->session->session_id)) {
999             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1000             goto err;
1001         }
1002         memcpy(p, s->session->session_id, i);
1003         p += i;
1004     }
1005
1006     /* cookie stuff for DTLS */
1007     if (SSL_IS_DTLS(s)) {
1008         if (s->d1->cookie_len > sizeof(s->d1->cookie)) {
1009             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1010             goto err;
1011         }
1012         *(p++) = s->d1->cookie_len;
1013         memcpy(p, s->d1->cookie, s->d1->cookie_len);
1014         p += s->d1->cookie_len;
1015     }
1016
1017     /* Ciphers supported */
1018     i = ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s), &(p[2]));
1019     if (i == 0) {
1020         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, SSL_R_NO_CIPHERS_AVAILABLE);
1021         goto err;
1022     }
1023 #ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH
1024     /*
1025      * Some servers hang if client hello > 256 bytes as hack workaround
1026      * chop number of supported ciphers to keep it well below this if we
1027      * use TLS v1.2
1028      */
1029     if (TLS1_get_version(s) >= TLS1_2_VERSION
1030         && i > OPENSSL_MAX_TLS1_2_CIPHER_LENGTH)
1031         i = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1;
1032 #endif
1033     s2n(i, p);
1034     p += i;
1035
1036     /* COMPRESSION */
1037 #ifdef OPENSSL_NO_COMP
1038     *(p++) = 1;
1039 #else
1040
1041     if (!ssl_allow_compression(s) || !s->ctx->comp_methods)
1042         j = 0;
1043     else
1044         j = sk_SSL_COMP_num(s->ctx->comp_methods);
1045     *(p++) = 1 + j;
1046     for (i = 0; i < j; i++) {
1047         comp = sk_SSL_COMP_value(s->ctx->comp_methods, i);
1048         *(p++) = comp->id;
1049     }
1050 #endif
1051     *(p++) = 0;             /* Add the NULL method */
1052
1053     /* TLS extensions */
1054     if (ssl_prepare_clienthello_tlsext(s) <= 0) {
1055         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1056         goto err;
1057     }
1058     if ((p =
1059          ssl_add_clienthello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,
1060                                     &al)) == NULL) {
1061         ssl3_send_alert(s, SSL3_AL_FATAL, al);
1062         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1063         goto err;
1064     }
1065
1066     l = p - d;
1067     if (!ssl_set_handshake_header(s, SSL3_MT_CLIENT_HELLO, l)) {
1068         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1069         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1070         goto err;
1071     }
1072
1073     return 1;
1074  err:
1075     ossl_statem_set_error(s);
1076     return 0;
1077 }
1078
1079 MSG_PROCESS_RETURN dtls_process_hello_verify(SSL *s, PACKET *pkt)
1080 {
1081     int al;
1082     unsigned int cookie_len;
1083     PACKET cookiepkt;
1084
1085     if (!PACKET_forward(pkt, 2)
1086             || !PACKET_get_length_prefixed_1(pkt, &cookiepkt)) {
1087         al = SSL_AD_DECODE_ERROR;
1088         SSLerr(SSL_F_DTLS_PROCESS_HELLO_VERIFY, SSL_R_LENGTH_MISMATCH);
1089         goto f_err;
1090     }
1091
1092     cookie_len = PACKET_remaining(&cookiepkt);
1093     if (cookie_len > sizeof(s->d1->cookie)) {
1094         al = SSL_AD_ILLEGAL_PARAMETER;
1095         SSLerr(SSL_F_DTLS_PROCESS_HELLO_VERIFY, SSL_R_LENGTH_TOO_LONG);
1096         goto f_err;
1097     }
1098
1099     if (!PACKET_copy_bytes(&cookiepkt, s->d1->cookie, cookie_len)) {
1100         al = SSL_AD_DECODE_ERROR;
1101         SSLerr(SSL_F_DTLS_PROCESS_HELLO_VERIFY, SSL_R_LENGTH_MISMATCH);
1102         goto f_err;
1103     }
1104     s->d1->cookie_len = cookie_len;
1105
1106     return MSG_PROCESS_FINISHED_READING;
1107  f_err:
1108     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1109     ossl_statem_set_error(s);
1110     return MSG_PROCESS_ERROR;
1111 }
1112
1113 MSG_PROCESS_RETURN tls_process_server_hello(SSL *s, PACKET *pkt)
1114 {
1115     STACK_OF(SSL_CIPHER) *sk;
1116     const SSL_CIPHER *c;
1117     PACKET session_id;
1118     size_t session_id_len;
1119     unsigned char *cipherchars;
1120     int i, al = SSL_AD_INTERNAL_ERROR;
1121     unsigned int compression;
1122 #ifndef OPENSSL_NO_COMP
1123     SSL_COMP *comp;
1124 #endif
1125
1126     if (s->method->version == TLS_ANY_VERSION) {
1127         unsigned int sversion;
1128
1129         if (!PACKET_get_net_2(pkt, &sversion)) {
1130             al = SSL_AD_DECODE_ERROR;
1131             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
1132             goto f_err;
1133         }
1134
1135 #if TLS_MAX_VERSION != TLS1_2_VERSION
1136 #error Code needs updating for new TLS version
1137 #endif
1138 #ifndef OPENSSL_NO_SSL3
1139         if ((sversion == SSL3_VERSION) && !(s->options & SSL_OP_NO_SSLv3)) {
1140             if (FIPS_mode()) {
1141                 SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1142                        SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE);
1143                 al = SSL_AD_PROTOCOL_VERSION;
1144                 goto f_err;
1145             }
1146             s->method = SSLv3_client_method();
1147         } else
1148 #endif
1149         if ((sversion == TLS1_VERSION) && !(s->options & SSL_OP_NO_TLSv1)) {
1150             s->method = TLSv1_client_method();
1151         } else if ((sversion == TLS1_1_VERSION) &&
1152                    !(s->options & SSL_OP_NO_TLSv1_1)) {
1153             s->method = TLSv1_1_client_method();
1154         } else if ((sversion == TLS1_2_VERSION) &&
1155                    !(s->options & SSL_OP_NO_TLSv1_2)) {
1156             s->method = TLSv1_2_client_method();
1157         } else {
1158             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_UNSUPPORTED_PROTOCOL);
1159             al = SSL_AD_PROTOCOL_VERSION;
1160             goto f_err;
1161         }
1162         s->session->ssl_version = s->version = s->method->version;
1163
1164         if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL)) {
1165             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_VERSION_TOO_LOW);
1166             al = SSL_AD_PROTOCOL_VERSION;
1167             goto f_err;
1168         }
1169     } else if (s->method->version == DTLS_ANY_VERSION) {
1170         /* Work out correct protocol version to use */
1171         unsigned int hversion;
1172         int options;
1173
1174         if (!PACKET_get_net_2(pkt, &hversion)) {
1175             al = SSL_AD_DECODE_ERROR;
1176             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
1177             goto f_err;
1178         }
1179
1180         options = s->options;
1181         if (hversion == DTLS1_2_VERSION && !(options & SSL_OP_NO_DTLSv1_2))
1182             s->method = DTLSv1_2_client_method();
1183         else if (tls1_suiteb(s)) {
1184             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1185                    SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
1186             s->version = hversion;
1187             al = SSL_AD_PROTOCOL_VERSION;
1188             goto f_err;
1189         } else if (hversion == DTLS1_VERSION && !(options & SSL_OP_NO_DTLSv1))
1190             s->method = DTLSv1_client_method();
1191         else {
1192             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_WRONG_SSL_VERSION);
1193             s->version = hversion;
1194             al = SSL_AD_PROTOCOL_VERSION;
1195             goto f_err;
1196         }
1197         s->session->ssl_version = s->version = s->method->version;
1198     } else {
1199         unsigned char *vers;
1200
1201         if (!PACKET_get_bytes(pkt, &vers, 2)) {
1202             al = SSL_AD_DECODE_ERROR;
1203             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
1204             goto f_err;
1205         }
1206         if ((vers[0] != (s->version >> 8))
1207                 || (vers[1] != (s->version & 0xff))) {
1208             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_WRONG_SSL_VERSION);
1209             s->version = (s->version & 0xff00) | vers[1];
1210             al = SSL_AD_PROTOCOL_VERSION;
1211             goto f_err;
1212         }
1213     }
1214
1215     /* load the server hello data */
1216     /* load the server random */
1217     if (!PACKET_copy_bytes(pkt, s->s3->server_random, SSL3_RANDOM_SIZE)) {
1218         al = SSL_AD_DECODE_ERROR;
1219         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
1220         goto f_err;
1221     }
1222
1223     s->hit = 0;
1224
1225     /* Get the session-id. */
1226     if (!PACKET_get_length_prefixed_1(pkt, &session_id)) {
1227         al = SSL_AD_DECODE_ERROR;
1228         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
1229         goto f_err;
1230     }
1231     session_id_len = PACKET_remaining(&session_id);
1232     if (session_id_len > sizeof s->session->session_id
1233         || session_id_len > SSL3_SESSION_ID_SIZE) {
1234         al = SSL_AD_ILLEGAL_PARAMETER;
1235         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_SSL3_SESSION_ID_TOO_LONG);
1236         goto f_err;
1237     }
1238
1239     if (!PACKET_get_bytes(pkt, &cipherchars, TLS_CIPHER_LEN)) {
1240         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
1241         al = SSL_AD_DECODE_ERROR;
1242         goto f_err;
1243     }
1244
1245     /*
1246      * Check if we can resume the session based on external pre-shared secret.
1247      * EAP-FAST (RFC 4851) supports two types of session resumption.
1248      * Resumption based on server-side state works with session IDs.
1249      * Resumption based on pre-shared Protected Access Credentials (PACs)
1250      * works by overriding the SessionTicket extension at the application
1251      * layer, and does not send a session ID. (We do not know whether EAP-FAST
1252      * servers would honour the session ID.) Therefore, the session ID alone
1253      * is not a reliable indicator of session resumption, so we first check if
1254      * we can resume, and later peek at the next handshake message to see if the
1255      * server wants to resume.
1256      */
1257     if (s->version >= TLS1_VERSION && s->tls_session_secret_cb &&
1258         s->session->tlsext_tick) {
1259         SSL_CIPHER *pref_cipher = NULL;
1260         s->session->master_key_length = sizeof(s->session->master_key);
1261         if (s->tls_session_secret_cb(s, s->session->master_key,
1262                                      &s->session->master_key_length,
1263                                      NULL, &pref_cipher,
1264                                      s->tls_session_secret_cb_arg)) {
1265             s->session->cipher = pref_cipher ?
1266                 pref_cipher : ssl_get_cipher_by_char(s, cipherchars);
1267         } else {
1268             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1269             al = SSL_AD_INTERNAL_ERROR;
1270             goto f_err;
1271         }
1272     }
1273
1274     if (session_id_len != 0 && session_id_len == s->session->session_id_length
1275         && memcmp(PACKET_data(&session_id), s->session->session_id,
1276                   session_id_len) == 0) {
1277         if (s->sid_ctx_length != s->session->sid_ctx_length
1278             || memcmp(s->session->sid_ctx, s->sid_ctx, s->sid_ctx_length)) {
1279             /* actually a client application bug */
1280             al = SSL_AD_ILLEGAL_PARAMETER;
1281             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1282                    SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
1283             goto f_err;
1284         }
1285         s->hit = 1;
1286     } else {
1287         /*
1288          * If we were trying for session-id reuse but the server
1289          * didn't echo the ID, make a new SSL_SESSION.
1290          * In the case of EAP-FAST and PAC, we do not send a session ID,
1291          * so the PAC-based session secret is always preserved. It'll be
1292          * overwritten if the server refuses resumption.
1293          */
1294         if (s->session->session_id_length > 0) {
1295             if (!ssl_get_new_session(s, 0)) {
1296                 goto f_err;
1297             }
1298         }
1299
1300         s->session->session_id_length = session_id_len;
1301         /* session_id_len could be 0 */
1302         memcpy(s->session->session_id, PACKET_data(&session_id),
1303                session_id_len);
1304     }
1305
1306     c = ssl_get_cipher_by_char(s, cipherchars);
1307     if (c == NULL) {
1308         /* unknown cipher */
1309         al = SSL_AD_ILLEGAL_PARAMETER;
1310         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_UNKNOWN_CIPHER_RETURNED);
1311         goto f_err;
1312     }
1313     /* Set version disabled mask now we know version */
1314     if (!SSL_USE_TLS1_2_CIPHERS(s))
1315         s->s3->tmp.mask_ssl = SSL_TLSV1_2;
1316     else
1317         s->s3->tmp.mask_ssl = 0;
1318     /* Skip TLS v1.0 ciphersuites if SSLv3 */
1319     if ((c->algorithm_ssl & SSL_TLSV1) && s->version == SSL3_VERSION)
1320         s->s3->tmp.mask_ssl |= SSL_TLSV1;
1321     /*
1322      * If it is a disabled cipher we didn't send it in client hello, so
1323      * return an error.
1324      */
1325     if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_CHECK)) {
1326         al = SSL_AD_ILLEGAL_PARAMETER;
1327         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_WRONG_CIPHER_RETURNED);
1328         goto f_err;
1329     }
1330
1331     sk = ssl_get_ciphers_by_id(s);
1332     i = sk_SSL_CIPHER_find(sk, c);
1333     if (i < 0) {
1334         /* we did not say we would use this cipher */
1335         al = SSL_AD_ILLEGAL_PARAMETER;
1336         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_WRONG_CIPHER_RETURNED);
1337         goto f_err;
1338     }
1339
1340     /*
1341      * Depending on the session caching (internal/external), the cipher
1342      * and/or cipher_id values may not be set. Make sure that cipher_id is
1343      * set and use it for comparison.
1344      */
1345     if (s->session->cipher)
1346         s->session->cipher_id = s->session->cipher->id;
1347     if (s->hit && (s->session->cipher_id != c->id)) {
1348         al = SSL_AD_ILLEGAL_PARAMETER;
1349         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1350                SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
1351         goto f_err;
1352     }
1353     s->s3->tmp.new_cipher = c;
1354     /* lets get the compression algorithm */
1355     /* COMPRESSION */
1356     if (!PACKET_get_1(pkt, &compression)) {
1357         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
1358         al = SSL_AD_DECODE_ERROR;
1359         goto f_err;
1360     }
1361 #ifdef OPENSSL_NO_COMP
1362     if (compression != 0) {
1363         al = SSL_AD_ILLEGAL_PARAMETER;
1364         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1365                SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1366         goto f_err;
1367     }
1368     /*
1369      * If compression is disabled we'd better not try to resume a session
1370      * using compression.
1371      */
1372     if (s->session->compress_meth != 0) {
1373         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
1374         goto f_err;
1375     }
1376 #else
1377     if (s->hit && compression != s->session->compress_meth) {
1378         al = SSL_AD_ILLEGAL_PARAMETER;
1379         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1380                SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED);
1381         goto f_err;
1382     }
1383     if (compression == 0)
1384         comp = NULL;
1385     else if (!ssl_allow_compression(s)) {
1386         al = SSL_AD_ILLEGAL_PARAMETER;
1387         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_COMPRESSION_DISABLED);
1388         goto f_err;
1389     } else {
1390         comp = ssl3_comp_find(s->ctx->comp_methods, compression);
1391     }
1392
1393     if (compression != 0 && comp == NULL) {
1394         al = SSL_AD_ILLEGAL_PARAMETER;
1395         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1396                SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1397         goto f_err;
1398     } else {
1399         s->s3->tmp.new_compression = comp;
1400     }
1401 #endif
1402
1403     /* TLS extensions */
1404     if (!ssl_parse_serverhello_tlsext(s, pkt)) {
1405         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_PARSE_TLSEXT);
1406         goto err;
1407     }
1408
1409     if (PACKET_remaining(pkt) != 0) {
1410         /* wrong packet length */
1411         al = SSL_AD_DECODE_ERROR;
1412         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_BAD_PACKET_LENGTH);
1413         goto f_err;
1414     }
1415
1416 #ifndef OPENSSL_NO_SCTP
1417     if (SSL_IS_DTLS(s) && s->hit) {
1418         unsigned char sctpauthkey[64];
1419         char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
1420
1421         /*
1422          * Add new shared key for SCTP-Auth, will be ignored if
1423          * no SCTP used.
1424          */
1425         memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
1426                sizeof(DTLS1_SCTP_AUTH_LABEL));
1427
1428         if (SSL_export_keying_material(s, sctpauthkey,
1429                                    sizeof(sctpauthkey),
1430                                    labelbuffer,
1431                                    sizeof(labelbuffer), NULL, 0,
1432                                    0) <= 0)
1433             goto err;
1434
1435         BIO_ctrl(SSL_get_wbio(s),
1436                  BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
1437                  sizeof(sctpauthkey), sctpauthkey);
1438     }
1439 #endif
1440
1441     return MSG_PROCESS_CONTINUE_READING;
1442  f_err:
1443     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1444  err:
1445     ossl_statem_set_error(s);
1446     return MSG_PROCESS_ERROR;
1447 }
1448
1449 MSG_PROCESS_RETURN tls_process_server_certificate(SSL *s, PACKET *pkt)
1450 {
1451     int al, i, ret = MSG_PROCESS_ERROR, exp_idx;
1452     unsigned long cert_list_len, cert_len;
1453     X509 *x = NULL;
1454     unsigned char *certstart, *certbytes;
1455     STACK_OF(X509) *sk = NULL;
1456     EVP_PKEY *pkey = NULL;
1457
1458     if ((sk = sk_X509_new_null()) == NULL) {
1459         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, ERR_R_MALLOC_FAILURE);
1460         goto err;
1461     }
1462
1463     if (!PACKET_get_net_3(pkt, &cert_list_len)
1464             || PACKET_remaining(pkt) != cert_list_len) {
1465         al = SSL_AD_DECODE_ERROR;
1466         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
1467         goto f_err;
1468     }
1469     while (PACKET_remaining(pkt)) {
1470         if (!PACKET_get_net_3(pkt, &cert_len)
1471                 || !PACKET_get_bytes(pkt, &certbytes, cert_len)) {
1472             al = SSL_AD_DECODE_ERROR;
1473             SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1474                    SSL_R_CERT_LENGTH_MISMATCH);
1475             goto f_err;
1476         }
1477
1478         certstart = certbytes;
1479         x = d2i_X509(NULL, (const unsigned char **)&certbytes, cert_len);
1480         if (x == NULL) {
1481             al = SSL_AD_BAD_CERTIFICATE;
1482             SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, ERR_R_ASN1_LIB);
1483             goto f_err;
1484         }
1485         if (certbytes != (certstart + cert_len)) {
1486             al = SSL_AD_DECODE_ERROR;
1487             SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1488                    SSL_R_CERT_LENGTH_MISMATCH);
1489             goto f_err;
1490         }
1491         if (!sk_X509_push(sk, x)) {
1492             SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, ERR_R_MALLOC_FAILURE);
1493             goto err;
1494         }
1495         x = NULL;
1496     }
1497
1498     i = ssl_verify_cert_chain(s, sk);
1499     if (s->verify_mode != SSL_VERIFY_NONE && i <= 0) {
1500         al = ssl_verify_alarm_type(s->verify_result);
1501         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1502                SSL_R_CERTIFICATE_VERIFY_FAILED);
1503         goto f_err;
1504     }
1505     ERR_clear_error();          /* but we keep s->verify_result */
1506     if (i > 1) {
1507         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, i);
1508         al = SSL_AD_HANDSHAKE_FAILURE;
1509         goto f_err;
1510     }
1511
1512     s->session->peer_chain = sk;
1513     /*
1514      * Inconsistency alert: cert_chain does include the peer's certificate,
1515      * which we don't include in s3_srvr.c
1516      */
1517     x = sk_X509_value(sk, 0);
1518     sk = NULL;
1519     /*
1520      * VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end
1521      */
1522
1523     pkey = X509_get_pubkey(x);
1524
1525     if (pkey == NULL || EVP_PKEY_missing_parameters(pkey)) {
1526         x = NULL;
1527         al = SSL3_AL_FATAL;
1528         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1529                SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
1530         goto f_err;
1531     }
1532
1533     i = ssl_cert_type(x, pkey);
1534     if (i < 0) {
1535         x = NULL;
1536         al = SSL3_AL_FATAL;
1537         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1538                SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1539         goto f_err;
1540     }
1541
1542     exp_idx = ssl_cipher_get_cert_index(s->s3->tmp.new_cipher);
1543     if (exp_idx >= 0 && i != exp_idx
1544             && (exp_idx != SSL_PKEY_GOST_EC ||
1545                 (i != SSL_PKEY_GOST12_512 && i != SSL_PKEY_GOST12_256
1546                  && i != SSL_PKEY_GOST01))) {
1547         x = NULL;
1548         al = SSL_AD_ILLEGAL_PARAMETER;
1549         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1550                SSL_R_WRONG_CERTIFICATE_TYPE);
1551         goto f_err;
1552     }
1553     s->session->peer_type = i;
1554
1555     X509_free(s->session->peer);
1556     X509_up_ref(x);
1557     s->session->peer = x;
1558     s->session->verify_result = s->verify_result;
1559
1560     x = NULL;
1561     ret = MSG_PROCESS_CONTINUE_READING;
1562     goto done;
1563
1564  f_err:
1565     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1566  err:
1567     ossl_statem_set_error(s);
1568  done:
1569     EVP_PKEY_free(pkey);
1570     X509_free(x);
1571     sk_X509_pop_free(sk, X509_free);
1572     return ret;
1573 }
1574
1575 MSG_PROCESS_RETURN tls_process_key_exchange(SSL *s, PACKET *pkt)
1576 {
1577     EVP_MD_CTX *md_ctx;
1578     int al, j;
1579     long alg_k, alg_a;
1580     EVP_PKEY *pkey = NULL;
1581     const EVP_MD *md = NULL;
1582 #ifndef OPENSSL_NO_RSA
1583     RSA *rsa = NULL;
1584 #endif
1585 #ifndef OPENSSL_NO_EC
1586     EVP_PKEY_CTX *pctx = NULL;
1587 #endif
1588     PACKET save_param_start, signature;
1589
1590     md_ctx = EVP_MD_CTX_new();
1591     if (md_ctx == NULL) {
1592         al = SSL_AD_INTERNAL_ERROR;
1593         SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1594         goto f_err;
1595     }
1596
1597     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1598
1599     save_param_start = *pkt;
1600
1601 #if !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)
1602     EVP_PKEY_free(s->s3->peer_tmp);
1603     s->s3->peer_tmp = NULL;
1604 #endif
1605
1606     alg_a = s->s3->tmp.new_cipher->algorithm_auth;
1607
1608     al = SSL_AD_DECODE_ERROR;
1609
1610 #ifndef OPENSSL_NO_PSK
1611     /* PSK ciphersuites are preceded by an identity hint */
1612     if (alg_k & SSL_PSK) {
1613         PACKET psk_identity_hint;
1614         if (!PACKET_get_length_prefixed_2(pkt, &psk_identity_hint)) {
1615             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
1616             goto f_err;
1617         }
1618
1619         /*
1620          * Store PSK identity hint for later use, hint is used in
1621          * ssl3_send_client_key_exchange.  Assume that the maximum length of
1622          * a PSK identity hint can be as long as the maximum length of a PSK
1623          * identity.
1624          */
1625         if (PACKET_remaining(&psk_identity_hint) > PSK_MAX_IDENTITY_LEN) {
1626             al = SSL_AD_HANDSHAKE_FAILURE;
1627             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG);
1628             goto f_err;
1629         }
1630
1631         if (PACKET_remaining(&psk_identity_hint) == 0) {
1632             OPENSSL_free(s->session->psk_identity_hint);
1633             s->session->psk_identity_hint = NULL;
1634         } else if (!PACKET_strndup(&psk_identity_hint,
1635                             &s->session->psk_identity_hint)) {
1636             al = SSL_AD_INTERNAL_ERROR;
1637             goto f_err;
1638         }
1639     }
1640
1641     /* Nothing else to do for plain PSK or RSAPSK */
1642     if (alg_k & (SSL_kPSK | SSL_kRSAPSK)) {
1643     } else
1644 #endif                          /* !OPENSSL_NO_PSK */
1645     /*
1646      * Dummy "if" to ensure sane C code in the event of various OPENSSL_NO_*
1647      * options
1648      */
1649     if (0) {
1650     }
1651 #ifndef OPENSSL_NO_SRP
1652     else if (alg_k & SSL_kSRP) {
1653         PACKET prime, generator, salt, server_pub;
1654         if (!PACKET_get_length_prefixed_2(pkt, &prime)
1655             || !PACKET_get_length_prefixed_2(pkt, &generator)
1656             || !PACKET_get_length_prefixed_1(pkt, &salt)
1657             || !PACKET_get_length_prefixed_2(pkt, &server_pub)) {
1658             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
1659             goto f_err;
1660         }
1661
1662         if ((s->srp_ctx.N =
1663              BN_bin2bn(PACKET_data(&prime),
1664                        PACKET_remaining(&prime), NULL)) == NULL
1665             || (s->srp_ctx.g =
1666                 BN_bin2bn(PACKET_data(&generator),
1667                           PACKET_remaining(&generator), NULL)) == NULL
1668             || (s->srp_ctx.s =
1669                 BN_bin2bn(PACKET_data(&salt),
1670                           PACKET_remaining(&salt), NULL)) == NULL
1671             || (s->srp_ctx.B =
1672                 BN_bin2bn(PACKET_data(&server_pub),
1673                           PACKET_remaining(&server_pub), NULL)) == NULL) {
1674             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_BN_LIB);
1675             goto err;
1676         }
1677
1678         if (!srp_verify_server_param(s, &al)) {
1679             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_BAD_SRP_PARAMETERS);
1680             goto f_err;
1681         }
1682
1683 /* We must check if there is a certificate */
1684         if (alg_a & (SSL_aRSA|SSL_aDSS))
1685             pkey = X509_get_pubkey(s->session->peer);
1686     }
1687 #endif                          /* !OPENSSL_NO_SRP */
1688 #ifndef OPENSSL_NO_DH
1689     else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
1690         PACKET prime, generator, pub_key;
1691
1692         DH *dh;
1693
1694         if (!PACKET_get_length_prefixed_2(pkt, &prime)
1695             || !PACKET_get_length_prefixed_2(pkt, &generator)
1696             || !PACKET_get_length_prefixed_2(pkt, &pub_key)) {
1697             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
1698             goto f_err;
1699         }
1700
1701         s->s3->peer_tmp = EVP_PKEY_new();
1702         dh = DH_new();
1703
1704         if (s->s3->peer_tmp == NULL || dh == NULL) {
1705             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1706             DH_free(dh);
1707             goto err;
1708         }
1709
1710         if (EVP_PKEY_assign_DH(s->s3->peer_tmp, dh) == 0) {
1711             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_EVP_LIB);
1712             DH_free(dh);
1713             goto err;
1714         }
1715
1716         if ((dh->p = BN_bin2bn(PACKET_data(&prime),
1717                                PACKET_remaining(&prime), NULL)) == NULL
1718             || (dh->g = BN_bin2bn(PACKET_data(&generator),
1719                                   PACKET_remaining(&generator), NULL)) == NULL
1720             || (dh->pub_key =
1721                 BN_bin2bn(PACKET_data(&pub_key),
1722                           PACKET_remaining(&pub_key), NULL)) == NULL) {
1723             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_BN_LIB);
1724             goto err;
1725         }
1726
1727         if (BN_is_zero(dh->p) || BN_is_zero(dh->g) || BN_is_zero(dh->pub_key)) {
1728             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_BAD_DH_VALUE);
1729             goto f_err;
1730         }
1731
1732         if (!ssl_security(s, SSL_SECOP_TMP_DH, DH_security_bits(dh), 0, dh)) {
1733             al = SSL_AD_HANDSHAKE_FAILURE;
1734             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_DH_KEY_TOO_SMALL);
1735             goto f_err;
1736         }
1737         if (alg_a & (SSL_aRSA|SSL_aDSS))
1738             pkey = X509_get_pubkey(s->session->peer);
1739         /* else anonymous DH, so no certificate or pkey. */
1740     }
1741 #endif                          /* !OPENSSL_NO_DH */
1742
1743 #ifndef OPENSSL_NO_EC
1744     else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
1745         PACKET encoded_pt;
1746         unsigned char *ecparams;
1747         int curve_nid;
1748
1749         /*
1750          * Extract elliptic curve parameters and the server's ephemeral ECDH
1751          * public key. For now we only support named (not generic) curves and
1752          * ECParameters in this case is just three bytes.
1753          */
1754         if (!PACKET_get_bytes(pkt, &ecparams, 3)) {
1755             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1756             goto f_err;
1757         }
1758         /*
1759          * Check curve is one of our preferences, if not server has sent an
1760          * invalid curve. ECParameters is 3 bytes.
1761          */
1762         if (!tls1_check_curve(s, ecparams, 3)) {
1763             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_WRONG_CURVE);
1764             goto f_err;
1765         }
1766
1767         curve_nid = tls1_ec_curve_id2nid(*(ecparams + 2));
1768         if (curve_nid  == 0) {
1769             al = SSL_AD_INTERNAL_ERROR;
1770             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE,
1771                    SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
1772             goto f_err;
1773         }
1774
1775         /* Set up EVP_PKEY with named curve as parameters */
1776         pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL);
1777         if (pctx == NULL
1778             || EVP_PKEY_paramgen_init(pctx) <= 0
1779             || EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx, curve_nid) <= 0
1780             || EVP_PKEY_paramgen(pctx, &s->s3->peer_tmp) <= 0) {
1781             al = SSL_AD_INTERNAL_ERROR;
1782             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_EVP_LIB);
1783             goto f_err;
1784         }
1785         EVP_PKEY_CTX_free(pctx);
1786         pctx = NULL;
1787
1788         if (!PACKET_get_length_prefixed_1(pkt, &encoded_pt)) {
1789             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
1790             goto f_err;
1791         }
1792
1793         if (EC_KEY_oct2key(EVP_PKEY_get0_EC_KEY(s->s3->peer_tmp),
1794                            PACKET_data(&encoded_pt),
1795                            PACKET_remaining(&encoded_pt), NULL) == 0) {
1796             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_BAD_ECPOINT);
1797             goto f_err;
1798         }
1799
1800         /*
1801          * The ECC/TLS specification does not mention the use of DSA to sign
1802          * ECParameters in the server key exchange message. We do support RSA
1803          * and ECDSA.
1804          */
1805         if (0) ;
1806 # ifndef OPENSSL_NO_RSA
1807         else if (alg_a & SSL_aRSA)
1808             pkey = X509_get_pubkey(s->session->peer);
1809 # endif
1810 # ifndef OPENSSL_NO_EC
1811         else if (alg_a & SSL_aECDSA)
1812             pkey = X509_get_pubkey(s->session->peer);
1813 # endif
1814         /* else anonymous ECDH, so no certificate or pkey. */
1815     } else if (alg_k) {
1816         al = SSL_AD_UNEXPECTED_MESSAGE;
1817         SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
1818         goto f_err;
1819     }
1820 #endif                          /* !OPENSSL_NO_EC */
1821
1822     /* if it was signed, check the signature */
1823     if (pkey != NULL) {
1824         PACKET params;
1825         /*
1826          * |pkt| now points to the beginning of the signature, so the difference
1827          * equals the length of the parameters.
1828          */
1829         if (!PACKET_get_sub_packet(&save_param_start, &params,
1830                                    PACKET_remaining(&save_param_start) -
1831                                    PACKET_remaining(pkt))) {
1832             al = SSL_AD_INTERNAL_ERROR;
1833             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1834             goto f_err;
1835         }
1836
1837         if (SSL_USE_SIGALGS(s)) {
1838             unsigned char *sigalgs;
1839             int rv;
1840             if (!PACKET_get_bytes(pkt, &sigalgs, 2)) {
1841                 SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1842                 goto f_err;
1843             }
1844             rv = tls12_check_peer_sigalg(&md, s, sigalgs, pkey);
1845             if (rv == -1)
1846                 goto err;
1847             else if (rv == 0) {
1848                 goto f_err;
1849             }
1850 #ifdef SSL_DEBUG
1851             fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
1852 #endif
1853         } else if (pkey->type == EVP_PKEY_RSA) {
1854             md = EVP_md5_sha1();
1855         } else {
1856             md = EVP_sha1();
1857         }
1858
1859         if (!PACKET_get_length_prefixed_2(pkt, &signature)
1860             || PACKET_remaining(pkt) != 0) {
1861             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
1862             goto f_err;
1863         }
1864         j = EVP_PKEY_size(pkey);
1865         if (j < 0) {
1866             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1867             goto f_err;
1868         }
1869
1870         /*
1871          * Check signature length
1872          */
1873         if (PACKET_remaining(&signature) > (size_t)j) {
1874             /* wrong packet length */
1875             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_WRONG_SIGNATURE_LENGTH);
1876             goto f_err;
1877         }
1878         if (EVP_VerifyInit_ex(md_ctx, md, NULL) <= 0
1879                 || EVP_VerifyUpdate(md_ctx, &(s->s3->client_random[0]),
1880                                     SSL3_RANDOM_SIZE) <= 0
1881                 || EVP_VerifyUpdate(md_ctx, &(s->s3->server_random[0]),
1882                                     SSL3_RANDOM_SIZE) <= 0
1883                 || EVP_VerifyUpdate(md_ctx, PACKET_data(&params),
1884                                     PACKET_remaining(&params)) <= 0) {
1885             al = SSL_AD_INTERNAL_ERROR;
1886             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_EVP_LIB);
1887             goto f_err;
1888         }
1889         if (EVP_VerifyFinal(md_ctx, PACKET_data(&signature),
1890                             PACKET_remaining(&signature), pkey) <= 0) {
1891             /* bad signature */
1892             al = SSL_AD_DECRYPT_ERROR;
1893             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_BAD_SIGNATURE);
1894             goto f_err;
1895         }
1896     } else {
1897         /* aNULL, aSRP or PSK do not need public keys */
1898         if (!(alg_a & (SSL_aNULL | SSL_aSRP)) && !(alg_k & SSL_PSK)) {
1899             /* Might be wrong key type, check it */
1900             if (ssl3_check_cert_and_algorithm(s))
1901                 /* Otherwise this shouldn't happen */
1902                 SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1903             goto err;
1904         }
1905         /* still data left over */
1906         if (PACKET_remaining(pkt) != 0) {
1907             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_EXTRA_DATA_IN_MESSAGE);
1908             goto f_err;
1909         }
1910     }
1911     EVP_PKEY_free(pkey);
1912     EVP_MD_CTX_free(md_ctx);
1913     return MSG_PROCESS_CONTINUE_READING;
1914  f_err:
1915     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1916  err:
1917     EVP_PKEY_free(pkey);
1918 #ifndef OPENSSL_NO_RSA
1919     RSA_free(rsa);
1920 #endif
1921 #ifndef OPENSSL_NO_EC
1922     EVP_PKEY_CTX_free(pctx);
1923 #endif
1924     EVP_MD_CTX_free(md_ctx);
1925     ossl_statem_set_error(s);
1926     return MSG_PROCESS_ERROR;
1927 }
1928
1929 MSG_PROCESS_RETURN tls_process_certificate_request(SSL *s, PACKET *pkt)
1930 {
1931     int ret = MSG_PROCESS_ERROR;
1932     unsigned int list_len, ctype_num, i, name_len;
1933     X509_NAME *xn = NULL;
1934     unsigned char *data;
1935     unsigned char *namestart, *namebytes;
1936     STACK_OF(X509_NAME) *ca_sk = NULL;
1937
1938     if ((ca_sk = sk_X509_NAME_new(ca_dn_cmp)) == NULL) {
1939         SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
1940         goto err;
1941     }
1942
1943     /* get the certificate types */
1944     if (!PACKET_get_1(pkt, &ctype_num)
1945             || !PACKET_get_bytes(pkt, &data, ctype_num)) {
1946         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1947         SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, SSL_R_LENGTH_MISMATCH);
1948         goto err;
1949     }
1950     OPENSSL_free(s->cert->ctypes);
1951     s->cert->ctypes = NULL;
1952     if (ctype_num > SSL3_CT_NUMBER) {
1953         /* If we exceed static buffer copy all to cert structure */
1954         s->cert->ctypes = OPENSSL_malloc(ctype_num);
1955         if (s->cert->ctypes == NULL) {
1956             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
1957             goto err;
1958         }
1959         memcpy(s->cert->ctypes, data, ctype_num);
1960         s->cert->ctype_num = (size_t)ctype_num;
1961         ctype_num = SSL3_CT_NUMBER;
1962     }
1963     for (i = 0; i < ctype_num; i++)
1964         s->s3->tmp.ctype[i] = data[i];
1965
1966     if (SSL_USE_SIGALGS(s)) {
1967         if (!PACKET_get_net_2(pkt, &list_len)
1968                 || !PACKET_get_bytes(pkt, &data, list_len)) {
1969             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1970             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST,
1971                    SSL_R_LENGTH_MISMATCH);
1972             goto err;
1973         }
1974
1975         /* Clear certificate digests and validity flags */
1976         for (i = 0; i < SSL_PKEY_NUM; i++) {
1977             s->s3->tmp.md[i] = NULL;
1978             s->s3->tmp.valid_flags[i] = 0;
1979         }
1980         if ((list_len & 1) || !tls1_save_sigalgs(s, data, list_len)) {
1981             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1982             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST,
1983                    SSL_R_SIGNATURE_ALGORITHMS_ERROR);
1984             goto err;
1985         }
1986         if (!tls1_process_sigalgs(s)) {
1987             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1988             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
1989             goto err;
1990         }
1991     } else {
1992         ssl_set_default_md(s);
1993     }
1994
1995     /* get the CA RDNs */
1996     if (!PACKET_get_net_2(pkt, &list_len)
1997             || PACKET_remaining(pkt) != list_len) {
1998         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1999         SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, SSL_R_LENGTH_MISMATCH);
2000         goto err;
2001     }
2002
2003     while (PACKET_remaining(pkt)) {
2004         if (!PACKET_get_net_2(pkt, &name_len)
2005                 || !PACKET_get_bytes(pkt, &namebytes, name_len)) {
2006             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2007             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST,
2008                    SSL_R_LENGTH_MISMATCH);
2009             goto err;
2010         }
2011
2012         namestart = namebytes;
2013
2014         if ((xn = d2i_X509_NAME(NULL, (const unsigned char **)&namebytes,
2015                                 name_len)) == NULL) {
2016             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2017             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_ASN1_LIB);
2018             goto err;
2019         }
2020
2021         if (namebytes != (namestart + name_len)) {
2022             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2023             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST,
2024                    SSL_R_CA_DN_LENGTH_MISMATCH);
2025             goto err;
2026         }
2027         if (!sk_X509_NAME_push(ca_sk, xn)) {
2028             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
2029             goto err;
2030         }
2031     }
2032
2033     /* we should setup a certificate to return.... */
2034     s->s3->tmp.cert_req = 1;
2035     s->s3->tmp.ctype_num = ctype_num;
2036     sk_X509_NAME_pop_free(s->s3->tmp.ca_names, X509_NAME_free);
2037     s->s3->tmp.ca_names = ca_sk;
2038     ca_sk = NULL;
2039
2040     ret = MSG_PROCESS_CONTINUE_READING;
2041     goto done;
2042  err:
2043     ossl_statem_set_error(s);
2044  done:
2045     sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
2046     return ret;
2047 }
2048
2049 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
2050 {
2051     return (X509_NAME_cmp(*a, *b));
2052 }
2053
2054 MSG_PROCESS_RETURN tls_process_new_session_ticket(SSL *s, PACKET *pkt)
2055 {
2056     int al;
2057     unsigned int ticklen;
2058     unsigned long ticket_lifetime_hint;
2059
2060     if (!PACKET_get_net_4(pkt, &ticket_lifetime_hint)
2061             || !PACKET_get_net_2(pkt, &ticklen)
2062             || PACKET_remaining(pkt) != ticklen) {
2063         al = SSL_AD_DECODE_ERROR;
2064         SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
2065         goto f_err;
2066     }
2067
2068     /* Server is allowed to change its mind and send an empty ticket. */
2069     if (ticklen == 0)
2070         return MSG_PROCESS_CONTINUE_READING;
2071
2072     if (s->session->session_id_length > 0) {
2073         int i = s->session_ctx->session_cache_mode;
2074         SSL_SESSION *new_sess;
2075         /*
2076          * We reused an existing session, so we need to replace it with a new
2077          * one
2078          */
2079         if (i & SSL_SESS_CACHE_CLIENT) {
2080             /*
2081              * Remove the old session from the cache
2082              */
2083             if (i & SSL_SESS_CACHE_NO_INTERNAL_STORE) {
2084                 if (s->session_ctx->remove_session_cb != NULL)
2085                     s->session_ctx->remove_session_cb(s->session_ctx,
2086                                                       s->session);
2087             } else {
2088                 /* We carry on if this fails */
2089                 SSL_CTX_remove_session(s->session_ctx, s->session);
2090             }
2091         }
2092
2093         if ((new_sess = ssl_session_dup(s->session, 0)) == 0) {
2094             al = SSL_AD_INTERNAL_ERROR;
2095             SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
2096             goto f_err;
2097         }
2098
2099         SSL_SESSION_free(s->session);
2100         s->session = new_sess;
2101     }
2102
2103     OPENSSL_free(s->session->tlsext_tick);
2104     s->session->tlsext_ticklen = 0;
2105
2106     s->session->tlsext_tick = OPENSSL_malloc(ticklen);
2107     if (s->session->tlsext_tick == NULL) {
2108         SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
2109         goto err;
2110     }
2111     if (!PACKET_copy_bytes(pkt, s->session->tlsext_tick, ticklen)) {
2112         al = SSL_AD_DECODE_ERROR;
2113         SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
2114         goto f_err;
2115     }
2116
2117     s->session->tlsext_tick_lifetime_hint = ticket_lifetime_hint;
2118     s->session->tlsext_ticklen = ticklen;
2119     /*
2120      * There are two ways to detect a resumed ticket session. One is to set
2121      * an appropriate session ID and then the server must return a match in
2122      * ServerHello. This allows the normal client session ID matching to work
2123      * and we know much earlier that the ticket has been accepted. The
2124      * other way is to set zero length session ID when the ticket is
2125      * presented and rely on the handshake to determine session resumption.
2126      * We choose the former approach because this fits in with assumptions
2127      * elsewhere in OpenSSL. The session ID is set to the SHA256 (or SHA1 is
2128      * SHA256 is disabled) hash of the ticket.
2129      */
2130     EVP_Digest(s->session->tlsext_tick, ticklen,
2131                s->session->session_id, &s->session->session_id_length,
2132                EVP_sha256(), NULL);
2133     return MSG_PROCESS_CONTINUE_READING;
2134  f_err:
2135     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2136  err:
2137     ossl_statem_set_error(s);
2138     return MSG_PROCESS_ERROR;
2139 }
2140
2141 MSG_PROCESS_RETURN tls_process_cert_status(SSL *s, PACKET *pkt)
2142 {
2143     int al;
2144     unsigned long resplen;
2145     unsigned int type;
2146
2147     if (!PACKET_get_1(pkt, &type)
2148             || type != TLSEXT_STATUSTYPE_ocsp) {
2149         al = SSL_AD_DECODE_ERROR;
2150         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, SSL_R_UNSUPPORTED_STATUS_TYPE);
2151         goto f_err;
2152     }
2153     if (!PACKET_get_net_3(pkt, &resplen)
2154             || PACKET_remaining(pkt) != resplen) {
2155         al = SSL_AD_DECODE_ERROR;
2156         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, SSL_R_LENGTH_MISMATCH);
2157         goto f_err;
2158     }
2159     s->tlsext_ocsp_resp = OPENSSL_malloc(resplen);
2160     if (s->tlsext_ocsp_resp == NULL) {
2161         al = SSL_AD_INTERNAL_ERROR;
2162         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, ERR_R_MALLOC_FAILURE);
2163         goto f_err;
2164     }
2165     if (!PACKET_copy_bytes(pkt, s->tlsext_ocsp_resp, resplen)) {
2166         al = SSL_AD_DECODE_ERROR;
2167         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, SSL_R_LENGTH_MISMATCH);
2168         goto f_err;
2169     }
2170     s->tlsext_ocsp_resplen = resplen;
2171     return MSG_PROCESS_CONTINUE_READING;
2172  f_err:
2173     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2174     ossl_statem_set_error(s);
2175     return MSG_PROCESS_ERROR;
2176 }
2177
2178 MSG_PROCESS_RETURN tls_process_server_done(SSL *s, PACKET *pkt)
2179 {
2180     if (PACKET_remaining(pkt) > 0) {
2181         /* should contain no data */
2182         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2183         SSLerr(SSL_F_TLS_PROCESS_SERVER_DONE, SSL_R_LENGTH_MISMATCH);
2184         ossl_statem_set_error(s);
2185         return MSG_PROCESS_ERROR;
2186     }
2187
2188 #ifndef OPENSSL_NO_SRP
2189     if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) {
2190         if (SRP_Calc_A_param(s) <= 0) {
2191             SSLerr(SSL_F_TLS_PROCESS_SERVER_DONE, SSL_R_SRP_A_CALC);
2192             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2193             ossl_statem_set_error(s);
2194             return MSG_PROCESS_ERROR;
2195         }
2196     }
2197 #endif
2198
2199     /*
2200      * at this point we check that we have the required stuff from
2201      * the server
2202      */
2203     if (!ssl3_check_cert_and_algorithm(s)) {
2204         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2205         ossl_statem_set_error(s);
2206         return MSG_PROCESS_ERROR;
2207     }
2208
2209     /*
2210      * Call the ocsp status callback if needed. The |tlsext_ocsp_resp| and
2211      * |tlsext_ocsp_resplen| values will be set if we actually received a status
2212      * message, or NULL and -1 otherwise
2213      */
2214     if (s->tlsext_status_expected && s->ctx->tlsext_status_cb != NULL) {
2215         int ret;
2216         ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
2217         if (ret == 0) {
2218             ssl3_send_alert(s, SSL3_AL_FATAL,
2219                             SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE);
2220             SSLerr(SSL_F_TLS_PROCESS_SERVER_DONE,
2221                    SSL_R_INVALID_STATUS_RESPONSE);
2222             return MSG_PROCESS_ERROR;
2223         }
2224         if (ret < 0) {
2225             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2226             SSLerr(SSL_F_TLS_PROCESS_SERVER_DONE, ERR_R_MALLOC_FAILURE);
2227             return MSG_PROCESS_ERROR;
2228         }
2229     }
2230
2231 #ifndef OPENSSL_NO_SCTP
2232     /* Only applies to renegotiation */
2233     if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))
2234             && s->renegotiate != 0)
2235         return MSG_PROCESS_CONTINUE_PROCESSING;
2236     else
2237 #endif
2238         return MSG_PROCESS_FINISHED_READING;
2239 }
2240
2241 int tls_construct_client_key_exchange(SSL *s)
2242 {
2243     unsigned char *p;
2244     int n;
2245 #ifndef OPENSSL_NO_PSK
2246     size_t pskhdrlen = 0;
2247 #endif
2248     unsigned long alg_k;
2249 #ifndef OPENSSL_NO_RSA
2250     unsigned char *q;
2251     EVP_PKEY *pkey = NULL;
2252 #endif
2253 #if !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)
2254     EVP_PKEY *ckey = NULL, *skey = NULL;
2255 #endif
2256 #ifndef OPENSSL_NO_EC
2257     unsigned char *encodedPoint = NULL;
2258     int encoded_pt_len = 0;
2259 #endif
2260     unsigned char *pms = NULL;
2261     size_t pmslen = 0;
2262     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2263
2264     p = ssl_handshake_start(s);
2265
2266
2267 #ifndef OPENSSL_NO_PSK
2268     if (alg_k & SSL_PSK) {
2269         int psk_err = 1;
2270         /*
2271          * The callback needs PSK_MAX_IDENTITY_LEN + 1 bytes to return a
2272          * \0-terminated identity. The last byte is for us for simulating
2273          * strnlen.
2274          */
2275         char identity[PSK_MAX_IDENTITY_LEN + 1];
2276         size_t identitylen;
2277         unsigned char psk[PSK_MAX_PSK_LEN];
2278         size_t psklen;
2279
2280         if (s->psk_client_callback == NULL) {
2281             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2282                    SSL_R_PSK_NO_CLIENT_CB);
2283             goto err;
2284         }
2285
2286         memset(identity, 0, sizeof(identity));
2287
2288         psklen = s->psk_client_callback(s, s->session->psk_identity_hint,
2289                                         identity, sizeof(identity) - 1,
2290                                         psk, sizeof(psk));
2291
2292         if (psklen > PSK_MAX_PSK_LEN) {
2293             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2294                    ERR_R_INTERNAL_ERROR);
2295             goto psk_err;
2296         } else if (psklen == 0) {
2297             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2298                    SSL_R_PSK_IDENTITY_NOT_FOUND);
2299             goto psk_err;
2300         }
2301         OPENSSL_free(s->s3->tmp.psk);
2302         s->s3->tmp.psk = OPENSSL_memdup(psk, psklen);
2303         OPENSSL_cleanse(psk, psklen);
2304
2305         if (s->s3->tmp.psk == NULL) {
2306             OPENSSL_cleanse(identity, sizeof(identity));
2307             goto memerr;
2308         }
2309
2310         s->s3->tmp.psklen = psklen;
2311         identitylen = strlen(identity);
2312         if (identitylen > PSK_MAX_IDENTITY_LEN) {
2313             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2314                    ERR_R_INTERNAL_ERROR);
2315             goto psk_err;
2316         }
2317         OPENSSL_free(s->session->psk_identity);
2318         s->session->psk_identity = OPENSSL_strdup(identity);
2319         if (s->session->psk_identity == NULL) {
2320             OPENSSL_cleanse(identity, sizeof(identity));
2321             goto memerr;
2322         }
2323
2324         s2n(identitylen, p);
2325         memcpy(p, identity, identitylen);
2326         pskhdrlen = 2 + identitylen;
2327         p += identitylen;
2328         psk_err = 0;
2329 psk_err:
2330         OPENSSL_cleanse(identity, sizeof(identity));
2331         if (psk_err != 0) {
2332             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2333             goto err;
2334         }
2335     }
2336     if (alg_k & SSL_kPSK) {
2337         n = 0;
2338     } else
2339 #endif
2340
2341     /* Fool emacs indentation */
2342     if (0) {
2343     }
2344 #ifndef OPENSSL_NO_RSA
2345     else if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
2346         RSA *rsa;
2347         pmslen = SSL_MAX_MASTER_KEY_LENGTH;
2348         pms = OPENSSL_malloc(pmslen);
2349         if (pms == NULL)
2350             goto memerr;
2351
2352         if (s->session->peer == NULL) {
2353             /*
2354              * We should always have a server certificate with SSL_kRSA.
2355              */
2356             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2357                    ERR_R_INTERNAL_ERROR);
2358             goto err;
2359         }
2360
2361         pkey = X509_get_pubkey(s->session->peer);
2362         if ((pkey == NULL) || (pkey->type != EVP_PKEY_RSA)
2363             || (pkey->pkey.rsa == NULL)) {
2364             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2365                    ERR_R_INTERNAL_ERROR);
2366             EVP_PKEY_free(pkey);
2367             goto err;
2368         }
2369         rsa = pkey->pkey.rsa;
2370         EVP_PKEY_free(pkey);
2371
2372         pms[0] = s->client_version >> 8;
2373         pms[1] = s->client_version & 0xff;
2374         if (RAND_bytes(pms + 2, pmslen - 2) <= 0)
2375             goto err;
2376
2377         q = p;
2378         /* Fix buf for TLS and beyond */
2379         if (s->version > SSL3_VERSION)
2380             p += 2;
2381         n = RSA_public_encrypt(pmslen, pms, p, rsa, RSA_PKCS1_PADDING);
2382 # ifdef PKCS1_CHECK
2383         if (s->options & SSL_OP_PKCS1_CHECK_1)
2384             p[1]++;
2385         if (s->options & SSL_OP_PKCS1_CHECK_2)
2386             tmp_buf[0] = 0x70;
2387 # endif
2388         if (n <= 0) {
2389             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2390                    SSL_R_BAD_RSA_ENCRYPT);
2391             goto err;
2392         }
2393
2394         /* Fix buf for TLS and beyond */
2395         if (s->version > SSL3_VERSION) {
2396             s2n(n, q);
2397             n += 2;
2398         }
2399     }
2400 #endif
2401 #ifndef OPENSSL_NO_DH
2402     else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
2403         DH *dh_clnt = NULL;
2404         skey = s->s3->peer_tmp;
2405         if (skey == NULL) {
2406             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2407                    ERR_R_INTERNAL_ERROR);
2408             goto err;
2409         }
2410         ckey = ssl_generate_pkey(skey, NID_undef);
2411         dh_clnt = EVP_PKEY_get0_DH(ckey);
2412
2413         if (dh_clnt == NULL || ssl_derive(s, ckey, skey) == 0) {
2414             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2415                    ERR_R_INTERNAL_ERROR);
2416             goto err;
2417         }
2418
2419
2420         /* send off the data */
2421         n = BN_num_bytes(dh_clnt->pub_key);
2422         s2n(n, p);
2423         BN_bn2bin(dh_clnt->pub_key, p);
2424         n += 2;
2425         EVP_PKEY_free(ckey);
2426         ckey = NULL;
2427     }
2428 #endif
2429
2430 #ifndef OPENSSL_NO_EC
2431     else if (alg_k & (SSL_kECDHE | SSL_kECDHr | SSL_kECDHe | SSL_kECDHEPSK)) {
2432
2433         if (s->s3->peer_tmp != NULL) {
2434             skey = s->s3->peer_tmp;
2435         } else {
2436             /* Get the Server Public Key from Cert */
2437             skey = X509_get0_pubkey(s->session->peer);
2438             if ((skey == NULL)
2439                 || (skey->type != EVP_PKEY_EC)
2440                 || (skey->pkey.ec == NULL)) {
2441                 SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2442                        ERR_R_INTERNAL_ERROR);
2443                 goto err;
2444             }
2445         }
2446
2447         ckey = ssl_generate_pkey(skey, NID_undef);
2448
2449         if (ssl_derive(s, ckey, skey) == 0) {
2450             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_EVP_LIB);
2451             goto err;
2452         }
2453
2454         /* Generate encoding of client key */
2455         encoded_pt_len = EC_KEY_key2buf(EVP_PKEY_get0_EC_KEY(ckey),
2456                                         POINT_CONVERSION_UNCOMPRESSED,
2457                                         &encodedPoint, NULL);
2458
2459         if (encoded_pt_len == 0) {
2460             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2461             goto err;
2462         }
2463
2464         EVP_PKEY_free(ckey);
2465         ckey = NULL;
2466
2467         n = encoded_pt_len;
2468
2469         *p = n;         /* length of encoded point */
2470         /* Encoded point will be copied here */
2471         p += 1;
2472         /* copy the point */
2473         memcpy(p, encodedPoint, n);
2474         /* increment n to account for length field */
2475         n += 1;
2476
2477         /* Free allocated memory */
2478         OPENSSL_free(encodedPoint);
2479     }
2480 #endif                          /* !OPENSSL_NO_EC */
2481 #ifndef OPENSSL_NO_GOST
2482     else if (alg_k & SSL_kGOST) {
2483         /* GOST key exchange message creation */
2484         EVP_PKEY_CTX *pkey_ctx;
2485         X509 *peer_cert;
2486         size_t msglen;
2487         unsigned int md_len;
2488         unsigned char shared_ukm[32], tmp[256];
2489         EVP_MD_CTX *ukm_hash;
2490         EVP_PKEY *pub_key;
2491         int dgst_nid = NID_id_GostR3411_94;
2492         if ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aGOST12) != 0)
2493             dgst_nid = NID_id_GostR3411_2012_256;
2494
2495
2496         pmslen = 32;
2497         pms = OPENSSL_malloc(pmslen);
2498         if (pms == NULL)
2499             goto memerr;
2500
2501         /*
2502          * Get server sertificate PKEY and create ctx from it
2503          */
2504         peer_cert = s->session->peer;
2505         if (!peer_cert) {
2506             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2507                    SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
2508             goto err;
2509         }
2510
2511         pkey_ctx = EVP_PKEY_CTX_new(pub_key =
2512                                     X509_get_pubkey(peer_cert), NULL);
2513         if (pkey_ctx == NULL) {
2514             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2515                    ERR_R_MALLOC_FAILURE);
2516             goto err;
2517         }
2518         /*
2519          * If we have send a certificate, and certificate key
2520          * parameters match those of server certificate, use
2521          * certificate key for key exchange
2522          */
2523
2524         /* Otherwise, generate ephemeral key pair */
2525
2526         if (pkey_ctx == NULL
2527                 || EVP_PKEY_encrypt_init(pkey_ctx) <= 0
2528                 /* Generate session key */
2529                 || RAND_bytes(pms, pmslen) <= 0) {
2530             EVP_PKEY_CTX_free(pkey_ctx);
2531             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2532                    ERR_R_INTERNAL_ERROR);
2533             goto err;
2534         };
2535         /*
2536          * If we have client certificate, use its secret as peer key
2537          */
2538         if (s->s3->tmp.cert_req && s->cert->key->privatekey) {
2539             if (EVP_PKEY_derive_set_peer
2540                 (pkey_ctx, s->cert->key->privatekey) <= 0) {
2541                 /*
2542                  * If there was an error - just ignore it. Ephemeral key
2543                  * * would be used
2544                  */
2545                 ERR_clear_error();
2546             }
2547         }
2548         /*
2549          * Compute shared IV and store it in algorithm-specific context
2550          * data
2551          */
2552         ukm_hash = EVP_MD_CTX_new();
2553         if (EVP_DigestInit(ukm_hash,
2554                            EVP_get_digestbynid(dgst_nid)) <= 0
2555                 || EVP_DigestUpdate(ukm_hash, s->s3->client_random,
2556                                     SSL3_RANDOM_SIZE) <= 0
2557                 || EVP_DigestUpdate(ukm_hash, s->s3->server_random,
2558                                     SSL3_RANDOM_SIZE) <= 0
2559                 || EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len) <= 0) {
2560             EVP_MD_CTX_free(ukm_hash);
2561             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2562                    ERR_R_INTERNAL_ERROR);
2563             goto err;
2564         }
2565         EVP_MD_CTX_free(ukm_hash);
2566         if (EVP_PKEY_CTX_ctrl
2567             (pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT, EVP_PKEY_CTRL_SET_IV, 8,
2568              shared_ukm) < 0) {
2569             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2570                    SSL_R_LIBRARY_BUG);
2571             goto err;
2572         }
2573         /* Make GOST keytransport blob message */
2574         /*
2575          * Encapsulate it into sequence
2576          */
2577         *(p++) = V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED;
2578         msglen = 255;
2579         if (EVP_PKEY_encrypt(pkey_ctx, tmp, &msglen, pms, pmslen) <= 0) {
2580             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2581                    SSL_R_LIBRARY_BUG);
2582             goto err;
2583         }
2584         if (msglen >= 0x80) {
2585             *(p++) = 0x81;
2586             *(p++) = msglen & 0xff;
2587             n = msglen + 3;
2588         } else {
2589             *(p++) = msglen & 0xff;
2590             n = msglen + 2;
2591         }
2592         memcpy(p, tmp, msglen);
2593         /* Check if pubkey from client certificate was used */
2594         if (EVP_PKEY_CTX_ctrl
2595             (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0) {
2596             /* Set flag "skip certificate verify" */
2597             s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
2598         }
2599         EVP_PKEY_CTX_free(pkey_ctx);
2600         EVP_PKEY_free(pub_key);
2601
2602     }
2603 #endif
2604 #ifndef OPENSSL_NO_SRP
2605     else if (alg_k & SSL_kSRP) {
2606         if (s->srp_ctx.A != NULL) {
2607             /* send off the data */
2608             n = BN_num_bytes(s->srp_ctx.A);
2609             s2n(n, p);
2610             BN_bn2bin(s->srp_ctx.A, p);
2611             n += 2;
2612         } else {
2613             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2614                    ERR_R_INTERNAL_ERROR);
2615             goto err;
2616         }
2617         OPENSSL_free(s->session->srp_username);
2618         s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);
2619         if (s->session->srp_username == NULL) {
2620             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE,
2621                    ERR_R_MALLOC_FAILURE);
2622             goto err;
2623         }
2624     }
2625 #endif
2626     else {
2627         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2628         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2629         goto err;
2630     }
2631
2632 #ifndef OPENSSL_NO_PSK
2633     n += pskhdrlen;
2634 #endif
2635
2636     if (!ssl_set_handshake_header(s, SSL3_MT_CLIENT_KEY_EXCHANGE, n)) {
2637         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2638         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2639         goto err;
2640     }
2641
2642     if (pms != NULL) {
2643         s->s3->tmp.pms = pms;
2644         s->s3->tmp.pmslen = pmslen;
2645     }
2646
2647     return 1;
2648  memerr:
2649     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2650     SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2651  err:
2652     OPENSSL_clear_free(pms, pmslen);
2653     s->s3->tmp.pms = NULL;
2654 #ifndef OPENSSL_NO_EC
2655     OPENSSL_free(encodedPoint);
2656 #endif
2657 #if !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)
2658     EVP_PKEY_free(ckey);
2659 #endif
2660 #ifndef OPENSSL_NO_PSK
2661     OPENSSL_clear_free(s->s3->tmp.psk, s->s3->tmp.psklen);
2662     s->s3->tmp.psk = NULL;
2663 #endif
2664     ossl_statem_set_error(s);
2665     return 0;
2666 }
2667
2668 int tls_client_key_exchange_post_work(SSL *s)
2669 {
2670     unsigned char *pms = NULL;
2671     size_t pmslen = 0;
2672
2673 #ifndef OPENSSL_NO_SRP
2674     /* Check for SRP */
2675     if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) {
2676         if (!srp_generate_client_master_secret(s)) {
2677             SSLerr(SSL_F_TLS_CLIENT_KEY_EXCHANGE_POST_WORK,
2678                    ERR_R_INTERNAL_ERROR);
2679             goto err;
2680         }
2681         return 1;
2682     }
2683 #endif
2684     pms = s->s3->tmp.pms;
2685     pmslen = s->s3->tmp.pmslen;
2686
2687     if (pms == NULL && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
2688         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2689         SSLerr(SSL_F_TLS_CLIENT_KEY_EXCHANGE_POST_WORK, ERR_R_MALLOC_FAILURE);
2690         goto err;
2691     }
2692     if (!ssl_generate_master_secret(s, pms, pmslen, 1)) {
2693         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2694         SSLerr(SSL_F_TLS_CLIENT_KEY_EXCHANGE_POST_WORK, ERR_R_INTERNAL_ERROR);
2695         goto err;
2696     }
2697
2698 #ifndef OPENSSL_NO_SCTP
2699     if (SSL_IS_DTLS(s)) {
2700         unsigned char sctpauthkey[64];
2701         char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
2702
2703         /*
2704          * Add new shared key for SCTP-Auth, will be ignored if no SCTP
2705          * used.
2706          */
2707         memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
2708                sizeof(DTLS1_SCTP_AUTH_LABEL));
2709
2710         if (SSL_export_keying_material(s, sctpauthkey,
2711                                    sizeof(sctpauthkey), labelbuffer,
2712                                    sizeof(labelbuffer), NULL, 0, 0) <= 0)
2713             goto err;
2714
2715         BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
2716                  sizeof(sctpauthkey), sctpauthkey);
2717     }
2718 #endif
2719
2720     return 1;
2721  err:
2722     OPENSSL_clear_free(pms, pmslen);
2723     s->s3->tmp.pms = NULL;
2724     return 0;
2725 }
2726
2727 int tls_construct_client_verify(SSL *s)
2728 {
2729     unsigned char *p;
2730     EVP_PKEY *pkey;
2731     const EVP_MD *md = s->s3->tmp.md[s->cert->key - s->cert->pkeys];
2732     EVP_MD_CTX *mctx;
2733     unsigned u = 0;
2734     unsigned long n = 0;
2735     long hdatalen = 0;
2736     void *hdata;
2737
2738     mctx = EVP_MD_CTX_new();
2739     if (mctx == NULL) {
2740         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_MALLOC_FAILURE);
2741         goto err;
2742     }
2743
2744     p = ssl_handshake_start(s);
2745     pkey = s->cert->key->privatekey;
2746
2747     hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
2748     if (hdatalen <= 0) {
2749         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
2750         goto err;
2751     }
2752     if (SSL_USE_SIGALGS(s)) {
2753         if (!tls12_get_sigandhash(p, pkey, md)) {
2754             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
2755             goto err;
2756         }
2757         p += 2;
2758         n = 2;
2759     }
2760 #ifdef SSL_DEBUG
2761     fprintf(stderr, "Using client alg %s\n", EVP_MD_name(md));
2762 #endif
2763     if (!EVP_SignInit_ex(mctx, md, NULL)
2764         || !EVP_SignUpdate(mctx, hdata, hdatalen)
2765         || (s->version == SSL3_VERSION
2766             && !EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
2767                                 s->session->master_key_length,
2768                                 s->session->master_key))
2769         || !EVP_SignFinal(mctx, p + 2, &u, pkey)) {
2770         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_EVP_LIB);
2771         goto err;
2772     }
2773 #ifndef OPENSSL_NO_GOST
2774     if (pkey->type == NID_id_GostR3410_2001
2775             || pkey->type == NID_id_GostR3410_2012_256
2776             || pkey->type == NID_id_GostR3410_2012_512) {
2777         BUF_reverse(p + 2, NULL, u);
2778     }
2779 #endif
2780
2781     s2n(u, p);
2782     n += u + 2;
2783     /* Digest cached records and discard handshake buffer */
2784     if (!ssl3_digest_cached_records(s, 0))
2785         goto err;
2786     if (!ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_VERIFY, n)) {
2787         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
2788         goto err;
2789     }
2790
2791     EVP_MD_CTX_free(mctx);
2792     return 1;
2793  err:
2794     EVP_MD_CTX_free(mctx);
2795     return 0;
2796 }
2797
2798 /*
2799  * Check a certificate can be used for client authentication. Currently check
2800  * cert exists, if we have a suitable digest for TLS 1.2 if static DH client
2801  * certificates can be used and optionally checks suitability for Suite B.
2802  */
2803 static int ssl3_check_client_certificate(SSL *s)
2804 {
2805     if (!s->cert || !s->cert->key->x509 || !s->cert->key->privatekey)
2806         return 0;
2807     /* If no suitable signature algorithm can't use certificate */
2808     if (SSL_USE_SIGALGS(s) && !s->s3->tmp.md[s->cert->key - s->cert->pkeys])
2809         return 0;
2810     /*
2811      * If strict mode check suitability of chain before using it. This also
2812      * adjusts suite B digest if necessary.
2813      */
2814     if (s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT &&
2815         !tls1_check_chain(s, NULL, NULL, NULL, -2))
2816         return 0;
2817     return 1;
2818 }
2819
2820 WORK_STATE tls_prepare_client_certificate(SSL *s, WORK_STATE wst)
2821 {
2822     X509 *x509 = NULL;
2823     EVP_PKEY *pkey = NULL;
2824     int i;
2825
2826     if (wst == WORK_MORE_A) {
2827         /* Let cert callback update client certificates if required */
2828         if (s->cert->cert_cb) {
2829             i = s->cert->cert_cb(s, s->cert->cert_cb_arg);
2830             if (i < 0) {
2831                 s->rwstate = SSL_X509_LOOKUP;
2832                 return WORK_MORE_A;
2833             }
2834             if (i == 0) {
2835                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2836                 ossl_statem_set_error(s);
2837                 return 0;
2838             }
2839             s->rwstate = SSL_NOTHING;
2840         }
2841         if (ssl3_check_client_certificate(s))
2842             return WORK_FINISHED_CONTINUE;
2843
2844         /* Fall through to WORK_MORE_B */
2845         wst = WORK_MORE_B;
2846     }
2847
2848     /* We need to get a client cert */
2849     if (wst == WORK_MORE_B) {
2850         /*
2851          * If we get an error, we need to ssl->rwstate=SSL_X509_LOOKUP;
2852          * return(-1); We then get retied later
2853          */
2854         i = ssl_do_client_cert_cb(s, &x509, &pkey);
2855         if (i < 0) {
2856             s->rwstate = SSL_X509_LOOKUP;
2857             return WORK_MORE_B;
2858         }
2859         s->rwstate = SSL_NOTHING;
2860         if ((i == 1) && (pkey != NULL) && (x509 != NULL)) {
2861             if (!SSL_use_certificate(s, x509) || !SSL_use_PrivateKey(s, pkey))
2862                 i = 0;
2863         } else if (i == 1) {
2864             i = 0;
2865             SSLerr(SSL_F_TLS_PREPARE_CLIENT_CERTIFICATE,
2866                    SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
2867         }
2868
2869         X509_free(x509);
2870         EVP_PKEY_free(pkey);
2871         if (i && !ssl3_check_client_certificate(s))
2872             i = 0;
2873         if (i == 0) {
2874             if (s->version == SSL3_VERSION) {
2875                 s->s3->tmp.cert_req = 0;
2876                 ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_CERTIFICATE);
2877                 return WORK_FINISHED_CONTINUE;
2878             } else {
2879                 s->s3->tmp.cert_req = 2;
2880                 if (!ssl3_digest_cached_records(s, 0)) {
2881                     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2882                     ossl_statem_set_error(s);
2883                     return 0;
2884                 }
2885             }
2886         }
2887
2888         return WORK_FINISHED_CONTINUE;
2889     }
2890
2891     /* Shouldn't ever get here */
2892     return WORK_ERROR;
2893 }
2894
2895 int tls_construct_client_certificate(SSL *s)
2896 {
2897     if (!ssl3_output_cert_chain(s,
2898                                 (s->s3->tmp.cert_req ==
2899                                  2) ? NULL : s->cert->key)) {
2900         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_CERTIFICATE, ERR_R_INTERNAL_ERROR);
2901         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2902         ossl_statem_set_error(s);
2903         return 0;
2904     }
2905
2906     return 1;
2907 }
2908
2909 #define has_bits(i,m)   (((i)&(m)) == (m))
2910
2911 int ssl3_check_cert_and_algorithm(SSL *s)
2912 {
2913     int i;
2914 #ifndef OPENSSL_NO_EC
2915     int idx;
2916 #endif
2917     long alg_k, alg_a;
2918     EVP_PKEY *pkey = NULL;
2919     int al = SSL_AD_HANDSHAKE_FAILURE;
2920
2921     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2922     alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2923
2924     /* we don't have a certificate */
2925     if ((alg_a & SSL_aNULL) || (alg_k & SSL_kPSK))
2926         return (1);
2927
2928     /* This is the passed certificate */
2929
2930 #ifndef OPENSSL_NO_EC
2931     idx = s->session->peer_type;
2932     if (idx == SSL_PKEY_ECC) {
2933         if (ssl_check_srvr_ecc_cert_and_alg(s->session->peer, s) == 0) {
2934             /* check failed */
2935             SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_BAD_ECC_CERT);
2936             goto f_err;
2937         } else {
2938             return 1;
2939         }
2940     } else if (alg_a & SSL_aECDSA) {
2941         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
2942                SSL_R_MISSING_ECDSA_SIGNING_CERT);
2943         goto f_err;
2944     } else if (alg_k & (SSL_kECDHr | SSL_kECDHe)) {
2945         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_MISSING_ECDH_CERT);
2946         goto f_err;
2947     }
2948 #endif
2949     pkey = X509_get_pubkey(s->session->peer);
2950     i = X509_certificate_type(s->session->peer, pkey);
2951     EVP_PKEY_free(pkey);
2952
2953     /* Check that we have a certificate if we require one */
2954     if ((alg_a & SSL_aRSA) && !has_bits(i, EVP_PK_RSA | EVP_PKT_SIGN)) {
2955         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
2956                SSL_R_MISSING_RSA_SIGNING_CERT);
2957         goto f_err;
2958     }
2959 #ifndef OPENSSL_NO_DSA
2960     else if ((alg_a & SSL_aDSS) && !has_bits(i, EVP_PK_DSA | EVP_PKT_SIGN)) {
2961         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
2962                SSL_R_MISSING_DSA_SIGNING_CERT);
2963         goto f_err;
2964     }
2965 #endif
2966 #ifndef OPENSSL_NO_RSA
2967     if (alg_k & (SSL_kRSA | SSL_kRSAPSK) &&
2968         !has_bits(i, EVP_PK_RSA | EVP_PKT_ENC)) {
2969         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
2970                SSL_R_MISSING_RSA_ENCRYPTING_CERT);
2971         goto f_err;
2972     }
2973 #endif
2974 #ifndef OPENSSL_NO_DH
2975     if ((alg_k & SSL_kDHE) && (s->s3->peer_tmp == NULL)) {
2976         al = SSL_AD_INTERNAL_ERROR;
2977         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR);
2978         goto f_err;
2979     }
2980 #endif
2981
2982     return (1);
2983  f_err:
2984     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2985     return (0);
2986 }
2987
2988 #ifndef OPENSSL_NO_NEXTPROTONEG
2989 int tls_construct_next_proto(SSL *s)
2990 {
2991     unsigned int len, padding_len;
2992     unsigned char *d;
2993
2994     len = s->next_proto_negotiated_len;
2995     padding_len = 32 - ((len + 2) % 32);
2996     d = (unsigned char *)s->init_buf->data;
2997     d[4] = len;
2998     memcpy(d + 5, s->next_proto_negotiated, len);
2999     d[5 + len] = padding_len;
3000     memset(d + 6 + len, 0, padding_len);
3001     *(d++) = SSL3_MT_NEXT_PROTO;
3002     l2n3(2 + len + padding_len, d);
3003     s->init_num = 4 + 2 + len + padding_len;
3004     s->init_off = 0;
3005
3006     return 1;
3007 }
3008 #endif
3009
3010 int ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
3011 {
3012     int i = 0;
3013 #ifndef OPENSSL_NO_ENGINE
3014     if (s->ctx->client_cert_engine) {
3015         i = ENGINE_load_ssl_client_cert(s->ctx->client_cert_engine, s,
3016                                         SSL_get_client_CA_list(s),
3017                                         px509, ppkey, NULL, NULL, NULL);
3018         if (i != 0)
3019             return i;
3020     }
3021 #endif
3022     if (s->ctx->client_cert_cb)
3023         i = s->ctx->client_cert_cb(s, px509, ppkey);
3024     return i;
3025 }
3026
3027 int ssl_cipher_list_to_bytes(SSL *s, STACK_OF(SSL_CIPHER) *sk,
3028                              unsigned char *p)
3029 {
3030     int i, j = 0;
3031     SSL_CIPHER *c;
3032     unsigned char *q;
3033     int empty_reneg_info_scsv = !s->renegotiate;
3034     /* Set disabled masks for this session */
3035     ssl_set_client_disabled(s);
3036
3037     if (sk == NULL)
3038         return (0);
3039     q = p;
3040
3041     for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3042         c = sk_SSL_CIPHER_value(sk, i);
3043         /* Skip disabled ciphers */
3044         if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_SUPPORTED))
3045             continue;
3046 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
3047         if (c->id == SSL3_CK_SCSV) {
3048             if (!empty_reneg_info_scsv)
3049                 continue;
3050             else
3051                 empty_reneg_info_scsv = 0;
3052         }
3053 #endif
3054         j = s->method->put_cipher_by_char(c, p);
3055         p += j;
3056     }
3057     /*
3058      * If p == q, no ciphers; caller indicates an error. Otherwise, add
3059      * applicable SCSVs.
3060      */
3061     if (p != q) {
3062         if (empty_reneg_info_scsv) {
3063             static SSL_CIPHER scsv = {
3064                 0, NULL, SSL3_CK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
3065             };
3066             j = s->method->put_cipher_by_char(&scsv, p);
3067             p += j;
3068 #ifdef OPENSSL_RI_DEBUG
3069             fprintf(stderr,
3070                     "TLS_EMPTY_RENEGOTIATION_INFO_SCSV sent by client\n");
3071 #endif
3072         }
3073         if (s->mode & SSL_MODE_SEND_FALLBACK_SCSV) {
3074             static SSL_CIPHER scsv = {
3075                 0, NULL, SSL3_CK_FALLBACK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
3076             };
3077             j = s->method->put_cipher_by_char(&scsv, p);
3078             p += j;
3079         }
3080     }
3081
3082     return (p - q);
3083 }