]> git.ipfire.org Git - thirdparty/openssl.git/blame - ssl/statem/statem_lib.c
Fix speed command for alternation of ciphers and digests.
[thirdparty/openssl.git] / ssl / statem / statem_lib.c
CommitLineData
846e33c7
RS
1/*
2 * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
3813046d 3 *
846e33c7
RS
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
3813046d 8 */
846e33c7 9
ea262260
BM
10/* ====================================================================
11 * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
0f113f3e 12 * ECC cipher suite support in OpenSSL originally developed by
ea262260
BM
13 * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
14 */
d02b48c6 15
48948d53 16#include <limits.h>
f2d9a32c 17#include <string.h>
d02b48c6 18#include <stdio.h>
8ba708e5 19#include "../ssl_locl.h"
61ae935a 20#include "statem_locl.h"
ec577822 21#include <openssl/buffer.h>
ec577822
BM
22#include <openssl/objects.h>
23#include <openssl/evp.h>
24#include <openssl/x509.h>
d02b48c6 25
0f113f3e
MC
26/*
27 * send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or
28 * SSL3_RT_CHANGE_CIPHER_SPEC)
29 */
e7ecc7d4 30int ssl3_do_write(SSL *s, int type)
0f113f3e
MC
31{
32 int ret;
7ee8627f 33 size_t written = 0;
0f113f3e
MC
34
35 ret = ssl3_write_bytes(s, type, &s->init_buf->data[s->init_off],
7ee8627f 36 s->init_num, &written);
0f113f3e
MC
37 if (ret < 0)
38 return (-1);
39 if (type == SSL3_RT_HANDSHAKE)
40 /*
41 * should not be done for 'Hello Request's, but in that case we'll
42 * ignore the result anyway
43 */
d166ed8c
DSH
44 if (!ssl3_finish_mac(s,
45 (unsigned char *)&s->init_buf->data[s->init_off],
7ee8627f 46 written))
d166ed8c 47 return -1;
0f113f3e 48
7ee8627f 49 if (written == s->init_num) {
0f113f3e
MC
50 if (s->msg_callback)
51 s->msg_callback(1, s->version, type, s->init_buf->data,
52 (size_t)(s->init_off + s->init_num), s,
53 s->msg_callback_arg);
54 return (1);
55 }
7ee8627f
MC
56 s->init_off += written;
57 s->init_num -= written;
0f113f3e
MC
58 return (0);
59}
e7ecc7d4 60
4a01c59f 61int tls_close_construct_packet(SSL *s, WPACKET *pkt, int htype)
2c7b4dbc
MC
62{
63 size_t msglen;
64
4a01c59f 65 if ((htype != SSL3_MT_CHANGE_CIPHER_SPEC && !WPACKET_close(pkt))
f1ec23c0 66 || !WPACKET_get_length(pkt, &msglen)
7cea05dc 67 || msglen > INT_MAX)
2c7b4dbc
MC
68 return 0;
69 s->init_num = (int)msglen;
70 s->init_off = 0;
71
72 return 1;
73}
74
1f5b44e9
MC
75int tls_setup_handshake(SSL *s)
76{
c7f47786
MC
77 if (!ssl3_init_finished_mac(s))
78 return 0;
79
b186a592
MC
80 /* Reset any extension flags */
81 memset(s->ext.extflags, 0, sizeof(s->ext.extflags));
82
c7f47786 83 if (s->server) {
38a73150
MC
84 STACK_OF(SSL_CIPHER) *ciphers = SSL_get_ciphers(s);
85 int i, ver_min, ver_max, ok = 0;
86
87 /*
88 * Sanity check that the maximum version we accept has ciphers
89 * enabled. For clients we do this check during construction of the
90 * ClientHello.
91 */
92 if (ssl_get_min_max_version(s, &ver_min, &ver_max) != 0) {
93 SSLerr(SSL_F_TLS_SETUP_HANDSHAKE, ERR_R_INTERNAL_ERROR);
94 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
95 return 0;
96 }
97 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
98 const SSL_CIPHER *c = sk_SSL_CIPHER_value(ciphers, i);
99
100 if (SSL_IS_DTLS(s)) {
101 if (DTLS_VERSION_GE(ver_max, c->min_dtls) &&
102 DTLS_VERSION_LE(ver_max, c->max_dtls))
103 ok = 1;
104 } else if (ver_max >= c->min_tls && ver_max <= c->max_tls) {
105 ok = 1;
106 }
107 if (ok)
108 break;
109 }
110 if (!ok) {
111 SSLerr(SSL_F_TLS_SETUP_HANDSHAKE, SSL_R_NO_CIPHERS_AVAILABLE);
112 ERR_add_error_data(1, "No ciphers enabled for max supported "
113 "SSL/TLS version");
114 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
115 return 0;
116 }
c7f47786
MC
117 if (SSL_IS_FIRST_HANDSHAKE(s)) {
118 s->ctx->stats.sess_accept++;
db0f35dd
TS
119 } else if ((s->options & SSL_OP_NO_RENEGOTIATION)) {
120 /* Renegotiation is disabled */
121 ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
122 return 0;
c7f47786
MC
123 } else if (!s->s3->send_connection_binding &&
124 !(s->options &
125 SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
126 /*
127 * Server attempting to renegotiate with client that doesn't
128 * support secure renegotiation.
129 */
130 SSLerr(SSL_F_TLS_SETUP_HANDSHAKE,
131 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
132 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
133 return 0;
134 } else {
135 s->ctx->stats.sess_accept_renegotiate++;
136
137 s->s3->tmp.cert_request = 0;
138 }
139 } else {
140 if (SSL_IS_FIRST_HANDSHAKE(s))
141 s->ctx->stats.sess_connect++;
142 else
143 s->ctx->stats.sess_connect_renegotiate++;
144
145 /* mark client_random uninitialized */
146 memset(s->s3->client_random, 0, sizeof(s->s3->client_random));
147 s->hit = 0;
148
149 s->s3->tmp.cert_req = 0;
150
1f5b44e9 151 if (SSL_IS_DTLS(s))
c7f47786 152 s->statem.use_timer = 1;
c7f47786
MC
153 }
154
155 return 1;
156}
157
2c5dfdc3
MC
158/*
159 * Size of the to-be-signed TLS13 data, without the hash size itself:
160 * 64 bytes of value 32, 33 context bytes, 1 byte separator
161 */
162#define TLS13_TBS_START_SIZE 64
163#define TLS13_TBS_PREAMBLE_SIZE (TLS13_TBS_START_SIZE + 33 + 1)
164
165static int get_cert_verify_tbs_data(SSL *s, unsigned char *tls13tbs,
166 void **hdata, size_t *hdatalen)
167{
168 static const char *servercontext = "TLS 1.3, server CertificateVerify";
169 static const char *clientcontext = "TLS 1.3, client CertificateVerify";
170
171 if (SSL_IS_TLS13(s)) {
172 size_t hashlen;
173
174 /* Set the first 64 bytes of to-be-signed data to octet 32 */
175 memset(tls13tbs, 32, TLS13_TBS_START_SIZE);
176 /* This copies the 33 bytes of context plus the 0 separator byte */
177 if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
178 || s->statem.hand_state == TLS_ST_SW_CERT_VRFY)
179 strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, servercontext);
180 else
181 strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, clientcontext);
182
183 /*
184 * If we're currently reading then we need to use the saved handshake
185 * hash value. We can't use the current handshake hash state because
186 * that includes the CertVerify itself.
187 */
188 if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
189 || s->statem.hand_state == TLS_ST_SR_CERT_VRFY) {
190 memcpy(tls13tbs + TLS13_TBS_PREAMBLE_SIZE, s->cert_verify_hash,
191 s->cert_verify_hash_len);
192 hashlen = s->cert_verify_hash_len;
193 } else if (!ssl_handshake_hash(s, tls13tbs + TLS13_TBS_PREAMBLE_SIZE,
194 EVP_MAX_MD_SIZE, &hashlen)) {
195 return 0;
196 }
197
198 *hdata = tls13tbs;
199 *hdatalen = TLS13_TBS_PREAMBLE_SIZE + hashlen;
200 } else {
201 size_t retlen;
202
203 retlen = BIO_get_mem_data(s->s3->handshake_buffer, hdata);
204 if (retlen <= 0)
205 return 0;
206 *hdatalen = retlen;
207 }
208
209 return 1;
210}
211
d8bc1399
MC
212int tls_construct_cert_verify(SSL *s, WPACKET *pkt)
213{
ad4dd362
DSH
214 EVP_PKEY *pkey = NULL;
215 const EVP_MD *md = NULL;
d8bc1399 216 EVP_MD_CTX *mctx = NULL;
5f9b64a2
MC
217 EVP_PKEY_CTX *pctx = NULL;
218 size_t hdatalen = 0, siglen = 0;
d8bc1399
MC
219 void *hdata;
220 unsigned char *sig = NULL;
2c5dfdc3 221 unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
ad4dd362 222 const SIGALG_LOOKUP *lu = s->s3->tmp.sigalg;
2c5dfdc3 223
ad4dd362
DSH
224 if (lu == NULL || s->s3->tmp.cert == NULL) {
225 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
226 goto err;
227 }
228 pkey = s->s3->tmp.cert->privatekey;
229 md = ssl_md(lu->hash_idx);
230
231 if (pkey == NULL || md == NULL) {
232 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
233 goto err;
234 }
d8bc1399
MC
235
236 mctx = EVP_MD_CTX_new();
237 if (mctx == NULL) {
238 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
239 goto err;
240 }
d8bc1399 241
2c5dfdc3
MC
242 /* Get the data to be signed */
243 if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
d8bc1399
MC
244 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
245 goto err;
246 }
247
ad4dd362 248 if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
d8bc1399
MC
249 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
250 goto err;
251 }
5f9b64a2
MC
252 siglen = EVP_PKEY_size(pkey);
253 sig = OPENSSL_malloc(siglen);
d8bc1399
MC
254 if (sig == NULL) {
255 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
256 goto err;
257 }
5f9b64a2 258
75394189 259 if (EVP_DigestSignInit(mctx, &pctx, md, NULL, pkey) <= 0) {
5f9b64a2
MC
260 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_EVP_LIB);
261 goto err;
262 }
263
ad4dd362 264 if (lu->sig == EVP_PKEY_RSA_PSS) {
5f9b64a2 265 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
968ae5b3
DSH
266 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
267 RSA_PSS_SALTLEN_DIGEST) <= 0) {
5f9b64a2
MC
268 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_EVP_LIB);
269 goto err;
270 }
caf2b6b5
DSH
271 }
272 if (s->version == SSL3_VERSION) {
273 if (EVP_DigestSignUpdate(mctx, hdata, hdatalen) <= 0
274 || !EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
275 (int)s->session->master_key_length,
276 s->session->master_key)
277 || EVP_DigestSignFinal(mctx, sig, &siglen) <= 0) {
278
5f9b64a2
MC
279 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_EVP_LIB);
280 goto err;
281 }
caf2b6b5 282 } else if (EVP_DigestSign(mctx, sig, &siglen, hdata, hdatalen) <= 0) {
d8bc1399
MC
283 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_EVP_LIB);
284 goto err;
285 }
5f9b64a2 286
d8bc1399
MC
287#ifndef OPENSSL_NO_GOST
288 {
ad4dd362
DSH
289 int pktype = lu->sig;
290
d8bc1399
MC
291 if (pktype == NID_id_GostR3410_2001
292 || pktype == NID_id_GostR3410_2012_256
293 || pktype == NID_id_GostR3410_2012_512)
5f9b64a2 294 BUF_reverse(sig, NULL, siglen);
d8bc1399
MC
295 }
296#endif
297
5f9b64a2 298 if (!WPACKET_sub_memcpy_u16(pkt, sig, siglen)) {
d8bc1399
MC
299 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
300 goto err;
301 }
302
303 /* Digest cached records and discard handshake buffer */
304 if (!ssl3_digest_cached_records(s, 0))
305 goto err;
306
307 OPENSSL_free(sig);
308 EVP_MD_CTX_free(mctx);
309 return 1;
310 err:
311 OPENSSL_free(sig);
312 EVP_MD_CTX_free(mctx);
313 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
314 return 0;
315}
316
317MSG_PROCESS_RETURN tls_process_cert_verify(SSL *s, PACKET *pkt)
318{
319 EVP_PKEY *pkey = NULL;
703bcee0 320 const unsigned char *data;
d8bc1399
MC
321#ifndef OPENSSL_NO_GOST
322 unsigned char *gost_data = NULL;
323#endif
5f9b64a2 324 int al = SSL_AD_INTERNAL_ERROR, ret = MSG_PROCESS_ERROR;
dc8da7b1 325 int type = 0, j;
d8bc1399
MC
326 unsigned int len;
327 X509 *peer;
328 const EVP_MD *md = NULL;
2c5dfdc3 329 size_t hdatalen = 0;
d8bc1399 330 void *hdata;
2c5dfdc3 331 unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
d8bc1399 332 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
5f9b64a2 333 EVP_PKEY_CTX *pctx = NULL;
d8bc1399
MC
334
335 if (mctx == NULL) {
336 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
d8bc1399
MC
337 goto f_err;
338 }
339
340 peer = s->session->peer;
341 pkey = X509_get0_pubkey(peer);
fb34a0f4 342 if (pkey == NULL)
83b4049a 343 goto f_err;
83b4049a 344
d8bc1399
MC
345 type = X509_certificate_type(peer, pkey);
346
347 if (!(type & EVP_PKT_SIGN)) {
348 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY,
349 SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
350 al = SSL_AD_ILLEGAL_PARAMETER;
351 goto f_err;
352 }
353
354 /* Check for broken implementations of GOST ciphersuites */
355 /*
356 * If key is GOST and n is exactly 64, it is bare signature without
357 * length field (CryptoPro implementations at least till CSP 4.0)
358 */
359#ifndef OPENSSL_NO_GOST
360 if (PACKET_remaining(pkt) == 64
361 && EVP_PKEY_id(pkey) == NID_id_GostR3410_2001) {
362 len = 64;
363 } else
364#endif
365 {
366 if (SSL_USE_SIGALGS(s)) {
367 int rv;
703bcee0 368 unsigned int sigalg;
d8bc1399 369
703bcee0 370 if (!PACKET_get_net_2(pkt, &sigalg)) {
d8bc1399
MC
371 al = SSL_AD_DECODE_ERROR;
372 goto f_err;
373 }
5554facb 374 rv = tls12_check_peer_sigalg(s, sigalg, pkey);
d8bc1399 375 if (rv == -1) {
d8bc1399
MC
376 goto f_err;
377 } else if (rv == 0) {
378 al = SSL_AD_DECODE_ERROR;
379 goto f_err;
380 }
381#ifdef SSL_DEBUG
382 fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
383#endif
f365a3e2 384 } else if (!tls1_set_peer_legacy_sigalg(s, pkey)) {
d8bc1399
MC
385 al = SSL_AD_INTERNAL_ERROR;
386 goto f_err;
d8bc1399
MC
387 }
388
f365a3e2
DSH
389 md = ssl_md(s->s3->tmp.peer_sigalg->hash_idx);
390
d8bc1399
MC
391 if (!PACKET_get_net_2(pkt, &len)) {
392 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
393 al = SSL_AD_DECODE_ERROR;
394 goto f_err;
395 }
396 }
397 j = EVP_PKEY_size(pkey);
398 if (((int)len > j) || ((int)PACKET_remaining(pkt) > j)
399 || (PACKET_remaining(pkt) == 0)) {
400 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_WRONG_SIGNATURE_SIZE);
401 al = SSL_AD_DECODE_ERROR;
402 goto f_err;
403 }
404 if (!PACKET_get_bytes(pkt, &data, len)) {
405 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
406 al = SSL_AD_DECODE_ERROR;
407 goto f_err;
408 }
409
2c5dfdc3 410 if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
d8bc1399 411 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
d8bc1399
MC
412 goto f_err;
413 }
414
415#ifdef SSL_DEBUG
416 fprintf(stderr, "Using client verify alg %s\n", EVP_MD_name(md));
417#endif
75394189 418 if (EVP_DigestVerifyInit(mctx, &pctx, md, NULL, pkey) <= 0) {
d8bc1399 419 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
d8bc1399
MC
420 goto f_err;
421 }
422#ifndef OPENSSL_NO_GOST
423 {
dc8da7b1 424 int pktype = EVP_PKEY_id(pkey);
d8bc1399
MC
425 if (pktype == NID_id_GostR3410_2001
426 || pktype == NID_id_GostR3410_2012_256
427 || pktype == NID_id_GostR3410_2012_512) {
428 if ((gost_data = OPENSSL_malloc(len)) == NULL) {
429 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
d8bc1399
MC
430 goto f_err;
431 }
432 BUF_reverse(gost_data, data, len);
433 data = gost_data;
434 }
435 }
436#endif
437
5554facb 438 if (SSL_USE_PSS(s)) {
5f9b64a2 439 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
968ae5b3
DSH
440 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
441 RSA_PSS_SALTLEN_DIGEST) <= 0) {
5f9b64a2
MC
442 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
443 goto f_err;
444 }
d8bc1399 445 }
caf2b6b5
DSH
446 if (s->version == SSL3_VERSION) {
447 if (EVP_DigestVerifyUpdate(mctx, hdata, hdatalen) <= 0
448 || !EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
449 (int)s->session->master_key_length,
450 s->session->master_key)) {
451 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
452 goto f_err;
453 }
454 if (EVP_DigestVerifyFinal(mctx, data, len) <= 0) {
455 al = SSL_AD_DECRYPT_ERROR;
456 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_BAD_SIGNATURE);
457 goto f_err;
458 }
459 } else {
460 j = EVP_DigestVerify(mctx, data, len, hdata, hdatalen);
461 if (j < 0) {
462 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
463 goto f_err;
464 } else if (j == 0) {
465 al = SSL_AD_DECRYPT_ERROR;
466 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_BAD_SIGNATURE);
467 goto f_err;
468 }
d8bc1399
MC
469 }
470
bd79bcb4 471 ret = MSG_PROCESS_CONTINUE_READING;
d8bc1399
MC
472 if (0) {
473 f_err:
474 ssl3_send_alert(s, SSL3_AL_FATAL, al);
475 ossl_statem_set_error(s);
476 }
477 BIO_free(s->s3->handshake_buffer);
478 s->s3->handshake_buffer = NULL;
479 EVP_MD_CTX_free(mctx);
480#ifndef OPENSSL_NO_GOST
481 OPENSSL_free(gost_data);
482#endif
483 return ret;
484}
485
229185e6 486int tls_construct_finished(SSL *s, WPACKET *pkt)
0f113f3e 487{
12472b45 488 size_t finish_md_len;
229185e6 489 const char *sender;
8b0e934a 490 size_t slen;
229185e6 491
f7e393be
MC
492 /* This is a real handshake so make sure we clean it up at the end */
493 if (!s->server)
494 s->statem.cleanuphand = 1;
495
496 /*
497 * We only change the keys if we didn't already do this when we sent the
498 * client certificate
499 */
500 if (SSL_IS_TLS13(s)
501 && !s->server
502 && s->s3->tmp.cert_req == 0
503 && (!s->method->ssl3_enc->change_cipher_state(s,
504 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE))) {
505 SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, SSL_R_CANNOT_CHANGE_CIPHER);
506 goto err;
507 }
508
229185e6
MC
509 if (s->server) {
510 sender = s->method->ssl3_enc->server_finished_label;
511 slen = s->method->ssl3_enc->server_finished_label_len;
512 } else {
513 sender = s->method->ssl3_enc->client_finished_label;
514 slen = s->method->ssl3_enc->client_finished_label_len;
515 }
0f113f3e 516
12472b45
MC
517 finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
518 sender, slen,
519 s->s3->tmp.finish_md);
520 if (finish_md_len == 0) {
4f89bfbf
MC
521 SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, ERR_R_INTERNAL_ERROR);
522 goto err;
523 }
524
12472b45 525 s->s3->tmp.finish_md_len = finish_md_len;
4f89bfbf 526
12472b45 527 if (!WPACKET_memcpy(pkt, s->s3->tmp.finish_md, finish_md_len)) {
4f89bfbf
MC
528 SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, ERR_R_INTERNAL_ERROR);
529 goto err;
530 }
0f113f3e 531
2c7bd692
CB
532 /*
533 * Log the master secret, if logging is enabled. We don't log it for
534 * TLSv1.3: there's a different key schedule for that.
535 */
536 if (!SSL_IS_TLS13(s) && !ssl_log_secret(s, MASTER_SECRET_LABEL,
537 s->session->master_key,
380a522f
MC
538 s->session->master_key_length)) {
539 SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, ERR_R_INTERNAL_ERROR);
540 goto err;
541 }
2faa1b48 542
b9908bf9
MC
543 /*
544 * Copy the finished so we can use it for renegotiation checks
545 */
380a522f
MC
546 if (!ossl_assert(finish_md_len <= EVP_MAX_MD_SIZE)) {
547 SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, ERR_R_INTERNAL_ERROR);
548 goto err;
549 }
23a635c0 550 if (!s->server) {
12472b45
MC
551 memcpy(s->s3->previous_client_finished, s->s3->tmp.finish_md,
552 finish_md_len);
553 s->s3->previous_client_finished_len = finish_md_len;
b9908bf9 554 } else {
12472b45
MC
555 memcpy(s->s3->previous_server_finished, s->s3->tmp.finish_md,
556 finish_md_len);
557 s->s3->previous_server_finished_len = finish_md_len;
b9908bf9 558 }
0f113f3e 559
b9908bf9 560 return 1;
4f89bfbf 561 err:
4f89bfbf
MC
562 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
563 return 0;
0f113f3e 564}
d02b48c6 565
44c04a2e
MC
566int tls_construct_key_update(SSL *s, WPACKET *pkt)
567{
568 if (!WPACKET_put_bytes_u8(pkt, s->key_update)) {
569 SSLerr(SSL_F_TLS_CONSTRUCT_KEY_UPDATE, ERR_R_INTERNAL_ERROR);
570 goto err;
571 }
572
9412b3ad 573 s->key_update = SSL_KEY_UPDATE_NONE;
44c04a2e 574 return 1;
f14afcaa 575
44c04a2e
MC
576 err:
577 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
578 return 0;
579}
580
e1c3de44
MC
581MSG_PROCESS_RETURN tls_process_key_update(SSL *s, PACKET *pkt)
582{
57389a32 583 int al;
e1c3de44
MC
584 unsigned int updatetype;
585
82f992cb
MC
586 s->key_update_count++;
587 if (s->key_update_count > MAX_KEY_UPDATE_MESSAGES) {
588 al = SSL_AD_ILLEGAL_PARAMETER;
589 SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, SSL_R_TOO_MANY_KEY_UPDATES);
590 goto err;
591 }
592
524420d8
MC
593 /*
594 * A KeyUpdate message signals a key change so the end of the message must
595 * be on a record boundary.
596 */
597 if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
598 al = SSL_AD_UNEXPECTED_MESSAGE;
599 SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, SSL_R_NOT_ON_RECORD_BOUNDARY);
600 goto err;
601 }
602
e1c3de44 603 if (!PACKET_get_1(pkt, &updatetype)
2d871227 604 || PACKET_remaining(pkt) != 0) {
57389a32 605 al = SSL_AD_DECODE_ERROR;
e1c3de44 606 SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, SSL_R_BAD_KEY_UPDATE);
57389a32 607 goto err;
e1c3de44
MC
608 }
609
9010b7bc
MC
610 /*
611 * There are only two defined key update types. Fail if we get a value we
612 * didn't recognise.
613 */
2d871227
MC
614 if (updatetype != SSL_KEY_UPDATE_NOT_REQUESTED
615 && updatetype != SSL_KEY_UPDATE_REQUESTED) {
616 al = SSL_AD_ILLEGAL_PARAMETER;
617 SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, SSL_R_BAD_KEY_UPDATE);
618 goto err;
619 }
620
5bf47933
MC
621 /*
622 * If we get a request for us to update our sending keys too then, we need
623 * to additionally send a KeyUpdate message. However that message should
624 * not also request an update (otherwise we get into an infinite loop).
625 */
626 if (updatetype == SSL_KEY_UPDATE_REQUESTED)
627 s->key_update = SSL_KEY_UPDATE_NOT_REQUESTED;
628
57389a32
MC
629 if (!tls13_update_key(s, 0)) {
630 al = SSL_AD_INTERNAL_ERROR;
631 SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, ERR_R_INTERNAL_ERROR);
632 goto err;
633 }
634
e1c3de44 635 return MSG_PROCESS_FINISHED_READING;
57389a32
MC
636 err:
637 ssl3_send_alert(s, SSL3_AL_FATAL, al);
638 ossl_statem_set_error(s);
639 return MSG_PROCESS_ERROR;
e1c3de44
MC
640}
641
bf48836c 642#ifndef OPENSSL_NO_NEXTPROTONEG
0f113f3e
MC
643/*
644 * ssl3_take_mac calculates the Finished MAC for the handshakes messages seen
645 * to far.
646 */
ee2ffc27 647static void ssl3_take_mac(SSL *s)
0f113f3e
MC
648{
649 const char *sender;
8b0e934a 650 size_t slen;
0f113f3e
MC
651 /*
652 * If no new cipher setup return immediately: other functions will set
653 * the appropriate error.
654 */
655 if (s->s3->tmp.new_cipher == NULL)
656 return;
49ae7423 657 if (!s->server) {
0f113f3e
MC
658 sender = s->method->ssl3_enc->server_finished_label;
659 slen = s->method->ssl3_enc->server_finished_label_len;
660 } else {
661 sender = s->method->ssl3_enc->client_finished_label;
662 slen = s->method->ssl3_enc->client_finished_label_len;
663 }
664
665 s->s3->tmp.peer_finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
666 sender,
667 slen,
668 s->s3->tmp.peer_finish_md);
669}
ee2ffc27
BL
670#endif
671
be3583fa 672MSG_PROCESS_RETURN tls_process_change_cipher_spec(SSL *s, PACKET *pkt)
b9908bf9
MC
673{
674 int al;
348240c6 675 size_t remain;
4fa52141 676
73999b62 677 remain = PACKET_remaining(pkt);
657da85e
MC
678 /*
679 * 'Change Cipher Spec' is just a single byte, which should already have
c69f2adf
MC
680 * been consumed by ssl_get_message() so there should be no bytes left,
681 * unless we're using DTLS1_BAD_VER, which has an extra 2 bytes
657da85e 682 */
c69f2adf 683 if (SSL_IS_DTLS(s)) {
73999b62 684 if ((s->version == DTLS1_BAD_VER
a230b26e
EK
685 && remain != DTLS1_CCS_HEADER_LENGTH + 1)
686 || (s->version != DTLS1_BAD_VER
687 && remain != DTLS1_CCS_HEADER_LENGTH - 1)) {
fb34a0f4 688 al = SSL_AD_DECODE_ERROR;
a230b26e
EK
689 SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
690 SSL_R_BAD_CHANGE_CIPHER_SPEC);
691 goto f_err;
c69f2adf
MC
692 }
693 } else {
73999b62 694 if (remain != 0) {
fb34a0f4 695 al = SSL_AD_DECODE_ERROR;
b9908bf9
MC
696 SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
697 SSL_R_BAD_CHANGE_CIPHER_SPEC);
c69f2adf
MC
698 goto f_err;
699 }
657da85e
MC
700 }
701
702 /* Check we have a cipher to change to */
703 if (s->s3->tmp.new_cipher == NULL) {
704 al = SSL_AD_UNEXPECTED_MESSAGE;
b9908bf9 705 SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC, SSL_R_CCS_RECEIVED_EARLY);
657da85e
MC
706 goto f_err;
707 }
708
709 s->s3->change_cipher_spec = 1;
710 if (!ssl3_do_change_cipher_spec(s)) {
711 al = SSL_AD_INTERNAL_ERROR;
b9908bf9 712 SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
657da85e
MC
713 goto f_err;
714 }
715
c69f2adf
MC
716 if (SSL_IS_DTLS(s)) {
717 dtls1_reset_seq_numbers(s, SSL3_CC_READ);
718
719 if (s->version == DTLS1_BAD_VER)
720 s->d1->handshake_read_seq++;
721
722#ifndef OPENSSL_NO_SCTP
723 /*
724 * Remember that a CCS has been received, so that an old key of
725 * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
726 * SCTP is used
727 */
728 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
729#endif
730 }
731
b9908bf9 732 return MSG_PROCESS_CONTINUE_READING;
657da85e
MC
733 f_err:
734 ssl3_send_alert(s, SSL3_AL_FATAL, al);
fe3a3291 735 ossl_statem_set_error(s);
b9908bf9 736 return MSG_PROCESS_ERROR;
657da85e
MC
737}
738
be3583fa 739MSG_PROCESS_RETURN tls_process_finished(SSL *s, PACKET *pkt)
b9908bf9 740{
7776a36c 741 int al = SSL_AD_INTERNAL_ERROR;
12472b45 742 size_t md_len;
b9908bf9 743
d781d247
MC
744
745 /* This is a real handshake so make sure we clean it up at the end */
f7e393be
MC
746 if (s->server)
747 s->statem.cleanuphand = 1;
d781d247 748
524420d8
MC
749 /*
750 * In TLSv1.3 a Finished message signals a key change so the end of the
751 * message must be on a record boundary.
752 */
753 if (SSL_IS_TLS13(s) && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
754 al = SSL_AD_UNEXPECTED_MESSAGE;
755 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_NOT_ON_RECORD_BOUNDARY);
756 goto f_err;
757 }
758
0f113f3e 759 /* If this occurs, we have missed a message */
92760c21 760 if (!SSL_IS_TLS13(s) && !s->s3->change_cipher_spec) {
0f113f3e 761 al = SSL_AD_UNEXPECTED_MESSAGE;
b9908bf9 762 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_GOT_A_FIN_BEFORE_A_CCS);
0f113f3e
MC
763 goto f_err;
764 }
765 s->s3->change_cipher_spec = 0;
766
12472b45 767 md_len = s->s3->tmp.peer_finish_md_len;
0f113f3e 768
12472b45 769 if (md_len != PACKET_remaining(pkt)) {
0f113f3e 770 al = SSL_AD_DECODE_ERROR;
b9908bf9 771 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_BAD_DIGEST_LENGTH);
0f113f3e
MC
772 goto f_err;
773 }
774
12472b45
MC
775 if (CRYPTO_memcmp(PACKET_data(pkt), s->s3->tmp.peer_finish_md,
776 md_len) != 0) {
0f113f3e 777 al = SSL_AD_DECRYPT_ERROR;
b9908bf9 778 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_DIGEST_CHECK_FAILED);
0f113f3e
MC
779 goto f_err;
780 }
781
782 /*
783 * Copy the finished so we can use it for renegotiation checks
784 */
380a522f
MC
785 if (!ossl_assert(md_len <= EVP_MAX_MD_SIZE)) {
786 al = SSL_AD_INTERNAL_ERROR;
787 SSLerr(SSL_F_TLS_PROCESS_FINISHED, ERR_R_INTERNAL_ERROR);
788 goto f_err;
789 }
23a635c0 790 if (s->server) {
12472b45
MC
791 memcpy(s->s3->previous_client_finished, s->s3->tmp.peer_finish_md,
792 md_len);
793 s->s3->previous_client_finished_len = md_len;
0f113f3e 794 } else {
12472b45
MC
795 memcpy(s->s3->previous_server_finished, s->s3->tmp.peer_finish_md,
796 md_len);
797 s->s3->previous_server_finished_len = md_len;
0f113f3e
MC
798 }
799
7776a36c
MC
800 /*
801 * In TLS1.3 we also have to change cipher state and do any final processing
802 * of the initial server flight (if we are a client)
803 */
92760c21
MC
804 if (SSL_IS_TLS13(s)) {
805 if (s->server) {
806 if (!s->method->ssl3_enc->change_cipher_state(s,
807 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_READ)) {
92760c21
MC
808 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_CANNOT_CHANGE_CIPHER);
809 goto f_err;
810 }
811 } else {
812 if (!s->method->ssl3_enc->generate_master_secret(s,
ec15acb6 813 s->master_secret, s->handshake_secret, 0,
92760c21 814 &s->session->master_key_length)) {
92760c21
MC
815 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_CANNOT_CHANGE_CIPHER);
816 goto f_err;
817 }
818 if (!s->method->ssl3_enc->change_cipher_state(s,
819 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_READ)) {
92760c21
MC
820 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_CANNOT_CHANGE_CIPHER);
821 goto f_err;
822 }
7776a36c
MC
823 if (!tls_process_initial_server_flight(s, &al))
824 goto f_err;
92760c21
MC
825 }
826 }
827
e6575156 828 return MSG_PROCESS_FINISHED_READING;
0f113f3e
MC
829 f_err:
830 ssl3_send_alert(s, SSL3_AL_FATAL, al);
fe3a3291 831 ossl_statem_set_error(s);
b9908bf9 832 return MSG_PROCESS_ERROR;
0f113f3e 833}
d02b48c6 834
7cea05dc 835int tls_construct_change_cipher_spec(SSL *s, WPACKET *pkt)
b9908bf9 836{
7cea05dc 837 if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS)) {
3c106325 838 SSLerr(SSL_F_TLS_CONSTRUCT_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
85a7a5e6
MC
839 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
840 return 0;
841 }
b9908bf9 842
b9908bf9
MC
843 return 1;
844}
845
e96e0f8e
MC
846/* Add a certificate to the WPACKET */
847static int ssl_add_cert_to_wpacket(SSL *s, WPACKET *pkt, X509 *x, int chain,
848 int *al)
0f113f3e 849{
e96e0f8e
MC
850 int len;
851 unsigned char *outbytes;
852
853 len = i2d_X509(x, NULL);
854 if (len < 0) {
f63e4288 855 SSLerr(SSL_F_SSL_ADD_CERT_TO_WPACKET, ERR_R_BUF_LIB);
e96e0f8e
MC
856 *al = SSL_AD_INTERNAL_ERROR;
857 return 0;
858 }
859 if (!WPACKET_sub_allocate_bytes_u24(pkt, len, &outbytes)
860 || i2d_X509(x, &outbytes) != len) {
f63e4288 861 SSLerr(SSL_F_SSL_ADD_CERT_TO_WPACKET, ERR_R_INTERNAL_ERROR);
e96e0f8e
MC
862 *al = SSL_AD_INTERNAL_ERROR;
863 return 0;
864 }
865
866 if (SSL_IS_TLS13(s)
fe874d27 867 && !tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_CERTIFICATE, x,
e96e0f8e
MC
868 chain, al))
869 return 0;
870
871 return 1;
872}
873
874/* Add certificate chain to provided WPACKET */
875static int ssl_add_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk, int *al)
876{
877 int i, chain_count;
878 X509 *x;
879 STACK_OF(X509) *extra_certs;
880 STACK_OF(X509) *chain = NULL;
881 X509_STORE *chain_store;
882 int tmpal = SSL_AD_INTERNAL_ERROR;
883
884 if (cpk == NULL || cpk->x509 == NULL)
885 return 1;
886
887 x = cpk->x509;
888
889 /*
890 * If we have a certificate specific chain use it, else use parent ctx.
891 */
d805a57b 892 if (cpk->chain != NULL)
e96e0f8e
MC
893 extra_certs = cpk->chain;
894 else
895 extra_certs = s->ctx->extra_certs;
896
897 if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || extra_certs)
898 chain_store = NULL;
899 else if (s->cert->chain_store)
900 chain_store = s->cert->chain_store;
901 else
902 chain_store = s->ctx->cert_store;
903
d805a57b 904 if (chain_store != NULL) {
e96e0f8e
MC
905 X509_STORE_CTX *xs_ctx = X509_STORE_CTX_new();
906
907 if (xs_ctx == NULL) {
908 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, ERR_R_MALLOC_FAILURE);
909 goto err;
910 }
911 if (!X509_STORE_CTX_init(xs_ctx, chain_store, x, NULL)) {
912 X509_STORE_CTX_free(xs_ctx);
913 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, ERR_R_X509_LIB);
914 goto err;
915 }
916 /*
917 * It is valid for the chain not to be complete (because normally we
918 * don't include the root cert in the chain). Therefore we deliberately
919 * ignore the error return from this call. We're not actually verifying
920 * the cert - we're just building as much of the chain as we can
921 */
922 (void)X509_verify_cert(xs_ctx);
923 /* Don't leave errors in the queue */
924 ERR_clear_error();
925 chain = X509_STORE_CTX_get0_chain(xs_ctx);
926 i = ssl_security_cert_chain(s, chain, NULL, 0);
927 if (i != 1) {
928#if 0
929 /* Dummy error calls so mkerr generates them */
930 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_EE_KEY_TOO_SMALL);
931 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_CA_KEY_TOO_SMALL);
932 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_CA_MD_TOO_WEAK);
933#endif
934 X509_STORE_CTX_free(xs_ctx);
935 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, i);
936 goto err;
937 }
938 chain_count = sk_X509_num(chain);
939 for (i = 0; i < chain_count; i++) {
940 x = sk_X509_value(chain, i);
941
942 if (!ssl_add_cert_to_wpacket(s, pkt, x, i, &tmpal)) {
943 X509_STORE_CTX_free(xs_ctx);
944 goto err;
945 }
946 }
947 X509_STORE_CTX_free(xs_ctx);
948 } else {
949 i = ssl_security_cert_chain(s, extra_certs, x, 0);
950 if (i != 1) {
951 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, i);
952 goto err;
953 }
954 if (!ssl_add_cert_to_wpacket(s, pkt, x, 0, &tmpal))
955 goto err;
956 for (i = 0; i < sk_X509_num(extra_certs); i++) {
957 x = sk_X509_value(extra_certs, i);
958 if (!ssl_add_cert_to_wpacket(s, pkt, x, i + 1, &tmpal))
959 goto err;
960 }
961 }
962 return 1;
963
964 err:
965 *al = tmpal;
966 return 0;
967}
968
969unsigned long ssl3_output_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk,
970 int *al)
971{
972 int tmpal = SSL_AD_INTERNAL_ERROR;
973
5923ad4b 974 if (!WPACKET_start_sub_packet_u24(pkt)
e96e0f8e 975 || !ssl_add_cert_chain(s, pkt, cpk, &tmpal)
5923ad4b 976 || !WPACKET_close(pkt)) {
c49e1912 977 SSLerr(SSL_F_SSL3_OUTPUT_CERT_CHAIN, ERR_R_INTERNAL_ERROR);
e96e0f8e 978 *al = tmpal;
7cea05dc 979 return 0;
77d514c5 980 }
c49e1912 981 return 1;
0f113f3e
MC
982}
983
30f05b19
MC
984/*
985 * Tidy up after the end of a handshake. In the case of SCTP this may result
986 * in NBIO events. If |clearbufs| is set then init_buf and the wbio buffer is
987 * freed up as well.
988 */
989WORK_STATE tls_finish_handshake(SSL *s, WORK_STATE wst, int clearbufs)
8723588e
MC
990{
991 void (*cb) (const SSL *ssl, int type, int val) = NULL;
992
993#ifndef OPENSSL_NO_SCTP
994 if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))) {
be3583fa 995 WORK_STATE ret;
8723588e
MC
996 ret = dtls_wait_for_dry(s);
997 if (ret != WORK_FINISHED_CONTINUE)
998 return ret;
999 }
1000#endif
1001
30f05b19
MC
1002 if (clearbufs) {
1003 if (!SSL_IS_DTLS(s)) {
1004 /*
1005 * We don't do this in DTLS because we may still need the init_buf
1006 * in case there are any unexpected retransmits
1007 */
1008 BUF_MEM_free(s->init_buf);
1009 s->init_buf = NULL;
1010 }
b77f3ed1
MC
1011 if (!ssl_free_wbio_buffer(s))
1012 return WORK_ERROR;
30f05b19 1013 s->init_num = 0;
473483d4 1014 }
8723588e 1015
c7f47786 1016 if (s->statem.cleanuphand) {
8723588e
MC
1017 /* skipped if we just sent a HelloRequest */
1018 s->renegotiate = 0;
1019 s->new_session = 0;
c7f47786 1020 s->statem.cleanuphand = 0;
8723588e 1021
30f05b19
MC
1022 ssl3_cleanup_key_block(s);
1023
8723588e 1024 if (s->server) {
8723588e
MC
1025 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
1026
1027 s->ctx->stats.sess_accept_good++;
fe3a3291 1028 s->handshake_func = ossl_statem_accept;
8723588e
MC
1029 } else {
1030 ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
1031 if (s->hit)
1032 s->ctx->stats.sess_hit++;
1033
fe3a3291 1034 s->handshake_func = ossl_statem_connect;
8723588e
MC
1035 s->ctx->stats.sess_connect_good++;
1036 }
1037
1038 if (s->info_callback != NULL)
1039 cb = s->info_callback;
1040 else if (s->ctx->info_callback != NULL)
1041 cb = s->ctx->info_callback;
1042
1043 if (cb != NULL)
1044 cb(s, SSL_CB_HANDSHAKE_DONE, 1);
1045
1046 if (SSL_IS_DTLS(s)) {
1047 /* done with handshaking */
1048 s->d1->handshake_read_seq = 0;
1049 s->d1->handshake_write_seq = 0;
1050 s->d1->next_handshake_write_seq = 0;
f5c7f5df 1051 dtls1_clear_received_buffer(s);
8723588e
MC
1052 }
1053 }
1054
30f05b19
MC
1055 /*
1056 * If we've not cleared the buffers its because we've got more work to do,
1057 * so continue.
1058 */
1059 if (!clearbufs)
1060 return WORK_FINISHED_CONTINUE;
1061
4004ce5f 1062 ossl_statem_set_in_init(s, 0);
8723588e
MC
1063 return WORK_FINISHED_STOP;
1064}
1065
9ab930b2
MC
1066int tls_get_message_header(SSL *s, int *mt)
1067{
1068 /* s->init_num < SSL3_HM_HEADER_LENGTH */
1069 int skip_message, i, recvd_type, al;
1070 unsigned char *p;
54105ddd 1071 size_t l, readbytes;
9ab930b2
MC
1072
1073 p = (unsigned char *)s->init_buf->data;
1074
1075 do {
1076 while (s->init_num < SSL3_HM_HEADER_LENGTH) {
1077 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, &recvd_type,
a230b26e
EK
1078 &p[s->init_num],
1079 SSL3_HM_HEADER_LENGTH - s->init_num,
54105ddd 1080 0, &readbytes);
9ab930b2
MC
1081 if (i <= 0) {
1082 s->rwstate = SSL_READING;
1083 return 0;
32ec4153 1084 }
9ab930b2 1085 if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1257adec 1086 /*
a230b26e
EK
1087 * A ChangeCipherSpec must be a single byte and may not occur
1088 * in the middle of a handshake message.
1089 */
54105ddd 1090 if (s->init_num != 0 || readbytes != 1 || p[0] != SSL3_MT_CCS) {
1257adec
DB
1091 al = SSL_AD_UNEXPECTED_MESSAGE;
1092 SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER,
1093 SSL_R_BAD_CHANGE_CIPHER_SPEC);
1094 goto f_err;
1095 }
9ab930b2 1096 s->s3->tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
54105ddd 1097 s->init_num = readbytes - 1;
c4377574 1098 s->init_msg = s->init_buf->data;
54105ddd 1099 s->s3->tmp.message_size = readbytes;
9ab930b2
MC
1100 return 1;
1101 } else if (recvd_type != SSL3_RT_HANDSHAKE) {
1102 al = SSL_AD_UNEXPECTED_MESSAGE;
1103 SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, SSL_R_CCS_RECEIVED_EARLY);
32ec4153
MC
1104 goto f_err;
1105 }
54105ddd 1106 s->init_num += readbytes;
9ab930b2
MC
1107 }
1108
1109 skip_message = 0;
1110 if (!s->server)
c7f47786
MC
1111 if (s->statem.hand_state != TLS_ST_OK
1112 && p[0] == SSL3_MT_HELLO_REQUEST)
9ab930b2
MC
1113 /*
1114 * The server may always send 'Hello Request' messages --
1115 * we are doing a handshake anyway now, so ignore them if
1116 * their format is correct. Does not count for 'Finished'
1117 * MAC.
1118 */
1119 if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
1120 s->init_num = 0;
1121 skip_message = 1;
1122
1123 if (s->msg_callback)
1124 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1125 p, SSL3_HM_HEADER_LENGTH, s,
1126 s->msg_callback_arg);
1127 }
1128 } while (skip_message);
1129 /* s->init_num == SSL3_HM_HEADER_LENGTH */
1130
1131 *mt = *p;
1132 s->s3->tmp.message_type = *(p++);
32ec4153 1133
e8aa8b6c 1134 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
9ab930b2
MC
1135 /*
1136 * Only happens with SSLv3+ in an SSLv2 backward compatible
1137 * ClientHello
e8aa8b6c
F
1138 *
1139 * Total message size is the remaining record bytes to read
1140 * plus the SSL3_HM_HEADER_LENGTH bytes that we already read
9ab930b2 1141 */
9ab930b2
MC
1142 l = RECORD_LAYER_get_rrec_length(&s->rlayer)
1143 + SSL3_HM_HEADER_LENGTH;
9ab930b2
MC
1144 s->s3->tmp.message_size = l;
1145
1146 s->init_msg = s->init_buf->data;
1147 s->init_num = SSL3_HM_HEADER_LENGTH;
1148 } else {
1149 n2l3(p, l);
1150 /* BUF_MEM_grow takes an 'int' parameter */
1151 if (l > (INT_MAX - SSL3_HM_HEADER_LENGTH)) {
1152 al = SSL_AD_ILLEGAL_PARAMETER;
1153 SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, SSL_R_EXCESSIVE_MESSAGE_SIZE);
1154 goto f_err;
32ec4153 1155 }
9ab930b2
MC
1156 s->s3->tmp.message_size = l;
1157
1158 s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
1159 s->init_num = 0;
1160 }
1161
1162 return 1;
1163 f_err:
1164 ssl3_send_alert(s, SSL3_AL_FATAL, al);
9ab930b2
MC
1165 return 0;
1166}
1167
eda75751 1168int tls_get_message_body(SSL *s, size_t *len)
9ab930b2 1169{
54105ddd 1170 size_t n, readbytes;
9ab930b2
MC
1171 unsigned char *p;
1172 int i;
1173
1174 if (s->s3->tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
1175 /* We've already read everything in */
1176 *len = (unsigned long)s->init_num;
1177 return 1;
0f113f3e
MC
1178 }
1179
0f113f3e
MC
1180 p = s->init_msg;
1181 n = s->s3->tmp.message_size - s->init_num;
1182 while (n > 0) {
657da85e 1183 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
54105ddd 1184 &p[s->init_num], n, 0, &readbytes);
0f113f3e
MC
1185 if (i <= 0) {
1186 s->rwstate = SSL_READING;
9ab930b2
MC
1187 *len = 0;
1188 return 0;
0f113f3e 1189 }
54105ddd
MC
1190 s->init_num += readbytes;
1191 n -= readbytes;
0f113f3e 1192 }
ee2ffc27 1193
bf48836c 1194#ifndef OPENSSL_NO_NEXTPROTONEG
0f113f3e
MC
1195 /*
1196 * If receiving Finished, record MAC of prior handshake messages for
1197 * Finished verification.
1198 */
1199 if (*s->init_buf->data == SSL3_MT_FINISHED)
1200 ssl3_take_mac(s);
ee2ffc27
BL
1201#endif
1202
0f113f3e 1203 /* Feed this message into MAC computation. */
e8aa8b6c 1204 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
d166ed8c
DSH
1205 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1206 s->init_num)) {
1207 SSLerr(SSL_F_TLS_GET_MESSAGE_BODY, ERR_R_EVP_LIB);
1208 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1209 *len = 0;
1210 return 0;
1211 }
32ec4153 1212 if (s->msg_callback)
a230b26e 1213 s->msg_callback(0, SSL2_VERSION, 0, s->init_buf->data,
32ec4153
MC
1214 (size_t)s->init_num, s, s->msg_callback_arg);
1215 } else {
11c67eea
MC
1216 /*
1217 * We defer feeding in the HRR until later. We'll do it as part of
1218 * processing the message
1219 */
1220 if (s->s3->tmp.message_type != SSL3_MT_HELLO_RETRY_REQUEST
1221 && !ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1222 s->init_num + SSL3_HM_HEADER_LENGTH)) {
d166ed8c
DSH
1223 SSLerr(SSL_F_TLS_GET_MESSAGE_BODY, ERR_R_EVP_LIB);
1224 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1225 *len = 0;
1226 return 0;
1227 }
32ec4153
MC
1228 if (s->msg_callback)
1229 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
1230 (size_t)s->init_num + SSL3_HM_HEADER_LENGTH, s,
1231 s->msg_callback_arg);
1232 }
1233
eda75751 1234 *len = s->init_num;
9ab930b2 1235 return 1;
0f113f3e 1236}
d02b48c6 1237
2e5ead83 1238int ssl_cert_type(const X509 *x, const EVP_PKEY *pk)
0f113f3e 1239{
a230b26e 1240 if (pk == NULL && (pk = X509_get0_pubkey(x)) == NULL)
17a72388
VD
1241 return -1;
1242
1243 switch (EVP_PKEY_id(pk)) {
1244 default:
1245 return -1;
1246 case EVP_PKEY_RSA:
d0ff28f8 1247 return SSL_PKEY_RSA;
17a72388
VD
1248 case EVP_PKEY_DSA:
1249 return SSL_PKEY_DSA_SIGN;
ea262260 1250#ifndef OPENSSL_NO_EC
17a72388
VD
1251 case EVP_PKEY_EC:
1252 return SSL_PKEY_ECC;
ea262260 1253#endif
2a9b9654 1254#ifndef OPENSSL_NO_GOST
17a72388
VD
1255 case NID_id_GostR3410_2001:
1256 return SSL_PKEY_GOST01;
1257 case NID_id_GostR3410_2012_256:
1258 return SSL_PKEY_GOST12_256;
1259 case NID_id_GostR3410_2012_512:
1260 return SSL_PKEY_GOST12_512;
2a9b9654 1261#endif
82049c54 1262 }
0f113f3e 1263}
d02b48c6 1264
6b691a5c 1265int ssl_verify_alarm_type(long type)
0f113f3e
MC
1266{
1267 int al;
1268
1269 switch (type) {
1270 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1271 case X509_V_ERR_UNABLE_TO_GET_CRL:
1272 case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
1273 al = SSL_AD_UNKNOWN_CA;
1274 break;
1275 case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
1276 case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
1277 case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
1278 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1279 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1280 case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
1281 case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
1282 case X509_V_ERR_CERT_NOT_YET_VALID:
1283 case X509_V_ERR_CRL_NOT_YET_VALID:
1284 case X509_V_ERR_CERT_UNTRUSTED:
1285 case X509_V_ERR_CERT_REJECTED:
f3e235ed
VD
1286 case X509_V_ERR_HOSTNAME_MISMATCH:
1287 case X509_V_ERR_EMAIL_MISMATCH:
1288 case X509_V_ERR_IP_ADDRESS_MISMATCH:
1289 case X509_V_ERR_DANE_NO_MATCH:
1290 case X509_V_ERR_EE_KEY_TOO_SMALL:
1291 case X509_V_ERR_CA_KEY_TOO_SMALL:
1292 case X509_V_ERR_CA_MD_TOO_WEAK:
0f113f3e
MC
1293 al = SSL_AD_BAD_CERTIFICATE;
1294 break;
1295 case X509_V_ERR_CERT_SIGNATURE_FAILURE:
1296 case X509_V_ERR_CRL_SIGNATURE_FAILURE:
1297 al = SSL_AD_DECRYPT_ERROR;
1298 break;
1299 case X509_V_ERR_CERT_HAS_EXPIRED:
1300 case X509_V_ERR_CRL_HAS_EXPIRED:
1301 al = SSL_AD_CERTIFICATE_EXPIRED;
1302 break;
1303 case X509_V_ERR_CERT_REVOKED:
1304 al = SSL_AD_CERTIFICATE_REVOKED;
1305 break;
f3e235ed 1306 case X509_V_ERR_UNSPECIFIED:
0f113f3e 1307 case X509_V_ERR_OUT_OF_MEM:
f3e235ed
VD
1308 case X509_V_ERR_INVALID_CALL:
1309 case X509_V_ERR_STORE_LOOKUP:
0f113f3e
MC
1310 al = SSL_AD_INTERNAL_ERROR;
1311 break;
1312 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1313 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
1314 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
1315 case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
1316 case X509_V_ERR_CERT_CHAIN_TOO_LONG:
1317 case X509_V_ERR_PATH_LENGTH_EXCEEDED:
1318 case X509_V_ERR_INVALID_CA:
1319 al = SSL_AD_UNKNOWN_CA;
1320 break;
1321 case X509_V_ERR_APPLICATION_VERIFICATION:
1322 al = SSL_AD_HANDSHAKE_FAILURE;
1323 break;
1324 case X509_V_ERR_INVALID_PURPOSE:
1325 al = SSL_AD_UNSUPPORTED_CERTIFICATE;
1326 break;
1327 default:
1328 al = SSL_AD_CERTIFICATE_UNKNOWN;
1329 break;
1330 }
1331 return (al);
1332}
d02b48c6 1333
b362ccab 1334int ssl_allow_compression(SSL *s)
0f113f3e
MC
1335{
1336 if (s->options & SSL_OP_NO_COMPRESSION)
1337 return 0;
1338 return ssl_security(s, SSL_SECOP_COMPRESSION, 0, 0, NULL);
1339}
4fa52141 1340
068c358a 1341static int version_cmp(const SSL *s, int a, int b)
4fa52141
VD
1342{
1343 int dtls = SSL_IS_DTLS(s);
1344
1345 if (a == b)
1346 return 0;
1347 if (!dtls)
1348 return a < b ? -1 : 1;
1349 return DTLS_VERSION_LT(a, b) ? -1 : 1;
1350}
1351
1352typedef struct {
1353 int version;
a230b26e
EK
1354 const SSL_METHOD *(*cmeth) (void);
1355 const SSL_METHOD *(*smeth) (void);
4fa52141
VD
1356} version_info;
1357
582a17d6
MC
1358#if TLS_MAX_VERSION != TLS1_3_VERSION
1359# error Code needs update for TLS_method() support beyond TLS1_3_VERSION.
4fa52141
VD
1360#endif
1361
f7f2a01d 1362/* Must be in order high to low */
4fa52141 1363static const version_info tls_version_table[] = {
582a17d6
MC
1364#ifndef OPENSSL_NO_TLS1_3
1365 {TLS1_3_VERSION, tlsv1_3_client_method, tlsv1_3_server_method},
1366#else
1367 {TLS1_3_VERSION, NULL, NULL},
1368#endif
6b01bed2 1369#ifndef OPENSSL_NO_TLS1_2
a230b26e 1370 {TLS1_2_VERSION, tlsv1_2_client_method, tlsv1_2_server_method},
6b01bed2 1371#else
a230b26e 1372 {TLS1_2_VERSION, NULL, NULL},
6b01bed2
VD
1373#endif
1374#ifndef OPENSSL_NO_TLS1_1
a230b26e 1375 {TLS1_1_VERSION, tlsv1_1_client_method, tlsv1_1_server_method},
6b01bed2 1376#else
a230b26e 1377 {TLS1_1_VERSION, NULL, NULL},
6b01bed2
VD
1378#endif
1379#ifndef OPENSSL_NO_TLS1
a230b26e 1380 {TLS1_VERSION, tlsv1_client_method, tlsv1_server_method},
6b01bed2 1381#else
a230b26e 1382 {TLS1_VERSION, NULL, NULL},
6b01bed2 1383#endif
4fa52141 1384#ifndef OPENSSL_NO_SSL3
a230b26e 1385 {SSL3_VERSION, sslv3_client_method, sslv3_server_method},
6b01bed2 1386#else
a230b26e 1387 {SSL3_VERSION, NULL, NULL},
4fa52141 1388#endif
a230b26e 1389 {0, NULL, NULL},
4fa52141
VD
1390};
1391
1392#if DTLS_MAX_VERSION != DTLS1_2_VERSION
1393# error Code needs update for DTLS_method() support beyond DTLS1_2_VERSION.
1394#endif
1395
f7f2a01d 1396/* Must be in order high to low */
4fa52141 1397static const version_info dtls_version_table[] = {
6b01bed2 1398#ifndef OPENSSL_NO_DTLS1_2
a230b26e 1399 {DTLS1_2_VERSION, dtlsv1_2_client_method, dtlsv1_2_server_method},
6b01bed2 1400#else
a230b26e 1401 {DTLS1_2_VERSION, NULL, NULL},
6b01bed2
VD
1402#endif
1403#ifndef OPENSSL_NO_DTLS1
a230b26e
EK
1404 {DTLS1_VERSION, dtlsv1_client_method, dtlsv1_server_method},
1405 {DTLS1_BAD_VER, dtls_bad_ver_client_method, NULL},
6b01bed2 1406#else
a230b26e
EK
1407 {DTLS1_VERSION, NULL, NULL},
1408 {DTLS1_BAD_VER, NULL, NULL},
6b01bed2 1409#endif
a230b26e 1410 {0, NULL, NULL},
4fa52141
VD
1411};
1412
1413/*
1414 * ssl_method_error - Check whether an SSL_METHOD is enabled.
1415 *
1416 * @s: The SSL handle for the candidate method
1417 * @method: the intended method.
1418 *
1419 * Returns 0 on success, or an SSL error reason on failure.
1420 */
068c358a 1421static int ssl_method_error(const SSL *s, const SSL_METHOD *method)
4fa52141
VD
1422{
1423 int version = method->version;
1424
1425 if ((s->min_proto_version != 0 &&
1426 version_cmp(s, version, s->min_proto_version) < 0) ||
1427 ssl_security(s, SSL_SECOP_VERSION, 0, version, NULL) == 0)
1428 return SSL_R_VERSION_TOO_LOW;
1429
1430 if (s->max_proto_version != 0 &&
a230b26e 1431 version_cmp(s, version, s->max_proto_version) > 0)
4fa52141
VD
1432 return SSL_R_VERSION_TOO_HIGH;
1433
1434 if ((s->options & method->mask) != 0)
1435 return SSL_R_UNSUPPORTED_PROTOCOL;
1436 if ((method->flags & SSL_METHOD_NO_SUITEB) != 0 && tls1_suiteb(s))
1437 return SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE;
4fa52141
VD
1438
1439 return 0;
1440}
1441
ccae4a15
FI
1442/*
1443 * ssl_version_supported - Check that the specified `version` is supported by
1444 * `SSL *` instance
1445 *
1446 * @s: The SSL handle for the candidate method
1447 * @version: Protocol version to test against
1448 *
1449 * Returns 1 when supported, otherwise 0
1450 */
1451int ssl_version_supported(const SSL *s, int version)
1452{
1453 const version_info *vent;
1454 const version_info *table;
1455
1456 switch (s->method->version) {
1457 default:
1458 /* Version should match method version for non-ANY method */
1459 return version_cmp(s, version, s->version) == 0;
1460 case TLS_ANY_VERSION:
1461 table = tls_version_table;
1462 break;
1463 case DTLS_ANY_VERSION:
1464 table = dtls_version_table;
1465 break;
1466 }
1467
1468 for (vent = table;
1469 vent->version != 0 && version_cmp(s, version, vent->version) <= 0;
1470 ++vent) {
1471 if (vent->cmeth != NULL &&
1472 version_cmp(s, version, vent->version) == 0 &&
1473 ssl_method_error(s, vent->cmeth()) == 0) {
1474 return 1;
1475 }
1476 }
1477 return 0;
1478}
1479
4fa52141
VD
1480/*
1481 * ssl_check_version_downgrade - In response to RFC7507 SCSV version
1482 * fallback indication from a client check whether we're using the highest
1483 * supported protocol version.
1484 *
1485 * @s server SSL handle.
1486 *
1487 * Returns 1 when using the highest enabled version, 0 otherwise.
1488 */
1489int ssl_check_version_downgrade(SSL *s)
1490{
1491 const version_info *vent;
1492 const version_info *table;
1493
1494 /*
1495 * Check that the current protocol is the highest enabled version
1496 * (according to s->ctx->method, as version negotiation may have changed
1497 * s->method).
1498 */
1499 if (s->version == s->ctx->method->version)
1500 return 1;
1501
1502 /*
1503 * Apparently we're using a version-flexible SSL_METHOD (not at its
1504 * highest protocol version).
1505 */
1506 if (s->ctx->method->version == TLS_method()->version)
1507 table = tls_version_table;
1508 else if (s->ctx->method->version == DTLS_method()->version)
1509 table = dtls_version_table;
1510 else {
1511 /* Unexpected state; fail closed. */
1512 return 0;
1513 }
1514
1515 for (vent = table; vent->version != 0; ++vent) {
a230b26e 1516 if (vent->smeth != NULL && ssl_method_error(s, vent->smeth()) == 0)
4fa52141
VD
1517 return s->version == vent->version;
1518 }
1519 return 0;
1520}
1521
1522/*
1523 * ssl_set_version_bound - set an upper or lower bound on the supported (D)TLS
1524 * protocols, provided the initial (D)TLS method is version-flexible. This
1525 * function sanity-checks the proposed value and makes sure the method is
1526 * version-flexible, then sets the limit if all is well.
1527 *
1528 * @method_version: The version of the current SSL_METHOD.
1529 * @version: the intended limit.
1530 * @bound: pointer to limit to be updated.
1531 *
1532 * Returns 1 on success, 0 on failure.
1533 */
1534int ssl_set_version_bound(int method_version, int version, int *bound)
1535{
869e978c
KR
1536 if (version == 0) {
1537 *bound = version;
1538 return 1;
1539 }
1540
4fa52141
VD
1541 /*-
1542 * Restrict TLS methods to TLS protocol versions.
1543 * Restrict DTLS methods to DTLS protocol versions.
1544 * Note, DTLS version numbers are decreasing, use comparison macros.
1545 *
1546 * Note that for both lower-bounds we use explicit versions, not
1547 * (D)TLS_MIN_VERSION. This is because we don't want to break user
1548 * configurations. If the MIN (supported) version ever rises, the user's
1549 * "floor" remains valid even if no longer available. We don't expect the
1550 * MAX ceiling to ever get lower, so making that variable makes sense.
1551 */
1552 switch (method_version) {
1553 default:
1554 /*
1555 * XXX For fixed version methods, should we always fail and not set any
1556 * bounds, always succeed and not set any bounds, or set the bounds and
1557 * arrange to fail later if they are not met? At present fixed-version
1558 * methods are not subject to controls that disable individual protocol
1559 * versions.
1560 */
1561 return 0;
1562
1563 case TLS_ANY_VERSION:
1564 if (version < SSL3_VERSION || version > TLS_MAX_VERSION)
1565 return 0;
1566 break;
1567
1568 case DTLS_ANY_VERSION:
1569 if (DTLS_VERSION_GT(version, DTLS_MAX_VERSION) ||
032924c4 1570 DTLS_VERSION_LT(version, DTLS1_BAD_VER))
4fa52141
VD
1571 return 0;
1572 break;
1573 }
1574
1575 *bound = version;
1576 return 1;
1577}
1578
f7f2a01d
MC
1579static void check_for_downgrade(SSL *s, int vers, DOWNGRADE *dgrd)
1580{
1581 if (vers == TLS1_2_VERSION
1582 && ssl_version_supported(s, TLS1_3_VERSION)) {
1583 *dgrd = DOWNGRADE_TO_1_2;
1584 } else if (!SSL_IS_DTLS(s) && vers < TLS1_2_VERSION
1585 && (ssl_version_supported(s, TLS1_2_VERSION)
1586 || ssl_version_supported(s, TLS1_3_VERSION))) {
1587 *dgrd = DOWNGRADE_TO_1_1;
1588 } else {
1589 *dgrd = DOWNGRADE_NONE;
1590 }
1591}
1592
4fa52141
VD
1593/*
1594 * ssl_choose_server_version - Choose server (D)TLS version. Called when the
1595 * client HELLO is received to select the final server protocol version and
1596 * the version specific method.
1597 *
1598 * @s: server SSL handle.
1599 *
1600 * Returns 0 on success or an SSL error reason number on failure.
1601 */
f7f2a01d 1602int ssl_choose_server_version(SSL *s, CLIENTHELLO_MSG *hello, DOWNGRADE *dgrd)
4fa52141
VD
1603{
1604 /*-
1605 * With version-flexible methods we have an initial state with:
1606 *
1607 * s->method->version == (D)TLS_ANY_VERSION,
1608 * s->version == (D)TLS_MAX_VERSION.
1609 *
1610 * So we detect version-flexible methods via the method version, not the
1611 * handle version.
1612 */
1613 int server_version = s->method->version;
df7ce507 1614 int client_version = hello->legacy_version;
4fa52141
VD
1615 const version_info *vent;
1616 const version_info *table;
1617 int disabled = 0;
cd998837 1618 RAW_EXTENSION *suppversions;
4fa52141 1619
1ab3836b
MC
1620 s->client_version = client_version;
1621
4fa52141
VD
1622 switch (server_version) {
1623 default:
7d061fce
MC
1624 if (!SSL_IS_TLS13(s)) {
1625 if (version_cmp(s, client_version, s->version) < 0)
1626 return SSL_R_WRONG_SSL_VERSION;
f7f2a01d 1627 *dgrd = DOWNGRADE_NONE;
7d061fce
MC
1628 /*
1629 * If this SSL handle is not from a version flexible method we don't
1630 * (and never did) check min/max FIPS or Suite B constraints. Hope
1631 * that's OK. It is up to the caller to not choose fixed protocol
1632 * versions they don't want. If not, then easy to fix, just return
1633 * ssl_method_error(s, s->method)
1634 */
1635 return 0;
1636 }
d2f42576 1637 /*
7d061fce
MC
1638 * Fall through if we are TLSv1.3 already (this means we must be after
1639 * a HelloRetryRequest
4fa52141 1640 */
018fcbec 1641 /* fall thru */
4fa52141
VD
1642 case TLS_ANY_VERSION:
1643 table = tls_version_table;
1644 break;
1645 case DTLS_ANY_VERSION:
1646 table = dtls_version_table;
1647 break;
1648 }
1649
70af3d8e 1650 suppversions = &hello->pre_proc_exts[TLSEXT_IDX_supported_versions];
cd998837 1651
70af3d8e 1652 if (suppversions->present && !SSL_IS_DTLS(s)) {
cd998837
MC
1653 unsigned int candidate_vers = 0;
1654 unsigned int best_vers = 0;
1655 const SSL_METHOD *best_method = NULL;
1656 PACKET versionslist;
1657
6b473aca
MC
1658 suppversions->parsed = 1;
1659
16bce0e0 1660 if (!PACKET_as_length_prefixed_1(&suppversions->data, &versionslist)) {
cd998837
MC
1661 /* Trailing or invalid data? */
1662 return SSL_R_LENGTH_MISMATCH;
1663 }
1664
1665 while (PACKET_get_net_2(&versionslist, &candidate_vers)) {
1666 /* TODO(TLS1.3): Remove this before release */
1667 if (candidate_vers == TLS1_3_VERSION_DRAFT)
1668 candidate_vers = TLS1_3_VERSION;
f2342b7a
MC
1669 /*
1670 * TODO(TLS1.3): There is some discussion on the TLS list about
1ee4b98e 1671 * whether to ignore versions <TLS1.2 in supported_versions. At the
f2342b7a
MC
1672 * moment we honour them if present. To be reviewed later
1673 */
cd998837
MC
1674 if (version_cmp(s, candidate_vers, best_vers) <= 0)
1675 continue;
1676 for (vent = table;
1677 vent->version != 0 && vent->version != (int)candidate_vers;
16bce0e0 1678 ++vent)
bf0ba5e7 1679 continue;
bf85ef1b 1680 if (vent->version != 0 && vent->smeth != NULL) {
cd998837
MC
1681 const SSL_METHOD *method;
1682
1683 method = vent->smeth();
1684 if (ssl_method_error(s, method) == 0) {
1685 best_vers = candidate_vers;
1686 best_method = method;
1687 }
1688 }
1689 }
1690 if (PACKET_remaining(&versionslist) != 0) {
1691 /* Trailing data? */
1692 return SSL_R_LENGTH_MISMATCH;
1693 }
1694
1695 if (best_vers > 0) {
7d061fce
MC
1696 if (SSL_IS_TLS13(s)) {
1697 /*
1698 * We get here if this is after a HelloRetryRequest. In this
1699 * case we just check that we still negotiated TLSv1.3
1700 */
1701 if (best_vers != TLS1_3_VERSION)
1702 return SSL_R_UNSUPPORTED_PROTOCOL;
1703 return 0;
1704 }
f7f2a01d 1705 check_for_downgrade(s, best_vers, dgrd);
cd998837
MC
1706 s->version = best_vers;
1707 s->method = best_method;
1708 return 0;
1709 }
1710 return SSL_R_UNSUPPORTED_PROTOCOL;
1711 }
1712
1713 /*
1714 * If the supported versions extension isn't present, then the highest
1715 * version we can negotiate is TLSv1.2
1716 */
1717 if (version_cmp(s, client_version, TLS1_3_VERSION) >= 0)
1718 client_version = TLS1_2_VERSION;
1719
1720 /*
1721 * No supported versions extension, so we just use the version supplied in
1722 * the ClientHello.
1723 */
4fa52141
VD
1724 for (vent = table; vent->version != 0; ++vent) {
1725 const SSL_METHOD *method;
1726
1727 if (vent->smeth == NULL ||
1728 version_cmp(s, client_version, vent->version) < 0)
1729 continue;
1730 method = vent->smeth();
1731 if (ssl_method_error(s, method) == 0) {
f7f2a01d 1732 check_for_downgrade(s, vent->version, dgrd);
4fa52141
VD
1733 s->version = vent->version;
1734 s->method = method;
1735 return 0;
1736 }
1737 disabled = 1;
1738 }
1739 return disabled ? SSL_R_UNSUPPORTED_PROTOCOL : SSL_R_VERSION_TOO_LOW;
1740}
1741
1742/*
1743 * ssl_choose_client_version - Choose client (D)TLS version. Called when the
1744 * server HELLO is received to select the final client protocol version and
1745 * the version specific method.
1746 *
1747 * @s: client SSL handle.
1748 * @version: The proposed version from the server's HELLO.
c3043dcd
MC
1749 * @checkdgrd: Whether to check the downgrade sentinels in the server_random
1750 * @al: Where to store any alert value that may be generated
4fa52141
VD
1751 *
1752 * Returns 0 on success or an SSL error reason number on failure.
1753 */
c3043dcd 1754int ssl_choose_client_version(SSL *s, int version, int checkdgrd, int *al)
4fa52141
VD
1755{
1756 const version_info *vent;
1757 const version_info *table;
c3043dcd 1758 int highver = 0;
4fa52141 1759
b97667ce
MC
1760 /* TODO(TLS1.3): Remove this before release */
1761 if (version == TLS1_3_VERSION_DRAFT)
1762 version = TLS1_3_VERSION;
1763
c3043dcd
MC
1764 if (s->hello_retry_request && version != TLS1_3_VERSION) {
1765 *al = SSL_AD_PROTOCOL_VERSION;
1766 return SSL_R_WRONG_SSL_VERSION;
1767 }
1768
4fa52141
VD
1769 switch (s->method->version) {
1770 default:
c3043dcd
MC
1771 if (version != s->version) {
1772 *al = SSL_AD_PROTOCOL_VERSION;
4fa52141 1773 return SSL_R_WRONG_SSL_VERSION;
c3043dcd 1774 }
4fa52141
VD
1775 /*
1776 * If this SSL handle is not from a version flexible method we don't
1777 * (and never did) check min/max, FIPS or Suite B constraints. Hope
1778 * that's OK. It is up to the caller to not choose fixed protocol
1779 * versions they don't want. If not, then easy to fix, just return
1780 * ssl_method_error(s, s->method)
1781 */
4fa52141
VD
1782 return 0;
1783 case TLS_ANY_VERSION:
1784 table = tls_version_table;
1785 break;
1786 case DTLS_ANY_VERSION:
1787 table = dtls_version_table;
1788 break;
1789 }
1790
1791 for (vent = table; vent->version != 0; ++vent) {
1792 const SSL_METHOD *method;
1793 int err;
1794
4fa52141 1795 if (vent->cmeth == NULL)
c3043dcd
MC
1796 continue;
1797
1798 if (highver != 0 && version != vent->version)
1799 continue;
3847d426 1800
4fa52141
VD
1801 method = vent->cmeth();
1802 err = ssl_method_error(s, method);
c3043dcd
MC
1803 if (err != 0) {
1804 if (version == vent->version) {
1805 *al = SSL_AD_PROTOCOL_VERSION;
1806 return err;
1807 }
1808
1809 continue;
1810 }
1811 if (highver == 0)
1812 highver = vent->version;
1813
1814 if (version != vent->version)
1815 continue;
1816
1817#ifndef OPENSSL_NO_TLS13DOWNGRADE
1818 /* Check for downgrades */
1819 if (checkdgrd) {
1820 if (version == TLS1_2_VERSION && highver > version) {
1821 if (memcmp(tls12downgrade,
1822 s->s3->server_random + SSL3_RANDOM_SIZE
1823 - sizeof(tls12downgrade),
1824 sizeof(tls12downgrade)) == 0) {
1825 *al = SSL_AD_ILLEGAL_PARAMETER;
1826 return SSL_R_INAPPROPRIATE_FALLBACK;
1827 }
1828 } else if (!SSL_IS_DTLS(s)
1829 && version < TLS1_2_VERSION
1830 && highver > version) {
1831 if (memcmp(tls11downgrade,
1832 s->s3->server_random + SSL3_RANDOM_SIZE
1833 - sizeof(tls11downgrade),
1834 sizeof(tls11downgrade)) == 0) {
1835 *al = SSL_AD_ILLEGAL_PARAMETER;
1836 return SSL_R_INAPPROPRIATE_FALLBACK;
1837 }
1838 }
1839 }
1840#endif
1841
4fa52141 1842 s->method = method;
ccae4a15 1843 s->version = version;
4fa52141
VD
1844 return 0;
1845 }
1846
c3043dcd 1847 *al = SSL_AD_PROTOCOL_VERSION;
4fa52141
VD
1848 return SSL_R_UNSUPPORTED_PROTOCOL;
1849}
1850
068c358a 1851/*
38a73150 1852 * ssl_get_min_max_version - get minimum and maximum protocol version
068c358a
KR
1853 * @s: The SSL connection
1854 * @min_version: The minimum supported version
1855 * @max_version: The maximum supported version
1856 *
1857 * Work out what version we should be using for the initial ClientHello if the
1858 * version is initially (D)TLS_ANY_VERSION. We apply any explicit SSL_OP_NO_xxx
1859 * options, the MinProtocol and MaxProtocol configuration commands, any Suite B
b53338cb 1860 * constraints and any floor imposed by the security level here,
068c358a 1861 * so we don't advertise the wrong protocol version to only reject the outcome later.
4fa52141 1862 *
0485d540 1863 * Computing the right floor matters. If, e.g., TLS 1.0 and 1.2 are enabled,
4fa52141
VD
1864 * TLS 1.1 is disabled, but the security level, Suite-B and/or MinProtocol
1865 * only allow TLS 1.2, we want to advertise TLS1.2, *not* TLS1.
1866 *
068c358a
KR
1867 * Returns 0 on success or an SSL error reason number on failure. On failure
1868 * min_version and max_version will also be set to 0.
4fa52141 1869 */
38a73150 1870int ssl_get_min_max_version(const SSL *s, int *min_version, int *max_version)
4fa52141
VD
1871{
1872 int version;
1873 int hole;
1874 const SSL_METHOD *single = NULL;
1875 const SSL_METHOD *method;
1876 const version_info *table;
1877 const version_info *vent;
1878
1879 switch (s->method->version) {
1880 default:
1881 /*
1882 * If this SSL handle is not from a version flexible method we don't
1883 * (and never did) check min/max FIPS or Suite B constraints. Hope
1884 * that's OK. It is up to the caller to not choose fixed protocol
1885 * versions they don't want. If not, then easy to fix, just return
1886 * ssl_method_error(s, s->method)
1887 */
068c358a 1888 *min_version = *max_version = s->version;
4fa52141
VD
1889 return 0;
1890 case TLS_ANY_VERSION:
1891 table = tls_version_table;
1892 break;
1893 case DTLS_ANY_VERSION:
1894 table = dtls_version_table;
1895 break;
1896 }
1897
1898 /*
1899 * SSL_OP_NO_X disables all protocols above X *if* there are some protocols
1900 * below X enabled. This is required in order to maintain the "version
1901 * capability" vector contiguous. Any versions with a NULL client method
1902 * (protocol version client is disabled at compile-time) is also a "hole".
1903 *
1904 * Our initial state is hole == 1, version == 0. That is, versions above
1905 * the first version in the method table are disabled (a "hole" above
1906 * the valid protocol entries) and we don't have a selected version yet.
1907 *
1908 * Whenever "hole == 1", and we hit an enabled method, its version becomes
1909 * the selected version, and the method becomes a candidate "single"
1910 * method. We're no longer in a hole, so "hole" becomes 0.
1911 *
1912 * If "hole == 0" and we hit an enabled method, then "single" is cleared,
1913 * as we support a contiguous range of at least two methods. If we hit
1914 * a disabled method, then hole becomes true again, but nothing else
1915 * changes yet, because all the remaining methods may be disabled too.
1916 * If we again hit an enabled method after the new hole, it becomes
1917 * selected, as we start from scratch.
1918 */
068c358a 1919 *min_version = version = 0;
4fa52141
VD
1920 hole = 1;
1921 for (vent = table; vent->version != 0; ++vent) {
1922 /*
1923 * A table entry with a NULL client method is still a hole in the
1924 * "version capability" vector.
1925 */
1926 if (vent->cmeth == NULL) {
1927 hole = 1;
1928 continue;
1929 }
1930 method = vent->cmeth();
1931 if (ssl_method_error(s, method) != 0) {
1932 hole = 1;
1933 } else if (!hole) {
1934 single = NULL;
068c358a 1935 *min_version = method->version;
4fa52141
VD
1936 } else {
1937 version = (single = method)->version;
068c358a 1938 *min_version = version;
4fa52141
VD
1939 hole = 0;
1940 }
1941 }
1942
068c358a
KR
1943 *max_version = version;
1944
4fa52141
VD
1945 /* Fail if everything is disabled */
1946 if (version == 0)
1947 return SSL_R_NO_PROTOCOLS_AVAILABLE;
1948
068c358a
KR
1949 return 0;
1950}
1951
1952/*
1953 * ssl_set_client_hello_version - Work out what version we should be using for
7acb8b64 1954 * the initial ClientHello.legacy_version field.
068c358a
KR
1955 *
1956 * @s: client SSL handle.
1957 *
1958 * Returns 0 on success or an SSL error reason number on failure.
1959 */
1960int ssl_set_client_hello_version(SSL *s)
1961{
3eb2aff4 1962 int ver_min, ver_max, ret;
068c358a 1963
38a73150 1964 ret = ssl_get_min_max_version(s, &ver_min, &ver_max);
068c358a
KR
1965
1966 if (ret != 0)
1967 return ret;
1968
7acb8b64
MC
1969 s->version = ver_max;
1970
1971 /* TLS1.3 always uses TLS1.2 in the legacy_version field */
1972 if (!SSL_IS_DTLS(s) && ver_max > TLS1_2_VERSION)
1973 ver_max = TLS1_2_VERSION;
1974
1975 s->client_version = ver_max;
4fa52141
VD
1976 return 0;
1977}
aff9929b
MC
1978
1979/*
1980 * Checks a list of |groups| to determine if the |group_id| is in it. If it is
1981 * and |checkallow| is 1 then additionally check if the group is allowed to be
1982 * used. Returns 1 if the group is in the list (and allowed if |checkallow| is
1983 * 1) or 0 otherwise.
1984 */
deb2d5e7 1985#ifndef OPENSSL_NO_EC
aff9929b
MC
1986int check_in_list(SSL *s, unsigned int group_id, const unsigned char *groups,
1987 size_t num_groups, int checkallow)
1988{
1989 size_t i;
1990
1991 if (groups == NULL || num_groups == 0)
1992 return 0;
1993
1994 for (i = 0; i < num_groups; i++, groups += 2) {
6af87546 1995 if (group_id == GET_GROUP_ID(groups, 0)
aff9929b
MC
1996 && (!checkallow
1997 || tls_curve_allowed(s, groups, SSL_SECOP_CURVE_CHECK))) {
0acee504 1998 return 1;
aff9929b
MC
1999 }
2000 }
2001
0acee504 2002 return 0;
aff9929b 2003}
deb2d5e7 2004#endif
11c67eea
MC
2005
2006/* Replace ClientHello1 in the transcript hash with a synthetic message */
2007int create_synthetic_message_hash(SSL *s)
2008{
2009 unsigned char hashval[EVP_MAX_MD_SIZE];
2010 size_t hashlen = 0;
635b7d3f
MC
2011 unsigned char msghdr[SSL3_HM_HEADER_LENGTH];
2012
2013 memset(msghdr, 0, sizeof(msghdr));
11c67eea
MC
2014
2015 /* Get the hash of the initial ClientHello */
2016 if (!ssl3_digest_cached_records(s, 0)
2017 || !ssl_handshake_hash(s, hashval, sizeof(hashval), &hashlen)) {
2018 SSLerr(SSL_F_CREATE_SYNTHETIC_MESSAGE_HASH, ERR_R_INTERNAL_ERROR);
2019 return 0;
2020 }
2021
2022 /* Reinitialise the transcript hash */
2023 if (!ssl3_init_finished_mac(s))
2024 return 0;
2025
2026 /* Inject the synthetic message_hash message */
635b7d3f 2027 msghdr[0] = SSL3_MT_MESSAGE_HASH;
11c67eea
MC
2028 msghdr[SSL3_HM_HEADER_LENGTH - 1] = hashlen;
2029 if (!ssl3_finish_mac(s, msghdr, SSL3_HM_HEADER_LENGTH)
2030 || !ssl3_finish_mac(s, hashval, hashlen)) {
2031 SSLerr(SSL_F_CREATE_SYNTHETIC_MESSAGE_HASH, ERR_R_INTERNAL_ERROR);
2032 return 0;
2033 }
2034
2035 return 1;
2036}
5d6cca05
DSH
2037
2038static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
2039{
2040 return X509_NAME_cmp(*a, *b);
2041}
2042
2043int parse_ca_names(SSL *s, PACKET *pkt, int *al)
2044{
2045 STACK_OF(X509_NAME) *ca_sk = sk_X509_NAME_new(ca_dn_cmp);
2046 X509_NAME *xn = NULL;
2047 PACKET cadns;
2048
2049 if (ca_sk == NULL) {
2050 SSLerr(SSL_F_PARSE_CA_NAMES, ERR_R_MALLOC_FAILURE);
2051 goto decerr;
2052 }
2053 /* get the CA RDNs */
2054 if (!PACKET_get_length_prefixed_2(pkt, &cadns)) {
2055 *al = SSL_AD_DECODE_ERROR;
2056 SSLerr(SSL_F_PARSE_CA_NAMES, SSL_R_LENGTH_MISMATCH);
2057 goto decerr;
2058 }
2059
2060 while (PACKET_remaining(&cadns)) {
2061 const unsigned char *namestart, *namebytes;
2062 unsigned int name_len;
2063
2064 if (!PACKET_get_net_2(&cadns, &name_len)
2065 || !PACKET_get_bytes(&cadns, &namebytes, name_len)) {
2066 SSLerr(SSL_F_PARSE_CA_NAMES, SSL_R_LENGTH_MISMATCH);
2067 goto decerr;
2068 }
2069
2070 namestart = namebytes;
2071 if ((xn = d2i_X509_NAME(NULL, &namebytes, name_len)) == NULL) {
2072 SSLerr(SSL_F_PARSE_CA_NAMES, ERR_R_ASN1_LIB);
2073 goto decerr;
2074 }
2075 if (namebytes != (namestart + name_len)) {
2076 SSLerr(SSL_F_PARSE_CA_NAMES, SSL_R_CA_DN_LENGTH_MISMATCH);
2077 goto decerr;
2078 }
2079
2080 if (!sk_X509_NAME_push(ca_sk, xn)) {
2081 SSLerr(SSL_F_PARSE_CA_NAMES, ERR_R_MALLOC_FAILURE);
2082 *al = SSL_AD_INTERNAL_ERROR;
2083 goto err;
2084 }
2085 xn = NULL;
2086 }
2087
fa7c2637
DSH
2088 sk_X509_NAME_pop_free(s->s3->tmp.peer_ca_names, X509_NAME_free);
2089 s->s3->tmp.peer_ca_names = ca_sk;
5d6cca05
DSH
2090
2091 return 1;
2092
2093 decerr:
2094 *al = SSL_AD_DECODE_ERROR;
2095 err:
2096 sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
2097 X509_NAME_free(xn);
2098 return 0;
2099}
2100
2101int construct_ca_names(SSL *s, WPACKET *pkt)
2102{
9784ec04 2103 const STACK_OF(X509_NAME) *ca_sk = SSL_get0_CA_list(s);
5d6cca05
DSH
2104
2105 /* Start sub-packet for client CA list */
2106 if (!WPACKET_start_sub_packet_u16(pkt))
2107 return 0;
2108
2109 if (ca_sk != NULL) {
2110 int i;
2111
2112 for (i = 0; i < sk_X509_NAME_num(ca_sk); i++) {
2113 unsigned char *namebytes;
2114 X509_NAME *name = sk_X509_NAME_value(ca_sk, i);
2115 int namelen;
2116
2117 if (name == NULL
2118 || (namelen = i2d_X509_NAME(name, NULL)) < 0
2119 || !WPACKET_sub_allocate_bytes_u16(pkt, namelen,
2120 &namebytes)
2121 || i2d_X509_NAME(name, &namebytes) != namelen) {
2122 return 0;
2123 }
2124 }
2125 }
2126
2127 if (!WPACKET_close(pkt))
2128 return 0;
2129
2130 return 1;
2131}