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