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