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