If-guard to avoid null ptr deref in statem_srvr.c
[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  *   signature_algorithms (for TLSv1.2 only)
1179  *
1180  * We wish to fingerprint Safari because they broke ECDHE-ECDSA support in 10.8,
1181  * but they advertise support. So enabling ECDHE-ECDSA ciphers breaks them.
1182  * Sadly we cannot differentiate 10.6, 10.7 and 10.8.4 (which work), from
1183  * 10.8..10.8.3 (which don't work).
1184  */
1185 static void ssl_check_for_safari(SSL *s, const CLIENTHELLO_MSG *hello)
1186 {
1187     static const unsigned char kSafariExtensionsBlock[] = {
1188         0x00, 0x0a,             /* elliptic_curves extension */
1189         0x00, 0x08,             /* 8 bytes */
1190         0x00, 0x06,             /* 6 bytes of curve ids */
1191         0x00, 0x17,             /* P-256 */
1192         0x00, 0x18,             /* P-384 */
1193         0x00, 0x19,             /* P-521 */
1194
1195         0x00, 0x0b,             /* ec_point_formats */
1196         0x00, 0x02,             /* 2 bytes */
1197         0x01,                   /* 1 point format */
1198         0x00,                   /* uncompressed */
1199         /* The following is only present in TLS 1.2 */
1200         0x00, 0x0d,             /* signature_algorithms */
1201         0x00, 0x0c,             /* 12 bytes */
1202         0x00, 0x0a,             /* 10 bytes */
1203         0x05, 0x01,             /* SHA-384/RSA */
1204         0x04, 0x01,             /* SHA-256/RSA */
1205         0x02, 0x01,             /* SHA-1/RSA */
1206         0x04, 0x03,             /* SHA-256/ECDSA */
1207         0x02, 0x03,             /* SHA-1/ECDSA */
1208     };
1209     /* Length of the common prefix (first two extensions). */
1210     static const size_t kSafariCommonExtensionsLength = 18;
1211     unsigned int type;
1212     PACKET sni, tmppkt;
1213     size_t ext_len;
1214
1215     tmppkt = hello->extensions;
1216
1217     if (!PACKET_forward(&tmppkt, 2)
1218         || !PACKET_get_net_2(&tmppkt, &type)
1219         || !PACKET_get_length_prefixed_2(&tmppkt, &sni)) {
1220         return;
1221     }
1222
1223     if (type != TLSEXT_TYPE_server_name)
1224         return;
1225
1226     ext_len = TLS1_get_client_version(s) >= TLS1_2_VERSION ?
1227         sizeof(kSafariExtensionsBlock) : kSafariCommonExtensionsLength;
1228
1229     s->s3->is_probably_safari = PACKET_equal(&tmppkt, kSafariExtensionsBlock,
1230                                              ext_len);
1231 }
1232 #endif                          /* !OPENSSL_NO_EC */
1233
1234 MSG_PROCESS_RETURN tls_process_client_hello(SSL *s, PACKET *pkt)
1235 {
1236     int al = SSL_AD_INTERNAL_ERROR;
1237     /* |cookie| will only be initialized for DTLS. */
1238     PACKET session_id, compression, extensions, cookie;
1239     static const unsigned char null_compression = 0;
1240     CLIENTHELLO_MSG *clienthello;
1241
1242     clienthello = OPENSSL_zalloc(sizeof(*clienthello));
1243     if (clienthello == NULL) {
1244         SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1245         goto err;
1246     }
1247     /* Check if this is actually an unexpected renegotiation ClientHello */
1248     if (s->renegotiate == 0 && !SSL_IS_FIRST_HANDSHAKE(s)) {
1249         if ((s->options & SSL_OP_NO_RENEGOTIATION)) {
1250             ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
1251             goto err;
1252         }
1253         s->renegotiate = 1;
1254         s->new_session = 1;
1255     }
1256
1257     /*
1258      * First, parse the raw ClientHello data into the CLIENTHELLO_MSG structure.
1259      */
1260     clienthello->isv2 = RECORD_LAYER_is_sslv2_record(&s->rlayer);
1261     PACKET_null_init(&cookie);
1262
1263     if (clienthello->isv2) {
1264         unsigned int mt;
1265
1266         if (!SSL_IS_FIRST_HANDSHAKE(s) || s->hello_retry_request) {
1267             al = SSL_AD_UNEXPECTED_MESSAGE;
1268             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNEXPECTED_MESSAGE);
1269             goto f_err;
1270         }
1271
1272         /*-
1273          * An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2
1274          * header is sent directly on the wire, not wrapped as a TLS
1275          * record. Our record layer just processes the message length and passes
1276          * the rest right through. Its format is:
1277          * Byte  Content
1278          * 0-1   msg_length - decoded by the record layer
1279          * 2     msg_type - s->init_msg points here
1280          * 3-4   version
1281          * 5-6   cipher_spec_length
1282          * 7-8   session_id_length
1283          * 9-10  challenge_length
1284          * ...   ...
1285          */
1286
1287         if (!PACKET_get_1(pkt, &mt)
1288             || mt != SSL2_MT_CLIENT_HELLO) {
1289             /*
1290              * Should never happen. We should have tested this in the record
1291              * layer in order to have determined that this is a SSLv2 record
1292              * in the first place
1293              */
1294             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1295             goto err;
1296         }
1297     }
1298
1299     if (!PACKET_get_net_2(pkt, &clienthello->legacy_version)) {
1300         al = SSL_AD_DECODE_ERROR;
1301         SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1302         goto err;
1303     }
1304
1305     /* Parse the message and load client random. */
1306     if (clienthello->isv2) {
1307         /*
1308          * Handle an SSLv2 backwards compatible ClientHello
1309          * Note, this is only for SSLv3+ using the backward compatible format.
1310          * Real SSLv2 is not supported, and is rejected below.
1311          */
1312         unsigned int ciphersuite_len, session_id_len, challenge_len;
1313         PACKET challenge;
1314
1315         if (!PACKET_get_net_2(pkt, &ciphersuite_len)
1316             || !PACKET_get_net_2(pkt, &session_id_len)
1317             || !PACKET_get_net_2(pkt, &challenge_len)) {
1318             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1319                    SSL_R_RECORD_LENGTH_MISMATCH);
1320             al = SSL_AD_DECODE_ERROR;
1321             goto f_err;
1322         }
1323
1324         if (session_id_len > SSL_MAX_SSL_SESSION_ID_LENGTH) {
1325             al = SSL_AD_ILLEGAL_PARAMETER;
1326             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1327             goto f_err;
1328         }
1329
1330         if (!PACKET_get_sub_packet(pkt, &clienthello->ciphersuites,
1331                                    ciphersuite_len)
1332             || !PACKET_copy_bytes(pkt, clienthello->session_id, session_id_len)
1333             || !PACKET_get_sub_packet(pkt, &challenge, challenge_len)
1334             /* No extensions. */
1335             || PACKET_remaining(pkt) != 0) {
1336             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1337                    SSL_R_RECORD_LENGTH_MISMATCH);
1338             al = SSL_AD_DECODE_ERROR;
1339             goto f_err;
1340         }
1341         clienthello->session_id_len = session_id_len;
1342
1343         /* Load the client random and compression list. We use SSL3_RANDOM_SIZE
1344          * here rather than sizeof(clienthello->random) because that is the limit
1345          * for SSLv3 and it is fixed. It won't change even if
1346          * sizeof(clienthello->random) does.
1347          */
1348         challenge_len = challenge_len > SSL3_RANDOM_SIZE
1349                         ? SSL3_RANDOM_SIZE : challenge_len;
1350         memset(clienthello->random, 0, SSL3_RANDOM_SIZE);
1351         if (!PACKET_copy_bytes(&challenge,
1352                                clienthello->random + SSL3_RANDOM_SIZE -
1353                                challenge_len, challenge_len)
1354             /* Advertise only null compression. */
1355             || !PACKET_buf_init(&compression, &null_compression, 1)) {
1356             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1357             al = SSL_AD_INTERNAL_ERROR;
1358             goto f_err;
1359         }
1360
1361         PACKET_null_init(&clienthello->extensions);
1362     } else {
1363         /* Regular ClientHello. */
1364         if (!PACKET_copy_bytes(pkt, clienthello->random, SSL3_RANDOM_SIZE)
1365             || !PACKET_get_length_prefixed_1(pkt, &session_id)
1366             || !PACKET_copy_all(&session_id, clienthello->session_id,
1367                     SSL_MAX_SSL_SESSION_ID_LENGTH,
1368                     &clienthello->session_id_len)) {
1369             al = SSL_AD_DECODE_ERROR;
1370             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1371             goto f_err;
1372         }
1373
1374         if (SSL_IS_DTLS(s)) {
1375             if (!PACKET_get_length_prefixed_1(pkt, &cookie)) {
1376                 al = SSL_AD_DECODE_ERROR;
1377                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1378                 goto f_err;
1379             }
1380             if (!PACKET_copy_all(&cookie, clienthello->dtls_cookie,
1381                                  DTLS1_COOKIE_LENGTH,
1382                                  &clienthello->dtls_cookie_len)) {
1383                 al = SSL_AD_INTERNAL_ERROR;
1384                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1385                 goto f_err;
1386             }
1387             /*
1388              * If we require cookies and this ClientHello doesn't contain one,
1389              * just return since we do not want to allocate any memory yet.
1390              * So check cookie length...
1391              */
1392             if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1393                 if (clienthello->dtls_cookie_len == 0)
1394                     return 1;
1395             }
1396         }
1397
1398         if (!PACKET_get_length_prefixed_2(pkt, &clienthello->ciphersuites)) {
1399             al = SSL_AD_DECODE_ERROR;
1400             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1401             goto f_err;
1402         }
1403
1404         if (!PACKET_get_length_prefixed_1(pkt, &compression)) {
1405             al = SSL_AD_DECODE_ERROR;
1406             SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1407             goto f_err;
1408         }
1409
1410         /* Could be empty. */
1411         if (PACKET_remaining(pkt) == 0) {
1412             PACKET_null_init(&clienthello->extensions);
1413         } else {
1414             if (!PACKET_get_length_prefixed_2(pkt, &clienthello->extensions)
1415                     || PACKET_remaining(pkt) != 0) {
1416                 al = SSL_AD_DECODE_ERROR;
1417                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1418                 goto f_err;
1419             }
1420         }
1421     }
1422
1423     if (!PACKET_copy_all(&compression, clienthello->compressions,
1424                          MAX_COMPRESSIONS_SIZE,
1425                          &clienthello->compressions_len)) {
1426         al = SSL_AD_INTERNAL_ERROR;
1427         SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1428         goto f_err;
1429     }
1430
1431     /* Preserve the raw extensions PACKET for later use */
1432     extensions = clienthello->extensions;
1433     if (!tls_collect_extensions(s, &extensions, SSL_EXT_CLIENT_HELLO,
1434                                 &clienthello->pre_proc_exts, &al,
1435                                 &clienthello->pre_proc_exts_len, 1)) {
1436         /* SSLerr already been called */
1437         goto f_err;
1438     }
1439     s->clienthello = clienthello;
1440
1441     return MSG_PROCESS_CONTINUE_PROCESSING;
1442  f_err:
1443     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1444  err:
1445     ossl_statem_set_error(s);
1446
1447     if (clienthello != NULL)
1448         OPENSSL_free(clienthello->pre_proc_exts);
1449     OPENSSL_free(clienthello);
1450
1451     return MSG_PROCESS_ERROR;
1452 }
1453
1454 static int tls_early_post_process_client_hello(SSL *s, int *pal)
1455 {
1456     unsigned int j;
1457     int i, al = SSL_AD_INTERNAL_ERROR;
1458     int protverr;
1459     size_t loop;
1460     unsigned long id;
1461 #ifndef OPENSSL_NO_COMP
1462     SSL_COMP *comp = NULL;
1463 #endif
1464     const SSL_CIPHER *c;
1465     STACK_OF(SSL_CIPHER) *ciphers = NULL;
1466     STACK_OF(SSL_CIPHER) *scsvs = NULL;
1467     CLIENTHELLO_MSG *clienthello = s->clienthello;
1468     DOWNGRADE dgrd = DOWNGRADE_NONE;
1469
1470     /* Finished parsing the ClientHello, now we can start processing it */
1471     /* Give the early callback a crack at things */
1472     if (s->ctx->early_cb != NULL) {
1473         int code;
1474         /* A failure in the early callback terminates the connection. */
1475         code = s->ctx->early_cb(s, &al, s->ctx->early_cb_arg);
1476         if (code == 0)
1477             goto err;
1478         if (code < 0) {
1479             s->rwstate = SSL_EARLY_WORK;
1480             return code;
1481         }
1482     }
1483
1484     /* Set up the client_random */
1485     memcpy(s->s3->client_random, clienthello->random, SSL3_RANDOM_SIZE);
1486
1487     /* Choose the version */
1488
1489     if (clienthello->isv2) {
1490         if (clienthello->legacy_version == SSL2_VERSION
1491                 || (clienthello->legacy_version & 0xff00)
1492                    != (SSL3_VERSION_MAJOR << 8)) {
1493             /*
1494              * This is real SSLv2 or something complete unknown. We don't
1495              * support it.
1496              */
1497             SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
1498             goto err;
1499         }
1500         /* SSLv3/TLS */
1501         s->client_version = clienthello->legacy_version;
1502     }
1503     /*
1504      * Do SSL/TLS version negotiation if applicable. For DTLS we just check
1505      * versions are potentially compatible. Version negotiation comes later.
1506      */
1507     if (!SSL_IS_DTLS(s)) {
1508         protverr = ssl_choose_server_version(s, clienthello, &dgrd);
1509     } else if (s->method->version != DTLS_ANY_VERSION &&
1510                DTLS_VERSION_LT((int)clienthello->legacy_version, s->version)) {
1511         protverr = SSL_R_VERSION_TOO_LOW;
1512     } else {
1513         protverr = 0;
1514     }
1515
1516     if (protverr) {
1517         SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, protverr);
1518         if (SSL_IS_FIRST_HANDSHAKE(s)) {
1519             /* like ssl3_get_record, send alert using remote version number */
1520             s->version = s->client_version = clienthello->legacy_version;
1521         }
1522         al = SSL_AD_PROTOCOL_VERSION;
1523         goto err;
1524     }
1525
1526     /* TLSv1.3 specifies that a ClientHello must end on a record boundary */
1527     if (SSL_IS_TLS13(s) && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
1528         al = SSL_AD_UNEXPECTED_MESSAGE;
1529         SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1530                SSL_R_NOT_ON_RECORD_BOUNDARY);
1531         goto err;
1532     }
1533
1534     if (SSL_IS_DTLS(s)) {
1535         /* Empty cookie was already handled above by returning early. */
1536         if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1537             if (s->ctx->app_verify_cookie_cb != NULL) {
1538                 if (s->ctx->app_verify_cookie_cb(s, clienthello->dtls_cookie,
1539                         clienthello->dtls_cookie_len) == 0) {
1540                     al = SSL_AD_HANDSHAKE_FAILURE;
1541                     SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1542                            SSL_R_COOKIE_MISMATCH);
1543                     goto err;
1544                     /* else cookie verification succeeded */
1545                 }
1546                 /* default verification */
1547             } else if (s->d1->cookie_len != clienthello->dtls_cookie_len
1548                     || memcmp(clienthello->dtls_cookie, s->d1->cookie,
1549                               s->d1->cookie_len) != 0) {
1550                 al = SSL_AD_HANDSHAKE_FAILURE;
1551                 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1552                 goto err;
1553             }
1554             s->d1->cookie_verified = 1;
1555         }
1556         if (s->method->version == DTLS_ANY_VERSION) {
1557             protverr = ssl_choose_server_version(s, clienthello, &dgrd);
1558             if (protverr != 0) {
1559                 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, protverr);
1560                 s->version = s->client_version;
1561                 al = SSL_AD_PROTOCOL_VERSION;
1562                 goto err;
1563             }
1564         }
1565     }
1566
1567     s->hit = 0;
1568
1569     /* We need to do this before getting the session */
1570     if (!tls_parse_extension(s, TLSEXT_IDX_extended_master_secret,
1571                              SSL_EXT_CLIENT_HELLO,
1572                              clienthello->pre_proc_exts, NULL, 0, &al)) {
1573         SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1574         goto err;
1575     }
1576
1577     /*
1578      * We don't allow resumption in a backwards compatible ClientHello.
1579      * TODO(openssl-team): in TLS1.1+, session_id MUST be empty.
1580      *
1581      * Versions before 0.9.7 always allow clients to resume sessions in
1582      * renegotiation. 0.9.7 and later allow this by default, but optionally
1583      * ignore resumption requests with flag
1584      * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
1585      * than a change to default behavior so that applications relying on
1586      * this for security won't even compile against older library versions).
1587      * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
1588      * request renegotiation but not a new session (s->new_session remains
1589      * unset): for servers, this essentially just means that the
1590      * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be
1591      * ignored.
1592      */
1593     if (clienthello->isv2 ||
1594         (s->new_session &&
1595          (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
1596         if (!ssl_get_new_session(s, 1))
1597             goto err;
1598     } else {
1599         i = ssl_get_prev_session(s, clienthello, &al);
1600         if (i == 1) {
1601             /* previous session */
1602             s->hit = 1;
1603         } else if (i == -1) {
1604             goto err;
1605         } else {
1606             /* i == 0 */
1607             if (!ssl_get_new_session(s, 1))
1608                 goto err;
1609         }
1610     }
1611
1612     if (!ssl_cache_cipherlist(s, &clienthello->ciphersuites,
1613                               clienthello->isv2, &al) ||
1614         !bytes_to_cipher_list(s, &clienthello->ciphersuites, &ciphers, &scsvs,
1615                              clienthello->isv2, &al)) {
1616         goto err;
1617     }
1618
1619     s->s3->send_connection_binding = 0;
1620     /* Check what signalling cipher-suite values were received. */
1621     if (scsvs != NULL) {
1622         for(i = 0; i < sk_SSL_CIPHER_num(scsvs); i++) {
1623             c = sk_SSL_CIPHER_value(scsvs, i);
1624             if (SSL_CIPHER_get_id(c) == SSL3_CK_SCSV) {
1625                 if (s->renegotiate) {
1626                     /* SCSV is fatal if renegotiating */
1627                     SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1628                            SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING);
1629                     al = SSL_AD_HANDSHAKE_FAILURE;
1630                     goto err;
1631                 }
1632                 s->s3->send_connection_binding = 1;
1633             } else if (SSL_CIPHER_get_id(c) == SSL3_CK_FALLBACK_SCSV &&
1634                        !ssl_check_version_downgrade(s)) {
1635                 /*
1636                  * This SCSV indicates that the client previously tried
1637                  * a higher version.  We should fail if the current version
1638                  * is an unexpected downgrade, as that indicates that the first
1639                  * connection may have been tampered with in order to trigger
1640                  * an insecure downgrade.
1641                  */
1642                 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1643                        SSL_R_INAPPROPRIATE_FALLBACK);
1644                 al = SSL_AD_INAPPROPRIATE_FALLBACK;
1645                 goto err;
1646             }
1647         }
1648     }
1649
1650     /* If it is a hit, check that the cipher is in the list */
1651     if (s->hit) {
1652         j = 0;
1653         id = s->session->cipher->id;
1654
1655 #ifdef CIPHER_DEBUG
1656         fprintf(stderr, "client sent %d ciphers\n", sk_SSL_CIPHER_num(ciphers));
1657 #endif
1658         for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1659             c = sk_SSL_CIPHER_value(ciphers, i);
1660 #ifdef CIPHER_DEBUG
1661             fprintf(stderr, "client [%2d of %2d]:%s\n",
1662                     i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
1663 #endif
1664             if (c->id == id) {
1665                 j = 1;
1666                 break;
1667             }
1668         }
1669         if (j == 0) {
1670             /*
1671              * we need to have the cipher in the cipher list if we are asked
1672              * to reuse it
1673              */
1674             al = SSL_AD_ILLEGAL_PARAMETER;
1675             SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1676                    SSL_R_REQUIRED_CIPHER_MISSING);
1677             goto err;
1678         }
1679     }
1680
1681     for (loop = 0; loop < clienthello->compressions_len; loop++) {
1682         if (clienthello->compressions[loop] == 0)
1683             break;
1684     }
1685
1686     if (loop >= clienthello->compressions_len) {
1687         /* no compress */
1688         al = SSL_AD_DECODE_ERROR;
1689         SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED);
1690         goto err;
1691     }
1692
1693 #ifndef OPENSSL_NO_EC
1694     if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
1695         ssl_check_for_safari(s, clienthello);
1696 #endif                          /* !OPENSSL_NO_EC */
1697
1698     /* TLS extensions */
1699     if (!tls_parse_all_extensions(s, SSL_EXT_CLIENT_HELLO,
1700                                   clienthello->pre_proc_exts, NULL, 0, &al, 1)) {
1701         SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_PARSE_TLSEXT);
1702         goto err;
1703     }
1704
1705     /*
1706      * Check if we want to use external pre-shared secret for this handshake
1707      * for not reused session only. We need to generate server_random before
1708      * calling tls_session_secret_cb in order to allow SessionTicket
1709      * processing to use it in key derivation.
1710      */
1711     {
1712         unsigned char *pos;
1713         pos = s->s3->server_random;
1714         if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE, dgrd) <= 0) {
1715             goto err;
1716         }
1717     }
1718
1719     if (!s->hit && s->version >= TLS1_VERSION && s->ext.session_secret_cb) {
1720         const SSL_CIPHER *pref_cipher = NULL;
1721         /*
1722          * s->session->master_key_length is a size_t, but this is an int for
1723          * backwards compat reasons
1724          */
1725         int master_key_length;
1726
1727         master_key_length = sizeof(s->session->master_key);
1728         if (s->ext.session_secret_cb(s, s->session->master_key,
1729                                      &master_key_length, ciphers,
1730                                      &pref_cipher,
1731                                      s->ext.session_secret_cb_arg)
1732                 && master_key_length > 0) {
1733             s->session->master_key_length = master_key_length;
1734             s->hit = 1;
1735             s->session->ciphers = ciphers;
1736             s->session->verify_result = X509_V_OK;
1737
1738             ciphers = NULL;
1739
1740             /* check if some cipher was preferred by call back */
1741             if (pref_cipher == NULL)
1742                 pref_cipher = ssl3_choose_cipher(s, s->session->ciphers,
1743                                                  SSL_get_ciphers(s));
1744             if (pref_cipher == NULL) {
1745                 al = SSL_AD_HANDSHAKE_FAILURE;
1746                 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1747                 goto err;
1748             }
1749
1750             s->session->cipher = pref_cipher;
1751             sk_SSL_CIPHER_free(s->cipher_list);
1752             s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1753             sk_SSL_CIPHER_free(s->cipher_list_by_id);
1754             s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1755         }
1756     }
1757
1758     /*
1759      * Worst case, we will use the NULL compression, but if we have other
1760      * options, we will now look for them.  We have complen-1 compression
1761      * algorithms from the client, starting at q.
1762      */
1763     s->s3->tmp.new_compression = NULL;
1764     if (SSL_IS_TLS13(s)) {
1765         /*
1766          * We already checked above that the NULL compression method appears in
1767          * the list. Now we check there aren't any others (which is illegal in
1768          * a TLSv1.3 ClientHello.
1769          */
1770         if (clienthello->compressions_len != 1) {
1771             al = SSL_AD_ILLEGAL_PARAMETER;
1772             SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1773                    SSL_R_INVALID_COMPRESSION_ALGORITHM);
1774             goto err;
1775         }
1776     }
1777 #ifndef OPENSSL_NO_COMP
1778     /* This only happens if we have a cache hit */
1779     else if (s->session->compress_meth != 0) {
1780         int m, comp_id = s->session->compress_meth;
1781         unsigned int k;
1782         /* Perform sanity checks on resumed compression algorithm */
1783         /* Can't disable compression */
1784         if (!ssl_allow_compression(s)) {
1785             SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1786                    SSL_R_INCONSISTENT_COMPRESSION);
1787             goto err;
1788         }
1789         /* Look for resumed compression method */
1790         for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) {
1791             comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1792             if (comp_id == comp->id) {
1793                 s->s3->tmp.new_compression = comp;
1794                 break;
1795             }
1796         }
1797         if (s->s3->tmp.new_compression == NULL) {
1798             SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1799                    SSL_R_INVALID_COMPRESSION_ALGORITHM);
1800             goto err;
1801         }
1802         /* Look for resumed method in compression list */
1803         for (k = 0; k < clienthello->compressions_len; k++) {
1804             if (clienthello->compressions[k] == comp_id)
1805                 break;
1806         }
1807         if (k >= clienthello->compressions_len) {
1808             al = SSL_AD_ILLEGAL_PARAMETER;
1809             SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1810                    SSL_R_REQUIRED_COMPRESSION_ALGORITHM_MISSING);
1811             goto err;
1812         }
1813     } else if (s->hit) {
1814         comp = NULL;
1815     } else if (ssl_allow_compression(s) && s->ctx->comp_methods) {
1816         /* See if we have a match */
1817         int m, nn, v, done = 0;
1818         unsigned int o;
1819
1820         nn = sk_SSL_COMP_num(s->ctx->comp_methods);
1821         for (m = 0; m < nn; m++) {
1822             comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1823             v = comp->id;
1824             for (o = 0; o < clienthello->compressions_len; o++) {
1825                 if (v == clienthello->compressions[o]) {
1826                     done = 1;
1827                     break;
1828                 }
1829             }
1830             if (done)
1831                 break;
1832         }
1833         if (done)
1834             s->s3->tmp.new_compression = comp;
1835         else
1836             comp = NULL;
1837     }
1838 #else
1839     /*
1840      * If compression is disabled we'd better not try to resume a session
1841      * using compression.
1842      */
1843     if (s->session->compress_meth != 0) {
1844         SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
1845         goto err;
1846     }
1847 #endif
1848
1849     /*
1850      * Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher
1851      */
1852
1853     if (!s->hit || s->hello_retry_request) {
1854         sk_SSL_CIPHER_free(s->session->ciphers);
1855         s->session->ciphers = ciphers;
1856         if (ciphers == NULL) {
1857             al = SSL_AD_INTERNAL_ERROR;
1858             SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1859             goto err;
1860         }
1861         ciphers = NULL;
1862     }
1863
1864     if (!s->hit) {
1865 #ifdef OPENSSL_NO_COMP
1866         s->session->compress_meth = 0;
1867 #else
1868         s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
1869 #endif
1870         if (!tls1_set_server_sigalgs(s)) {
1871             SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1872             goto err;
1873         }
1874     }
1875
1876     sk_SSL_CIPHER_free(ciphers);
1877     sk_SSL_CIPHER_free(scsvs);
1878     OPENSSL_free(clienthello->pre_proc_exts);
1879     OPENSSL_free(s->clienthello);
1880     s->clienthello = NULL;
1881     return 1;
1882  err:
1883     ossl_statem_set_error(s);
1884     *pal = al;
1885
1886     sk_SSL_CIPHER_free(ciphers);
1887     sk_SSL_CIPHER_free(scsvs);
1888     OPENSSL_free(clienthello->pre_proc_exts);
1889     OPENSSL_free(s->clienthello);
1890     s->clienthello = NULL;
1891
1892     return 0;
1893 }
1894
1895 /*
1896  * Call the status request callback if needed. Upon success, returns 1.
1897  * Upon failure, returns 0 and sets |*al| to the appropriate fatal alert.
1898  */
1899 static int tls_handle_status_request(SSL *s, int *al)
1900 {
1901     s->ext.status_expected = 0;
1902
1903     /*
1904      * If status request then ask callback what to do. Note: this must be
1905      * called after servername callbacks in case the certificate has changed,
1906      * and must be called after the cipher has been chosen because this may
1907      * influence which certificate is sent
1908      */
1909     if (s->ext.status_type != TLSEXT_STATUSTYPE_nothing && s->ctx != NULL
1910             && s->ctx->ext.status_cb != NULL) {
1911         int ret;
1912
1913         /* If no certificate can't return certificate status */
1914         if (s->s3->tmp.cert != NULL) {
1915             /*
1916              * Set current certificate to one we will use so SSL_get_certificate
1917              * et al can pick it up.
1918              */
1919             s->cert->key = s->s3->tmp.cert;
1920             ret = s->ctx->ext.status_cb(s, s->ctx->ext.status_arg);
1921             switch (ret) {
1922                 /* We don't want to send a status request response */
1923             case SSL_TLSEXT_ERR_NOACK:
1924                 s->ext.status_expected = 0;
1925                 break;
1926                 /* status request response should be sent */
1927             case SSL_TLSEXT_ERR_OK:
1928                 if (s->ext.ocsp.resp)
1929                     s->ext.status_expected = 1;
1930                 break;
1931                 /* something bad happened */
1932             case SSL_TLSEXT_ERR_ALERT_FATAL:
1933             default:
1934                 *al = SSL_AD_INTERNAL_ERROR;
1935                 return 0;
1936             }
1937         }
1938     }
1939
1940     return 1;
1941 }
1942
1943 WORK_STATE tls_post_process_client_hello(SSL *s, WORK_STATE wst)
1944 {
1945     int al = SSL_AD_HANDSHAKE_FAILURE;
1946     const SSL_CIPHER *cipher;
1947
1948     if (wst == WORK_MORE_A) {
1949         int rv = tls_early_post_process_client_hello(s, &al);
1950         if (rv == 0) {
1951             /* SSLErr() was already called */
1952             goto f_err;
1953         }
1954         if (rv < 0)
1955             return WORK_MORE_A;
1956         wst = WORK_MORE_B;
1957     }
1958     if (wst == WORK_MORE_B) {
1959         if (!s->hit || s->hello_retry_request) {
1960             /* Let cert callback update server certificates if required */
1961             if (s->cert->cert_cb) {
1962                 int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
1963                 if (rv == 0) {
1964                     al = SSL_AD_INTERNAL_ERROR;
1965                     SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
1966                            SSL_R_CERT_CB_ERROR);
1967                     goto f_err;
1968                 }
1969                 if (rv < 0) {
1970                     s->rwstate = SSL_X509_LOOKUP;
1971                     return WORK_MORE_B;
1972                 }
1973                 s->rwstate = SSL_NOTHING;
1974             }
1975             cipher =
1976                 ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
1977
1978             if (cipher == NULL) {
1979                 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
1980                        SSL_R_NO_SHARED_CIPHER);
1981                 goto f_err;
1982             }
1983             if (SSL_IS_TLS13(s) && s->s3->tmp.new_cipher != NULL
1984                     && s->s3->tmp.new_cipher->id != cipher->id) {
1985                 /*
1986                  * A previous HRR picked a different ciphersuite to the one we
1987                  * just selected. Something must have changed.
1988                  */
1989                 al = SSL_AD_ILLEGAL_PARAMETER;
1990                 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO, SSL_R_BAD_CIPHER);
1991                 goto f_err;
1992             }
1993             s->s3->tmp.new_cipher = cipher;
1994             if (!s->hit) {
1995                 if (!tls_choose_sigalg(s, &al))
1996                     goto f_err;
1997                 /* check whether we should disable session resumption */
1998                 if (s->not_resumable_session_cb != NULL)
1999                     s->session->not_resumable =
2000                         s->not_resumable_session_cb(s, ((cipher->algorithm_mkey
2001                                                         & (SSL_kDHE | SSL_kECDHE))
2002                                                        != 0));
2003                 if (s->session->not_resumable)
2004                     /* do not send a session ticket */
2005                     s->ext.ticket_expected = 0;
2006             }
2007         } else {
2008             /* Session-id reuse */
2009             s->s3->tmp.new_cipher = s->session->cipher;
2010         }
2011
2012         /*-
2013          * we now have the following setup.
2014          * client_random
2015          * cipher_list          - our preferred list of ciphers
2016          * ciphers              - the clients preferred list of ciphers
2017          * compression          - basically ignored right now
2018          * ssl version is set   - sslv3
2019          * s->session           - The ssl session has been setup.
2020          * s->hit               - session reuse flag
2021          * s->s3->tmp.new_cipher- the new cipher to use.
2022          */
2023
2024         /*
2025          * Call status_request callback if needed. Has to be done after the
2026          * certificate callbacks etc above.
2027          */
2028         if (!tls_handle_status_request(s, &al)) {
2029             SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
2030                    SSL_R_CLIENTHELLO_TLSEXT);
2031             goto f_err;
2032         }
2033
2034         wst = WORK_MORE_C;
2035     }
2036 #ifndef OPENSSL_NO_SRP
2037     if (wst == WORK_MORE_C) {
2038         int ret;
2039         if ((ret = ssl_check_srp_ext_ClientHello(s, &al)) < 0) {
2040             /*
2041              * callback indicates further work to be done
2042              */
2043             s->rwstate = SSL_X509_LOOKUP;
2044             return WORK_MORE_C;
2045         }
2046         if (ret != SSL_ERROR_NONE) {
2047             /*
2048              * This is not really an error but the only means to for
2049              * a client to detect whether srp is supported.
2050              */
2051             if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)
2052                 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
2053                        SSL_R_CLIENTHELLO_TLSEXT);
2054             else
2055                 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
2056                        SSL_R_PSK_IDENTITY_NOT_FOUND);
2057             goto f_err;
2058         }
2059     }
2060 #endif
2061
2062     return WORK_FINISHED_STOP;
2063  f_err:
2064     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2065     ossl_statem_set_error(s);
2066     return WORK_ERROR;
2067 }
2068
2069 int tls_construct_server_hello(SSL *s, WPACKET *pkt)
2070 {
2071     int compm, al = SSL_AD_INTERNAL_ERROR;
2072     size_t sl, len;
2073     int version;
2074
2075     /* TODO(TLS1.3): Remove the DRAFT conditional before release */
2076     version = SSL_IS_TLS13(s) ? TLS1_3_VERSION_DRAFT : s->version;
2077     if (!WPACKET_put_bytes_u16(pkt, version)
2078                /*
2079                 * Random stuff. Filling of the server_random takes place in
2080                 * tls_process_client_hello()
2081                 */
2082             || !WPACKET_memcpy(pkt, s->s3->server_random, SSL3_RANDOM_SIZE)) {
2083         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
2084         goto err;
2085     }
2086
2087     /*-
2088      * There are several cases for the session ID to send
2089      * back in the server hello:
2090      * - For session reuse from the session cache,
2091      *   we send back the old session ID.
2092      * - If stateless session reuse (using a session ticket)
2093      *   is successful, we send back the client's "session ID"
2094      *   (which doesn't actually identify the session).
2095      * - If it is a new session, we send back the new
2096      *   session ID.
2097      * - However, if we want the new session to be single-use,
2098      *   we send back a 0-length session ID.
2099      * s->hit is non-zero in either case of session reuse,
2100      * so the following won't overwrite an ID that we're supposed
2101      * to send back.
2102      */
2103     if (s->session->not_resumable ||
2104         (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
2105          && !s->hit))
2106         s->session->session_id_length = 0;
2107
2108     sl = s->session->session_id_length;
2109     if (sl > sizeof(s->session->session_id)) {
2110         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
2111         goto err;
2112     }
2113
2114     /* set up the compression method */
2115 #ifdef OPENSSL_NO_COMP
2116     compm = 0;
2117 #else
2118     if (s->s3->tmp.new_compression == NULL)
2119         compm = 0;
2120     else
2121         compm = s->s3->tmp.new_compression->id;
2122 #endif
2123
2124     if ((!SSL_IS_TLS13(s)
2125                 && !WPACKET_sub_memcpy_u8(pkt, s->session->session_id, sl))
2126             || !s->method->put_cipher_by_char(s->s3->tmp.new_cipher, pkt, &len)
2127             || (!SSL_IS_TLS13(s)
2128                 && !WPACKET_put_bytes_u8(pkt, compm))
2129             || !tls_construct_extensions(s, pkt,
2130                                          SSL_IS_TLS13(s)
2131                                             ? SSL_EXT_TLS1_3_SERVER_HELLO
2132                                             : SSL_EXT_TLS1_2_SERVER_HELLO,
2133                                          NULL, 0, &al)) {
2134         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
2135         goto err;
2136     }
2137
2138     if (!(s->verify_mode & SSL_VERIFY_PEER)
2139             && !ssl3_digest_cached_records(s, 0)) {
2140         al = SSL_AD_INTERNAL_ERROR;
2141         goto err;
2142     }
2143
2144     return 1;
2145  err:
2146     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2147     return 0;
2148 }
2149
2150 int tls_construct_server_done(SSL *s, WPACKET *pkt)
2151 {
2152     if (!s->s3->tmp.cert_request) {
2153         if (!ssl3_digest_cached_records(s, 0)) {
2154             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2155             return 0;
2156         }
2157     }
2158     return 1;
2159 }
2160
2161 int tls_construct_server_key_exchange(SSL *s, WPACKET *pkt)
2162 {
2163 #ifndef OPENSSL_NO_DH
2164     EVP_PKEY *pkdh = NULL;
2165 #endif
2166 #ifndef OPENSSL_NO_EC
2167     unsigned char *encodedPoint = NULL;
2168     size_t encodedlen = 0;
2169     int curve_id = 0;
2170 #endif
2171     const SIGALG_LOOKUP *lu = s->s3->tmp.sigalg;
2172     int al = SSL_AD_INTERNAL_ERROR, i;
2173     unsigned long type;
2174     const BIGNUM *r[4];
2175     EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
2176     EVP_PKEY_CTX *pctx = NULL;
2177     size_t paramlen, paramoffset;
2178
2179     if (!WPACKET_get_total_written(pkt, &paramoffset)) {
2180         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2181         goto f_err;
2182     }
2183
2184     if (md_ctx == NULL) {
2185         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2186         goto f_err;
2187     }
2188
2189     type = s->s3->tmp.new_cipher->algorithm_mkey;
2190
2191     r[0] = r[1] = r[2] = r[3] = NULL;
2192 #ifndef OPENSSL_NO_PSK
2193     /* Plain PSK or RSAPSK nothing to do */
2194     if (type & (SSL_kPSK | SSL_kRSAPSK)) {
2195     } else
2196 #endif                          /* !OPENSSL_NO_PSK */
2197 #ifndef OPENSSL_NO_DH
2198     if (type & (SSL_kDHE | SSL_kDHEPSK)) {
2199         CERT *cert = s->cert;
2200
2201         EVP_PKEY *pkdhp = NULL;
2202         DH *dh;
2203
2204         if (s->cert->dh_tmp_auto) {
2205             DH *dhp = ssl_get_auto_dh(s);
2206             pkdh = EVP_PKEY_new();
2207             if (pkdh == NULL || dhp == NULL) {
2208                 DH_free(dhp);
2209                 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2210                        ERR_R_INTERNAL_ERROR);
2211                 goto f_err;
2212             }
2213             EVP_PKEY_assign_DH(pkdh, dhp);
2214             pkdhp = pkdh;
2215         } else {
2216             pkdhp = cert->dh_tmp;
2217         }
2218         if ((pkdhp == NULL) && (s->cert->dh_tmp_cb != NULL)) {
2219             DH *dhp = s->cert->dh_tmp_cb(s, 0, 1024);
2220             pkdh = ssl_dh_to_pkey(dhp);
2221             if (pkdh == NULL) {
2222                 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2223                        ERR_R_INTERNAL_ERROR);
2224                 goto f_err;
2225             }
2226             pkdhp = pkdh;
2227         }
2228         if (pkdhp == NULL) {
2229             al = SSL_AD_INTERNAL_ERROR;
2230             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2231                    SSL_R_MISSING_TMP_DH_KEY);
2232             goto f_err;
2233         }
2234         if (!ssl_security(s, SSL_SECOP_TMP_DH,
2235                           EVP_PKEY_security_bits(pkdhp), 0, pkdhp)) {
2236             al = SSL_AD_HANDSHAKE_FAILURE;
2237             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2238                    SSL_R_DH_KEY_TOO_SMALL);
2239             goto f_err;
2240         }
2241         if (s->s3->tmp.pkey != NULL) {
2242             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2243                    ERR_R_INTERNAL_ERROR);
2244             goto err;
2245         }
2246
2247         s->s3->tmp.pkey = ssl_generate_pkey(pkdhp);
2248
2249         if (s->s3->tmp.pkey == NULL) {
2250             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EVP_LIB);
2251             goto err;
2252         }
2253
2254         dh = EVP_PKEY_get0_DH(s->s3->tmp.pkey);
2255
2256         EVP_PKEY_free(pkdh);
2257         pkdh = NULL;
2258
2259         DH_get0_pqg(dh, &r[0], NULL, &r[1]);
2260         DH_get0_key(dh, &r[2], NULL);
2261     } else
2262 #endif
2263 #ifndef OPENSSL_NO_EC
2264     if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
2265         int nid;
2266
2267         if (s->s3->tmp.pkey != NULL) {
2268             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2269                    ERR_R_INTERNAL_ERROR);
2270             goto err;
2271         }
2272
2273         /* Get NID of appropriate shared curve */
2274         nid = tls1_shared_group(s, -2);
2275         curve_id = tls1_ec_nid2curve_id(nid);
2276         if (curve_id == 0) {
2277             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2278                    SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
2279             goto err;
2280         }
2281         s->s3->tmp.pkey = ssl_generate_pkey_curve(curve_id);
2282         /* Generate a new key for this curve */
2283         if (s->s3->tmp.pkey == NULL) {
2284             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EVP_LIB);
2285             goto f_err;
2286         }
2287
2288         /* Encode the public key. */
2289         encodedlen = EVP_PKEY_get1_tls_encodedpoint(s->s3->tmp.pkey,
2290                                                     &encodedPoint);
2291         if (encodedlen == 0) {
2292             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EC_LIB);
2293             goto err;
2294         }
2295
2296         /*
2297          * We'll generate the serverKeyExchange message explicitly so we
2298          * can set these to NULLs
2299          */
2300         r[0] = NULL;
2301         r[1] = NULL;
2302         r[2] = NULL;
2303         r[3] = NULL;
2304     } else
2305 #endif                          /* !OPENSSL_NO_EC */
2306 #ifndef OPENSSL_NO_SRP
2307     if (type & SSL_kSRP) {
2308         if ((s->srp_ctx.N == NULL) ||
2309             (s->srp_ctx.g == NULL) ||
2310             (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
2311             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2312                    SSL_R_MISSING_SRP_PARAM);
2313             goto err;
2314         }
2315         r[0] = s->srp_ctx.N;
2316         r[1] = s->srp_ctx.g;
2317         r[2] = s->srp_ctx.s;
2318         r[3] = s->srp_ctx.B;
2319     } else
2320 #endif
2321     {
2322         al = SSL_AD_INTERNAL_ERROR;
2323         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2324                SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
2325         goto f_err;
2326     }
2327
2328     if (((s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP)) != 0)
2329         || ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_PSK)) != 0) {
2330         lu = NULL;
2331     } else if (lu == NULL) {
2332         al = SSL_AD_DECODE_ERROR;
2333         goto f_err;
2334     }
2335
2336 #ifndef OPENSSL_NO_PSK
2337     if (type & SSL_PSK) {
2338         size_t len = (s->cert->psk_identity_hint == NULL)
2339                         ? 0 : strlen(s->cert->psk_identity_hint);
2340
2341         /*
2342          * It should not happen that len > PSK_MAX_IDENTITY_LEN - we already
2343          * checked this when we set the identity hint - but just in case
2344          */
2345         if (len > PSK_MAX_IDENTITY_LEN
2346                 || !WPACKET_sub_memcpy_u16(pkt, s->cert->psk_identity_hint,
2347                                            len)) {
2348             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2349                    ERR_R_INTERNAL_ERROR);
2350             goto f_err;
2351         }
2352     }
2353 #endif
2354
2355     for (i = 0; i < 4 && r[i] != NULL; i++) {
2356         unsigned char *binval;
2357         int res;
2358
2359 #ifndef OPENSSL_NO_SRP
2360         if ((i == 2) && (type & SSL_kSRP)) {
2361             res = WPACKET_start_sub_packet_u8(pkt);
2362         } else
2363 #endif
2364             res = WPACKET_start_sub_packet_u16(pkt);
2365
2366         if (!res) {
2367             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2368                    ERR_R_INTERNAL_ERROR);
2369             goto f_err;
2370         }
2371
2372 #ifndef OPENSSL_NO_DH
2373         /*-
2374          * for interoperability with some versions of the Microsoft TLS
2375          * stack, we need to zero pad the DHE pub key to the same length
2376          * as the prime
2377          */
2378         if ((i == 2) && (type & (SSL_kDHE | SSL_kDHEPSK))) {
2379             size_t len = BN_num_bytes(r[0]) - BN_num_bytes(r[2]);
2380
2381             if (len > 0) {
2382                 if (!WPACKET_allocate_bytes(pkt, len, &binval)) {
2383                     SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2384                            ERR_R_INTERNAL_ERROR);
2385                     goto f_err;
2386                 }
2387                 memset(binval, 0, len);
2388             }
2389         }
2390 #endif
2391         if (!WPACKET_allocate_bytes(pkt, BN_num_bytes(r[i]), &binval)
2392                 || !WPACKET_close(pkt)) {
2393             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2394                    ERR_R_INTERNAL_ERROR);
2395             goto f_err;
2396         }
2397
2398         BN_bn2bin(r[i], binval);
2399     }
2400
2401 #ifndef OPENSSL_NO_EC
2402     if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
2403         /*
2404          * We only support named (not generic) curves. In this situation, the
2405          * ServerKeyExchange message has: [1 byte CurveType], [2 byte CurveName]
2406          * [1 byte length of encoded point], followed by the actual encoded
2407          * point itself
2408          */
2409         if (!WPACKET_put_bytes_u8(pkt, NAMED_CURVE_TYPE)
2410                 || !WPACKET_put_bytes_u8(pkt, 0)
2411                 || !WPACKET_put_bytes_u8(pkt, curve_id)
2412                 || !WPACKET_sub_memcpy_u8(pkt, encodedPoint, encodedlen)) {
2413             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2414                    ERR_R_INTERNAL_ERROR);
2415             goto f_err;
2416         }
2417         OPENSSL_free(encodedPoint);
2418         encodedPoint = NULL;
2419     }
2420 #endif
2421
2422     /* not anonymous */
2423     if (lu != NULL) {
2424         EVP_PKEY *pkey = s->s3->tmp.cert->privatekey;
2425         const EVP_MD *md = ssl_md(lu->hash_idx);
2426         unsigned char *sigbytes1, *sigbytes2;
2427         size_t siglen;
2428
2429         if (pkey == NULL || md == NULL) {
2430             /* Should never happen */
2431             al = SSL_AD_INTERNAL_ERROR;
2432             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2433                    ERR_R_INTERNAL_ERROR);
2434             goto f_err;
2435         }
2436         /*
2437          * n is the length of the params, they start at &(d[4]) and p
2438          * points to the space at the end.
2439          */
2440
2441         /* Get length of the parameters we have written above */
2442         if (!WPACKET_get_length(pkt, &paramlen)) {
2443             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2444                    ERR_R_INTERNAL_ERROR);
2445             goto f_err;
2446         }
2447         /* send signature algorithm */
2448         if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg))
2449                 return 0;
2450         /*
2451          * Create the signature. We don't know the actual length of the sig
2452          * until after we've created it, so we reserve enough bytes for it
2453          * up front, and then properly allocate them in the WPACKET
2454          * afterwards.
2455          */
2456         siglen = EVP_PKEY_size(pkey);
2457         if (!WPACKET_sub_reserve_bytes_u16(pkt, siglen, &sigbytes1)
2458             || EVP_DigestSignInit(md_ctx, &pctx, md, NULL, pkey) <= 0) {
2459             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2460                    ERR_R_INTERNAL_ERROR);
2461             goto f_err;
2462         }
2463         if (lu->sig == EVP_PKEY_RSA_PSS) {
2464             if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
2465                 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, RSA_PSS_SALTLEN_DIGEST) <= 0) {
2466                 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2467                        ERR_R_EVP_LIB);
2468                 goto f_err;
2469             }
2470         }
2471         if (EVP_DigestSignUpdate(md_ctx, &(s->s3->client_random[0]),
2472                                  SSL3_RANDOM_SIZE) <= 0
2473             || EVP_DigestSignUpdate(md_ctx, &(s->s3->server_random[0]),
2474                                         SSL3_RANDOM_SIZE) <= 0
2475             || EVP_DigestSignUpdate(md_ctx,
2476                                         s->init_buf->data + paramoffset,
2477                                         paramlen) <= 0
2478             || EVP_DigestSignFinal(md_ctx, sigbytes1, &siglen) <= 0
2479             || !WPACKET_sub_allocate_bytes_u16(pkt, siglen, &sigbytes2)
2480             || sigbytes1 != sigbytes2) {
2481             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2482                    ERR_R_INTERNAL_ERROR);
2483             goto f_err;
2484         }
2485     }
2486
2487     EVP_MD_CTX_free(md_ctx);
2488     return 1;
2489  f_err:
2490     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2491  err:
2492 #ifndef OPENSSL_NO_DH
2493     EVP_PKEY_free(pkdh);
2494 #endif
2495 #ifndef OPENSSL_NO_EC
2496     OPENSSL_free(encodedPoint);
2497 #endif
2498     EVP_MD_CTX_free(md_ctx);
2499     return 0;
2500 }
2501
2502 int tls_construct_certificate_request(SSL *s, WPACKET *pkt)
2503 {
2504     int al = SSL_AD_INTERNAL_ERROR;
2505
2506     if (SSL_IS_TLS13(s)) {
2507         /* TODO(TLS1.3) for now send empty request context */
2508         if (!WPACKET_put_bytes_u8(pkt, 0)) {
2509             SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2510                    ERR_R_INTERNAL_ERROR);
2511             goto err;
2512         }
2513
2514         if (!tls_construct_extensions(s, pkt,
2515                                       SSL_EXT_TLS1_3_CERTIFICATE_REQUEST, NULL,
2516                                       0, &al)) {
2517             SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2518                    ERR_R_INTERNAL_ERROR);
2519             goto err;
2520         }
2521         goto done;
2522     }
2523
2524     /* get the list of acceptable cert types */
2525     if (!WPACKET_start_sub_packet_u8(pkt)
2526         || !ssl3_get_req_cert_type(s, pkt) || !WPACKET_close(pkt)) {
2527         SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR);
2528         goto err;
2529     }
2530
2531     if (SSL_USE_SIGALGS(s)) {
2532         const uint16_t *psigs;
2533         size_t nl = tls12_get_psigalgs(s, 1, &psigs);
2534
2535         if (!WPACKET_start_sub_packet_u16(pkt)
2536                 || !WPACKET_set_flags(pkt, WPACKET_FLAGS_NON_ZERO_LENGTH)
2537                 || !tls12_copy_sigalgs(s, pkt, psigs, nl)
2538                 || !WPACKET_close(pkt)) {
2539             SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2540                    ERR_R_INTERNAL_ERROR);
2541             goto err;
2542         }
2543     }
2544
2545     if (!construct_ca_names(s, pkt)) {
2546         SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR);
2547         goto err;
2548     }
2549
2550  done:
2551     s->s3->tmp.cert_request = 1;
2552     return 1;
2553  err:
2554     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2555     return 0;
2556 }
2557
2558 static int tls_process_cke_psk_preamble(SSL *s, PACKET *pkt, int *al)
2559 {
2560 #ifndef OPENSSL_NO_PSK
2561     unsigned char psk[PSK_MAX_PSK_LEN];
2562     size_t psklen;
2563     PACKET psk_identity;
2564
2565     if (!PACKET_get_length_prefixed_2(pkt, &psk_identity)) {
2566         *al = SSL_AD_DECODE_ERROR;
2567         SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, SSL_R_LENGTH_MISMATCH);
2568         return 0;
2569     }
2570     if (PACKET_remaining(&psk_identity) > PSK_MAX_IDENTITY_LEN) {
2571         *al = SSL_AD_DECODE_ERROR;
2572         SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, SSL_R_DATA_LENGTH_TOO_LONG);
2573         return 0;
2574     }
2575     if (s->psk_server_callback == NULL) {
2576         *al = SSL_AD_INTERNAL_ERROR;
2577         SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, SSL_R_PSK_NO_SERVER_CB);
2578         return 0;
2579     }
2580
2581     if (!PACKET_strndup(&psk_identity, &s->session->psk_identity)) {
2582         *al = SSL_AD_INTERNAL_ERROR;
2583         SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
2584         return 0;
2585     }
2586
2587     psklen = s->psk_server_callback(s, s->session->psk_identity,
2588                                     psk, sizeof(psk));
2589
2590     if (psklen > PSK_MAX_PSK_LEN) {
2591         *al = SSL_AD_INTERNAL_ERROR;
2592         SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
2593         return 0;
2594     } else if (psklen == 0) {
2595         /*
2596          * PSK related to the given identity not found
2597          */
2598         *al = SSL_AD_UNKNOWN_PSK_IDENTITY;
2599         SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2600                SSL_R_PSK_IDENTITY_NOT_FOUND);
2601         return 0;
2602     }
2603
2604     OPENSSL_free(s->s3->tmp.psk);
2605     s->s3->tmp.psk = OPENSSL_memdup(psk, psklen);
2606     OPENSSL_cleanse(psk, psklen);
2607
2608     if (s->s3->tmp.psk == NULL) {
2609         *al = SSL_AD_INTERNAL_ERROR;
2610         SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, ERR_R_MALLOC_FAILURE);
2611         return 0;
2612     }
2613
2614     s->s3->tmp.psklen = psklen;
2615
2616     return 1;
2617 #else
2618     /* Should never happen */
2619     *al = SSL_AD_INTERNAL_ERROR;
2620     SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
2621     return 0;
2622 #endif
2623 }
2624
2625 static int tls_process_cke_rsa(SSL *s, PACKET *pkt, int *al)
2626 {
2627 #ifndef OPENSSL_NO_RSA
2628     unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2629     int decrypt_len;
2630     unsigned char decrypt_good, version_good;
2631     size_t j, padding_len;
2632     PACKET enc_premaster;
2633     RSA *rsa = NULL;
2634     unsigned char *rsa_decrypt = NULL;
2635     int ret = 0;
2636
2637     rsa = EVP_PKEY_get0_RSA(s->cert->pkeys[SSL_PKEY_RSA].privatekey);
2638     if (rsa == NULL) {
2639         *al = SSL_AD_INTERNAL_ERROR;
2640         SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, SSL_R_MISSING_RSA_CERTIFICATE);
2641         return 0;
2642     }
2643
2644     /* SSLv3 and pre-standard DTLS omit the length bytes. */
2645     if (s->version == SSL3_VERSION || s->version == DTLS1_BAD_VER) {
2646         enc_premaster = *pkt;
2647     } else {
2648         if (!PACKET_get_length_prefixed_2(pkt, &enc_premaster)
2649             || PACKET_remaining(pkt) != 0) {
2650             *al = SSL_AD_DECODE_ERROR;
2651             SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, SSL_R_LENGTH_MISMATCH);
2652             return 0;
2653         }
2654     }
2655
2656     /*
2657      * We want to be sure that the plaintext buffer size makes it safe to
2658      * iterate over the entire size of a premaster secret
2659      * (SSL_MAX_MASTER_KEY_LENGTH). Reject overly short RSA keys because
2660      * their ciphertext cannot accommodate a premaster secret anyway.
2661      */
2662     if (RSA_size(rsa) < SSL_MAX_MASTER_KEY_LENGTH) {
2663         *al = SSL_AD_INTERNAL_ERROR;
2664         SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, RSA_R_KEY_SIZE_TOO_SMALL);
2665         return 0;
2666     }
2667
2668     rsa_decrypt = OPENSSL_malloc(RSA_size(rsa));
2669     if (rsa_decrypt == NULL) {
2670         *al = SSL_AD_INTERNAL_ERROR;
2671         SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, ERR_R_MALLOC_FAILURE);
2672         return 0;
2673     }
2674
2675     /*
2676      * We must not leak whether a decryption failure occurs because of
2677      * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
2678      * section 7.4.7.1). The code follows that advice of the TLS RFC and
2679      * generates a random premaster secret for the case that the decrypt
2680      * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
2681      */
2682
2683     if (RAND_bytes(rand_premaster_secret, sizeof(rand_premaster_secret)) <= 0)
2684         goto err;
2685
2686     /*
2687      * Decrypt with no padding. PKCS#1 padding will be removed as part of
2688      * the timing-sensitive code below.
2689      */
2690      /* TODO(size_t): Convert this function */
2691     decrypt_len = (int)RSA_private_decrypt((int)PACKET_remaining(&enc_premaster),
2692                                            PACKET_data(&enc_premaster),
2693                                            rsa_decrypt, rsa, RSA_NO_PADDING);
2694     if (decrypt_len < 0)
2695         goto err;
2696
2697     /* Check the padding. See RFC 3447, section 7.2.2. */
2698
2699     /*
2700      * The smallest padded premaster is 11 bytes of overhead. Small keys
2701      * are publicly invalid, so this may return immediately. This ensures
2702      * PS is at least 8 bytes.
2703      */
2704     if (decrypt_len < 11 + SSL_MAX_MASTER_KEY_LENGTH) {
2705         *al = SSL_AD_DECRYPT_ERROR;
2706         SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, SSL_R_DECRYPTION_FAILED);
2707         goto err;
2708     }
2709
2710     padding_len = decrypt_len - SSL_MAX_MASTER_KEY_LENGTH;
2711     decrypt_good = constant_time_eq_int_8(rsa_decrypt[0], 0) &
2712         constant_time_eq_int_8(rsa_decrypt[1], 2);
2713     for (j = 2; j < padding_len - 1; j++) {
2714         decrypt_good &= ~constant_time_is_zero_8(rsa_decrypt[j]);
2715     }
2716     decrypt_good &= constant_time_is_zero_8(rsa_decrypt[padding_len - 1]);
2717
2718     /*
2719      * If the version in the decrypted pre-master secret is correct then
2720      * version_good will be 0xff, otherwise it'll be zero. The
2721      * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
2722      * (http://eprint.iacr.org/2003/052/) exploits the version number
2723      * check as a "bad version oracle". Thus version checks are done in
2724      * constant time and are treated like any other decryption error.
2725      */
2726     version_good =
2727         constant_time_eq_8(rsa_decrypt[padding_len],
2728                            (unsigned)(s->client_version >> 8));
2729     version_good &=
2730         constant_time_eq_8(rsa_decrypt[padding_len + 1],
2731                            (unsigned)(s->client_version & 0xff));
2732
2733     /*
2734      * The premaster secret must contain the same version number as the
2735      * ClientHello to detect version rollback attacks (strangely, the
2736      * protocol does not offer such protection for DH ciphersuites).
2737      * However, buggy clients exist that send the negotiated protocol
2738      * version instead if the server does not support the requested
2739      * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
2740      * clients.
2741      */
2742     if (s->options & SSL_OP_TLS_ROLLBACK_BUG) {
2743         unsigned char workaround_good;
2744         workaround_good = constant_time_eq_8(rsa_decrypt[padding_len],
2745                                              (unsigned)(s->version >> 8));
2746         workaround_good &=
2747             constant_time_eq_8(rsa_decrypt[padding_len + 1],
2748                                (unsigned)(s->version & 0xff));
2749         version_good |= workaround_good;
2750     }
2751
2752     /*
2753      * Both decryption and version must be good for decrypt_good to
2754      * remain non-zero (0xff).
2755      */
2756     decrypt_good &= version_good;
2757
2758     /*
2759      * Now copy rand_premaster_secret over from p using
2760      * decrypt_good_mask. If decryption failed, then p does not
2761      * contain valid plaintext, however, a check above guarantees
2762      * it is still sufficiently large to read from.
2763      */
2764     for (j = 0; j < sizeof(rand_premaster_secret); j++) {
2765         rsa_decrypt[padding_len + j] =
2766             constant_time_select_8(decrypt_good,
2767                                    rsa_decrypt[padding_len + j],
2768                                    rand_premaster_secret[j]);
2769     }
2770
2771     if (!ssl_generate_master_secret(s, rsa_decrypt + padding_len,
2772                                     sizeof(rand_premaster_secret), 0)) {
2773         *al = SSL_AD_INTERNAL_ERROR;
2774         SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, ERR_R_INTERNAL_ERROR);
2775         goto err;
2776     }
2777
2778     ret = 1;
2779  err:
2780     OPENSSL_free(rsa_decrypt);
2781     return ret;
2782 #else
2783     /* Should never happen */
2784     *al = SSL_AD_INTERNAL_ERROR;
2785     SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, ERR_R_INTERNAL_ERROR);
2786     return 0;
2787 #endif
2788 }
2789
2790 static int tls_process_cke_dhe(SSL *s, PACKET *pkt, int *al)
2791 {
2792 #ifndef OPENSSL_NO_DH
2793     EVP_PKEY *skey = NULL;
2794     DH *cdh;
2795     unsigned int i;
2796     BIGNUM *pub_key;
2797     const unsigned char *data;
2798     EVP_PKEY *ckey = NULL;
2799     int ret = 0;
2800
2801     if (!PACKET_get_net_2(pkt, &i) || PACKET_remaining(pkt) != i) {
2802         *al = SSL_AD_DECODE_ERROR;
2803         SSLerr(SSL_F_TLS_PROCESS_CKE_DHE,
2804                SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2805         goto err;
2806     }
2807     skey = s->s3->tmp.pkey;
2808     if (skey == NULL) {
2809         *al = SSL_AD_INTERNAL_ERROR;
2810         SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, SSL_R_MISSING_TMP_DH_KEY);
2811         goto err;
2812     }
2813
2814     if (PACKET_remaining(pkt) == 0L) {
2815         *al = SSL_AD_DECODE_ERROR;
2816         SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, SSL_R_MISSING_TMP_DH_KEY);
2817         goto err;
2818     }
2819     if (!PACKET_get_bytes(pkt, &data, i)) {
2820         /* We already checked we have enough data */
2821         *al = SSL_AD_INTERNAL_ERROR;
2822         SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, ERR_R_INTERNAL_ERROR);
2823         goto err;
2824     }
2825     ckey = EVP_PKEY_new();
2826     if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) == 0) {
2827         SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, SSL_R_BN_LIB);
2828         goto err;
2829     }
2830     cdh = EVP_PKEY_get0_DH(ckey);
2831     pub_key = BN_bin2bn(data, i, NULL);
2832
2833     if (pub_key == NULL || !DH_set0_key(cdh, pub_key, NULL)) {
2834         SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, ERR_R_INTERNAL_ERROR);
2835         if (pub_key != NULL)
2836             BN_free(pub_key);
2837         goto err;
2838     }
2839
2840     if (ssl_derive(s, skey, ckey, 1) == 0) {
2841         *al = SSL_AD_INTERNAL_ERROR;
2842         SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, ERR_R_INTERNAL_ERROR);
2843         goto err;
2844     }
2845
2846     ret = 1;
2847     EVP_PKEY_free(s->s3->tmp.pkey);
2848     s->s3->tmp.pkey = NULL;
2849  err:
2850     EVP_PKEY_free(ckey);
2851     return ret;
2852 #else
2853     /* Should never happen */
2854     *al = SSL_AD_INTERNAL_ERROR;
2855     SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, ERR_R_INTERNAL_ERROR);
2856     return 0;
2857 #endif
2858 }
2859
2860 static int tls_process_cke_ecdhe(SSL *s, PACKET *pkt, int *al)
2861 {
2862 #ifndef OPENSSL_NO_EC
2863     EVP_PKEY *skey = s->s3->tmp.pkey;
2864     EVP_PKEY *ckey = NULL;
2865     int ret = 0;
2866
2867     if (PACKET_remaining(pkt) == 0L) {
2868         /* We don't support ECDH client auth */
2869         *al = SSL_AD_HANDSHAKE_FAILURE;
2870         SSLerr(SSL_F_TLS_PROCESS_CKE_ECDHE, SSL_R_MISSING_TMP_ECDH_KEY);
2871         goto err;
2872     } else {
2873         unsigned int i;
2874         const unsigned char *data;
2875
2876         /*
2877          * Get client's public key from encoded point in the
2878          * ClientKeyExchange message.
2879          */
2880
2881         /* Get encoded point length */
2882         if (!PACKET_get_1(pkt, &i) || !PACKET_get_bytes(pkt, &data, i)
2883             || PACKET_remaining(pkt) != 0) {
2884             *al = SSL_AD_DECODE_ERROR;
2885             SSLerr(SSL_F_TLS_PROCESS_CKE_ECDHE, SSL_R_LENGTH_MISMATCH);
2886             goto err;
2887         }
2888         ckey = EVP_PKEY_new();
2889         if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) <= 0) {
2890             SSLerr(SSL_F_TLS_PROCESS_CKE_ECDHE, ERR_R_EVP_LIB);
2891             goto err;
2892         }
2893         if (EVP_PKEY_set1_tls_encodedpoint(ckey, data, i) == 0) {
2894             *al = SSL_AD_ILLEGAL_PARAMETER;
2895             SSLerr(SSL_F_TLS_PROCESS_CKE_ECDHE, ERR_R_EC_LIB);
2896             goto err;
2897         }
2898     }
2899
2900     if (ssl_derive(s, skey, ckey, 1) == 0) {
2901         *al = SSL_AD_INTERNAL_ERROR;
2902         SSLerr(SSL_F_TLS_PROCESS_CKE_ECDHE, ERR_R_INTERNAL_ERROR);
2903         goto err;
2904     }
2905
2906     ret = 1;
2907     EVP_PKEY_free(s->s3->tmp.pkey);
2908     s->s3->tmp.pkey = NULL;
2909  err:
2910     EVP_PKEY_free(ckey);
2911
2912     return ret;
2913 #else
2914     /* Should never happen */
2915     *al = SSL_AD_INTERNAL_ERROR;
2916     SSLerr(SSL_F_TLS_PROCESS_CKE_ECDHE, ERR_R_INTERNAL_ERROR);
2917     return 0;
2918 #endif
2919 }
2920
2921 static int tls_process_cke_srp(SSL *s, PACKET *pkt, int *al)
2922 {
2923 #ifndef OPENSSL_NO_SRP
2924     unsigned int i;
2925     const unsigned char *data;
2926
2927     if (!PACKET_get_net_2(pkt, &i)
2928         || !PACKET_get_bytes(pkt, &data, i)) {
2929         *al = SSL_AD_DECODE_ERROR;
2930         SSLerr(SSL_F_TLS_PROCESS_CKE_SRP, SSL_R_BAD_SRP_A_LENGTH);
2931         return 0;
2932     }
2933     if ((s->srp_ctx.A = BN_bin2bn(data, i, NULL)) == NULL) {
2934         *al = SSL_AD_INTERNAL_ERROR;
2935         SSLerr(SSL_F_TLS_PROCESS_CKE_SRP, ERR_R_BN_LIB);
2936         return 0;
2937     }
2938     if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0 || BN_is_zero(s->srp_ctx.A)) {
2939         *al = SSL_AD_ILLEGAL_PARAMETER;
2940         SSLerr(SSL_F_TLS_PROCESS_CKE_SRP, SSL_R_BAD_SRP_PARAMETERS);
2941         return 0;
2942     }
2943     OPENSSL_free(s->session->srp_username);
2944     s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);
2945     if (s->session->srp_username == NULL) {
2946         SSLerr(SSL_F_TLS_PROCESS_CKE_SRP, ERR_R_MALLOC_FAILURE);
2947         return 0;
2948     }
2949
2950     if (!srp_generate_server_master_secret(s)) {
2951         SSLerr(SSL_F_TLS_PROCESS_CKE_SRP, ERR_R_INTERNAL_ERROR);
2952         return 0;
2953     }
2954
2955     return 1;
2956 #else
2957     /* Should never happen */
2958     *al = SSL_AD_INTERNAL_ERROR;
2959     SSLerr(SSL_F_TLS_PROCESS_CKE_SRP, ERR_R_INTERNAL_ERROR);
2960     return 0;
2961 #endif
2962 }
2963
2964 static int tls_process_cke_gost(SSL *s, PACKET *pkt, int *al)
2965 {
2966 #ifndef OPENSSL_NO_GOST
2967     EVP_PKEY_CTX *pkey_ctx;
2968     EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2969     unsigned char premaster_secret[32];
2970     const unsigned char *start;
2971     size_t outlen = 32, inlen;
2972     unsigned long alg_a;
2973     int Ttag, Tclass;
2974     long Tlen;
2975     size_t sess_key_len;
2976     const unsigned char *data;
2977     int ret = 0;
2978
2979     /* Get our certificate private key */
2980     alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2981     if (alg_a & SSL_aGOST12) {
2982         /*
2983          * New GOST ciphersuites have SSL_aGOST01 bit too
2984          */
2985         pk = s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey;
2986         if (pk == NULL) {
2987             pk = s->cert->pkeys[SSL_PKEY_GOST12_256].privatekey;
2988         }
2989         if (pk == NULL) {
2990             pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2991         }
2992     } else if (alg_a & SSL_aGOST01) {
2993         pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2994     }
2995
2996     pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
2997     if (pkey_ctx == NULL) {
2998         *al = SSL_AD_INTERNAL_ERROR;
2999         SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, ERR_R_MALLOC_FAILURE);
3000         return 0;
3001     }
3002     if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {
3003         *al = SSL_AD_INTERNAL_ERROR;
3004         SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, ERR_R_INTERNAL_ERROR);
3005         return 0;
3006     }
3007     /*
3008      * If client certificate is present and is of the same type, maybe
3009      * use it for key exchange.  Don't mind errors from
3010      * EVP_PKEY_derive_set_peer, because it is completely valid to use a
3011      * client certificate for authorization only.
3012      */
3013     client_pub_pkey = X509_get0_pubkey(s->session->peer);
3014     if (client_pub_pkey) {
3015         if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
3016             ERR_clear_error();
3017     }
3018     /* Decrypt session key */
3019     sess_key_len = PACKET_remaining(pkt);
3020     if (!PACKET_get_bytes(pkt, &data, sess_key_len)) {
3021         *al = SSL_AD_INTERNAL_ERROR;
3022         SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, ERR_R_INTERNAL_ERROR);
3023         goto err;
3024     }
3025     /* TODO(size_t): Convert this function */
3026     if (ASN1_get_object((const unsigned char **)&data, &Tlen, &Ttag,
3027                         &Tclass, (long)sess_key_len) != V_ASN1_CONSTRUCTED
3028         || Ttag != V_ASN1_SEQUENCE || Tclass != V_ASN1_UNIVERSAL) {
3029         *al = SSL_AD_DECODE_ERROR;
3030         SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, SSL_R_DECRYPTION_FAILED);
3031         goto err;
3032     }
3033     start = data;
3034     inlen = Tlen;
3035     if (EVP_PKEY_decrypt
3036         (pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {
3037         *al = SSL_AD_DECODE_ERROR;
3038         SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, SSL_R_DECRYPTION_FAILED);
3039         goto err;
3040     }
3041     /* Generate master secret */
3042     if (!ssl_generate_master_secret(s, premaster_secret,
3043                                     sizeof(premaster_secret), 0)) {
3044         *al = SSL_AD_INTERNAL_ERROR;
3045         SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, ERR_R_INTERNAL_ERROR);
3046         goto err;
3047     }
3048     /* Check if pubkey from client certificate was used */
3049     if (EVP_PKEY_CTX_ctrl
3050         (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
3051         s->statem.no_cert_verify = 1;
3052
3053     ret = 1;
3054  err:
3055     EVP_PKEY_CTX_free(pkey_ctx);
3056     return ret;
3057 #else
3058     /* Should never happen */
3059     *al = SSL_AD_INTERNAL_ERROR;
3060     SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, ERR_R_INTERNAL_ERROR);
3061     return 0;
3062 #endif
3063 }
3064
3065 MSG_PROCESS_RETURN tls_process_client_key_exchange(SSL *s, PACKET *pkt)
3066 {
3067     int al = -1;
3068     unsigned long alg_k;
3069
3070     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
3071
3072     /* For PSK parse and retrieve identity, obtain PSK key */
3073     if ((alg_k & SSL_PSK) && !tls_process_cke_psk_preamble(s, pkt, &al))
3074         goto err;
3075
3076     if (alg_k & SSL_kPSK) {
3077         /* Identity extracted earlier: should be nothing left */
3078         if (PACKET_remaining(pkt) != 0) {
3079             al = SSL_AD_DECODE_ERROR;
3080             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
3081                    SSL_R_LENGTH_MISMATCH);
3082             goto err;
3083         }
3084         /* PSK handled by ssl_generate_master_secret */
3085         if (!ssl_generate_master_secret(s, NULL, 0, 0)) {
3086             al = SSL_AD_INTERNAL_ERROR;
3087             SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
3088             goto err;
3089         }
3090     } else if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
3091         if (!tls_process_cke_rsa(s, pkt, &al))
3092             goto err;
3093     } else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
3094         if (!tls_process_cke_dhe(s, pkt, &al))
3095             goto err;
3096     } else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
3097         if (!tls_process_cke_ecdhe(s, pkt, &al))
3098             goto err;
3099     } else if (alg_k & SSL_kSRP) {
3100         if (!tls_process_cke_srp(s, pkt, &al))
3101             goto err;
3102     } else if (alg_k & SSL_kGOST) {
3103         if (!tls_process_cke_gost(s, pkt, &al))
3104             goto err;
3105     } else {
3106         al = SSL_AD_INTERNAL_ERROR;
3107         SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
3108                SSL_R_UNKNOWN_CIPHER_TYPE);
3109         goto err;
3110     }
3111
3112     return MSG_PROCESS_CONTINUE_PROCESSING;
3113  err:
3114     if (al != -1)
3115         ssl3_send_alert(s, SSL3_AL_FATAL, al);
3116 #ifndef OPENSSL_NO_PSK
3117     OPENSSL_clear_free(s->s3->tmp.psk, s->s3->tmp.psklen);
3118     s->s3->tmp.psk = NULL;
3119 #endif
3120     ossl_statem_set_error(s);
3121     return MSG_PROCESS_ERROR;
3122 }
3123
3124 WORK_STATE tls_post_process_client_key_exchange(SSL *s, WORK_STATE wst)
3125 {
3126 #ifndef OPENSSL_NO_SCTP
3127     if (wst == WORK_MORE_A) {
3128         if (SSL_IS_DTLS(s)) {
3129             unsigned char sctpauthkey[64];
3130             char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
3131             /*
3132              * Add new shared key for SCTP-Auth, will be ignored if no SCTP
3133              * used.
3134              */
3135             memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
3136                    sizeof(DTLS1_SCTP_AUTH_LABEL));
3137
3138             if (SSL_export_keying_material(s, sctpauthkey,
3139                                            sizeof(sctpauthkey), labelbuffer,
3140                                            sizeof(labelbuffer), NULL, 0,
3141                                            0) <= 0) {
3142                 ossl_statem_set_error(s);
3143                 return WORK_ERROR;
3144             }
3145
3146             BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
3147                      sizeof(sctpauthkey), sctpauthkey);
3148         }
3149     }
3150 #endif
3151
3152     if (s->statem.no_cert_verify || !s->session->peer) {
3153         /*
3154          * No certificate verify or no peer certificate so we no longer need
3155          * the handshake_buffer
3156          */
3157         if (!ssl3_digest_cached_records(s, 0)) {
3158             ossl_statem_set_error(s);
3159             return WORK_ERROR;
3160         }
3161         return WORK_FINISHED_CONTINUE;
3162     } else {
3163         if (!s->s3->handshake_buffer) {
3164             SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_KEY_EXCHANGE,
3165                    ERR_R_INTERNAL_ERROR);
3166             ossl_statem_set_error(s);
3167             return WORK_ERROR;
3168         }
3169         /*
3170          * For sigalgs freeze the handshake buffer. If we support
3171          * extms we've done this already so this is a no-op
3172          */
3173         if (!ssl3_digest_cached_records(s, 1)) {
3174             ossl_statem_set_error(s);
3175             return WORK_ERROR;
3176         }
3177     }
3178
3179     return WORK_FINISHED_CONTINUE;
3180 }
3181
3182 MSG_PROCESS_RETURN tls_process_client_certificate(SSL *s, PACKET *pkt)
3183 {
3184     int i, al = SSL_AD_INTERNAL_ERROR, ret = MSG_PROCESS_ERROR;
3185     X509 *x = NULL;
3186     unsigned long l, llen;
3187     const unsigned char *certstart, *certbytes;
3188     STACK_OF(X509) *sk = NULL;
3189     PACKET spkt, context;
3190     size_t chainidx;
3191
3192     if ((sk = sk_X509_new_null()) == NULL) {
3193         SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3194         goto f_err;
3195     }
3196
3197     /* TODO(TLS1.3): For now we ignore the context. We need to verify this */
3198     if ((SSL_IS_TLS13(s) && !PACKET_get_length_prefixed_1(pkt, &context))
3199             || !PACKET_get_net_3(pkt, &llen)
3200             || !PACKET_get_sub_packet(pkt, &spkt, llen)
3201             || PACKET_remaining(pkt) != 0) {
3202         al = SSL_AD_DECODE_ERROR;
3203         SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
3204         goto f_err;
3205     }
3206
3207     for (chainidx = 0; PACKET_remaining(&spkt) > 0; chainidx++) {
3208         if (!PACKET_get_net_3(&spkt, &l)
3209             || !PACKET_get_bytes(&spkt, &certbytes, l)) {
3210             al = SSL_AD_DECODE_ERROR;
3211             SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3212                    SSL_R_CERT_LENGTH_MISMATCH);
3213             goto f_err;
3214         }
3215
3216         certstart = certbytes;
3217         x = d2i_X509(NULL, (const unsigned char **)&certbytes, l);
3218         if (x == NULL) {
3219             SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_ASN1_LIB);
3220             goto f_err;
3221         }
3222         if (certbytes != (certstart + l)) {
3223             al = SSL_AD_DECODE_ERROR;
3224             SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3225                    SSL_R_CERT_LENGTH_MISMATCH);
3226             goto f_err;
3227         }
3228
3229         if (SSL_IS_TLS13(s)) {
3230             RAW_EXTENSION *rawexts = NULL;
3231             PACKET extensions;
3232
3233             if (!PACKET_get_length_prefixed_2(&spkt, &extensions)) {
3234                 al = SSL_AD_DECODE_ERROR;
3235                 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, SSL_R_BAD_LENGTH);
3236                 goto f_err;
3237             }
3238             if (!tls_collect_extensions(s, &extensions,
3239                                         SSL_EXT_TLS1_3_CERTIFICATE, &rawexts,
3240                                         &al, NULL, chainidx == 0)
3241                 || !tls_parse_all_extensions(s, SSL_EXT_TLS1_3_CERTIFICATE,
3242                                              rawexts, x, chainidx, &al,
3243                                              PACKET_remaining(&spkt) == 0)) {
3244                 OPENSSL_free(rawexts);
3245                 goto f_err;
3246             }
3247             OPENSSL_free(rawexts);
3248         }
3249
3250         if (!sk_X509_push(sk, x)) {
3251             SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3252             goto f_err;
3253         }
3254         x = NULL;
3255     }
3256
3257     if (sk_X509_num(sk) <= 0) {
3258         /* TLS does not mind 0 certs returned */
3259         if (s->version == SSL3_VERSION) {
3260             al = SSL_AD_HANDSHAKE_FAILURE;
3261             SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3262                    SSL_R_NO_CERTIFICATES_RETURNED);
3263             goto f_err;
3264         }
3265         /* Fail for TLS only if we required a certificate */
3266         else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3267                  (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3268             SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3269                    SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3270             al = SSL_AD_CERTIFICATE_REQUIRED;
3271             goto f_err;
3272         }
3273         /* No client certificate so digest cached records */
3274         if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s, 0)) {
3275             goto f_err;
3276         }
3277     } else {
3278         EVP_PKEY *pkey;
3279         i = ssl_verify_cert_chain(s, sk);
3280         if (i <= 0) {
3281             al = ssl_verify_alarm_type(s->verify_result);
3282             SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3283                    SSL_R_CERTIFICATE_VERIFY_FAILED);
3284             goto f_err;
3285         }
3286         if (i > 1) {
3287             SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, i);
3288             al = SSL_AD_HANDSHAKE_FAILURE;
3289             goto f_err;
3290         }
3291         pkey = X509_get0_pubkey(sk_X509_value(sk, 0));
3292         if (pkey == NULL) {
3293             al = SSL3_AD_HANDSHAKE_FAILURE;
3294             SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3295                    SSL_R_UNKNOWN_CERTIFICATE_TYPE);
3296             goto f_err;
3297         }
3298     }
3299
3300     X509_free(s->session->peer);
3301     s->session->peer = sk_X509_shift(sk);
3302     s->session->verify_result = s->verify_result;
3303
3304     sk_X509_pop_free(s->session->peer_chain, X509_free);
3305     s->session->peer_chain = sk;
3306
3307     /*
3308      * Freeze the handshake buffer. For <TLS1.3 we do this after the CKE
3309      * message
3310      */
3311     if (SSL_IS_TLS13(s) && !ssl3_digest_cached_records(s, 1)) {
3312         al = SSL_AD_INTERNAL_ERROR;
3313         SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3314         goto f_err;
3315     }
3316
3317     /*
3318      * Inconsistency alert: cert_chain does *not* include the peer's own
3319      * certificate, while we do include it in statem_clnt.c
3320      */
3321     sk = NULL;
3322
3323     /* Save the current hash state for when we receive the CertificateVerify */
3324     if (SSL_IS_TLS13(s)
3325             && !ssl_handshake_hash(s, s->cert_verify_hash,
3326                                    sizeof(s->cert_verify_hash),
3327                                    &s->cert_verify_hash_len)) {
3328         al = SSL_AD_INTERNAL_ERROR;
3329         SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3330         goto f_err;
3331     }
3332
3333     ret = MSG_PROCESS_CONTINUE_READING;
3334     goto done;
3335
3336  f_err:
3337     ssl3_send_alert(s, SSL3_AL_FATAL, al);
3338     ossl_statem_set_error(s);
3339  done:
3340     X509_free(x);
3341     sk_X509_pop_free(sk, X509_free);
3342     return ret;
3343 }
3344
3345 int tls_construct_server_certificate(SSL *s, WPACKET *pkt)
3346 {
3347     CERT_PKEY *cpk = s->s3->tmp.cert;
3348     int al = SSL_AD_INTERNAL_ERROR;
3349
3350     if (cpk == NULL) {
3351         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3352         return 0;
3353     }
3354
3355     /*
3356      * In TLSv1.3 the certificate chain is always preceded by a 0 length context
3357      * for the server Certificate message
3358      */
3359     if ((SSL_IS_TLS13(s) && !WPACKET_put_bytes_u8(pkt, 0))
3360             || !ssl3_output_cert_chain(s, pkt, cpk, &al)) {
3361         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3362         ssl3_send_alert(s, SSL3_AL_FATAL, al);
3363         return 0;
3364     }
3365
3366     return 1;
3367 }
3368
3369 int tls_construct_new_session_ticket(SSL *s, WPACKET *pkt)
3370 {
3371     unsigned char *senc = NULL;
3372     EVP_CIPHER_CTX *ctx = NULL;
3373     HMAC_CTX *hctx = NULL;
3374     unsigned char *p, *encdata1, *encdata2, *macdata1, *macdata2;
3375     const unsigned char *const_p;
3376     int len, slen_full, slen, lenfinal;
3377     SSL_SESSION *sess;
3378     unsigned int hlen;
3379     SSL_CTX *tctx = s->session_ctx;
3380     unsigned char iv[EVP_MAX_IV_LENGTH];
3381     unsigned char key_name[TLSEXT_KEYNAME_LENGTH];
3382     int iv_len, al = SSL_AD_INTERNAL_ERROR;
3383     size_t macoffset, macendoffset;
3384     union {
3385         unsigned char age_add_c[sizeof(uint32_t)];
3386         uint32_t age_add;
3387     } age_add_u;
3388
3389     if (SSL_IS_TLS13(s)) {
3390         if (RAND_bytes(age_add_u.age_add_c, sizeof(age_add_u)) <= 0)
3391             goto err;
3392         s->session->ext.tick_age_add = age_add_u.age_add;
3393         s->session->time = (long)time(NULL);
3394         if (s->s3->alpn_selected != NULL) {
3395             OPENSSL_free(s->session->ext.alpn_selected);
3396             s->session->ext.alpn_selected =
3397                 OPENSSL_memdup(s->s3->alpn_selected, s->s3->alpn_selected_len);
3398             if (s->session->ext.alpn_selected == NULL) {
3399                 SSLerr(SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET,
3400                        ERR_R_MALLOC_FAILURE);
3401                 goto err;
3402             }
3403             s->session->ext.alpn_selected_len = s->s3->alpn_selected_len;
3404         }
3405         s->session->ext.max_early_data = s->max_early_data;
3406     }
3407
3408     /* get session encoding length */
3409     slen_full = i2d_SSL_SESSION(s->session, NULL);
3410     /*
3411      * Some length values are 16 bits, so forget it if session is too
3412      * long
3413      */
3414     if (slen_full == 0 || slen_full > 0xFF00) {
3415         SSLerr(SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_INTERNAL_ERROR);
3416         goto err;
3417     }
3418     senc = OPENSSL_malloc(slen_full);
3419     if (senc == NULL) {
3420         SSLerr(SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
3421         goto err;
3422     }
3423
3424     ctx = EVP_CIPHER_CTX_new();
3425     hctx = HMAC_CTX_new();
3426     if (ctx == NULL || hctx == NULL) {
3427         SSLerr(SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
3428         goto err;
3429     }
3430
3431     p = senc;
3432     if (!i2d_SSL_SESSION(s->session, &p))
3433         goto err;
3434
3435     /*
3436      * create a fresh copy (not shared with other threads) to clean up
3437      */
3438     const_p = senc;
3439     sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3440     if (sess == NULL)
3441         goto err;
3442     sess->session_id_length = 0; /* ID is irrelevant for the ticket */
3443
3444     slen = i2d_SSL_SESSION(sess, NULL);
3445     if (slen == 0 || slen > slen_full) { /* shouldn't ever happen */
3446         SSL_SESSION_free(sess);
3447         goto err;
3448     }
3449     p = senc;
3450     if (!i2d_SSL_SESSION(sess, &p)) {
3451         SSL_SESSION_free(sess);
3452         goto err;
3453     }
3454     SSL_SESSION_free(sess);
3455
3456     /*
3457      * Initialize HMAC and cipher contexts. If callback present it does
3458      * all the work otherwise use generated values from parent ctx.
3459      */
3460     if (tctx->ext.ticket_key_cb) {
3461         /* if 0 is returned, write an empty ticket */
3462         int ret = tctx->ext.ticket_key_cb(s, key_name, iv, ctx,
3463                                              hctx, 1);
3464
3465         if (ret == 0) {
3466
3467             /* Put timeout and length */
3468             if (!WPACKET_put_bytes_u32(pkt, 0)
3469                     || !WPACKET_put_bytes_u16(pkt, 0)) {
3470                 SSLerr(SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET,
3471                        ERR_R_INTERNAL_ERROR);
3472                 goto err;
3473             }
3474             OPENSSL_free(senc);
3475             EVP_CIPHER_CTX_free(ctx);
3476             HMAC_CTX_free(hctx);
3477             return 1;
3478         }
3479         if (ret < 0)
3480             goto err;
3481         iv_len = EVP_CIPHER_CTX_iv_length(ctx);
3482     } else {
3483         const EVP_CIPHER *cipher = EVP_aes_256_cbc();
3484
3485         iv_len = EVP_CIPHER_iv_length(cipher);
3486         if (RAND_bytes(iv, iv_len) <= 0)
3487             goto err;
3488         if (!EVP_EncryptInit_ex(ctx, cipher, NULL,
3489                                 tctx->ext.tick_aes_key, iv))
3490             goto err;
3491         if (!HMAC_Init_ex(hctx, tctx->ext.tick_hmac_key,
3492                           sizeof(tctx->ext.tick_hmac_key),
3493                           EVP_sha256(), NULL))
3494             goto err;
3495         memcpy(key_name, tctx->ext.tick_key_name,
3496                sizeof(tctx->ext.tick_key_name));
3497     }
3498
3499     /*
3500      * Ticket lifetime hint: For TLSv1.2 this is advisory only and we leave this
3501      * unspecified for resumed session (for simplicity).
3502      * In TLSv1.3 we reset the "time" field above, and always specify the
3503      * timeout.
3504      */
3505     if (!WPACKET_put_bytes_u32(pkt,
3506                                (s->hit && !SSL_IS_TLS13(s))
3507                                ? 0 : s->session->timeout)
3508             || (SSL_IS_TLS13(s)
3509                 && !WPACKET_put_bytes_u32(pkt, age_add_u.age_add))
3510                /* Now the actual ticket data */
3511             || !WPACKET_start_sub_packet_u16(pkt)
3512             || !WPACKET_get_total_written(pkt, &macoffset)
3513                /* Output key name */
3514             || !WPACKET_memcpy(pkt, key_name, sizeof(key_name))
3515                /* output IV */
3516             || !WPACKET_memcpy(pkt, iv, iv_len)
3517             || !WPACKET_reserve_bytes(pkt, slen + EVP_MAX_BLOCK_LENGTH,
3518                                       &encdata1)
3519                /* Encrypt session data */
3520             || !EVP_EncryptUpdate(ctx, encdata1, &len, senc, slen)
3521             || !WPACKET_allocate_bytes(pkt, len, &encdata2)
3522             || encdata1 != encdata2
3523             || !EVP_EncryptFinal(ctx, encdata1 + len, &lenfinal)
3524             || !WPACKET_allocate_bytes(pkt, lenfinal, &encdata2)
3525             || encdata1 + len != encdata2
3526             || len + lenfinal > slen + EVP_MAX_BLOCK_LENGTH
3527             || !WPACKET_get_total_written(pkt, &macendoffset)
3528             || !HMAC_Update(hctx,
3529                             (unsigned char *)s->init_buf->data + macoffset,
3530                             macendoffset - macoffset)
3531             || !WPACKET_reserve_bytes(pkt, EVP_MAX_MD_SIZE, &macdata1)
3532             || !HMAC_Final(hctx, macdata1, &hlen)
3533             || hlen > EVP_MAX_MD_SIZE
3534             || !WPACKET_allocate_bytes(pkt, hlen, &macdata2)
3535             || macdata1 != macdata2
3536             || !WPACKET_close(pkt)
3537             || (SSL_IS_TLS13(s)
3538                 && !tls_construct_extensions(s, pkt,
3539                                              SSL_EXT_TLS1_3_NEW_SESSION_TICKET,
3540                                              NULL, 0, &al))) {
3541         SSLerr(SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_INTERNAL_ERROR);
3542         goto err;
3543     }
3544     EVP_CIPHER_CTX_free(ctx);
3545     HMAC_CTX_free(hctx);
3546     OPENSSL_free(senc);
3547
3548     return 1;
3549  err:
3550     ossl_statem_set_error(s);
3551     OPENSSL_free(senc);
3552     EVP_CIPHER_CTX_free(ctx);
3553     HMAC_CTX_free(hctx);
3554     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
3555     return 0;
3556 }
3557
3558 /*
3559  * In TLSv1.3 this is called from the extensions code, otherwise it is used to
3560  * create a separate message. Returns 1 on success or 0 on failure.
3561  */
3562 int tls_construct_cert_status_body(SSL *s, WPACKET *pkt)
3563 {
3564     if (!WPACKET_put_bytes_u8(pkt, s->ext.status_type)
3565             || !WPACKET_sub_memcpy_u24(pkt, s->ext.ocsp.resp,
3566                                        s->ext.ocsp.resp_len)) {
3567         SSLerr(SSL_F_TLS_CONSTRUCT_CERT_STATUS_BODY, ERR_R_INTERNAL_ERROR);
3568         return 0;
3569     }
3570
3571     return 1;
3572 }
3573
3574 int tls_construct_cert_status(SSL *s, WPACKET *pkt)
3575 {
3576     if (!tls_construct_cert_status_body(s, pkt)) {
3577         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
3578         return 0;
3579     }
3580
3581     return 1;
3582 }
3583
3584 #ifndef OPENSSL_NO_NEXTPROTONEG
3585 /*
3586  * tls_process_next_proto reads a Next Protocol Negotiation handshake message.
3587  * It sets the next_proto member in s if found
3588  */
3589 MSG_PROCESS_RETURN tls_process_next_proto(SSL *s, PACKET *pkt)
3590 {
3591     PACKET next_proto, padding;
3592     size_t next_proto_len;
3593     int al = SSL_AD_INTERNAL_ERROR;
3594
3595     /*-
3596      * The payload looks like:
3597      *   uint8 proto_len;
3598      *   uint8 proto[proto_len];
3599      *   uint8 padding_len;
3600      *   uint8 padding[padding_len];
3601      */
3602     if (!PACKET_get_length_prefixed_1(pkt, &next_proto)
3603         || !PACKET_get_length_prefixed_1(pkt, &padding)
3604         || PACKET_remaining(pkt) > 0) {
3605         al = SSL_AD_DECODE_ERROR;
3606         SSLerr(SSL_F_TLS_PROCESS_NEXT_PROTO, SSL_R_LENGTH_MISMATCH);
3607         goto err;
3608     }
3609
3610     if (!PACKET_memdup(&next_proto, &s->ext.npn, &next_proto_len)) {
3611         s->ext.npn_len = 0;
3612         goto err;
3613     }
3614
3615     s->ext.npn_len = (unsigned char)next_proto_len;
3616
3617     return MSG_PROCESS_CONTINUE_READING;
3618  err:
3619     ssl3_send_alert(s, SSL3_AL_FATAL, al);
3620     ossl_statem_set_error(s);
3621     return MSG_PROCESS_ERROR;
3622 }
3623 #endif
3624
3625 static int tls_construct_encrypted_extensions(SSL *s, WPACKET *pkt)
3626 {
3627     int al;
3628
3629     if (!tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
3630                                   NULL, 0, &al)) {
3631         ssl3_send_alert(s, SSL3_AL_FATAL, al);
3632         SSLerr(SSL_F_TLS_CONSTRUCT_ENCRYPTED_EXTENSIONS, ERR_R_INTERNAL_ERROR);
3633         return 0;
3634     }
3635
3636     return 1;
3637 }
3638
3639 static int tls_construct_hello_retry_request(SSL *s, WPACKET *pkt)
3640 {
3641     int al = SSL_AD_INTERNAL_ERROR;
3642     size_t len = 0;
3643
3644     /*
3645      * TODO(TLS1.3): Remove the DRAFT version before release
3646      * (should be s->version)
3647      */
3648     if (!WPACKET_put_bytes_u16(pkt, TLS1_3_VERSION_DRAFT)
3649             || !s->method->put_cipher_by_char(s->s3->tmp.new_cipher, pkt, &len)
3650             || !tls_construct_extensions(s, pkt,
3651                                          SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST,
3652                                          NULL, 0, &al)) {
3653         SSLerr(SSL_F_TLS_CONSTRUCT_HELLO_RETRY_REQUEST, ERR_R_INTERNAL_ERROR);
3654         goto err;
3655     }
3656
3657     /* Ditch the session. We'll create a new one next time around */
3658     SSL_SESSION_free(s->session);
3659     s->session = NULL;
3660     s->hit = 0;
3661
3662     /*
3663      * Re-initialise the Transcript Hash. We're going to prepopulate it with
3664      * a synthetic message_hash in place of ClientHello1.
3665      */
3666     if (!create_synthetic_message_hash(s))
3667         goto err;
3668
3669     return 1;
3670  err:
3671     ssl3_send_alert(s, SSL3_AL_FATAL, al);
3672     return 0;
3673 }
3674
3675 MSG_PROCESS_RETURN tls_process_end_of_early_data(SSL *s, PACKET *pkt)
3676 {
3677     int al = SSL_AD_INTERNAL_ERROR;
3678
3679     if (PACKET_remaining(pkt) != 0) {
3680         al = SSL_AD_DECODE_ERROR;
3681         SSLerr(SSL_F_TLS_PROCESS_END_OF_EARLY_DATA, SSL_R_LENGTH_MISMATCH);
3682         ossl_statem_set_error(s);
3683         return MSG_PROCESS_ERROR;
3684     }
3685
3686     if (s->early_data_state != SSL_EARLY_DATA_READING
3687             && s->early_data_state != SSL_EARLY_DATA_READ_RETRY) {
3688         SSLerr(SSL_F_TLS_PROCESS_END_OF_EARLY_DATA, ERR_R_INTERNAL_ERROR);
3689         goto err;
3690     }
3691
3692     /*
3693      * EndOfEarlyData signals a key change so the end of the message must be on
3694      * a record boundary.
3695      */
3696     if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
3697         al = SSL_AD_UNEXPECTED_MESSAGE;
3698         SSLerr(SSL_F_TLS_PROCESS_END_OF_EARLY_DATA,
3699                SSL_R_NOT_ON_RECORD_BOUNDARY);
3700         goto err;
3701     }
3702
3703     s->early_data_state = SSL_EARLY_DATA_FINISHED_READING;
3704     if (!s->method->ssl3_enc->change_cipher_state(s,
3705                 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_READ)) {
3706         SSLerr(SSL_F_TLS_PROCESS_END_OF_EARLY_DATA, ERR_R_INTERNAL_ERROR);
3707         goto err;
3708     }
3709
3710     return MSG_PROCESS_CONTINUE_READING;
3711  err:
3712     ssl3_send_alert(s, SSL3_AL_FATAL, al);
3713     ossl_statem_set_error(s);
3714     return MSG_PROCESS_ERROR;
3715 }