2 * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
10 /* ====================================================================
11 * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
13 * Portions of the attached software ("Contribution") are developed by
14 * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
16 * The Contribution is licensed pursuant to the OpenSSL open source
17 * license provided above.
19 * ECC cipher suite support in OpenSSL originally written by
20 * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
23 /* ====================================================================
24 * Copyright 2005 Nokia. All rights reserved.
26 * The portions of the attached software ("Contribution") is developed by
27 * Nokia Corporation and is licensed pursuant to the OpenSSL open source
30 * The Contribution, originally written by Mika Kousa and Pasi Eronen of
31 * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
32 * support (see RFC 4279) to OpenSSL.
34 * No patent licenses or other rights except those expressly stated in
35 * the OpenSSL open source license shall be deemed granted or received
36 * expressly, by implication, estoppel, or otherwise.
38 * No assurances are provided by Nokia that the Contribution does not
39 * infringe the patent or other intellectual property rights of any third
40 * party or that the license provides you with all the necessary rights
41 * to make use of the Contribution.
43 * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
44 * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
45 * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
46 * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
52 #include "../ssl_locl.h"
53 #include "statem_locl.h"
54 #include "internal/constant_time_locl.h"
55 #include <openssl/buffer.h>
56 #include <openssl/rand.h>
57 #include <openssl/objects.h>
58 #include <openssl/evp.h>
59 #include <openssl/hmac.h>
60 #include <openssl/x509.h>
61 #include <openssl/dh.h>
62 #include <openssl/bn.h>
63 #include <openssl/md5.h>
65 static STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list(SSL *s,
66 PACKET *cipher_suites,
67 STACK_OF(SSL_CIPHER) **skp,
68 int sslv2format, int *al);
71 * server_read_transition() encapsulates the logic for the allowed handshake
72 * state transitions when the server is reading messages from the client. The
73 * message type that the client has sent is provided in |mt|. The current state
74 * is in |s->statem.hand_state|.
76 * Valid return values are:
77 * 1: Success (transition allowed)
78 * 0: Error (transition not allowed)
80 int ossl_statem_server_read_transition(SSL *s, int mt)
82 OSSL_STATEM *st = &s->statem;
84 switch(st->hand_state) {
86 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
87 if (mt == SSL3_MT_CLIENT_HELLO) {
88 st->hand_state = TLS_ST_SR_CLNT_HELLO;
93 case TLS_ST_SW_SRVR_DONE:
95 * If we get a CKE message after a ServerDone then either
96 * 1) We didn't request a Certificate
98 * 2) If we did request one then
99 * a) We allow no Certificate to be returned
101 * b) We are running SSL3 (in TLS1.0+ the client must return a 0
102 * list if we requested a certificate)
104 if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE
105 && (!s->s3->tmp.cert_request
106 || (!((s->verify_mode & SSL_VERIFY_PEER) &&
107 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
108 && (s->version == SSL3_VERSION)))) {
109 st->hand_state = TLS_ST_SR_KEY_EXCH;
111 } else if (s->s3->tmp.cert_request) {
112 if (mt == SSL3_MT_CERTIFICATE) {
113 st->hand_state = TLS_ST_SR_CERT;
120 if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) {
121 st->hand_state = TLS_ST_SR_KEY_EXCH;
126 case TLS_ST_SR_KEY_EXCH:
128 * We should only process a CertificateVerify message if we have
129 * received a Certificate from the client. If so then |s->session->peer|
130 * will be non NULL. In some instances a CertificateVerify message is
131 * not required even if the peer has sent a Certificate (e.g. such as in
132 * the case of static DH). In that case |st->no_cert_verify| should be
135 if (s->session->peer == NULL || st->no_cert_verify) {
136 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
138 * For the ECDH ciphersuites when the client sends its ECDH
139 * pub key in a certificate, the CertificateVerify message is
140 * not sent. Also for GOST ciphersuites when the client uses
141 * its key from the certificate for key exchange.
143 st->hand_state = TLS_ST_SR_CHANGE;
147 if (mt == SSL3_MT_CERTIFICATE_VERIFY) {
148 st->hand_state = TLS_ST_SR_CERT_VRFY;
154 case TLS_ST_SR_CERT_VRFY:
155 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
156 st->hand_state = TLS_ST_SR_CHANGE;
161 case TLS_ST_SR_CHANGE:
162 #ifndef OPENSSL_NO_NEXTPROTONEG
163 if (s->s3->next_proto_neg_seen) {
164 if (mt == SSL3_MT_NEXT_PROTO) {
165 st->hand_state = TLS_ST_SR_NEXT_PROTO;
170 if (mt == SSL3_MT_FINISHED) {
171 st->hand_state = TLS_ST_SR_FINISHED;
174 #ifndef OPENSSL_NO_NEXTPROTONEG
179 #ifndef OPENSSL_NO_NEXTPROTONEG
180 case TLS_ST_SR_NEXT_PROTO:
181 if (mt == SSL3_MT_FINISHED) {
182 st->hand_state = TLS_ST_SR_FINISHED;
188 case TLS_ST_SW_FINISHED:
189 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
190 st->hand_state = TLS_ST_SR_CHANGE;
199 /* No valid transition found */
204 * Should we send a ServerKeyExchange message?
206 * Valid return values are:
210 static int send_server_key_exchange(SSL *s)
212 unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
215 * only send a ServerKeyExchange if DH or fortezza but we have a
216 * sign only certificate PSK: may send PSK identity hints For
217 * ECC ciphersuites, we send a serverKeyExchange message only if
218 * the cipher suite is either ECDH-anon or ECDHE. In other cases,
219 * the server certificate contains the server's public key for
222 if (alg_k & (SSL_kDHE|SSL_kECDHE)
224 * PSK: send ServerKeyExchange if PSK identity hint if
227 #ifndef OPENSSL_NO_PSK
228 /* Only send SKE if we have identity hint for plain PSK */
229 || ((alg_k & (SSL_kPSK | SSL_kRSAPSK))
230 && s->cert->psk_identity_hint)
231 /* For other PSK always send SKE */
232 || (alg_k & (SSL_PSK & (SSL_kDHEPSK | SSL_kECDHEPSK)))
234 #ifndef OPENSSL_NO_SRP
235 /* SRP: send ServerKeyExchange */
236 || (alg_k & SSL_kSRP)
246 * Should we send a CertificateRequest message?
248 * Valid return values are:
252 static int send_certificate_request(SSL *s)
255 /* don't request cert unless asked for it: */
256 s->verify_mode & SSL_VERIFY_PEER
258 * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert
259 * during re-negotiation:
261 && ((s->session->peer == NULL) ||
262 !(s->verify_mode & SSL_VERIFY_CLIENT_ONCE))
264 * never request cert in anonymous ciphersuites (see
265 * section "Certificate request" in SSL 3 drafts and in
268 && (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
270 * ... except when the application insists on
271 * verification (against the specs, but statem_clnt.c accepts
274 || (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
275 /* don't request certificate for SRP auth */
276 && !(s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)
278 * With normal PSK Certificates and Certificate Requests
281 && !(s->s3->tmp.new_cipher->algorithm_auth & SSL_aPSK)) {
289 * server_write_transition() works out what handshake state to move to next
290 * when the server is writing messages to be sent to the client.
292 WRITE_TRAN ossl_statem_server_write_transition(SSL *s)
294 OSSL_STATEM *st = &s->statem;
296 switch(st->hand_state) {
298 /* Just go straight to trying to read from the client */;
299 return WRITE_TRAN_FINISHED;
302 /* We must be trying to renegotiate */
303 st->hand_state = TLS_ST_SW_HELLO_REQ;
304 return WRITE_TRAN_CONTINUE;
306 case TLS_ST_SW_HELLO_REQ:
307 st->hand_state = TLS_ST_OK;
308 ossl_statem_set_in_init(s, 0);
309 return WRITE_TRAN_CONTINUE;
311 case TLS_ST_SR_CLNT_HELLO:
312 if (SSL_IS_DTLS(s) && !s->d1->cookie_verified
313 && (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE))
314 st->hand_state = DTLS_ST_SW_HELLO_VERIFY_REQUEST;
316 st->hand_state = TLS_ST_SW_SRVR_HELLO;
317 return WRITE_TRAN_CONTINUE;
319 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
320 return WRITE_TRAN_FINISHED;
322 case TLS_ST_SW_SRVR_HELLO:
324 if (s->tlsext_ticket_expected)
325 st->hand_state = TLS_ST_SW_SESSION_TICKET;
327 st->hand_state = TLS_ST_SW_CHANGE;
329 /* Check if it is anon DH or anon ECDH, */
330 /* normal PSK or SRP */
331 if (!(s->s3->tmp.new_cipher->algorithm_auth &
332 (SSL_aNULL | SSL_aSRP | SSL_aPSK))) {
333 st->hand_state = TLS_ST_SW_CERT;
334 } else if (send_server_key_exchange(s)) {
335 st->hand_state = TLS_ST_SW_KEY_EXCH;
336 } else if (send_certificate_request(s)) {
337 st->hand_state = TLS_ST_SW_CERT_REQ;
339 st->hand_state = TLS_ST_SW_SRVR_DONE;
342 return WRITE_TRAN_CONTINUE;
345 if (s->tlsext_status_expected) {
346 st->hand_state = TLS_ST_SW_CERT_STATUS;
347 return WRITE_TRAN_CONTINUE;
351 case TLS_ST_SW_CERT_STATUS:
352 if (send_server_key_exchange(s)) {
353 st->hand_state = TLS_ST_SW_KEY_EXCH;
354 return WRITE_TRAN_CONTINUE;
358 case TLS_ST_SW_KEY_EXCH:
359 if (send_certificate_request(s)) {
360 st->hand_state = TLS_ST_SW_CERT_REQ;
361 return WRITE_TRAN_CONTINUE;
365 case TLS_ST_SW_CERT_REQ:
366 st->hand_state = TLS_ST_SW_SRVR_DONE;
367 return WRITE_TRAN_CONTINUE;
369 case TLS_ST_SW_SRVR_DONE:
370 return WRITE_TRAN_FINISHED;
372 case TLS_ST_SR_FINISHED:
374 st->hand_state = TLS_ST_OK;
375 ossl_statem_set_in_init(s, 0);
376 return WRITE_TRAN_CONTINUE;
377 } else if (s->tlsext_ticket_expected) {
378 st->hand_state = TLS_ST_SW_SESSION_TICKET;
380 st->hand_state = TLS_ST_SW_CHANGE;
382 return WRITE_TRAN_CONTINUE;
384 case TLS_ST_SW_SESSION_TICKET:
385 st->hand_state = TLS_ST_SW_CHANGE;
386 return WRITE_TRAN_CONTINUE;
388 case TLS_ST_SW_CHANGE:
389 st->hand_state = TLS_ST_SW_FINISHED;
390 return WRITE_TRAN_CONTINUE;
392 case TLS_ST_SW_FINISHED:
394 return WRITE_TRAN_FINISHED;
396 st->hand_state = TLS_ST_OK;
397 ossl_statem_set_in_init(s, 0);
398 return WRITE_TRAN_CONTINUE;
401 /* Shouldn't happen */
402 return WRITE_TRAN_ERROR;
407 * Perform any pre work that needs to be done prior to sending a message from
408 * the server to the client.
410 WORK_STATE ossl_statem_server_pre_work(SSL *s, WORK_STATE wst)
412 OSSL_STATEM *st = &s->statem;
414 switch(st->hand_state) {
415 case TLS_ST_SW_HELLO_REQ:
418 dtls1_clear_record_buffer(s);
421 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
423 if (SSL_IS_DTLS(s)) {
424 dtls1_clear_record_buffer(s);
425 /* We don't buffer this message so don't use the timer */
430 case TLS_ST_SW_SRVR_HELLO:
431 if (SSL_IS_DTLS(s)) {
433 * Messages we write from now on should be bufferred and
434 * retransmitted if necessary, so we need to use the timer now
440 case TLS_ST_SW_SRVR_DONE:
441 #ifndef OPENSSL_NO_SCTP
442 if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s)))
443 return dtls_wait_for_dry(s);
445 return WORK_FINISHED_CONTINUE;
447 case TLS_ST_SW_SESSION_TICKET:
448 if (SSL_IS_DTLS(s)) {
450 * We're into the last flight. We don't retransmit the last flight
451 * unless we need to, so we don't use the timer
457 case TLS_ST_SW_CHANGE:
458 s->session->cipher = s->s3->tmp.new_cipher;
459 if (!s->method->ssl3_enc->setup_key_block(s)) {
460 ossl_statem_set_error(s);
463 if (SSL_IS_DTLS(s)) {
465 * We're into the last flight. We don't retransmit the last flight
466 * unless we need to, so we don't use the timer. This might have
467 * already been set to 0 if we sent a NewSessionTicket message,
468 * but we'll set it again here in case we didn't.
472 return WORK_FINISHED_CONTINUE;
475 return tls_finish_handshake(s, wst);
478 /* No pre work to be done */
482 return WORK_FINISHED_CONTINUE;
486 * Perform any work that needs to be done after sending a message from the
487 * server to the client.
489 WORK_STATE ossl_statem_server_post_work(SSL *s, WORK_STATE wst)
491 OSSL_STATEM *st = &s->statem;
495 switch(st->hand_state) {
496 case TLS_ST_SW_HELLO_REQ:
497 if (statem_flush(s) != 1)
499 ssl3_init_finished_mac(s);
502 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
503 if (statem_flush(s) != 1)
505 /* HelloVerifyRequest resets Finished MAC */
506 if (s->version != DTLS1_BAD_VER)
507 ssl3_init_finished_mac(s);
509 * The next message should be another ClientHello which we need to
510 * treat like it was the first packet
515 case TLS_ST_SW_SRVR_HELLO:
516 #ifndef OPENSSL_NO_SCTP
517 if (SSL_IS_DTLS(s) && s->hit) {
518 unsigned char sctpauthkey[64];
519 char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
522 * Add new shared key for SCTP-Auth, will be ignored if no
525 memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
526 sizeof(DTLS1_SCTP_AUTH_LABEL));
528 if (SSL_export_keying_material(s, sctpauthkey,
529 sizeof(sctpauthkey), labelbuffer,
530 sizeof(labelbuffer), NULL, 0, 0) <= 0) {
531 ossl_statem_set_error(s);
535 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
536 sizeof(sctpauthkey), sctpauthkey);
541 case TLS_ST_SW_CHANGE:
542 #ifndef OPENSSL_NO_SCTP
543 if (SSL_IS_DTLS(s) && !s->hit) {
545 * Change to new shared key of SCTP-Auth, will be ignored if
548 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
552 if (!s->method->ssl3_enc->change_cipher_state(s,
553 SSL3_CHANGE_CIPHER_SERVER_WRITE)) {
554 ossl_statem_set_error(s);
559 dtls1_reset_seq_numbers(s, SSL3_CC_WRITE);
562 case TLS_ST_SW_SRVR_DONE:
563 if (statem_flush(s) != 1)
567 case TLS_ST_SW_FINISHED:
568 if (statem_flush(s) != 1)
570 #ifndef OPENSSL_NO_SCTP
571 if (SSL_IS_DTLS(s) && s->hit) {
573 * Change to new shared key of SCTP-Auth, will be ignored if
576 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
583 /* No post work to be done */
587 return WORK_FINISHED_CONTINUE;
591 * Construct a message to be sent from the server to the client.
593 * Valid return values are:
597 int ossl_statem_server_construct_message(SSL *s)
599 OSSL_STATEM *st = &s->statem;
601 switch(st->hand_state) {
602 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
603 return dtls_construct_hello_verify_request(s);
605 case TLS_ST_SW_HELLO_REQ:
606 return tls_construct_hello_request(s);
608 case TLS_ST_SW_SRVR_HELLO:
609 return tls_construct_server_hello(s);
612 return tls_construct_server_certificate(s);
614 case TLS_ST_SW_KEY_EXCH:
615 return tls_construct_server_key_exchange(s);
617 case TLS_ST_SW_CERT_REQ:
618 return tls_construct_certificate_request(s);
620 case TLS_ST_SW_SRVR_DONE:
621 return tls_construct_server_done(s);
623 case TLS_ST_SW_SESSION_TICKET:
624 return tls_construct_new_session_ticket(s);
626 case TLS_ST_SW_CERT_STATUS:
627 return tls_construct_cert_status(s);
629 case TLS_ST_SW_CHANGE:
631 return dtls_construct_change_cipher_spec(s);
633 return tls_construct_change_cipher_spec(s);
635 case TLS_ST_SW_FINISHED:
636 return tls_construct_finished(s,
638 ssl3_enc->server_finished_label,
640 ssl3_enc->server_finished_label_len);
643 /* Shouldn't happen */
651 * Maximum size (excluding the Handshake header) of a ClientHello message,
652 * calculated as follows:
654 * 2 + # client_version
655 * 32 + # only valid length for random
656 * 1 + # length of session_id
657 * 32 + # maximum size for session_id
658 * 2 + # length of cipher suites
659 * 2^16-2 + # maximum length of cipher suites array
660 * 1 + # length of compression_methods
661 * 2^8-1 + # maximum length of compression methods
662 * 2 + # length of extensions
663 * 2^16-1 # maximum length of extensions
665 #define CLIENT_HELLO_MAX_LENGTH 131396
667 #define CLIENT_KEY_EXCH_MAX_LENGTH 2048
668 #define NEXT_PROTO_MAX_LENGTH 514
671 * Returns the maximum allowed length for the current message that we are
672 * reading. Excludes the message header.
674 unsigned long ossl_statem_server_max_message_size(SSL *s)
676 OSSL_STATEM *st = &s->statem;
678 switch(st->hand_state) {
679 case TLS_ST_SR_CLNT_HELLO:
680 return CLIENT_HELLO_MAX_LENGTH;
683 return s->max_cert_list;
685 case TLS_ST_SR_KEY_EXCH:
686 return CLIENT_KEY_EXCH_MAX_LENGTH;
688 case TLS_ST_SR_CERT_VRFY:
689 return SSL3_RT_MAX_PLAIN_LENGTH;
691 #ifndef OPENSSL_NO_NEXTPROTONEG
692 case TLS_ST_SR_NEXT_PROTO:
693 return NEXT_PROTO_MAX_LENGTH;
696 case TLS_ST_SR_CHANGE:
697 return CCS_MAX_LENGTH;
699 case TLS_ST_SR_FINISHED:
700 return FINISHED_MAX_LENGTH;
703 /* Shouldn't happen */
711 * Process a message that the server has received from the client.
713 MSG_PROCESS_RETURN ossl_statem_server_process_message(SSL *s, PACKET *pkt)
715 OSSL_STATEM *st = &s->statem;
717 switch(st->hand_state) {
718 case TLS_ST_SR_CLNT_HELLO:
719 return tls_process_client_hello(s, pkt);
722 return tls_process_client_certificate(s, pkt);
724 case TLS_ST_SR_KEY_EXCH:
725 return tls_process_client_key_exchange(s, pkt);
727 case TLS_ST_SR_CERT_VRFY:
728 return tls_process_cert_verify(s, pkt);
730 #ifndef OPENSSL_NO_NEXTPROTONEG
731 case TLS_ST_SR_NEXT_PROTO:
732 return tls_process_next_proto(s, pkt);
735 case TLS_ST_SR_CHANGE:
736 return tls_process_change_cipher_spec(s, pkt);
738 case TLS_ST_SR_FINISHED:
739 return tls_process_finished(s, pkt);
742 /* Shouldn't happen */
746 return MSG_PROCESS_ERROR;
750 * Perform any further processing required following the receipt of a message
753 WORK_STATE ossl_statem_server_post_process_message(SSL *s, WORK_STATE wst)
755 OSSL_STATEM *st = &s->statem;
757 switch(st->hand_state) {
758 case TLS_ST_SR_CLNT_HELLO:
759 return tls_post_process_client_hello(s, wst);
761 case TLS_ST_SR_KEY_EXCH:
762 return tls_post_process_client_key_exchange(s, wst);
764 case TLS_ST_SR_CERT_VRFY:
765 #ifndef OPENSSL_NO_SCTP
766 if ( /* Is this SCTP? */
767 BIO_dgram_is_sctp(SSL_get_wbio(s))
768 /* Are we renegotiating? */
770 && BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
771 s->s3->in_read_app_data = 2;
772 s->rwstate = SSL_READING;
773 BIO_clear_retry_flags(SSL_get_rbio(s));
774 BIO_set_retry_read(SSL_get_rbio(s));
775 ossl_statem_set_sctp_read_sock(s, 1);
778 ossl_statem_set_sctp_read_sock(s, 0);
781 return WORK_FINISHED_CONTINUE;
787 /* Shouldn't happen */
791 #ifndef OPENSSL_NO_SRP
792 static int ssl_check_srp_ext_ClientHello(SSL *s, int *al)
794 int ret = SSL_ERROR_NONE;
796 *al = SSL_AD_UNRECOGNIZED_NAME;
798 if ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) &&
799 (s->srp_ctx.TLS_ext_srp_username_callback != NULL)) {
800 if (s->srp_ctx.login == NULL) {
802 * RFC 5054 says SHOULD reject, we do so if There is no srp
806 *al = SSL_AD_UNKNOWN_PSK_IDENTITY;
808 ret = SSL_srp_server_param_with_username(s, al);
815 int tls_construct_hello_request(SSL *s)
817 if (!ssl_set_handshake_header(s, SSL3_MT_HELLO_REQUEST, 0)) {
818 SSLerr(SSL_F_TLS_CONSTRUCT_HELLO_REQUEST, ERR_R_INTERNAL_ERROR);
819 ossl_statem_set_error(s);
826 unsigned int dtls_raw_hello_verify_request(unsigned char *buf,
827 unsigned char *cookie,
828 unsigned char cookie_len)
830 unsigned int msg_len;
834 /* Always use DTLS 1.0 version: see RFC 6347 */
835 *(p++) = DTLS1_VERSION >> 8;
836 *(p++) = DTLS1_VERSION & 0xFF;
838 *(p++) = (unsigned char)cookie_len;
839 memcpy(p, cookie, cookie_len);
846 int dtls_construct_hello_verify_request(SSL *s)
851 buf = (unsigned char *)s->init_buf->data;
853 if (s->ctx->app_gen_cookie_cb == NULL ||
854 s->ctx->app_gen_cookie_cb(s, s->d1->cookie,
855 &(s->d1->cookie_len)) == 0 ||
856 s->d1->cookie_len > 255) {
857 SSLerr(SSL_F_DTLS_CONSTRUCT_HELLO_VERIFY_REQUEST,
858 SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
859 ossl_statem_set_error(s);
863 len = dtls_raw_hello_verify_request(&buf[DTLS1_HM_HEADER_LENGTH],
864 s->d1->cookie, s->d1->cookie_len);
866 dtls1_set_message_header(s, DTLS1_MT_HELLO_VERIFY_REQUEST, len, 0,
868 len += DTLS1_HM_HEADER_LENGTH;
870 /* number of bytes to write */
877 MSG_PROCESS_RETURN tls_process_client_hello(SSL *s, PACKET *pkt)
879 int i, al = SSL_AD_INTERNAL_ERROR;
880 unsigned int j, complen = 0;
883 #ifndef OPENSSL_NO_COMP
884 SSL_COMP *comp = NULL;
886 STACK_OF(SSL_CIPHER) *ciphers = NULL;
888 /* |cookie| will only be initialized for DTLS. */
889 PACKET session_id, cipher_suites, compression, extensions, cookie;
891 static const unsigned char null_compression = 0;
893 is_v2_record = RECORD_LAYER_is_sslv2_record(&s->rlayer);
895 PACKET_null_init(&cookie);
896 /* First lets get s->client_version set correctly */
898 unsigned int version;
901 * An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2
902 * header is sent directly on the wire, not wrapped as a TLS
903 * record. Our record layer just processes the message length and passes
904 * the rest right through. Its format is:
906 * 0-1 msg_length - decoded by the record layer
907 * 2 msg_type - s->init_msg points here
909 * 5-6 cipher_spec_length
910 * 7-8 session_id_length
911 * 9-10 challenge_length
915 if (!PACKET_get_1(pkt, &mt)
916 || mt != SSL2_MT_CLIENT_HELLO) {
918 * Should never happen. We should have tested this in the record
919 * layer in order to have determined that this is a SSLv2 record
922 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
926 if (!PACKET_get_net_2(pkt, &version)) {
927 /* No protocol version supplied! */
928 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
931 if (version == 0x0002) {
932 /* This is real SSLv2. We don't support it. */
933 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
935 } else if ((version & 0xff00) == (SSL3_VERSION_MAJOR << 8)) {
937 s->client_version = version;
939 /* No idea what protocol this is */
940 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
945 * use version from inside client hello, not from record header (may
946 * differ: see RFC 2246, Appendix E, second paragraph)
948 if(!PACKET_get_net_2(pkt, (unsigned int *)&s->client_version)) {
949 al = SSL_AD_DECODE_ERROR;
950 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
956 * Do SSL/TLS version negotiation if applicable. For DTLS we just check
957 * versions are potentially compatible. Version negotiation comes later.
959 if (!SSL_IS_DTLS(s)) {
960 protverr = ssl_choose_server_version(s);
961 } else if (s->method->version != DTLS_ANY_VERSION &&
962 DTLS_VERSION_LT(s->client_version, s->version)) {
963 protverr = SSL_R_VERSION_TOO_LOW;
969 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, protverr);
970 if ((!s->enc_write_ctx && !s->write_hash)) {
972 * similar to ssl3_get_record, send alert using remote version
975 s->version = s->client_version;
977 al = SSL_AD_PROTOCOL_VERSION;
981 /* Parse the message and load client random. */
984 * Handle an SSLv2 backwards compatible ClientHello
985 * Note, this is only for SSLv3+ using the backward compatible format.
986 * Real SSLv2 is not supported, and is rejected above.
988 unsigned int cipher_len, session_id_len, challenge_len;
991 if (!PACKET_get_net_2(pkt, &cipher_len)
992 || !PACKET_get_net_2(pkt, &session_id_len)
993 || !PACKET_get_net_2(pkt, &challenge_len)) {
994 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
995 SSL_R_RECORD_LENGTH_MISMATCH);
996 al = SSL_AD_DECODE_ERROR;
1000 if (session_id_len > SSL_MAX_SSL_SESSION_ID_LENGTH) {
1001 al = SSL_AD_DECODE_ERROR;
1002 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1006 if (!PACKET_get_sub_packet(pkt, &cipher_suites, cipher_len)
1007 || !PACKET_get_sub_packet(pkt, &session_id, session_id_len)
1008 || !PACKET_get_sub_packet(pkt, &challenge, challenge_len)
1009 /* No extensions. */
1010 || PACKET_remaining(pkt) != 0) {
1011 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1012 SSL_R_RECORD_LENGTH_MISMATCH);
1013 al = SSL_AD_DECODE_ERROR;
1017 /* Load the client random and compression list. */
1018 challenge_len = challenge_len > SSL3_RANDOM_SIZE ? SSL3_RANDOM_SIZE :
1020 memset(s->s3->client_random, 0, SSL3_RANDOM_SIZE);
1021 if (!PACKET_copy_bytes(&challenge,
1022 s->s3->client_random + SSL3_RANDOM_SIZE -
1023 challenge_len, challenge_len)
1024 /* Advertise only null compression. */
1025 || !PACKET_buf_init(&compression, &null_compression, 1)) {
1026 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1027 al = SSL_AD_INTERNAL_ERROR;
1031 PACKET_null_init(&extensions);
1033 /* Regular ClientHello. */
1034 if (!PACKET_copy_bytes(pkt, s->s3->client_random, SSL3_RANDOM_SIZE)
1035 || !PACKET_get_length_prefixed_1(pkt, &session_id)) {
1036 al = SSL_AD_DECODE_ERROR;
1037 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1041 if (PACKET_remaining(&session_id) > SSL_MAX_SSL_SESSION_ID_LENGTH) {
1042 al = SSL_AD_DECODE_ERROR;
1043 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1047 if (SSL_IS_DTLS(s)) {
1048 if (!PACKET_get_length_prefixed_1(pkt, &cookie)) {
1049 al = SSL_AD_DECODE_ERROR;
1050 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1054 * If we require cookies and this ClientHello doesn't contain one,
1055 * just return since we do not want to allocate any memory yet.
1056 * So check cookie length...
1058 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1059 if (PACKET_remaining(&cookie) == 0)
1064 if (!PACKET_get_length_prefixed_2(pkt, &cipher_suites)
1065 || !PACKET_get_length_prefixed_1(pkt, &compression)) {
1066 al = SSL_AD_DECODE_ERROR;
1067 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1070 /* Could be empty. */
1074 if (SSL_IS_DTLS(s)) {
1075 /* Empty cookie was already handled above by returning early. */
1076 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1077 if (s->ctx->app_verify_cookie_cb != NULL) {
1078 if (s->ctx->app_verify_cookie_cb(s, PACKET_data(&cookie),
1079 PACKET_remaining(&cookie)) == 0) {
1080 al = SSL_AD_HANDSHAKE_FAILURE;
1081 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1082 SSL_R_COOKIE_MISMATCH);
1084 /* else cookie verification succeeded */
1086 /* default verification */
1087 } else if (!PACKET_equal(&cookie, s->d1->cookie,
1088 s->d1->cookie_len)) {
1089 al = SSL_AD_HANDSHAKE_FAILURE;
1090 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1093 s->d1->cookie_verified = 1;
1095 if (s->method->version == DTLS_ANY_VERSION) {
1096 protverr = ssl_choose_server_version(s);
1097 if (protverr != 0) {
1098 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, protverr);
1099 s->version = s->client_version;
1100 al = SSL_AD_PROTOCOL_VERSION;
1109 * We don't allow resumption in a backwards compatible ClientHello.
1110 * TODO(openssl-team): in TLS1.1+, session_id MUST be empty.
1112 * Versions before 0.9.7 always allow clients to resume sessions in
1113 * renegotiation. 0.9.7 and later allow this by default, but optionally
1114 * ignore resumption requests with flag
1115 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
1116 * than a change to default behavior so that applications relying on
1117 * this for security won't even compile against older library versions).
1118 * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
1119 * request renegotiation but not a new session (s->new_session remains
1120 * unset): for servers, this essentially just means that the
1121 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be
1126 (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
1127 if (!ssl_get_new_session(s, 1))
1130 i = ssl_get_prev_session(s, &extensions, &session_id);
1132 * Only resume if the session's version matches the negotiated
1134 * RFC 5246 does not provide much useful advice on resumption
1135 * with a different protocol version. It doesn't forbid it but
1136 * the sanity of such behaviour would be questionable.
1137 * In practice, clients do not accept a version mismatch and
1138 * will abort the handshake with an error.
1140 if (i == 1 && s->version == s->session->ssl_version) {
1141 /* previous session */
1143 } else if (i == -1) {
1147 if (!ssl_get_new_session(s, 1))
1152 if (ssl_bytes_to_cipher_list(s, &cipher_suites, &(ciphers),
1153 is_v2_record, &al) == NULL) {
1157 /* If it is a hit, check that the cipher is in the list */
1160 id = s->session->cipher->id;
1163 fprintf(stderr, "client sent %d ciphers\n",
1164 sk_SSL_CIPHER_num(ciphers));
1166 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1167 c = sk_SSL_CIPHER_value(ciphers, i);
1169 fprintf(stderr, "client [%2d of %2d]:%s\n",
1170 i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
1179 * we need to have the cipher in the cipher list if we are asked
1182 al = SSL_AD_ILLEGAL_PARAMETER;
1183 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1184 SSL_R_REQUIRED_CIPHER_MISSING);
1189 complen = PACKET_remaining(&compression);
1190 for (j = 0; j < complen; j++) {
1191 if (PACKET_data(&compression)[j] == 0)
1197 al = SSL_AD_DECODE_ERROR;
1198 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED);
1202 /* TLS extensions */
1203 if (s->version >= SSL3_VERSION) {
1204 if (!ssl_parse_clienthello_tlsext(s, &extensions)) {
1205 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_PARSE_TLSEXT);
1211 * Check if we want to use external pre-shared secret for this handshake
1212 * for not reused session only. We need to generate server_random before
1213 * calling tls_session_secret_cb in order to allow SessionTicket
1214 * processing to use it in key derivation.
1218 pos = s->s3->server_random;
1219 if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0) {
1224 if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb) {
1225 const SSL_CIPHER *pref_cipher = NULL;
1227 s->session->master_key_length = sizeof(s->session->master_key);
1228 if (s->tls_session_secret_cb(s, s->session->master_key,
1229 &s->session->master_key_length, ciphers,
1231 s->tls_session_secret_cb_arg)) {
1233 s->session->ciphers = ciphers;
1234 s->session->verify_result = X509_V_OK;
1238 /* check if some cipher was preferred by call back */
1240 pref_cipher ? pref_cipher : ssl3_choose_cipher(s,
1245 if (pref_cipher == NULL) {
1246 al = SSL_AD_HANDSHAKE_FAILURE;
1247 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1251 s->session->cipher = pref_cipher;
1252 sk_SSL_CIPHER_free(s->cipher_list);
1253 s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1254 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1255 s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1260 * Worst case, we will use the NULL compression, but if we have other
1261 * options, we will now look for them. We have complen-1 compression
1262 * algorithms from the client, starting at q.
1264 s->s3->tmp.new_compression = NULL;
1265 #ifndef OPENSSL_NO_COMP
1266 /* This only happens if we have a cache hit */
1267 if (s->session->compress_meth != 0) {
1268 int m, comp_id = s->session->compress_meth;
1270 /* Perform sanity checks on resumed compression algorithm */
1271 /* Can't disable compression */
1272 if (!ssl_allow_compression(s)) {
1273 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1274 SSL_R_INCONSISTENT_COMPRESSION);
1277 /* Look for resumed compression method */
1278 for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) {
1279 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1280 if (comp_id == comp->id) {
1281 s->s3->tmp.new_compression = comp;
1285 if (s->s3->tmp.new_compression == NULL) {
1286 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1287 SSL_R_INVALID_COMPRESSION_ALGORITHM);
1290 /* Look for resumed method in compression list */
1291 for (k = 0; k < complen; k++) {
1292 if (PACKET_data(&compression)[k] == comp_id)
1296 al = SSL_AD_ILLEGAL_PARAMETER;
1297 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1298 SSL_R_REQUIRED_COMPRESSION_ALGORITHM_MISSING);
1303 else if (ssl_allow_compression(s) && s->ctx->comp_methods) {
1304 /* See if we have a match */
1305 int m, nn, v, done = 0;
1308 nn = sk_SSL_COMP_num(s->ctx->comp_methods);
1309 for (m = 0; m < nn; m++) {
1310 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1312 for (o = 0; o < complen; o++) {
1313 if (v == PACKET_data(&compression)[o]) {
1322 s->s3->tmp.new_compression = comp;
1328 * If compression is disabled we'd better not try to resume a session
1329 * using compression.
1331 if (s->session->compress_meth != 0) {
1332 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
1338 * Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher
1342 #ifdef OPENSSL_NO_COMP
1343 s->session->compress_meth = 0;
1345 s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
1347 sk_SSL_CIPHER_free(s->session->ciphers);
1348 s->session->ciphers = ciphers;
1349 if (ciphers == NULL) {
1350 al = SSL_AD_INTERNAL_ERROR;
1351 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1355 if (!tls1_set_server_sigalgs(s)) {
1356 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1361 sk_SSL_CIPHER_free(ciphers);
1362 return MSG_PROCESS_CONTINUE_PROCESSING;
1364 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1366 ossl_statem_set_error(s);
1368 sk_SSL_CIPHER_free(ciphers);
1369 return MSG_PROCESS_ERROR;
1373 WORK_STATE tls_post_process_client_hello(SSL *s, WORK_STATE wst)
1375 int al = SSL_AD_HANDSHAKE_FAILURE;
1376 const SSL_CIPHER *cipher;
1378 if (wst == WORK_MORE_A) {
1380 /* Let cert callback update server certificates if required */
1381 if (s->cert->cert_cb) {
1382 int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
1384 al = SSL_AD_INTERNAL_ERROR;
1385 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO, SSL_R_CERT_CB_ERROR);
1389 s->rwstate = SSL_X509_LOOKUP;
1392 s->rwstate = SSL_NOTHING;
1394 cipher = ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
1396 if (cipher == NULL) {
1397 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1400 s->s3->tmp.new_cipher = cipher;
1401 /* check whether we should disable session resumption */
1402 if (s->not_resumable_session_cb != NULL)
1403 s->session->not_resumable = s->not_resumable_session_cb(s,
1404 ((cipher->algorithm_mkey & (SSL_kDHE | SSL_kECDHE)) != 0));
1405 if (s->session->not_resumable)
1406 /* do not send a session ticket */
1407 s->tlsext_ticket_expected = 0;
1409 /* Session-id reuse */
1410 s->s3->tmp.new_cipher = s->session->cipher;
1413 if (!(s->verify_mode & SSL_VERIFY_PEER)) {
1414 if (!ssl3_digest_cached_records(s, 0)) {
1415 al = SSL_AD_INTERNAL_ERROR;
1421 * we now have the following setup.
1423 * cipher_list - our prefered list of ciphers
1424 * ciphers - the clients prefered list of ciphers
1425 * compression - basically ignored right now
1426 * ssl version is set - sslv3
1427 * s->session - The ssl session has been setup.
1428 * s->hit - session reuse flag
1429 * s->s3->tmp.new_cipher- the new cipher to use.
1432 /* Handles TLS extensions that we couldn't check earlier */
1433 if (s->version >= SSL3_VERSION) {
1434 if (ssl_check_clienthello_tlsext_late(s) <= 0) {
1435 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
1436 SSL_R_CLIENTHELLO_TLSEXT);
1443 #ifndef OPENSSL_NO_SRP
1444 if (wst == WORK_MORE_B) {
1446 if ((ret = ssl_check_srp_ext_ClientHello(s, &al)) < 0) {
1448 * callback indicates further work to be done
1450 s->rwstate = SSL_X509_LOOKUP;
1453 if (ret != SSL_ERROR_NONE) {
1455 * This is not really an error but the only means to for
1456 * a client to detect whether srp is supported.
1458 if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)
1459 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
1460 SSL_R_CLIENTHELLO_TLSEXT);
1467 return WORK_FINISHED_STOP;
1469 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1470 ossl_statem_set_error(s);
1474 int tls_construct_server_hello(SSL *s)
1477 unsigned char *p, *d;
1482 buf = (unsigned char *)s->init_buf->data;
1484 /* Do the message type and length last */
1485 d = p = ssl_handshake_start(s);
1487 *(p++) = s->version >> 8;
1488 *(p++) = s->version & 0xff;
1491 * Random stuff. Filling of the server_random takes place in
1492 * tls_process_client_hello()
1494 memcpy(p, s->s3->server_random, SSL3_RANDOM_SIZE);
1495 p += SSL3_RANDOM_SIZE;
1498 * There are several cases for the session ID to send
1499 * back in the server hello:
1500 * - For session reuse from the session cache,
1501 * we send back the old session ID.
1502 * - If stateless session reuse (using a session ticket)
1503 * is successful, we send back the client's "session ID"
1504 * (which doesn't actually identify the session).
1505 * - If it is a new session, we send back the new
1507 * - However, if we want the new session to be single-use,
1508 * we send back a 0-length session ID.
1509 * s->hit is non-zero in either case of session reuse,
1510 * so the following won't overwrite an ID that we're supposed
1513 if (s->session->not_resumable ||
1514 (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1516 s->session->session_id_length = 0;
1518 sl = s->session->session_id_length;
1519 if (sl > (int)sizeof(s->session->session_id)) {
1520 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1521 ossl_statem_set_error(s);
1525 memcpy(p, s->session->session_id, sl);
1528 /* put the cipher */
1529 i = ssl3_put_cipher_by_char(s->s3->tmp.new_cipher, p);
1532 /* put the compression method */
1533 #ifdef OPENSSL_NO_COMP
1536 if (s->s3->tmp.new_compression == NULL)
1539 *(p++) = s->s3->tmp.new_compression->id;
1542 if (ssl_prepare_serverhello_tlsext(s) <= 0) {
1543 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, SSL_R_SERVERHELLO_TLSEXT);
1544 ossl_statem_set_error(s);
1548 ssl_add_serverhello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,
1550 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1551 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1552 ossl_statem_set_error(s);
1558 if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l)) {
1559 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1560 ossl_statem_set_error(s);
1567 int tls_construct_server_done(SSL *s)
1569 if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0)) {
1570 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_DONE, ERR_R_INTERNAL_ERROR);
1571 ossl_statem_set_error(s);
1575 if (!s->s3->tmp.cert_request) {
1576 if (!ssl3_digest_cached_records(s, 0)) {
1577 ossl_statem_set_error(s);
1584 int tls_construct_server_key_exchange(SSL *s)
1586 #ifndef OPENSSL_NO_DH
1587 EVP_PKEY *pkdh = NULL;
1589 #ifndef OPENSSL_NO_EC
1590 unsigned char *encodedPoint = NULL;
1595 const EVP_MD *md = NULL;
1596 unsigned char *p, *d;
1603 EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
1605 if (md_ctx == NULL) {
1606 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1607 al = SSL_AD_INTERNAL_ERROR;
1611 type = s->s3->tmp.new_cipher->algorithm_mkey;
1615 r[0] = r[1] = r[2] = r[3] = NULL;
1617 #ifndef OPENSSL_NO_PSK
1618 if (type & SSL_PSK) {
1620 * reserve size for record length and PSK identity hint
1623 if (s->cert->psk_identity_hint)
1624 n += strlen(s->cert->psk_identity_hint);
1626 /* Plain PSK or RSAPSK nothing to do */
1627 if (type & (SSL_kPSK | SSL_kRSAPSK)) {
1629 #endif /* !OPENSSL_NO_PSK */
1630 #ifndef OPENSSL_NO_DH
1631 if (type & (SSL_kDHE | SSL_kDHEPSK)) {
1632 CERT *cert = s->cert;
1634 EVP_PKEY *pkdhp = NULL;
1637 if (s->cert->dh_tmp_auto) {
1638 DH *dhp = ssl_get_auto_dh(s);
1639 pkdh = EVP_PKEY_new();
1640 if (pkdh == NULL || dhp == NULL) {
1642 al = SSL_AD_INTERNAL_ERROR;
1643 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1644 ERR_R_INTERNAL_ERROR);
1647 EVP_PKEY_assign_DH(pkdh, dhp);
1650 pkdhp = cert->dh_tmp;
1652 if ((pkdhp == NULL) && (s->cert->dh_tmp_cb != NULL)) {
1653 DH *dhp = s->cert->dh_tmp_cb(s, 0, 1024);
1654 pkdh = ssl_dh_to_pkey(dhp);
1656 al = SSL_AD_INTERNAL_ERROR;
1657 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1658 ERR_R_INTERNAL_ERROR);
1663 if (pkdhp == NULL) {
1664 al = SSL_AD_HANDSHAKE_FAILURE;
1665 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1666 SSL_R_MISSING_TMP_DH_KEY);
1669 if (!ssl_security(s, SSL_SECOP_TMP_DH,
1670 EVP_PKEY_security_bits(pkdhp), 0, pkdhp)) {
1671 al = SSL_AD_HANDSHAKE_FAILURE;
1672 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1673 SSL_R_DH_KEY_TOO_SMALL);
1676 if (s->s3->tmp.pkey != NULL) {
1677 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1678 ERR_R_INTERNAL_ERROR);
1682 s->s3->tmp.pkey = ssl_generate_pkey(pkdhp, NID_undef);
1684 if (s->s3->tmp.pkey == NULL) {
1685 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EVP_LIB);
1689 dh = EVP_PKEY_get0_DH(s->s3->tmp.pkey);
1691 EVP_PKEY_free(pkdh);
1694 DH_get0_pqg(dh, &r[0], NULL, &r[1]);
1695 DH_get0_key(dh, &r[2], NULL);
1698 #ifndef OPENSSL_NO_EC
1699 if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
1702 if (s->s3->tmp.pkey != NULL) {
1703 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1704 ERR_R_INTERNAL_ERROR);
1708 /* Get NID of appropriate shared curve */
1709 nid = tls1_shared_curve(s, -2);
1710 curve_id = tls1_ec_nid2curve_id(nid);
1711 if (curve_id == 0) {
1712 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1713 SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1716 s->s3->tmp.pkey = ssl_generate_pkey(NULL, nid);
1717 /* Generate a new key for this curve */
1718 if (s->s3->tmp.pkey == NULL) {
1719 al = SSL_AD_INTERNAL_ERROR;
1720 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EVP_LIB);
1724 /* Encode the public key. */
1725 encodedlen = EC_KEY_key2buf(EVP_PKEY_get0_EC_KEY(s->s3->tmp.pkey),
1726 POINT_CONVERSION_UNCOMPRESSED,
1727 &encodedPoint, NULL);
1729 if (encodedlen == 0) {
1730 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EC_LIB);
1735 * We only support named (not generic) curves in ECDH ephemeral key
1736 * exchanges. In this situation, we need four additional bytes to
1737 * encode the entire ServerECDHParams structure.
1739 n += 4 + encodedlen;
1742 * We'll generate the serverKeyExchange message explicitly so we
1743 * can set these to NULLs
1750 #endif /* !OPENSSL_NO_EC */
1751 #ifndef OPENSSL_NO_SRP
1752 if (type & SSL_kSRP) {
1753 if ((s->srp_ctx.N == NULL) ||
1754 (s->srp_ctx.g == NULL) ||
1755 (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
1756 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1757 SSL_R_MISSING_SRP_PARAM);
1760 r[0] = s->srp_ctx.N;
1761 r[1] = s->srp_ctx.g;
1762 r[2] = s->srp_ctx.s;
1763 r[3] = s->srp_ctx.B;
1767 al = SSL_AD_HANDSHAKE_FAILURE;
1768 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1769 SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1772 for (i = 0; i < 4 && r[i] != NULL; i++) {
1773 nr[i] = BN_num_bytes(r[i]);
1774 #ifndef OPENSSL_NO_SRP
1775 if ((i == 2) && (type & SSL_kSRP))
1782 if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aSRP))
1783 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_PSK)) {
1784 if ((pkey = ssl_get_sign_pkey(s, s->s3->tmp.new_cipher, &md))
1786 al = SSL_AD_DECODE_ERROR;
1789 kn = EVP_PKEY_size(pkey);
1795 if (!BUF_MEM_grow_clean(buf, n + SSL_HM_HEADER_LENGTH(s) + kn)) {
1796 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_LIB_BUF);
1799 d = p = ssl_handshake_start(s);
1801 #ifndef OPENSSL_NO_PSK
1802 if (type & SSL_PSK) {
1803 /* copy PSK identity hint */
1804 if (s->cert->psk_identity_hint) {
1805 s2n(strlen(s->cert->psk_identity_hint), p);
1806 strncpy((char *)p, s->cert->psk_identity_hint,
1807 strlen(s->cert->psk_identity_hint));
1808 p += strlen(s->cert->psk_identity_hint);
1815 for (i = 0; i < 4 && r[i] != NULL; i++) {
1816 #ifndef OPENSSL_NO_SRP
1817 if ((i == 2) && (type & SSL_kSRP)) {
1827 #ifndef OPENSSL_NO_EC
1828 if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
1830 * XXX: For now, we only support named (not generic) curves. In
1831 * this situation, the serverKeyExchange message has: [1 byte
1832 * CurveType], [2 byte CurveName] [1 byte length of encoded
1833 * point], followed by the actual encoded point itself
1835 *p = NAMED_CURVE_TYPE;
1843 memcpy(p, encodedPoint, encodedlen);
1844 OPENSSL_free(encodedPoint);
1845 encodedPoint = NULL;
1853 * n is the length of the params, they start at &(d[4]) and p
1854 * points to the space at the end.
1857 /* send signature algorithm */
1858 if (SSL_USE_SIGALGS(s)) {
1859 if (!tls12_get_sigandhash(p, pkey, md)) {
1860 /* Should never happen */
1861 al = SSL_AD_INTERNAL_ERROR;
1862 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1863 ERR_R_INTERNAL_ERROR);
1869 fprintf(stderr, "Using hash %s\n", EVP_MD_name(md));
1871 if (EVP_SignInit_ex(md_ctx, md, NULL) <= 0
1872 || EVP_SignUpdate(md_ctx, &(s->s3->client_random[0]),
1873 SSL3_RANDOM_SIZE) <= 0
1874 || EVP_SignUpdate(md_ctx, &(s->s3->server_random[0]),
1875 SSL3_RANDOM_SIZE) <= 0
1876 || EVP_SignUpdate(md_ctx, d, n) <= 0
1877 || EVP_SignFinal(md_ctx, &(p[2]),
1878 (unsigned int *)&i, pkey) <= 0) {
1879 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_LIB_EVP);
1880 al = SSL_AD_INTERNAL_ERROR;
1885 if (SSL_USE_SIGALGS(s))
1888 /* Is this error check actually needed? */
1889 al = SSL_AD_HANDSHAKE_FAILURE;
1890 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1891 SSL_R_UNKNOWN_PKEY_TYPE);
1896 if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n)) {
1897 al = SSL_AD_HANDSHAKE_FAILURE;
1898 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1902 EVP_MD_CTX_free(md_ctx);
1905 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1907 #ifndef OPENSSL_NO_DH
1908 EVP_PKEY_free(pkdh);
1910 #ifndef OPENSSL_NO_EC
1911 OPENSSL_free(encodedPoint);
1913 EVP_MD_CTX_free(md_ctx);
1914 ossl_statem_set_error(s);
1918 int tls_construct_certificate_request(SSL *s)
1920 unsigned char *p, *d;
1921 int i, j, nl, off, n;
1922 STACK_OF(X509_NAME) *sk = NULL;
1928 d = p = ssl_handshake_start(s);
1930 /* get the list of acceptable cert types */
1932 n = ssl3_get_req_cert_type(s, p);
1937 if (SSL_USE_SIGALGS(s)) {
1938 const unsigned char *psigs;
1939 unsigned char *etmp = p;
1940 nl = tls12_get_psigalgs(s, &psigs);
1941 /* Skip over length for now */
1943 nl = tls12_copy_sigalgs(s, p, psigs, nl);
1944 /* Now fill in length */
1954 sk = SSL_get_client_CA_list(s);
1957 for (i = 0; i < sk_X509_NAME_num(sk); i++) {
1958 name = sk_X509_NAME_value(sk, i);
1959 j = i2d_X509_NAME(name, NULL);
1960 if (!BUF_MEM_grow_clean
1961 (buf, SSL_HM_HEADER_LENGTH(s) + n + j + 2)) {
1962 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
1966 p = ssl_handshake_start(s) + n;
1968 i2d_X509_NAME(name, &p);
1973 /* else no CA names */
1974 p = ssl_handshake_start(s) + off;
1977 if (!ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n)) {
1978 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR);
1982 s->s3->tmp.cert_request = 1;
1986 ossl_statem_set_error(s);
1990 MSG_PROCESS_RETURN tls_process_client_key_exchange(SSL *s, PACKET *pkt)
1993 unsigned long alg_k;
1994 #ifndef OPENSSL_NO_RSA
1997 #if !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)
1998 EVP_PKEY *ckey = NULL;
2000 PACKET enc_premaster;
2001 unsigned char *rsa_decrypt = NULL;
2003 alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2005 #ifndef OPENSSL_NO_PSK
2006 /* For PSK parse and retrieve identity, obtain PSK key */
2007 if (alg_k & SSL_PSK) {
2008 unsigned char psk[PSK_MAX_PSK_LEN];
2010 PACKET psk_identity;
2012 if (!PACKET_get_length_prefixed_2(pkt, &psk_identity)) {
2013 al = SSL_AD_DECODE_ERROR;
2014 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
2017 if (PACKET_remaining(&psk_identity) > PSK_MAX_IDENTITY_LEN) {
2018 al = SSL_AD_DECODE_ERROR;
2019 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2020 SSL_R_DATA_LENGTH_TOO_LONG);
2023 if (s->psk_server_callback == NULL) {
2024 al = SSL_AD_INTERNAL_ERROR;
2025 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2026 SSL_R_PSK_NO_SERVER_CB);
2030 if (!PACKET_strndup(&psk_identity, &s->session->psk_identity)) {
2031 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2032 al = SSL_AD_INTERNAL_ERROR;
2036 psklen = s->psk_server_callback(s, s->session->psk_identity,
2039 if (psklen > PSK_MAX_PSK_LEN) {
2040 al = SSL_AD_INTERNAL_ERROR;
2041 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2043 } else if (psklen == 0) {
2045 * PSK related to the given identity not found
2047 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2048 SSL_R_PSK_IDENTITY_NOT_FOUND);
2049 al = SSL_AD_UNKNOWN_PSK_IDENTITY;
2053 OPENSSL_free(s->s3->tmp.psk);
2054 s->s3->tmp.psk = OPENSSL_memdup(psk, psklen);
2055 OPENSSL_cleanse(psk, psklen);
2057 if (s->s3->tmp.psk == NULL) {
2058 al = SSL_AD_INTERNAL_ERROR;
2059 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2063 s->s3->tmp.psklen = psklen;
2065 if (alg_k & SSL_kPSK) {
2066 /* Identity extracted earlier: should be nothing left */
2067 if (PACKET_remaining(pkt) != 0) {
2068 al = SSL_AD_HANDSHAKE_FAILURE;
2069 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
2072 /* PSK handled by ssl_generate_master_secret */
2073 if (!ssl_generate_master_secret(s, NULL, 0, 0)) {
2074 al = SSL_AD_INTERNAL_ERROR;
2075 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2080 #ifndef OPENSSL_NO_RSA
2081 if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
2082 unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2084 unsigned char decrypt_good, version_good;
2087 /* FIX THIS UP EAY EAY EAY EAY */
2088 rsa = EVP_PKEY_get0_RSA(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey);
2090 al = SSL_AD_HANDSHAKE_FAILURE;
2091 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2092 SSL_R_MISSING_RSA_CERTIFICATE);
2096 /* SSLv3 and pre-standard DTLS omit the length bytes. */
2097 if (s->version == SSL3_VERSION || s->version == DTLS1_BAD_VER) {
2098 enc_premaster = *pkt;
2100 if (!PACKET_get_length_prefixed_2(pkt, &enc_premaster)
2101 || PACKET_remaining(pkt) != 0) {
2102 al = SSL_AD_DECODE_ERROR;
2103 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2104 SSL_R_LENGTH_MISMATCH);
2110 * We want to be sure that the plaintext buffer size makes it safe to
2111 * iterate over the entire size of a premaster secret
2112 * (SSL_MAX_MASTER_KEY_LENGTH). Reject overly short RSA keys because
2113 * their ciphertext cannot accommodate a premaster secret anyway.
2115 if (RSA_size(rsa) < SSL_MAX_MASTER_KEY_LENGTH) {
2116 al = SSL_AD_INTERNAL_ERROR;
2117 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2118 RSA_R_KEY_SIZE_TOO_SMALL);
2122 rsa_decrypt = OPENSSL_malloc(RSA_size(rsa));
2123 if (rsa_decrypt == NULL) {
2124 al = SSL_AD_INTERNAL_ERROR;
2125 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2130 * We must not leak whether a decryption failure occurs because of
2131 * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
2132 * section 7.4.7.1). The code follows that advice of the TLS RFC and
2133 * generates a random premaster secret for the case that the decrypt
2134 * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
2137 if (RAND_bytes(rand_premaster_secret,
2138 sizeof(rand_premaster_secret)) <= 0) {
2142 decrypt_len = RSA_private_decrypt(PACKET_remaining(&enc_premaster),
2143 PACKET_data(&enc_premaster),
2144 rsa_decrypt, rsa, RSA_PKCS1_PADDING);
2148 * decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH. decrypt_good will
2149 * be 0xff if so and zero otherwise.
2152 constant_time_eq_int_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH);
2155 * If the version in the decrypted pre-master secret is correct then
2156 * version_good will be 0xff, otherwise it'll be zero. The
2157 * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
2158 * (http://eprint.iacr.org/2003/052/) exploits the version number
2159 * check as a "bad version oracle". Thus version checks are done in
2160 * constant time and are treated like any other decryption error.
2163 constant_time_eq_8(rsa_decrypt[0],
2164 (unsigned)(s->client_version >> 8));
2166 constant_time_eq_8(rsa_decrypt[1],
2167 (unsigned)(s->client_version & 0xff));
2170 * The premaster secret must contain the same version number as the
2171 * ClientHello to detect version rollback attacks (strangely, the
2172 * protocol does not offer such protection for DH ciphersuites).
2173 * However, buggy clients exist that send the negotiated protocol
2174 * version instead if the server does not support the requested
2175 * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
2178 if (s->options & SSL_OP_TLS_ROLLBACK_BUG) {
2179 unsigned char workaround_good;
2181 constant_time_eq_8(rsa_decrypt[0], (unsigned)(s->version >> 8));
2183 constant_time_eq_8(rsa_decrypt[1],
2184 (unsigned)(s->version & 0xff));
2185 version_good |= workaround_good;
2189 * Both decryption and version must be good for decrypt_good to
2190 * remain non-zero (0xff).
2192 decrypt_good &= version_good;
2195 * Now copy rand_premaster_secret over from p using
2196 * decrypt_good_mask. If decryption failed, then p does not
2197 * contain valid plaintext, however, a check above guarantees
2198 * it is still sufficiently large to read from.
2200 for (j = 0; j < sizeof(rand_premaster_secret); j++) {
2202 constant_time_select_8(decrypt_good, rsa_decrypt[j],
2203 rand_premaster_secret[j]);
2206 if (!ssl_generate_master_secret(s, rsa_decrypt,
2207 sizeof(rand_premaster_secret), 0)) {
2208 al = SSL_AD_INTERNAL_ERROR;
2209 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2212 OPENSSL_free(rsa_decrypt);
2216 #ifndef OPENSSL_NO_DH
2217 if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
2218 EVP_PKEY *skey = NULL;
2222 const unsigned char *data;
2224 if (!PACKET_get_net_2(pkt, &i)) {
2225 if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
2226 al = SSL_AD_HANDSHAKE_FAILURE;
2227 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2228 SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2233 if (PACKET_remaining(pkt) != i) {
2234 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2235 SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2238 skey = s->s3->tmp.pkey;
2240 al = SSL_AD_HANDSHAKE_FAILURE;
2241 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2242 SSL_R_MISSING_TMP_DH_KEY);
2246 if (PACKET_remaining(pkt) == 0L) {
2247 al = SSL_AD_HANDSHAKE_FAILURE;
2248 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2249 SSL_R_MISSING_TMP_DH_KEY);
2252 if (!PACKET_get_bytes(pkt, &data, i)) {
2253 /* We already checked we have enough data */
2254 al = SSL_AD_INTERNAL_ERROR;
2255 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2256 ERR_R_INTERNAL_ERROR);
2259 ckey = EVP_PKEY_new();
2260 if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) == 0) {
2261 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_BN_LIB);
2264 cdh = EVP_PKEY_get0_DH(ckey);
2265 pub_key = BN_bin2bn(data, i, NULL);
2267 if (pub_key == NULL || !DH_set0_key(cdh, pub_key, NULL)) {
2268 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2269 if (pub_key != NULL)
2274 if (ssl_derive(s, skey, ckey) == 0) {
2275 al = SSL_AD_INTERNAL_ERROR;
2276 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2280 EVP_PKEY_free(ckey);
2282 EVP_PKEY_free(s->s3->tmp.pkey);
2283 s->s3->tmp.pkey = NULL;
2288 #ifndef OPENSSL_NO_EC
2289 if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
2290 EVP_PKEY *skey = s->s3->tmp.pkey;
2292 if (PACKET_remaining(pkt) == 0L) {
2293 /* We don't support ECDH client auth */
2294 al = SSL_AD_HANDSHAKE_FAILURE;
2295 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2296 SSL_R_MISSING_TMP_ECDH_KEY);
2300 const unsigned char *data;
2303 * Get client's public key from encoded point in the
2304 * ClientKeyExchange message.
2307 /* Get encoded point length */
2308 if (!PACKET_get_1(pkt, &i)) {
2309 al = SSL_AD_DECODE_ERROR;
2310 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2311 SSL_R_LENGTH_MISMATCH);
2314 if (!PACKET_get_bytes(pkt, &data, i)
2315 || PACKET_remaining(pkt) != 0) {
2316 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2319 ckey = EVP_PKEY_new();
2320 if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) <= 0) {
2321 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_EVP_LIB);
2324 if (EC_KEY_oct2key(EVP_PKEY_get0_EC_KEY(ckey), data, i,
2326 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2331 if (ssl_derive(s, skey, ckey) == 0) {
2332 al = SSL_AD_INTERNAL_ERROR;
2333 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2337 EVP_PKEY_free(ckey);
2339 EVP_PKEY_free(s->s3->tmp.pkey);
2340 s->s3->tmp.pkey = NULL;
2342 return MSG_PROCESS_CONTINUE_PROCESSING;
2345 #ifndef OPENSSL_NO_SRP
2346 if (alg_k & SSL_kSRP) {
2348 const unsigned char *data;
2350 if (!PACKET_get_net_2(pkt, &i)
2351 || !PACKET_get_bytes(pkt, &data, i)) {
2352 al = SSL_AD_DECODE_ERROR;
2353 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_BAD_SRP_A_LENGTH);
2356 if ((s->srp_ctx.A = BN_bin2bn(data, i, NULL)) == NULL) {
2357 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_BN_LIB);
2360 if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0
2361 || BN_is_zero(s->srp_ctx.A)) {
2362 al = SSL_AD_ILLEGAL_PARAMETER;
2363 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2364 SSL_R_BAD_SRP_PARAMETERS);
2367 OPENSSL_free(s->session->srp_username);
2368 s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);
2369 if (s->session->srp_username == NULL) {
2370 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2374 if (!srp_generate_server_master_secret(s)) {
2375 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2379 #endif /* OPENSSL_NO_SRP */
2380 #ifndef OPENSSL_NO_GOST
2381 if (alg_k & SSL_kGOST) {
2382 EVP_PKEY_CTX *pkey_ctx;
2383 EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2384 unsigned char premaster_secret[32];
2385 const unsigned char *start;
2386 size_t outlen = 32, inlen;
2387 unsigned long alg_a;
2391 const unsigned char *data;
2393 /* Get our certificate private key */
2394 alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2395 if (alg_a & SSL_aGOST12) {
2397 * New GOST ciphersuites have SSL_aGOST01 bit too
2399 pk = s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey;
2401 pk = s->cert->pkeys[SSL_PKEY_GOST12_256].privatekey;
2404 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2406 } else if (alg_a & SSL_aGOST01) {
2407 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2410 pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
2411 if (pkey_ctx == NULL) {
2412 al = SSL_AD_INTERNAL_ERROR;
2413 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2416 if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {
2417 al = SSL_AD_INTERNAL_ERROR;
2418 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2422 * If client certificate is present and is of the same type, maybe
2423 * use it for key exchange. Don't mind errors from
2424 * EVP_PKEY_derive_set_peer, because it is completely valid to use a
2425 * client certificate for authorization only.
2427 client_pub_pkey = X509_get0_pubkey(s->session->peer);
2428 if (client_pub_pkey) {
2429 if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
2432 /* Decrypt session key */
2433 sess_key_len = PACKET_remaining(pkt);
2434 if (!PACKET_get_bytes(pkt, &data, sess_key_len)) {
2435 al = SSL_AD_INTERNAL_ERROR;
2436 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2439 if (ASN1_get_object ((const unsigned char **)&data, &Tlen, &Ttag,
2440 &Tclass, sess_key_len) != V_ASN1_CONSTRUCTED
2441 || Ttag != V_ASN1_SEQUENCE
2442 || Tclass != V_ASN1_UNIVERSAL) {
2443 al = SSL_AD_DECODE_ERROR;
2444 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2445 SSL_R_DECRYPTION_FAILED);
2450 if (EVP_PKEY_decrypt
2451 (pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {
2452 al = SSL_AD_DECODE_ERROR;
2453 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2454 SSL_R_DECRYPTION_FAILED);
2457 /* Generate master secret */
2458 if (!ssl_generate_master_secret(s, premaster_secret,
2459 sizeof(premaster_secret), 0)) {
2460 al = SSL_AD_INTERNAL_ERROR;
2461 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2464 /* Check if pubkey from client certificate was used */
2465 if (EVP_PKEY_CTX_ctrl
2466 (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
2467 s->statem.no_cert_verify = 1;
2469 EVP_PKEY_CTX_free(pkey_ctx);
2470 return MSG_PROCESS_CONTINUE_PROCESSING;
2472 EVP_PKEY_CTX_free(pkey_ctx);
2477 al = SSL_AD_HANDSHAKE_FAILURE;
2478 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_UNKNOWN_CIPHER_TYPE);
2482 return MSG_PROCESS_CONTINUE_PROCESSING;
2484 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2485 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_EC) || defined(OPENSSL_NO_SRP)
2488 #if !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)
2489 EVP_PKEY_free(ckey);
2491 OPENSSL_free(rsa_decrypt);
2492 #ifndef OPENSSL_NO_PSK
2493 OPENSSL_clear_free(s->s3->tmp.psk, s->s3->tmp.psklen);
2494 s->s3->tmp.psk = NULL;
2496 ossl_statem_set_error(s);
2497 return MSG_PROCESS_ERROR;
2500 WORK_STATE tls_post_process_client_key_exchange(SSL *s, WORK_STATE wst)
2502 #ifndef OPENSSL_NO_SCTP
2503 if (wst == WORK_MORE_A) {
2504 if (SSL_IS_DTLS(s)) {
2505 unsigned char sctpauthkey[64];
2506 char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
2508 * Add new shared key for SCTP-Auth, will be ignored if no SCTP
2511 memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
2512 sizeof(DTLS1_SCTP_AUTH_LABEL));
2514 if (SSL_export_keying_material(s, sctpauthkey,
2515 sizeof(sctpauthkey), labelbuffer,
2516 sizeof(labelbuffer), NULL, 0, 0) <= 0) {
2517 ossl_statem_set_error(s);
2521 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
2522 sizeof(sctpauthkey), sctpauthkey);
2527 if ((wst == WORK_MORE_B)
2529 && BIO_dgram_is_sctp(SSL_get_wbio(s))
2530 /* Are we renegotiating? */
2532 /* Are we going to skip the CertificateVerify? */
2533 && (s->session->peer == NULL || s->statem.no_cert_verify)
2534 && BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
2535 s->s3->in_read_app_data = 2;
2536 s->rwstate = SSL_READING;
2537 BIO_clear_retry_flags(SSL_get_rbio(s));
2538 BIO_set_retry_read(SSL_get_rbio(s));
2539 ossl_statem_set_sctp_read_sock(s, 1);
2542 ossl_statem_set_sctp_read_sock(s, 0);
2546 if (s->statem.no_cert_verify) {
2547 /* No certificate verify so we no longer need the handshake_buffer */
2548 BIO_free(s->s3->handshake_buffer);
2549 s->s3->handshake_buffer = NULL;
2550 return WORK_FINISHED_CONTINUE;
2552 if (!s->session->peer) {
2553 /* No peer certificate so we no longer need the handshake_buffer */
2554 BIO_free(s->s3->handshake_buffer);
2555 return WORK_FINISHED_CONTINUE;
2557 if (!s->s3->handshake_buffer) {
2558 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_KEY_EXCHANGE,
2559 ERR_R_INTERNAL_ERROR);
2560 ossl_statem_set_error(s);
2564 * For sigalgs freeze the handshake buffer. If we support
2565 * extms we've done this already so this is a no-op
2567 if (!ssl3_digest_cached_records(s, 1)) {
2568 ossl_statem_set_error(s);
2573 return WORK_FINISHED_CONTINUE;
2576 MSG_PROCESS_RETURN tls_process_cert_verify(SSL *s, PACKET *pkt)
2578 EVP_PKEY *pkey = NULL;
2579 const unsigned char *sig, *data;
2580 #ifndef OPENSSL_NO_GOST
2581 unsigned char *gost_data = NULL;
2583 int al, ret = MSG_PROCESS_ERROR;
2587 const EVP_MD *md = NULL;
2591 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
2594 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
2595 al = SSL_AD_INTERNAL_ERROR;
2599 peer = s->session->peer;
2600 pkey = X509_get0_pubkey(peer);
2601 type = X509_certificate_type(peer, pkey);
2603 if (!(type & EVP_PKT_SIGN)) {
2604 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY,
2605 SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
2606 al = SSL_AD_ILLEGAL_PARAMETER;
2610 /* Check for broken implementations of GOST ciphersuites */
2612 * If key is GOST and n is exactly 64, it is bare signature without
2613 * length field (CryptoPro implementations at least till CSP 4.0)
2615 #ifndef OPENSSL_NO_GOST
2616 if (PACKET_remaining(pkt) == 64
2617 && EVP_PKEY_id(pkey) == NID_id_GostR3410_2001) {
2622 if (SSL_USE_SIGALGS(s)) {
2625 if (!PACKET_get_bytes(pkt, &sig, 2)) {
2626 al = SSL_AD_DECODE_ERROR;
2629 rv = tls12_check_peer_sigalg(&md, s, sig, pkey);
2631 al = SSL_AD_INTERNAL_ERROR;
2633 } else if (rv == 0) {
2634 al = SSL_AD_DECODE_ERROR;
2638 fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
2641 /* Use default digest for this key type */
2642 int idx = ssl_cert_type(NULL, pkey);
2644 md = s->s3->tmp.md[idx];
2646 al = SSL_AD_INTERNAL_ERROR;
2651 if (!PACKET_get_net_2(pkt, &len)) {
2652 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
2653 al = SSL_AD_DECODE_ERROR;
2657 j = EVP_PKEY_size(pkey);
2658 if (((int)len > j) || ((int)PACKET_remaining(pkt) > j)
2659 || (PACKET_remaining(pkt) == 0)) {
2660 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_WRONG_SIGNATURE_SIZE);
2661 al = SSL_AD_DECODE_ERROR;
2664 if (!PACKET_get_bytes(pkt, &data, len)) {
2665 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
2666 al = SSL_AD_DECODE_ERROR;
2670 hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
2671 if (hdatalen <= 0) {
2672 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
2673 al = SSL_AD_INTERNAL_ERROR;
2677 fprintf(stderr, "Using client verify alg %s\n", EVP_MD_name(md));
2679 if (!EVP_VerifyInit_ex(mctx, md, NULL)
2680 || !EVP_VerifyUpdate(mctx, hdata, hdatalen)) {
2681 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
2682 al = SSL_AD_INTERNAL_ERROR;
2686 #ifndef OPENSSL_NO_GOST
2688 int pktype = EVP_PKEY_id(pkey);
2689 if (pktype == NID_id_GostR3410_2001
2690 || pktype == NID_id_GostR3410_2012_256
2691 || pktype == NID_id_GostR3410_2012_512) {
2692 if ((gost_data = OPENSSL_malloc(len)) == NULL) {
2693 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
2694 al = SSL_AD_INTERNAL_ERROR;
2697 BUF_reverse(gost_data, data, len);
2703 if (s->version == SSL3_VERSION
2704 && !EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
2705 s->session->master_key_length,
2706 s->session->master_key)) {
2707 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
2708 al = SSL_AD_INTERNAL_ERROR;
2712 if (EVP_VerifyFinal(mctx, data, len, pkey) <= 0) {
2713 al = SSL_AD_DECRYPT_ERROR;
2714 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_BAD_SIGNATURE);
2718 ret = MSG_PROCESS_CONTINUE_PROCESSING;
2721 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2722 ossl_statem_set_error(s);
2724 BIO_free(s->s3->handshake_buffer);
2725 s->s3->handshake_buffer = NULL;
2726 EVP_MD_CTX_free(mctx);
2727 #ifndef OPENSSL_NO_GOST
2728 OPENSSL_free(gost_data);
2733 MSG_PROCESS_RETURN tls_process_client_certificate(SSL *s, PACKET *pkt)
2735 int i, al = SSL_AD_INTERNAL_ERROR, ret = MSG_PROCESS_ERROR;
2737 unsigned long l, llen;
2738 const unsigned char *certstart, *certbytes;
2739 STACK_OF(X509) *sk = NULL;
2742 if ((sk = sk_X509_new_null()) == NULL) {
2743 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
2747 if (!PACKET_get_net_3(pkt, &llen)
2748 || !PACKET_get_sub_packet(pkt, &spkt, llen)
2749 || PACKET_remaining(pkt) != 0) {
2750 al = SSL_AD_DECODE_ERROR;
2751 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
2755 while (PACKET_remaining(&spkt) > 0) {
2756 if (!PACKET_get_net_3(&spkt, &l)
2757 || !PACKET_get_bytes(&spkt, &certbytes, l)) {
2758 al = SSL_AD_DECODE_ERROR;
2759 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
2760 SSL_R_CERT_LENGTH_MISMATCH);
2764 certstart = certbytes;
2765 x = d2i_X509(NULL, (const unsigned char **)&certbytes, l);
2767 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_ASN1_LIB);
2770 if (certbytes != (certstart + l)) {
2771 al = SSL_AD_DECODE_ERROR;
2772 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
2773 SSL_R_CERT_LENGTH_MISMATCH);
2776 if (!sk_X509_push(sk, x)) {
2777 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
2783 if (sk_X509_num(sk) <= 0) {
2784 /* TLS does not mind 0 certs returned */
2785 if (s->version == SSL3_VERSION) {
2786 al = SSL_AD_HANDSHAKE_FAILURE;
2787 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
2788 SSL_R_NO_CERTIFICATES_RETURNED);
2791 /* Fail for TLS only if we required a certificate */
2792 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
2793 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
2794 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
2795 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2796 al = SSL_AD_HANDSHAKE_FAILURE;
2799 /* No client certificate so digest cached records */
2800 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s, 0)) {
2805 i = ssl_verify_cert_chain(s, sk);
2807 al = ssl_verify_alarm_type(s->verify_result);
2808 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
2809 SSL_R_CERTIFICATE_VERIFY_FAILED);
2813 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, i);
2814 al = SSL_AD_HANDSHAKE_FAILURE;
2817 pkey = X509_get0_pubkey(sk_X509_value(sk, 0));
2819 al = SSL3_AD_HANDSHAKE_FAILURE;
2820 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
2821 SSL_R_UNKNOWN_CERTIFICATE_TYPE);
2826 X509_free(s->session->peer);
2827 s->session->peer = sk_X509_shift(sk);
2828 s->session->verify_result = s->verify_result;
2830 sk_X509_pop_free(s->session->peer_chain, X509_free);
2831 s->session->peer_chain = sk;
2833 * Inconsistency alert: cert_chain does *not* include the peer's own
2834 * certificate, while we do include it in statem_clnt.c
2837 ret = MSG_PROCESS_CONTINUE_READING;
2841 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2842 ossl_statem_set_error(s);
2845 sk_X509_pop_free(sk, X509_free);
2849 int tls_construct_server_certificate(SSL *s)
2853 cpk = ssl_get_server_send_pkey(s);
2855 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
2856 ossl_statem_set_error(s);
2860 if (!ssl3_output_cert_chain(s, cpk)) {
2861 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
2862 ossl_statem_set_error(s);
2869 int tls_construct_new_session_ticket(SSL *s)
2871 unsigned char *senc = NULL;
2872 EVP_CIPHER_CTX *ctx;
2873 HMAC_CTX *hctx = NULL;
2874 unsigned char *p, *macstart;
2875 const unsigned char *const_p;
2876 int len, slen_full, slen;
2879 SSL_CTX *tctx = s->initial_ctx;
2880 unsigned char iv[EVP_MAX_IV_LENGTH];
2881 unsigned char key_name[TLSEXT_KEYNAME_LENGTH];
2884 /* get session encoding length */
2885 slen_full = i2d_SSL_SESSION(s->session, NULL);
2887 * Some length values are 16 bits, so forget it if session is too
2890 if (slen_full == 0 || slen_full > 0xFF00) {
2891 ossl_statem_set_error(s);
2894 senc = OPENSSL_malloc(slen_full);
2896 ossl_statem_set_error(s);
2900 ctx = EVP_CIPHER_CTX_new();
2901 hctx = HMAC_CTX_new();
2904 if (!i2d_SSL_SESSION(s->session, &p))
2908 * create a fresh copy (not shared with other threads) to clean up
2911 sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
2914 sess->session_id_length = 0; /* ID is irrelevant for the ticket */
2916 slen = i2d_SSL_SESSION(sess, NULL);
2917 if (slen == 0 || slen > slen_full) { /* shouldn't ever happen */
2918 SSL_SESSION_free(sess);
2922 if (!i2d_SSL_SESSION(sess, &p)) {
2923 SSL_SESSION_free(sess);
2926 SSL_SESSION_free(sess);
2929 * Grow buffer if need be: the length calculation is as
2930 * follows handshake_header_length +
2931 * 4 (ticket lifetime hint) + 2 (ticket length) +
2932 * sizeof(keyname) + max_iv_len (iv length) +
2933 * max_enc_block_size (max encrypted session * length) +
2934 * max_md_size (HMAC) + session_length.
2936 if (!BUF_MEM_grow(s->init_buf,
2937 SSL_HM_HEADER_LENGTH(s) + 6 + sizeof(key_name) +
2938 EVP_MAX_IV_LENGTH + EVP_MAX_BLOCK_LENGTH +
2939 EVP_MAX_MD_SIZE + slen))
2942 p = ssl_handshake_start(s);
2944 * Initialize HMAC and cipher contexts. If callback present it does
2945 * all the work otherwise use generated values from parent ctx.
2947 if (tctx->tlsext_ticket_key_cb) {
2948 if (tctx->tlsext_ticket_key_cb(s, key_name, iv, ctx, hctx, 1) < 0)
2950 iv_len = EVP_CIPHER_CTX_iv_length(ctx);
2952 const EVP_CIPHER *cipher = EVP_aes_256_cbc();
2954 iv_len = EVP_CIPHER_iv_length(cipher);
2955 if (RAND_bytes(iv, iv_len) <= 0)
2957 if (!EVP_EncryptInit_ex(ctx, cipher, NULL,
2958 tctx->tlsext_tick_aes_key, iv))
2960 if (!HMAC_Init_ex(hctx, tctx->tlsext_tick_hmac_key,
2961 sizeof(tctx->tlsext_tick_hmac_key),
2962 EVP_sha256(), NULL))
2964 memcpy(key_name, tctx->tlsext_tick_key_name,
2965 sizeof(tctx->tlsext_tick_key_name));
2969 * Ticket lifetime hint (advisory only): We leave this unspecified
2970 * for resumed session (for simplicity), and guess that tickets for
2971 * new sessions will live as long as their sessions.
2973 l2n(s->hit ? 0 : s->session->timeout, p);
2975 /* Skip ticket length for now */
2977 /* Output key name */
2979 memcpy(p, key_name, sizeof(key_name));
2980 p += sizeof(key_name);
2982 memcpy(p, iv, iv_len);
2984 /* Encrypt session data */
2985 if (!EVP_EncryptUpdate(ctx, p, &len, senc, slen))
2988 if (!EVP_EncryptFinal(ctx, p, &len))
2992 if (!HMAC_Update(hctx, macstart, p - macstart))
2994 if (!HMAC_Final(hctx, p, &hlen))
2997 EVP_CIPHER_CTX_free(ctx);
2998 HMAC_CTX_free(hctx);
3003 /* Now write out lengths: p points to end of data written */
3005 len = p - ssl_handshake_start(s);
3006 /* Skip ticket lifetime hint */
3007 p = ssl_handshake_start(s) + 4;
3009 if (!ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len))
3016 EVP_CIPHER_CTX_free(ctx);
3017 HMAC_CTX_free(hctx);
3018 ossl_statem_set_error(s);
3022 int tls_construct_cert_status(SSL *s)
3026 * Grow buffer if need be: the length calculation is as
3027 * follows 1 (message type) + 3 (message length) +
3028 * 1 (ocsp response type) + 3 (ocsp response length)
3031 if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen)) {
3032 ossl_statem_set_error(s);
3036 p = (unsigned char *)s->init_buf->data;
3039 *(p++) = SSL3_MT_CERTIFICATE_STATUS;
3040 /* message length */
3041 l2n3(s->tlsext_ocsp_resplen + 4, p);
3043 *(p++) = s->tlsext_status_type;
3044 /* length of OCSP response */
3045 l2n3(s->tlsext_ocsp_resplen, p);
3046 /* actual response */
3047 memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
3048 /* number of bytes to write */
3049 s->init_num = 8 + s->tlsext_ocsp_resplen;
3055 #ifndef OPENSSL_NO_NEXTPROTONEG
3057 * tls_process_next_proto reads a Next Protocol Negotiation handshake message.
3058 * It sets the next_proto member in s if found
3060 MSG_PROCESS_RETURN tls_process_next_proto(SSL *s, PACKET *pkt)
3062 PACKET next_proto, padding;
3063 size_t next_proto_len;
3066 * The payload looks like:
3068 * uint8 proto[proto_len];
3069 * uint8 padding_len;
3070 * uint8 padding[padding_len];
3072 if (!PACKET_get_length_prefixed_1(pkt, &next_proto)
3073 || !PACKET_get_length_prefixed_1(pkt, &padding)
3074 || PACKET_remaining(pkt) > 0) {
3075 SSLerr(SSL_F_TLS_PROCESS_NEXT_PROTO, SSL_R_LENGTH_MISMATCH);
3079 if (!PACKET_memdup(&next_proto, &s->next_proto_negotiated,
3081 s->next_proto_negotiated_len = 0;
3085 s->next_proto_negotiated_len = (unsigned char)next_proto_len;
3087 return MSG_PROCESS_CONTINUE_READING;
3089 ossl_statem_set_error(s);
3090 return MSG_PROCESS_ERROR;
3094 #define SSLV2_CIPHER_LEN 3
3096 STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list(SSL *s,
3097 PACKET *cipher_suites,
3098 STACK_OF(SSL_CIPHER) **skp,
3099 int sslv2format, int *al
3102 const SSL_CIPHER *c;
3103 STACK_OF(SSL_CIPHER) *sk;
3105 /* 3 = SSLV2_CIPHER_LEN > TLS_CIPHER_LEN = 2. */
3106 unsigned char cipher[SSLV2_CIPHER_LEN];
3108 s->s3->send_connection_binding = 0;
3110 n = sslv2format ? SSLV2_CIPHER_LEN : TLS_CIPHER_LEN;
3112 if (PACKET_remaining(cipher_suites) == 0) {
3113 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, SSL_R_NO_CIPHERS_SPECIFIED);
3114 *al = SSL_AD_ILLEGAL_PARAMETER;
3118 if (PACKET_remaining(cipher_suites) % n != 0) {
3119 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
3120 SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
3121 *al = SSL_AD_DECODE_ERROR;
3125 if ((skp == NULL) || (*skp == NULL)) {
3126 sk = sk_SSL_CIPHER_new_null(); /* change perhaps later */
3128 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
3129 *al = SSL_AD_INTERNAL_ERROR;
3134 sk_SSL_CIPHER_zero(sk);
3137 if (!PACKET_memdup(cipher_suites, &s->s3->tmp.ciphers_raw,
3138 &s->s3->tmp.ciphers_rawlen)) {
3139 *al = SSL_AD_INTERNAL_ERROR;
3143 while (PACKET_copy_bytes(cipher_suites, cipher, n)) {
3145 * SSLv3 ciphers wrapped in an SSLv2-compatible ClientHello have the
3146 * first byte set to zero, while true SSLv2 ciphers have a non-zero
3147 * first byte. We don't support any true SSLv2 ciphers, so skip them.
3149 if (sslv2format && cipher[0] != '\0')
3152 /* Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV */
3153 if ((cipher[n - 2] == ((SSL3_CK_SCSV >> 8) & 0xff)) &&
3154 (cipher[n - 1] == (SSL3_CK_SCSV & 0xff))) {
3155 /* SCSV fatal if renegotiating */
3156 if (s->renegotiate) {
3157 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
3158 SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING);
3159 *al = SSL_AD_HANDSHAKE_FAILURE;
3162 s->s3->send_connection_binding = 1;
3166 /* Check for TLS_FALLBACK_SCSV */
3167 if ((cipher[n - 2] == ((SSL3_CK_FALLBACK_SCSV >> 8) & 0xff)) &&
3168 (cipher[n - 1] == (SSL3_CK_FALLBACK_SCSV & 0xff))) {
3170 * The SCSV indicates that the client previously tried a higher
3171 * version. Fail if the current version is an unexpected
3174 if (!ssl_check_version_downgrade(s)) {
3175 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
3176 SSL_R_INAPPROPRIATE_FALLBACK);
3177 *al = SSL_AD_INAPPROPRIATE_FALLBACK;
3183 /* For SSLv2-compat, ignore leading 0-byte. */
3184 c = ssl_get_cipher_by_char(s, sslv2format ? &cipher[1] : cipher);
3186 if (!sk_SSL_CIPHER_push(sk, c)) {
3187 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
3188 *al = SSL_AD_INTERNAL_ERROR;
3193 if (PACKET_remaining(cipher_suites) > 0) {
3194 *al = SSL_AD_INTERNAL_ERROR;
3195 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_INTERNAL_ERROR);
3203 if ((skp == NULL) || (*skp == NULL))
3204 sk_SSL_CIPHER_free(sk);