d37415940f101c0afe416a3b3122b5c41ca434a1
[openssl.git] / ssl / statem / statem_srvr.c
1 /* ssl/statem/statem_srvr.c -*- mode:C; c-file-style: "eay" -*- */
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
152 #include <stdio.h>
153 #include "../ssl_locl.h"
154 #include "statem_locl.h"
155 #include "internal/constant_time_locl.h"
156 #include <openssl/buffer.h>
157 #include <openssl/rand.h>
158 #include <openssl/objects.h>
159 #include <openssl/evp.h>
160 #include <openssl/hmac.h>
161 #include <openssl/x509.h>
162 #ifndef OPENSSL_NO_DH
163 # include <openssl/dh.h>
164 #endif
165 #include <openssl/bn.h>
166 #include <openssl/md5.h>
167
168 static STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list(SSL *s,
169                                                       PACKET *cipher_suites,
170                                                       STACK_OF(SSL_CIPHER) **skp,
171                                                       int sslv2format, int *al);
172
173 /*
174  * server_read_transition() encapsulates the logic for the allowed handshake
175  * state transitions when the server is reading messages from the client. The
176  * message type that the client has sent is provided in |mt|. The current state
177  * is in |s->statem.hand_state|.
178  *
179  *  Valid return values are:
180  *  1: Success (transition allowed)
181  *  0: Error (transition not allowed)
182  */
183 int ossl_statem_server_read_transition(SSL *s, int mt)
184 {
185     OSSL_STATEM *st = &s->statem;
186
187     switch(st->hand_state) {
188     case TLS_ST_BEFORE:
189     case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
190         if (mt == SSL3_MT_CLIENT_HELLO) {
191             st->hand_state = TLS_ST_SR_CLNT_HELLO;
192             return 1;
193         }
194         break;
195
196     case TLS_ST_SW_SRVR_DONE:
197         /*
198          * If we get a CKE message after a ServerDone then either
199          * 1) We didn't request a Certificate
200          * OR
201          * 2) If we did request one then
202          *      a) We allow no Certificate to be returned
203          *      AND
204          *      b) We are running SSL3 (in TLS1.0+ the client must return a 0
205          *         list if we requested a certificate)
206          */
207         if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE
208                 && (!s->s3->tmp.cert_request
209                     || (!((s->verify_mode & SSL_VERIFY_PEER) &&
210                           (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
211                         && (s->version == SSL3_VERSION)))) {
212             st->hand_state = TLS_ST_SR_KEY_EXCH;
213             return 1;
214         } else if (s->s3->tmp.cert_request) {
215             if (mt == SSL3_MT_CERTIFICATE) {
216                 st->hand_state = TLS_ST_SR_CERT;
217                 return 1;
218             } 
219         }
220         break;
221
222     case TLS_ST_SR_CERT:
223         if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) {
224             st->hand_state = TLS_ST_SR_KEY_EXCH;
225             return 1;
226         }
227         break;
228
229     case TLS_ST_SR_KEY_EXCH:
230         /*
231          * We should only process a CertificateVerify message if we have
232          * received a Certificate from the client. If so then |s->session->peer|
233          * will be non NULL. In some instances a CertificateVerify message is
234          * not required even if the peer has sent a Certificate (e.g. such as in
235          * the case of static DH). In that case |st->no_cert_verify| should be
236          * set.
237          */
238         if (s->session->peer == NULL || st->no_cert_verify) {
239             if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
240                 /*
241                  * For the ECDH ciphersuites when the client sends its ECDH
242                  * pub key in a certificate, the CertificateVerify message is
243                  * not sent. Also for GOST ciphersuites when the client uses
244                  * its key from the certificate for key exchange.
245                  */
246                 st->hand_state = TLS_ST_SR_CHANGE;
247                 return 1;
248             }
249         } else {
250             if (mt == SSL3_MT_CERTIFICATE_VERIFY) {
251                 st->hand_state = TLS_ST_SR_CERT_VRFY;
252                 return 1;
253             }
254         }
255         break;
256
257     case TLS_ST_SR_CERT_VRFY:
258         if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
259             st->hand_state = TLS_ST_SR_CHANGE;
260             return 1;
261         }
262         break;
263
264     case TLS_ST_SR_CHANGE:
265 #ifndef OPENSSL_NO_NEXTPROTONEG
266         if (s->s3->next_proto_neg_seen) {
267             if (mt == SSL3_MT_NEXT_PROTO) {
268                 st->hand_state = TLS_ST_SR_NEXT_PROTO;
269                 return 1;
270             }
271         } else {
272 #endif
273             if (mt == SSL3_MT_FINISHED) {
274                 st->hand_state = TLS_ST_SR_FINISHED;
275                 return 1;
276             }
277 #ifndef OPENSSL_NO_NEXTPROTONEG
278         }
279 #endif
280         break;
281
282 #ifndef OPENSSL_NO_NEXTPROTONEG
283     case TLS_ST_SR_NEXT_PROTO:
284         if (mt == SSL3_MT_FINISHED) {
285             st->hand_state = TLS_ST_SR_FINISHED;
286             return 1;
287         }
288         break;
289 #endif
290
291     case TLS_ST_SW_FINISHED:
292         if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
293             st->hand_state = TLS_ST_SR_CHANGE;
294             return 1;
295         }
296         break;
297
298     default:
299         break;
300     }
301
302     /* No valid transition found */
303     return 0;
304 }
305
306 /*
307  * Should we send a ServerKeyExchange message?
308  *
309  * Valid return values are:
310  *   1: Yes
311  *   0: No
312  */
313 static int send_server_key_exchange(SSL *s)
314 {
315     unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
316
317     /*
318      * only send a ServerKeyExchange if DH or fortezza but we have a
319      * sign only certificate PSK: may send PSK identity hints For
320      * ECC ciphersuites, we send a serverKeyExchange message only if
321      * the cipher suite is either ECDH-anon or ECDHE. In other cases,
322      * the server certificate contains the server's public key for
323      * key exchange.
324      */
325     if (   (alg_k & SSL_kDHE)
326         || (alg_k & SSL_kECDHE)
327         /*
328          * PSK: send ServerKeyExchange if PSK identity hint if
329          * provided
330          */
331 #ifndef OPENSSL_NO_PSK
332         /* Only send SKE if we have identity hint for plain PSK */
333         || ((alg_k & (SSL_kPSK | SSL_kRSAPSK))
334             && s->cert->psk_identity_hint)
335         /* For other PSK always send SKE */
336         || (alg_k & (SSL_PSK & (SSL_kDHEPSK | SSL_kECDHEPSK)))
337 #endif
338 #ifndef OPENSSL_NO_SRP
339         /* SRP: send ServerKeyExchange */
340         || (alg_k & SSL_kSRP)
341 #endif
342        ) {
343         return 1;
344     }
345
346     return 0;
347 }
348
349 /*
350  * Should we send a CertificateRequest message?
351  *
352  * Valid return values are:
353  *   1: Yes
354  *   0: No
355  */
356 static int send_certificate_request(SSL *s)
357 {
358     if (
359            /* don't request cert unless asked for it: */
360            s->verify_mode & SSL_VERIFY_PEER
361            /*
362             * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert
363             * during re-negotiation:
364             */
365            && ((s->session->peer == NULL) ||
366                !(s->verify_mode & SSL_VERIFY_CLIENT_ONCE))
367            /*
368             * never request cert in anonymous ciphersuites (see
369             * section "Certificate request" in SSL 3 drafts and in
370             * RFC 2246):
371             */
372            && (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
373            /*
374             * ... except when the application insists on
375             * verification (against the specs, but s3_clnt.c accepts
376             * this for SSL 3)
377             */
378                || (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
379            /* don't request certificate for SRP auth */
380            && !(s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)
381            /*
382             * With normal PSK Certificates and Certificate Requests
383             * are omitted
384             */
385            && !(s->s3->tmp.new_cipher->algorithm_auth & SSL_aPSK)) {
386         return 1;
387     }
388
389     return 0;
390 }
391
392 /*
393  * server_write_transition() works out what handshake state to move to next
394  * when the server is writing messages to be sent to the client.
395  */
396 WRITE_TRAN ossl_statem_server_write_transition(SSL *s)
397 {
398     OSSL_STATEM *st = &s->statem;
399
400     switch(st->hand_state) {
401         case TLS_ST_BEFORE:
402             /* Just go straight to trying to read from the client */;
403             return WRITE_TRAN_FINISHED;
404
405         case TLS_ST_OK:
406             /* We must be trying to renegotiate */
407             st->hand_state = TLS_ST_SW_HELLO_REQ;
408             return WRITE_TRAN_CONTINUE;
409
410         case TLS_ST_SW_HELLO_REQ:
411             st->hand_state = TLS_ST_OK;
412             ossl_statem_set_in_init(s, 0);
413             return WRITE_TRAN_CONTINUE;
414
415         case TLS_ST_SR_CLNT_HELLO:
416             if (SSL_IS_DTLS(s) && !s->d1->cookie_verified
417                     && (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE))
418                 st->hand_state = DTLS_ST_SW_HELLO_VERIFY_REQUEST;
419             else
420                 st->hand_state = TLS_ST_SW_SRVR_HELLO;
421             return WRITE_TRAN_CONTINUE;
422
423         case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
424             return WRITE_TRAN_FINISHED;
425
426         case TLS_ST_SW_SRVR_HELLO:
427             if (s->hit) {
428                 if (s->tlsext_ticket_expected)
429                     st->hand_state = TLS_ST_SW_SESSION_TICKET;
430                 else
431                     st->hand_state = TLS_ST_SW_CHANGE;
432             } else {
433                 /* Check if it is anon DH or anon ECDH, */
434                 /* normal PSK or SRP */
435                 if (!(s->s3->tmp.new_cipher->algorithm_auth &
436                      (SSL_aNULL | SSL_aSRP | SSL_aPSK))) {
437                     st->hand_state = TLS_ST_SW_CERT;
438                 } else if (send_server_key_exchange(s)) {
439                     st->hand_state = TLS_ST_SW_KEY_EXCH;
440                 } else if (send_certificate_request(s)) {
441                     st->hand_state = TLS_ST_SW_CERT_REQ;
442                 } else {
443                     st->hand_state = TLS_ST_SW_SRVR_DONE;
444                 }
445             }
446             return WRITE_TRAN_CONTINUE;
447
448         case TLS_ST_SW_CERT:
449             if (s->tlsext_status_expected) {
450                 st->hand_state = TLS_ST_SW_CERT_STATUS;
451                 return WRITE_TRAN_CONTINUE;
452             }
453             /* Fall through */
454
455         case TLS_ST_SW_CERT_STATUS:
456             if (send_server_key_exchange(s)) {
457                 st->hand_state = TLS_ST_SW_KEY_EXCH;
458                 return WRITE_TRAN_CONTINUE;
459             }
460             /* Fall through */
461
462         case TLS_ST_SW_KEY_EXCH:
463             if (send_certificate_request(s)) {
464                 st->hand_state = TLS_ST_SW_CERT_REQ;
465                 return WRITE_TRAN_CONTINUE;
466             }
467             /* Fall through */
468
469         case TLS_ST_SW_CERT_REQ:
470             st->hand_state = TLS_ST_SW_SRVR_DONE;
471             return WRITE_TRAN_CONTINUE;
472
473         case TLS_ST_SW_SRVR_DONE:
474             return WRITE_TRAN_FINISHED;
475
476         case TLS_ST_SR_FINISHED:
477             if (s->hit) {
478                 st->hand_state = TLS_ST_OK;
479                 ossl_statem_set_in_init(s, 0);
480                 return WRITE_TRAN_CONTINUE;
481             } else if (s->tlsext_ticket_expected) {
482                 st->hand_state = TLS_ST_SW_SESSION_TICKET;
483             } else {
484                 st->hand_state = TLS_ST_SW_CHANGE;
485             }
486             return WRITE_TRAN_CONTINUE;
487
488         case TLS_ST_SW_SESSION_TICKET:
489             st->hand_state = TLS_ST_SW_CHANGE;
490             return WRITE_TRAN_CONTINUE;
491
492         case TLS_ST_SW_CHANGE:
493             st->hand_state = TLS_ST_SW_FINISHED;
494             return WRITE_TRAN_CONTINUE;
495
496         case TLS_ST_SW_FINISHED:
497             if (s->hit) {
498                 return WRITE_TRAN_FINISHED;
499             }
500             st->hand_state = TLS_ST_OK;
501             ossl_statem_set_in_init(s, 0);
502             return WRITE_TRAN_CONTINUE;
503
504         default:
505             /* Shouldn't happen */
506             return WRITE_TRAN_ERROR;
507     }
508 }
509
510 /*
511  * Perform any pre work that needs to be done prior to sending a message from
512  * the server to the client.
513  */
514 WORK_STATE ossl_statem_server_pre_work(SSL *s, WORK_STATE wst)
515 {
516     OSSL_STATEM *st = &s->statem;
517
518     switch(st->hand_state) {
519     case TLS_ST_SW_HELLO_REQ:
520         s->shutdown = 0;
521         if (SSL_IS_DTLS(s))
522             dtls1_clear_record_buffer(s);
523         break;
524
525     case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
526         s->shutdown = 0;
527         if (SSL_IS_DTLS(s)) {
528             dtls1_clear_record_buffer(s);
529             /* We don't buffer this message so don't use the timer */
530             st->use_timer = 0;
531         }
532         break;
533
534     case TLS_ST_SW_SRVR_HELLO:
535         if (SSL_IS_DTLS(s)) {
536             /*
537              * Messages we write from now on should be bufferred and
538              * retransmitted if necessary, so we need to use the timer now
539              */
540             st->use_timer = 1;
541         }
542         break;
543
544     case TLS_ST_SW_SRVR_DONE:
545 #ifndef OPENSSL_NO_SCTP
546         if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s)))
547             return dtls_wait_for_dry(s);
548 #endif
549         return WORK_FINISHED_CONTINUE;
550
551     case TLS_ST_SW_SESSION_TICKET:
552         if (SSL_IS_DTLS(s)) {
553             /*
554              * We're into the last flight. We don't retransmit the last flight
555              * unless we need to, so we don't use the timer
556              */
557             st->use_timer = 0;
558         }
559         break;
560
561     case TLS_ST_SW_CHANGE:
562         s->session->cipher = s->s3->tmp.new_cipher;
563         if (!s->method->ssl3_enc->setup_key_block(s)) {
564             ossl_statem_set_error(s);
565             return WORK_ERROR;
566         }
567         if (SSL_IS_DTLS(s)) {
568             /*
569              * We're into the last flight. We don't retransmit the last flight
570              * unless we need to, so we don't use the timer. This might have
571              * already been set to 0 if we sent a NewSessionTicket message,
572              * but we'll set it again here in case we didn't.
573              */
574             st->use_timer = 0;
575         }
576         return WORK_FINISHED_CONTINUE;
577
578     case TLS_ST_OK:
579         return tls_finish_handshake(s, wst);
580
581     default:
582         /* No pre work to be done */
583         break;
584     }
585
586     return WORK_FINISHED_CONTINUE;
587 }
588
589 /*
590  * Perform any work that needs to be done after sending a message from the
591  * server to the client.
592  */
593 WORK_STATE ossl_statem_server_post_work(SSL *s, WORK_STATE wst)
594 {
595     OSSL_STATEM *st = &s->statem;
596
597     s->init_num = 0;
598
599     switch(st->hand_state) {
600     case TLS_ST_SW_HELLO_REQ:
601         if (statem_flush(s) != 1)
602             return WORK_MORE_A;
603         ssl3_init_finished_mac(s);
604         break;
605
606     case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
607         if (statem_flush(s) != 1)
608             return WORK_MORE_A;
609         /* HelloVerifyRequest resets Finished MAC */
610         if (s->version != DTLS1_BAD_VER)
611             ssl3_init_finished_mac(s);
612         /*
613          * The next message should be another ClientHello which we need to
614          * treat like it was the first packet
615          */
616         s->first_packet = 1;
617         break;
618
619     case TLS_ST_SW_SRVR_HELLO:
620 #ifndef OPENSSL_NO_SCTP
621         if (SSL_IS_DTLS(s) && s->hit) {
622             unsigned char sctpauthkey[64];
623             char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
624
625             /*
626              * Add new shared key for SCTP-Auth, will be ignored if no
627              * SCTP used.
628              */
629             memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
630                    sizeof(DTLS1_SCTP_AUTH_LABEL));
631
632             if (SSL_export_keying_material(s, sctpauthkey,
633                     sizeof(sctpauthkey), labelbuffer,
634                     sizeof(labelbuffer), NULL, 0, 0) <= 0) {
635                 ossl_statem_set_error(s);
636                 return WORK_ERROR;
637             }
638
639             BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
640                      sizeof(sctpauthkey), sctpauthkey);
641         }
642 #endif
643         break;
644
645     case TLS_ST_SW_CHANGE:
646 #ifndef OPENSSL_NO_SCTP
647         if (SSL_IS_DTLS(s) && !s->hit) {
648             /*
649              * Change to new shared key of SCTP-Auth, will be ignored if
650              * no SCTP used.
651              */
652             BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
653                      0, NULL);
654         }
655 #endif
656         if (!s->method->ssl3_enc->change_cipher_state(s,
657                 SSL3_CHANGE_CIPHER_SERVER_WRITE)) {
658             ossl_statem_set_error(s);
659             return WORK_ERROR;
660         }
661
662         if (SSL_IS_DTLS(s))
663             dtls1_reset_seq_numbers(s, SSL3_CC_WRITE);
664         break;
665
666     case TLS_ST_SW_SRVR_DONE:
667         if (statem_flush(s) != 1)
668             return WORK_MORE_A;
669         break;
670
671     case TLS_ST_SW_FINISHED:
672         if (statem_flush(s) != 1)
673             return WORK_MORE_A;
674 #ifndef OPENSSL_NO_SCTP
675         if (SSL_IS_DTLS(s) && s->hit) {
676             /*
677              * Change to new shared key of SCTP-Auth, will be ignored if
678              * no SCTP used.
679              */
680             BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
681                      0, NULL);
682         }
683 #endif
684         break;
685
686     default:
687         /* No post work to be done */
688         break;
689     }
690
691     return WORK_FINISHED_CONTINUE;
692 }
693
694 /*
695  * Construct a message to be sent from the server to the client.
696  *
697  * Valid return values are:
698  *   1: Success
699  *   0: Error
700  */
701 int ossl_statem_server_construct_message(SSL *s)
702 {
703     OSSL_STATEM *st = &s->statem;
704
705     switch(st->hand_state) {
706     case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
707         return dtls_construct_hello_verify_request(s);
708
709     case TLS_ST_SW_HELLO_REQ:
710         return tls_construct_hello_request(s);
711
712     case TLS_ST_SW_SRVR_HELLO:
713         return tls_construct_server_hello(s);
714
715     case TLS_ST_SW_CERT:
716         return tls_construct_server_certificate(s);
717
718     case TLS_ST_SW_KEY_EXCH:
719         return tls_construct_server_key_exchange(s);
720
721     case TLS_ST_SW_CERT_REQ:
722         return tls_construct_certificate_request(s);
723
724     case TLS_ST_SW_SRVR_DONE:
725         return tls_construct_server_done(s);
726
727     case TLS_ST_SW_SESSION_TICKET:
728         return tls_construct_new_session_ticket(s);
729
730     case TLS_ST_SW_CERT_STATUS:
731         return tls_construct_cert_status(s);
732
733     case TLS_ST_SW_CHANGE:
734         if (SSL_IS_DTLS(s))
735             return dtls_construct_change_cipher_spec(s);
736         else
737             return tls_construct_change_cipher_spec(s);
738
739     case TLS_ST_SW_FINISHED:
740         return tls_construct_finished(s,
741                                       s->method->
742                                       ssl3_enc->server_finished_label,
743                                       s->method->
744                                       ssl3_enc->server_finished_label_len);
745
746     default:
747         /* Shouldn't happen */
748         break;
749     }
750
751     return 0;
752 }
753
754 #define CLIENT_KEY_EXCH_MAX_LENGTH      2048
755 #define NEXT_PROTO_MAX_LENGTH           514
756
757 /*
758  * Returns the maximum allowed length for the current message that we are
759  * reading. Excludes the message header.
760  */
761 unsigned long ossl_statem_server_max_message_size(SSL *s)
762 {
763     OSSL_STATEM *st = &s->statem;
764
765     switch(st->hand_state) {
766     case TLS_ST_SR_CLNT_HELLO:
767         return SSL3_RT_MAX_PLAIN_LENGTH;
768
769     case TLS_ST_SR_CERT:
770         return s->max_cert_list;
771
772     case TLS_ST_SR_KEY_EXCH:
773         return CLIENT_KEY_EXCH_MAX_LENGTH;
774
775     case TLS_ST_SR_CERT_VRFY:
776         return SSL3_RT_MAX_PLAIN_LENGTH;
777
778 #ifndef OPENSSL_NO_NEXTPROTONEG
779     case TLS_ST_SR_NEXT_PROTO:
780         return NEXT_PROTO_MAX_LENGTH;
781 #endif
782
783     case TLS_ST_SR_CHANGE:
784         return CCS_MAX_LENGTH;
785
786     case TLS_ST_SR_FINISHED:
787         return FINISHED_MAX_LENGTH;
788
789     default:
790         /* Shouldn't happen */
791         break;
792     }
793
794     return 0;
795 }
796
797 /*
798  * Process a message that the server has received from the client.
799  */
800 MSG_PROCESS_RETURN ossl_statem_server_process_message(SSL *s, PACKET *pkt)
801 {
802     OSSL_STATEM *st = &s->statem;
803
804     switch(st->hand_state) {
805     case TLS_ST_SR_CLNT_HELLO:
806         return tls_process_client_hello(s, pkt);
807
808     case TLS_ST_SR_CERT:
809         return tls_process_client_certificate(s, pkt);
810
811     case TLS_ST_SR_KEY_EXCH:
812         return tls_process_client_key_exchange(s, pkt);
813
814     case TLS_ST_SR_CERT_VRFY:
815         return tls_process_cert_verify(s, pkt);
816
817 #ifndef OPENSSL_NO_NEXTPROTONEG
818     case TLS_ST_SR_NEXT_PROTO:
819         return tls_process_next_proto(s, pkt);
820 #endif
821
822     case TLS_ST_SR_CHANGE:
823         return tls_process_change_cipher_spec(s, pkt);
824
825     case TLS_ST_SR_FINISHED:
826         return tls_process_finished(s, pkt);
827
828     default:
829         /* Shouldn't happen */
830         break;
831     }
832
833     return MSG_PROCESS_ERROR;
834 }
835
836 /*
837  * Perform any further processing required following the receipt of a message
838  * from the client
839  */
840 WORK_STATE ossl_statem_server_post_process_message(SSL *s, WORK_STATE wst)
841 {
842     OSSL_STATEM *st = &s->statem;
843
844     switch(st->hand_state) {
845     case TLS_ST_SR_CLNT_HELLO:
846         return tls_post_process_client_hello(s, wst);
847
848     case TLS_ST_SR_KEY_EXCH:
849         return tls_post_process_client_key_exchange(s, wst);
850
851     case TLS_ST_SR_CERT_VRFY:
852 #ifndef OPENSSL_NO_SCTP
853         if (    /* Is this SCTP? */
854                 BIO_dgram_is_sctp(SSL_get_wbio(s))
855                 /* Are we renegotiating? */
856                 && s->renegotiate
857                 && BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
858             s->s3->in_read_app_data = 2;
859             s->rwstate = SSL_READING;
860             BIO_clear_retry_flags(SSL_get_rbio(s));
861             BIO_set_retry_read(SSL_get_rbio(s));
862             ossl_statem_set_sctp_read_sock(s, 1);
863             return WORK_MORE_A;
864         } else {
865             ossl_statem_set_sctp_read_sock(s, 0);
866         }
867 #endif
868         return WORK_FINISHED_CONTINUE;
869
870     default:
871         break;
872     }
873
874     /* Shouldn't happen */
875     return WORK_ERROR;
876 }
877
878 #ifndef OPENSSL_NO_SRP
879 static int ssl_check_srp_ext_ClientHello(SSL *s, int *al)
880 {
881     int ret = SSL_ERROR_NONE;
882
883     *al = SSL_AD_UNRECOGNIZED_NAME;
884
885     if ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) &&
886         (s->srp_ctx.TLS_ext_srp_username_callback != NULL)) {
887         if (s->srp_ctx.login == NULL) {
888             /*
889              * RFC 5054 says SHOULD reject, we do so if There is no srp
890              * login name
891              */
892             ret = SSL3_AL_FATAL;
893             *al = SSL_AD_UNKNOWN_PSK_IDENTITY;
894         } else {
895             ret = SSL_srp_server_param_with_username(s, al);
896         }
897     }
898     return ret;
899 }
900 #endif
901
902 int tls_construct_hello_request(SSL *s)
903 {
904     if (!ssl_set_handshake_header(s, SSL3_MT_HELLO_REQUEST, 0)) {
905         SSLerr(SSL_F_TLS_CONSTRUCT_HELLO_REQUEST, ERR_R_INTERNAL_ERROR);
906         ossl_statem_set_error(s);
907         return 0;
908     }
909
910     return 1;
911 }
912
913 unsigned int dtls_raw_hello_verify_request(unsigned char *buf,
914                                             unsigned char *cookie,
915                                             unsigned char cookie_len)
916 {
917     unsigned int msg_len;
918     unsigned char *p;
919
920     p = buf;
921     /* Always use DTLS 1.0 version: see RFC 6347 */
922     *(p++) = DTLS1_VERSION >> 8;
923     *(p++) = DTLS1_VERSION & 0xFF;
924
925     *(p++) = (unsigned char)cookie_len;
926     memcpy(p, cookie, cookie_len);
927     p += cookie_len;
928     msg_len = p - buf;
929
930     return msg_len;
931 }
932
933 int dtls_construct_hello_verify_request(SSL *s)
934 {
935     unsigned int len;
936     unsigned char *buf;
937
938     buf = (unsigned char *)s->init_buf->data;
939
940     if (s->ctx->app_gen_cookie_cb == NULL ||
941         s->ctx->app_gen_cookie_cb(s, s->d1->cookie,
942                                   &(s->d1->cookie_len)) == 0 ||
943         s->d1->cookie_len > 255) {
944         SSLerr(SSL_F_DTLS_CONSTRUCT_HELLO_VERIFY_REQUEST,
945                SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
946         ossl_statem_set_error(s);
947         return 0;
948     }
949
950     len = dtls_raw_hello_verify_request(&buf[DTLS1_HM_HEADER_LENGTH],
951                                          s->d1->cookie, s->d1->cookie_len);
952
953     dtls1_set_message_header(s, buf, DTLS1_MT_HELLO_VERIFY_REQUEST, len, 0,
954                              len);
955     len += DTLS1_HM_HEADER_LENGTH;
956
957     /* number of bytes to write */
958     s->init_num = len;
959     s->init_off = 0;
960
961     return 1;
962 }
963
964 MSG_PROCESS_RETURN tls_process_client_hello(SSL *s, PACKET *pkt)
965 {
966     int i, al = SSL_AD_INTERNAL_ERROR;
967     unsigned int j, complen = 0;
968     unsigned long id;
969     SSL_CIPHER *c;
970 #ifndef OPENSSL_NO_COMP
971     SSL_COMP *comp = NULL;
972 #endif
973     STACK_OF(SSL_CIPHER) *ciphers = NULL;
974     int protverr = 1;
975     /* |cookie| will only be initialized for DTLS. */
976     PACKET session_id, cipher_suites, compression, extensions, cookie;
977     int is_v2_record;
978
979     is_v2_record = RECORD_LAYER_is_sslv2_record(&s->rlayer);
980
981     PACKET_null_init(&cookie);
982     /* First lets get s->client_version set correctly */
983     if (is_v2_record) {
984         unsigned int version;
985         unsigned int mt;
986         /*-
987          * An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2
988          * header is sent directly on the wire, not wrapped as a TLS
989          * record. Our record layer just processes the message length and passes
990          * the rest right through. Its format is:
991          * Byte  Content
992          * 0-1   msg_length - decoded by the record layer
993          * 2     msg_type - s->init_msg points here
994          * 3-4   version
995          * 5-6   cipher_spec_length
996          * 7-8   session_id_length
997          * 9-10  challenge_length
998          * ...   ...
999          */
1000
1001         if (!PACKET_get_1(pkt, &mt)
1002                 || mt != SSL2_MT_CLIENT_HELLO) {
1003             /*
1004              * Should never happen. We should have tested this in the record
1005              * layer in order to have determined that this is a SSLv2 record
1006              * in the first place
1007              */
1008             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1009             goto err;
1010         }
1011
1012         if (!PACKET_get_net_2(pkt, &version)) {
1013             /* No protocol version supplied! */
1014             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
1015             goto err;
1016         }
1017         if (version == 0x0002) {
1018             /* This is real SSLv2. We don't support it. */
1019             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
1020             goto err;
1021         } else if ((version & 0xff00) == (SSL3_VERSION_MAJOR << 8)) {
1022             /* SSLv3/TLS */
1023             s->client_version = version;
1024         } else {
1025             /* No idea what protocol this is */
1026             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
1027             goto err;
1028         }
1029     } else {
1030         /*
1031          * use version from inside client hello, not from record header (may
1032          * differ: see RFC 2246, Appendix E, second paragraph)
1033          */
1034         if(!PACKET_get_net_2(pkt, (unsigned int *)&s->client_version)) {
1035             al = SSL_AD_DECODE_ERROR;
1036             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1037             goto f_err;
1038         }
1039     }
1040
1041     /* Do SSL/TLS version negotiation if applicable */
1042     if (!SSL_IS_DTLS(s)) {
1043         if (s->version != TLS_ANY_VERSION) {
1044             if (s->client_version >= s->version) {
1045                 protverr = 0;
1046             }
1047         } else if (s->client_version >= SSL3_VERSION) {
1048             switch(s->client_version) {
1049             default:
1050             case TLS1_2_VERSION:
1051                 if(!(s->options & SSL_OP_NO_TLSv1_2)) {
1052                     s->version = TLS1_2_VERSION;
1053                     s->method = TLSv1_2_server_method();
1054                     protverr = 0;
1055                     break;
1056                 }
1057                 /* Deliberately fall through */
1058             case TLS1_1_VERSION:
1059                 if(!(s->options & SSL_OP_NO_TLSv1_1)) {
1060                     s->version = TLS1_1_VERSION;
1061                     s->method = TLSv1_1_server_method();
1062                     protverr = 0;
1063                     break;
1064                 }
1065                 /* Deliberately fall through */
1066             case TLS1_VERSION:
1067                 if(!(s->options & SSL_OP_NO_TLSv1)) {
1068                     s->version = TLS1_VERSION;
1069                     s->method = TLSv1_server_method();
1070                     protverr = 0;
1071                     break;
1072                 }
1073                 /* Deliberately fall through */
1074             case SSL3_VERSION:
1075 #ifndef OPENSSL_NO_SSL3
1076                 if(!(s->options & SSL_OP_NO_SSLv3)) {
1077                     s->version = SSL3_VERSION;
1078                     s->method = SSLv3_server_method();
1079                     protverr = 0;
1080                     break;
1081                 }
1082 #else
1083                 break;
1084 #endif
1085             }
1086         }
1087     } else if (s->client_version <= s->version
1088                 || s->method->version == DTLS_ANY_VERSION) {
1089         /*
1090          * For DTLS we just check versions are potentially compatible. Version
1091          * negotiation comes later.
1092          */
1093         protverr = 0;
1094     }
1095
1096     if (protverr) {
1097         SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
1098         if ((!s->enc_write_ctx && !s->write_hash)) {
1099             /*
1100              * similar to ssl3_get_record, send alert using remote version
1101              * number
1102              */
1103             s->version = s->client_version;
1104         }
1105         al = SSL_AD_PROTOCOL_VERSION;
1106         goto f_err;
1107     }
1108
1109     /* Parse the message and load client random. */
1110     if (is_v2_record) {
1111         /*
1112          * Handle an SSLv2 backwards compatible ClientHello
1113          * Note, this is only for SSLv3+ using the backward compatible format.
1114          * Real SSLv2 is not supported, and is rejected above.
1115          */
1116         unsigned int cipher_len, session_id_len, challenge_len;
1117         PACKET challenge;
1118
1119         if (!PACKET_get_net_2(pkt, &cipher_len)
1120                 || !PACKET_get_net_2(pkt, &session_id_len)
1121                 || !PACKET_get_net_2(pkt, &challenge_len)) {
1122             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1123                    SSL_R_RECORD_LENGTH_MISMATCH);
1124             al = SSL_AD_DECODE_ERROR;
1125             goto f_err;
1126         }
1127
1128         if (!PACKET_get_sub_packet(pkt, &cipher_suites, cipher_len)
1129             || !PACKET_get_sub_packet(pkt, &session_id, session_id_len)
1130             || !PACKET_get_sub_packet(pkt, &challenge, challenge_len)
1131             /* No extensions. */
1132             || PACKET_remaining(pkt) != 0) {
1133             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1134                    SSL_R_RECORD_LENGTH_MISMATCH);
1135             al = SSL_AD_DECODE_ERROR;
1136             goto f_err;
1137         }
1138
1139         /* Load the client random */
1140         challenge_len = challenge_len > SSL3_RANDOM_SIZE ? SSL3_RANDOM_SIZE :
1141             challenge_len;
1142         memset(s->s3->client_random, 0, SSL3_RANDOM_SIZE);
1143         if (!PACKET_copy_bytes(&challenge,
1144                                s->s3->client_random + SSL3_RANDOM_SIZE -
1145                                challenge_len, challenge_len)) {
1146             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1147             al = SSL_AD_INTERNAL_ERROR;
1148             goto f_err;
1149         }
1150
1151         PACKET_null_init(&compression);
1152         PACKET_null_init(&extensions);
1153     } else {
1154         /* Regular ClientHello. */
1155         if (!PACKET_copy_bytes(pkt, s->s3->client_random, SSL3_RANDOM_SIZE)
1156             || !PACKET_get_length_prefixed_1(pkt, &session_id)) {
1157             al = SSL_AD_DECODE_ERROR;
1158             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1159             goto f_err;
1160         }
1161
1162         if (SSL_IS_DTLS(s)) {
1163             if (!PACKET_get_length_prefixed_1(pkt, &cookie)) {
1164                 al = SSL_AD_DECODE_ERROR;
1165                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1166                 goto f_err;
1167             }
1168             /*
1169              * If we require cookies and this ClientHello doesn't contain one,
1170              * just return since we do not want to allocate any memory yet.
1171              * So check cookie length...
1172              */
1173             if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1174                 if (PACKET_remaining(&cookie) == 0)
1175                 return 1;
1176             }
1177         }
1178
1179         if (!PACKET_get_length_prefixed_2(pkt, &cipher_suites)
1180             || !PACKET_get_length_prefixed_1(pkt, &compression)) {
1181                 al = SSL_AD_DECODE_ERROR;
1182                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1183                 goto f_err;
1184         }
1185         /* Could be empty. */
1186         extensions = *pkt;
1187     }
1188
1189     s->hit = 0;
1190
1191     /*
1192      * We don't allow resumption in a backwards compatible ClientHello.
1193      * TODO(openssl-team): in TLS1.1+, session_id MUST be empty.
1194      *
1195      * Versions before 0.9.7 always allow clients to resume sessions in
1196      * renegotiation. 0.9.7 and later allow this by default, but optionally
1197      * ignore resumption requests with flag
1198      * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
1199      * than a change to default behavior so that applications relying on
1200      * this for security won't even compile against older library versions).
1201      * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
1202      * request renegotiation but not a new session (s->new_session remains
1203      * unset): for servers, this essentially just means that the
1204      * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be
1205      * ignored.
1206      */
1207     if (is_v2_record ||
1208         (s->new_session &&
1209          (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
1210         if (!ssl_get_new_session(s, 1))
1211             goto err;
1212     } else {
1213         i = ssl_get_prev_session(s, &extensions, &session_id);
1214         /*
1215          * Only resume if the session's version matches the negotiated
1216          * version.
1217          * RFC 5246 does not provide much useful advice on resumption
1218          * with a different protocol version. It doesn't forbid it but
1219          * the sanity of such behaviour would be questionable.
1220          * In practice, clients do not accept a version mismatch and
1221          * will abort the handshake with an error.
1222          */
1223         if (i == 1 && s->version == s->session->ssl_version) {
1224             /* previous session */
1225             s->hit = 1;
1226         } else if (i == -1) {
1227             goto err;
1228         } else {
1229             /* i == 0 */
1230             if (!ssl_get_new_session(s, 1))
1231                 goto err;
1232         }
1233     }
1234
1235     if (SSL_IS_DTLS(s)) {
1236         /* Empty cookie was already handled above by returning early. */
1237         if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1238             if (s->ctx->app_verify_cookie_cb != NULL) {
1239                 if (s->ctx->app_verify_cookie_cb(s, PACKET_data(&cookie),
1240                                                  PACKET_remaining(&cookie)) == 0) {
1241                     al = SSL_AD_HANDSHAKE_FAILURE;
1242                     SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1243                            SSL_R_COOKIE_MISMATCH);
1244                     goto f_err;
1245                     /* else cookie verification succeeded */
1246                 }
1247             /* default verification */
1248             } else if (!PACKET_equal(&cookie, s->d1->cookie,
1249                                      s->d1->cookie_len)) {
1250                 al = SSL_AD_HANDSHAKE_FAILURE;
1251                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1252                 goto f_err;
1253             }
1254             s->d1->cookie_verified = 1;
1255         }
1256         if (s->method->version == DTLS_ANY_VERSION) {
1257             /* Select version to use */
1258             if (s->client_version <= DTLS1_2_VERSION &&
1259                 !(s->options & SSL_OP_NO_DTLSv1_2)) {
1260                 s->version = DTLS1_2_VERSION;
1261                 s->method = DTLSv1_2_server_method();
1262             } else if (tls1_suiteb(s)) {
1263                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1264                        SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
1265                 s->version = s->client_version;
1266                 al = SSL_AD_PROTOCOL_VERSION;
1267                 goto f_err;
1268             } else if (s->client_version <= DTLS1_VERSION &&
1269                        !(s->options & SSL_OP_NO_DTLSv1)) {
1270                 s->version = DTLS1_VERSION;
1271                 s->method = DTLSv1_server_method();
1272             } else {
1273                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1274                        SSL_R_WRONG_VERSION_NUMBER);
1275                 s->version = s->client_version;
1276                 al = SSL_AD_PROTOCOL_VERSION;
1277                 goto f_err;
1278             }
1279             s->session->ssl_version = s->version;
1280         }
1281     }
1282
1283     if (ssl_bytes_to_cipher_list(s, &cipher_suites, &(ciphers),
1284                                  is_v2_record, &al) == NULL) {
1285         goto f_err;
1286     }
1287
1288     /* If it is a hit, check that the cipher is in the list */
1289     if (s->hit) {
1290         j = 0;
1291         id = s->session->cipher->id;
1292
1293 #ifdef CIPHER_DEBUG
1294         fprintf(stderr, "client sent %d ciphers\n",
1295                 sk_SSL_CIPHER_num(ciphers));
1296 #endif
1297         for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1298             c = sk_SSL_CIPHER_value(ciphers, i);
1299 #ifdef CIPHER_DEBUG
1300             fprintf(stderr, "client [%2d of %2d]:%s\n",
1301                     i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
1302 #endif
1303             if (c->id == id) {
1304                 j = 1;
1305                 break;
1306             }
1307         }
1308         if (j == 0) {
1309             /*
1310              * we need to have the cipher in the cipher list if we are asked
1311              * to reuse it
1312              */
1313             al = SSL_AD_ILLEGAL_PARAMETER;
1314             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1315                    SSL_R_REQUIRED_CIPHER_MISSING);
1316             goto f_err;
1317         }
1318     }
1319
1320     complen = PACKET_remaining(&compression);
1321     for (j = 0; j < complen; j++) {
1322         if (PACKET_data(&compression)[j] == 0)
1323             break;
1324     }
1325
1326     if (j >= complen) {
1327         /* no compress */
1328         al = SSL_AD_DECODE_ERROR;
1329         SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED);
1330         goto f_err;
1331     }
1332     
1333     /* TLS extensions */
1334     if (s->version >= SSL3_VERSION) {
1335         if (!ssl_parse_clienthello_tlsext(s, &extensions)) {
1336             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_PARSE_TLSEXT);
1337             goto err;
1338         }
1339     }
1340
1341     /*
1342      * Check if we want to use external pre-shared secret for this handshake
1343      * for not reused session only. We need to generate server_random before
1344      * calling tls_session_secret_cb in order to allow SessionTicket
1345      * processing to use it in key derivation.
1346      */
1347     {
1348         unsigned char *pos;
1349         pos = s->s3->server_random;
1350         if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0) {
1351             goto f_err;
1352         }
1353     }
1354
1355     if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb) {
1356         SSL_CIPHER *pref_cipher = NULL;
1357
1358         s->session->master_key_length = sizeof(s->session->master_key);
1359         if (s->tls_session_secret_cb(s, s->session->master_key,
1360                                      &s->session->master_key_length, ciphers,
1361                                      &pref_cipher,
1362                                      s->tls_session_secret_cb_arg)) {
1363             s->hit = 1;
1364             s->session->ciphers = ciphers;
1365             s->session->verify_result = X509_V_OK;
1366
1367             ciphers = NULL;
1368
1369             /* check if some cipher was preferred by call back */
1370             pref_cipher =
1371                 pref_cipher ? pref_cipher : ssl3_choose_cipher(s,
1372                                                                s->
1373                                                                session->ciphers,
1374                                                                SSL_get_ciphers
1375                                                                (s));
1376             if (pref_cipher == NULL) {
1377                 al = SSL_AD_HANDSHAKE_FAILURE;
1378                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1379                 goto f_err;
1380             }
1381
1382             s->session->cipher = pref_cipher;
1383             sk_SSL_CIPHER_free(s->cipher_list);
1384             s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1385             sk_SSL_CIPHER_free(s->cipher_list_by_id);
1386             s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1387         }
1388     }
1389
1390     /*
1391      * Worst case, we will use the NULL compression, but if we have other
1392      * options, we will now look for them.  We have complen-1 compression
1393      * algorithms from the client, starting at q.
1394      */
1395     s->s3->tmp.new_compression = NULL;
1396 #ifndef OPENSSL_NO_COMP
1397     /* This only happens if we have a cache hit */
1398     if (s->session->compress_meth != 0) {
1399         int m, comp_id = s->session->compress_meth;
1400         unsigned int k;
1401         /* Perform sanity checks on resumed compression algorithm */
1402         /* Can't disable compression */
1403         if (!ssl_allow_compression(s)) {
1404             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1405                    SSL_R_INCONSISTENT_COMPRESSION);
1406             goto f_err;
1407         }
1408         /* Look for resumed compression method */
1409         for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) {
1410             comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1411             if (comp_id == comp->id) {
1412                 s->s3->tmp.new_compression = comp;
1413                 break;
1414             }
1415         }
1416         if (s->s3->tmp.new_compression == NULL) {
1417             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1418                    SSL_R_INVALID_COMPRESSION_ALGORITHM);
1419             goto f_err;
1420         }
1421         /* Look for resumed method in compression list */
1422         for (k = 0; k < complen; k++) {
1423             if (PACKET_data(&compression)[k] == comp_id)
1424                 break;
1425         }
1426         if (k >= complen) {
1427             al = SSL_AD_ILLEGAL_PARAMETER;
1428             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1429                    SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING);
1430             goto f_err;
1431         }
1432     } else if (s->hit)
1433         comp = NULL;
1434     else if (ssl_allow_compression(s) && s->ctx->comp_methods) {
1435         /* See if we have a match */
1436         int m, nn, v, done = 0;
1437         unsigned int o;
1438
1439         nn = sk_SSL_COMP_num(s->ctx->comp_methods);
1440         for (m = 0; m < nn; m++) {
1441             comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1442             v = comp->id;
1443             for (o = 0; o < complen; o++) {
1444                 if (v == PACKET_data(&compression)[o]) {
1445                     done = 1;
1446                     break;
1447                 }
1448             }
1449             if (done)
1450                 break;
1451         }
1452         if (done)
1453             s->s3->tmp.new_compression = comp;
1454         else
1455             comp = NULL;
1456     }
1457 #else
1458     /*
1459      * If compression is disabled we'd better not try to resume a session
1460      * using compression.
1461      */
1462     if (s->session->compress_meth != 0) {
1463         SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
1464         goto f_err;
1465     }
1466 #endif
1467
1468     /*
1469      * Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher
1470      */
1471
1472     if (!s->hit) {
1473 #ifdef OPENSSL_NO_COMP
1474         s->session->compress_meth = 0;
1475 #else
1476         s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
1477 #endif
1478         sk_SSL_CIPHER_free(s->session->ciphers);
1479         s->session->ciphers = ciphers;
1480         if (ciphers == NULL) {
1481             al = SSL_AD_INTERNAL_ERROR;
1482             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1483             goto f_err;
1484         }
1485         ciphers = NULL;
1486         if (!tls1_set_server_sigalgs(s)) {
1487             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1488             goto err;
1489         }
1490     }
1491
1492     sk_SSL_CIPHER_free(ciphers);
1493     return MSG_PROCESS_CONTINUE_PROCESSING;
1494  f_err:
1495     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1496  err:
1497     ossl_statem_set_error(s);
1498
1499     sk_SSL_CIPHER_free(ciphers);
1500     return MSG_PROCESS_ERROR;
1501
1502 }
1503
1504 WORK_STATE tls_post_process_client_hello(SSL *s, WORK_STATE wst)
1505 {
1506     int al = SSL_AD_HANDSHAKE_FAILURE;
1507     SSL_CIPHER *cipher;
1508
1509     if (wst == WORK_MORE_A) {
1510         if (!s->hit) {
1511             /* Let cert callback update server certificates if required */
1512             if (s->cert->cert_cb) {
1513                 int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
1514                 if (rv == 0) {
1515                     al = SSL_AD_INTERNAL_ERROR;
1516                     SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO, SSL_R_CERT_CB_ERROR);
1517                     goto f_err;
1518                 }
1519                 if (rv < 0) {
1520                     s->rwstate = SSL_X509_LOOKUP;
1521                     return WORK_MORE_A;
1522                 }
1523                 s->rwstate = SSL_NOTHING;
1524             }
1525             cipher = ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
1526
1527             if (cipher == NULL) {
1528                 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1529                 goto f_err;
1530             }
1531             s->s3->tmp.new_cipher = cipher;
1532             /* check whether we should disable session resumption */
1533             if (s->not_resumable_session_cb != NULL)
1534                 s->session->not_resumable = s->not_resumable_session_cb(s,
1535                     ((cipher->algorithm_mkey & (SSL_kDHE | SSL_kECDHE)) != 0));
1536             if (s->session->not_resumable)
1537                 /* do not send a session ticket */
1538                 s->tlsext_ticket_expected = 0;
1539         } else {
1540             /* Session-id reuse */
1541             s->s3->tmp.new_cipher = s->session->cipher;
1542         }
1543
1544         if (!(s->verify_mode & SSL_VERIFY_PEER)) {
1545             if (!ssl3_digest_cached_records(s, 0)) {
1546                 al = SSL_AD_INTERNAL_ERROR;
1547                 goto f_err;
1548             }
1549         }
1550
1551         /*-
1552          * we now have the following setup.
1553          * client_random
1554          * cipher_list          - our prefered list of ciphers
1555          * ciphers              - the clients prefered list of ciphers
1556          * compression          - basically ignored right now
1557          * ssl version is set   - sslv3
1558          * s->session           - The ssl session has been setup.
1559          * s->hit               - session reuse flag
1560          * s->s3->tmp.new_cipher- the new cipher to use.
1561          */
1562
1563         /* Handles TLS extensions that we couldn't check earlier */
1564         if (s->version >= SSL3_VERSION) {
1565             if (ssl_check_clienthello_tlsext_late(s) <= 0) {
1566                 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
1567                        SSL_R_CLIENTHELLO_TLSEXT);
1568                 goto f_err;
1569             }
1570         }
1571
1572         wst = WORK_MORE_B;
1573     }
1574 #ifndef OPENSSL_NO_SRP
1575     if (wst == WORK_MORE_B) {
1576         int ret;
1577         if ((ret = ssl_check_srp_ext_ClientHello(s, &al)) < 0) {
1578             /*
1579              * callback indicates further work to be done
1580              */
1581             s->rwstate = SSL_X509_LOOKUP;
1582             return WORK_MORE_B;
1583         }
1584         if (ret != SSL_ERROR_NONE) {
1585             /*
1586              * This is not really an error but the only means to for
1587              * a client to detect whether srp is supported.
1588              */
1589             if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)
1590                 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
1591                            SSL_R_CLIENTHELLO_TLSEXT);
1592             goto f_err;
1593         }
1594     }
1595 #endif
1596     s->renegotiate = 2;
1597
1598     return WORK_FINISHED_STOP;
1599  f_err:
1600     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1601     ossl_statem_set_error(s);
1602     return WORK_ERROR;
1603 }
1604
1605 int tls_construct_server_hello(SSL *s)
1606 {
1607     unsigned char *buf;
1608     unsigned char *p, *d;
1609     int i, sl;
1610     int al = 0;
1611     unsigned long l;
1612
1613     buf = (unsigned char *)s->init_buf->data;
1614
1615     /* Do the message type and length last */
1616     d = p = ssl_handshake_start(s);
1617
1618     *(p++) = s->version >> 8;
1619     *(p++) = s->version & 0xff;
1620
1621     /*
1622      * Random stuff. Filling of the server_random takes place in
1623      * tls_process_client_hello()
1624      */
1625     memcpy(p, s->s3->server_random, SSL3_RANDOM_SIZE);
1626     p += SSL3_RANDOM_SIZE;
1627
1628     /*-
1629      * There are several cases for the session ID to send
1630      * back in the server hello:
1631      * - For session reuse from the session cache,
1632      *   we send back the old session ID.
1633      * - If stateless session reuse (using a session ticket)
1634      *   is successful, we send back the client's "session ID"
1635      *   (which doesn't actually identify the session).
1636      * - If it is a new session, we send back the new
1637      *   session ID.
1638      * - However, if we want the new session to be single-use,
1639      *   we send back a 0-length session ID.
1640      * s->hit is non-zero in either case of session reuse,
1641      * so the following won't overwrite an ID that we're supposed
1642      * to send back.
1643      */
1644     if (s->session->not_resumable ||
1645         (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1646          && !s->hit))
1647         s->session->session_id_length = 0;
1648
1649     sl = s->session->session_id_length;
1650     if (sl > (int)sizeof(s->session->session_id)) {
1651         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1652         ossl_statem_set_error(s);
1653         return 0;
1654     }
1655     *(p++) = sl;
1656     memcpy(p, s->session->session_id, sl);
1657     p += sl;
1658
1659     /* put the cipher */
1660     i = ssl3_put_cipher_by_char(s->s3->tmp.new_cipher, p);
1661     p += i;
1662
1663     /* put the compression method */
1664 #ifdef OPENSSL_NO_COMP
1665     *(p++) = 0;
1666 #else
1667     if (s->s3->tmp.new_compression == NULL)
1668         *(p++) = 0;
1669     else
1670         *(p++) = s->s3->tmp.new_compression->id;
1671 #endif
1672
1673     if (ssl_prepare_serverhello_tlsext(s) <= 0) {
1674         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, SSL_R_SERVERHELLO_TLSEXT);
1675         ossl_statem_set_error(s);
1676         return 0;
1677     }
1678     if ((p =
1679          ssl_add_serverhello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,
1680                                     &al)) == NULL) {
1681         ssl3_send_alert(s, SSL3_AL_FATAL, al);
1682         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1683         ossl_statem_set_error(s);
1684         return 0;
1685     }
1686
1687     /* do the header */
1688     l = (p - d);
1689     if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l)) {
1690         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1691         ossl_statem_set_error(s);
1692         return 0;
1693     }
1694
1695     return 1;
1696 }
1697
1698 int tls_construct_server_done(SSL *s)
1699 {
1700     if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0)) {
1701         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_DONE, ERR_R_INTERNAL_ERROR);
1702         ossl_statem_set_error(s);
1703         return 0;
1704     }
1705
1706     if (!s->s3->tmp.cert_request) {
1707         if (!ssl3_digest_cached_records(s, 0)) {
1708             ossl_statem_set_error(s);
1709         }
1710     }
1711
1712     return 1;
1713 }
1714
1715 int tls_construct_server_key_exchange(SSL *s)
1716 {
1717 #ifndef OPENSSL_NO_DH
1718     DH *dh = NULL, *dhp;
1719 #endif
1720 #ifndef OPENSSL_NO_EC
1721     unsigned char *encodedPoint = NULL;
1722     int encodedlen = 0;
1723     int curve_id = 0;
1724 #endif
1725     EVP_PKEY *pkey;
1726     const EVP_MD *md = NULL;
1727     unsigned char *p, *d;
1728     int al, i;
1729     unsigned long type;
1730     int n;
1731     BIGNUM *r[4];
1732     int nr[4], kn;
1733     BUF_MEM *buf;
1734     EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
1735
1736     if (md_ctx == NULL) {
1737         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1738         al = SSL_AD_INTERNAL_ERROR;
1739         goto f_err;
1740     }
1741
1742     type = s->s3->tmp.new_cipher->algorithm_mkey;
1743
1744     buf = s->init_buf;
1745
1746     r[0] = r[1] = r[2] = r[3] = NULL;
1747     n = 0;
1748 #ifndef OPENSSL_NO_PSK
1749     if (type & SSL_PSK) {
1750         /*
1751          * reserve size for record length and PSK identity hint
1752          */
1753         n += 2;
1754         if (s->cert->psk_identity_hint)
1755             n += strlen(s->cert->psk_identity_hint);
1756     }
1757     /* Plain PSK or RSAPSK nothing to do */
1758     if (type & (SSL_kPSK | SSL_kRSAPSK)) {
1759     } else
1760 #endif                          /* !OPENSSL_NO_PSK */
1761 #ifndef OPENSSL_NO_DH
1762     if (type & (SSL_kDHE | SSL_kDHEPSK)) {
1763         CERT *cert = s->cert;
1764
1765         if (s->cert->dh_tmp_auto) {
1766             dhp = ssl_get_auto_dh(s);
1767             if (dhp == NULL) {
1768                 al = SSL_AD_INTERNAL_ERROR;
1769                 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1770                        ERR_R_INTERNAL_ERROR);
1771                 goto f_err;
1772             }
1773         } else
1774             dhp = cert->dh_tmp;
1775         if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1776             dhp = s->cert->dh_tmp_cb(s, 0, 1024);
1777         if (dhp == NULL) {
1778             al = SSL_AD_HANDSHAKE_FAILURE;
1779             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1780                    SSL_R_MISSING_TMP_DH_KEY);
1781             goto f_err;
1782         }
1783         if (!ssl_security(s, SSL_SECOP_TMP_DH,
1784                           DH_security_bits(dhp), 0, dhp)) {
1785             al = SSL_AD_HANDSHAKE_FAILURE;
1786             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1787                    SSL_R_DH_KEY_TOO_SMALL);
1788             goto f_err;
1789         }
1790         if (s->s3->tmp.dh != NULL) {
1791             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1792                    ERR_R_INTERNAL_ERROR);
1793             goto err;
1794         }
1795
1796         if (s->cert->dh_tmp_auto)
1797             dh = dhp;
1798         else if ((dh = DHparams_dup(dhp)) == NULL) {
1799             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1800             goto err;
1801         }
1802
1803         s->s3->tmp.dh = dh;
1804         if ((dhp->pub_key == NULL ||
1805              dhp->priv_key == NULL ||
1806              (s->options & SSL_OP_SINGLE_DH_USE))) {
1807             if (!DH_generate_key(dh)) {
1808                 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1809                 goto err;
1810             }
1811         } else {
1812             dh->pub_key = BN_dup(dhp->pub_key);
1813             dh->priv_key = BN_dup(dhp->priv_key);
1814             if ((dh->pub_key == NULL) || (dh->priv_key == NULL)) {
1815                 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1816                 goto err;
1817             }
1818         }
1819         r[0] = dh->p;
1820         r[1] = dh->g;
1821         r[2] = dh->pub_key;
1822     } else
1823 #endif
1824 #ifndef OPENSSL_NO_EC
1825     if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
1826         EC_KEY *ecdh = NULL;
1827         int nid;
1828
1829         if (s->s3->tmp.ecdh != NULL) {
1830             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1831                    ERR_R_INTERNAL_ERROR);
1832             goto err;
1833         }
1834
1835         /* Get NID of appropriate shared curve */
1836         nid = tls1_shared_curve(s, -2);
1837         curve_id = tls1_ec_nid2curve_id(nid);
1838         if (curve_id == 0) {
1839             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1840                    SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1841             goto err;
1842         }
1843         ecdh = EC_KEY_new_by_curve_name(nid);
1844         if (ecdh == NULL || !EC_KEY_generate_key(ecdh)) {
1845             al = SSL_AD_INTERNAL_ERROR;
1846             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1847                    ERR_R_EC_LIB);
1848             goto f_err;
1849         }
1850
1851         s->s3->tmp.ecdh = ecdh;
1852
1853         /*
1854          * Encode the public key. First check the size of encoding and
1855          * allocate memory accordingly.
1856          */
1857         encodedlen = EC_KEY_key2buf(ecdh, POINT_CONVERSION_UNCOMPRESSED,
1858                                     &encodedPoint, NULL);
1859
1860         if (encodedlen == 0) {
1861             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EC_LIB);
1862             goto err;
1863         }
1864
1865         /*
1866          * We only support named (not generic) curves in ECDH ephemeral key
1867          * exchanges. In this situation, we need four additional bytes to
1868          * encode the entire ServerECDHParams structure.
1869          */
1870         n += 4 + encodedlen;
1871
1872         /*
1873          * We'll generate the serverKeyExchange message explicitly so we
1874          * can set these to NULLs
1875          */
1876         r[0] = NULL;
1877         r[1] = NULL;
1878         r[2] = NULL;
1879         r[3] = NULL;
1880     } else
1881 #endif                          /* !OPENSSL_NO_EC */
1882 #ifndef OPENSSL_NO_SRP
1883     if (type & SSL_kSRP) {
1884         if ((s->srp_ctx.N == NULL) ||
1885             (s->srp_ctx.g == NULL) ||
1886             (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
1887             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1888                    SSL_R_MISSING_SRP_PARAM);
1889             goto err;
1890         }
1891         r[0] = s->srp_ctx.N;
1892         r[1] = s->srp_ctx.g;
1893         r[2] = s->srp_ctx.s;
1894         r[3] = s->srp_ctx.B;
1895     } else
1896 #endif
1897     {
1898         al = SSL_AD_HANDSHAKE_FAILURE;
1899         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1900                SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1901         goto f_err;
1902     }
1903     for (i = 0; i < 4 && r[i] != NULL; i++) {
1904         nr[i] = BN_num_bytes(r[i]);
1905 #ifndef OPENSSL_NO_SRP
1906         if ((i == 2) && (type & SSL_kSRP))
1907             n += 1 + nr[i];
1908         else
1909 #endif
1910             n += 2 + nr[i];
1911     }
1912
1913     if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aSRP))
1914         && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_PSK)) {
1915         if ((pkey = ssl_get_sign_pkey(s, s->s3->tmp.new_cipher, &md))
1916             == NULL) {
1917             al = SSL_AD_DECODE_ERROR;
1918             goto f_err;
1919         }
1920         kn = EVP_PKEY_size(pkey);
1921     } else {
1922         pkey = NULL;
1923         kn = 0;
1924     }
1925
1926     if (!BUF_MEM_grow_clean(buf, n + SSL_HM_HEADER_LENGTH(s) + kn)) {
1927         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_LIB_BUF);
1928         goto err;
1929     }
1930     d = p = ssl_handshake_start(s);
1931
1932 #ifndef OPENSSL_NO_PSK
1933     if (type & SSL_PSK) {
1934         /* copy PSK identity hint */
1935         if (s->cert->psk_identity_hint) {
1936             s2n(strlen(s->cert->psk_identity_hint), p);
1937             strncpy((char *)p, s->cert->psk_identity_hint,
1938                     strlen(s->cert->psk_identity_hint));
1939             p += strlen(s->cert->psk_identity_hint);
1940         } else {
1941             s2n(0, p);
1942         }
1943     }
1944 #endif
1945
1946     for (i = 0; i < 4 && r[i] != NULL; i++) {
1947 #ifndef OPENSSL_NO_SRP
1948         if ((i == 2) && (type & SSL_kSRP)) {
1949             *p = nr[i];
1950             p++;
1951         } else
1952 #endif
1953             s2n(nr[i], p);
1954         BN_bn2bin(r[i], p);
1955         p += nr[i];
1956     }
1957
1958 #ifndef OPENSSL_NO_EC
1959     if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
1960         /*
1961          * XXX: For now, we only support named (not generic) curves. In
1962          * this situation, the serverKeyExchange message has: [1 byte
1963          * CurveType], [2 byte CurveName] [1 byte length of encoded
1964          * point], followed by the actual encoded point itself
1965          */
1966         *p = NAMED_CURVE_TYPE;
1967         p += 1;
1968         *p = 0;
1969         p += 1;
1970         *p = curve_id;
1971         p += 1;
1972         *p = encodedlen;
1973         p += 1;
1974         memcpy(p, encodedPoint, encodedlen);
1975         OPENSSL_free(encodedPoint);
1976         encodedPoint = NULL;
1977         p += encodedlen;
1978     }
1979 #endif
1980
1981     /* not anonymous */
1982     if (pkey != NULL) {
1983         /*
1984          * n is the length of the params, they start at &(d[4]) and p
1985          * points to the space at the end.
1986          */
1987         if (md) {
1988             /* send signature algorithm */
1989             if (SSL_USE_SIGALGS(s)) {
1990                 if (!tls12_get_sigandhash(p, pkey, md)) {
1991                     /* Should never happen */
1992                     al = SSL_AD_INTERNAL_ERROR;
1993                     SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1994                            ERR_R_INTERNAL_ERROR);
1995                     goto f_err;
1996                 }
1997                 p += 2;
1998             }
1999 #ifdef SSL_DEBUG
2000             fprintf(stderr, "Using hash %s\n", EVP_MD_name(md));
2001 #endif
2002             if (EVP_SignInit_ex(md_ctx, md, NULL) <= 0
2003                     || EVP_SignUpdate(md_ctx, &(s->s3->client_random[0]),
2004                                       SSL3_RANDOM_SIZE) <= 0
2005                     || EVP_SignUpdate(md_ctx, &(s->s3->server_random[0]),
2006                                       SSL3_RANDOM_SIZE) <= 0
2007                     || EVP_SignUpdate(md_ctx, d, n) <= 0
2008                     || EVP_SignFinal(md_ctx, &(p[2]),
2009                                (unsigned int *)&i, pkey) <= 0) {
2010                 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_LIB_EVP);
2011                 al = SSL_AD_INTERNAL_ERROR;
2012                 goto f_err;
2013             }
2014             s2n(i, p);
2015             n += i + 2;
2016             if (SSL_USE_SIGALGS(s))
2017                 n += 2;
2018         } else {
2019             /* Is this error check actually needed? */
2020             al = SSL_AD_HANDSHAKE_FAILURE;
2021             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2022                    SSL_R_UNKNOWN_PKEY_TYPE);
2023             goto f_err;
2024         }
2025     }
2026
2027     if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n)) {
2028         al = SSL_AD_HANDSHAKE_FAILURE;
2029         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2030         goto f_err;
2031     }
2032
2033     EVP_MD_CTX_free(md_ctx);
2034     return 1;
2035  f_err:
2036     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2037  err:
2038 #ifndef OPENSSL_NO_EC
2039     OPENSSL_free(encodedPoint);
2040 #endif
2041     EVP_MD_CTX_free(md_ctx);
2042     ossl_statem_set_error(s);
2043     return 0;
2044 }
2045
2046 int tls_construct_certificate_request(SSL *s)
2047 {
2048     unsigned char *p, *d;
2049     int i, j, nl, off, n;
2050     STACK_OF(X509_NAME) *sk = NULL;
2051     X509_NAME *name;
2052     BUF_MEM *buf;
2053
2054     buf = s->init_buf;
2055
2056     d = p = ssl_handshake_start(s);
2057
2058     /* get the list of acceptable cert types */
2059     p++;
2060     n = ssl3_get_req_cert_type(s, p);
2061     d[0] = n;
2062     p += n;
2063     n++;
2064
2065     if (SSL_USE_SIGALGS(s)) {
2066         const unsigned char *psigs;
2067         unsigned char *etmp = p;
2068         nl = tls12_get_psigalgs(s, &psigs);
2069         /* Skip over length for now */
2070         p += 2;
2071         nl = tls12_copy_sigalgs(s, p, psigs, nl);
2072         /* Now fill in length */
2073         s2n(nl, etmp);
2074         p += nl;
2075         n += nl + 2;
2076     }
2077
2078     off = n;
2079     p += 2;
2080     n += 2;
2081
2082     sk = SSL_get_client_CA_list(s);
2083     nl = 0;
2084     if (sk != NULL) {
2085         for (i = 0; i < sk_X509_NAME_num(sk); i++) {
2086             name = sk_X509_NAME_value(sk, i);
2087             j = i2d_X509_NAME(name, NULL);
2088             if (!BUF_MEM_grow_clean
2089                 (buf, SSL_HM_HEADER_LENGTH(s) + n + j + 2)) {
2090                 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2091                        ERR_R_BUF_LIB);
2092                 goto err;
2093             }
2094             p = ssl_handshake_start(s) + n;
2095             s2n(j, p);
2096             i2d_X509_NAME(name, &p);
2097             n += 2 + j;
2098             nl += 2 + j;
2099         }
2100     }
2101     /* else no CA names */
2102     p = ssl_handshake_start(s) + off;
2103     s2n(nl, p);
2104
2105     if (!ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n)) {
2106         SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR);
2107         goto err;
2108     }
2109
2110     s->s3->tmp.cert_request = 1;
2111
2112     return 1;
2113  err:
2114     ossl_statem_set_error(s);
2115     return 0;
2116 }
2117
2118 MSG_PROCESS_RETURN tls_process_client_key_exchange(SSL *s, PACKET *pkt)
2119 {
2120     int al;
2121     unsigned int i;
2122     unsigned long alg_k;
2123 #ifndef OPENSSL_NO_RSA
2124     RSA *rsa = NULL;
2125     EVP_PKEY *pkey = NULL;
2126 #endif
2127 #ifndef OPENSSL_NO_DH
2128     BIGNUM *pub = NULL;
2129     DH *dh_srvr, *dh_clnt = NULL;
2130 #endif
2131 #ifndef OPENSSL_NO_EC
2132     EC_KEY *srvr_ecdh = NULL;
2133     EC_POINT *clnt_ecpoint = NULL;
2134 #endif
2135     PACKET enc_premaster;
2136     unsigned char *data, *rsa_decrypt = NULL;
2137
2138     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2139
2140 #ifndef OPENSSL_NO_PSK
2141     /* For PSK parse and retrieve identity, obtain PSK key */
2142     if (alg_k & SSL_PSK) {
2143         unsigned char psk[PSK_MAX_PSK_LEN];
2144         size_t psklen;
2145         PACKET psk_identity;
2146
2147         if (!PACKET_get_length_prefixed_2(pkt, &psk_identity)) {
2148             al = SSL_AD_DECODE_ERROR;
2149             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
2150             goto f_err;
2151         }
2152         if (PACKET_remaining(&psk_identity) > PSK_MAX_IDENTITY_LEN) {
2153             al = SSL_AD_DECODE_ERROR;
2154             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2155                    SSL_R_DATA_LENGTH_TOO_LONG);
2156             goto f_err;
2157         }
2158         if (s->psk_server_callback == NULL) {
2159             al = SSL_AD_INTERNAL_ERROR;
2160             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2161                    SSL_R_PSK_NO_SERVER_CB);
2162             goto f_err;
2163         }
2164
2165         if (!PACKET_strndup(&psk_identity, &s->session->psk_identity)) {
2166             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2167             al = SSL_AD_INTERNAL_ERROR;
2168             goto f_err;
2169         }
2170
2171         psklen = s->psk_server_callback(s, s->session->psk_identity,
2172                                          psk, sizeof(psk));
2173
2174         if (psklen > PSK_MAX_PSK_LEN) {
2175             al = SSL_AD_INTERNAL_ERROR;
2176             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2177             goto f_err;
2178         } else if (psklen == 0) {
2179             /*
2180              * PSK related to the given identity not found
2181              */
2182             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2183                    SSL_R_PSK_IDENTITY_NOT_FOUND);
2184             al = SSL_AD_UNKNOWN_PSK_IDENTITY;
2185             goto f_err;
2186         }
2187
2188         OPENSSL_free(s->s3->tmp.psk);
2189         s->s3->tmp.psk = BUF_memdup(psk, psklen);
2190         OPENSSL_cleanse(psk, psklen);
2191
2192         if (s->s3->tmp.psk == NULL) {
2193             al = SSL_AD_INTERNAL_ERROR;
2194             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2195             goto f_err;
2196         }
2197
2198         s->s3->tmp.psklen = psklen;
2199     }
2200     if (alg_k & SSL_kPSK) {
2201         /* Identity extracted earlier: should be nothing left */
2202         if (PACKET_remaining(pkt) != 0) {
2203             al = SSL_AD_HANDSHAKE_FAILURE;
2204             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
2205             goto f_err;
2206         }
2207         /* PSK handled by ssl_generate_master_secret */
2208         if (!ssl_generate_master_secret(s, NULL, 0, 0)) {
2209             al = SSL_AD_INTERNAL_ERROR;
2210             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2211             goto f_err;
2212         }
2213     } else
2214 #endif
2215 #ifndef OPENSSL_NO_RSA
2216     if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
2217         unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2218         int decrypt_len;
2219         unsigned char decrypt_good, version_good;
2220         size_t j;
2221
2222         /* FIX THIS UP EAY EAY EAY EAY */
2223         pkey = s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
2224         if ((pkey == NULL) ||
2225             (pkey->type != EVP_PKEY_RSA) || (pkey->pkey.rsa == NULL)) {
2226             al = SSL_AD_HANDSHAKE_FAILURE;
2227             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2228                    SSL_R_MISSING_RSA_CERTIFICATE);
2229             goto f_err;
2230         }
2231         rsa = pkey->pkey.rsa;
2232
2233         /* SSLv3 and pre-standard DTLS omit the length bytes. */
2234         if (s->version == SSL3_VERSION || s->version == DTLS1_BAD_VER) {
2235             enc_premaster = *pkt;
2236         } else {
2237             PACKET orig = *pkt;
2238             if (!PACKET_get_length_prefixed_2(pkt, &enc_premaster)
2239                 || PACKET_remaining(pkt) != 0) {
2240                 /* Try SSLv3 behaviour for TLS. */
2241                 if (s->options & SSL_OP_TLS_D5_BUG) {
2242                     enc_premaster = orig;
2243                 } else {
2244                     al = SSL_AD_DECODE_ERROR;
2245                     SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2246                            SSL_R_LENGTH_MISMATCH);
2247                     goto f_err;
2248                 }
2249             }
2250         }
2251
2252         /*
2253          * We want to be sure that the plaintext buffer size makes it safe to
2254          * iterate over the entire size of a premaster secret
2255          * (SSL_MAX_MASTER_KEY_LENGTH). Reject overly short RSA keys because
2256          * their ciphertext cannot accommodate a premaster secret anyway.
2257          */
2258         if (RSA_size(rsa) < SSL_MAX_MASTER_KEY_LENGTH) {
2259             al = SSL_AD_INTERNAL_ERROR;
2260             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2261                    RSA_R_KEY_SIZE_TOO_SMALL);
2262             goto f_err;
2263         }
2264
2265         rsa_decrypt = OPENSSL_malloc(RSA_size(rsa));
2266         if (rsa_decrypt == NULL) {
2267             al = SSL_AD_INTERNAL_ERROR;
2268             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2269             goto f_err;
2270         }
2271
2272         /*
2273          * We must not leak whether a decryption failure occurs because of
2274          * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
2275          * section 7.4.7.1). The code follows that advice of the TLS RFC and
2276          * generates a random premaster secret for the case that the decrypt
2277          * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
2278          */
2279
2280         if (RAND_bytes(rand_premaster_secret,
2281                        sizeof(rand_premaster_secret)) <= 0) {
2282             goto err;
2283         }
2284
2285         decrypt_len = RSA_private_decrypt(PACKET_remaining(&enc_premaster),
2286                                           PACKET_data(&enc_premaster),
2287                                           rsa_decrypt, rsa, RSA_PKCS1_PADDING);
2288         ERR_clear_error();
2289
2290         /*
2291          * decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH. decrypt_good will
2292          * be 0xff if so and zero otherwise.
2293          */
2294         decrypt_good =
2295             constant_time_eq_int_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH);
2296
2297         /*
2298          * If the version in the decrypted pre-master secret is correct then
2299          * version_good will be 0xff, otherwise it'll be zero. The
2300          * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
2301          * (http://eprint.iacr.org/2003/052/) exploits the version number
2302          * check as a "bad version oracle". Thus version checks are done in
2303          * constant time and are treated like any other decryption error.
2304          */
2305         version_good =
2306             constant_time_eq_8(rsa_decrypt[0],
2307                                (unsigned)(s->client_version >> 8));
2308         version_good &=
2309             constant_time_eq_8(rsa_decrypt[1],
2310                                (unsigned)(s->client_version & 0xff));
2311
2312         /*
2313          * The premaster secret must contain the same version number as the
2314          * ClientHello to detect version rollback attacks (strangely, the
2315          * protocol does not offer such protection for DH ciphersuites).
2316          * However, buggy clients exist that send the negotiated protocol
2317          * version instead if the server does not support the requested
2318          * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
2319          * clients.
2320          */
2321         if (s->options & SSL_OP_TLS_ROLLBACK_BUG) {
2322             unsigned char workaround_good;
2323             workaround_good =
2324                 constant_time_eq_8(rsa_decrypt[0], (unsigned)(s->version >> 8));
2325             workaround_good &=
2326                 constant_time_eq_8(rsa_decrypt[1],
2327                                    (unsigned)(s->version & 0xff));
2328             version_good |= workaround_good;
2329         }
2330
2331         /*
2332          * Both decryption and version must be good for decrypt_good to
2333          * remain non-zero (0xff).
2334          */
2335         decrypt_good &= version_good;
2336
2337         /*
2338          * Now copy rand_premaster_secret over from p using
2339          * decrypt_good_mask. If decryption failed, then p does not
2340          * contain valid plaintext, however, a check above guarantees
2341          * it is still sufficiently large to read from.
2342          */
2343         for (j = 0; j < sizeof(rand_premaster_secret); j++) {
2344             rsa_decrypt[j] =
2345                 constant_time_select_8(decrypt_good, rsa_decrypt[j],
2346                                        rand_premaster_secret[j]);
2347         }
2348
2349         if (!ssl_generate_master_secret(s, rsa_decrypt,
2350                                         sizeof(rand_premaster_secret), 0)) {
2351             al = SSL_AD_INTERNAL_ERROR;
2352             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2353             goto f_err;
2354         }
2355         OPENSSL_free(rsa_decrypt);
2356         rsa_decrypt = NULL;
2357     } else
2358 #endif
2359 #ifndef OPENSSL_NO_DH
2360     if (alg_k & (SSL_kDHE | SSL_kDHr | SSL_kDHd | SSL_kDHEPSK)) {
2361         int idx = -1;
2362         EVP_PKEY *skey = NULL;
2363         unsigned char shared[(OPENSSL_DH_MAX_MODULUS_BITS + 7) / 8];
2364
2365         if (!PACKET_get_net_2(pkt, &i)) {
2366             if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
2367                 al = SSL_AD_HANDSHAKE_FAILURE;
2368                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2369                        SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2370                 goto f_err;
2371             }
2372             i = 0;
2373         }
2374         if (PACKET_remaining(pkt) != i) {
2375             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2376                    SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2377             goto err;
2378         }
2379         if (alg_k & SSL_kDHr)
2380             idx = SSL_PKEY_DH_RSA;
2381         else if (alg_k & SSL_kDHd)
2382             idx = SSL_PKEY_DH_DSA;
2383         if (idx >= 0) {
2384             skey = s->cert->pkeys[idx].privatekey;
2385             if ((skey == NULL) ||
2386                 (skey->type != EVP_PKEY_DH) || (skey->pkey.dh == NULL)) {
2387                 al = SSL_AD_HANDSHAKE_FAILURE;
2388                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2389                        SSL_R_MISSING_RSA_CERTIFICATE);
2390                 goto f_err;
2391             }
2392             dh_srvr = skey->pkey.dh;
2393         } else if (s->s3->tmp.dh == NULL) {
2394             al = SSL_AD_HANDSHAKE_FAILURE;
2395             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2396                    SSL_R_MISSING_TMP_DH_KEY);
2397             goto f_err;
2398         } else
2399             dh_srvr = s->s3->tmp.dh;
2400
2401         if (PACKET_remaining(pkt) == 0L) {
2402             /* Get pubkey from cert */
2403             EVP_PKEY *clkey = X509_get_pubkey(s->session->peer);
2404             if (clkey) {
2405                 if (EVP_PKEY_cmp_parameters(clkey, skey) == 1)
2406                     dh_clnt = EVP_PKEY_get1_DH(clkey);
2407             }
2408             if (dh_clnt == NULL) {
2409                 al = SSL_AD_HANDSHAKE_FAILURE;
2410                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2411                        SSL_R_MISSING_TMP_DH_KEY);
2412                 goto f_err;
2413             }
2414             EVP_PKEY_free(clkey);
2415             pub = dh_clnt->pub_key;
2416         } else {
2417             if (!PACKET_get_bytes(pkt, &data, i)) {
2418                 /* We already checked we have enough data */
2419                 al = SSL_AD_INTERNAL_ERROR;
2420                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2421                        ERR_R_INTERNAL_ERROR);
2422                 goto f_err;
2423             }
2424             pub = BN_bin2bn(data, i, NULL);
2425         }
2426         if (pub == NULL) {
2427             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_BN_LIB);
2428             goto err;
2429         }
2430
2431         i = DH_compute_key(shared, pub, dh_srvr);
2432
2433         if (i <= 0) {
2434             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
2435             BN_clear_free(pub);
2436             goto err;
2437         }
2438
2439         DH_free(s->s3->tmp.dh);
2440         s->s3->tmp.dh = NULL;
2441         if (dh_clnt)
2442             DH_free(dh_clnt);
2443         else
2444             BN_clear_free(pub);
2445         pub = NULL;
2446         if (!ssl_generate_master_secret(s, shared, i, 0)) {
2447             al = SSL_AD_INTERNAL_ERROR;
2448             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2449             goto f_err;
2450         }
2451         if (dh_clnt) {
2452             s->statem.no_cert_verify = 1;
2453             return MSG_PROCESS_CONTINUE_PROCESSING;
2454         }
2455     } else
2456 #endif
2457
2458 #ifndef OPENSSL_NO_EC
2459     if (alg_k & (SSL_kECDHE | SSL_kECDHr | SSL_kECDHe | SSL_kECDHEPSK)) {
2460         int field_size = 0;
2461         const EC_KEY *tkey;
2462         const EC_GROUP *group;
2463         const BIGNUM *priv_key;
2464         unsigned char *shared;
2465
2466         /* initialize structures for server's ECDH key pair */
2467         if ((srvr_ecdh = EC_KEY_new()) == NULL) {
2468             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2469             goto err;
2470         }
2471
2472         /* Let's get server private key and group information */
2473         if (alg_k & (SSL_kECDHr | SSL_kECDHe)) {
2474             /* use the certificate */
2475             tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec;
2476         } else {
2477             /*
2478              * use the ephermeral values we saved when generating the
2479              * ServerKeyExchange msg.
2480              */
2481             tkey = s->s3->tmp.ecdh;
2482         }
2483
2484         group = EC_KEY_get0_group(tkey);
2485         priv_key = EC_KEY_get0_private_key(tkey);
2486
2487         if (!EC_KEY_set_group(srvr_ecdh, group) ||
2488             !EC_KEY_set_private_key(srvr_ecdh, priv_key)) {
2489             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2490             goto err;
2491         }
2492
2493         /* Let's get client's public key */
2494         if ((clnt_ecpoint = EC_POINT_new(group)) == NULL) {
2495             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2496             goto err;
2497         }
2498
2499         if (PACKET_remaining(pkt) == 0L) {
2500             /* Client Publickey was in Client Certificate */
2501
2502             if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
2503                 al = SSL_AD_HANDSHAKE_FAILURE;
2504                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2505                        SSL_R_MISSING_TMP_ECDH_KEY);
2506                 goto f_err;
2507             }
2508             if (((clnt_pub_pkey = X509_get_pubkey(s->session->peer))
2509                  == NULL) || (clnt_pub_pkey->type != EVP_PKEY_EC)) {
2510                 /*
2511                  * XXX: For now, we do not support client authentication
2512                  * using ECDH certificates so this branch (n == 0L) of the
2513                  * code is never executed. When that support is added, we
2514                  * ought to ensure the key received in the certificate is
2515                  * authorized for key agreement. ECDH_compute_key implicitly
2516                  * checks that the two ECDH shares are for the same group.
2517                  */
2518                 al = SSL_AD_HANDSHAKE_FAILURE;
2519                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2520                        SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
2521                 goto f_err;
2522             }
2523
2524             if (EC_POINT_copy(clnt_ecpoint,
2525                               EC_KEY_get0_public_key(clnt_pub_pkey->
2526                                                      pkey.ec)) == 0) {
2527                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2528                 goto err;
2529             }
2530             s->statem.no_cert_verify = 1;
2531         } else {
2532             /*
2533              * Get client's public key from encoded point in the
2534              * ClientKeyExchange message.
2535              */
2536
2537             /* Get encoded point length */
2538             if (!PACKET_get_1(pkt, &i)) {
2539                 al = SSL_AD_DECODE_ERROR;
2540                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2541                        SSL_R_LENGTH_MISMATCH);
2542                 goto f_err;
2543             }
2544             if (!PACKET_get_bytes(pkt, &data, i)
2545                     || PACKET_remaining(pkt) != 0) {
2546                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2547                 goto err;
2548             }
2549             if (EC_POINT_oct2point(group, clnt_ecpoint, data, i, NULL) == 0) {
2550                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2551                 goto err;
2552             }
2553         }
2554
2555         /* Compute the shared pre-master secret */
2556         field_size = EC_GROUP_get_degree(group);
2557         if (field_size <= 0) {
2558             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2559             goto err;
2560         }
2561         shared = OPENSSL_malloc((field_size + 7) / 8);
2562         if (shared == NULL) {
2563             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2564             goto err;
2565         }
2566         i = ECDH_compute_key(shared, (field_size + 7) / 8, clnt_ecpoint,
2567                              srvr_ecdh, NULL);
2568         if (i <= 0) {
2569             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2570             OPENSSL_free(shared);
2571             goto err;
2572         }
2573
2574         EC_POINT_free(clnt_ecpoint);
2575         EC_KEY_free(srvr_ecdh);
2576         EC_KEY_free(s->s3->tmp.ecdh);
2577         s->s3->tmp.ecdh = NULL;
2578
2579         if (!ssl_generate_master_secret(s, shared, i, 1)) {
2580             al = SSL_AD_INTERNAL_ERROR;
2581             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2582             goto f_err;
2583         }
2584         return MSG_PROCESS_CONTINUE_PROCESSING;
2585     } else
2586 #endif
2587 #ifndef OPENSSL_NO_SRP
2588     if (alg_k & SSL_kSRP) {
2589         if (!PACKET_get_net_2(pkt, &i)
2590                 || !PACKET_get_bytes(pkt, &data, i)) {
2591             al = SSL_AD_DECODE_ERROR;
2592             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_BAD_SRP_A_LENGTH);
2593             goto f_err;
2594         }
2595         if ((s->srp_ctx.A = BN_bin2bn(data, i, NULL)) == NULL) {
2596             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_BN_LIB);
2597             goto err;
2598         }
2599         if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0
2600             || BN_is_zero(s->srp_ctx.A)) {
2601             al = SSL_AD_ILLEGAL_PARAMETER;
2602             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2603                    SSL_R_BAD_SRP_PARAMETERS);
2604             goto f_err;
2605         }
2606         OPENSSL_free(s->session->srp_username);
2607         s->session->srp_username = BUF_strdup(s->srp_ctx.login);
2608         if (s->session->srp_username == NULL) {
2609             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2610             goto err;
2611         }
2612
2613         if (!srp_generate_server_master_secret(s)) {
2614             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2615             goto err;
2616         }
2617     } else
2618 #endif                          /* OPENSSL_NO_SRP */
2619 #ifndef OPENSSL_NO_GOST
2620     if (alg_k & SSL_kGOST) {
2621         EVP_PKEY_CTX *pkey_ctx;
2622         EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2623         unsigned char premaster_secret[32], *start;
2624         size_t outlen = 32, inlen;
2625         unsigned long alg_a;
2626         int Ttag, Tclass;
2627         long Tlen;
2628         long sess_key_len;
2629
2630         /* Get our certificate private key */
2631         alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2632         if (alg_a & SSL_aGOST12) {
2633             /*
2634              * New GOST ciphersuites have SSL_aGOST01 bit too
2635              */
2636             pk = s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey;
2637             if (pk == NULL) {
2638                 pk = s->cert->pkeys[SSL_PKEY_GOST12_256].privatekey;
2639             }
2640             if (pk == NULL) {
2641                 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2642             }
2643         } else if (alg_a & SSL_aGOST01) {
2644             pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2645         }
2646
2647         pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
2648         if (pkey_ctx == NULL) {
2649             al = SSL_AD_INTERNAL_ERROR;
2650             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2651             goto f_err;
2652         }
2653         if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {
2654             al = SSL_AD_INTERNAL_ERROR;
2655             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2656             goto f_err;
2657         }
2658         /*
2659          * If client certificate is present and is of the same type, maybe
2660          * use it for key exchange.  Don't mind errors from
2661          * EVP_PKEY_derive_set_peer, because it is completely valid to use a
2662          * client certificate for authorization only.
2663          */
2664         client_pub_pkey = X509_get_pubkey(s->session->peer);
2665         if (client_pub_pkey) {
2666             if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
2667                 ERR_clear_error();
2668         }
2669         /* Decrypt session key */
2670         sess_key_len = PACKET_remaining(pkt);
2671         if (!PACKET_get_bytes(pkt, &data, sess_key_len)) {
2672             al = SSL_AD_INTERNAL_ERROR;
2673             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2674             goto gerr;
2675         }
2676         if (ASN1_get_object ((const unsigned char **)&data, &Tlen, &Ttag,
2677                              &Tclass, sess_key_len) != V_ASN1_CONSTRUCTED
2678             || Ttag != V_ASN1_SEQUENCE
2679             || Tclass != V_ASN1_UNIVERSAL) {
2680             al = SSL_AD_DECODE_ERROR;
2681             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2682                    SSL_R_DECRYPTION_FAILED);
2683             goto gerr;
2684         }
2685         start = data;
2686         inlen = Tlen;
2687         if (EVP_PKEY_decrypt
2688             (pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {
2689             al = SSL_AD_DECODE_ERROR;
2690             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2691                    SSL_R_DECRYPTION_FAILED);
2692             goto gerr;
2693         }
2694         /* Generate master secret */
2695         if (!ssl_generate_master_secret(s, premaster_secret,
2696                                         sizeof(premaster_secret), 0)) {
2697             al = SSL_AD_INTERNAL_ERROR;
2698             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2699             goto gerr;
2700         }
2701         /* Check if pubkey from client certificate was used */
2702         if (EVP_PKEY_CTX_ctrl
2703             (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
2704             s->statem.no_cert_verify = 1;
2705
2706         EVP_PKEY_free(client_pub_pkey);
2707         EVP_PKEY_CTX_free(pkey_ctx);
2708         return MSG_PROCESS_CONTINUE_PROCESSING;
2709  gerr:
2710         EVP_PKEY_free(client_pub_pkey);
2711         EVP_PKEY_CTX_free(pkey_ctx);
2712         goto f_err;
2713     } else
2714 #endif
2715     {
2716         al = SSL_AD_HANDSHAKE_FAILURE;
2717         SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_UNKNOWN_CIPHER_TYPE);
2718         goto f_err;
2719     }
2720
2721     return MSG_PROCESS_CONTINUE_PROCESSING;
2722  f_err:
2723     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2724 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_EC) || defined(OPENSSL_NO_SRP)
2725  err:
2726 #endif
2727 #ifndef OPENSSL_NO_EC
2728     EC_POINT_free(clnt_ecpoint);
2729     EC_KEY_free(srvr_ecdh);
2730     OPENSSL_free(rsa_decrypt);
2731 #endif
2732 #ifndef OPENSSL_NO_PSK
2733     OPENSSL_clear_free(s->s3->tmp.psk, s->s3->tmp.psklen);
2734     s->s3->tmp.psk = NULL;
2735 #endif
2736     ossl_statem_set_error(s);
2737     return MSG_PROCESS_ERROR;
2738 }
2739
2740 WORK_STATE tls_post_process_client_key_exchange(SSL *s, WORK_STATE wst)
2741 {
2742 #ifndef OPENSSL_NO_SCTP
2743     if (wst == WORK_MORE_A) {
2744         if (SSL_IS_DTLS(s)) {
2745             unsigned char sctpauthkey[64];
2746             char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
2747             /*
2748              * Add new shared key for SCTP-Auth, will be ignored if no SCTP
2749              * used.
2750              */
2751             memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
2752                    sizeof(DTLS1_SCTP_AUTH_LABEL));
2753
2754             if (SSL_export_keying_material(s, sctpauthkey,
2755                                        sizeof(sctpauthkey), labelbuffer,
2756                                        sizeof(labelbuffer), NULL, 0, 0) <= 0) {
2757                 ossl_statem_set_error(s);
2758                 return WORK_ERROR;;
2759             }
2760
2761             BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
2762                      sizeof(sctpauthkey), sctpauthkey);
2763         }
2764         wst = WORK_MORE_B;
2765     }
2766
2767     if ((wst == WORK_MORE_B)
2768             /* Is this SCTP? */
2769             && BIO_dgram_is_sctp(SSL_get_wbio(s))
2770             /* Are we renegotiating? */
2771             && s->renegotiate
2772             /* Are we going to skip the CertificateVerify? */
2773             && (s->session->peer == NULL || s->statem.no_cert_verify)
2774             && BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
2775         s->s3->in_read_app_data = 2;
2776         s->rwstate = SSL_READING;
2777         BIO_clear_retry_flags(SSL_get_rbio(s));
2778         BIO_set_retry_read(SSL_get_rbio(s));
2779         ossl_statem_set_sctp_read_sock(s, 1);
2780         return WORK_MORE_B;
2781     } else {
2782         ossl_statem_set_sctp_read_sock(s, 0);
2783     }
2784 #endif
2785
2786     if (s->statem.no_cert_verify) {
2787         /* No certificate verify so we no longer need the handshake_buffer */
2788         BIO_free(s->s3->handshake_buffer);
2789         s->s3->handshake_buffer = NULL;
2790         return WORK_FINISHED_CONTINUE;
2791     } else {
2792         if (!s->session->peer) {
2793             /* No peer certificate so we no longer need the handshake_buffer */
2794             BIO_free(s->s3->handshake_buffer);
2795             return WORK_FINISHED_CONTINUE;
2796         }
2797         if (!s->s3->handshake_buffer) {
2798             SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_KEY_EXCHANGE,
2799                    ERR_R_INTERNAL_ERROR);
2800             ossl_statem_set_error(s);
2801             return WORK_ERROR;
2802         }
2803         /*
2804          * For sigalgs freeze the handshake buffer. If we support
2805          * extms we've done this already so this is a no-op
2806          */
2807         if (!ssl3_digest_cached_records(s, 1)) {
2808             ossl_statem_set_error(s);
2809             return WORK_ERROR;
2810         }
2811     }
2812
2813     return WORK_FINISHED_CONTINUE;
2814 }
2815
2816 MSG_PROCESS_RETURN tls_process_cert_verify(SSL *s, PACKET *pkt)
2817 {
2818     EVP_PKEY *pkey = NULL;
2819     unsigned char *sig, *data;
2820     int al, ret = MSG_PROCESS_ERROR;
2821     int type = 0, j;
2822     unsigned int len;
2823     X509 *peer;
2824     const EVP_MD *md = NULL;
2825     long hdatalen = 0;
2826     void *hdata;
2827
2828     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
2829
2830     if (mctx == NULL) {
2831         SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
2832         al = SSL_AD_INTERNAL_ERROR;
2833         goto f_err;
2834     }
2835
2836     peer = s->session->peer;
2837     pkey = X509_get_pubkey(peer);
2838     type = X509_certificate_type(peer, pkey);
2839
2840     if (!(type & EVP_PKT_SIGN)) {
2841         SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY,
2842                SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
2843         al = SSL_AD_ILLEGAL_PARAMETER;
2844         goto f_err;
2845     }
2846
2847     /* Check for broken implementations of GOST ciphersuites */
2848     /*
2849      * If key is GOST and n is exactly 64, it is bare signature without
2850      * length field (CryptoPro implementations at least till CSP 4.0)
2851      */
2852 #ifndef OPENSSL_NO_GOST
2853     if (PACKET_remaining(pkt) == 64 && pkey->type == NID_id_GostR3410_2001) {
2854         len = 64;
2855     } else
2856 #endif
2857     {
2858         if (SSL_USE_SIGALGS(s)) {
2859             int rv;
2860
2861             if (!PACKET_get_bytes(pkt, &sig, 2)) {
2862                 al = SSL_AD_DECODE_ERROR;
2863                 goto f_err;
2864             }
2865             rv = tls12_check_peer_sigalg(&md, s, sig, pkey);
2866             if (rv == -1) {
2867                 al = SSL_AD_INTERNAL_ERROR;
2868                 goto f_err;
2869             } else if (rv == 0) {
2870                 al = SSL_AD_DECODE_ERROR;
2871                 goto f_err;
2872             }
2873 #ifdef SSL_DEBUG
2874             fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
2875 #endif
2876         } else {
2877             /* Use default digest for this key type */
2878             int idx = ssl_cert_type(NULL, pkey);
2879             if (idx >= 0)
2880                 md = s->s3->tmp.md[idx];
2881             if (md == NULL) {
2882                 al = SSL_AD_INTERNAL_ERROR;
2883                 goto f_err;
2884             }
2885         }
2886
2887         if (!PACKET_get_net_2(pkt, &len)) {
2888             SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
2889             al = SSL_AD_DECODE_ERROR;
2890             goto f_err;
2891         }
2892     }
2893     j = EVP_PKEY_size(pkey);
2894     if (((int)len > j) || ((int)PACKET_remaining(pkt) > j)
2895             || (PACKET_remaining(pkt) == 0)) {
2896         SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_WRONG_SIGNATURE_SIZE);
2897         al = SSL_AD_DECODE_ERROR;
2898         goto f_err;
2899     }
2900     if (!PACKET_get_bytes(pkt, &data, len)) {
2901         SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
2902         al = SSL_AD_DECODE_ERROR;
2903         goto f_err;
2904     }
2905
2906     hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
2907     if (hdatalen <= 0) {
2908         SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
2909         al = SSL_AD_INTERNAL_ERROR;
2910         goto f_err;
2911     }
2912 #ifdef SSL_DEBUG
2913     fprintf(stderr, "Using client verify alg %s\n", EVP_MD_name(md));
2914 #endif
2915     if (!EVP_VerifyInit_ex(mctx, md, NULL)
2916         || !EVP_VerifyUpdate(mctx, hdata, hdatalen)) {
2917         SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
2918         al = SSL_AD_INTERNAL_ERROR;
2919         goto f_err;
2920     }
2921
2922 #ifndef OPENSSL_NO_GOST
2923     if (pkey->type == NID_id_GostR3410_2001
2924             || pkey->type == NID_id_GostR3410_2012_256
2925             || pkey->type == NID_id_GostR3410_2012_512) {
2926         BUF_reverse(data, NULL, len);
2927     }
2928 #endif
2929
2930     if (s->version == SSL3_VERSION
2931         && !EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
2932                             s->session->master_key_length,
2933                             s->session->master_key)) {
2934         SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
2935         al = SSL_AD_INTERNAL_ERROR;
2936         goto f_err;
2937     }
2938
2939     if (EVP_VerifyFinal(mctx, data, len, pkey) <= 0) {
2940         al = SSL_AD_DECRYPT_ERROR;
2941         SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_BAD_SIGNATURE);
2942         goto f_err;
2943     }
2944
2945     ret = MSG_PROCESS_CONTINUE_PROCESSING;
2946     if (0) {
2947  f_err:
2948         ssl3_send_alert(s, SSL3_AL_FATAL, al);
2949         ossl_statem_set_error(s);
2950     }
2951     BIO_free(s->s3->handshake_buffer);
2952     s->s3->handshake_buffer = NULL;
2953     EVP_MD_CTX_free(mctx);
2954     EVP_PKEY_free(pkey);
2955     return ret;
2956 }
2957
2958 MSG_PROCESS_RETURN tls_process_client_certificate(SSL *s, PACKET *pkt)
2959 {
2960     int i, al = SSL_AD_INTERNAL_ERROR, ret = MSG_PROCESS_ERROR;
2961     X509 *x = NULL;
2962     unsigned long l, llen;
2963     const unsigned char *certstart;
2964     unsigned char *certbytes;
2965     STACK_OF(X509) *sk = NULL;
2966     PACKET spkt;
2967
2968     if ((sk = sk_X509_new_null()) == NULL) {
2969         SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
2970         goto f_err;
2971     }
2972
2973     if (!PACKET_get_net_3(pkt, &llen)
2974             || !PACKET_get_sub_packet(pkt, &spkt, llen)
2975             || PACKET_remaining(pkt) != 0) {
2976         al = SSL_AD_DECODE_ERROR;
2977         SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
2978         goto f_err;
2979     }
2980
2981     while (PACKET_remaining(&spkt) > 0) {
2982         if (!PACKET_get_net_3(&spkt, &l)
2983                 || !PACKET_get_bytes(&spkt, &certbytes, l)) {
2984             al = SSL_AD_DECODE_ERROR;
2985             SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
2986                    SSL_R_CERT_LENGTH_MISMATCH);
2987             goto f_err;
2988         }
2989
2990         certstart = certbytes;
2991         x = d2i_X509(NULL, (const unsigned char **)&certbytes, l);
2992         if (x == NULL) {
2993             SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_ASN1_LIB);
2994             goto f_err;
2995         }
2996         if (certbytes != (certstart + l)) {
2997             al = SSL_AD_DECODE_ERROR;
2998             SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
2999                    SSL_R_CERT_LENGTH_MISMATCH);
3000             goto f_err;
3001         }
3002         if (!sk_X509_push(sk, x)) {
3003             SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3004             goto f_err;
3005         }
3006         x = NULL;
3007     }
3008
3009     if (sk_X509_num(sk) <= 0) {
3010         /* TLS does not mind 0 certs returned */
3011         if (s->version == SSL3_VERSION) {
3012             al = SSL_AD_HANDSHAKE_FAILURE;
3013             SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3014                    SSL_R_NO_CERTIFICATES_RETURNED);
3015             goto f_err;
3016         }
3017         /* Fail for TLS only if we required a certificate */
3018         else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3019                  (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3020             SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3021                    SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3022             al = SSL_AD_HANDSHAKE_FAILURE;
3023             goto f_err;
3024         }
3025         /* No client certificate so digest cached records */
3026         if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s, 0)) {
3027             goto f_err;
3028         }
3029     } else {
3030         EVP_PKEY *pkey;
3031         i = ssl_verify_cert_chain(s, sk);
3032         if (i <= 0) {
3033             al = ssl_verify_alarm_type(s->verify_result);
3034             SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3035                    SSL_R_CERTIFICATE_VERIFY_FAILED);
3036             goto f_err;
3037         }
3038         if (i > 1) {
3039             SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, i);
3040             al = SSL_AD_HANDSHAKE_FAILURE;
3041             goto f_err;
3042         }
3043         pkey = X509_get_pubkey(sk_X509_value(sk, 0));
3044         if (pkey == NULL) {
3045             al = SSL3_AD_HANDSHAKE_FAILURE;
3046             SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3047                    SSL_R_UNKNOWN_CERTIFICATE_TYPE);
3048             goto f_err;
3049         }
3050         EVP_PKEY_free(pkey);
3051     }
3052
3053     X509_free(s->session->peer);
3054     s->session->peer = sk_X509_shift(sk);
3055     s->session->verify_result = s->verify_result;
3056
3057     sk_X509_pop_free(s->session->peer_chain, X509_free);
3058     s->session->peer_chain = sk;
3059     /*
3060      * Inconsistency alert: cert_chain does *not* include the peer's own
3061      * certificate, while we do include it in s3_clnt.c
3062      */
3063     sk = NULL;
3064     ret = MSG_PROCESS_CONTINUE_READING;
3065     goto done;
3066
3067  f_err:
3068     ssl3_send_alert(s, SSL3_AL_FATAL, al);
3069     ossl_statem_set_error(s);
3070  done:
3071     X509_free(x);
3072     sk_X509_pop_free(sk, X509_free);
3073     return ret;
3074 }
3075
3076 int tls_construct_server_certificate(SSL *s)
3077 {
3078     CERT_PKEY *cpk;
3079
3080     cpk = ssl_get_server_send_pkey(s);
3081     if (cpk == NULL) {
3082         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3083         ossl_statem_set_error(s);
3084         return 0;
3085     }
3086
3087     if (!ssl3_output_cert_chain(s, cpk)) {
3088         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3089         ossl_statem_set_error(s);
3090         return 0;
3091     }
3092
3093     return 1;
3094 }
3095
3096 int tls_construct_new_session_ticket(SSL *s)
3097 {
3098     unsigned char *senc = NULL;
3099     EVP_CIPHER_CTX ctx;
3100     HMAC_CTX *hctx = NULL;
3101     unsigned char *p, *macstart;
3102     const unsigned char *const_p;
3103     int len, slen_full, slen;
3104     SSL_SESSION *sess;
3105     unsigned int hlen;
3106     SSL_CTX *tctx = s->initial_ctx;
3107     unsigned char iv[EVP_MAX_IV_LENGTH];
3108     unsigned char key_name[16];
3109
3110     /* get session encoding length */
3111     slen_full = i2d_SSL_SESSION(s->session, NULL);
3112     /*
3113      * Some length values are 16 bits, so forget it if session is too
3114      * long
3115      */
3116     if (slen_full == 0 || slen_full > 0xFF00) {
3117         ossl_statem_set_error(s);
3118         return 0;
3119     }
3120     senc = OPENSSL_malloc(slen_full);
3121     if (senc == NULL) {
3122         ossl_statem_set_error(s);
3123         return 0;
3124     }
3125
3126     EVP_CIPHER_CTX_init(&ctx);
3127     hctx = HMAC_CTX_new();
3128
3129     p = senc;
3130     if (!i2d_SSL_SESSION(s->session, &p))
3131         goto err;
3132
3133     /*
3134      * create a fresh copy (not shared with other threads) to clean up
3135      */
3136     const_p = senc;
3137     sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3138     if (sess == NULL)
3139         goto err;
3140     sess->session_id_length = 0; /* ID is irrelevant for the ticket */
3141
3142     slen = i2d_SSL_SESSION(sess, NULL);
3143     if (slen == 0 || slen > slen_full) { /* shouldn't ever happen */
3144         SSL_SESSION_free(sess);
3145         goto err;
3146     }
3147     p = senc;
3148     if (!i2d_SSL_SESSION(sess, &p)) {
3149         SSL_SESSION_free(sess);
3150         goto err;
3151     }
3152     SSL_SESSION_free(sess);
3153
3154     /*-
3155      * Grow buffer if need be: the length calculation is as
3156      * follows handshake_header_length +
3157      * 4 (ticket lifetime hint) + 2 (ticket length) +
3158      * 16 (key name) + max_iv_len (iv length) +
3159      * session_length + max_enc_block_size (max encrypted session
3160      * length) + max_md_size (HMAC).
3161      */
3162     if (!BUF_MEM_grow(s->init_buf,
3163                       SSL_HM_HEADER_LENGTH(s) + 22 + EVP_MAX_IV_LENGTH +
3164                       EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE + slen))
3165         goto err;
3166
3167     p = ssl_handshake_start(s);
3168     /*
3169      * Initialize HMAC and cipher contexts. If callback present it does
3170      * all the work otherwise use generated values from parent ctx.
3171      */
3172     if (tctx->tlsext_ticket_key_cb) {
3173         if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx, hctx, 1) < 0)
3174             goto err;
3175     } else {
3176         if (RAND_bytes(iv, 16) <= 0)
3177             goto err;
3178         if (!EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3179                                 tctx->tlsext_tick_aes_key, iv))
3180             goto err;
3181         if (!HMAC_Init_ex(hctx, tctx->tlsext_tick_hmac_key, 16,
3182                           EVP_sha256(), NULL))
3183             goto err;
3184         memcpy(key_name, tctx->tlsext_tick_key_name, 16);
3185     }
3186
3187     /*
3188      * Ticket lifetime hint (advisory only): We leave this unspecified
3189      * for resumed session (for simplicity), and guess that tickets for
3190      * new sessions will live as long as their sessions.
3191      */
3192     l2n(s->hit ? 0 : s->session->timeout, p);
3193
3194     /* Skip ticket length for now */
3195     p += 2;
3196     /* Output key name */
3197     macstart = p;
3198     memcpy(p, key_name, 16);
3199     p += 16;
3200     /* output IV */
3201     memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
3202     p += EVP_CIPHER_CTX_iv_length(&ctx);
3203     /* Encrypt session data */
3204     if (!EVP_EncryptUpdate(&ctx, p, &len, senc, slen))
3205         goto err;
3206     p += len;
3207     if (!EVP_EncryptFinal(&ctx, p, &len))
3208         goto err;
3209     p += len;
3210
3211     if (!HMAC_Update(hctx, macstart, p - macstart))
3212         goto err;
3213     if (!HMAC_Final(hctx, p, &hlen))
3214         goto err;
3215
3216     EVP_CIPHER_CTX_cleanup(&ctx);
3217     HMAC_CTX_free(hctx);
3218
3219     p += hlen;
3220     /* Now write out lengths: p points to end of data written */
3221     /* Total length */
3222     len = p - ssl_handshake_start(s);
3223     /* Skip ticket lifetime hint */
3224     p = ssl_handshake_start(s) + 4;
3225     s2n(len - 6, p);
3226     if (!ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len))
3227         goto err;
3228     OPENSSL_free(senc);
3229
3230     return 1;
3231  err:
3232     OPENSSL_free(senc);
3233     EVP_CIPHER_CTX_cleanup(&ctx);
3234     HMAC_CTX_free(hctx);
3235     ossl_statem_set_error(s);
3236     return 0;
3237 }
3238
3239 int tls_construct_cert_status(SSL *s)
3240 {
3241     unsigned char *p;
3242     /*-
3243      * Grow buffer if need be: the length calculation is as
3244      * follows 1 (message type) + 3 (message length) +
3245      * 1 (ocsp response type) + 3 (ocsp response length)
3246      * + (ocsp response)
3247      */
3248     if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen)) {
3249         ossl_statem_set_error(s);
3250         return 0;
3251     }
3252
3253     p = (unsigned char *)s->init_buf->data;
3254
3255     /* do the header */
3256     *(p++) = SSL3_MT_CERTIFICATE_STATUS;
3257     /* message length */
3258     l2n3(s->tlsext_ocsp_resplen + 4, p);
3259     /* status type */
3260     *(p++) = s->tlsext_status_type;
3261     /* length of OCSP response */
3262     l2n3(s->tlsext_ocsp_resplen, p);
3263     /* actual response */
3264     memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
3265     /* number of bytes to write */
3266     s->init_num = 8 + s->tlsext_ocsp_resplen;
3267     s->init_off = 0;
3268
3269     return 1;
3270 }
3271
3272 #ifndef OPENSSL_NO_NEXTPROTONEG
3273 /*
3274  * tls_process_next_proto reads a Next Protocol Negotiation handshake message.
3275  * It sets the next_proto member in s if found
3276  */
3277 MSG_PROCESS_RETURN tls_process_next_proto(SSL *s, PACKET *pkt)
3278 {
3279     PACKET next_proto, padding;
3280     size_t next_proto_len;
3281
3282     /*-
3283      * The payload looks like:
3284      *   uint8 proto_len;
3285      *   uint8 proto[proto_len];
3286      *   uint8 padding_len;
3287      *   uint8 padding[padding_len];
3288      */
3289     if (!PACKET_get_length_prefixed_1(pkt, &next_proto)
3290         || !PACKET_get_length_prefixed_1(pkt, &padding)
3291         || PACKET_remaining(pkt) > 0) {
3292         SSLerr(SSL_F_TLS_PROCESS_NEXT_PROTO, SSL_R_LENGTH_MISMATCH);
3293         goto err;
3294     }
3295
3296     if (!PACKET_memdup(&next_proto, &s->next_proto_negotiated,
3297                        &next_proto_len)) {
3298         s->next_proto_negotiated_len = 0;
3299         goto err;
3300     }
3301
3302     s->next_proto_negotiated_len = (unsigned char)next_proto_len;
3303
3304     return MSG_PROCESS_CONTINUE_READING;
3305 err:
3306     ossl_statem_set_error(s);
3307     return MSG_PROCESS_ERROR;
3308 }
3309 #endif
3310
3311 #define SSLV2_CIPHER_LEN    3
3312
3313 STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list(SSL *s,
3314                                                PACKET *cipher_suites,
3315                                                STACK_OF(SSL_CIPHER) **skp,
3316                                                int sslv2format, int *al
3317                                                )
3318 {
3319     const SSL_CIPHER *c;
3320     STACK_OF(SSL_CIPHER) *sk;
3321     int n;
3322     /* 3 = SSLV2_CIPHER_LEN > TLS_CIPHER_LEN = 2. */
3323     unsigned char cipher[SSLV2_CIPHER_LEN];
3324
3325     s->s3->send_connection_binding = 0;
3326
3327     n = sslv2format ? SSLV2_CIPHER_LEN : TLS_CIPHER_LEN;
3328
3329     if (PACKET_remaining(cipher_suites) == 0) {
3330         SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, SSL_R_NO_CIPHERS_SPECIFIED);
3331         *al = SSL_AD_ILLEGAL_PARAMETER;
3332         return NULL;
3333     }
3334
3335     if (PACKET_remaining(cipher_suites) % n != 0) {
3336         SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
3337                SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
3338         *al = SSL_AD_DECODE_ERROR;
3339         return NULL;
3340     }
3341
3342     if ((skp == NULL) || (*skp == NULL)) {
3343         sk = sk_SSL_CIPHER_new_null(); /* change perhaps later */
3344         if(sk == NULL) {
3345             SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
3346             *al = SSL_AD_INTERNAL_ERROR;
3347             return NULL;
3348         }
3349     } else {
3350         sk = *skp;
3351         sk_SSL_CIPHER_zero(sk);
3352     }
3353
3354     if (!PACKET_memdup(cipher_suites, &s->s3->tmp.ciphers_raw,
3355                        &s->s3->tmp.ciphers_rawlen)) {
3356         *al = SSL_AD_INTERNAL_ERROR;
3357         goto err;
3358     }
3359
3360     while (PACKET_copy_bytes(cipher_suites, cipher, n)) {
3361         /*
3362          * SSLv3 ciphers wrapped in an SSLv2-compatible ClientHello have the
3363          * first byte set to zero, while true SSLv2 ciphers have a non-zero
3364          * first byte. We don't support any true SSLv2 ciphers, so skip them.
3365          */
3366         if (sslv2format && cipher[0] != '\0')
3367                 continue;
3368
3369         /* Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV */
3370         if ((cipher[n - 2] == ((SSL3_CK_SCSV >> 8) & 0xff)) &&
3371             (cipher[n - 1] == (SSL3_CK_SCSV & 0xff))) {
3372             /* SCSV fatal if renegotiating */
3373             if (s->renegotiate) {
3374                 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
3375                        SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING);
3376                 *al = SSL_AD_HANDSHAKE_FAILURE;
3377                 goto err;
3378             }
3379             s->s3->send_connection_binding = 1;
3380 #ifdef OPENSSL_RI_DEBUG
3381             fprintf(stderr, "SCSV received by server\n");
3382 #endif
3383             continue;
3384         }
3385
3386         /* Check for TLS_FALLBACK_SCSV */
3387         if ((cipher[n - 2] == ((SSL3_CK_FALLBACK_SCSV >> 8) & 0xff)) &&
3388             (cipher[n - 1] == (SSL3_CK_FALLBACK_SCSV & 0xff))) {
3389             /*
3390              * The SCSV indicates that the client previously tried a higher
3391              * version. Fail if the current version is an unexpected
3392              * downgrade.
3393              */
3394             if (!SSL_ctrl(s, SSL_CTRL_CHECK_PROTO_VERSION, 0, NULL)) {
3395                 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
3396                        SSL_R_INAPPROPRIATE_FALLBACK);
3397                 *al = SSL_AD_INAPPROPRIATE_FALLBACK;
3398                 goto err;
3399             }
3400             continue;
3401         }
3402
3403         /* For SSLv2-compat, ignore leading 0-byte. */
3404         c = ssl_get_cipher_by_char(s, sslv2format ? &cipher[1] : cipher);
3405         if (c != NULL) {
3406             if (!sk_SSL_CIPHER_push(sk, c)) {
3407                 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
3408                 *al = SSL_AD_INTERNAL_ERROR;
3409                 goto err;
3410             }
3411         }
3412     }
3413     if (PACKET_remaining(cipher_suites) > 0) {
3414         *al = SSL_AD_INTERNAL_ERROR;
3415         SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_INTERNAL_ERROR);
3416         goto err;
3417     }
3418
3419     if (skp != NULL)
3420         *skp = sk;
3421     return (sk);
3422  err:
3423     if ((skp == NULL) || (*skp == NULL))
3424         sk_SSL_CIPHER_free(sk);
3425     return NULL;
3426 }