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