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