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