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