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