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