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