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