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