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.
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
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>
26 static int tls_construct_encrypted_extensions(SSL *s, WPACKET *pkt);
27 static int tls_construct_hello_retry_request(SSL *s, WPACKET *pkt);
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|.
35 * Return values are 1 for success (transition allowed) and 0 on error
36 * (transition not allowed)
38 static int ossl_statem_server13_read_transition(SSL *s, int mt)
40 OSSL_STATEM *st = &s->statem;
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()
47 switch (st->hand_state) {
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;
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;
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;
75 if (mt == SSL3_MT_FINISHED) {
76 st->hand_state = TLS_ST_SR_FINISHED;
83 if (s->session->peer == NULL) {
84 if (mt == SSL3_MT_FINISHED) {
85 st->hand_state = TLS_ST_SR_FINISHED;
89 if (mt == SSL3_MT_CERTIFICATE_VERIFY) {
90 st->hand_state = TLS_ST_SR_CERT_VRFY;
96 case TLS_ST_SR_CERT_VRFY:
97 if (mt == SSL3_MT_FINISHED) {
98 st->hand_state = TLS_ST_SR_FINISHED;
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)
108 if (s->early_data_state == SSL_EARLY_DATA_READING)
110 if (mt == SSL3_MT_KEY_UPDATE) {
111 st->hand_state = TLS_ST_SR_KEY_UPDATE;
117 /* No valid transition found */
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|.
127 * Return values are 1 for success (transition allowed) and 0 on error
128 * (transition not allowed)
130 int ossl_statem_server_read_transition(SSL *s, int mt)
132 OSSL_STATEM *st = &s->statem;
134 if (SSL_IS_TLS13(s)) {
135 if (!ossl_statem_server13_read_transition(s, mt))
140 switch (st->hand_state) {
146 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
147 if (mt == SSL3_MT_CLIENT_HELLO) {
148 st->hand_state = TLS_ST_SR_CLNT_HELLO;
153 case TLS_ST_SW_SRVR_DONE:
155 * If we get a CKE message after a ServerDone then either
156 * 1) We didn't request a Certificate
158 * 2) If we did request one then
159 * a) We allow no Certificate to be returned
161 * b) We are running SSL3 (in TLS1.0+ the client must return a 0
162 * list if we requested a certificate)
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)) {
170 * This isn't an unexpected message as such - we're just
171 * not going to accept it because we require a client
174 ssl3_send_alert(s, SSL3_AL_FATAL,
175 SSL3_AD_HANDSHAKE_FAILURE);
176 SSLerr(SSL_F_OSSL_STATEM_SERVER_READ_TRANSITION,
177 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
180 st->hand_state = TLS_ST_SR_KEY_EXCH;
184 st->hand_state = TLS_ST_SR_KEY_EXCH;
187 } else if (s->s3->tmp.cert_request) {
188 if (mt == SSL3_MT_CERTIFICATE) {
189 st->hand_state = TLS_ST_SR_CERT;
196 if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) {
197 st->hand_state = TLS_ST_SR_KEY_EXCH;
202 case TLS_ST_SR_KEY_EXCH:
204 * We should only process a CertificateVerify message if we have
205 * received a Certificate from the client. If so then |s->session->peer|
206 * will be non NULL. In some instances a CertificateVerify message is
207 * not required even if the peer has sent a Certificate (e.g. such as in
208 * the case of static DH). In that case |st->no_cert_verify| should be
211 if (s->session->peer == NULL || st->no_cert_verify) {
212 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
214 * For the ECDH ciphersuites when the client sends its ECDH
215 * pub key in a certificate, the CertificateVerify message is
216 * not sent. Also for GOST ciphersuites when the client uses
217 * its key from the certificate for key exchange.
219 st->hand_state = TLS_ST_SR_CHANGE;
223 if (mt == SSL3_MT_CERTIFICATE_VERIFY) {
224 st->hand_state = TLS_ST_SR_CERT_VRFY;
230 case TLS_ST_SR_CERT_VRFY:
231 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
232 st->hand_state = TLS_ST_SR_CHANGE;
237 case TLS_ST_SR_CHANGE:
238 #ifndef OPENSSL_NO_NEXTPROTONEG
239 if (s->s3->npn_seen) {
240 if (mt == SSL3_MT_NEXT_PROTO) {
241 st->hand_state = TLS_ST_SR_NEXT_PROTO;
246 if (mt == SSL3_MT_FINISHED) {
247 st->hand_state = TLS_ST_SR_FINISHED;
250 #ifndef OPENSSL_NO_NEXTPROTONEG
255 #ifndef OPENSSL_NO_NEXTPROTONEG
256 case TLS_ST_SR_NEXT_PROTO:
257 if (mt == SSL3_MT_FINISHED) {
258 st->hand_state = TLS_ST_SR_FINISHED;
264 case TLS_ST_SW_FINISHED:
265 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
266 st->hand_state = TLS_ST_SR_CHANGE;
273 /* No valid transition found */
274 SSLfatal(s, SSL3_AD_UNEXPECTED_MESSAGE,
275 SSL_F_OSSL_STATEM_SERVER_READ_TRANSITION,
276 SSL_R_UNEXPECTED_MESSAGE);
281 * Should we send a ServerKeyExchange message?
283 * Valid return values are:
287 static int send_server_key_exchange(SSL *s)
289 unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
292 * only send a ServerKeyExchange if DH or fortezza but we have a
293 * sign only certificate PSK: may send PSK identity hints For
294 * ECC ciphersuites, we send a serverKeyExchange message only if
295 * the cipher suite is either ECDH-anon or ECDHE. In other cases,
296 * the server certificate contains the server's public key for
299 if (alg_k & (SSL_kDHE | SSL_kECDHE)
301 * PSK: send ServerKeyExchange if PSK identity hint if
304 #ifndef OPENSSL_NO_PSK
305 /* Only send SKE if we have identity hint for plain PSK */
306 || ((alg_k & (SSL_kPSK | SSL_kRSAPSK))
307 && s->cert->psk_identity_hint)
308 /* For other PSK always send SKE */
309 || (alg_k & (SSL_PSK & (SSL_kDHEPSK | SSL_kECDHEPSK)))
311 #ifndef OPENSSL_NO_SRP
312 /* SRP: send ServerKeyExchange */
313 || (alg_k & SSL_kSRP)
323 * Should we send a CertificateRequest message?
325 * Valid return values are:
329 static int send_certificate_request(SSL *s)
332 /* don't request cert unless asked for it: */
333 s->verify_mode & SSL_VERIFY_PEER
335 * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert
336 * during re-negotiation:
338 && (s->s3->tmp.finish_md_len == 0 ||
339 !(s->verify_mode & SSL_VERIFY_CLIENT_ONCE))
341 * never request cert in anonymous ciphersuites (see
342 * section "Certificate request" in SSL 3 drafts and in
345 && (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
347 * ... except when the application insists on
348 * verification (against the specs, but statem_clnt.c accepts
351 || (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
352 /* don't request certificate for SRP auth */
353 && !(s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)
355 * With normal PSK Certificates and Certificate Requests
358 && !(s->s3->tmp.new_cipher->algorithm_auth & SSL_aPSK)) {
366 * ossl_statem_server13_write_transition() works out what handshake state to
367 * move to next when a TLSv1.3 server is writing messages to be sent to the
370 static WRITE_TRAN ossl_statem_server13_write_transition(SSL *s)
372 OSSL_STATEM *st = &s->statem;
375 * No case for TLS_ST_BEFORE, because at that stage we have not negotiated
376 * TLSv1.3 yet, so that is handled by ossl_statem_server_write_transition()
379 switch (st->hand_state) {
381 /* Shouldn't happen */
382 return WRITE_TRAN_ERROR;
385 if (s->key_update != SSL_KEY_UPDATE_NONE) {
386 st->hand_state = TLS_ST_SW_KEY_UPDATE;
387 return WRITE_TRAN_CONTINUE;
389 /* Try to read from the client instead */
390 return WRITE_TRAN_FINISHED;
392 case TLS_ST_SR_CLNT_HELLO:
393 if (s->hello_retry_request)
394 st->hand_state = TLS_ST_SW_HELLO_RETRY_REQUEST;
396 st->hand_state = TLS_ST_SW_SRVR_HELLO;
397 return WRITE_TRAN_CONTINUE;
399 case TLS_ST_SW_HELLO_RETRY_REQUEST:
400 st->hand_state = TLS_ST_EARLY_DATA;
401 return WRITE_TRAN_CONTINUE;
403 case TLS_ST_SW_SRVR_HELLO:
404 st->hand_state = TLS_ST_SW_ENCRYPTED_EXTENSIONS;
405 return WRITE_TRAN_CONTINUE;
407 case TLS_ST_SW_ENCRYPTED_EXTENSIONS:
409 st->hand_state = TLS_ST_SW_FINISHED;
410 else if (send_certificate_request(s))
411 st->hand_state = TLS_ST_SW_CERT_REQ;
413 st->hand_state = TLS_ST_SW_CERT;
415 return WRITE_TRAN_CONTINUE;
417 case TLS_ST_SW_CERT_REQ:
418 st->hand_state = TLS_ST_SW_CERT;
419 return WRITE_TRAN_CONTINUE;
422 st->hand_state = TLS_ST_SW_CERT_VRFY;
423 return WRITE_TRAN_CONTINUE;
425 case TLS_ST_SW_CERT_VRFY:
426 st->hand_state = TLS_ST_SW_FINISHED;
427 return WRITE_TRAN_CONTINUE;
429 case TLS_ST_SW_FINISHED:
430 st->hand_state = TLS_ST_EARLY_DATA;
431 return WRITE_TRAN_CONTINUE;
433 case TLS_ST_EARLY_DATA:
434 return WRITE_TRAN_FINISHED;
436 case TLS_ST_SR_FINISHED:
438 * Technically we have finished the handshake at this point, but we're
439 * going to remain "in_init" for now and write out the session ticket
441 * TODO(TLS1.3): Perhaps we need to be able to control this behaviour
442 * and give the application the opportunity to delay sending the
445 st->hand_state = TLS_ST_SW_SESSION_TICKET;
446 return WRITE_TRAN_CONTINUE;
448 case TLS_ST_SR_KEY_UPDATE:
449 if (s->key_update != SSL_KEY_UPDATE_NONE) {
450 st->hand_state = TLS_ST_SW_KEY_UPDATE;
451 return WRITE_TRAN_CONTINUE;
455 case TLS_ST_SW_KEY_UPDATE:
456 case TLS_ST_SW_SESSION_TICKET:
457 st->hand_state = TLS_ST_OK;
458 return WRITE_TRAN_CONTINUE;
463 * ossl_statem_server_write_transition() works out what handshake state to move
464 * to next when the server is writing messages to be sent to the client.
466 WRITE_TRAN ossl_statem_server_write_transition(SSL *s)
468 OSSL_STATEM *st = &s->statem;
471 * Note that before the ClientHello we don't know what version we are going
472 * to negotiate yet, so we don't take this branch until later
476 return ossl_statem_server13_write_transition(s);
478 switch (st->hand_state) {
480 /* Shouldn't happen */
481 return WRITE_TRAN_ERROR;
484 if (st->request_state == TLS_ST_SW_HELLO_REQ) {
485 /* We must be trying to renegotiate */
486 st->hand_state = TLS_ST_SW_HELLO_REQ;
487 st->request_state = TLS_ST_BEFORE;
488 return WRITE_TRAN_CONTINUE;
490 /* Must be an incoming ClientHello */
491 if (!tls_setup_handshake(s)) {
492 /* SSLfatal() already called */
493 return WRITE_TRAN_ERROR;
498 /* Just go straight to trying to read from the client */
499 return WRITE_TRAN_FINISHED;
501 case TLS_ST_SW_HELLO_REQ:
502 st->hand_state = TLS_ST_OK;
503 return WRITE_TRAN_CONTINUE;
505 case TLS_ST_SR_CLNT_HELLO:
506 if (SSL_IS_DTLS(s) && !s->d1->cookie_verified
507 && (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE))
508 st->hand_state = DTLS_ST_SW_HELLO_VERIFY_REQUEST;
510 st->hand_state = TLS_ST_SW_SRVR_HELLO;
511 return WRITE_TRAN_CONTINUE;
513 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
514 return WRITE_TRAN_FINISHED;
516 case TLS_ST_SW_SRVR_HELLO:
518 if (s->ext.ticket_expected)
519 st->hand_state = TLS_ST_SW_SESSION_TICKET;
521 st->hand_state = TLS_ST_SW_CHANGE;
523 /* Check if it is anon DH or anon ECDH, */
524 /* normal PSK or SRP */
525 if (!(s->s3->tmp.new_cipher->algorithm_auth &
526 (SSL_aNULL | SSL_aSRP | SSL_aPSK))) {
527 st->hand_state = TLS_ST_SW_CERT;
528 } else if (send_server_key_exchange(s)) {
529 st->hand_state = TLS_ST_SW_KEY_EXCH;
530 } else if (send_certificate_request(s)) {
531 st->hand_state = TLS_ST_SW_CERT_REQ;
533 st->hand_state = TLS_ST_SW_SRVR_DONE;
536 return WRITE_TRAN_CONTINUE;
539 if (s->ext.status_expected) {
540 st->hand_state = TLS_ST_SW_CERT_STATUS;
541 return WRITE_TRAN_CONTINUE;
545 case TLS_ST_SW_CERT_STATUS:
546 if (send_server_key_exchange(s)) {
547 st->hand_state = TLS_ST_SW_KEY_EXCH;
548 return WRITE_TRAN_CONTINUE;
552 case TLS_ST_SW_KEY_EXCH:
553 if (send_certificate_request(s)) {
554 st->hand_state = TLS_ST_SW_CERT_REQ;
555 return WRITE_TRAN_CONTINUE;
559 case TLS_ST_SW_CERT_REQ:
560 st->hand_state = TLS_ST_SW_SRVR_DONE;
561 return WRITE_TRAN_CONTINUE;
563 case TLS_ST_SW_SRVR_DONE:
564 return WRITE_TRAN_FINISHED;
566 case TLS_ST_SR_FINISHED:
568 st->hand_state = TLS_ST_OK;
569 return WRITE_TRAN_CONTINUE;
570 } else if (s->ext.ticket_expected) {
571 st->hand_state = TLS_ST_SW_SESSION_TICKET;
573 st->hand_state = TLS_ST_SW_CHANGE;
575 return WRITE_TRAN_CONTINUE;
577 case TLS_ST_SW_SESSION_TICKET:
578 st->hand_state = TLS_ST_SW_CHANGE;
579 return WRITE_TRAN_CONTINUE;
581 case TLS_ST_SW_CHANGE:
582 st->hand_state = TLS_ST_SW_FINISHED;
583 return WRITE_TRAN_CONTINUE;
585 case TLS_ST_SW_FINISHED:
587 return WRITE_TRAN_FINISHED;
589 st->hand_state = TLS_ST_OK;
590 return WRITE_TRAN_CONTINUE;
595 * Perform any pre work that needs to be done prior to sending a message from
596 * the server to the client.
598 WORK_STATE ossl_statem_server_pre_work(SSL *s, WORK_STATE wst)
600 OSSL_STATEM *st = &s->statem;
602 switch (st->hand_state) {
604 /* No pre work to be done */
607 case TLS_ST_SW_HELLO_REQ:
610 dtls1_clear_sent_buffer(s);
613 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
615 if (SSL_IS_DTLS(s)) {
616 dtls1_clear_sent_buffer(s);
617 /* We don't buffer this message so don't use the timer */
622 case TLS_ST_SW_SRVR_HELLO:
623 if (SSL_IS_DTLS(s)) {
625 * Messages we write from now on should be buffered and
626 * retransmitted if necessary, so we need to use the timer now
632 case TLS_ST_SW_SRVR_DONE:
633 #ifndef OPENSSL_NO_SCTP
634 if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s)))
635 return dtls_wait_for_dry(s);
637 return WORK_FINISHED_CONTINUE;
639 case TLS_ST_SW_SESSION_TICKET:
640 if (SSL_IS_TLS13(s)) {
642 * Actually this is the end of the handshake, but we're going
643 * straight into writing the session ticket out. So we finish off
644 * the handshake, but keep the various buffers active.
646 return tls_finish_handshake(s, wst, 0);
647 } if (SSL_IS_DTLS(s)) {
649 * We're into the last flight. We don't retransmit the last flight
650 * unless we need to, so we don't use the timer
656 case TLS_ST_SW_CHANGE:
657 s->session->cipher = s->s3->tmp.new_cipher;
658 if (!s->method->ssl3_enc->setup_key_block(s)) {
659 /* SSLfatal() already called */
662 if (SSL_IS_DTLS(s)) {
664 * We're into the last flight. We don't retransmit the last flight
665 * unless we need to, so we don't use the timer. This might have
666 * already been set to 0 if we sent a NewSessionTicket message,
667 * but we'll set it again here in case we didn't.
671 return WORK_FINISHED_CONTINUE;
673 case TLS_ST_EARLY_DATA:
674 if (s->early_data_state != SSL_EARLY_DATA_ACCEPTING)
675 return WORK_FINISHED_CONTINUE;
679 return tls_finish_handshake(s, wst, 1);
682 return WORK_FINISHED_CONTINUE;
686 * Perform any work that needs to be done after sending a message from the
687 * server to the client.
689 WORK_STATE ossl_statem_server_post_work(SSL *s, WORK_STATE wst)
691 OSSL_STATEM *st = &s->statem;
695 switch (st->hand_state) {
697 /* No post work to be done */
700 case TLS_ST_SW_HELLO_RETRY_REQUEST:
701 if (statem_flush(s) != 1)
705 case TLS_ST_SW_HELLO_REQ:
706 if (statem_flush(s) != 1)
708 if (!ssl3_init_finished_mac(s)) {
709 /* SSLfatal() already called */
714 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
715 if (statem_flush(s) != 1)
717 /* HelloVerifyRequest resets Finished MAC */
718 if (s->version != DTLS1_BAD_VER && !ssl3_init_finished_mac(s)) {
719 /* SSLfatal() already called */
723 * The next message should be another ClientHello which we need to
724 * treat like it was the first packet
729 case TLS_ST_SW_SRVR_HELLO:
730 #ifndef OPENSSL_NO_SCTP
731 if (SSL_IS_DTLS(s) && s->hit) {
732 unsigned char sctpauthkey[64];
733 char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
736 * Add new shared key for SCTP-Auth, will be ignored if no
739 memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
740 sizeof(DTLS1_SCTP_AUTH_LABEL));
742 if (SSL_export_keying_material(s, sctpauthkey,
743 sizeof(sctpauthkey), labelbuffer,
744 sizeof(labelbuffer), NULL, 0,
746 ossl_statem_set_error(s);
750 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
751 sizeof(sctpauthkey), sctpauthkey);
755 * TODO(TLS1.3): This actually causes a problem. We don't yet know
756 * whether the next record we are going to receive is an unencrypted
757 * alert, or an encrypted handshake message. We're going to need
758 * something clever in the record layer for this.
760 if (SSL_IS_TLS13(s)) {
761 if (!s->method->ssl3_enc->setup_key_block(s)
762 || !s->method->ssl3_enc->change_cipher_state(s,
763 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_WRITE))
766 if (s->ext.early_data != SSL_EARLY_DATA_ACCEPTED
767 && !s->method->ssl3_enc->change_cipher_state(s,
768 SSL3_CC_HANDSHAKE |SSL3_CHANGE_CIPHER_SERVER_READ))
773 case TLS_ST_SW_CHANGE:
774 #ifndef OPENSSL_NO_SCTP
775 if (SSL_IS_DTLS(s) && !s->hit) {
777 * Change to new shared key of SCTP-Auth, will be ignored if
780 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
784 if (!s->method->ssl3_enc->change_cipher_state(s,
785 SSL3_CHANGE_CIPHER_SERVER_WRITE))
787 /* SSLfatal() already called */
792 dtls1_reset_seq_numbers(s, SSL3_CC_WRITE);
795 case TLS_ST_SW_SRVR_DONE:
796 if (statem_flush(s) != 1)
800 case TLS_ST_SW_FINISHED:
801 if (statem_flush(s) != 1)
803 #ifndef OPENSSL_NO_SCTP
804 if (SSL_IS_DTLS(s) && s->hit) {
806 * Change to new shared key of SCTP-Auth, will be ignored if
809 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
813 if (SSL_IS_TLS13(s)) {
814 if (!s->method->ssl3_enc->generate_master_secret(s,
815 s->master_secret, s->handshake_secret, 0,
816 &s->session->master_key_length)
817 || !s->method->ssl3_enc->change_cipher_state(s,
818 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_WRITE))
819 /* SSLfatal() already called */
824 case TLS_ST_SW_KEY_UPDATE:
825 if (statem_flush(s) != 1)
827 if (!tls13_update_key(s, 1))
831 case TLS_ST_SW_SESSION_TICKET:
832 if (SSL_IS_TLS13(s) && statem_flush(s) != 1)
837 return WORK_FINISHED_CONTINUE;
841 * Get the message construction function and message type for sending from the
844 * Valid return values are:
848 int ossl_statem_server_construct_message(SSL *s, WPACKET *pkt,
849 confunc_f *confunc, int *mt)
851 OSSL_STATEM *st = &s->statem;
853 switch (st->hand_state) {
855 /* Shouldn't happen */
856 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
857 SSL_F_OSSL_STATEM_SERVER_CONSTRUCT_MESSAGE,
858 SSL_R_BAD_HANDSHAKE_STATE);
861 case TLS_ST_SW_CHANGE:
863 *confunc = dtls_construct_change_cipher_spec;
865 *confunc = tls_construct_change_cipher_spec;
866 *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
869 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
870 *confunc = dtls_construct_hello_verify_request;
871 *mt = DTLS1_MT_HELLO_VERIFY_REQUEST;
874 case TLS_ST_SW_HELLO_REQ:
875 /* No construction function needed */
877 *mt = SSL3_MT_HELLO_REQUEST;
880 case TLS_ST_SW_SRVR_HELLO:
881 *confunc = tls_construct_server_hello;
882 *mt = SSL3_MT_SERVER_HELLO;
886 *confunc = tls_construct_server_certificate;
887 *mt = SSL3_MT_CERTIFICATE;
890 case TLS_ST_SW_CERT_VRFY:
891 *confunc = tls_construct_cert_verify;
892 *mt = SSL3_MT_CERTIFICATE_VERIFY;
896 case TLS_ST_SW_KEY_EXCH:
897 *confunc = tls_construct_server_key_exchange;
898 *mt = SSL3_MT_SERVER_KEY_EXCHANGE;
901 case TLS_ST_SW_CERT_REQ:
902 *confunc = tls_construct_certificate_request;
903 *mt = SSL3_MT_CERTIFICATE_REQUEST;
906 case TLS_ST_SW_SRVR_DONE:
907 *confunc = tls_construct_server_done;
908 *mt = SSL3_MT_SERVER_DONE;
911 case TLS_ST_SW_SESSION_TICKET:
912 *confunc = tls_construct_new_session_ticket;
913 *mt = SSL3_MT_NEWSESSION_TICKET;
916 case TLS_ST_SW_CERT_STATUS:
917 *confunc = tls_construct_cert_status;
918 *mt = SSL3_MT_CERTIFICATE_STATUS;
921 case TLS_ST_SW_FINISHED:
922 *confunc = tls_construct_finished;
923 *mt = SSL3_MT_FINISHED;
926 case TLS_ST_EARLY_DATA:
931 case TLS_ST_SW_ENCRYPTED_EXTENSIONS:
932 *confunc = tls_construct_encrypted_extensions;
933 *mt = SSL3_MT_ENCRYPTED_EXTENSIONS;
936 case TLS_ST_SW_HELLO_RETRY_REQUEST:
937 *confunc = tls_construct_hello_retry_request;
938 *mt = SSL3_MT_HELLO_RETRY_REQUEST;
941 case TLS_ST_SW_KEY_UPDATE:
942 *confunc = tls_construct_key_update;
943 *mt = SSL3_MT_KEY_UPDATE;
951 * Maximum size (excluding the Handshake header) of a ClientHello message,
952 * calculated as follows:
954 * 2 + # client_version
955 * 32 + # only valid length for random
956 * 1 + # length of session_id
957 * 32 + # maximum size for session_id
958 * 2 + # length of cipher suites
959 * 2^16-2 + # maximum length of cipher suites array
960 * 1 + # length of compression_methods
961 * 2^8-1 + # maximum length of compression methods
962 * 2 + # length of extensions
963 * 2^16-1 # maximum length of extensions
965 #define CLIENT_HELLO_MAX_LENGTH 131396
967 #define CLIENT_KEY_EXCH_MAX_LENGTH 2048
968 #define NEXT_PROTO_MAX_LENGTH 514
971 * Returns the maximum allowed length for the current message that we are
972 * reading. Excludes the message header.
974 size_t ossl_statem_server_max_message_size(SSL *s)
976 OSSL_STATEM *st = &s->statem;
978 switch (st->hand_state) {
980 /* Shouldn't happen */
983 case TLS_ST_SR_CLNT_HELLO:
984 return CLIENT_HELLO_MAX_LENGTH;
986 case TLS_ST_SR_END_OF_EARLY_DATA:
987 return END_OF_EARLY_DATA_MAX_LENGTH;
990 return s->max_cert_list;
992 case TLS_ST_SR_KEY_EXCH:
993 return CLIENT_KEY_EXCH_MAX_LENGTH;
995 case TLS_ST_SR_CERT_VRFY:
996 return SSL3_RT_MAX_PLAIN_LENGTH;
998 #ifndef OPENSSL_NO_NEXTPROTONEG
999 case TLS_ST_SR_NEXT_PROTO:
1000 return NEXT_PROTO_MAX_LENGTH;
1003 case TLS_ST_SR_CHANGE:
1004 return CCS_MAX_LENGTH;
1006 case TLS_ST_SR_FINISHED:
1007 return FINISHED_MAX_LENGTH;
1009 case TLS_ST_SR_KEY_UPDATE:
1010 return KEY_UPDATE_MAX_LENGTH;
1015 * Process a message that the server has received from the client.
1017 MSG_PROCESS_RETURN ossl_statem_server_process_message(SSL *s, PACKET *pkt)
1019 OSSL_STATEM *st = &s->statem;
1021 switch (st->hand_state) {
1023 /* Shouldn't happen */
1024 return MSG_PROCESS_ERROR;
1026 case TLS_ST_SR_CLNT_HELLO:
1027 return tls_process_client_hello(s, pkt);
1029 case TLS_ST_SR_END_OF_EARLY_DATA:
1030 return tls_process_end_of_early_data(s, pkt);
1032 case TLS_ST_SR_CERT:
1033 return tls_process_client_certificate(s, pkt);
1035 case TLS_ST_SR_KEY_EXCH:
1036 return tls_process_client_key_exchange(s, pkt);
1038 case TLS_ST_SR_CERT_VRFY:
1039 return tls_process_cert_verify(s, pkt);
1041 #ifndef OPENSSL_NO_NEXTPROTONEG
1042 case TLS_ST_SR_NEXT_PROTO:
1043 return tls_process_next_proto(s, pkt);
1046 case TLS_ST_SR_CHANGE:
1047 return tls_process_change_cipher_spec(s, pkt);
1049 case TLS_ST_SR_FINISHED:
1050 return tls_process_finished(s, pkt);
1052 case TLS_ST_SR_KEY_UPDATE:
1053 return tls_process_key_update(s, pkt);
1059 * Perform any further processing required following the receipt of a message
1062 WORK_STATE ossl_statem_server_post_process_message(SSL *s, WORK_STATE wst)
1064 OSSL_STATEM *st = &s->statem;
1066 switch (st->hand_state) {
1068 /* Shouldn't happen */
1071 case TLS_ST_SR_CLNT_HELLO:
1072 return tls_post_process_client_hello(s, wst);
1074 case TLS_ST_SR_KEY_EXCH:
1075 return tls_post_process_client_key_exchange(s, wst);
1077 return WORK_FINISHED_CONTINUE;
1080 #ifndef OPENSSL_NO_SRP
1081 static int ssl_check_srp_ext_ClientHello(SSL *s, int *al)
1083 int ret = SSL_ERROR_NONE;
1085 *al = SSL_AD_UNRECOGNIZED_NAME;
1087 if ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) &&
1088 (s->srp_ctx.TLS_ext_srp_username_callback != NULL)) {
1089 if (s->srp_ctx.login == NULL) {
1091 * RFC 5054 says SHOULD reject, we do so if There is no srp
1094 ret = SSL3_AL_FATAL;
1095 *al = SSL_AD_UNKNOWN_PSK_IDENTITY;
1097 ret = SSL_srp_server_param_with_username(s, al);
1104 int dtls_raw_hello_verify_request(WPACKET *pkt, unsigned char *cookie,
1107 /* Always use DTLS 1.0 version: see RFC 6347 */
1108 if (!WPACKET_put_bytes_u16(pkt, DTLS1_VERSION)
1109 || !WPACKET_sub_memcpy_u8(pkt, cookie, cookie_len))
1115 int dtls_construct_hello_verify_request(SSL *s, WPACKET *pkt)
1117 unsigned int cookie_leni;
1118 if (s->ctx->app_gen_cookie_cb == NULL ||
1119 s->ctx->app_gen_cookie_cb(s, s->d1->cookie,
1120 &cookie_leni) == 0 ||
1121 cookie_leni > 255) {
1122 SSLfatal(s, SSL_AD_NO_ALERT, SSL_F_DTLS_CONSTRUCT_HELLO_VERIFY_REQUEST,
1123 SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
1126 s->d1->cookie_len = cookie_leni;
1128 if (!dtls_raw_hello_verify_request(pkt, s->d1->cookie,
1129 s->d1->cookie_len)) {
1130 SSLfatal(s, SSL_AD_NO_ALERT, SSL_F_DTLS_CONSTRUCT_HELLO_VERIFY_REQUEST,
1131 ERR_R_INTERNAL_ERROR);
1138 #ifndef OPENSSL_NO_EC
1140 * ssl_check_for_safari attempts to fingerprint Safari using OS X
1141 * SecureTransport using the TLS extension block in |hello|.
1142 * Safari, since 10.6, sends exactly these extensions, in this order:
1146 * signature_algorithms (for TLSv1.2 only)
1148 * We wish to fingerprint Safari because they broke ECDHE-ECDSA support in 10.8,
1149 * but they advertise support. So enabling ECDHE-ECDSA ciphers breaks them.
1150 * Sadly we cannot differentiate 10.6, 10.7 and 10.8.4 (which work), from
1151 * 10.8..10.8.3 (which don't work).
1153 static void ssl_check_for_safari(SSL *s, const CLIENTHELLO_MSG *hello)
1155 static const unsigned char kSafariExtensionsBlock[] = {
1156 0x00, 0x0a, /* elliptic_curves extension */
1157 0x00, 0x08, /* 8 bytes */
1158 0x00, 0x06, /* 6 bytes of curve ids */
1159 0x00, 0x17, /* P-256 */
1160 0x00, 0x18, /* P-384 */
1161 0x00, 0x19, /* P-521 */
1163 0x00, 0x0b, /* ec_point_formats */
1164 0x00, 0x02, /* 2 bytes */
1165 0x01, /* 1 point format */
1166 0x00, /* uncompressed */
1167 /* The following is only present in TLS 1.2 */
1168 0x00, 0x0d, /* signature_algorithms */
1169 0x00, 0x0c, /* 12 bytes */
1170 0x00, 0x0a, /* 10 bytes */
1171 0x05, 0x01, /* SHA-384/RSA */
1172 0x04, 0x01, /* SHA-256/RSA */
1173 0x02, 0x01, /* SHA-1/RSA */
1174 0x04, 0x03, /* SHA-256/ECDSA */
1175 0x02, 0x03, /* SHA-1/ECDSA */
1177 /* Length of the common prefix (first two extensions). */
1178 static const size_t kSafariCommonExtensionsLength = 18;
1183 tmppkt = hello->extensions;
1185 if (!PACKET_forward(&tmppkt, 2)
1186 || !PACKET_get_net_2(&tmppkt, &type)
1187 || !PACKET_get_length_prefixed_2(&tmppkt, &sni)) {
1191 if (type != TLSEXT_TYPE_server_name)
1194 ext_len = TLS1_get_client_version(s) >= TLS1_2_VERSION ?
1195 sizeof(kSafariExtensionsBlock) : kSafariCommonExtensionsLength;
1197 s->s3->is_probably_safari = PACKET_equal(&tmppkt, kSafariExtensionsBlock,
1200 #endif /* !OPENSSL_NO_EC */
1202 MSG_PROCESS_RETURN tls_process_client_hello(SSL *s, PACKET *pkt)
1204 /* |cookie| will only be initialized for DTLS. */
1205 PACKET session_id, compression, extensions, cookie;
1206 static const unsigned char null_compression = 0;
1207 CLIENTHELLO_MSG *clienthello;
1209 clienthello = OPENSSL_zalloc(sizeof(*clienthello));
1210 if (clienthello == NULL) {
1211 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1212 ERR_R_INTERNAL_ERROR);
1215 /* Check if this is actually an unexpected renegotiation ClientHello */
1216 if (s->renegotiate == 0 && !SSL_IS_FIRST_HANDSHAKE(s)) {
1217 if ((s->options & SSL_OP_NO_RENEGOTIATION)) {
1218 ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
1226 * First, parse the raw ClientHello data into the CLIENTHELLO_MSG structure.
1228 clienthello->isv2 = RECORD_LAYER_is_sslv2_record(&s->rlayer);
1229 PACKET_null_init(&cookie);
1231 if (clienthello->isv2) {
1234 if (!SSL_IS_FIRST_HANDSHAKE(s) || s->hello_retry_request) {
1235 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1236 SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNEXPECTED_MESSAGE);
1241 * An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2
1242 * header is sent directly on the wire, not wrapped as a TLS
1243 * record. Our record layer just processes the message length and passes
1244 * the rest right through. Its format is:
1246 * 0-1 msg_length - decoded by the record layer
1247 * 2 msg_type - s->init_msg points here
1249 * 5-6 cipher_spec_length
1250 * 7-8 session_id_length
1251 * 9-10 challenge_length
1255 if (!PACKET_get_1(pkt, &mt)
1256 || mt != SSL2_MT_CLIENT_HELLO) {
1258 * Should never happen. We should have tested this in the record
1259 * layer in order to have determined that this is a SSLv2 record
1260 * in the first place
1262 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1263 ERR_R_INTERNAL_ERROR);
1268 if (!PACKET_get_net_2(pkt, &clienthello->legacy_version)) {
1269 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1270 SSL_R_LENGTH_TOO_SHORT);
1274 /* Parse the message and load client random. */
1275 if (clienthello->isv2) {
1277 * Handle an SSLv2 backwards compatible ClientHello
1278 * Note, this is only for SSLv3+ using the backward compatible format.
1279 * Real SSLv2 is not supported, and is rejected below.
1281 unsigned int ciphersuite_len, session_id_len, challenge_len;
1284 if (!PACKET_get_net_2(pkt, &ciphersuite_len)
1285 || !PACKET_get_net_2(pkt, &session_id_len)
1286 || !PACKET_get_net_2(pkt, &challenge_len)) {
1287 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1288 SSL_R_RECORD_LENGTH_MISMATCH);
1292 if (session_id_len > SSL_MAX_SSL_SESSION_ID_LENGTH) {
1293 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1294 SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1298 if (!PACKET_get_sub_packet(pkt, &clienthello->ciphersuites,
1300 || !PACKET_copy_bytes(pkt, clienthello->session_id, session_id_len)
1301 || !PACKET_get_sub_packet(pkt, &challenge, challenge_len)
1302 /* No extensions. */
1303 || PACKET_remaining(pkt) != 0) {
1304 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1305 SSL_R_RECORD_LENGTH_MISMATCH);
1308 clienthello->session_id_len = session_id_len;
1310 /* Load the client random and compression list. We use SSL3_RANDOM_SIZE
1311 * here rather than sizeof(clienthello->random) because that is the limit
1312 * for SSLv3 and it is fixed. It won't change even if
1313 * sizeof(clienthello->random) does.
1315 challenge_len = challenge_len > SSL3_RANDOM_SIZE
1316 ? SSL3_RANDOM_SIZE : challenge_len;
1317 memset(clienthello->random, 0, SSL3_RANDOM_SIZE);
1318 if (!PACKET_copy_bytes(&challenge,
1319 clienthello->random + SSL3_RANDOM_SIZE -
1320 challenge_len, challenge_len)
1321 /* Advertise only null compression. */
1322 || !PACKET_buf_init(&compression, &null_compression, 1)) {
1323 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1324 ERR_R_INTERNAL_ERROR);
1328 PACKET_null_init(&clienthello->extensions);
1330 /* Regular ClientHello. */
1331 if (!PACKET_copy_bytes(pkt, clienthello->random, SSL3_RANDOM_SIZE)
1332 || !PACKET_get_length_prefixed_1(pkt, &session_id)
1333 || !PACKET_copy_all(&session_id, clienthello->session_id,
1334 SSL_MAX_SSL_SESSION_ID_LENGTH,
1335 &clienthello->session_id_len)) {
1336 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1337 SSL_R_LENGTH_MISMATCH);
1341 if (SSL_IS_DTLS(s)) {
1342 if (!PACKET_get_length_prefixed_1(pkt, &cookie)) {
1343 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1344 SSL_R_LENGTH_MISMATCH);
1347 if (!PACKET_copy_all(&cookie, clienthello->dtls_cookie,
1348 DTLS1_COOKIE_LENGTH,
1349 &clienthello->dtls_cookie_len)) {
1350 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1351 SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1355 * If we require cookies and this ClientHello doesn't contain one,
1356 * just return since we do not want to allocate any memory yet.
1357 * So check cookie length...
1359 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1360 if (clienthello->dtls_cookie_len == 0)
1361 return MSG_PROCESS_FINISHED_READING;
1365 if (!PACKET_get_length_prefixed_2(pkt, &clienthello->ciphersuites)) {
1366 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1367 SSL_R_LENGTH_MISMATCH);
1371 if (!PACKET_get_length_prefixed_1(pkt, &compression)) {
1372 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1373 SSL_R_LENGTH_MISMATCH);
1377 /* Could be empty. */
1378 if (PACKET_remaining(pkt) == 0) {
1379 PACKET_null_init(&clienthello->extensions);
1381 if (!PACKET_get_length_prefixed_2(pkt, &clienthello->extensions)
1382 || PACKET_remaining(pkt) != 0) {
1383 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1384 SSL_R_LENGTH_MISMATCH);
1390 if (!PACKET_copy_all(&compression, clienthello->compressions,
1391 MAX_COMPRESSIONS_SIZE,
1392 &clienthello->compressions_len)) {
1393 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1394 ERR_R_INTERNAL_ERROR);
1398 /* Preserve the raw extensions PACKET for later use */
1399 extensions = clienthello->extensions;
1400 if (!tls_collect_extensions(s, &extensions, SSL_EXT_CLIENT_HELLO,
1401 &clienthello->pre_proc_exts,
1402 &clienthello->pre_proc_exts_len, 1)) {
1403 /* SSLfatal already been called */
1406 s->clienthello = clienthello;
1408 return MSG_PROCESS_CONTINUE_PROCESSING;
1411 if (clienthello != NULL)
1412 OPENSSL_free(clienthello->pre_proc_exts);
1413 OPENSSL_free(clienthello);
1415 return MSG_PROCESS_ERROR;
1418 static int tls_early_post_process_client_hello(SSL *s)
1421 int i, al = SSL_AD_INTERNAL_ERROR;
1425 #ifndef OPENSSL_NO_COMP
1426 SSL_COMP *comp = NULL;
1428 const SSL_CIPHER *c;
1429 STACK_OF(SSL_CIPHER) *ciphers = NULL;
1430 STACK_OF(SSL_CIPHER) *scsvs = NULL;
1431 CLIENTHELLO_MSG *clienthello = s->clienthello;
1432 DOWNGRADE dgrd = DOWNGRADE_NONE;
1434 /* Finished parsing the ClientHello, now we can start processing it */
1435 /* Give the ClientHello callback a crack at things */
1436 if (s->ctx->client_hello_cb != NULL) {
1437 /* A failure in the ClientHello callback terminates the connection. */
1438 switch (s->ctx->client_hello_cb(s, &al, s->ctx->client_hello_cb_arg)) {
1439 case SSL_CLIENT_HELLO_SUCCESS:
1441 case SSL_CLIENT_HELLO_RETRY:
1442 s->rwstate = SSL_CLIENT_HELLO_CB;
1444 case SSL_CLIENT_HELLO_ERROR:
1447 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1448 SSL_R_CALLBACK_FAILED);
1453 /* Set up the client_random */
1454 memcpy(s->s3->client_random, clienthello->random, SSL3_RANDOM_SIZE);
1456 /* Choose the version */
1458 if (clienthello->isv2) {
1459 if (clienthello->legacy_version == SSL2_VERSION
1460 || (clienthello->legacy_version & 0xff00)
1461 != (SSL3_VERSION_MAJOR << 8)) {
1463 * This is real SSLv2 or something completely unknown. We don't
1466 SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
1467 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1468 SSL_R_UNKNOWN_PROTOCOL);
1472 s->client_version = clienthello->legacy_version;
1475 * Do SSL/TLS version negotiation if applicable. For DTLS we just check
1476 * versions are potentially compatible. Version negotiation comes later.
1478 if (!SSL_IS_DTLS(s)) {
1479 protverr = ssl_choose_server_version(s, clienthello, &dgrd);
1480 } else if (s->method->version != DTLS_ANY_VERSION &&
1481 DTLS_VERSION_LT((int)clienthello->legacy_version, s->version)) {
1482 protverr = SSL_R_VERSION_TOO_LOW;
1488 if (SSL_IS_FIRST_HANDSHAKE(s)) {
1489 /* like ssl3_get_record, send alert using remote version number */
1490 s->version = s->client_version = clienthello->legacy_version;
1492 SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
1493 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, protverr);
1497 /* TLSv1.3 specifies that a ClientHello must end on a record boundary */
1498 if (SSL_IS_TLS13(s) && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
1499 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1500 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1501 SSL_R_NOT_ON_RECORD_BOUNDARY);
1505 if (SSL_IS_DTLS(s)) {
1506 /* Empty cookie was already handled above by returning early. */
1507 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1508 if (s->ctx->app_verify_cookie_cb != NULL) {
1509 if (s->ctx->app_verify_cookie_cb(s, clienthello->dtls_cookie,
1510 clienthello->dtls_cookie_len) == 0) {
1511 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1512 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1513 SSL_R_COOKIE_MISMATCH);
1515 /* else cookie verification succeeded */
1517 /* default verification */
1518 } else if (s->d1->cookie_len != clienthello->dtls_cookie_len
1519 || memcmp(clienthello->dtls_cookie, s->d1->cookie,
1520 s->d1->cookie_len) != 0) {
1521 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1522 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1523 SSL_R_COOKIE_MISMATCH);
1526 s->d1->cookie_verified = 1;
1528 if (s->method->version == DTLS_ANY_VERSION) {
1529 protverr = ssl_choose_server_version(s, clienthello, &dgrd);
1530 if (protverr != 0) {
1531 s->version = s->client_version;
1532 SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
1533 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, protverr);
1541 if (!ssl_cache_cipherlist(s, &clienthello->ciphersuites,
1542 clienthello->isv2) ||
1543 !bytes_to_cipher_list(s, &clienthello->ciphersuites, &ciphers, &scsvs,
1544 clienthello->isv2, 1)) {
1545 /* SSLfatal() already called */
1549 s->s3->send_connection_binding = 0;
1550 /* Check what signalling cipher-suite values were received. */
1551 if (scsvs != NULL) {
1552 for(i = 0; i < sk_SSL_CIPHER_num(scsvs); i++) {
1553 c = sk_SSL_CIPHER_value(scsvs, i);
1554 if (SSL_CIPHER_get_id(c) == SSL3_CK_SCSV) {
1555 if (s->renegotiate) {
1556 /* SCSV is fatal if renegotiating */
1557 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1558 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1559 SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING);
1562 s->s3->send_connection_binding = 1;
1563 } else if (SSL_CIPHER_get_id(c) == SSL3_CK_FALLBACK_SCSV &&
1564 !ssl_check_version_downgrade(s)) {
1566 * This SCSV indicates that the client previously tried
1567 * a higher version. We should fail if the current version
1568 * is an unexpected downgrade, as that indicates that the first
1569 * connection may have been tampered with in order to trigger
1570 * an insecure downgrade.
1572 SSLfatal(s, SSL_AD_INAPPROPRIATE_FALLBACK,
1573 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1574 SSL_R_INAPPROPRIATE_FALLBACK);
1580 /* For TLSv1.3 we must select the ciphersuite *before* session resumption */
1581 if (SSL_IS_TLS13(s)) {
1582 const SSL_CIPHER *cipher =
1583 ssl3_choose_cipher(s, ciphers, SSL_get_ciphers(s));
1585 if (cipher == NULL) {
1586 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1587 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1588 SSL_R_NO_SHARED_CIPHER);
1591 if (s->hello_retry_request
1592 && (s->s3->tmp.new_cipher == NULL
1593 || s->s3->tmp.new_cipher->id != cipher->id)) {
1595 * A previous HRR picked a different ciphersuite to the one we
1596 * just selected. Something must have changed.
1598 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1599 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1603 s->s3->tmp.new_cipher = cipher;
1606 /* We need to do this before getting the session */
1607 if (!tls_parse_extension(s, TLSEXT_IDX_extended_master_secret,
1608 SSL_EXT_CLIENT_HELLO,
1609 clienthello->pre_proc_exts, NULL, 0)) {
1610 /* SSLfatal() already called */
1615 * We don't allow resumption in a backwards compatible ClientHello.
1616 * TODO(openssl-team): in TLS1.1+, session_id MUST be empty.
1618 * Versions before 0.9.7 always allow clients to resume sessions in
1619 * renegotiation. 0.9.7 and later allow this by default, but optionally
1620 * ignore resumption requests with flag
1621 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
1622 * than a change to default behavior so that applications relying on
1623 * this for security won't even compile against older library versions).
1624 * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
1625 * request renegotiation but not a new session (s->new_session remains
1626 * unset): for servers, this essentially just means that the
1627 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be
1630 if (clienthello->isv2 ||
1632 (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
1633 if (!ssl_get_new_session(s, 1)) {
1634 /* SSLfatal() already called */
1638 i = ssl_get_prev_session(s, clienthello);
1640 /* previous session */
1642 } else if (i == -1) {
1643 /* SSLfatal() already called */
1647 if (!ssl_get_new_session(s, 1)) {
1648 /* SSLfatal() already called */
1655 * If it is a hit, check that the cipher is in the list. In TLSv1.3 we check
1656 * ciphersuite compatibility with the session as part of resumption.
1658 if (!SSL_IS_TLS13(s) && s->hit) {
1660 id = s->session->cipher->id;
1663 fprintf(stderr, "client sent %d ciphers\n", sk_SSL_CIPHER_num(ciphers));
1665 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1666 c = sk_SSL_CIPHER_value(ciphers, i);
1668 fprintf(stderr, "client [%2d of %2d]:%s\n",
1669 i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
1678 * we need to have the cipher in the cipher list if we are asked
1681 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1682 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1683 SSL_R_REQUIRED_CIPHER_MISSING);
1688 for (loop = 0; loop < clienthello->compressions_len; loop++) {
1689 if (clienthello->compressions[loop] == 0)
1693 if (loop >= clienthello->compressions_len) {
1695 SSLfatal(s, SSL_AD_DECODE_ERROR,
1696 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1697 SSL_R_NO_COMPRESSION_SPECIFIED);
1701 #ifndef OPENSSL_NO_EC
1702 if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
1703 ssl_check_for_safari(s, clienthello);
1704 #endif /* !OPENSSL_NO_EC */
1706 /* TLS extensions */
1707 if (!tls_parse_all_extensions(s, SSL_EXT_CLIENT_HELLO,
1708 clienthello->pre_proc_exts, NULL, 0, 1)) {
1709 /* SSLfatal() already called */
1714 * Check if we want to use external pre-shared secret for this handshake
1715 * for not reused session only. We need to generate server_random before
1716 * calling tls_session_secret_cb in order to allow SessionTicket
1717 * processing to use it in key derivation.
1721 pos = s->s3->server_random;
1722 if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE, dgrd) <= 0) {
1723 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1724 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1725 ERR_R_INTERNAL_ERROR);
1731 && s->version >= TLS1_VERSION
1734 && s->ext.session_secret_cb) {
1735 const SSL_CIPHER *pref_cipher = NULL;
1737 * s->session->master_key_length is a size_t, but this is an int for
1738 * backwards compat reasons
1740 int master_key_length;
1742 master_key_length = sizeof(s->session->master_key);
1743 if (s->ext.session_secret_cb(s, s->session->master_key,
1744 &master_key_length, ciphers,
1746 s->ext.session_secret_cb_arg)
1747 && master_key_length > 0) {
1748 s->session->master_key_length = master_key_length;
1750 s->session->ciphers = ciphers;
1751 s->session->verify_result = X509_V_OK;
1755 /* check if some cipher was preferred by call back */
1756 if (pref_cipher == NULL)
1757 pref_cipher = ssl3_choose_cipher(s, s->session->ciphers,
1758 SSL_get_ciphers(s));
1759 if (pref_cipher == NULL) {
1760 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1761 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1762 SSL_R_NO_SHARED_CIPHER);
1766 s->session->cipher = pref_cipher;
1767 sk_SSL_CIPHER_free(s->cipher_list);
1768 s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1769 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1770 s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1775 * Worst case, we will use the NULL compression, but if we have other
1776 * options, we will now look for them. We have complen-1 compression
1777 * algorithms from the client, starting at q.
1779 s->s3->tmp.new_compression = NULL;
1780 if (SSL_IS_TLS13(s)) {
1782 * We already checked above that the NULL compression method appears in
1783 * the list. Now we check there aren't any others (which is illegal in
1784 * a TLSv1.3 ClientHello.
1786 if (clienthello->compressions_len != 1) {
1787 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1788 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1789 SSL_R_INVALID_COMPRESSION_ALGORITHM);
1793 #ifndef OPENSSL_NO_COMP
1794 /* This only happens if we have a cache hit */
1795 else if (s->session->compress_meth != 0) {
1796 int m, comp_id = s->session->compress_meth;
1798 /* Perform sanity checks on resumed compression algorithm */
1799 /* Can't disable compression */
1800 if (!ssl_allow_compression(s)) {
1801 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1802 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1803 SSL_R_INCONSISTENT_COMPRESSION);
1806 /* Look for resumed compression method */
1807 for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) {
1808 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1809 if (comp_id == comp->id) {
1810 s->s3->tmp.new_compression = comp;
1814 if (s->s3->tmp.new_compression == NULL) {
1815 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1816 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1817 SSL_R_INVALID_COMPRESSION_ALGORITHM);
1820 /* Look for resumed method in compression list */
1821 for (k = 0; k < clienthello->compressions_len; k++) {
1822 if (clienthello->compressions[k] == comp_id)
1825 if (k >= clienthello->compressions_len) {
1826 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1827 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1828 SSL_R_REQUIRED_COMPRESSION_ALGORITHM_MISSING);
1831 } else if (s->hit) {
1833 } else if (ssl_allow_compression(s) && s->ctx->comp_methods) {
1834 /* See if we have a match */
1835 int m, nn, v, done = 0;
1838 nn = sk_SSL_COMP_num(s->ctx->comp_methods);
1839 for (m = 0; m < nn; m++) {
1840 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1842 for (o = 0; o < clienthello->compressions_len; o++) {
1843 if (v == clienthello->compressions[o]) {
1852 s->s3->tmp.new_compression = comp;
1858 * If compression is disabled we'd better not try to resume a session
1859 * using compression.
1861 if (s->session->compress_meth != 0) {
1862 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1863 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1864 SSL_R_INCONSISTENT_COMPRESSION);
1870 * Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher
1873 if (!s->hit || SSL_IS_TLS13(s)) {
1874 sk_SSL_CIPHER_free(s->session->ciphers);
1875 s->session->ciphers = ciphers;
1876 if (ciphers == NULL) {
1877 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1878 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1879 ERR_R_INTERNAL_ERROR);
1886 #ifdef OPENSSL_NO_COMP
1887 s->session->compress_meth = 0;
1889 s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
1891 if (!tls1_set_server_sigalgs(s)) {
1892 /* SSLfatal() already called */
1897 sk_SSL_CIPHER_free(ciphers);
1898 sk_SSL_CIPHER_free(scsvs);
1899 OPENSSL_free(clienthello->pre_proc_exts);
1900 OPENSSL_free(s->clienthello);
1901 s->clienthello = NULL;
1904 sk_SSL_CIPHER_free(ciphers);
1905 sk_SSL_CIPHER_free(scsvs);
1906 OPENSSL_free(clienthello->pre_proc_exts);
1907 OPENSSL_free(s->clienthello);
1908 s->clienthello = NULL;
1914 * Call the status request callback if needed. Upon success, returns 1.
1915 * Upon failure, returns 0.
1917 static int tls_handle_status_request(SSL *s)
1919 s->ext.status_expected = 0;
1922 * If status request then ask callback what to do. Note: this must be
1923 * called after servername callbacks in case the certificate has changed,
1924 * and must be called after the cipher has been chosen because this may
1925 * influence which certificate is sent
1927 if (s->ext.status_type != TLSEXT_STATUSTYPE_nothing && s->ctx != NULL
1928 && s->ctx->ext.status_cb != NULL) {
1931 /* If no certificate can't return certificate status */
1932 if (s->s3->tmp.cert != NULL) {
1934 * Set current certificate to one we will use so SSL_get_certificate
1935 * et al can pick it up.
1937 s->cert->key = s->s3->tmp.cert;
1938 ret = s->ctx->ext.status_cb(s, s->ctx->ext.status_arg);
1940 /* We don't want to send a status request response */
1941 case SSL_TLSEXT_ERR_NOACK:
1942 s->ext.status_expected = 0;
1944 /* status request response should be sent */
1945 case SSL_TLSEXT_ERR_OK:
1946 if (s->ext.ocsp.resp)
1947 s->ext.status_expected = 1;
1949 /* something bad happened */
1950 case SSL_TLSEXT_ERR_ALERT_FATAL:
1952 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1953 SSL_F_TLS_HANDLE_STATUS_REQUEST,
1954 SSL_R_CLIENTHELLO_TLSEXT);
1964 * Call the alpn_select callback if needed. Upon success, returns 1.
1965 * Upon failure, returns 0 and sets |*al| to the appropriate fatal alert.
1967 int tls_handle_alpn(SSL *s)
1969 const unsigned char *selected = NULL;
1970 unsigned char selected_len = 0;
1972 if (s->ctx->ext.alpn_select_cb != NULL && s->s3->alpn_proposed != NULL) {
1973 int r = s->ctx->ext.alpn_select_cb(s, &selected, &selected_len,
1974 s->s3->alpn_proposed,
1975 (unsigned int)s->s3->alpn_proposed_len,
1976 s->ctx->ext.alpn_select_cb_arg);
1978 if (r == SSL_TLSEXT_ERR_OK) {
1979 OPENSSL_free(s->s3->alpn_selected);
1980 s->s3->alpn_selected = OPENSSL_memdup(selected, selected_len);
1981 if (s->s3->alpn_selected == NULL) {
1982 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_HANDLE_ALPN,
1983 ERR_R_INTERNAL_ERROR);
1986 s->s3->alpn_selected_len = selected_len;
1987 #ifndef OPENSSL_NO_NEXTPROTONEG
1988 /* ALPN takes precedence over NPN. */
1989 s->s3->npn_seen = 0;
1992 /* Check ALPN is consistent with session */
1993 if (s->session->ext.alpn_selected == NULL
1994 || selected_len != s->session->ext.alpn_selected_len
1995 || memcmp(selected, s->session->ext.alpn_selected,
1996 selected_len) != 0) {
1997 /* Not consistent so can't be used for early_data */
1998 s->ext.early_data_ok = 0;
2001 /* If a new session update it with the new ALPN value */
2002 s->session->ext.alpn_selected = OPENSSL_memdup(selected,
2004 if (s->session->ext.alpn_selected == NULL) {
2005 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2006 SSL_F_TLS_HANDLE_ALPN,
2007 ERR_R_INTERNAL_ERROR);
2010 s->session->ext.alpn_selected_len = selected_len;
2015 } else if (r != SSL_TLSEXT_ERR_NOACK) {
2016 SSLfatal(s, SSL_AD_NO_APPLICATION_PROTOCOL, SSL_F_TLS_HANDLE_ALPN,
2017 SSL_R_NO_APPLICATION_PROTOCOL);
2021 * If r == SSL_TLSEXT_ERR_NOACK then behave as if no callback was
2026 /* Check ALPN is consistent with session */
2027 if (s->session->ext.alpn_selected != NULL) {
2028 /* Not consistent so can't be used for early_data */
2029 s->ext.early_data_ok = 0;
2035 WORK_STATE tls_post_process_client_hello(SSL *s, WORK_STATE wst)
2037 int al = SSL_AD_HANDSHAKE_FAILURE;
2038 const SSL_CIPHER *cipher;
2040 if (wst == WORK_MORE_A) {
2041 int rv = tls_early_post_process_client_hello(s);
2043 /* SSLfatal() was already called */
2050 if (wst == WORK_MORE_B) {
2051 if (!s->hit || SSL_IS_TLS13(s)) {
2052 /* Let cert callback update server certificates if required */
2053 if (!s->hit && s->cert->cert_cb != NULL) {
2054 int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
2056 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2057 SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
2058 SSL_R_CERT_CB_ERROR);
2062 s->rwstate = SSL_X509_LOOKUP;
2065 s->rwstate = SSL_NOTHING;
2068 /* In TLSv1.3 we selected the ciphersuite before resumption */
2069 if (!SSL_IS_TLS13(s)) {
2071 ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
2073 if (cipher == NULL) {
2074 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2075 SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
2076 SSL_R_NO_SHARED_CIPHER);
2079 s->s3->tmp.new_cipher = cipher;
2082 if (!tls_choose_sigalg(s, 1)) {
2083 /* SSLfatal already called */
2086 /* check whether we should disable session resumption */
2087 if (s->not_resumable_session_cb != NULL)
2088 s->session->not_resumable =
2089 s->not_resumable_session_cb(s,
2090 ((s->s3->tmp.new_cipher->algorithm_mkey
2091 & (SSL_kDHE | SSL_kECDHE)) != 0));
2092 if (s->session->not_resumable)
2093 /* do not send a session ticket */
2094 s->ext.ticket_expected = 0;
2097 /* Session-id reuse */
2098 s->s3->tmp.new_cipher = s->session->cipher;
2102 * we now have the following setup.
2104 * cipher_list - our preferred list of ciphers
2105 * ciphers - the clients preferred list of ciphers
2106 * compression - basically ignored right now
2107 * ssl version is set - sslv3
2108 * s->session - The ssl session has been setup.
2109 * s->hit - session reuse flag
2110 * s->s3->tmp.new_cipher- the new cipher to use.
2114 * Call status_request callback if needed. Has to be done after the
2115 * certificate callbacks etc above.
2117 if (!tls_handle_status_request(s)) {
2118 /* SSLfatal() already called */
2122 * Call alpn_select callback if needed. Has to be done after SNI and
2123 * cipher negotiation (HTTP/2 restricts permitted ciphers). In TLSv1.3
2124 * we already did this because cipher negotiation happens earlier, and
2125 * we must handle ALPN before we decide whether to accept early_data.
2127 if (!SSL_IS_TLS13(s) && !tls_handle_alpn(s)) {
2128 /* SSLfatal() already called */
2134 #ifndef OPENSSL_NO_SRP
2135 if (wst == WORK_MORE_C) {
2137 if ((ret = ssl_check_srp_ext_ClientHello(s, &al)) < 0) {
2139 * callback indicates further work to be done
2141 s->rwstate = SSL_X509_LOOKUP;
2144 if (ret != SSL_ERROR_NONE) {
2146 * This is not really an error but the only means to for
2147 * a client to detect whether srp is supported.
2149 if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)
2150 SSLfatal(s, al, SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
2151 SSL_R_CLIENTHELLO_TLSEXT);
2153 SSLfatal(s, al, SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
2154 SSL_R_PSK_IDENTITY_NOT_FOUND);
2160 return WORK_FINISHED_STOP;
2165 int tls_construct_server_hello(SSL *s, WPACKET *pkt)
2171 /* TODO(TLS1.3): Remove the DRAFT conditional before release */
2172 version = SSL_IS_TLS13(s) ? TLS1_3_VERSION_DRAFT : s->version;
2173 if (!WPACKET_put_bytes_u16(pkt, version)
2175 * Random stuff. Filling of the server_random takes place in
2176 * tls_process_client_hello()
2178 || !WPACKET_memcpy(pkt, s->s3->server_random, SSL3_RANDOM_SIZE)) {
2179 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_HELLO,
2180 ERR_R_INTERNAL_ERROR);
2185 * There are several cases for the session ID to send
2186 * back in the server hello:
2187 * - For session reuse from the session cache,
2188 * we send back the old session ID.
2189 * - If stateless session reuse (using a session ticket)
2190 * is successful, we send back the client's "session ID"
2191 * (which doesn't actually identify the session).
2192 * - If it is a new session, we send back the new
2194 * - However, if we want the new session to be single-use,
2195 * we send back a 0-length session ID.
2196 * s->hit is non-zero in either case of session reuse,
2197 * so the following won't overwrite an ID that we're supposed
2200 if (s->session->not_resumable ||
2201 (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
2203 s->session->session_id_length = 0;
2205 sl = s->session->session_id_length;
2206 if (sl > sizeof(s->session->session_id)) {
2207 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_HELLO,
2208 ERR_R_INTERNAL_ERROR);
2212 /* set up the compression method */
2213 #ifdef OPENSSL_NO_COMP
2216 if (s->s3->tmp.new_compression == NULL)
2219 compm = s->s3->tmp.new_compression->id;
2222 if ((!SSL_IS_TLS13(s)
2223 && !WPACKET_sub_memcpy_u8(pkt, s->session->session_id, sl))
2224 || !s->method->put_cipher_by_char(s->s3->tmp.new_cipher, pkt, &len)
2225 || (!SSL_IS_TLS13(s)
2226 && !WPACKET_put_bytes_u8(pkt, compm))
2227 || !tls_construct_extensions(s, pkt,
2229 ? SSL_EXT_TLS1_3_SERVER_HELLO
2230 : SSL_EXT_TLS1_2_SERVER_HELLO,
2232 /* SSLfatal() already called */
2236 if (!(s->verify_mode & SSL_VERIFY_PEER)
2237 && !ssl3_digest_cached_records(s, 0)) {
2238 /* SSLfatal() already called */;
2245 int tls_construct_server_done(SSL *s, WPACKET *pkt)
2247 if (!s->s3->tmp.cert_request) {
2248 if (!ssl3_digest_cached_records(s, 0)) {
2249 /* SSLfatal() already called */
2256 int tls_construct_server_key_exchange(SSL *s, WPACKET *pkt)
2258 #ifndef OPENSSL_NO_DH
2259 EVP_PKEY *pkdh = NULL;
2261 #ifndef OPENSSL_NO_EC
2262 unsigned char *encodedPoint = NULL;
2263 size_t encodedlen = 0;
2266 const SIGALG_LOOKUP *lu = s->s3->tmp.sigalg;
2270 EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
2271 EVP_PKEY_CTX *pctx = NULL;
2272 size_t paramlen, paramoffset;
2274 if (!WPACKET_get_total_written(pkt, ¶moffset)) {
2275 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2276 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2280 if (md_ctx == NULL) {
2281 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2282 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2286 type = s->s3->tmp.new_cipher->algorithm_mkey;
2288 r[0] = r[1] = r[2] = r[3] = NULL;
2289 #ifndef OPENSSL_NO_PSK
2290 /* Plain PSK or RSAPSK nothing to do */
2291 if (type & (SSL_kPSK | SSL_kRSAPSK)) {
2293 #endif /* !OPENSSL_NO_PSK */
2294 #ifndef OPENSSL_NO_DH
2295 if (type & (SSL_kDHE | SSL_kDHEPSK)) {
2296 CERT *cert = s->cert;
2298 EVP_PKEY *pkdhp = NULL;
2301 if (s->cert->dh_tmp_auto) {
2302 DH *dhp = ssl_get_auto_dh(s);
2303 pkdh = EVP_PKEY_new();
2304 if (pkdh == NULL || dhp == NULL) {
2306 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2307 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2308 ERR_R_INTERNAL_ERROR);
2311 EVP_PKEY_assign_DH(pkdh, dhp);
2314 pkdhp = cert->dh_tmp;
2316 if ((pkdhp == NULL) && (s->cert->dh_tmp_cb != NULL)) {
2317 DH *dhp = s->cert->dh_tmp_cb(s, 0, 1024);
2318 pkdh = ssl_dh_to_pkey(dhp);
2320 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2321 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2322 ERR_R_INTERNAL_ERROR);
2327 if (pkdhp == NULL) {
2328 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2329 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2330 SSL_R_MISSING_TMP_DH_KEY);
2333 if (!ssl_security(s, SSL_SECOP_TMP_DH,
2334 EVP_PKEY_security_bits(pkdhp), 0, pkdhp)) {
2335 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2336 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2337 SSL_R_DH_KEY_TOO_SMALL);
2340 if (s->s3->tmp.pkey != NULL) {
2341 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2342 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2343 ERR_R_INTERNAL_ERROR);
2347 s->s3->tmp.pkey = ssl_generate_pkey(pkdhp);
2348 if (s->s3->tmp.pkey == NULL) {
2349 /* SSLfatal() already called */
2353 dh = EVP_PKEY_get0_DH(s->s3->tmp.pkey);
2355 EVP_PKEY_free(pkdh);
2358 DH_get0_pqg(dh, &r[0], NULL, &r[1]);
2359 DH_get0_key(dh, &r[2], NULL);
2362 #ifndef OPENSSL_NO_EC
2363 if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
2365 if (s->s3->tmp.pkey != NULL) {
2366 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2367 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2368 ERR_R_INTERNAL_ERROR);
2372 /* Get NID of appropriate shared curve */
2373 curve_id = tls1_shared_group(s, -2);
2374 if (curve_id == 0) {
2375 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2376 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2377 SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
2380 s->s3->tmp.pkey = ssl_generate_pkey_group(s, curve_id);
2381 /* Generate a new key for this curve */
2382 if (s->s3->tmp.pkey == NULL) {
2383 /* SSLfatal() already called */
2387 /* Encode the public key. */
2388 encodedlen = EVP_PKEY_get1_tls_encodedpoint(s->s3->tmp.pkey,
2390 if (encodedlen == 0) {
2391 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2392 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EC_LIB);
2397 * We'll generate the serverKeyExchange message explicitly so we
2398 * can set these to NULLs
2405 #endif /* !OPENSSL_NO_EC */
2406 #ifndef OPENSSL_NO_SRP
2407 if (type & SSL_kSRP) {
2408 if ((s->srp_ctx.N == NULL) ||
2409 (s->srp_ctx.g == NULL) ||
2410 (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
2411 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2412 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2413 SSL_R_MISSING_SRP_PARAM);
2416 r[0] = s->srp_ctx.N;
2417 r[1] = s->srp_ctx.g;
2418 r[2] = s->srp_ctx.s;
2419 r[3] = s->srp_ctx.B;
2423 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2424 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2425 SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
2429 if (((s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP)) != 0)
2430 || ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_PSK)) != 0) {
2432 } else if (lu == NULL) {
2433 SSLfatal(s, SSL_AD_DECODE_ERROR,
2434 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2438 #ifndef OPENSSL_NO_PSK
2439 if (type & SSL_PSK) {
2440 size_t len = (s->cert->psk_identity_hint == NULL)
2441 ? 0 : strlen(s->cert->psk_identity_hint);
2444 * It should not happen that len > PSK_MAX_IDENTITY_LEN - we already
2445 * checked this when we set the identity hint - but just in case
2447 if (len > PSK_MAX_IDENTITY_LEN
2448 || !WPACKET_sub_memcpy_u16(pkt, s->cert->psk_identity_hint,
2450 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2451 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2452 ERR_R_INTERNAL_ERROR);
2458 for (i = 0; i < 4 && r[i] != NULL; i++) {
2459 unsigned char *binval;
2462 #ifndef OPENSSL_NO_SRP
2463 if ((i == 2) && (type & SSL_kSRP)) {
2464 res = WPACKET_start_sub_packet_u8(pkt);
2467 res = WPACKET_start_sub_packet_u16(pkt);
2470 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2471 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2472 ERR_R_INTERNAL_ERROR);
2476 #ifndef OPENSSL_NO_DH
2478 * for interoperability with some versions of the Microsoft TLS
2479 * stack, we need to zero pad the DHE pub key to the same length
2482 if ((i == 2) && (type & (SSL_kDHE | SSL_kDHEPSK))) {
2483 size_t len = BN_num_bytes(r[0]) - BN_num_bytes(r[2]);
2486 if (!WPACKET_allocate_bytes(pkt, len, &binval)) {
2487 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2488 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2489 ERR_R_INTERNAL_ERROR);
2492 memset(binval, 0, len);
2496 if (!WPACKET_allocate_bytes(pkt, BN_num_bytes(r[i]), &binval)
2497 || !WPACKET_close(pkt)) {
2498 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2499 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2500 ERR_R_INTERNAL_ERROR);
2504 BN_bn2bin(r[i], binval);
2507 #ifndef OPENSSL_NO_EC
2508 if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
2510 * We only support named (not generic) curves. In this situation, the
2511 * ServerKeyExchange message has: [1 byte CurveType], [2 byte CurveName]
2512 * [1 byte length of encoded point], followed by the actual encoded
2515 if (!WPACKET_put_bytes_u8(pkt, NAMED_CURVE_TYPE)
2516 || !WPACKET_put_bytes_u8(pkt, 0)
2517 || !WPACKET_put_bytes_u8(pkt, curve_id)
2518 || !WPACKET_sub_memcpy_u8(pkt, encodedPoint, encodedlen)) {
2519 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2520 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2521 ERR_R_INTERNAL_ERROR);
2524 OPENSSL_free(encodedPoint);
2525 encodedPoint = NULL;
2531 EVP_PKEY *pkey = s->s3->tmp.cert->privatekey;
2533 unsigned char *sigbytes1, *sigbytes2, *tbs;
2534 size_t siglen, tbslen;
2537 if (pkey == NULL || !tls1_lookup_md(lu, &md)) {
2538 /* Should never happen */
2539 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2540 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2541 ERR_R_INTERNAL_ERROR);
2545 * n is the length of the params, they start at &(d[4]) and p
2546 * points to the space at the end.
2549 /* Get length of the parameters we have written above */
2550 if (!WPACKET_get_length(pkt, ¶mlen)) {
2551 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2552 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2553 ERR_R_INTERNAL_ERROR);
2556 /* send signature algorithm */
2557 if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
2558 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2559 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2560 ERR_R_INTERNAL_ERROR);
2564 * Create the signature. We don't know the actual length of the sig
2565 * until after we've created it, so we reserve enough bytes for it
2566 * up front, and then properly allocate them in the WPACKET
2569 siglen = EVP_PKEY_size(pkey);
2570 if (!WPACKET_sub_reserve_bytes_u16(pkt, siglen, &sigbytes1)
2571 || EVP_DigestSignInit(md_ctx, &pctx, md, NULL, pkey) <= 0) {
2572 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2573 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2574 ERR_R_INTERNAL_ERROR);
2577 if (lu->sig == EVP_PKEY_RSA_PSS) {
2578 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
2579 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, RSA_PSS_SALTLEN_DIGEST) <= 0) {
2580 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2581 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2586 tbslen = construct_key_exchange_tbs(s, &tbs,
2587 s->init_buf->data + paramoffset,
2590 /* SSLfatal() already called */
2593 rv = EVP_DigestSign(md_ctx, sigbytes1, &siglen, tbs, tbslen);
2595 if (rv <= 0 || !WPACKET_sub_allocate_bytes_u16(pkt, siglen, &sigbytes2)
2596 || sigbytes1 != sigbytes2) {
2597 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2598 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2599 ERR_R_INTERNAL_ERROR);
2604 EVP_MD_CTX_free(md_ctx);
2607 #ifndef OPENSSL_NO_DH
2608 EVP_PKEY_free(pkdh);
2610 #ifndef OPENSSL_NO_EC
2611 OPENSSL_free(encodedPoint);
2613 EVP_MD_CTX_free(md_ctx);
2617 int tls_construct_certificate_request(SSL *s, WPACKET *pkt)
2619 if (SSL_IS_TLS13(s)) {
2620 /* TODO(TLS1.3) for now send empty request context */
2621 if (!WPACKET_put_bytes_u8(pkt, 0)) {
2622 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2623 SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2624 ERR_R_INTERNAL_ERROR);
2628 if (!tls_construct_extensions(s, pkt,
2629 SSL_EXT_TLS1_3_CERTIFICATE_REQUEST, NULL,
2631 /* SSLfatal() already called */
2637 /* get the list of acceptable cert types */
2638 if (!WPACKET_start_sub_packet_u8(pkt)
2639 || !ssl3_get_req_cert_type(s, pkt) || !WPACKET_close(pkt)) {
2640 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2641 SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR);
2645 if (SSL_USE_SIGALGS(s)) {
2646 const uint16_t *psigs;
2647 size_t nl = tls12_get_psigalgs(s, 1, &psigs);
2649 if (!WPACKET_start_sub_packet_u16(pkt)
2650 || !WPACKET_set_flags(pkt, WPACKET_FLAGS_NON_ZERO_LENGTH)
2651 || !tls12_copy_sigalgs(s, pkt, psigs, nl)
2652 || !WPACKET_close(pkt)) {
2653 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2654 SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2655 ERR_R_INTERNAL_ERROR);
2660 if (!construct_ca_names(s, pkt)) {
2661 /* SSLfatal() already called */
2666 s->s3->tmp.cert_request = 1;
2670 static int tls_process_cke_psk_preamble(SSL *s, PACKET *pkt)
2672 #ifndef OPENSSL_NO_PSK
2673 unsigned char psk[PSK_MAX_PSK_LEN];
2675 PACKET psk_identity;
2677 if (!PACKET_get_length_prefixed_2(pkt, &psk_identity)) {
2678 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2679 SSL_R_LENGTH_MISMATCH);
2682 if (PACKET_remaining(&psk_identity) > PSK_MAX_IDENTITY_LEN) {
2683 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2684 SSL_R_DATA_LENGTH_TOO_LONG);
2687 if (s->psk_server_callback == NULL) {
2688 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2689 SSL_R_PSK_NO_SERVER_CB);
2693 if (!PACKET_strndup(&psk_identity, &s->session->psk_identity)) {
2694 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2695 ERR_R_INTERNAL_ERROR);
2699 psklen = s->psk_server_callback(s, s->session->psk_identity,
2702 if (psklen > PSK_MAX_PSK_LEN) {
2703 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2704 ERR_R_INTERNAL_ERROR);
2706 } else if (psklen == 0) {
2708 * PSK related to the given identity not found
2710 SSLfatal(s, SSL_AD_UNKNOWN_PSK_IDENTITY,
2711 SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2712 SSL_R_PSK_IDENTITY_NOT_FOUND);
2716 OPENSSL_free(s->s3->tmp.psk);
2717 s->s3->tmp.psk = OPENSSL_memdup(psk, psklen);
2718 OPENSSL_cleanse(psk, psklen);
2720 if (s->s3->tmp.psk == NULL) {
2721 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2722 SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, ERR_R_MALLOC_FAILURE);
2726 s->s3->tmp.psklen = psklen;
2730 /* Should never happen */
2731 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2732 ERR_R_INTERNAL_ERROR);
2737 static int tls_process_cke_rsa(SSL *s, PACKET *pkt)
2739 #ifndef OPENSSL_NO_RSA
2740 unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2742 unsigned char decrypt_good, version_good;
2743 size_t j, padding_len;
2744 PACKET enc_premaster;
2746 unsigned char *rsa_decrypt = NULL;
2749 rsa = EVP_PKEY_get0_RSA(s->cert->pkeys[SSL_PKEY_RSA].privatekey);
2751 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
2752 SSL_R_MISSING_RSA_CERTIFICATE);
2756 /* SSLv3 and pre-standard DTLS omit the length bytes. */
2757 if (s->version == SSL3_VERSION || s->version == DTLS1_BAD_VER) {
2758 enc_premaster = *pkt;
2760 if (!PACKET_get_length_prefixed_2(pkt, &enc_premaster)
2761 || PACKET_remaining(pkt) != 0) {
2762 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
2763 SSL_R_LENGTH_MISMATCH);
2769 * We want to be sure that the plaintext buffer size makes it safe to
2770 * iterate over the entire size of a premaster secret
2771 * (SSL_MAX_MASTER_KEY_LENGTH). Reject overly short RSA keys because
2772 * their ciphertext cannot accommodate a premaster secret anyway.
2774 if (RSA_size(rsa) < SSL_MAX_MASTER_KEY_LENGTH) {
2775 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
2776 RSA_R_KEY_SIZE_TOO_SMALL);
2780 rsa_decrypt = OPENSSL_malloc(RSA_size(rsa));
2781 if (rsa_decrypt == NULL) {
2782 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
2783 ERR_R_MALLOC_FAILURE);
2788 * We must not leak whether a decryption failure occurs because of
2789 * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
2790 * section 7.4.7.1). The code follows that advice of the TLS RFC and
2791 * generates a random premaster secret for the case that the decrypt
2792 * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
2795 if (ssl_randbytes(s, rand_premaster_secret,
2796 sizeof(rand_premaster_secret)) <= 0) {
2797 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
2798 ERR_R_INTERNAL_ERROR);
2803 * Decrypt with no padding. PKCS#1 padding will be removed as part of
2804 * the timing-sensitive code below.
2806 /* TODO(size_t): Convert this function */
2807 decrypt_len = (int)RSA_private_decrypt((int)PACKET_remaining(&enc_premaster),
2808 PACKET_data(&enc_premaster),
2809 rsa_decrypt, rsa, RSA_NO_PADDING);
2810 if (decrypt_len < 0) {
2811 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
2812 ERR_R_INTERNAL_ERROR);
2816 /* Check the padding. See RFC 3447, section 7.2.2. */
2819 * The smallest padded premaster is 11 bytes of overhead. Small keys
2820 * are publicly invalid, so this may return immediately. This ensures
2821 * PS is at least 8 bytes.
2823 if (decrypt_len < 11 + SSL_MAX_MASTER_KEY_LENGTH) {
2824 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
2825 SSL_R_DECRYPTION_FAILED);
2829 padding_len = decrypt_len - SSL_MAX_MASTER_KEY_LENGTH;
2830 decrypt_good = constant_time_eq_int_8(rsa_decrypt[0], 0) &
2831 constant_time_eq_int_8(rsa_decrypt[1], 2);
2832 for (j = 2; j < padding_len - 1; j++) {
2833 decrypt_good &= ~constant_time_is_zero_8(rsa_decrypt[j]);
2835 decrypt_good &= constant_time_is_zero_8(rsa_decrypt[padding_len - 1]);
2838 * If the version in the decrypted pre-master secret is correct then
2839 * version_good will be 0xff, otherwise it'll be zero. The
2840 * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
2841 * (http://eprint.iacr.org/2003/052/) exploits the version number
2842 * check as a "bad version oracle". Thus version checks are done in
2843 * constant time and are treated like any other decryption error.
2846 constant_time_eq_8(rsa_decrypt[padding_len],
2847 (unsigned)(s->client_version >> 8));
2849 constant_time_eq_8(rsa_decrypt[padding_len + 1],
2850 (unsigned)(s->client_version & 0xff));
2853 * The premaster secret must contain the same version number as the
2854 * ClientHello to detect version rollback attacks (strangely, the
2855 * protocol does not offer such protection for DH ciphersuites).
2856 * However, buggy clients exist that send the negotiated protocol
2857 * version instead if the server does not support the requested
2858 * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
2861 if (s->options & SSL_OP_TLS_ROLLBACK_BUG) {
2862 unsigned char workaround_good;
2863 workaround_good = constant_time_eq_8(rsa_decrypt[padding_len],
2864 (unsigned)(s->version >> 8));
2866 constant_time_eq_8(rsa_decrypt[padding_len + 1],
2867 (unsigned)(s->version & 0xff));
2868 version_good |= workaround_good;
2872 * Both decryption and version must be good for decrypt_good to
2873 * remain non-zero (0xff).
2875 decrypt_good &= version_good;
2878 * Now copy rand_premaster_secret over from p using
2879 * decrypt_good_mask. If decryption failed, then p does not
2880 * contain valid plaintext, however, a check above guarantees
2881 * it is still sufficiently large to read from.
2883 for (j = 0; j < sizeof(rand_premaster_secret); j++) {
2884 rsa_decrypt[padding_len + j] =
2885 constant_time_select_8(decrypt_good,
2886 rsa_decrypt[padding_len + j],
2887 rand_premaster_secret[j]);
2890 if (!ssl_generate_master_secret(s, rsa_decrypt + padding_len,
2891 sizeof(rand_premaster_secret), 0)) {
2892 /* SSLfatal() already called */
2898 OPENSSL_free(rsa_decrypt);
2901 /* Should never happen */
2902 *al = SSL_AD_INTERNAL_ERROR;
2903 SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, ERR_R_INTERNAL_ERROR);
2908 static int tls_process_cke_dhe(SSL *s, PACKET *pkt)
2910 #ifndef OPENSSL_NO_DH
2911 EVP_PKEY *skey = NULL;
2915 const unsigned char *data;
2916 EVP_PKEY *ckey = NULL;
2919 if (!PACKET_get_net_2(pkt, &i) || PACKET_remaining(pkt) != i) {
2920 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
2921 SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2924 skey = s->s3->tmp.pkey;
2926 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
2927 SSL_R_MISSING_TMP_DH_KEY);
2931 if (PACKET_remaining(pkt) == 0L) {
2932 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
2933 SSL_R_MISSING_TMP_DH_KEY);
2936 if (!PACKET_get_bytes(pkt, &data, i)) {
2937 /* We already checked we have enough data */
2938 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
2939 ERR_R_INTERNAL_ERROR);
2942 ckey = EVP_PKEY_new();
2943 if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) == 0) {
2944 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
2948 cdh = EVP_PKEY_get0_DH(ckey);
2949 pub_key = BN_bin2bn(data, i, NULL);
2951 if (pub_key == NULL || !DH_set0_key(cdh, pub_key, NULL)) {
2952 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
2953 ERR_R_INTERNAL_ERROR);
2954 if (pub_key != NULL)
2959 if (ssl_derive(s, skey, ckey, 1) == 0) {
2960 /* SSLfatal() already called */
2965 EVP_PKEY_free(s->s3->tmp.pkey);
2966 s->s3->tmp.pkey = NULL;
2968 EVP_PKEY_free(ckey);
2971 /* Should never happen */
2972 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
2973 ERR_R_INTERNAL_ERROR);
2978 static int tls_process_cke_ecdhe(SSL *s, PACKET *pkt)
2980 #ifndef OPENSSL_NO_EC
2981 EVP_PKEY *skey = s->s3->tmp.pkey;
2982 EVP_PKEY *ckey = NULL;
2985 if (PACKET_remaining(pkt) == 0L) {
2986 /* We don't support ECDH client auth */
2987 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_PROCESS_CKE_ECDHE,
2988 SSL_R_MISSING_TMP_ECDH_KEY);
2992 const unsigned char *data;
2995 * Get client's public key from encoded point in the
2996 * ClientKeyExchange message.
2999 /* Get encoded point length */
3000 if (!PACKET_get_1(pkt, &i) || !PACKET_get_bytes(pkt, &data, i)
3001 || PACKET_remaining(pkt) != 0) {
3002 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_ECDHE,
3003 SSL_R_LENGTH_MISMATCH);
3006 ckey = EVP_PKEY_new();
3007 if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) <= 0) {
3008 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_ECDHE,
3012 if (EVP_PKEY_set1_tls_encodedpoint(ckey, data, i) == 0) {
3013 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_ECDHE,
3019 if (ssl_derive(s, skey, ckey, 1) == 0) {
3020 /* SSLfatal() already called */
3025 EVP_PKEY_free(s->s3->tmp.pkey);
3026 s->s3->tmp.pkey = NULL;
3028 EVP_PKEY_free(ckey);
3032 /* Should never happen */
3033 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_ECDHE,
3034 ERR_R_INTERNAL_ERROR);
3039 static int tls_process_cke_srp(SSL *s, PACKET *pkt)
3041 #ifndef OPENSSL_NO_SRP
3043 const unsigned char *data;
3045 if (!PACKET_get_net_2(pkt, &i)
3046 || !PACKET_get_bytes(pkt, &data, i)) {
3047 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_SRP,
3048 SSL_R_BAD_SRP_A_LENGTH);
3051 if ((s->srp_ctx.A = BN_bin2bn(data, i, NULL)) == NULL) {
3052 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_SRP,
3056 if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0 || BN_is_zero(s->srp_ctx.A)) {
3057 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PROCESS_CKE_SRP,
3058 SSL_R_BAD_SRP_PARAMETERS);
3061 OPENSSL_free(s->session->srp_username);
3062 s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);
3063 if (s->session->srp_username == NULL) {
3064 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_SRP,
3065 ERR_R_MALLOC_FAILURE);
3069 if (!srp_generate_server_master_secret(s)) {
3070 /* SSLfatal() already called */
3076 /* Should never happen */
3077 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_SRP,
3078 ERR_R_INTERNAL_ERROR);
3083 static int tls_process_cke_gost(SSL *s, PACKET *pkt)
3085 #ifndef OPENSSL_NO_GOST
3086 EVP_PKEY_CTX *pkey_ctx;
3087 EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
3088 unsigned char premaster_secret[32];
3089 const unsigned char *start;
3090 size_t outlen = 32, inlen;
3091 unsigned long alg_a;
3094 size_t sess_key_len;
3095 const unsigned char *data;
3098 /* Get our certificate private key */
3099 alg_a = s->s3->tmp.new_cipher->algorithm_auth;
3100 if (alg_a & SSL_aGOST12) {
3102 * New GOST ciphersuites have SSL_aGOST01 bit too
3104 pk = s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey;
3106 pk = s->cert->pkeys[SSL_PKEY_GOST12_256].privatekey;
3109 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
3111 } else if (alg_a & SSL_aGOST01) {
3112 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
3115 pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
3116 if (pkey_ctx == NULL) {
3117 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3118 ERR_R_MALLOC_FAILURE);
3121 if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {
3122 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3123 ERR_R_INTERNAL_ERROR);
3127 * If client certificate is present and is of the same type, maybe
3128 * use it for key exchange. Don't mind errors from
3129 * EVP_PKEY_derive_set_peer, because it is completely valid to use a
3130 * client certificate for authorization only.
3132 client_pub_pkey = X509_get0_pubkey(s->session->peer);
3133 if (client_pub_pkey) {
3134 if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
3137 /* Decrypt session key */
3138 sess_key_len = PACKET_remaining(pkt);
3139 if (!PACKET_get_bytes(pkt, &data, sess_key_len)) {
3140 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3141 ERR_R_INTERNAL_ERROR);
3144 /* TODO(size_t): Convert this function */
3145 if (ASN1_get_object((const unsigned char **)&data, &Tlen, &Ttag,
3146 &Tclass, (long)sess_key_len) != V_ASN1_CONSTRUCTED
3147 || Ttag != V_ASN1_SEQUENCE || Tclass != V_ASN1_UNIVERSAL) {
3148 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3149 SSL_R_DECRYPTION_FAILED);
3154 if (EVP_PKEY_decrypt(pkey_ctx, premaster_secret, &outlen, start,
3156 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3157 SSL_R_DECRYPTION_FAILED);
3160 /* Generate master secret */
3161 if (!ssl_generate_master_secret(s, premaster_secret,
3162 sizeof(premaster_secret), 0)) {
3163 /* SSLfatal() already called */
3166 /* Check if pubkey from client certificate was used */
3167 if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2,
3169 s->statem.no_cert_verify = 1;
3173 EVP_PKEY_CTX_free(pkey_ctx);
3176 /* Should never happen */
3177 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3178 ERR_R_INTERNAL_ERROR);
3183 MSG_PROCESS_RETURN tls_process_client_key_exchange(SSL *s, PACKET *pkt)
3185 unsigned long alg_k;
3187 alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
3189 /* For PSK parse and retrieve identity, obtain PSK key */
3190 if ((alg_k & SSL_PSK) && !tls_process_cke_psk_preamble(s, pkt)) {
3191 /* SSLfatal() already called */
3195 if (alg_k & SSL_kPSK) {
3196 /* Identity extracted earlier: should be nothing left */
3197 if (PACKET_remaining(pkt) != 0) {
3198 SSLfatal(s, SSL_AD_DECODE_ERROR,
3199 SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
3200 SSL_R_LENGTH_MISMATCH);
3203 /* PSK handled by ssl_generate_master_secret */
3204 if (!ssl_generate_master_secret(s, NULL, 0, 0)) {
3205 /* SSLfatal() already called */
3208 } else if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
3209 if (!tls_process_cke_rsa(s, pkt)) {
3210 /* SSLfatal() already called */
3213 } else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
3214 if (!tls_process_cke_dhe(s, pkt)) {
3215 /* SSLfatal() already called */
3218 } else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
3219 if (!tls_process_cke_ecdhe(s, pkt)) {
3220 /* SSLfatal() already called */
3223 } else if (alg_k & SSL_kSRP) {
3224 if (!tls_process_cke_srp(s, pkt)) {
3225 /* SSLfatal() already called */
3228 } else if (alg_k & SSL_kGOST) {
3229 if (!tls_process_cke_gost(s, pkt)) {
3230 /* SSLfatal() already called */
3234 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3235 SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
3236 SSL_R_UNKNOWN_CIPHER_TYPE);
3240 return MSG_PROCESS_CONTINUE_PROCESSING;
3242 #ifndef OPENSSL_NO_PSK
3243 OPENSSL_clear_free(s->s3->tmp.psk, s->s3->tmp.psklen);
3244 s->s3->tmp.psk = NULL;
3246 return MSG_PROCESS_ERROR;
3249 WORK_STATE tls_post_process_client_key_exchange(SSL *s, WORK_STATE wst)
3251 #ifndef OPENSSL_NO_SCTP
3252 if (wst == WORK_MORE_A) {
3253 if (SSL_IS_DTLS(s)) {
3254 unsigned char sctpauthkey[64];
3255 char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
3257 * Add new shared key for SCTP-Auth, will be ignored if no SCTP
3260 memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
3261 sizeof(DTLS1_SCTP_AUTH_LABEL));
3263 if (SSL_export_keying_material(s, sctpauthkey,
3264 sizeof(sctpauthkey), labelbuffer,
3265 sizeof(labelbuffer), NULL, 0,
3267 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3268 SSL_F_TLS_POST_PROCESS_CLIENT_KEY_EXCHANGE,
3269 ERR_R_INTERNAL_ERROR);
3273 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
3274 sizeof(sctpauthkey), sctpauthkey);
3279 if (s->statem.no_cert_verify || !s->session->peer) {
3281 * No certificate verify or no peer certificate so we no longer need
3282 * the handshake_buffer
3284 if (!ssl3_digest_cached_records(s, 0)) {
3285 /* SSLfatal() already called */
3288 return WORK_FINISHED_CONTINUE;
3290 if (!s->s3->handshake_buffer) {
3291 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3292 SSL_F_TLS_POST_PROCESS_CLIENT_KEY_EXCHANGE,
3293 ERR_R_INTERNAL_ERROR);
3297 * For sigalgs freeze the handshake buffer. If we support
3298 * extms we've done this already so this is a no-op
3300 if (!ssl3_digest_cached_records(s, 1)) {
3301 /* SSLfatal() already called */
3306 return WORK_FINISHED_CONTINUE;
3309 MSG_PROCESS_RETURN tls_process_client_certificate(SSL *s, PACKET *pkt)
3312 MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
3314 unsigned long l, llen;
3315 const unsigned char *certstart, *certbytes;
3316 STACK_OF(X509) *sk = NULL;
3317 PACKET spkt, context;
3320 if ((sk = sk_X509_new_null()) == NULL) {
3321 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3322 ERR_R_MALLOC_FAILURE);
3326 /* TODO(TLS1.3): For now we ignore the context. We need to verify this */
3327 if ((SSL_IS_TLS13(s) && !PACKET_get_length_prefixed_1(pkt, &context))
3328 || !PACKET_get_net_3(pkt, &llen)
3329 || !PACKET_get_sub_packet(pkt, &spkt, llen)
3330 || PACKET_remaining(pkt) != 0) {
3331 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3332 SSL_R_LENGTH_MISMATCH);
3336 for (chainidx = 0; PACKET_remaining(&spkt) > 0; chainidx++) {
3337 if (!PACKET_get_net_3(&spkt, &l)
3338 || !PACKET_get_bytes(&spkt, &certbytes, l)) {
3339 SSLfatal(s, SSL_AD_DECODE_ERROR,
3340 SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3341 SSL_R_CERT_LENGTH_MISMATCH);
3345 certstart = certbytes;
3346 x = d2i_X509(NULL, (const unsigned char **)&certbytes, l);
3348 SSLfatal(s, SSL_AD_DECODE_ERROR,
3349 SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_ASN1_LIB);
3352 if (certbytes != (certstart + l)) {
3353 SSLfatal(s, SSL_AD_DECODE_ERROR,
3354 SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3355 SSL_R_CERT_LENGTH_MISMATCH);
3359 if (SSL_IS_TLS13(s)) {
3360 RAW_EXTENSION *rawexts = NULL;
3363 if (!PACKET_get_length_prefixed_2(&spkt, &extensions)) {
3364 SSLfatal(s, SSL_AD_DECODE_ERROR,
3365 SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3369 if (!tls_collect_extensions(s, &extensions,
3370 SSL_EXT_TLS1_3_CERTIFICATE, &rawexts,
3371 NULL, chainidx == 0)
3372 || !tls_parse_all_extensions(s, SSL_EXT_TLS1_3_CERTIFICATE,
3373 rawexts, x, chainidx,
3374 PACKET_remaining(&spkt) == 0)) {
3375 OPENSSL_free(rawexts);
3378 OPENSSL_free(rawexts);
3381 if (!sk_X509_push(sk, x)) {
3382 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3383 SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3384 ERR_R_MALLOC_FAILURE);
3390 if (sk_X509_num(sk) <= 0) {
3391 /* TLS does not mind 0 certs returned */
3392 if (s->version == SSL3_VERSION) {
3393 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
3394 SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3395 SSL_R_NO_CERTIFICATES_RETURNED);
3398 /* Fail for TLS only if we required a certificate */
3399 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3400 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3401 SSLfatal(s, SSL_AD_CERTIFICATE_REQUIRED,
3402 SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3403 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3406 /* No client certificate so digest cached records */
3407 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s, 0)) {
3408 /* SSLfatal() already called */
3413 i = ssl_verify_cert_chain(s, sk);
3415 SSLfatal(s, ssl_verify_alarm_type(s->verify_result),
3416 SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3417 SSL_R_CERTIFICATE_VERIFY_FAILED);
3421 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
3422 SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, i);
3425 pkey = X509_get0_pubkey(sk_X509_value(sk, 0));
3427 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
3428 SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3429 SSL_R_UNKNOWN_CERTIFICATE_TYPE);
3434 X509_free(s->session->peer);
3435 s->session->peer = sk_X509_shift(sk);
3436 s->session->verify_result = s->verify_result;
3438 sk_X509_pop_free(s->session->peer_chain, X509_free);
3439 s->session->peer_chain = sk;
3442 * Freeze the handshake buffer. For <TLS1.3 we do this after the CKE
3445 if (SSL_IS_TLS13(s) && !ssl3_digest_cached_records(s, 1)) {
3446 /* SSLfatal() already called */
3451 * Inconsistency alert: cert_chain does *not* include the peer's own
3452 * certificate, while we do include it in statem_clnt.c
3456 /* Save the current hash state for when we receive the CertificateVerify */
3458 && !ssl_handshake_hash(s, s->cert_verify_hash,
3459 sizeof(s->cert_verify_hash),
3460 &s->cert_verify_hash_len)) {
3461 /* SSLfatal() already called */
3465 ret = MSG_PROCESS_CONTINUE_READING;
3469 sk_X509_pop_free(sk, X509_free);
3473 int tls_construct_server_certificate(SSL *s, WPACKET *pkt)
3475 CERT_PKEY *cpk = s->s3->tmp.cert;
3478 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3479 SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3484 * In TLSv1.3 the certificate chain is always preceded by a 0 length context
3485 * for the server Certificate message
3487 if (SSL_IS_TLS13(s) && !WPACKET_put_bytes_u8(pkt, 0)) {
3488 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3489 SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3492 if (!ssl3_output_cert_chain(s, pkt, cpk)) {
3493 /* SSLfatal() already called */
3500 int tls_construct_new_session_ticket(SSL *s, WPACKET *pkt)
3502 unsigned char *senc = NULL;
3503 EVP_CIPHER_CTX *ctx = NULL;
3504 HMAC_CTX *hctx = NULL;
3505 unsigned char *p, *encdata1, *encdata2, *macdata1, *macdata2;
3506 const unsigned char *const_p;
3507 int len, slen_full, slen, lenfinal;
3510 SSL_CTX *tctx = s->session_ctx;
3511 unsigned char iv[EVP_MAX_IV_LENGTH];
3512 unsigned char key_name[TLSEXT_KEYNAME_LENGTH];
3514 size_t macoffset, macendoffset;
3516 unsigned char age_add_c[sizeof(uint32_t)];
3520 if (SSL_IS_TLS13(s)) {
3521 if (ssl_randbytes(s, age_add_u.age_add_c, sizeof(age_add_u)) <= 0) {
3522 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3523 SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET,
3524 ERR_R_INTERNAL_ERROR);
3527 s->session->ext.tick_age_add = age_add_u.age_add;
3529 * ticket_nonce is set to a single 0 byte because we only ever send a
3530 * single ticket per connection. IMPORTANT: If we ever support multiple
3531 * tickets per connection then this will need to be changed.
3533 OPENSSL_free(s->session->ext.tick_nonce);
3534 s->session->ext.tick_nonce = OPENSSL_zalloc(sizeof(char));
3535 if (s->session->ext.tick_nonce == NULL) {
3536 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3537 SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET,
3538 ERR_R_MALLOC_FAILURE);
3541 s->session->ext.tick_nonce_len = 1;
3542 s->session->time = (long)time(NULL);
3543 if (s->s3->alpn_selected != NULL) {
3544 OPENSSL_free(s->session->ext.alpn_selected);
3545 s->session->ext.alpn_selected =
3546 OPENSSL_memdup(s->s3->alpn_selected, s->s3->alpn_selected_len);
3547 if (s->session->ext.alpn_selected == NULL) {
3548 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3549 SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET,
3550 ERR_R_MALLOC_FAILURE);
3553 s->session->ext.alpn_selected_len = s->s3->alpn_selected_len;
3555 s->session->ext.max_early_data = s->max_early_data;
3558 /* get session encoding length */
3559 slen_full = i2d_SSL_SESSION(s->session, NULL);
3561 * Some length values are 16 bits, so forget it if session is too
3564 if (slen_full == 0 || slen_full > 0xFF00) {
3565 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3566 SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_INTERNAL_ERROR);
3569 senc = OPENSSL_malloc(slen_full);
3571 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3572 SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
3576 ctx = EVP_CIPHER_CTX_new();
3577 hctx = HMAC_CTX_new();
3578 if (ctx == NULL || hctx == NULL) {
3579 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3580 SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
3585 if (!i2d_SSL_SESSION(s->session, &p)) {
3586 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3587 SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_INTERNAL_ERROR);
3592 * create a fresh copy (not shared with other threads) to clean up
3595 sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3597 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3598 SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_INTERNAL_ERROR);
3601 sess->session_id_length = 0; /* ID is irrelevant for the ticket */
3603 slen = i2d_SSL_SESSION(sess, NULL);
3604 if (slen == 0 || slen > slen_full) {
3605 /* shouldn't ever happen */
3606 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3607 SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_INTERNAL_ERROR);
3608 SSL_SESSION_free(sess);
3612 if (!i2d_SSL_SESSION(sess, &p)) {
3613 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3614 SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_INTERNAL_ERROR);
3615 SSL_SESSION_free(sess);
3618 SSL_SESSION_free(sess);
3621 * Initialize HMAC and cipher contexts. If callback present it does
3622 * all the work otherwise use generated values from parent ctx.
3624 if (tctx->ext.ticket_key_cb) {
3625 /* if 0 is returned, write an empty ticket */
3626 int ret = tctx->ext.ticket_key_cb(s, key_name, iv, ctx,
3631 /* Put timeout and length */
3632 if (!WPACKET_put_bytes_u32(pkt, 0)
3633 || !WPACKET_put_bytes_u16(pkt, 0)) {
3634 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3635 SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET,
3636 ERR_R_INTERNAL_ERROR);
3640 EVP_CIPHER_CTX_free(ctx);
3641 HMAC_CTX_free(hctx);
3645 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3646 SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET,
3647 SSL_R_CALLBACK_FAILED);
3650 iv_len = EVP_CIPHER_CTX_iv_length(ctx);
3652 const EVP_CIPHER *cipher = EVP_aes_256_cbc();
3654 iv_len = EVP_CIPHER_iv_length(cipher);
3655 if (ssl_randbytes(s, iv, iv_len) <= 0
3656 || !EVP_EncryptInit_ex(ctx, cipher, NULL,
3657 tctx->ext.tick_aes_key, iv)
3658 || !HMAC_Init_ex(hctx, tctx->ext.tick_hmac_key,
3659 sizeof(tctx->ext.tick_hmac_key),
3660 EVP_sha256(), NULL)) {
3661 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3662 SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET,
3663 ERR_R_INTERNAL_ERROR);
3666 memcpy(key_name, tctx->ext.tick_key_name,
3667 sizeof(tctx->ext.tick_key_name));
3671 * Ticket lifetime hint: For TLSv1.2 this is advisory only and we leave this
3672 * unspecified for resumed session (for simplicity).
3673 * In TLSv1.3 we reset the "time" field above, and always specify the
3676 if (!WPACKET_put_bytes_u32(pkt,
3677 (s->hit && !SSL_IS_TLS13(s))
3678 ? 0 : s->session->timeout)
3680 && (!WPACKET_put_bytes_u32(pkt, age_add_u.age_add)
3681 || !WPACKET_sub_memcpy_u8(pkt, s->session->ext.tick_nonce,
3682 s->session->ext.tick_nonce_len)))
3683 /* Now the actual ticket data */
3684 || !WPACKET_start_sub_packet_u16(pkt)
3685 || !WPACKET_get_total_written(pkt, &macoffset)
3686 /* Output key name */
3687 || !WPACKET_memcpy(pkt, key_name, sizeof(key_name))
3689 || !WPACKET_memcpy(pkt, iv, iv_len)
3690 || !WPACKET_reserve_bytes(pkt, slen + EVP_MAX_BLOCK_LENGTH,
3692 /* Encrypt session data */
3693 || !EVP_EncryptUpdate(ctx, encdata1, &len, senc, slen)
3694 || !WPACKET_allocate_bytes(pkt, len, &encdata2)
3695 || encdata1 != encdata2
3696 || !EVP_EncryptFinal(ctx, encdata1 + len, &lenfinal)
3697 || !WPACKET_allocate_bytes(pkt, lenfinal, &encdata2)
3698 || encdata1 + len != encdata2
3699 || len + lenfinal > slen + EVP_MAX_BLOCK_LENGTH
3700 || !WPACKET_get_total_written(pkt, &macendoffset)
3701 || !HMAC_Update(hctx,
3702 (unsigned char *)s->init_buf->data + macoffset,
3703 macendoffset - macoffset)
3704 || !WPACKET_reserve_bytes(pkt, EVP_MAX_MD_SIZE, &macdata1)
3705 || !HMAC_Final(hctx, macdata1, &hlen)
3706 || hlen > EVP_MAX_MD_SIZE
3707 || !WPACKET_allocate_bytes(pkt, hlen, &macdata2)
3708 || macdata1 != macdata2
3709 || !WPACKET_close(pkt)) {
3710 SSLerr(SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_INTERNAL_ERROR);
3714 && !tls_construct_extensions(s, pkt,
3715 SSL_EXT_TLS1_3_NEW_SESSION_TICKET,
3717 /* SSLfatal() already called */
3720 EVP_CIPHER_CTX_free(ctx);
3721 HMAC_CTX_free(hctx);
3727 EVP_CIPHER_CTX_free(ctx);
3728 HMAC_CTX_free(hctx);
3733 * In TLSv1.3 this is called from the extensions code, otherwise it is used to
3734 * create a separate message. Returns 1 on success or 0 on failure.
3736 int tls_construct_cert_status_body(SSL *s, WPACKET *pkt)
3738 if (!WPACKET_put_bytes_u8(pkt, s->ext.status_type)
3739 || !WPACKET_sub_memcpy_u24(pkt, s->ext.ocsp.resp,
3740 s->ext.ocsp.resp_len)) {
3741 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_STATUS_BODY, ERR_R_INTERNAL_ERROR);
3748 int tls_construct_cert_status(SSL *s, WPACKET *pkt)
3750 if (!tls_construct_cert_status_body(s, pkt)) {
3751 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
3758 #ifndef OPENSSL_NO_NEXTPROTONEG
3760 * tls_process_next_proto reads a Next Protocol Negotiation handshake message.
3761 * It sets the next_proto member in s if found
3763 MSG_PROCESS_RETURN tls_process_next_proto(SSL *s, PACKET *pkt)
3765 PACKET next_proto, padding;
3766 size_t next_proto_len;
3769 * The payload looks like:
3771 * uint8 proto[proto_len];
3772 * uint8 padding_len;
3773 * uint8 padding[padding_len];
3775 if (!PACKET_get_length_prefixed_1(pkt, &next_proto)
3776 || !PACKET_get_length_prefixed_1(pkt, &padding)
3777 || PACKET_remaining(pkt) > 0) {
3778 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_NEXT_PROTO,
3779 SSL_R_LENGTH_MISMATCH);
3780 return MSG_PROCESS_ERROR;
3783 if (!PACKET_memdup(&next_proto, &s->ext.npn, &next_proto_len)) {
3785 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_NEXT_PROTO,
3786 ERR_R_INTERNAL_ERROR);
3787 return MSG_PROCESS_ERROR;
3790 s->ext.npn_len = (unsigned char)next_proto_len;
3792 return MSG_PROCESS_CONTINUE_READING;
3796 static int tls_construct_encrypted_extensions(SSL *s, WPACKET *pkt)
3798 if (!tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
3800 /* SSLfatal() already called */
3807 static int tls_construct_hello_retry_request(SSL *s, WPACKET *pkt)
3812 * TODO(TLS1.3): Remove the DRAFT version before release
3813 * (should be s->version)
3815 if (!WPACKET_put_bytes_u16(pkt, TLS1_3_VERSION_DRAFT)
3816 || !s->method->put_cipher_by_char(s->s3->tmp.new_cipher, pkt,
3818 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3819 SSL_F_TLS_CONSTRUCT_HELLO_RETRY_REQUEST, ERR_R_INTERNAL_ERROR);
3823 if (!tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST,
3825 /* SSLfatal() already called */
3829 /* Ditch the session. We'll create a new one next time around */
3830 SSL_SESSION_free(s->session);
3835 * Re-initialise the Transcript Hash. We're going to prepopulate it with
3836 * a synthetic message_hash in place of ClientHello1.
3838 if (!create_synthetic_message_hash(s)) {
3839 /* SSLfatal() already called */
3846 MSG_PROCESS_RETURN tls_process_end_of_early_data(SSL *s, PACKET *pkt)
3848 if (PACKET_remaining(pkt) != 0) {
3849 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_END_OF_EARLY_DATA,
3850 SSL_R_LENGTH_MISMATCH);
3851 return MSG_PROCESS_ERROR;
3854 if (s->early_data_state != SSL_EARLY_DATA_READING
3855 && s->early_data_state != SSL_EARLY_DATA_READ_RETRY) {
3856 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_END_OF_EARLY_DATA,
3857 ERR_R_INTERNAL_ERROR);
3858 return MSG_PROCESS_ERROR;
3862 * EndOfEarlyData signals a key change so the end of the message must be on
3863 * a record boundary.
3865 if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
3866 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
3867 SSL_F_TLS_PROCESS_END_OF_EARLY_DATA,
3868 SSL_R_NOT_ON_RECORD_BOUNDARY);
3869 return MSG_PROCESS_ERROR;
3872 s->early_data_state = SSL_EARLY_DATA_FINISHED_READING;
3873 if (!s->method->ssl3_enc->change_cipher_state(s,
3874 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_READ)) {
3875 /* SSLfatal() already called */
3876 return MSG_PROCESS_ERROR;
3879 return MSG_PROCESS_CONTINUE_READING;