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