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