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