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