1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
4 * This package is an SSL implementation written
5 * by Eric Young (eay@cryptsoft.com).
6 * The implementation was written so as to conform with Netscapes SSL.
8 * This library is free for commercial and non-commercial use as long as
9 * the following conditions are aheared to. The following conditions
10 * apply to all code found in this distribution, be it the RC4, RSA,
11 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
12 * included with this distribution is covered by the same copyright terms
13 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15 * Copyright remains Eric Young's, and as such any Copyright notices in
16 * the code are not to be removed.
17 * If this package is used in a product, Eric Young should be given attribution
18 * as the author of the parts of the library used.
19 * This can be in the form of a textual message at program startup or
20 * in documentation (online or textual) provided with the package.
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
25 * 1. Redistributions of source code must retain the copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
30 * 3. All advertising materials mentioning features or use of this software
31 * must display the following acknowledgement:
32 * "This product includes cryptographic software written by
33 * Eric Young (eay@cryptsoft.com)"
34 * The word 'cryptographic' can be left out if the rouines from the library
35 * being used are not cryptographic related :-).
36 * 4. If you include any Windows specific code (or a derivative thereof) from
37 * the apps directory (application code) you must include an acknowledgement:
38 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
52 * The licence and distribution terms for any publically available version or
53 * derivative of this code cannot be changed. i.e. this code cannot simply be
54 * copied and put under another distribution licence
55 * [including the GNU Public Licence.]
57 /* ====================================================================
58 * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
60 * Redistribution and use in source and binary forms, with or without
61 * modification, are permitted provided that the following conditions
64 * 1. Redistributions of source code must retain the above copyright
65 * notice, this list of conditions and the following disclaimer.
67 * 2. Redistributions in binary form must reproduce the above copyright
68 * notice, this list of conditions and the following disclaimer in
69 * the documentation and/or other materials provided with the
72 * 3. All advertising materials mentioning features or use of this
73 * software must display the following acknowledgment:
74 * "This product includes software developed by the OpenSSL Project
75 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78 * endorse or promote products derived from this software without
79 * prior written permission. For written permission, please contact
80 * openssl-core@openssl.org.
82 * 5. Products derived from this software may not be called "OpenSSL"
83 * nor may "OpenSSL" appear in their names without prior written
84 * permission of the OpenSSL Project.
86 * 6. Redistributions of any form whatsoever must retain the following
88 * "This product includes software developed by the OpenSSL Project
89 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
95 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102 * OF THE POSSIBILITY OF SUCH DAMAGE.
103 * ====================================================================
105 * This product includes cryptographic software written by Eric Young
106 * (eay@cryptsoft.com). This product includes software written by Tim
107 * Hudson (tjh@cryptsoft.com).
110 /* ====================================================================
111 * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
113 * Portions of the attached software ("Contribution") are developed by
114 * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
116 * The Contribution is licensed pursuant to the OpenSSL open source
117 * license provided above.
119 * ECC cipher suite support in OpenSSL originally written by
120 * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
123 /* ====================================================================
124 * Copyright 2005 Nokia. All rights reserved.
126 * The portions of the attached software ("Contribution") is developed by
127 * Nokia Corporation and is licensed pursuant to the OpenSSL open source
130 * The Contribution, originally written by Mika Kousa and Pasi Eronen of
131 * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
132 * support (see RFC 4279) to OpenSSL.
134 * No patent licenses or other rights except those expressly stated in
135 * the OpenSSL open source license shall be deemed granted or received
136 * expressly, by implication, estoppel, or otherwise.
138 * No assurances are provided by Nokia that the Contribution does not
139 * infringe the patent or other intellectual property rights of any third
140 * party or that the license provides you with all the necessary rights
141 * to make use of the Contribution.
143 * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
144 * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
145 * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
146 * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
152 #include "../ssl_locl.h"
153 #include "statem_locl.h"
154 #include "internal/constant_time_locl.h"
155 #include <openssl/buffer.h>
156 #include <openssl/rand.h>
157 #include <openssl/objects.h>
158 #include <openssl/evp.h>
159 #include <openssl/hmac.h>
160 #include <openssl/x509.h>
161 #include <openssl/dh.h>
162 #include <openssl/bn.h>
163 #include <openssl/md5.h>
165 static STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list(SSL *s,
166 PACKET *cipher_suites,
167 STACK_OF(SSL_CIPHER) **skp,
168 int sslv2format, int *al);
171 * server_read_transition() encapsulates the logic for the allowed handshake
172 * state transitions when the server is reading messages from the client. The
173 * message type that the client has sent is provided in |mt|. The current state
174 * is in |s->statem.hand_state|.
176 * Valid return values are:
177 * 1: Success (transition allowed)
178 * 0: Error (transition not allowed)
180 int ossl_statem_server_read_transition(SSL *s, int mt)
182 OSSL_STATEM *st = &s->statem;
184 switch(st->hand_state) {
186 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
187 if (mt == SSL3_MT_CLIENT_HELLO) {
188 st->hand_state = TLS_ST_SR_CLNT_HELLO;
193 case TLS_ST_SW_SRVR_DONE:
195 * If we get a CKE message after a ServerDone then either
196 * 1) We didn't request a Certificate
198 * 2) If we did request one then
199 * a) We allow no Certificate to be returned
201 * b) We are running SSL3 (in TLS1.0+ the client must return a 0
202 * list if we requested a certificate)
204 if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE
205 && (!s->s3->tmp.cert_request
206 || (!((s->verify_mode & SSL_VERIFY_PEER) &&
207 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
208 && (s->version == SSL3_VERSION)))) {
209 st->hand_state = TLS_ST_SR_KEY_EXCH;
211 } else if (s->s3->tmp.cert_request) {
212 if (mt == SSL3_MT_CERTIFICATE) {
213 st->hand_state = TLS_ST_SR_CERT;
220 if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) {
221 st->hand_state = TLS_ST_SR_KEY_EXCH;
226 case TLS_ST_SR_KEY_EXCH:
228 * We should only process a CertificateVerify message if we have
229 * received a Certificate from the client. If so then |s->session->peer|
230 * will be non NULL. In some instances a CertificateVerify message is
231 * not required even if the peer has sent a Certificate (e.g. such as in
232 * the case of static DH). In that case |st->no_cert_verify| should be
235 if (s->session->peer == NULL || st->no_cert_verify) {
236 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
238 * For the ECDH ciphersuites when the client sends its ECDH
239 * pub key in a certificate, the CertificateVerify message is
240 * not sent. Also for GOST ciphersuites when the client uses
241 * its key from the certificate for key exchange.
243 st->hand_state = TLS_ST_SR_CHANGE;
247 if (mt == SSL3_MT_CERTIFICATE_VERIFY) {
248 st->hand_state = TLS_ST_SR_CERT_VRFY;
254 case TLS_ST_SR_CERT_VRFY:
255 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
256 st->hand_state = TLS_ST_SR_CHANGE;
261 case TLS_ST_SR_CHANGE:
262 #ifndef OPENSSL_NO_NEXTPROTONEG
263 if (s->s3->next_proto_neg_seen) {
264 if (mt == SSL3_MT_NEXT_PROTO) {
265 st->hand_state = TLS_ST_SR_NEXT_PROTO;
270 if (mt == SSL3_MT_FINISHED) {
271 st->hand_state = TLS_ST_SR_FINISHED;
274 #ifndef OPENSSL_NO_NEXTPROTONEG
279 #ifndef OPENSSL_NO_NEXTPROTONEG
280 case TLS_ST_SR_NEXT_PROTO:
281 if (mt == SSL3_MT_FINISHED) {
282 st->hand_state = TLS_ST_SR_FINISHED;
288 case TLS_ST_SW_FINISHED:
289 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
290 st->hand_state = TLS_ST_SR_CHANGE;
299 /* No valid transition found */
304 * Should we send a ServerKeyExchange message?
306 * Valid return values are:
310 static int send_server_key_exchange(SSL *s)
312 unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
315 * only send a ServerKeyExchange if DH or fortezza but we have a
316 * sign only certificate PSK: may send PSK identity hints For
317 * ECC ciphersuites, we send a serverKeyExchange message only if
318 * the cipher suite is either ECDH-anon or ECDHE. In other cases,
319 * the server certificate contains the server's public key for
322 if (alg_k & (SSL_kDHE|SSL_kECDHE)
324 * PSK: send ServerKeyExchange if PSK identity hint if
327 #ifndef OPENSSL_NO_PSK
328 /* Only send SKE if we have identity hint for plain PSK */
329 || ((alg_k & (SSL_kPSK | SSL_kRSAPSK))
330 && s->cert->psk_identity_hint)
331 /* For other PSK always send SKE */
332 || (alg_k & (SSL_PSK & (SSL_kDHEPSK | SSL_kECDHEPSK)))
334 #ifndef OPENSSL_NO_SRP
335 /* SRP: send ServerKeyExchange */
336 || (alg_k & SSL_kSRP)
346 * Should we send a CertificateRequest message?
348 * Valid return values are:
352 static int send_certificate_request(SSL *s)
355 /* don't request cert unless asked for it: */
356 s->verify_mode & SSL_VERIFY_PEER
358 * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert
359 * during re-negotiation:
361 && ((s->session->peer == NULL) ||
362 !(s->verify_mode & SSL_VERIFY_CLIENT_ONCE))
364 * never request cert in anonymous ciphersuites (see
365 * section "Certificate request" in SSL 3 drafts and in
368 && (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
370 * ... except when the application insists on
371 * verification (against the specs, but s3_clnt.c accepts
374 || (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
375 /* don't request certificate for SRP auth */
376 && !(s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)
378 * With normal PSK Certificates and Certificate Requests
381 && !(s->s3->tmp.new_cipher->algorithm_auth & SSL_aPSK)) {
389 * server_write_transition() works out what handshake state to move to next
390 * when the server is writing messages to be sent to the client.
392 WRITE_TRAN ossl_statem_server_write_transition(SSL *s)
394 OSSL_STATEM *st = &s->statem;
396 switch(st->hand_state) {
398 /* Just go straight to trying to read from the client */;
399 return WRITE_TRAN_FINISHED;
402 /* We must be trying to renegotiate */
403 st->hand_state = TLS_ST_SW_HELLO_REQ;
404 return WRITE_TRAN_CONTINUE;
406 case TLS_ST_SW_HELLO_REQ:
407 st->hand_state = TLS_ST_OK;
408 ossl_statem_set_in_init(s, 0);
409 return WRITE_TRAN_CONTINUE;
411 case TLS_ST_SR_CLNT_HELLO:
412 if (SSL_IS_DTLS(s) && !s->d1->cookie_verified
413 && (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE))
414 st->hand_state = DTLS_ST_SW_HELLO_VERIFY_REQUEST;
416 st->hand_state = TLS_ST_SW_SRVR_HELLO;
417 return WRITE_TRAN_CONTINUE;
419 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
420 return WRITE_TRAN_FINISHED;
422 case TLS_ST_SW_SRVR_HELLO:
424 if (s->tlsext_ticket_expected)
425 st->hand_state = TLS_ST_SW_SESSION_TICKET;
427 st->hand_state = TLS_ST_SW_CHANGE;
429 /* Check if it is anon DH or anon ECDH, */
430 /* normal PSK or SRP */
431 if (!(s->s3->tmp.new_cipher->algorithm_auth &
432 (SSL_aNULL | SSL_aSRP | SSL_aPSK))) {
433 st->hand_state = TLS_ST_SW_CERT;
434 } else if (send_server_key_exchange(s)) {
435 st->hand_state = TLS_ST_SW_KEY_EXCH;
436 } else if (send_certificate_request(s)) {
437 st->hand_state = TLS_ST_SW_CERT_REQ;
439 st->hand_state = TLS_ST_SW_SRVR_DONE;
442 return WRITE_TRAN_CONTINUE;
445 if (s->tlsext_status_expected) {
446 st->hand_state = TLS_ST_SW_CERT_STATUS;
447 return WRITE_TRAN_CONTINUE;
451 case TLS_ST_SW_CERT_STATUS:
452 if (send_server_key_exchange(s)) {
453 st->hand_state = TLS_ST_SW_KEY_EXCH;
454 return WRITE_TRAN_CONTINUE;
458 case TLS_ST_SW_KEY_EXCH:
459 if (send_certificate_request(s)) {
460 st->hand_state = TLS_ST_SW_CERT_REQ;
461 return WRITE_TRAN_CONTINUE;
465 case TLS_ST_SW_CERT_REQ:
466 st->hand_state = TLS_ST_SW_SRVR_DONE;
467 return WRITE_TRAN_CONTINUE;
469 case TLS_ST_SW_SRVR_DONE:
470 return WRITE_TRAN_FINISHED;
472 case TLS_ST_SR_FINISHED:
474 st->hand_state = TLS_ST_OK;
475 ossl_statem_set_in_init(s, 0);
476 return WRITE_TRAN_CONTINUE;
477 } else if (s->tlsext_ticket_expected) {
478 st->hand_state = TLS_ST_SW_SESSION_TICKET;
480 st->hand_state = TLS_ST_SW_CHANGE;
482 return WRITE_TRAN_CONTINUE;
484 case TLS_ST_SW_SESSION_TICKET:
485 st->hand_state = TLS_ST_SW_CHANGE;
486 return WRITE_TRAN_CONTINUE;
488 case TLS_ST_SW_CHANGE:
489 st->hand_state = TLS_ST_SW_FINISHED;
490 return WRITE_TRAN_CONTINUE;
492 case TLS_ST_SW_FINISHED:
494 return WRITE_TRAN_FINISHED;
496 st->hand_state = TLS_ST_OK;
497 ossl_statem_set_in_init(s, 0);
498 return WRITE_TRAN_CONTINUE;
501 /* Shouldn't happen */
502 return WRITE_TRAN_ERROR;
507 * Perform any pre work that needs to be done prior to sending a message from
508 * the server to the client.
510 WORK_STATE ossl_statem_server_pre_work(SSL *s, WORK_STATE wst)
512 OSSL_STATEM *st = &s->statem;
514 switch(st->hand_state) {
515 case TLS_ST_SW_HELLO_REQ:
518 dtls1_clear_record_buffer(s);
521 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
523 if (SSL_IS_DTLS(s)) {
524 dtls1_clear_record_buffer(s);
525 /* We don't buffer this message so don't use the timer */
530 case TLS_ST_SW_SRVR_HELLO:
531 if (SSL_IS_DTLS(s)) {
533 * Messages we write from now on should be bufferred and
534 * retransmitted if necessary, so we need to use the timer now
540 case TLS_ST_SW_SRVR_DONE:
541 #ifndef OPENSSL_NO_SCTP
542 if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s)))
543 return dtls_wait_for_dry(s);
545 return WORK_FINISHED_CONTINUE;
547 case TLS_ST_SW_SESSION_TICKET:
548 if (SSL_IS_DTLS(s)) {
550 * We're into the last flight. We don't retransmit the last flight
551 * unless we need to, so we don't use the timer
557 case TLS_ST_SW_CHANGE:
558 s->session->cipher = s->s3->tmp.new_cipher;
559 if (!s->method->ssl3_enc->setup_key_block(s)) {
560 ossl_statem_set_error(s);
563 if (SSL_IS_DTLS(s)) {
565 * We're into the last flight. We don't retransmit the last flight
566 * unless we need to, so we don't use the timer. This might have
567 * already been set to 0 if we sent a NewSessionTicket message,
568 * but we'll set it again here in case we didn't.
572 return WORK_FINISHED_CONTINUE;
575 return tls_finish_handshake(s, wst);
578 /* No pre work to be done */
582 return WORK_FINISHED_CONTINUE;
586 * Perform any work that needs to be done after sending a message from the
587 * server to the client.
589 WORK_STATE ossl_statem_server_post_work(SSL *s, WORK_STATE wst)
591 OSSL_STATEM *st = &s->statem;
595 switch(st->hand_state) {
596 case TLS_ST_SW_HELLO_REQ:
597 if (statem_flush(s) != 1)
599 ssl3_init_finished_mac(s);
602 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
603 if (statem_flush(s) != 1)
605 /* HelloVerifyRequest resets Finished MAC */
606 if (s->version != DTLS1_BAD_VER)
607 ssl3_init_finished_mac(s);
609 * The next message should be another ClientHello which we need to
610 * treat like it was the first packet
615 case TLS_ST_SW_SRVR_HELLO:
616 #ifndef OPENSSL_NO_SCTP
617 if (SSL_IS_DTLS(s) && s->hit) {
618 unsigned char sctpauthkey[64];
619 char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
622 * Add new shared key for SCTP-Auth, will be ignored if no
625 memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
626 sizeof(DTLS1_SCTP_AUTH_LABEL));
628 if (SSL_export_keying_material(s, sctpauthkey,
629 sizeof(sctpauthkey), labelbuffer,
630 sizeof(labelbuffer), NULL, 0, 0) <= 0) {
631 ossl_statem_set_error(s);
635 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
636 sizeof(sctpauthkey), sctpauthkey);
641 case TLS_ST_SW_CHANGE:
642 #ifndef OPENSSL_NO_SCTP
643 if (SSL_IS_DTLS(s) && !s->hit) {
645 * Change to new shared key of SCTP-Auth, will be ignored if
648 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
652 if (!s->method->ssl3_enc->change_cipher_state(s,
653 SSL3_CHANGE_CIPHER_SERVER_WRITE)) {
654 ossl_statem_set_error(s);
659 dtls1_reset_seq_numbers(s, SSL3_CC_WRITE);
662 case TLS_ST_SW_SRVR_DONE:
663 if (statem_flush(s) != 1)
667 case TLS_ST_SW_FINISHED:
668 if (statem_flush(s) != 1)
670 #ifndef OPENSSL_NO_SCTP
671 if (SSL_IS_DTLS(s) && s->hit) {
673 * Change to new shared key of SCTP-Auth, will be ignored if
676 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
683 /* No post work to be done */
687 return WORK_FINISHED_CONTINUE;
691 * Construct a message to be sent from the server to the client.
693 * Valid return values are:
697 int ossl_statem_server_construct_message(SSL *s)
699 OSSL_STATEM *st = &s->statem;
701 switch(st->hand_state) {
702 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
703 return dtls_construct_hello_verify_request(s);
705 case TLS_ST_SW_HELLO_REQ:
706 return tls_construct_hello_request(s);
708 case TLS_ST_SW_SRVR_HELLO:
709 return tls_construct_server_hello(s);
712 return tls_construct_server_certificate(s);
714 case TLS_ST_SW_KEY_EXCH:
715 return tls_construct_server_key_exchange(s);
717 case TLS_ST_SW_CERT_REQ:
718 return tls_construct_certificate_request(s);
720 case TLS_ST_SW_SRVR_DONE:
721 return tls_construct_server_done(s);
723 case TLS_ST_SW_SESSION_TICKET:
724 return tls_construct_new_session_ticket(s);
726 case TLS_ST_SW_CERT_STATUS:
727 return tls_construct_cert_status(s);
729 case TLS_ST_SW_CHANGE:
731 return dtls_construct_change_cipher_spec(s);
733 return tls_construct_change_cipher_spec(s);
735 case TLS_ST_SW_FINISHED:
736 return tls_construct_finished(s,
738 ssl3_enc->server_finished_label,
740 ssl3_enc->server_finished_label_len);
743 /* Shouldn't happen */
750 #define CLIENT_KEY_EXCH_MAX_LENGTH 2048
751 #define NEXT_PROTO_MAX_LENGTH 514
754 * Returns the maximum allowed length for the current message that we are
755 * reading. Excludes the message header.
757 unsigned long ossl_statem_server_max_message_size(SSL *s)
759 OSSL_STATEM *st = &s->statem;
761 switch(st->hand_state) {
762 case TLS_ST_SR_CLNT_HELLO:
763 return SSL3_RT_MAX_PLAIN_LENGTH;
766 return s->max_cert_list;
768 case TLS_ST_SR_KEY_EXCH:
769 return CLIENT_KEY_EXCH_MAX_LENGTH;
771 case TLS_ST_SR_CERT_VRFY:
772 return SSL3_RT_MAX_PLAIN_LENGTH;
774 #ifndef OPENSSL_NO_NEXTPROTONEG
775 case TLS_ST_SR_NEXT_PROTO:
776 return NEXT_PROTO_MAX_LENGTH;
779 case TLS_ST_SR_CHANGE:
780 return CCS_MAX_LENGTH;
782 case TLS_ST_SR_FINISHED:
783 return FINISHED_MAX_LENGTH;
786 /* Shouldn't happen */
794 * Process a message that the server has received from the client.
796 MSG_PROCESS_RETURN ossl_statem_server_process_message(SSL *s, PACKET *pkt)
798 OSSL_STATEM *st = &s->statem;
800 switch(st->hand_state) {
801 case TLS_ST_SR_CLNT_HELLO:
802 return tls_process_client_hello(s, pkt);
805 return tls_process_client_certificate(s, pkt);
807 case TLS_ST_SR_KEY_EXCH:
808 return tls_process_client_key_exchange(s, pkt);
810 case TLS_ST_SR_CERT_VRFY:
811 return tls_process_cert_verify(s, pkt);
813 #ifndef OPENSSL_NO_NEXTPROTONEG
814 case TLS_ST_SR_NEXT_PROTO:
815 return tls_process_next_proto(s, pkt);
818 case TLS_ST_SR_CHANGE:
819 return tls_process_change_cipher_spec(s, pkt);
821 case TLS_ST_SR_FINISHED:
822 return tls_process_finished(s, pkt);
825 /* Shouldn't happen */
829 return MSG_PROCESS_ERROR;
833 * Perform any further processing required following the receipt of a message
836 WORK_STATE ossl_statem_server_post_process_message(SSL *s, WORK_STATE wst)
838 OSSL_STATEM *st = &s->statem;
840 switch(st->hand_state) {
841 case TLS_ST_SR_CLNT_HELLO:
842 return tls_post_process_client_hello(s, wst);
844 case TLS_ST_SR_KEY_EXCH:
845 return tls_post_process_client_key_exchange(s, wst);
847 case TLS_ST_SR_CERT_VRFY:
848 #ifndef OPENSSL_NO_SCTP
849 if ( /* Is this SCTP? */
850 BIO_dgram_is_sctp(SSL_get_wbio(s))
851 /* Are we renegotiating? */
853 && BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
854 s->s3->in_read_app_data = 2;
855 s->rwstate = SSL_READING;
856 BIO_clear_retry_flags(SSL_get_rbio(s));
857 BIO_set_retry_read(SSL_get_rbio(s));
858 ossl_statem_set_sctp_read_sock(s, 1);
861 ossl_statem_set_sctp_read_sock(s, 0);
864 return WORK_FINISHED_CONTINUE;
870 /* Shouldn't happen */
874 #ifndef OPENSSL_NO_SRP
875 static int ssl_check_srp_ext_ClientHello(SSL *s, int *al)
877 int ret = SSL_ERROR_NONE;
879 *al = SSL_AD_UNRECOGNIZED_NAME;
881 if ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) &&
882 (s->srp_ctx.TLS_ext_srp_username_callback != NULL)) {
883 if (s->srp_ctx.login == NULL) {
885 * RFC 5054 says SHOULD reject, we do so if There is no srp
889 *al = SSL_AD_UNKNOWN_PSK_IDENTITY;
891 ret = SSL_srp_server_param_with_username(s, al);
898 int tls_construct_hello_request(SSL *s)
900 if (!ssl_set_handshake_header(s, SSL3_MT_HELLO_REQUEST, 0)) {
901 SSLerr(SSL_F_TLS_CONSTRUCT_HELLO_REQUEST, ERR_R_INTERNAL_ERROR);
902 ossl_statem_set_error(s);
909 unsigned int dtls_raw_hello_verify_request(unsigned char *buf,
910 unsigned char *cookie,
911 unsigned char cookie_len)
913 unsigned int msg_len;
917 /* Always use DTLS 1.0 version: see RFC 6347 */
918 *(p++) = DTLS1_VERSION >> 8;
919 *(p++) = DTLS1_VERSION & 0xFF;
921 *(p++) = (unsigned char)cookie_len;
922 memcpy(p, cookie, cookie_len);
929 int dtls_construct_hello_verify_request(SSL *s)
934 buf = (unsigned char *)s->init_buf->data;
936 if (s->ctx->app_gen_cookie_cb == NULL ||
937 s->ctx->app_gen_cookie_cb(s, s->d1->cookie,
938 &(s->d1->cookie_len)) == 0 ||
939 s->d1->cookie_len > 255) {
940 SSLerr(SSL_F_DTLS_CONSTRUCT_HELLO_VERIFY_REQUEST,
941 SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
942 ossl_statem_set_error(s);
946 len = dtls_raw_hello_verify_request(&buf[DTLS1_HM_HEADER_LENGTH],
947 s->d1->cookie, s->d1->cookie_len);
949 dtls1_set_message_header(s, DTLS1_MT_HELLO_VERIFY_REQUEST, len, 0,
951 len += DTLS1_HM_HEADER_LENGTH;
953 /* number of bytes to write */
960 MSG_PROCESS_RETURN tls_process_client_hello(SSL *s, PACKET *pkt)
962 int i, al = SSL_AD_INTERNAL_ERROR;
963 unsigned int j, complen = 0;
966 #ifndef OPENSSL_NO_COMP
967 SSL_COMP *comp = NULL;
969 STACK_OF(SSL_CIPHER) *ciphers = NULL;
971 /* |cookie| will only be initialized for DTLS. */
972 PACKET session_id, cipher_suites, compression, extensions, cookie;
974 static const unsigned char null_compression = 0;
976 is_v2_record = RECORD_LAYER_is_sslv2_record(&s->rlayer);
978 PACKET_null_init(&cookie);
979 /* First lets get s->client_version set correctly */
981 unsigned int version;
984 * An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2
985 * header is sent directly on the wire, not wrapped as a TLS
986 * record. Our record layer just processes the message length and passes
987 * the rest right through. Its format is:
989 * 0-1 msg_length - decoded by the record layer
990 * 2 msg_type - s->init_msg points here
992 * 5-6 cipher_spec_length
993 * 7-8 session_id_length
994 * 9-10 challenge_length
998 if (!PACKET_get_1(pkt, &mt)
999 || mt != SSL2_MT_CLIENT_HELLO) {
1001 * Should never happen. We should have tested this in the record
1002 * layer in order to have determined that this is a SSLv2 record
1003 * in the first place
1005 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1009 if (!PACKET_get_net_2(pkt, &version)) {
1010 /* No protocol version supplied! */
1011 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
1014 if (version == 0x0002) {
1015 /* This is real SSLv2. We don't support it. */
1016 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
1018 } else if ((version & 0xff00) == (SSL3_VERSION_MAJOR << 8)) {
1020 s->client_version = version;
1022 /* No idea what protocol this is */
1023 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
1028 * use version from inside client hello, not from record header (may
1029 * differ: see RFC 2246, Appendix E, second paragraph)
1031 if(!PACKET_get_net_2(pkt, (unsigned int *)&s->client_version)) {
1032 al = SSL_AD_DECODE_ERROR;
1033 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1039 * Do SSL/TLS version negotiation if applicable. For DTLS we just check
1040 * versions are potentially compatible. Version negotiation comes later.
1042 if (!SSL_IS_DTLS(s)) {
1043 protverr = ssl_choose_server_version(s);
1044 } else if (s->method->version != DTLS_ANY_VERSION &&
1045 DTLS_VERSION_LT(s->client_version, s->version)) {
1046 protverr = SSL_R_VERSION_TOO_LOW;
1052 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, protverr);
1053 if ((!s->enc_write_ctx && !s->write_hash)) {
1055 * similar to ssl3_get_record, send alert using remote version
1058 s->version = s->client_version;
1060 al = SSL_AD_PROTOCOL_VERSION;
1064 /* Parse the message and load client random. */
1067 * Handle an SSLv2 backwards compatible ClientHello
1068 * Note, this is only for SSLv3+ using the backward compatible format.
1069 * Real SSLv2 is not supported, and is rejected above.
1071 unsigned int cipher_len, session_id_len, challenge_len;
1074 if (!PACKET_get_net_2(pkt, &cipher_len)
1075 || !PACKET_get_net_2(pkt, &session_id_len)
1076 || !PACKET_get_net_2(pkt, &challenge_len)) {
1077 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1078 SSL_R_RECORD_LENGTH_MISMATCH);
1079 al = SSL_AD_DECODE_ERROR;
1083 if (session_id_len > SSL_MAX_SSL_SESSION_ID_LENGTH) {
1084 al = SSL_AD_DECODE_ERROR;
1085 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1089 if (!PACKET_get_sub_packet(pkt, &cipher_suites, cipher_len)
1090 || !PACKET_get_sub_packet(pkt, &session_id, session_id_len)
1091 || !PACKET_get_sub_packet(pkt, &challenge, challenge_len)
1092 /* No extensions. */
1093 || PACKET_remaining(pkt) != 0) {
1094 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1095 SSL_R_RECORD_LENGTH_MISMATCH);
1096 al = SSL_AD_DECODE_ERROR;
1100 /* Load the client random and compression list. */
1101 challenge_len = challenge_len > SSL3_RANDOM_SIZE ? SSL3_RANDOM_SIZE :
1103 memset(s->s3->client_random, 0, SSL3_RANDOM_SIZE);
1104 if (!PACKET_copy_bytes(&challenge,
1105 s->s3->client_random + SSL3_RANDOM_SIZE -
1106 challenge_len, challenge_len)
1107 /* Advertise only null compression. */
1108 || !PACKET_buf_init(&compression, &null_compression, 1)) {
1109 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1110 al = SSL_AD_INTERNAL_ERROR;
1114 PACKET_null_init(&extensions);
1116 /* Regular ClientHello. */
1117 if (!PACKET_copy_bytes(pkt, s->s3->client_random, SSL3_RANDOM_SIZE)
1118 || !PACKET_get_length_prefixed_1(pkt, &session_id)) {
1119 al = SSL_AD_DECODE_ERROR;
1120 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1124 if (PACKET_remaining(&session_id) > SSL_MAX_SSL_SESSION_ID_LENGTH) {
1125 al = SSL_AD_DECODE_ERROR;
1126 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1130 if (SSL_IS_DTLS(s)) {
1131 if (!PACKET_get_length_prefixed_1(pkt, &cookie)) {
1132 al = SSL_AD_DECODE_ERROR;
1133 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1137 * If we require cookies and this ClientHello doesn't contain one,
1138 * just return since we do not want to allocate any memory yet.
1139 * So check cookie length...
1141 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1142 if (PACKET_remaining(&cookie) == 0)
1147 if (!PACKET_get_length_prefixed_2(pkt, &cipher_suites)
1148 || !PACKET_get_length_prefixed_1(pkt, &compression)) {
1149 al = SSL_AD_DECODE_ERROR;
1150 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1153 /* Could be empty. */
1157 if (SSL_IS_DTLS(s)) {
1158 /* Empty cookie was already handled above by returning early. */
1159 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1160 if (s->ctx->app_verify_cookie_cb != NULL) {
1161 if (s->ctx->app_verify_cookie_cb(s, PACKET_data(&cookie),
1162 PACKET_remaining(&cookie)) == 0) {
1163 al = SSL_AD_HANDSHAKE_FAILURE;
1164 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1165 SSL_R_COOKIE_MISMATCH);
1167 /* else cookie verification succeeded */
1169 /* default verification */
1170 } else if (!PACKET_equal(&cookie, s->d1->cookie,
1171 s->d1->cookie_len)) {
1172 al = SSL_AD_HANDSHAKE_FAILURE;
1173 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1176 s->d1->cookie_verified = 1;
1178 if (s->method->version == DTLS_ANY_VERSION) {
1179 protverr = ssl_choose_server_version(s);
1180 if (protverr != 0) {
1181 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, protverr);
1182 s->version = s->client_version;
1183 al = SSL_AD_PROTOCOL_VERSION;
1192 * We don't allow resumption in a backwards compatible ClientHello.
1193 * TODO(openssl-team): in TLS1.1+, session_id MUST be empty.
1195 * Versions before 0.9.7 always allow clients to resume sessions in
1196 * renegotiation. 0.9.7 and later allow this by default, but optionally
1197 * ignore resumption requests with flag
1198 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
1199 * than a change to default behavior so that applications relying on
1200 * this for security won't even compile against older library versions).
1201 * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
1202 * request renegotiation but not a new session (s->new_session remains
1203 * unset): for servers, this essentially just means that the
1204 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be
1209 (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
1210 if (!ssl_get_new_session(s, 1))
1213 i = ssl_get_prev_session(s, &extensions, &session_id);
1215 * Only resume if the session's version matches the negotiated
1217 * RFC 5246 does not provide much useful advice on resumption
1218 * with a different protocol version. It doesn't forbid it but
1219 * the sanity of such behaviour would be questionable.
1220 * In practice, clients do not accept a version mismatch and
1221 * will abort the handshake with an error.
1223 if (i == 1 && s->version == s->session->ssl_version) {
1224 /* previous session */
1226 } else if (i == -1) {
1230 if (!ssl_get_new_session(s, 1))
1235 if (ssl_bytes_to_cipher_list(s, &cipher_suites, &(ciphers),
1236 is_v2_record, &al) == NULL) {
1240 /* If it is a hit, check that the cipher is in the list */
1243 id = s->session->cipher->id;
1246 fprintf(stderr, "client sent %d ciphers\n",
1247 sk_SSL_CIPHER_num(ciphers));
1249 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1250 c = sk_SSL_CIPHER_value(ciphers, i);
1252 fprintf(stderr, "client [%2d of %2d]:%s\n",
1253 i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
1262 * we need to have the cipher in the cipher list if we are asked
1265 al = SSL_AD_ILLEGAL_PARAMETER;
1266 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1267 SSL_R_REQUIRED_CIPHER_MISSING);
1272 complen = PACKET_remaining(&compression);
1273 for (j = 0; j < complen; j++) {
1274 if (PACKET_data(&compression)[j] == 0)
1280 al = SSL_AD_DECODE_ERROR;
1281 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED);
1285 /* TLS extensions */
1286 if (s->version >= SSL3_VERSION) {
1287 if (!ssl_parse_clienthello_tlsext(s, &extensions)) {
1288 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_PARSE_TLSEXT);
1294 * Check if we want to use external pre-shared secret for this handshake
1295 * for not reused session only. We need to generate server_random before
1296 * calling tls_session_secret_cb in order to allow SessionTicket
1297 * processing to use it in key derivation.
1301 pos = s->s3->server_random;
1302 if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0) {
1307 if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb) {
1308 const SSL_CIPHER *pref_cipher = NULL;
1310 s->session->master_key_length = sizeof(s->session->master_key);
1311 if (s->tls_session_secret_cb(s, s->session->master_key,
1312 &s->session->master_key_length, ciphers,
1314 s->tls_session_secret_cb_arg)) {
1316 s->session->ciphers = ciphers;
1317 s->session->verify_result = X509_V_OK;
1321 /* check if some cipher was preferred by call back */
1323 pref_cipher ? pref_cipher : ssl3_choose_cipher(s,
1328 if (pref_cipher == NULL) {
1329 al = SSL_AD_HANDSHAKE_FAILURE;
1330 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1334 s->session->cipher = pref_cipher;
1335 sk_SSL_CIPHER_free(s->cipher_list);
1336 s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1337 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1338 s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1343 * Worst case, we will use the NULL compression, but if we have other
1344 * options, we will now look for them. We have complen-1 compression
1345 * algorithms from the client, starting at q.
1347 s->s3->tmp.new_compression = NULL;
1348 #ifndef OPENSSL_NO_COMP
1349 /* This only happens if we have a cache hit */
1350 if (s->session->compress_meth != 0) {
1351 int m, comp_id = s->session->compress_meth;
1353 /* Perform sanity checks on resumed compression algorithm */
1354 /* Can't disable compression */
1355 if (!ssl_allow_compression(s)) {
1356 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1357 SSL_R_INCONSISTENT_COMPRESSION);
1360 /* Look for resumed compression method */
1361 for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) {
1362 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1363 if (comp_id == comp->id) {
1364 s->s3->tmp.new_compression = comp;
1368 if (s->s3->tmp.new_compression == NULL) {
1369 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1370 SSL_R_INVALID_COMPRESSION_ALGORITHM);
1373 /* Look for resumed method in compression list */
1374 for (k = 0; k < complen; k++) {
1375 if (PACKET_data(&compression)[k] == comp_id)
1379 al = SSL_AD_ILLEGAL_PARAMETER;
1380 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1381 SSL_R_REQUIRED_COMPRESSION_ALGORITHM_MISSING);
1386 else if (ssl_allow_compression(s) && s->ctx->comp_methods) {
1387 /* See if we have a match */
1388 int m, nn, v, done = 0;
1391 nn = sk_SSL_COMP_num(s->ctx->comp_methods);
1392 for (m = 0; m < nn; m++) {
1393 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1395 for (o = 0; o < complen; o++) {
1396 if (v == PACKET_data(&compression)[o]) {
1405 s->s3->tmp.new_compression = comp;
1411 * If compression is disabled we'd better not try to resume a session
1412 * using compression.
1414 if (s->session->compress_meth != 0) {
1415 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
1421 * Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher
1425 #ifdef OPENSSL_NO_COMP
1426 s->session->compress_meth = 0;
1428 s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
1430 sk_SSL_CIPHER_free(s->session->ciphers);
1431 s->session->ciphers = ciphers;
1432 if (ciphers == NULL) {
1433 al = SSL_AD_INTERNAL_ERROR;
1434 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1438 if (!tls1_set_server_sigalgs(s)) {
1439 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1444 sk_SSL_CIPHER_free(ciphers);
1445 return MSG_PROCESS_CONTINUE_PROCESSING;
1447 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1449 ossl_statem_set_error(s);
1451 sk_SSL_CIPHER_free(ciphers);
1452 return MSG_PROCESS_ERROR;
1456 WORK_STATE tls_post_process_client_hello(SSL *s, WORK_STATE wst)
1458 int al = SSL_AD_HANDSHAKE_FAILURE;
1459 const SSL_CIPHER *cipher;
1461 if (wst == WORK_MORE_A) {
1463 /* Let cert callback update server certificates if required */
1464 if (s->cert->cert_cb) {
1465 int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
1467 al = SSL_AD_INTERNAL_ERROR;
1468 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO, SSL_R_CERT_CB_ERROR);
1472 s->rwstate = SSL_X509_LOOKUP;
1475 s->rwstate = SSL_NOTHING;
1477 cipher = ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
1479 if (cipher == NULL) {
1480 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1483 s->s3->tmp.new_cipher = cipher;
1484 /* check whether we should disable session resumption */
1485 if (s->not_resumable_session_cb != NULL)
1486 s->session->not_resumable = s->not_resumable_session_cb(s,
1487 ((cipher->algorithm_mkey & (SSL_kDHE | SSL_kECDHE)) != 0));
1488 if (s->session->not_resumable)
1489 /* do not send a session ticket */
1490 s->tlsext_ticket_expected = 0;
1492 /* Session-id reuse */
1493 s->s3->tmp.new_cipher = s->session->cipher;
1496 if (!(s->verify_mode & SSL_VERIFY_PEER)) {
1497 if (!ssl3_digest_cached_records(s, 0)) {
1498 al = SSL_AD_INTERNAL_ERROR;
1504 * we now have the following setup.
1506 * cipher_list - our prefered list of ciphers
1507 * ciphers - the clients prefered list of ciphers
1508 * compression - basically ignored right now
1509 * ssl version is set - sslv3
1510 * s->session - The ssl session has been setup.
1511 * s->hit - session reuse flag
1512 * s->s3->tmp.new_cipher- the new cipher to use.
1515 /* Handles TLS extensions that we couldn't check earlier */
1516 if (s->version >= SSL3_VERSION) {
1517 if (ssl_check_clienthello_tlsext_late(s) <= 0) {
1518 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
1519 SSL_R_CLIENTHELLO_TLSEXT);
1526 #ifndef OPENSSL_NO_SRP
1527 if (wst == WORK_MORE_B) {
1529 if ((ret = ssl_check_srp_ext_ClientHello(s, &al)) < 0) {
1531 * callback indicates further work to be done
1533 s->rwstate = SSL_X509_LOOKUP;
1536 if (ret != SSL_ERROR_NONE) {
1538 * This is not really an error but the only means to for
1539 * a client to detect whether srp is supported.
1541 if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)
1542 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
1543 SSL_R_CLIENTHELLO_TLSEXT);
1550 return WORK_FINISHED_STOP;
1552 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1553 ossl_statem_set_error(s);
1557 int tls_construct_server_hello(SSL *s)
1560 unsigned char *p, *d;
1565 buf = (unsigned char *)s->init_buf->data;
1567 /* Do the message type and length last */
1568 d = p = ssl_handshake_start(s);
1570 *(p++) = s->version >> 8;
1571 *(p++) = s->version & 0xff;
1574 * Random stuff. Filling of the server_random takes place in
1575 * tls_process_client_hello()
1577 memcpy(p, s->s3->server_random, SSL3_RANDOM_SIZE);
1578 p += SSL3_RANDOM_SIZE;
1581 * There are several cases for the session ID to send
1582 * back in the server hello:
1583 * - For session reuse from the session cache,
1584 * we send back the old session ID.
1585 * - If stateless session reuse (using a session ticket)
1586 * is successful, we send back the client's "session ID"
1587 * (which doesn't actually identify the session).
1588 * - If it is a new session, we send back the new
1590 * - However, if we want the new session to be single-use,
1591 * we send back a 0-length session ID.
1592 * s->hit is non-zero in either case of session reuse,
1593 * so the following won't overwrite an ID that we're supposed
1596 if (s->session->not_resumable ||
1597 (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1599 s->session->session_id_length = 0;
1601 sl = s->session->session_id_length;
1602 if (sl > (int)sizeof(s->session->session_id)) {
1603 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1604 ossl_statem_set_error(s);
1608 memcpy(p, s->session->session_id, sl);
1611 /* put the cipher */
1612 i = ssl3_put_cipher_by_char(s->s3->tmp.new_cipher, p);
1615 /* put the compression method */
1616 #ifdef OPENSSL_NO_COMP
1619 if (s->s3->tmp.new_compression == NULL)
1622 *(p++) = s->s3->tmp.new_compression->id;
1625 if (ssl_prepare_serverhello_tlsext(s) <= 0) {
1626 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, SSL_R_SERVERHELLO_TLSEXT);
1627 ossl_statem_set_error(s);
1631 ssl_add_serverhello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,
1633 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1634 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1635 ossl_statem_set_error(s);
1641 if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l)) {
1642 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1643 ossl_statem_set_error(s);
1650 int tls_construct_server_done(SSL *s)
1652 if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0)) {
1653 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_DONE, ERR_R_INTERNAL_ERROR);
1654 ossl_statem_set_error(s);
1658 if (!s->s3->tmp.cert_request) {
1659 if (!ssl3_digest_cached_records(s, 0)) {
1660 ossl_statem_set_error(s);
1667 int tls_construct_server_key_exchange(SSL *s)
1669 #ifndef OPENSSL_NO_DH
1670 EVP_PKEY *pkdh = NULL;
1672 #ifndef OPENSSL_NO_EC
1673 unsigned char *encodedPoint = NULL;
1678 const EVP_MD *md = NULL;
1679 unsigned char *p, *d;
1686 EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
1688 if (md_ctx == NULL) {
1689 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1690 al = SSL_AD_INTERNAL_ERROR;
1694 type = s->s3->tmp.new_cipher->algorithm_mkey;
1698 r[0] = r[1] = r[2] = r[3] = NULL;
1700 #ifndef OPENSSL_NO_PSK
1701 if (type & SSL_PSK) {
1703 * reserve size for record length and PSK identity hint
1706 if (s->cert->psk_identity_hint)
1707 n += strlen(s->cert->psk_identity_hint);
1709 /* Plain PSK or RSAPSK nothing to do */
1710 if (type & (SSL_kPSK | SSL_kRSAPSK)) {
1712 #endif /* !OPENSSL_NO_PSK */
1713 #ifndef OPENSSL_NO_DH
1714 if (type & (SSL_kDHE | SSL_kDHEPSK)) {
1715 CERT *cert = s->cert;
1717 EVP_PKEY *pkdhp = NULL;
1720 if (s->cert->dh_tmp_auto) {
1721 DH *dhp = ssl_get_auto_dh(s);
1722 pkdh = EVP_PKEY_new();
1723 if (pkdh == NULL || dhp == NULL) {
1725 al = SSL_AD_INTERNAL_ERROR;
1726 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1727 ERR_R_INTERNAL_ERROR);
1730 EVP_PKEY_assign_DH(pkdh, dhp);
1733 pkdhp = cert->dh_tmp;
1735 if ((pkdhp == NULL) && (s->cert->dh_tmp_cb != NULL)) {
1736 DH *dhp = s->cert->dh_tmp_cb(s, 0, 1024);
1737 pkdh = ssl_dh_to_pkey(dhp);
1739 al = SSL_AD_INTERNAL_ERROR;
1740 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1741 ERR_R_INTERNAL_ERROR);
1746 if (pkdhp == NULL) {
1747 al = SSL_AD_HANDSHAKE_FAILURE;
1748 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1749 SSL_R_MISSING_TMP_DH_KEY);
1752 if (!ssl_security(s, SSL_SECOP_TMP_DH,
1753 EVP_PKEY_security_bits(pkdhp), 0, pkdhp)) {
1754 al = SSL_AD_HANDSHAKE_FAILURE;
1755 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1756 SSL_R_DH_KEY_TOO_SMALL);
1759 if (s->s3->tmp.pkey != NULL) {
1760 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1761 ERR_R_INTERNAL_ERROR);
1765 s->s3->tmp.pkey = ssl_generate_pkey(pkdhp, NID_undef);
1767 if (s->s3->tmp.pkey == NULL) {
1768 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EVP_LIB);
1772 dh = EVP_PKEY_get0_DH(s->s3->tmp.pkey);
1774 EVP_PKEY_free(pkdh);
1777 DH_get0_pqg(dh, &r[0], NULL, &r[1]);
1778 DH_get0_key(dh, &r[2], NULL);
1781 #ifndef OPENSSL_NO_EC
1782 if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
1785 if (s->s3->tmp.pkey != NULL) {
1786 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1787 ERR_R_INTERNAL_ERROR);
1791 /* Get NID of appropriate shared curve */
1792 nid = tls1_shared_curve(s, -2);
1793 curve_id = tls1_ec_nid2curve_id(nid);
1794 if (curve_id == 0) {
1795 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1796 SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1799 s->s3->tmp.pkey = ssl_generate_pkey(NULL, nid);
1800 /* Generate a new key for this curve */
1801 if (s->s3->tmp.pkey == NULL) {
1802 al = SSL_AD_INTERNAL_ERROR;
1803 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EVP_LIB);
1807 /* Encode the public key. */
1808 encodedlen = EC_KEY_key2buf(EVP_PKEY_get0_EC_KEY(s->s3->tmp.pkey),
1809 POINT_CONVERSION_UNCOMPRESSED,
1810 &encodedPoint, NULL);
1812 if (encodedlen == 0) {
1813 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EC_LIB);
1818 * We only support named (not generic) curves in ECDH ephemeral key
1819 * exchanges. In this situation, we need four additional bytes to
1820 * encode the entire ServerECDHParams structure.
1822 n += 4 + encodedlen;
1825 * We'll generate the serverKeyExchange message explicitly so we
1826 * can set these to NULLs
1833 #endif /* !OPENSSL_NO_EC */
1834 #ifndef OPENSSL_NO_SRP
1835 if (type & SSL_kSRP) {
1836 if ((s->srp_ctx.N == NULL) ||
1837 (s->srp_ctx.g == NULL) ||
1838 (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
1839 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1840 SSL_R_MISSING_SRP_PARAM);
1843 r[0] = s->srp_ctx.N;
1844 r[1] = s->srp_ctx.g;
1845 r[2] = s->srp_ctx.s;
1846 r[3] = s->srp_ctx.B;
1850 al = SSL_AD_HANDSHAKE_FAILURE;
1851 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1852 SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1855 for (i = 0; i < 4 && r[i] != NULL; i++) {
1856 nr[i] = BN_num_bytes(r[i]);
1857 #ifndef OPENSSL_NO_SRP
1858 if ((i == 2) && (type & SSL_kSRP))
1865 if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aSRP))
1866 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_PSK)) {
1867 if ((pkey = ssl_get_sign_pkey(s, s->s3->tmp.new_cipher, &md))
1869 al = SSL_AD_DECODE_ERROR;
1872 kn = EVP_PKEY_size(pkey);
1878 if (!BUF_MEM_grow_clean(buf, n + SSL_HM_HEADER_LENGTH(s) + kn)) {
1879 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_LIB_BUF);
1882 d = p = ssl_handshake_start(s);
1884 #ifndef OPENSSL_NO_PSK
1885 if (type & SSL_PSK) {
1886 /* copy PSK identity hint */
1887 if (s->cert->psk_identity_hint) {
1888 s2n(strlen(s->cert->psk_identity_hint), p);
1889 strncpy((char *)p, s->cert->psk_identity_hint,
1890 strlen(s->cert->psk_identity_hint));
1891 p += strlen(s->cert->psk_identity_hint);
1898 for (i = 0; i < 4 && r[i] != NULL; i++) {
1899 #ifndef OPENSSL_NO_SRP
1900 if ((i == 2) && (type & SSL_kSRP)) {
1910 #ifndef OPENSSL_NO_EC
1911 if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
1913 * XXX: For now, we only support named (not generic) curves. In
1914 * this situation, the serverKeyExchange message has: [1 byte
1915 * CurveType], [2 byte CurveName] [1 byte length of encoded
1916 * point], followed by the actual encoded point itself
1918 *p = NAMED_CURVE_TYPE;
1926 memcpy(p, encodedPoint, encodedlen);
1927 OPENSSL_free(encodedPoint);
1928 encodedPoint = NULL;
1936 * n is the length of the params, they start at &(d[4]) and p
1937 * points to the space at the end.
1940 /* send signature algorithm */
1941 if (SSL_USE_SIGALGS(s)) {
1942 if (!tls12_get_sigandhash(p, pkey, md)) {
1943 /* Should never happen */
1944 al = SSL_AD_INTERNAL_ERROR;
1945 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1946 ERR_R_INTERNAL_ERROR);
1952 fprintf(stderr, "Using hash %s\n", EVP_MD_name(md));
1954 if (EVP_SignInit_ex(md_ctx, md, NULL) <= 0
1955 || EVP_SignUpdate(md_ctx, &(s->s3->client_random[0]),
1956 SSL3_RANDOM_SIZE) <= 0
1957 || EVP_SignUpdate(md_ctx, &(s->s3->server_random[0]),
1958 SSL3_RANDOM_SIZE) <= 0
1959 || EVP_SignUpdate(md_ctx, d, n) <= 0
1960 || EVP_SignFinal(md_ctx, &(p[2]),
1961 (unsigned int *)&i, pkey) <= 0) {
1962 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_LIB_EVP);
1963 al = SSL_AD_INTERNAL_ERROR;
1968 if (SSL_USE_SIGALGS(s))
1971 /* Is this error check actually needed? */
1972 al = SSL_AD_HANDSHAKE_FAILURE;
1973 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1974 SSL_R_UNKNOWN_PKEY_TYPE);
1979 if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n)) {
1980 al = SSL_AD_HANDSHAKE_FAILURE;
1981 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1985 EVP_MD_CTX_free(md_ctx);
1988 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1990 #ifndef OPENSSL_NO_DH
1991 EVP_PKEY_free(pkdh);
1993 #ifndef OPENSSL_NO_EC
1994 OPENSSL_free(encodedPoint);
1996 EVP_MD_CTX_free(md_ctx);
1997 ossl_statem_set_error(s);
2001 int tls_construct_certificate_request(SSL *s)
2003 unsigned char *p, *d;
2004 int i, j, nl, off, n;
2005 STACK_OF(X509_NAME) *sk = NULL;
2011 d = p = ssl_handshake_start(s);
2013 /* get the list of acceptable cert types */
2015 n = ssl3_get_req_cert_type(s, p);
2020 if (SSL_USE_SIGALGS(s)) {
2021 const unsigned char *psigs;
2022 unsigned char *etmp = p;
2023 nl = tls12_get_psigalgs(s, &psigs);
2024 /* Skip over length for now */
2026 nl = tls12_copy_sigalgs(s, p, psigs, nl);
2027 /* Now fill in length */
2037 sk = SSL_get_client_CA_list(s);
2040 for (i = 0; i < sk_X509_NAME_num(sk); i++) {
2041 name = sk_X509_NAME_value(sk, i);
2042 j = i2d_X509_NAME(name, NULL);
2043 if (!BUF_MEM_grow_clean
2044 (buf, SSL_HM_HEADER_LENGTH(s) + n + j + 2)) {
2045 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2049 p = ssl_handshake_start(s) + n;
2051 i2d_X509_NAME(name, &p);
2056 /* else no CA names */
2057 p = ssl_handshake_start(s) + off;
2060 if (!ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n)) {
2061 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR);
2065 s->s3->tmp.cert_request = 1;
2069 ossl_statem_set_error(s);
2073 MSG_PROCESS_RETURN tls_process_client_key_exchange(SSL *s, PACKET *pkt)
2076 unsigned long alg_k;
2077 #ifndef OPENSSL_NO_RSA
2080 #if !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)
2081 EVP_PKEY *ckey = NULL;
2083 PACKET enc_premaster;
2084 unsigned char *rsa_decrypt = NULL;
2086 alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2088 #ifndef OPENSSL_NO_PSK
2089 /* For PSK parse and retrieve identity, obtain PSK key */
2090 if (alg_k & SSL_PSK) {
2091 unsigned char psk[PSK_MAX_PSK_LEN];
2093 PACKET psk_identity;
2095 if (!PACKET_get_length_prefixed_2(pkt, &psk_identity)) {
2096 al = SSL_AD_DECODE_ERROR;
2097 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
2100 if (PACKET_remaining(&psk_identity) > PSK_MAX_IDENTITY_LEN) {
2101 al = SSL_AD_DECODE_ERROR;
2102 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2103 SSL_R_DATA_LENGTH_TOO_LONG);
2106 if (s->psk_server_callback == NULL) {
2107 al = SSL_AD_INTERNAL_ERROR;
2108 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2109 SSL_R_PSK_NO_SERVER_CB);
2113 if (!PACKET_strndup(&psk_identity, &s->session->psk_identity)) {
2114 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2115 al = SSL_AD_INTERNAL_ERROR;
2119 psklen = s->psk_server_callback(s, s->session->psk_identity,
2122 if (psklen > PSK_MAX_PSK_LEN) {
2123 al = SSL_AD_INTERNAL_ERROR;
2124 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2126 } else if (psklen == 0) {
2128 * PSK related to the given identity not found
2130 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2131 SSL_R_PSK_IDENTITY_NOT_FOUND);
2132 al = SSL_AD_UNKNOWN_PSK_IDENTITY;
2136 OPENSSL_free(s->s3->tmp.psk);
2137 s->s3->tmp.psk = OPENSSL_memdup(psk, psklen);
2138 OPENSSL_cleanse(psk, psklen);
2140 if (s->s3->tmp.psk == NULL) {
2141 al = SSL_AD_INTERNAL_ERROR;
2142 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2146 s->s3->tmp.psklen = psklen;
2148 if (alg_k & SSL_kPSK) {
2149 /* Identity extracted earlier: should be nothing left */
2150 if (PACKET_remaining(pkt) != 0) {
2151 al = SSL_AD_HANDSHAKE_FAILURE;
2152 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
2155 /* PSK handled by ssl_generate_master_secret */
2156 if (!ssl_generate_master_secret(s, NULL, 0, 0)) {
2157 al = SSL_AD_INTERNAL_ERROR;
2158 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2163 #ifndef OPENSSL_NO_RSA
2164 if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
2165 unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2167 unsigned char decrypt_good, version_good;
2170 /* FIX THIS UP EAY EAY EAY EAY */
2171 rsa = EVP_PKEY_get0_RSA(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey);
2173 al = SSL_AD_HANDSHAKE_FAILURE;
2174 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2175 SSL_R_MISSING_RSA_CERTIFICATE);
2179 /* SSLv3 and pre-standard DTLS omit the length bytes. */
2180 if (s->version == SSL3_VERSION || s->version == DTLS1_BAD_VER) {
2181 enc_premaster = *pkt;
2183 if (!PACKET_get_length_prefixed_2(pkt, &enc_premaster)
2184 || PACKET_remaining(pkt) != 0) {
2185 al = SSL_AD_DECODE_ERROR;
2186 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2187 SSL_R_LENGTH_MISMATCH);
2193 * We want to be sure that the plaintext buffer size makes it safe to
2194 * iterate over the entire size of a premaster secret
2195 * (SSL_MAX_MASTER_KEY_LENGTH). Reject overly short RSA keys because
2196 * their ciphertext cannot accommodate a premaster secret anyway.
2198 if (RSA_size(rsa) < SSL_MAX_MASTER_KEY_LENGTH) {
2199 al = SSL_AD_INTERNAL_ERROR;
2200 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2201 RSA_R_KEY_SIZE_TOO_SMALL);
2205 rsa_decrypt = OPENSSL_malloc(RSA_size(rsa));
2206 if (rsa_decrypt == NULL) {
2207 al = SSL_AD_INTERNAL_ERROR;
2208 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2213 * We must not leak whether a decryption failure occurs because of
2214 * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
2215 * section 7.4.7.1). The code follows that advice of the TLS RFC and
2216 * generates a random premaster secret for the case that the decrypt
2217 * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
2220 if (RAND_bytes(rand_premaster_secret,
2221 sizeof(rand_premaster_secret)) <= 0) {
2225 decrypt_len = RSA_private_decrypt(PACKET_remaining(&enc_premaster),
2226 PACKET_data(&enc_premaster),
2227 rsa_decrypt, rsa, RSA_PKCS1_PADDING);
2231 * decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH. decrypt_good will
2232 * be 0xff if so and zero otherwise.
2235 constant_time_eq_int_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH);
2238 * If the version in the decrypted pre-master secret is correct then
2239 * version_good will be 0xff, otherwise it'll be zero. The
2240 * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
2241 * (http://eprint.iacr.org/2003/052/) exploits the version number
2242 * check as a "bad version oracle". Thus version checks are done in
2243 * constant time and are treated like any other decryption error.
2246 constant_time_eq_8(rsa_decrypt[0],
2247 (unsigned)(s->client_version >> 8));
2249 constant_time_eq_8(rsa_decrypt[1],
2250 (unsigned)(s->client_version & 0xff));
2253 * The premaster secret must contain the same version number as the
2254 * ClientHello to detect version rollback attacks (strangely, the
2255 * protocol does not offer such protection for DH ciphersuites).
2256 * However, buggy clients exist that send the negotiated protocol
2257 * version instead if the server does not support the requested
2258 * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
2261 if (s->options & SSL_OP_TLS_ROLLBACK_BUG) {
2262 unsigned char workaround_good;
2264 constant_time_eq_8(rsa_decrypt[0], (unsigned)(s->version >> 8));
2266 constant_time_eq_8(rsa_decrypt[1],
2267 (unsigned)(s->version & 0xff));
2268 version_good |= workaround_good;
2272 * Both decryption and version must be good for decrypt_good to
2273 * remain non-zero (0xff).
2275 decrypt_good &= version_good;
2278 * Now copy rand_premaster_secret over from p using
2279 * decrypt_good_mask. If decryption failed, then p does not
2280 * contain valid plaintext, however, a check above guarantees
2281 * it is still sufficiently large to read from.
2283 for (j = 0; j < sizeof(rand_premaster_secret); j++) {
2285 constant_time_select_8(decrypt_good, rsa_decrypt[j],
2286 rand_premaster_secret[j]);
2289 if (!ssl_generate_master_secret(s, rsa_decrypt,
2290 sizeof(rand_premaster_secret), 0)) {
2291 al = SSL_AD_INTERNAL_ERROR;
2292 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2295 OPENSSL_free(rsa_decrypt);
2299 #ifndef OPENSSL_NO_DH
2300 if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
2301 EVP_PKEY *skey = NULL;
2305 const unsigned char *data;
2307 if (!PACKET_get_net_2(pkt, &i)) {
2308 if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
2309 al = SSL_AD_HANDSHAKE_FAILURE;
2310 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2311 SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2316 if (PACKET_remaining(pkt) != i) {
2317 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2318 SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2321 skey = s->s3->tmp.pkey;
2323 al = SSL_AD_HANDSHAKE_FAILURE;
2324 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2325 SSL_R_MISSING_TMP_DH_KEY);
2329 if (PACKET_remaining(pkt) == 0L) {
2330 al = SSL_AD_HANDSHAKE_FAILURE;
2331 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2332 SSL_R_MISSING_TMP_DH_KEY);
2335 if (!PACKET_get_bytes(pkt, &data, i)) {
2336 /* We already checked we have enough data */
2337 al = SSL_AD_INTERNAL_ERROR;
2338 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2339 ERR_R_INTERNAL_ERROR);
2342 ckey = EVP_PKEY_new();
2343 if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) == 0) {
2344 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_BN_LIB);
2347 cdh = EVP_PKEY_get0_DH(ckey);
2348 pub_key = BN_bin2bn(data, i, NULL);
2350 if (pub_key == NULL || !DH_set0_key(cdh, pub_key, NULL)) {
2351 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2352 if (pub_key != NULL)
2357 if (ssl_derive(s, skey, ckey) == 0) {
2358 al = SSL_AD_INTERNAL_ERROR;
2359 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2363 EVP_PKEY_free(ckey);
2365 EVP_PKEY_free(s->s3->tmp.pkey);
2366 s->s3->tmp.pkey = NULL;
2371 #ifndef OPENSSL_NO_EC
2372 if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
2373 EVP_PKEY *skey = s->s3->tmp.pkey;
2375 if (PACKET_remaining(pkt) == 0L) {
2376 /* We don't support ECDH client auth */
2377 al = SSL_AD_HANDSHAKE_FAILURE;
2378 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2379 SSL_R_MISSING_TMP_ECDH_KEY);
2383 const unsigned char *data;
2386 * Get client's public key from encoded point in the
2387 * ClientKeyExchange message.
2390 /* Get encoded point length */
2391 if (!PACKET_get_1(pkt, &i)) {
2392 al = SSL_AD_DECODE_ERROR;
2393 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2394 SSL_R_LENGTH_MISMATCH);
2397 if (!PACKET_get_bytes(pkt, &data, i)
2398 || PACKET_remaining(pkt) != 0) {
2399 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2402 ckey = EVP_PKEY_new();
2403 if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) <= 0) {
2404 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_EVP_LIB);
2407 if (EC_KEY_oct2key(EVP_PKEY_get0_EC_KEY(ckey), data, i,
2409 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2414 if (ssl_derive(s, skey, ckey) == 0) {
2415 al = SSL_AD_INTERNAL_ERROR;
2416 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2420 EVP_PKEY_free(ckey);
2422 EVP_PKEY_free(s->s3->tmp.pkey);
2423 s->s3->tmp.pkey = NULL;
2425 return MSG_PROCESS_CONTINUE_PROCESSING;
2428 #ifndef OPENSSL_NO_SRP
2429 if (alg_k & SSL_kSRP) {
2431 const unsigned char *data;
2433 if (!PACKET_get_net_2(pkt, &i)
2434 || !PACKET_get_bytes(pkt, &data, i)) {
2435 al = SSL_AD_DECODE_ERROR;
2436 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_BAD_SRP_A_LENGTH);
2439 if ((s->srp_ctx.A = BN_bin2bn(data, i, NULL)) == NULL) {
2440 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_BN_LIB);
2443 if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0
2444 || BN_is_zero(s->srp_ctx.A)) {
2445 al = SSL_AD_ILLEGAL_PARAMETER;
2446 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2447 SSL_R_BAD_SRP_PARAMETERS);
2450 OPENSSL_free(s->session->srp_username);
2451 s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);
2452 if (s->session->srp_username == NULL) {
2453 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2457 if (!srp_generate_server_master_secret(s)) {
2458 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2462 #endif /* OPENSSL_NO_SRP */
2463 #ifndef OPENSSL_NO_GOST
2464 if (alg_k & SSL_kGOST) {
2465 EVP_PKEY_CTX *pkey_ctx;
2466 EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2467 unsigned char premaster_secret[32];
2468 const unsigned char *start;
2469 size_t outlen = 32, inlen;
2470 unsigned long alg_a;
2474 const unsigned char *data;
2476 /* Get our certificate private key */
2477 alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2478 if (alg_a & SSL_aGOST12) {
2480 * New GOST ciphersuites have SSL_aGOST01 bit too
2482 pk = s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey;
2484 pk = s->cert->pkeys[SSL_PKEY_GOST12_256].privatekey;
2487 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2489 } else if (alg_a & SSL_aGOST01) {
2490 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2493 pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
2494 if (pkey_ctx == NULL) {
2495 al = SSL_AD_INTERNAL_ERROR;
2496 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2499 if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {
2500 al = SSL_AD_INTERNAL_ERROR;
2501 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2505 * If client certificate is present and is of the same type, maybe
2506 * use it for key exchange. Don't mind errors from
2507 * EVP_PKEY_derive_set_peer, because it is completely valid to use a
2508 * client certificate for authorization only.
2510 client_pub_pkey = X509_get0_pubkey(s->session->peer);
2511 if (client_pub_pkey) {
2512 if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
2515 /* Decrypt session key */
2516 sess_key_len = PACKET_remaining(pkt);
2517 if (!PACKET_get_bytes(pkt, &data, sess_key_len)) {
2518 al = SSL_AD_INTERNAL_ERROR;
2519 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2522 if (ASN1_get_object ((const unsigned char **)&data, &Tlen, &Ttag,
2523 &Tclass, sess_key_len) != V_ASN1_CONSTRUCTED
2524 || Ttag != V_ASN1_SEQUENCE
2525 || Tclass != V_ASN1_UNIVERSAL) {
2526 al = SSL_AD_DECODE_ERROR;
2527 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2528 SSL_R_DECRYPTION_FAILED);
2533 if (EVP_PKEY_decrypt
2534 (pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {
2535 al = SSL_AD_DECODE_ERROR;
2536 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2537 SSL_R_DECRYPTION_FAILED);
2540 /* Generate master secret */
2541 if (!ssl_generate_master_secret(s, premaster_secret,
2542 sizeof(premaster_secret), 0)) {
2543 al = SSL_AD_INTERNAL_ERROR;
2544 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2547 /* Check if pubkey from client certificate was used */
2548 if (EVP_PKEY_CTX_ctrl
2549 (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
2550 s->statem.no_cert_verify = 1;
2552 EVP_PKEY_CTX_free(pkey_ctx);
2553 return MSG_PROCESS_CONTINUE_PROCESSING;
2555 EVP_PKEY_CTX_free(pkey_ctx);
2560 al = SSL_AD_HANDSHAKE_FAILURE;
2561 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_UNKNOWN_CIPHER_TYPE);
2565 return MSG_PROCESS_CONTINUE_PROCESSING;
2567 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2568 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_EC) || defined(OPENSSL_NO_SRP)
2571 #if !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)
2572 EVP_PKEY_free(ckey);
2574 OPENSSL_free(rsa_decrypt);
2575 #ifndef OPENSSL_NO_PSK
2576 OPENSSL_clear_free(s->s3->tmp.psk, s->s3->tmp.psklen);
2577 s->s3->tmp.psk = NULL;
2579 ossl_statem_set_error(s);
2580 return MSG_PROCESS_ERROR;
2583 WORK_STATE tls_post_process_client_key_exchange(SSL *s, WORK_STATE wst)
2585 #ifndef OPENSSL_NO_SCTP
2586 if (wst == WORK_MORE_A) {
2587 if (SSL_IS_DTLS(s)) {
2588 unsigned char sctpauthkey[64];
2589 char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
2591 * Add new shared key for SCTP-Auth, will be ignored if no SCTP
2594 memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
2595 sizeof(DTLS1_SCTP_AUTH_LABEL));
2597 if (SSL_export_keying_material(s, sctpauthkey,
2598 sizeof(sctpauthkey), labelbuffer,
2599 sizeof(labelbuffer), NULL, 0, 0) <= 0) {
2600 ossl_statem_set_error(s);
2604 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
2605 sizeof(sctpauthkey), sctpauthkey);
2610 if ((wst == WORK_MORE_B)
2612 && BIO_dgram_is_sctp(SSL_get_wbio(s))
2613 /* Are we renegotiating? */
2615 /* Are we going to skip the CertificateVerify? */
2616 && (s->session->peer == NULL || s->statem.no_cert_verify)
2617 && BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
2618 s->s3->in_read_app_data = 2;
2619 s->rwstate = SSL_READING;
2620 BIO_clear_retry_flags(SSL_get_rbio(s));
2621 BIO_set_retry_read(SSL_get_rbio(s));
2622 ossl_statem_set_sctp_read_sock(s, 1);
2625 ossl_statem_set_sctp_read_sock(s, 0);
2629 if (s->statem.no_cert_verify) {
2630 /* No certificate verify so we no longer need the handshake_buffer */
2631 BIO_free(s->s3->handshake_buffer);
2632 s->s3->handshake_buffer = NULL;
2633 return WORK_FINISHED_CONTINUE;
2635 if (!s->session->peer) {
2636 /* No peer certificate so we no longer need the handshake_buffer */
2637 BIO_free(s->s3->handshake_buffer);
2638 return WORK_FINISHED_CONTINUE;
2640 if (!s->s3->handshake_buffer) {
2641 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_KEY_EXCHANGE,
2642 ERR_R_INTERNAL_ERROR);
2643 ossl_statem_set_error(s);
2647 * For sigalgs freeze the handshake buffer. If we support
2648 * extms we've done this already so this is a no-op
2650 if (!ssl3_digest_cached_records(s, 1)) {
2651 ossl_statem_set_error(s);
2656 return WORK_FINISHED_CONTINUE;
2659 MSG_PROCESS_RETURN tls_process_cert_verify(SSL *s, PACKET *pkt)
2661 EVP_PKEY *pkey = NULL;
2662 const unsigned char *sig, *data;
2663 #ifndef OPENSSL_NO_GOST
2664 unsigned char *gost_data = NULL;
2666 int al, ret = MSG_PROCESS_ERROR;
2670 const EVP_MD *md = NULL;
2674 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
2677 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
2678 al = SSL_AD_INTERNAL_ERROR;
2682 peer = s->session->peer;
2683 pkey = X509_get0_pubkey(peer);
2684 type = X509_certificate_type(peer, pkey);
2686 if (!(type & EVP_PKT_SIGN)) {
2687 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY,
2688 SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
2689 al = SSL_AD_ILLEGAL_PARAMETER;
2693 /* Check for broken implementations of GOST ciphersuites */
2695 * If key is GOST and n is exactly 64, it is bare signature without
2696 * length field (CryptoPro implementations at least till CSP 4.0)
2698 #ifndef OPENSSL_NO_GOST
2699 if (PACKET_remaining(pkt) == 64
2700 && EVP_PKEY_id(pkey) == NID_id_GostR3410_2001) {
2705 if (SSL_USE_SIGALGS(s)) {
2708 if (!PACKET_get_bytes(pkt, &sig, 2)) {
2709 al = SSL_AD_DECODE_ERROR;
2712 rv = tls12_check_peer_sigalg(&md, s, sig, pkey);
2714 al = SSL_AD_INTERNAL_ERROR;
2716 } else if (rv == 0) {
2717 al = SSL_AD_DECODE_ERROR;
2721 fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
2724 /* Use default digest for this key type */
2725 int idx = ssl_cert_type(NULL, pkey);
2727 md = s->s3->tmp.md[idx];
2729 al = SSL_AD_INTERNAL_ERROR;
2734 if (!PACKET_get_net_2(pkt, &len)) {
2735 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
2736 al = SSL_AD_DECODE_ERROR;
2740 j = EVP_PKEY_size(pkey);
2741 if (((int)len > j) || ((int)PACKET_remaining(pkt) > j)
2742 || (PACKET_remaining(pkt) == 0)) {
2743 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_WRONG_SIGNATURE_SIZE);
2744 al = SSL_AD_DECODE_ERROR;
2747 if (!PACKET_get_bytes(pkt, &data, len)) {
2748 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
2749 al = SSL_AD_DECODE_ERROR;
2753 hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
2754 if (hdatalen <= 0) {
2755 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
2756 al = SSL_AD_INTERNAL_ERROR;
2760 fprintf(stderr, "Using client verify alg %s\n", EVP_MD_name(md));
2762 if (!EVP_VerifyInit_ex(mctx, md, NULL)
2763 || !EVP_VerifyUpdate(mctx, hdata, hdatalen)) {
2764 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
2765 al = SSL_AD_INTERNAL_ERROR;
2769 #ifndef OPENSSL_NO_GOST
2771 int pktype = EVP_PKEY_id(pkey);
2772 if (pktype == NID_id_GostR3410_2001
2773 || pktype == NID_id_GostR3410_2012_256
2774 || pktype == NID_id_GostR3410_2012_512) {
2775 if ((gost_data = OPENSSL_malloc(len)) == NULL) {
2776 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
2777 al = SSL_AD_INTERNAL_ERROR;
2780 BUF_reverse(gost_data, data, len);
2786 if (s->version == SSL3_VERSION
2787 && !EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
2788 s->session->master_key_length,
2789 s->session->master_key)) {
2790 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
2791 al = SSL_AD_INTERNAL_ERROR;
2795 if (EVP_VerifyFinal(mctx, data, len, pkey) <= 0) {
2796 al = SSL_AD_DECRYPT_ERROR;
2797 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_BAD_SIGNATURE);
2801 ret = MSG_PROCESS_CONTINUE_PROCESSING;
2804 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2805 ossl_statem_set_error(s);
2807 BIO_free(s->s3->handshake_buffer);
2808 s->s3->handshake_buffer = NULL;
2809 EVP_MD_CTX_free(mctx);
2810 #ifndef OPENSSL_NO_GOST
2811 OPENSSL_free(gost_data);
2816 MSG_PROCESS_RETURN tls_process_client_certificate(SSL *s, PACKET *pkt)
2818 int i, al = SSL_AD_INTERNAL_ERROR, ret = MSG_PROCESS_ERROR;
2820 unsigned long l, llen;
2821 const unsigned char *certstart, *certbytes;
2822 STACK_OF(X509) *sk = NULL;
2825 if ((sk = sk_X509_new_null()) == NULL) {
2826 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
2830 if (!PACKET_get_net_3(pkt, &llen)
2831 || !PACKET_get_sub_packet(pkt, &spkt, llen)
2832 || PACKET_remaining(pkt) != 0) {
2833 al = SSL_AD_DECODE_ERROR;
2834 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
2838 while (PACKET_remaining(&spkt) > 0) {
2839 if (!PACKET_get_net_3(&spkt, &l)
2840 || !PACKET_get_bytes(&spkt, &certbytes, l)) {
2841 al = SSL_AD_DECODE_ERROR;
2842 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
2843 SSL_R_CERT_LENGTH_MISMATCH);
2847 certstart = certbytes;
2848 x = d2i_X509(NULL, (const unsigned char **)&certbytes, l);
2850 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_ASN1_LIB);
2853 if (certbytes != (certstart + l)) {
2854 al = SSL_AD_DECODE_ERROR;
2855 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
2856 SSL_R_CERT_LENGTH_MISMATCH);
2859 if (!sk_X509_push(sk, x)) {
2860 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
2866 if (sk_X509_num(sk) <= 0) {
2867 /* TLS does not mind 0 certs returned */
2868 if (s->version == SSL3_VERSION) {
2869 al = SSL_AD_HANDSHAKE_FAILURE;
2870 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
2871 SSL_R_NO_CERTIFICATES_RETURNED);
2874 /* Fail for TLS only if we required a certificate */
2875 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
2876 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
2877 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
2878 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2879 al = SSL_AD_HANDSHAKE_FAILURE;
2882 /* No client certificate so digest cached records */
2883 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s, 0)) {
2888 i = ssl_verify_cert_chain(s, sk);
2890 al = ssl_verify_alarm_type(s->verify_result);
2891 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
2892 SSL_R_CERTIFICATE_VERIFY_FAILED);
2896 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, i);
2897 al = SSL_AD_HANDSHAKE_FAILURE;
2900 pkey = X509_get0_pubkey(sk_X509_value(sk, 0));
2902 al = SSL3_AD_HANDSHAKE_FAILURE;
2903 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
2904 SSL_R_UNKNOWN_CERTIFICATE_TYPE);
2909 X509_free(s->session->peer);
2910 s->session->peer = sk_X509_shift(sk);
2911 s->session->verify_result = s->verify_result;
2913 sk_X509_pop_free(s->session->peer_chain, X509_free);
2914 s->session->peer_chain = sk;
2916 * Inconsistency alert: cert_chain does *not* include the peer's own
2917 * certificate, while we do include it in s3_clnt.c
2920 ret = MSG_PROCESS_CONTINUE_READING;
2924 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2925 ossl_statem_set_error(s);
2928 sk_X509_pop_free(sk, X509_free);
2932 int tls_construct_server_certificate(SSL *s)
2936 cpk = ssl_get_server_send_pkey(s);
2938 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
2939 ossl_statem_set_error(s);
2943 if (!ssl3_output_cert_chain(s, cpk)) {
2944 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
2945 ossl_statem_set_error(s);
2952 int tls_construct_new_session_ticket(SSL *s)
2954 unsigned char *senc = NULL;
2955 EVP_CIPHER_CTX *ctx;
2956 HMAC_CTX *hctx = NULL;
2957 unsigned char *p, *macstart;
2958 const unsigned char *const_p;
2959 int len, slen_full, slen;
2962 SSL_CTX *tctx = s->initial_ctx;
2963 unsigned char iv[EVP_MAX_IV_LENGTH];
2964 unsigned char key_name[16];
2966 /* get session encoding length */
2967 slen_full = i2d_SSL_SESSION(s->session, NULL);
2969 * Some length values are 16 bits, so forget it if session is too
2972 if (slen_full == 0 || slen_full > 0xFF00) {
2973 ossl_statem_set_error(s);
2976 senc = OPENSSL_malloc(slen_full);
2978 ossl_statem_set_error(s);
2982 ctx = EVP_CIPHER_CTX_new();
2983 hctx = HMAC_CTX_new();
2986 if (!i2d_SSL_SESSION(s->session, &p))
2990 * create a fresh copy (not shared with other threads) to clean up
2993 sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
2996 sess->session_id_length = 0; /* ID is irrelevant for the ticket */
2998 slen = i2d_SSL_SESSION(sess, NULL);
2999 if (slen == 0 || slen > slen_full) { /* shouldn't ever happen */
3000 SSL_SESSION_free(sess);
3004 if (!i2d_SSL_SESSION(sess, &p)) {
3005 SSL_SESSION_free(sess);
3008 SSL_SESSION_free(sess);
3011 * Grow buffer if need be: the length calculation is as
3012 * follows handshake_header_length +
3013 * 4 (ticket lifetime hint) + 2 (ticket length) +
3014 * 16 (key name) + max_iv_len (iv length) +
3015 * session_length + max_enc_block_size (max encrypted session
3016 * length) + max_md_size (HMAC).
3018 if (!BUF_MEM_grow(s->init_buf,
3019 SSL_HM_HEADER_LENGTH(s) + 22 + EVP_MAX_IV_LENGTH +
3020 EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE + slen))
3023 p = ssl_handshake_start(s);
3025 * Initialize HMAC and cipher contexts. If callback present it does
3026 * all the work otherwise use generated values from parent ctx.
3028 if (tctx->tlsext_ticket_key_cb) {
3029 if (tctx->tlsext_ticket_key_cb(s, key_name, iv, ctx, hctx, 1) < 0)
3032 if (RAND_bytes(iv, 16) <= 0)
3034 if (!EVP_EncryptInit_ex(ctx, EVP_aes_128_cbc(), NULL,
3035 tctx->tlsext_tick_aes_key, iv))
3037 if (!HMAC_Init_ex(hctx, tctx->tlsext_tick_hmac_key, 16,
3038 EVP_sha256(), NULL))
3040 memcpy(key_name, tctx->tlsext_tick_key_name, 16);
3044 * Ticket lifetime hint (advisory only): We leave this unspecified
3045 * for resumed session (for simplicity), and guess that tickets for
3046 * new sessions will live as long as their sessions.
3048 l2n(s->hit ? 0 : s->session->timeout, p);
3050 /* Skip ticket length for now */
3052 /* Output key name */
3054 memcpy(p, key_name, 16);
3057 memcpy(p, iv, EVP_CIPHER_CTX_iv_length(ctx));
3058 p += EVP_CIPHER_CTX_iv_length(ctx);
3059 /* Encrypt session data */
3060 if (!EVP_EncryptUpdate(ctx, p, &len, senc, slen))
3063 if (!EVP_EncryptFinal(ctx, p, &len))
3067 if (!HMAC_Update(hctx, macstart, p - macstart))
3069 if (!HMAC_Final(hctx, p, &hlen))
3072 EVP_CIPHER_CTX_free(ctx);
3073 HMAC_CTX_free(hctx);
3078 /* Now write out lengths: p points to end of data written */
3080 len = p - ssl_handshake_start(s);
3081 /* Skip ticket lifetime hint */
3082 p = ssl_handshake_start(s) + 4;
3084 if (!ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len))
3091 EVP_CIPHER_CTX_free(ctx);
3092 HMAC_CTX_free(hctx);
3093 ossl_statem_set_error(s);
3097 int tls_construct_cert_status(SSL *s)
3101 * Grow buffer if need be: the length calculation is as
3102 * follows 1 (message type) + 3 (message length) +
3103 * 1 (ocsp response type) + 3 (ocsp response length)
3106 if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen)) {
3107 ossl_statem_set_error(s);
3111 p = (unsigned char *)s->init_buf->data;
3114 *(p++) = SSL3_MT_CERTIFICATE_STATUS;
3115 /* message length */
3116 l2n3(s->tlsext_ocsp_resplen + 4, p);
3118 *(p++) = s->tlsext_status_type;
3119 /* length of OCSP response */
3120 l2n3(s->tlsext_ocsp_resplen, p);
3121 /* actual response */
3122 memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
3123 /* number of bytes to write */
3124 s->init_num = 8 + s->tlsext_ocsp_resplen;
3130 #ifndef OPENSSL_NO_NEXTPROTONEG
3132 * tls_process_next_proto reads a Next Protocol Negotiation handshake message.
3133 * It sets the next_proto member in s if found
3135 MSG_PROCESS_RETURN tls_process_next_proto(SSL *s, PACKET *pkt)
3137 PACKET next_proto, padding;
3138 size_t next_proto_len;
3141 * The payload looks like:
3143 * uint8 proto[proto_len];
3144 * uint8 padding_len;
3145 * uint8 padding[padding_len];
3147 if (!PACKET_get_length_prefixed_1(pkt, &next_proto)
3148 || !PACKET_get_length_prefixed_1(pkt, &padding)
3149 || PACKET_remaining(pkt) > 0) {
3150 SSLerr(SSL_F_TLS_PROCESS_NEXT_PROTO, SSL_R_LENGTH_MISMATCH);
3154 if (!PACKET_memdup(&next_proto, &s->next_proto_negotiated,
3156 s->next_proto_negotiated_len = 0;
3160 s->next_proto_negotiated_len = (unsigned char)next_proto_len;
3162 return MSG_PROCESS_CONTINUE_READING;
3164 ossl_statem_set_error(s);
3165 return MSG_PROCESS_ERROR;
3169 #define SSLV2_CIPHER_LEN 3
3171 STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list(SSL *s,
3172 PACKET *cipher_suites,
3173 STACK_OF(SSL_CIPHER) **skp,
3174 int sslv2format, int *al
3177 const SSL_CIPHER *c;
3178 STACK_OF(SSL_CIPHER) *sk;
3180 /* 3 = SSLV2_CIPHER_LEN > TLS_CIPHER_LEN = 2. */
3181 unsigned char cipher[SSLV2_CIPHER_LEN];
3183 s->s3->send_connection_binding = 0;
3185 n = sslv2format ? SSLV2_CIPHER_LEN : TLS_CIPHER_LEN;
3187 if (PACKET_remaining(cipher_suites) == 0) {
3188 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, SSL_R_NO_CIPHERS_SPECIFIED);
3189 *al = SSL_AD_ILLEGAL_PARAMETER;
3193 if (PACKET_remaining(cipher_suites) % n != 0) {
3194 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
3195 SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
3196 *al = SSL_AD_DECODE_ERROR;
3200 if ((skp == NULL) || (*skp == NULL)) {
3201 sk = sk_SSL_CIPHER_new_null(); /* change perhaps later */
3203 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
3204 *al = SSL_AD_INTERNAL_ERROR;
3209 sk_SSL_CIPHER_zero(sk);
3212 if (!PACKET_memdup(cipher_suites, &s->s3->tmp.ciphers_raw,
3213 &s->s3->tmp.ciphers_rawlen)) {
3214 *al = SSL_AD_INTERNAL_ERROR;
3218 while (PACKET_copy_bytes(cipher_suites, cipher, n)) {
3220 * SSLv3 ciphers wrapped in an SSLv2-compatible ClientHello have the
3221 * first byte set to zero, while true SSLv2 ciphers have a non-zero
3222 * first byte. We don't support any true SSLv2 ciphers, so skip them.
3224 if (sslv2format && cipher[0] != '\0')
3227 /* Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV */
3228 if ((cipher[n - 2] == ((SSL3_CK_SCSV >> 8) & 0xff)) &&
3229 (cipher[n - 1] == (SSL3_CK_SCSV & 0xff))) {
3230 /* SCSV fatal if renegotiating */
3231 if (s->renegotiate) {
3232 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
3233 SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING);
3234 *al = SSL_AD_HANDSHAKE_FAILURE;
3237 s->s3->send_connection_binding = 1;
3241 /* Check for TLS_FALLBACK_SCSV */
3242 if ((cipher[n - 2] == ((SSL3_CK_FALLBACK_SCSV >> 8) & 0xff)) &&
3243 (cipher[n - 1] == (SSL3_CK_FALLBACK_SCSV & 0xff))) {
3245 * The SCSV indicates that the client previously tried a higher
3246 * version. Fail if the current version is an unexpected
3249 if (!ssl_check_version_downgrade(s)) {
3250 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
3251 SSL_R_INAPPROPRIATE_FALLBACK);
3252 *al = SSL_AD_INAPPROPRIATE_FALLBACK;
3258 /* For SSLv2-compat, ignore leading 0-byte. */
3259 c = ssl_get_cipher_by_char(s, sslv2format ? &cipher[1] : cipher);
3261 if (!sk_SSL_CIPHER_push(sk, c)) {
3262 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
3263 *al = SSL_AD_INTERNAL_ERROR;
3268 if (PACKET_remaining(cipher_suites) > 0) {
3269 *al = SSL_AD_INTERNAL_ERROR;
3270 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_INTERNAL_ERROR);
3278 if ((skp == NULL) || (*skp == NULL))
3279 sk_SSL_CIPHER_free(sk);