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