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