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