1 /*
2 * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved.
3 * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
4 *
5 * Licensed under the Apache License 2.0 (the "License"). You may not use
6 * this file except in compliance with the License. You can obtain a copy
7 * in the file LICENSE in the source distribution or at
8 * https://www.openssl.org/source/license.html
9 */
10
11 #include <limits.h>
12 #include <string.h>
13 #include <stdio.h>
14 #include "../ssl_local.h"
15 #include "statem_local.h"
16 #include "internal/cryptlib.h"
17 #include <openssl/buffer.h>
18 #include <openssl/objects.h>
19 #include <openssl/evp.h>
20 #include <openssl/rsa.h>
21 #include <openssl/x509.h>
22 #include <openssl/trace.h>
23
24 /*
25 * Map error codes to TLS/SSL alart types.
26 */
27 typedef struct x509err2alert_st {
28 int x509err;
29 int alert;
30 } X509ERR2ALERT;
31
32 /* Fixed value used in the ServerHello random field to identify an HRR */
33 const unsigned char hrrrandom[] = {
34 0xcf, 0x21, 0xad, 0x74, 0xe5, 0x9a, 0x61, 0x11, 0xbe, 0x1d, 0x8c, 0x02,
35 0x1e, 0x65, 0xb8, 0x91, 0xc2, 0xa2, 0x11, 0x16, 0x7a, 0xbb, 0x8c, 0x5e,
36 0x07, 0x9e, 0x09, 0xe2, 0xc8, 0xa8, 0x33, 0x9c
37 };
38
39 /*
40 * send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or
41 * SSL3_RT_CHANGE_CIPHER_SPEC)
42 */
ssl3_do_write(SSL * s,int type)43 int ssl3_do_write(SSL *s, int type)
44 {
45 int ret;
46 size_t written = 0;
47
48 #ifndef OPENSSL_NO_QUIC
49 if (SSL_IS_QUIC(s)) {
50 if (type == SSL3_RT_HANDSHAKE) {
51 ret = s->quic_method->add_handshake_data(s, s->quic_write_level,
52 (const uint8_t*)&s->init_buf->data[s->init_off],
53 s->init_num);
54 if (!ret) {
55 ret = -1;
56 /* QUIC can't sent anything out sice the above failed */
57 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
58 } else {
59 written = s->init_num;
60 }
61 } else {
62 /* QUIC doesn't use ChangeCipherSpec */
63 ret = -1;
64 ERR_raise(ERR_LIB_SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
65 }
66 } else
67 #endif
68 ret = ssl3_write_bytes(s, type, &s->init_buf->data[s->init_off],
69 s->init_num, &written);
70
71 if (ret <= 0)
72 return -1;
73 if (type == SSL3_RT_HANDSHAKE)
74 /*
75 * should not be done for 'Hello Request's, but in that case we'll
76 * ignore the result anyway
77 * TLS1.3 KeyUpdate and NewSessionTicket do not need to be added
78 */
79 if (!SSL_IS_TLS13(s) || (s->statem.hand_state != TLS_ST_SW_SESSION_TICKET
80 && s->statem.hand_state != TLS_ST_CW_KEY_UPDATE
81 && s->statem.hand_state != TLS_ST_SW_KEY_UPDATE))
82 if (!ssl3_finish_mac(s,
83 (unsigned char *)&s->init_buf->data[s->init_off],
84 written))
85 return -1;
86 if (written == s->init_num) {
87 if (s->msg_callback)
88 s->msg_callback(1, s->version, type, s->init_buf->data,
89 (size_t)(s->init_off + s->init_num), s,
90 s->msg_callback_arg);
91 return 1;
92 }
93 s->init_off += written;
94 s->init_num -= written;
95 return 0;
96 }
97
tls_close_construct_packet(SSL * s,WPACKET * pkt,int htype)98 int tls_close_construct_packet(SSL *s, WPACKET *pkt, int htype)
99 {
100 size_t msglen;
101
102 if ((htype != SSL3_MT_CHANGE_CIPHER_SPEC && !WPACKET_close(pkt))
103 || !WPACKET_get_length(pkt, &msglen)
104 || msglen > INT_MAX)
105 return 0;
106 s->init_num = (int)msglen;
107 s->init_off = 0;
108
109 return 1;
110 }
111
tls_setup_handshake(SSL * s)112 int tls_setup_handshake(SSL *s)
113 {
114 int ver_min, ver_max, ok;
115
116 if (!ssl3_init_finished_mac(s)) {
117 /* SSLfatal() already called */
118 return 0;
119 }
120
121 /* Reset any extension flags */
122 memset(s->ext.extflags, 0, sizeof(s->ext.extflags));
123
124 if (ssl_get_min_max_version(s, &ver_min, &ver_max, NULL) != 0) {
125 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_NO_PROTOCOLS_AVAILABLE);
126 return 0;
127 }
128
129 /* Sanity check that we have MD5-SHA1 if we need it */
130 if (s->ctx->ssl_digest_methods[SSL_MD_MD5_SHA1_IDX] == NULL) {
131 int md5sha1_needed = 0;
132
133 /* We don't have MD5-SHA1 - do we need it? */
134 if (SSL_IS_DTLS(s)) {
135 if (DTLS_VERSION_LE(ver_max, DTLS1_VERSION))
136 md5sha1_needed = 1;
137 } else {
138 if (ver_max <= TLS1_1_VERSION)
139 md5sha1_needed = 1;
140 }
141 if (md5sha1_needed) {
142 SSLfatal_data(s, SSL_AD_HANDSHAKE_FAILURE,
143 SSL_R_NO_SUITABLE_DIGEST_ALGORITHM,
144 "The max supported SSL/TLS version needs the"
145 " MD5-SHA1 digest but it is not available"
146 " in the loaded providers. Use (D)TLSv1.2 or"
147 " above, or load different providers");
148 return 0;
149 }
150
151 ok = 1;
152 /* Don't allow TLSv1.1 or below to be negotiated */
153 if (SSL_IS_DTLS(s)) {
154 if (DTLS_VERSION_LT(ver_min, DTLS1_2_VERSION))
155 ok = SSL_set_min_proto_version(s, DTLS1_2_VERSION);
156 } else {
157 if (ver_min < TLS1_2_VERSION)
158 ok = SSL_set_min_proto_version(s, TLS1_2_VERSION);
159 }
160 if (!ok) {
161 /* Shouldn't happen */
162 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, ERR_R_INTERNAL_ERROR);
163 return 0;
164 }
165 }
166
167 ok = 0;
168 if (s->server) {
169 STACK_OF(SSL_CIPHER) *ciphers = SSL_get_ciphers(s);
170 int i;
171
172 /*
173 * Sanity check that the maximum version we accept has ciphers
174 * enabled. For clients we do this check during construction of the
175 * ClientHello.
176 */
177 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
178 const SSL_CIPHER *c = sk_SSL_CIPHER_value(ciphers, i);
179
180 if (SSL_IS_DTLS(s)) {
181 if (DTLS_VERSION_GE(ver_max, c->min_dtls) &&
182 DTLS_VERSION_LE(ver_max, c->max_dtls))
183 ok = 1;
184 } else if (ver_max >= c->min_tls && ver_max <= c->max_tls) {
185 ok = 1;
186 }
187 if (ok)
188 break;
189 }
190 if (!ok) {
191 SSLfatal_data(s, SSL_AD_HANDSHAKE_FAILURE,
192 SSL_R_NO_CIPHERS_AVAILABLE,
193 "No ciphers enabled for max supported "
194 "SSL/TLS version");
195 return 0;
196 }
197 if (SSL_IS_FIRST_HANDSHAKE(s)) {
198 /* N.B. s->session_ctx == s->ctx here */
199 ssl_tsan_counter(s->session_ctx, &s->session_ctx->stats.sess_accept);
200 } else {
201 /* N.B. s->ctx may not equal s->session_ctx */
202 ssl_tsan_counter(s->ctx, &s->ctx->stats.sess_accept_renegotiate);
203
204 s->s3.tmp.cert_request = 0;
205 }
206 } else {
207 if (SSL_IS_FIRST_HANDSHAKE(s))
208 ssl_tsan_counter(s->session_ctx, &s->session_ctx->stats.sess_connect);
209 else
210 ssl_tsan_counter(s->session_ctx,
211 &s->session_ctx->stats.sess_connect_renegotiate);
212
213 /* mark client_random uninitialized */
214 memset(s->s3.client_random, 0, sizeof(s->s3.client_random));
215 s->hit = 0;
216
217 s->s3.tmp.cert_req = 0;
218
219 if (SSL_IS_DTLS(s))
220 s->statem.use_timer = 1;
221 }
222
223 return 1;
224 }
225
226 /*
227 * Size of the to-be-signed TLS13 data, without the hash size itself:
228 * 64 bytes of value 32, 33 context bytes, 1 byte separator
229 */
230 #define TLS13_TBS_START_SIZE 64
231 #define TLS13_TBS_PREAMBLE_SIZE (TLS13_TBS_START_SIZE + 33 + 1)
232
get_cert_verify_tbs_data(SSL * s,unsigned char * tls13tbs,void ** hdata,size_t * hdatalen)233 static int get_cert_verify_tbs_data(SSL *s, unsigned char *tls13tbs,
234 void **hdata, size_t *hdatalen)
235 {
236 #ifdef CHARSET_EBCDIC
237 static const char servercontext[] = { 0x54, 0x4c, 0x53, 0x20, 0x31, 0x2e,
238 0x33, 0x2c, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x43, 0x65,
239 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x56, 0x65, 0x72,
240 0x69, 0x66, 0x79, 0x00 };
241 static const char clientcontext[] = { 0x54, 0x4c, 0x53, 0x20, 0x31, 0x2e,
242 0x33, 0x2c, 0x20, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x20, 0x43, 0x65,
243 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x56, 0x65, 0x72,
244 0x69, 0x66, 0x79, 0x00 };
245 #else
246 static const char servercontext[] = "TLS 1.3, server CertificateVerify";
247 static const char clientcontext[] = "TLS 1.3, client CertificateVerify";
248 #endif
249 if (SSL_IS_TLS13(s)) {
250 size_t hashlen;
251
252 /* Set the first 64 bytes of to-be-signed data to octet 32 */
253 memset(tls13tbs, 32, TLS13_TBS_START_SIZE);
254 /* This copies the 33 bytes of context plus the 0 separator byte */
255 if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
256 || s->statem.hand_state == TLS_ST_SW_CERT_VRFY)
257 strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, servercontext);
258 else
259 strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, clientcontext);
260
261 /*
262 * If we're currently reading then we need to use the saved handshake
263 * hash value. We can't use the current handshake hash state because
264 * that includes the CertVerify itself.
265 */
266 if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
267 || s->statem.hand_state == TLS_ST_SR_CERT_VRFY) {
268 memcpy(tls13tbs + TLS13_TBS_PREAMBLE_SIZE, s->cert_verify_hash,
269 s->cert_verify_hash_len);
270 hashlen = s->cert_verify_hash_len;
271 } else if (!ssl_handshake_hash(s, tls13tbs + TLS13_TBS_PREAMBLE_SIZE,
272 EVP_MAX_MD_SIZE, &hashlen)) {
273 /* SSLfatal() already called */
274 return 0;
275 }
276
277 *hdata = tls13tbs;
278 *hdatalen = TLS13_TBS_PREAMBLE_SIZE + hashlen;
279 } else {
280 size_t retlen;
281 long retlen_l;
282
283 retlen = retlen_l = BIO_get_mem_data(s->s3.handshake_buffer, hdata);
284 if (retlen_l <= 0) {
285 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
286 return 0;
287 }
288 *hdatalen = retlen;
289 }
290
291 return 1;
292 }
293
tls_construct_cert_verify(SSL * s,WPACKET * pkt)294 int tls_construct_cert_verify(SSL *s, WPACKET *pkt)
295 {
296 EVP_PKEY *pkey = NULL;
297 const EVP_MD *md = NULL;
298 EVP_MD_CTX *mctx = NULL;
299 EVP_PKEY_CTX *pctx = NULL;
300 size_t hdatalen = 0, siglen = 0;
301 void *hdata;
302 unsigned char *sig = NULL;
303 unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
304 const SIGALG_LOOKUP *lu = s->s3.tmp.sigalg;
305
306 if (lu == NULL || s->s3.tmp.cert == NULL) {
307 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
308 goto err;
309 }
310 pkey = s->s3.tmp.cert->privatekey;
311
312 if (pkey == NULL || !tls1_lookup_md(s->ctx, lu, &md)) {
313 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
314 goto err;
315 }
316
317 mctx = EVP_MD_CTX_new();
318 if (mctx == NULL) {
319 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
320 goto err;
321 }
322
323 /* Get the data to be signed */
324 if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
325 /* SSLfatal() already called */
326 goto err;
327 }
328
329 if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
330 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
331 goto err;
332 }
333
334 if (EVP_DigestSignInit_ex(mctx, &pctx,
335 md == NULL ? NULL : EVP_MD_get0_name(md),
336 s->ctx->libctx, s->ctx->propq, pkey,
337 NULL) <= 0) {
338 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
339 goto err;
340 }
341
342 if (lu->sig == EVP_PKEY_RSA_PSS) {
343 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
344 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
345 RSA_PSS_SALTLEN_DIGEST) <= 0) {
346 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
347 goto err;
348 }
349 }
350 if (s->version == SSL3_VERSION) {
351 /*
352 * Here we use EVP_DigestSignUpdate followed by EVP_DigestSignFinal
353 * in order to add the EVP_CTRL_SSL3_MASTER_SECRET call between them.
354 */
355 if (EVP_DigestSignUpdate(mctx, hdata, hdatalen) <= 0
356 || EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
357 (int)s->session->master_key_length,
358 s->session->master_key) <= 0
359 || EVP_DigestSignFinal(mctx, NULL, &siglen) <= 0) {
360
361 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
362 goto err;
363 }
364 sig = OPENSSL_malloc(siglen);
365 if (sig == NULL
366 || EVP_DigestSignFinal(mctx, sig, &siglen) <= 0) {
367 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
368 goto err;
369 }
370 } else {
371 /*
372 * Here we *must* use EVP_DigestSign() because Ed25519/Ed448 does not
373 * support streaming via EVP_DigestSignUpdate/EVP_DigestSignFinal
374 */
375 if (EVP_DigestSign(mctx, NULL, &siglen, hdata, hdatalen) <= 0) {
376 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
377 goto err;
378 }
379 sig = OPENSSL_malloc(siglen);
380 if (sig == NULL
381 || EVP_DigestSign(mctx, sig, &siglen, hdata, hdatalen) <= 0) {
382 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
383 goto err;
384 }
385 }
386
387 #ifndef OPENSSL_NO_GOST
388 {
389 int pktype = lu->sig;
390
391 if (pktype == NID_id_GostR3410_2001
392 || pktype == NID_id_GostR3410_2012_256
393 || pktype == NID_id_GostR3410_2012_512)
394 BUF_reverse(sig, NULL, siglen);
395 }
396 #endif
397
398 if (!WPACKET_sub_memcpy_u16(pkt, sig, siglen)) {
399 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
400 goto err;
401 }
402
403 /* Digest cached records and discard handshake buffer */
404 if (!ssl3_digest_cached_records(s, 0)) {
405 /* SSLfatal() already called */
406 goto err;
407 }
408
409 OPENSSL_free(sig);
410 EVP_MD_CTX_free(mctx);
411 return 1;
412 err:
413 OPENSSL_free(sig);
414 EVP_MD_CTX_free(mctx);
415 return 0;
416 }
417
tls_process_cert_verify(SSL * s,PACKET * pkt)418 MSG_PROCESS_RETURN tls_process_cert_verify(SSL *s, PACKET *pkt)
419 {
420 EVP_PKEY *pkey = NULL;
421 const unsigned char *data;
422 #ifndef OPENSSL_NO_GOST
423 unsigned char *gost_data = NULL;
424 #endif
425 MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
426 int j;
427 unsigned int len;
428 X509 *peer;
429 const EVP_MD *md = NULL;
430 size_t hdatalen = 0;
431 void *hdata;
432 unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
433 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
434 EVP_PKEY_CTX *pctx = NULL;
435
436 if (mctx == NULL) {
437 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
438 goto err;
439 }
440
441 peer = s->session->peer;
442 pkey = X509_get0_pubkey(peer);
443 if (pkey == NULL) {
444 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
445 goto err;
446 }
447
448 if (ssl_cert_lookup_by_pkey(pkey, NULL) == NULL) {
449 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
450 SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
451 goto err;
452 }
453
454 if (SSL_USE_SIGALGS(s)) {
455 unsigned int sigalg;
456
457 if (!PACKET_get_net_2(pkt, &sigalg)) {
458 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_PACKET);
459 goto err;
460 }
461 if (tls12_check_peer_sigalg(s, sigalg, pkey) <= 0) {
462 /* SSLfatal() already called */
463 goto err;
464 }
465 } else if (!tls1_set_peer_legacy_sigalg(s, pkey)) {
466 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
467 SSL_R_LEGACY_SIGALG_DISALLOWED_OR_UNSUPPORTED);
468 goto err;
469 }
470
471 if (!tls1_lookup_md(s->ctx, s->s3.tmp.peer_sigalg, &md)) {
472 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
473 goto err;
474 }
475
476 if (SSL_USE_SIGALGS(s))
477 OSSL_TRACE1(TLS, "USING TLSv1.2 HASH %s\n",
478 md == NULL ? "n/a" : EVP_MD_get0_name(md));
479
480 /* Check for broken implementations of GOST ciphersuites */
481 /*
482 * If key is GOST and len is exactly 64 or 128, it is signature without
483 * length field (CryptoPro implementations at least till TLS 1.2)
484 */
485 #ifndef OPENSSL_NO_GOST
486 if (!SSL_USE_SIGALGS(s)
487 && ((PACKET_remaining(pkt) == 64
488 && (EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2001
489 || EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2012_256))
490 || (PACKET_remaining(pkt) == 128
491 && EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2012_512))) {
492 len = PACKET_remaining(pkt);
493 } else
494 #endif
495 if (!PACKET_get_net_2(pkt, &len)) {
496 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
497 goto err;
498 }
499
500 if (!PACKET_get_bytes(pkt, &data, len)) {
501 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
502 goto err;
503 }
504
505 if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
506 /* SSLfatal() already called */
507 goto err;
508 }
509
510 OSSL_TRACE1(TLS, "Using client verify alg %s\n",
511 md == NULL ? "n/a" : EVP_MD_get0_name(md));
512
513 if (EVP_DigestVerifyInit_ex(mctx, &pctx,
514 md == NULL ? NULL : EVP_MD_get0_name(md),
515 s->ctx->libctx, s->ctx->propq, pkey,
516 NULL) <= 0) {
517 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
518 goto err;
519 }
520 #ifndef OPENSSL_NO_GOST
521 {
522 int pktype = EVP_PKEY_get_id(pkey);
523 if (pktype == NID_id_GostR3410_2001
524 || pktype == NID_id_GostR3410_2012_256
525 || pktype == NID_id_GostR3410_2012_512) {
526 if ((gost_data = OPENSSL_malloc(len)) == NULL) {
527 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
528 goto err;
529 }
530 BUF_reverse(gost_data, data, len);
531 data = gost_data;
532 }
533 }
534 #endif
535
536 if (SSL_USE_PSS(s)) {
537 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
538 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
539 RSA_PSS_SALTLEN_DIGEST) <= 0) {
540 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
541 goto err;
542 }
543 }
544 if (s->version == SSL3_VERSION) {
545 if (EVP_DigestVerifyUpdate(mctx, hdata, hdatalen) <= 0
546 || EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
547 (int)s->session->master_key_length,
548 s->session->master_key) <= 0) {
549 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
550 goto err;
551 }
552 if (EVP_DigestVerifyFinal(mctx, data, len) <= 0) {
553 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_BAD_SIGNATURE);
554 goto err;
555 }
556 } else {
557 j = EVP_DigestVerify(mctx, data, len, hdata, hdatalen);
558 if (j <= 0) {
559 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_BAD_SIGNATURE);
560 goto err;
561 }
562 }
563
564 /*
565 * In TLSv1.3 on the client side we make sure we prepare the client
566 * certificate after the CertVerify instead of when we get the
567 * CertificateRequest. This is because in TLSv1.3 the CertificateRequest
568 * comes *before* the Certificate message. In TLSv1.2 it comes after. We
569 * want to make sure that SSL_get1_peer_certificate() will return the actual
570 * server certificate from the client_cert_cb callback.
571 */
572 if (!s->server && SSL_IS_TLS13(s) && s->s3.tmp.cert_req == 1)
573 ret = MSG_PROCESS_CONTINUE_PROCESSING;
574 else
575 ret = MSG_PROCESS_CONTINUE_READING;
576 err:
577 BIO_free(s->s3.handshake_buffer);
578 s->s3.handshake_buffer = NULL;
579 EVP_MD_CTX_free(mctx);
580 #ifndef OPENSSL_NO_GOST
581 OPENSSL_free(gost_data);
582 #endif
583 return ret;
584 }
585
tls_construct_finished(SSL * s,WPACKET * pkt)586 int tls_construct_finished(SSL *s, WPACKET *pkt)
587 {
588 size_t finish_md_len;
589 const char *sender;
590 size_t slen;
591
592 /* This is a real handshake so make sure we clean it up at the end */
593 if (!s->server && s->post_handshake_auth != SSL_PHA_REQUESTED)
594 s->statem.cleanuphand = 1;
595
596 /*
597 * We only change the keys if we didn't already do this when we sent the
598 * client certificate
599 */
600 if (SSL_IS_TLS13(s)
601 && !s->server
602 && s->s3.tmp.cert_req == 0
603 && (!s->method->ssl3_enc->change_cipher_state(s,
604 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE))) {;
605 /* SSLfatal() already called */
606 return 0;
607 }
608
609 if (s->server) {
610 sender = s->method->ssl3_enc->server_finished_label;
611 slen = s->method->ssl3_enc->server_finished_label_len;
612 } else {
613 sender = s->method->ssl3_enc->client_finished_label;
614 slen = s->method->ssl3_enc->client_finished_label_len;
615 }
616
617 finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
618 sender, slen,
619 s->s3.tmp.finish_md);
620 if (finish_md_len == 0) {
621 /* SSLfatal() already called */
622 return 0;
623 }
624
625 s->s3.tmp.finish_md_len = finish_md_len;
626
627 if (!WPACKET_memcpy(pkt, s->s3.tmp.finish_md, finish_md_len)) {
628 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
629 return 0;
630 }
631
632 /*
633 * Log the master secret, if logging is enabled. We don't log it for
634 * TLSv1.3: there's a different key schedule for that.
635 */
636 if (!SSL_IS_TLS13(s) && !ssl_log_secret(s, MASTER_SECRET_LABEL,
637 s->session->master_key,
638 s->session->master_key_length)) {
639 /* SSLfatal() already called */
640 return 0;
641 }
642
643 /*
644 * Copy the finished so we can use it for renegotiation checks
645 */
646 if (!ossl_assert(finish_md_len <= EVP_MAX_MD_SIZE)) {
647 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
648 return 0;
649 }
650 if (!s->server) {
651 memcpy(s->s3.previous_client_finished, s->s3.tmp.finish_md,
652 finish_md_len);
653 s->s3.previous_client_finished_len = finish_md_len;
654 } else {
655 memcpy(s->s3.previous_server_finished, s->s3.tmp.finish_md,
656 finish_md_len);
657 s->s3.previous_server_finished_len = finish_md_len;
658 }
659
660 return 1;
661 }
662
tls_construct_key_update(SSL * s,WPACKET * pkt)663 int tls_construct_key_update(SSL *s, WPACKET *pkt)
664 {
665 #ifndef OPENSSL_NO_QUIC
666 if (SSL_is_quic(s)) {
667 /* TLS KeyUpdate is not used for QUIC, so this is an error. */
668 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
669 return 0;
670 }
671 #endif
672 if (!WPACKET_put_bytes_u8(pkt, s->key_update)) {
673 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
674 return 0;
675 }
676
677 s->key_update = SSL_KEY_UPDATE_NONE;
678 return 1;
679 }
680
tls_process_key_update(SSL * s,PACKET * pkt)681 MSG_PROCESS_RETURN tls_process_key_update(SSL *s, PACKET *pkt)
682 {
683 unsigned int updatetype;
684
685 /*
686 * A KeyUpdate message signals a key change so the end of the message must
687 * be on a record boundary.
688 */
689 if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
690 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
691 return MSG_PROCESS_ERROR;
692 }
693
694 #ifndef OPENSSL_NO_QUIC
695 if (SSL_is_quic(s)) {
696 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
697 return MSG_PROCESS_ERROR;
698 }
699 #endif
700
701 if (!PACKET_get_1(pkt, &updatetype)
702 || PACKET_remaining(pkt) != 0) {
703 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_KEY_UPDATE);
704 return MSG_PROCESS_ERROR;
705 }
706
707 /*
708 * There are only two defined key update types. Fail if we get a value we
709 * didn't recognise.
710 */
711 if (updatetype != SSL_KEY_UPDATE_NOT_REQUESTED
712 && updatetype != SSL_KEY_UPDATE_REQUESTED) {
713 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_KEY_UPDATE);
714 return MSG_PROCESS_ERROR;
715 }
716
717 /*
718 * If we get a request for us to update our sending keys too then, we need
719 * to additionally send a KeyUpdate message. However that message should
720 * not also request an update (otherwise we get into an infinite loop).
721 */
722 if (updatetype == SSL_KEY_UPDATE_REQUESTED)
723 s->key_update = SSL_KEY_UPDATE_NOT_REQUESTED;
724
725 if (!tls13_update_key(s, 0)) {
726 /* SSLfatal() already called */
727 return MSG_PROCESS_ERROR;
728 }
729
730 return MSG_PROCESS_FINISHED_READING;
731 }
732
733 /*
734 * ssl3_take_mac calculates the Finished MAC for the handshakes messages seen
735 * to far.
736 */
ssl3_take_mac(SSL * s)737 int ssl3_take_mac(SSL *s)
738 {
739 const char *sender;
740 size_t slen;
741
742 if (!s->server) {
743 sender = s->method->ssl3_enc->server_finished_label;
744 slen = s->method->ssl3_enc->server_finished_label_len;
745 } else {
746 sender = s->method->ssl3_enc->client_finished_label;
747 slen = s->method->ssl3_enc->client_finished_label_len;
748 }
749
750 s->s3.tmp.peer_finish_md_len =
751 s->method->ssl3_enc->final_finish_mac(s, sender, slen,
752 s->s3.tmp.peer_finish_md);
753
754 if (s->s3.tmp.peer_finish_md_len == 0) {
755 /* SSLfatal() already called */
756 return 0;
757 }
758
759 return 1;
760 }
761
tls_process_change_cipher_spec(SSL * s,PACKET * pkt)762 MSG_PROCESS_RETURN tls_process_change_cipher_spec(SSL *s, PACKET *pkt)
763 {
764 size_t remain;
765
766 remain = PACKET_remaining(pkt);
767 /*
768 * 'Change Cipher Spec' is just a single byte, which should already have
769 * been consumed by ssl_get_message() so there should be no bytes left,
770 * unless we're using DTLS1_BAD_VER, which has an extra 2 bytes
771 */
772 if (SSL_IS_DTLS(s)) {
773 if ((s->version == DTLS1_BAD_VER
774 && remain != DTLS1_CCS_HEADER_LENGTH + 1)
775 || (s->version != DTLS1_BAD_VER
776 && remain != DTLS1_CCS_HEADER_LENGTH - 1)) {
777 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_CHANGE_CIPHER_SPEC);
778 return MSG_PROCESS_ERROR;
779 }
780 } else {
781 if (remain != 0) {
782 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_CHANGE_CIPHER_SPEC);
783 return MSG_PROCESS_ERROR;
784 }
785 }
786
787 /* Check we have a cipher to change to */
788 if (s->s3.tmp.new_cipher == NULL) {
789 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
790 return MSG_PROCESS_ERROR;
791 }
792
793 s->s3.change_cipher_spec = 1;
794 if (!ssl3_do_change_cipher_spec(s)) {
795 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
796 return MSG_PROCESS_ERROR;
797 }
798
799 if (SSL_IS_DTLS(s)) {
800 dtls1_reset_seq_numbers(s, SSL3_CC_READ);
801
802 if (s->version == DTLS1_BAD_VER)
803 s->d1->handshake_read_seq++;
804
805 #ifndef OPENSSL_NO_SCTP
806 /*
807 * Remember that a CCS has been received, so that an old key of
808 * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
809 * SCTP is used
810 */
811 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
812 #endif
813 }
814
815 return MSG_PROCESS_CONTINUE_READING;
816 }
817
tls_process_finished(SSL * s,PACKET * pkt)818 MSG_PROCESS_RETURN tls_process_finished(SSL *s, PACKET *pkt)
819 {
820 size_t md_len;
821
822
823 /* This is a real handshake so make sure we clean it up at the end */
824 if (s->server) {
825 /*
826 * To get this far we must have read encrypted data from the client. We
827 * no longer tolerate unencrypted alerts. This value is ignored if less
828 * than TLSv1.3
829 */
830 s->statem.enc_read_state = ENC_READ_STATE_VALID;
831 if (s->post_handshake_auth != SSL_PHA_REQUESTED)
832 s->statem.cleanuphand = 1;
833 if (SSL_IS_TLS13(s) && !tls13_save_handshake_digest_for_pha(s)) {
834 /* SSLfatal() already called */
835 return MSG_PROCESS_ERROR;
836 }
837 }
838
839 /*
840 * In TLSv1.3 a Finished message signals a key change so the end of the
841 * message must be on a record boundary.
842 */
843 if (SSL_IS_TLS13(s) && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
844 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
845 return MSG_PROCESS_ERROR;
846 }
847
848 /* If this occurs, we have missed a message */
849 if (!SSL_IS_TLS13(s) && !s->s3.change_cipher_spec) {
850 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_GOT_A_FIN_BEFORE_A_CCS);
851 return MSG_PROCESS_ERROR;
852 }
853 s->s3.change_cipher_spec = 0;
854
855 md_len = s->s3.tmp.peer_finish_md_len;
856
857 if (md_len != PACKET_remaining(pkt)) {
858 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_DIGEST_LENGTH);
859 return MSG_PROCESS_ERROR;
860 }
861
862 if (CRYPTO_memcmp(PACKET_data(pkt), s->s3.tmp.peer_finish_md,
863 md_len) != 0) {
864 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DIGEST_CHECK_FAILED);
865 return MSG_PROCESS_ERROR;
866 }
867
868 /*
869 * Copy the finished so we can use it for renegotiation checks
870 */
871 if (!ossl_assert(md_len <= EVP_MAX_MD_SIZE)) {
872 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
873 return MSG_PROCESS_ERROR;
874 }
875 if (s->server) {
876 memcpy(s->s3.previous_client_finished, s->s3.tmp.peer_finish_md,
877 md_len);
878 s->s3.previous_client_finished_len = md_len;
879 } else {
880 memcpy(s->s3.previous_server_finished, s->s3.tmp.peer_finish_md,
881 md_len);
882 s->s3.previous_server_finished_len = md_len;
883 }
884
885 /*
886 * In TLS1.3 we also have to change cipher state and do any final processing
887 * of the initial server flight (if we are a client)
888 */
889 if (SSL_IS_TLS13(s)) {
890 if (s->server) {
891 if (s->post_handshake_auth != SSL_PHA_REQUESTED &&
892 !s->method->ssl3_enc->change_cipher_state(s,
893 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_READ)) {
894 /* SSLfatal() already called */
895 return MSG_PROCESS_ERROR;
896 }
897 } else {
898 /* TLS 1.3 gets the secret size from the handshake md */
899 size_t dummy;
900 if (!s->method->ssl3_enc->generate_master_secret(s,
901 s->master_secret, s->handshake_secret, 0,
902 &dummy)) {
903 /* SSLfatal() already called */
904 return MSG_PROCESS_ERROR;
905 }
906 if (!s->method->ssl3_enc->change_cipher_state(s,
907 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_READ)) {
908 /* SSLfatal() already called */
909 return MSG_PROCESS_ERROR;
910 }
911 if (!tls_process_initial_server_flight(s)) {
912 /* SSLfatal() already called */
913 return MSG_PROCESS_ERROR;
914 }
915 }
916 }
917
918 return MSG_PROCESS_FINISHED_READING;
919 }
920
tls_construct_change_cipher_spec(SSL * s,WPACKET * pkt)921 int tls_construct_change_cipher_spec(SSL *s, WPACKET *pkt)
922 {
923 if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS)) {
924 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
925 return 0;
926 }
927
928 return 1;
929 }
930
931 /* Add a certificate to the WPACKET */
ssl_add_cert_to_wpacket(SSL * s,WPACKET * pkt,X509 * x,int chain)932 static int ssl_add_cert_to_wpacket(SSL *s, WPACKET *pkt, X509 *x, int chain)
933 {
934 int len;
935 unsigned char *outbytes;
936
937 len = i2d_X509(x, NULL);
938 if (len < 0) {
939 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BUF_LIB);
940 return 0;
941 }
942 if (!WPACKET_sub_allocate_bytes_u24(pkt, len, &outbytes)
943 || i2d_X509(x, &outbytes) != len) {
944 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
945 return 0;
946 }
947
948 if (SSL_IS_TLS13(s)
949 && !tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_CERTIFICATE, x,
950 chain)) {
951 /* SSLfatal() already called */
952 return 0;
953 }
954
955 return 1;
956 }
957
958 /* Add certificate chain to provided WPACKET */
ssl_add_cert_chain(SSL * s,WPACKET * pkt,CERT_PKEY * cpk)959 static int ssl_add_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk)
960 {
961 int i, chain_count;
962 X509 *x;
963 STACK_OF(X509) *extra_certs;
964 STACK_OF(X509) *chain = NULL;
965 X509_STORE *chain_store;
966
967 if (cpk == NULL || cpk->x509 == NULL)
968 return 1;
969
970 x = cpk->x509;
971
972 /*
973 * If we have a certificate specific chain use it, else use parent ctx.
974 */
975 if (cpk->chain != NULL)
976 extra_certs = cpk->chain;
977 else
978 extra_certs = s->ctx->extra_certs;
979
980 if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || extra_certs)
981 chain_store = NULL;
982 else if (s->cert->chain_store)
983 chain_store = s->cert->chain_store;
984 else
985 chain_store = s->ctx->cert_store;
986
987 if (chain_store != NULL) {
988 X509_STORE_CTX *xs_ctx = X509_STORE_CTX_new_ex(s->ctx->libctx,
989 s->ctx->propq);
990
991 if (xs_ctx == NULL) {
992 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
993 return 0;
994 }
995 if (!X509_STORE_CTX_init(xs_ctx, chain_store, x, NULL)) {
996 X509_STORE_CTX_free(xs_ctx);
997 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_X509_LIB);
998 return 0;
999 }
1000 /*
1001 * It is valid for the chain not to be complete (because normally we
1002 * don't include the root cert in the chain). Therefore we deliberately
1003 * ignore the error return from this call. We're not actually verifying
1004 * the cert - we're just building as much of the chain as we can
1005 */
1006 (void)X509_verify_cert(xs_ctx);
1007 /* Don't leave errors in the queue */
1008 ERR_clear_error();
1009 chain = X509_STORE_CTX_get0_chain(xs_ctx);
1010 i = ssl_security_cert_chain(s, chain, NULL, 0);
1011 if (i != 1) {
1012 #if 0
1013 /* Dummy error calls so mkerr generates them */
1014 ERR_raise(ERR_LIB_SSL, SSL_R_EE_KEY_TOO_SMALL);
1015 ERR_raise(ERR_LIB_SSL, SSL_R_CA_KEY_TOO_SMALL);
1016 ERR_raise(ERR_LIB_SSL, SSL_R_CA_MD_TOO_WEAK);
1017 #endif
1018 X509_STORE_CTX_free(xs_ctx);
1019 SSLfatal(s, SSL_AD_INTERNAL_ERROR, i);
1020 return 0;
1021 }
1022 chain_count = sk_X509_num(chain);
1023 for (i = 0; i < chain_count; i++) {
1024 x = sk_X509_value(chain, i);
1025
1026 if (!ssl_add_cert_to_wpacket(s, pkt, x, i)) {
1027 /* SSLfatal() already called */
1028 X509_STORE_CTX_free(xs_ctx);
1029 return 0;
1030 }
1031 }
1032 X509_STORE_CTX_free(xs_ctx);
1033 } else {
1034 i = ssl_security_cert_chain(s, extra_certs, x, 0);
1035 if (i != 1) {
1036 SSLfatal(s, SSL_AD_INTERNAL_ERROR, i);
1037 return 0;
1038 }
1039 if (!ssl_add_cert_to_wpacket(s, pkt, x, 0)) {
1040 /* SSLfatal() already called */
1041 return 0;
1042 }
1043 for (i = 0; i < sk_X509_num(extra_certs); i++) {
1044 x = sk_X509_value(extra_certs, i);
1045 if (!ssl_add_cert_to_wpacket(s, pkt, x, i + 1)) {
1046 /* SSLfatal() already called */
1047 return 0;
1048 }
1049 }
1050 }
1051 return 1;
1052 }
1053
ssl3_output_cert_chain(SSL * s,WPACKET * pkt,CERT_PKEY * cpk)1054 unsigned long ssl3_output_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk)
1055 {
1056 if (!WPACKET_start_sub_packet_u24(pkt)) {
1057 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1058 return 0;
1059 }
1060
1061 if (!ssl_add_cert_chain(s, pkt, cpk))
1062 return 0;
1063
1064 if (!WPACKET_close(pkt)) {
1065 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1066 return 0;
1067 }
1068
1069 return 1;
1070 }
1071
1072 /*
1073 * Tidy up after the end of a handshake. In the case of SCTP this may result
1074 * in NBIO events. If |clearbufs| is set then init_buf and the wbio buffer is
1075 * freed up as well.
1076 */
tls_finish_handshake(SSL * s,ossl_unused WORK_STATE wst,int clearbufs,int stop)1077 WORK_STATE tls_finish_handshake(SSL *s, ossl_unused WORK_STATE wst,
1078 int clearbufs, int stop)
1079 {
1080 void (*cb) (const SSL *ssl, int type, int val) = NULL;
1081 int cleanuphand = s->statem.cleanuphand;
1082
1083 if (clearbufs) {
1084 if (!SSL_IS_DTLS(s)
1085 #ifndef OPENSSL_NO_SCTP
1086 /*
1087 * RFC6083: SCTP provides a reliable and in-sequence transport service for DTLS
1088 * messages that require it. Therefore, DTLS procedures for retransmissions
1089 * MUST NOT be used.
1090 * Hence the init_buf can be cleared when DTLS over SCTP as transport is used.
1091 */
1092 || BIO_dgram_is_sctp(SSL_get_wbio(s))
1093 #endif
1094 ) {
1095 /*
1096 * We don't do this in DTLS over UDP because we may still need the init_buf
1097 * in case there are any unexpected retransmits
1098 */
1099 BUF_MEM_free(s->init_buf);
1100 s->init_buf = NULL;
1101 }
1102
1103 if (!ssl_free_wbio_buffer(s)) {
1104 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1105 return WORK_ERROR;
1106 }
1107 s->init_num = 0;
1108 }
1109
1110 if (SSL_IS_TLS13(s) && !s->server
1111 && s->post_handshake_auth == SSL_PHA_REQUESTED)
1112 s->post_handshake_auth = SSL_PHA_EXT_SENT;
1113
1114 /*
1115 * Only set if there was a Finished message and this isn't after a TLSv1.3
1116 * post handshake exchange
1117 */
1118 if (cleanuphand) {
1119 /* skipped if we just sent a HelloRequest */
1120 s->renegotiate = 0;
1121 s->new_session = 0;
1122 s->statem.cleanuphand = 0;
1123 s->ext.ticket_expected = 0;
1124
1125 ssl3_cleanup_key_block(s);
1126
1127 if (s->server) {
1128 /*
1129 * In TLSv1.3 we update the cache as part of constructing the
1130 * NewSessionTicket
1131 */
1132 if (!SSL_IS_TLS13(s))
1133 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
1134
1135 /* N.B. s->ctx may not equal s->session_ctx */
1136 ssl_tsan_counter(s->ctx, &s->ctx->stats.sess_accept_good);
1137 s->handshake_func = ossl_statem_accept;
1138 } else {
1139 if (SSL_IS_TLS13(s)) {
1140 /*
1141 * We encourage applications to only use TLSv1.3 tickets once,
1142 * so we remove this one from the cache.
1143 */
1144 if ((s->session_ctx->session_cache_mode
1145 & SSL_SESS_CACHE_CLIENT) != 0)
1146 SSL_CTX_remove_session(s->session_ctx, s->session);
1147 } else {
1148 /*
1149 * In TLSv1.3 we update the cache as part of processing the
1150 * NewSessionTicket
1151 */
1152 ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
1153 }
1154 if (s->hit)
1155 ssl_tsan_counter(s->session_ctx,
1156 &s->session_ctx->stats.sess_hit);
1157
1158 s->handshake_func = ossl_statem_connect;
1159 ssl_tsan_counter(s->session_ctx,
1160 &s->session_ctx->stats.sess_connect_good);
1161 }
1162
1163 if (SSL_IS_DTLS(s)) {
1164 /* done with handshaking */
1165 s->d1->handshake_read_seq = 0;
1166 s->d1->handshake_write_seq = 0;
1167 s->d1->next_handshake_write_seq = 0;
1168 dtls1_clear_received_buffer(s);
1169 }
1170 }
1171
1172 if (s->info_callback != NULL)
1173 cb = s->info_callback;
1174 else if (s->ctx->info_callback != NULL)
1175 cb = s->ctx->info_callback;
1176
1177 /* The callback may expect us to not be in init at handshake done */
1178 ossl_statem_set_in_init(s, 0);
1179
1180 if (cb != NULL) {
1181 if (cleanuphand
1182 || !SSL_IS_TLS13(s)
1183 || SSL_IS_FIRST_HANDSHAKE(s))
1184 cb(s, SSL_CB_HANDSHAKE_DONE, 1);
1185 }
1186
1187 if (!stop) {
1188 /* If we've got more work to do we go back into init */
1189 ossl_statem_set_in_init(s, 1);
1190 return WORK_FINISHED_CONTINUE;
1191 }
1192
1193 return WORK_FINISHED_STOP;
1194 }
1195
tls_get_message_header(SSL * s,int * mt)1196 int tls_get_message_header(SSL *s, int *mt)
1197 {
1198 /* s->init_num < SSL3_HM_HEADER_LENGTH */
1199 int skip_message, i, recvd_type;
1200 unsigned char *p;
1201 size_t l, readbytes;
1202
1203 p = (unsigned char *)s->init_buf->data;
1204
1205 do {
1206 while (s->init_num < SSL3_HM_HEADER_LENGTH) {
1207 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, &recvd_type,
1208 &p[s->init_num],
1209 SSL3_HM_HEADER_LENGTH - s->init_num,
1210 0, &readbytes);
1211 if (i <= 0) {
1212 s->rwstate = SSL_READING;
1213 return 0;
1214 }
1215 if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1216 /*
1217 * A ChangeCipherSpec must be a single byte and may not occur
1218 * in the middle of a handshake message.
1219 */
1220 if (s->init_num != 0 || readbytes != 1 || p[0] != SSL3_MT_CCS) {
1221 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1222 SSL_R_BAD_CHANGE_CIPHER_SPEC);
1223 return 0;
1224 }
1225 if (s->statem.hand_state == TLS_ST_BEFORE
1226 && (s->s3.flags & TLS1_FLAGS_STATELESS) != 0) {
1227 /*
1228 * We are stateless and we received a CCS. Probably this is
1229 * from a client between the first and second ClientHellos.
1230 * We should ignore this, but return an error because we do
1231 * not return success until we see the second ClientHello
1232 * with a valid cookie.
1233 */
1234 return 0;
1235 }
1236 s->s3.tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
1237 s->init_num = readbytes - 1;
1238 s->init_msg = s->init_buf->data;
1239 s->s3.tmp.message_size = readbytes;
1240 return 1;
1241 } else if (recvd_type != SSL3_RT_HANDSHAKE) {
1242 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1243 SSL_R_CCS_RECEIVED_EARLY);
1244 return 0;
1245 }
1246 s->init_num += readbytes;
1247 }
1248
1249 skip_message = 0;
1250 if (!s->server)
1251 if (s->statem.hand_state != TLS_ST_OK
1252 && p[0] == SSL3_MT_HELLO_REQUEST)
1253 /*
1254 * The server may always send 'Hello Request' messages --
1255 * we are doing a handshake anyway now, so ignore them if
1256 * their format is correct. Does not count for 'Finished'
1257 * MAC.
1258 */
1259 if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
1260 s->init_num = 0;
1261 skip_message = 1;
1262
1263 if (s->msg_callback)
1264 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1265 p, SSL3_HM_HEADER_LENGTH, s,
1266 s->msg_callback_arg);
1267 }
1268 } while (skip_message);
1269 /* s->init_num == SSL3_HM_HEADER_LENGTH */
1270
1271 *mt = *p;
1272 s->s3.tmp.message_type = *(p++);
1273
1274 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1275 /*
1276 * Only happens with SSLv3+ in an SSLv2 backward compatible
1277 * ClientHello
1278 *
1279 * Total message size is the remaining record bytes to read
1280 * plus the SSL3_HM_HEADER_LENGTH bytes that we already read
1281 */
1282 l = RECORD_LAYER_get_rrec_length(&s->rlayer)
1283 + SSL3_HM_HEADER_LENGTH;
1284 s->s3.tmp.message_size = l;
1285
1286 s->init_msg = s->init_buf->data;
1287 s->init_num = SSL3_HM_HEADER_LENGTH;
1288 } else {
1289 n2l3(p, l);
1290 /* BUF_MEM_grow takes an 'int' parameter */
1291 if (l > (INT_MAX - SSL3_HM_HEADER_LENGTH)) {
1292 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1293 SSL_R_EXCESSIVE_MESSAGE_SIZE);
1294 return 0;
1295 }
1296 s->s3.tmp.message_size = l;
1297
1298 s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
1299 s->init_num = 0;
1300 }
1301
1302 return 1;
1303 }
1304
tls_get_message_body(SSL * s,size_t * len)1305 int tls_get_message_body(SSL *s, size_t *len)
1306 {
1307 size_t n, readbytes;
1308 unsigned char *p;
1309 int i;
1310
1311 if (s->s3.tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
1312 /* We've already read everything in */
1313 *len = (unsigned long)s->init_num;
1314 return 1;
1315 }
1316
1317 p = s->init_msg;
1318 n = s->s3.tmp.message_size - s->init_num;
1319 while (n > 0) {
1320 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
1321 &p[s->init_num], n, 0, &readbytes);
1322 if (i <= 0) {
1323 s->rwstate = SSL_READING;
1324 *len = 0;
1325 return 0;
1326 }
1327 s->init_num += readbytes;
1328 n -= readbytes;
1329 }
1330
1331 /*
1332 * If receiving Finished, record MAC of prior handshake messages for
1333 * Finished verification.
1334 */
1335 if (*(s->init_buf->data) == SSL3_MT_FINISHED && !ssl3_take_mac(s)) {
1336 /* SSLfatal() already called */
1337 *len = 0;
1338 return 0;
1339 }
1340
1341 /* Feed this message into MAC computation. */
1342 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1343 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1344 s->init_num)) {
1345 /* SSLfatal() already called */
1346 *len = 0;
1347 return 0;
1348 }
1349 if (s->msg_callback)
1350 s->msg_callback(0, SSL2_VERSION, 0, s->init_buf->data,
1351 (size_t)s->init_num, s, s->msg_callback_arg);
1352 } else {
1353 /*
1354 * We defer feeding in the HRR until later. We'll do it as part of
1355 * processing the message
1356 * The TLsv1.3 handshake transcript stops at the ClientFinished
1357 * message.
1358 */
1359 #define SERVER_HELLO_RANDOM_OFFSET (SSL3_HM_HEADER_LENGTH + 2)
1360 /* KeyUpdate and NewSessionTicket do not need to be added */
1361 if (!SSL_IS_TLS13(s) || (s->s3.tmp.message_type != SSL3_MT_NEWSESSION_TICKET
1362 && s->s3.tmp.message_type != SSL3_MT_KEY_UPDATE)) {
1363 if (s->s3.tmp.message_type != SSL3_MT_SERVER_HELLO
1364 || s->init_num < SERVER_HELLO_RANDOM_OFFSET + SSL3_RANDOM_SIZE
1365 || memcmp(hrrrandom,
1366 s->init_buf->data + SERVER_HELLO_RANDOM_OFFSET,
1367 SSL3_RANDOM_SIZE) != 0) {
1368 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1369 s->init_num + SSL3_HM_HEADER_LENGTH)) {
1370 /* SSLfatal() already called */
1371 *len = 0;
1372 return 0;
1373 }
1374 }
1375 }
1376 if (s->msg_callback)
1377 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
1378 (size_t)s->init_num + SSL3_HM_HEADER_LENGTH, s,
1379 s->msg_callback_arg);
1380 }
1381
1382 *len = s->init_num;
1383 return 1;
1384 }
1385
1386 static const X509ERR2ALERT x509table[] = {
1387 {X509_V_ERR_APPLICATION_VERIFICATION, SSL_AD_HANDSHAKE_FAILURE},
1388 {X509_V_ERR_CA_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
1389 {X509_V_ERR_EC_KEY_EXPLICIT_PARAMS, SSL_AD_BAD_CERTIFICATE},
1390 {X509_V_ERR_CA_MD_TOO_WEAK, SSL_AD_BAD_CERTIFICATE},
1391 {X509_V_ERR_CERT_CHAIN_TOO_LONG, SSL_AD_UNKNOWN_CA},
1392 {X509_V_ERR_CERT_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
1393 {X509_V_ERR_CERT_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
1394 {X509_V_ERR_CERT_REJECTED, SSL_AD_BAD_CERTIFICATE},
1395 {X509_V_ERR_CERT_REVOKED, SSL_AD_CERTIFICATE_REVOKED},
1396 {X509_V_ERR_CERT_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
1397 {X509_V_ERR_CERT_UNTRUSTED, SSL_AD_BAD_CERTIFICATE},
1398 {X509_V_ERR_CRL_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
1399 {X509_V_ERR_CRL_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
1400 {X509_V_ERR_CRL_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
1401 {X509_V_ERR_DANE_NO_MATCH, SSL_AD_BAD_CERTIFICATE},
1402 {X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT, SSL_AD_UNKNOWN_CA},
1403 {X509_V_ERR_EE_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
1404 {X509_V_ERR_EMAIL_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1405 {X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD, SSL_AD_BAD_CERTIFICATE},
1406 {X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD, SSL_AD_BAD_CERTIFICATE},
1407 {X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
1408 {X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
1409 {X509_V_ERR_HOSTNAME_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1410 {X509_V_ERR_INVALID_CA, SSL_AD_UNKNOWN_CA},
1411 {X509_V_ERR_INVALID_CALL, SSL_AD_INTERNAL_ERROR},
1412 {X509_V_ERR_INVALID_PURPOSE, SSL_AD_UNSUPPORTED_CERTIFICATE},
1413 {X509_V_ERR_IP_ADDRESS_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1414 {X509_V_ERR_OUT_OF_MEM, SSL_AD_INTERNAL_ERROR},
1415 {X509_V_ERR_PATH_LENGTH_EXCEEDED, SSL_AD_UNKNOWN_CA},
1416 {X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN, SSL_AD_UNKNOWN_CA},
1417 {X509_V_ERR_STORE_LOOKUP, SSL_AD_INTERNAL_ERROR},
1418 {X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY, SSL_AD_BAD_CERTIFICATE},
1419 {X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
1420 {X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
1421 {X509_V_ERR_UNABLE_TO_GET_CRL, SSL_AD_UNKNOWN_CA},
1422 {X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER, SSL_AD_UNKNOWN_CA},
1423 {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT, SSL_AD_UNKNOWN_CA},
1424 {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, SSL_AD_UNKNOWN_CA},
1425 {X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE, SSL_AD_UNKNOWN_CA},
1426 {X509_V_ERR_UNSPECIFIED, SSL_AD_INTERNAL_ERROR},
1427
1428 /* Last entry; return this if we don't find the value above. */
1429 {X509_V_OK, SSL_AD_CERTIFICATE_UNKNOWN}
1430 };
1431
ssl_x509err2alert(int x509err)1432 int ssl_x509err2alert(int x509err)
1433 {
1434 const X509ERR2ALERT *tp;
1435
1436 for (tp = x509table; tp->x509err != X509_V_OK; ++tp)
1437 if (tp->x509err == x509err)
1438 break;
1439 return tp->alert;
1440 }
1441
ssl_allow_compression(SSL * s)1442 int ssl_allow_compression(SSL *s)
1443 {
1444 if (s->options & SSL_OP_NO_COMPRESSION)
1445 return 0;
1446 return ssl_security(s, SSL_SECOP_COMPRESSION, 0, 0, NULL);
1447 }
1448
version_cmp(const SSL * s,int a,int b)1449 static int version_cmp(const SSL *s, int a, int b)
1450 {
1451 int dtls = SSL_IS_DTLS(s);
1452
1453 if (a == b)
1454 return 0;
1455 if (!dtls)
1456 return a < b ? -1 : 1;
1457 return DTLS_VERSION_LT(a, b) ? -1 : 1;
1458 }
1459
1460 typedef struct {
1461 int version;
1462 const SSL_METHOD *(*cmeth) (void);
1463 const SSL_METHOD *(*smeth) (void);
1464 } version_info;
1465
1466 #if TLS_MAX_VERSION_INTERNAL != TLS1_3_VERSION
1467 # error Code needs update for TLS_method() support beyond TLS1_3_VERSION.
1468 #endif
1469
1470 /* Must be in order high to low */
1471 static const version_info tls_version_table[] = {
1472 #ifndef OPENSSL_NO_TLS1_3
1473 {TLS1_3_VERSION, tlsv1_3_client_method, tlsv1_3_server_method},
1474 #else
1475 {TLS1_3_VERSION, NULL, NULL},
1476 #endif
1477 #ifndef OPENSSL_NO_TLS1_2
1478 {TLS1_2_VERSION, tlsv1_2_client_method, tlsv1_2_server_method},
1479 #else
1480 {TLS1_2_VERSION, NULL, NULL},
1481 #endif
1482 #ifndef OPENSSL_NO_TLS1_1
1483 {TLS1_1_VERSION, tlsv1_1_client_method, tlsv1_1_server_method},
1484 #else
1485 {TLS1_1_VERSION, NULL, NULL},
1486 #endif
1487 #ifndef OPENSSL_NO_TLS1
1488 {TLS1_VERSION, tlsv1_client_method, tlsv1_server_method},
1489 #else
1490 {TLS1_VERSION, NULL, NULL},
1491 #endif
1492 #ifndef OPENSSL_NO_SSL3
1493 {SSL3_VERSION, sslv3_client_method, sslv3_server_method},
1494 #else
1495 {SSL3_VERSION, NULL, NULL},
1496 #endif
1497 {0, NULL, NULL},
1498 };
1499
1500 #if DTLS_MAX_VERSION_INTERNAL != DTLS1_2_VERSION
1501 # error Code needs update for DTLS_method() support beyond DTLS1_2_VERSION.
1502 #endif
1503
1504 /* Must be in order high to low */
1505 static const version_info dtls_version_table[] = {
1506 #ifndef OPENSSL_NO_DTLS1_2
1507 {DTLS1_2_VERSION, dtlsv1_2_client_method, dtlsv1_2_server_method},
1508 #else
1509 {DTLS1_2_VERSION, NULL, NULL},
1510 #endif
1511 #ifndef OPENSSL_NO_DTLS1
1512 {DTLS1_VERSION, dtlsv1_client_method, dtlsv1_server_method},
1513 {DTLS1_BAD_VER, dtls_bad_ver_client_method, NULL},
1514 #else
1515 {DTLS1_VERSION, NULL, NULL},
1516 {DTLS1_BAD_VER, NULL, NULL},
1517 #endif
1518 {0, NULL, NULL},
1519 };
1520
1521 /*
1522 * ssl_method_error - Check whether an SSL_METHOD is enabled.
1523 *
1524 * @s: The SSL handle for the candidate method
1525 * @method: the intended method.
1526 *
1527 * Returns 0 on success, or an SSL error reason on failure.
1528 */
ssl_method_error(const SSL * s,const SSL_METHOD * method)1529 static int ssl_method_error(const SSL *s, const SSL_METHOD *method)
1530 {
1531 int version = method->version;
1532
1533 if ((s->min_proto_version != 0 &&
1534 version_cmp(s, version, s->min_proto_version) < 0) ||
1535 ssl_security(s, SSL_SECOP_VERSION, 0, version, NULL) == 0)
1536 return SSL_R_VERSION_TOO_LOW;
1537
1538 if (s->max_proto_version != 0 &&
1539 version_cmp(s, version, s->max_proto_version) > 0)
1540 return SSL_R_VERSION_TOO_HIGH;
1541
1542 if ((s->options & method->mask) != 0)
1543 return SSL_R_UNSUPPORTED_PROTOCOL;
1544 if ((method->flags & SSL_METHOD_NO_SUITEB) != 0 && tls1_suiteb(s))
1545 return SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE;
1546
1547 return 0;
1548 }
1549
1550 /*
1551 * Only called by servers. Returns 1 if the server has a TLSv1.3 capable
1552 * certificate type, or has PSK or a certificate callback configured, or has
1553 * a servername callback configure. Otherwise returns 0.
1554 */
is_tls13_capable(const SSL * s)1555 static int is_tls13_capable(const SSL *s)
1556 {
1557 int i;
1558 int curve;
1559
1560 if (!ossl_assert(s->ctx != NULL) || !ossl_assert(s->session_ctx != NULL))
1561 return 0;
1562
1563 /*
1564 * A servername callback can change the available certs, so if a servername
1565 * cb is set then we just assume TLSv1.3 will be ok
1566 */
1567 if (s->ctx->ext.servername_cb != NULL
1568 || s->session_ctx->ext.servername_cb != NULL)
1569 return 1;
1570
1571 #ifndef OPENSSL_NO_PSK
1572 if (s->psk_server_callback != NULL)
1573 return 1;
1574 #endif
1575
1576 if (s->psk_find_session_cb != NULL || s->cert->cert_cb != NULL)
1577 return 1;
1578
1579 for (i = 0; i < SSL_PKEY_NUM; i++) {
1580 /* Skip over certs disallowed for TLSv1.3 */
1581 switch (i) {
1582 case SSL_PKEY_DSA_SIGN:
1583 case SSL_PKEY_GOST01:
1584 case SSL_PKEY_GOST12_256:
1585 case SSL_PKEY_GOST12_512:
1586 continue;
1587 default:
1588 break;
1589 }
1590 if (!ssl_has_cert(s, i))
1591 continue;
1592 if (i != SSL_PKEY_ECC)
1593 return 1;
1594 /*
1595 * Prior to TLSv1.3 sig algs allowed any curve to be used. TLSv1.3 is
1596 * more restrictive so check that our sig algs are consistent with this
1597 * EC cert. See section 4.2.3 of RFC8446.
1598 */
1599 curve = ssl_get_EC_curve_nid(s->cert->pkeys[SSL_PKEY_ECC].privatekey);
1600 if (tls_check_sigalg_curve(s, curve))
1601 return 1;
1602 }
1603
1604 return 0;
1605 }
1606
1607 /*
1608 * ssl_version_supported - Check that the specified `version` is supported by
1609 * `SSL *` instance
1610 *
1611 * @s: The SSL handle for the candidate method
1612 * @version: Protocol version to test against
1613 *
1614 * Returns 1 when supported, otherwise 0
1615 */
ssl_version_supported(const SSL * s,int version,const SSL_METHOD ** meth)1616 int ssl_version_supported(const SSL *s, int version, const SSL_METHOD **meth)
1617 {
1618 const version_info *vent;
1619 const version_info *table;
1620
1621 switch (s->method->version) {
1622 default:
1623 /* Version should match method version for non-ANY method */
1624 return version_cmp(s, version, s->version) == 0;
1625 case TLS_ANY_VERSION:
1626 table = tls_version_table;
1627 break;
1628 case DTLS_ANY_VERSION:
1629 table = dtls_version_table;
1630 break;
1631 }
1632
1633 for (vent = table;
1634 vent->version != 0 && version_cmp(s, version, vent->version) <= 0;
1635 ++vent) {
1636 if (vent->cmeth != NULL
1637 && version_cmp(s, version, vent->version) == 0
1638 && ssl_method_error(s, vent->cmeth()) == 0
1639 && (!s->server
1640 || version != TLS1_3_VERSION
1641 || is_tls13_capable(s))) {
1642 if (meth != NULL)
1643 *meth = vent->cmeth();
1644 return 1;
1645 }
1646 }
1647 return 0;
1648 }
1649
1650 /*
1651 * ssl_check_version_downgrade - In response to RFC7507 SCSV version
1652 * fallback indication from a client check whether we're using the highest
1653 * supported protocol version.
1654 *
1655 * @s server SSL handle.
1656 *
1657 * Returns 1 when using the highest enabled version, 0 otherwise.
1658 */
ssl_check_version_downgrade(SSL * s)1659 int ssl_check_version_downgrade(SSL *s)
1660 {
1661 const version_info *vent;
1662 const version_info *table;
1663
1664 /*
1665 * Check that the current protocol is the highest enabled version
1666 * (according to s->ctx->method, as version negotiation may have changed
1667 * s->method).
1668 */
1669 if (s->version == s->ctx->method->version)
1670 return 1;
1671
1672 /*
1673 * Apparently we're using a version-flexible SSL_METHOD (not at its
1674 * highest protocol version).
1675 */
1676 if (s->ctx->method->version == TLS_method()->version)
1677 table = tls_version_table;
1678 else if (s->ctx->method->version == DTLS_method()->version)
1679 table = dtls_version_table;
1680 else {
1681 /* Unexpected state; fail closed. */
1682 return 0;
1683 }
1684
1685 for (vent = table; vent->version != 0; ++vent) {
1686 if (vent->smeth != NULL && ssl_method_error(s, vent->smeth()) == 0)
1687 return s->version == vent->version;
1688 }
1689 return 0;
1690 }
1691
1692 /*
1693 * ssl_set_version_bound - set an upper or lower bound on the supported (D)TLS
1694 * protocols, provided the initial (D)TLS method is version-flexible. This
1695 * function sanity-checks the proposed value and makes sure the method is
1696 * version-flexible, then sets the limit if all is well.
1697 *
1698 * @method_version: The version of the current SSL_METHOD.
1699 * @version: the intended limit.
1700 * @bound: pointer to limit to be updated.
1701 *
1702 * Returns 1 on success, 0 on failure.
1703 */
ssl_set_version_bound(int method_version,int version,int * bound)1704 int ssl_set_version_bound(int method_version, int version, int *bound)
1705 {
1706 int valid_tls;
1707 int valid_dtls;
1708
1709 if (version == 0) {
1710 *bound = version;
1711 return 1;
1712 }
1713
1714 valid_tls = version >= SSL3_VERSION && version <= TLS_MAX_VERSION_INTERNAL;
1715 valid_dtls =
1716 DTLS_VERSION_LE(version, DTLS_MAX_VERSION_INTERNAL) &&
1717 DTLS_VERSION_GE(version, DTLS1_BAD_VER);
1718
1719 if (!valid_tls && !valid_dtls)
1720 return 0;
1721
1722 /*-
1723 * Restrict TLS methods to TLS protocol versions.
1724 * Restrict DTLS methods to DTLS protocol versions.
1725 * Note, DTLS version numbers are decreasing, use comparison macros.
1726 *
1727 * Note that for both lower-bounds we use explicit versions, not
1728 * (D)TLS_MIN_VERSION. This is because we don't want to break user
1729 * configurations. If the MIN (supported) version ever rises, the user's
1730 * "floor" remains valid even if no longer available. We don't expect the
1731 * MAX ceiling to ever get lower, so making that variable makes sense.
1732 *
1733 * We ignore attempts to set bounds on version-inflexible methods,
1734 * returning success.
1735 */
1736 switch (method_version) {
1737 default:
1738 break;
1739
1740 case TLS_ANY_VERSION:
1741 if (valid_tls)
1742 *bound = version;
1743 break;
1744
1745 case DTLS_ANY_VERSION:
1746 if (valid_dtls)
1747 *bound = version;
1748 break;
1749 }
1750 return 1;
1751 }
1752
check_for_downgrade(SSL * s,int vers,DOWNGRADE * dgrd)1753 static void check_for_downgrade(SSL *s, int vers, DOWNGRADE *dgrd)
1754 {
1755 if (vers == TLS1_2_VERSION
1756 && ssl_version_supported(s, TLS1_3_VERSION, NULL)) {
1757 *dgrd = DOWNGRADE_TO_1_2;
1758 } else if (!SSL_IS_DTLS(s)
1759 && vers < TLS1_2_VERSION
1760 /*
1761 * We need to ensure that a server that disables TLSv1.2
1762 * (creating a hole between TLSv1.3 and TLSv1.1) can still
1763 * complete handshakes with clients that support TLSv1.2 and
1764 * below. Therefore we do not enable the sentinel if TLSv1.3 is
1765 * enabled and TLSv1.2 is not.
1766 */
1767 && ssl_version_supported(s, TLS1_2_VERSION, NULL)) {
1768 *dgrd = DOWNGRADE_TO_1_1;
1769 } else {
1770 *dgrd = DOWNGRADE_NONE;
1771 }
1772 }
1773
1774 /*
1775 * ssl_choose_server_version - Choose server (D)TLS version. Called when the
1776 * client HELLO is received to select the final server protocol version and
1777 * the version specific method.
1778 *
1779 * @s: server SSL handle.
1780 *
1781 * Returns 0 on success or an SSL error reason number on failure.
1782 */
ssl_choose_server_version(SSL * s,CLIENTHELLO_MSG * hello,DOWNGRADE * dgrd)1783 int ssl_choose_server_version(SSL *s, CLIENTHELLO_MSG *hello, DOWNGRADE *dgrd)
1784 {
1785 /*-
1786 * With version-flexible methods we have an initial state with:
1787 *
1788 * s->method->version == (D)TLS_ANY_VERSION,
1789 * s->version == (D)TLS_MAX_VERSION_INTERNAL.
1790 *
1791 * So we detect version-flexible methods via the method version, not the
1792 * handle version.
1793 */
1794 int server_version = s->method->version;
1795 int client_version = hello->legacy_version;
1796 const version_info *vent;
1797 const version_info *table;
1798 int disabled = 0;
1799 RAW_EXTENSION *suppversions;
1800
1801 s->client_version = client_version;
1802
1803 switch (server_version) {
1804 default:
1805 if (!SSL_IS_TLS13(s)) {
1806 if (version_cmp(s, client_version, s->version) < 0)
1807 return SSL_R_WRONG_SSL_VERSION;
1808 *dgrd = DOWNGRADE_NONE;
1809 /*
1810 * If this SSL handle is not from a version flexible method we don't
1811 * (and never did) check min/max FIPS or Suite B constraints. Hope
1812 * that's OK. It is up to the caller to not choose fixed protocol
1813 * versions they don't want. If not, then easy to fix, just return
1814 * ssl_method_error(s, s->method)
1815 */
1816 return 0;
1817 }
1818 /*
1819 * Fall through if we are TLSv1.3 already (this means we must be after
1820 * a HelloRetryRequest
1821 */
1822 /* fall thru */
1823 case TLS_ANY_VERSION:
1824 table = tls_version_table;
1825 break;
1826 case DTLS_ANY_VERSION:
1827 table = dtls_version_table;
1828 break;
1829 }
1830
1831 suppversions = &hello->pre_proc_exts[TLSEXT_IDX_supported_versions];
1832
1833 /* If we did an HRR then supported versions is mandatory */
1834 if (!suppversions->present && s->hello_retry_request != SSL_HRR_NONE)
1835 return SSL_R_UNSUPPORTED_PROTOCOL;
1836
1837 if (suppversions->present && !SSL_IS_DTLS(s)) {
1838 unsigned int candidate_vers = 0;
1839 unsigned int best_vers = 0;
1840 const SSL_METHOD *best_method = NULL;
1841 PACKET versionslist;
1842
1843 suppversions->parsed = 1;
1844
1845 if (!PACKET_as_length_prefixed_1(&suppversions->data, &versionslist)) {
1846 /* Trailing or invalid data? */
1847 return SSL_R_LENGTH_MISMATCH;
1848 }
1849
1850 /*
1851 * The TLSv1.3 spec says the client MUST set this to TLS1_2_VERSION.
1852 * The spec only requires servers to check that it isn't SSLv3:
1853 * "Any endpoint receiving a Hello message with
1854 * ClientHello.legacy_version or ServerHello.legacy_version set to
1855 * 0x0300 MUST abort the handshake with a "protocol_version" alert."
1856 * We are slightly stricter and require that it isn't SSLv3 or lower.
1857 * We tolerate TLSv1 and TLSv1.1.
1858 */
1859 if (client_version <= SSL3_VERSION)
1860 return SSL_R_BAD_LEGACY_VERSION;
1861
1862 while (PACKET_get_net_2(&versionslist, &candidate_vers)) {
1863 if (version_cmp(s, candidate_vers, best_vers) <= 0)
1864 continue;
1865 if (ssl_version_supported(s, candidate_vers, &best_method))
1866 best_vers = candidate_vers;
1867 }
1868 if (PACKET_remaining(&versionslist) != 0) {
1869 /* Trailing data? */
1870 return SSL_R_LENGTH_MISMATCH;
1871 }
1872
1873 if (best_vers > 0) {
1874 if (s->hello_retry_request != SSL_HRR_NONE) {
1875 /*
1876 * This is after a HelloRetryRequest so we better check that we
1877 * negotiated TLSv1.3
1878 */
1879 if (best_vers != TLS1_3_VERSION)
1880 return SSL_R_UNSUPPORTED_PROTOCOL;
1881 return 0;
1882 }
1883 check_for_downgrade(s, best_vers, dgrd);
1884 s->version = best_vers;
1885 s->method = best_method;
1886 return 0;
1887 }
1888 return SSL_R_UNSUPPORTED_PROTOCOL;
1889 }
1890
1891 /*
1892 * If the supported versions extension isn't present, then the highest
1893 * version we can negotiate is TLSv1.2
1894 */
1895 if (version_cmp(s, client_version, TLS1_3_VERSION) >= 0)
1896 client_version = TLS1_2_VERSION;
1897
1898 /*
1899 * No supported versions extension, so we just use the version supplied in
1900 * the ClientHello.
1901 */
1902 for (vent = table; vent->version != 0; ++vent) {
1903 const SSL_METHOD *method;
1904
1905 if (vent->smeth == NULL ||
1906 version_cmp(s, client_version, vent->version) < 0)
1907 continue;
1908 method = vent->smeth();
1909 if (ssl_method_error(s, method) == 0) {
1910 check_for_downgrade(s, vent->version, dgrd);
1911 s->version = vent->version;
1912 s->method = method;
1913 return 0;
1914 }
1915 disabled = 1;
1916 }
1917 return disabled ? SSL_R_UNSUPPORTED_PROTOCOL : SSL_R_VERSION_TOO_LOW;
1918 }
1919
1920 /*
1921 * ssl_choose_client_version - Choose client (D)TLS version. Called when the
1922 * server HELLO is received to select the final client protocol version and
1923 * the version specific method.
1924 *
1925 * @s: client SSL handle.
1926 * @version: The proposed version from the server's HELLO.
1927 * @extensions: The extensions received
1928 *
1929 * Returns 1 on success or 0 on error.
1930 */
ssl_choose_client_version(SSL * s,int version,RAW_EXTENSION * extensions)1931 int ssl_choose_client_version(SSL *s, int version, RAW_EXTENSION *extensions)
1932 {
1933 const version_info *vent;
1934 const version_info *table;
1935 int ret, ver_min, ver_max, real_max, origv;
1936
1937 origv = s->version;
1938 s->version = version;
1939
1940 /* This will overwrite s->version if the extension is present */
1941 if (!tls_parse_extension(s, TLSEXT_IDX_supported_versions,
1942 SSL_EXT_TLS1_2_SERVER_HELLO
1943 | SSL_EXT_TLS1_3_SERVER_HELLO, extensions,
1944 NULL, 0)) {
1945 s->version = origv;
1946 return 0;
1947 }
1948
1949 if (s->hello_retry_request != SSL_HRR_NONE
1950 && s->version != TLS1_3_VERSION) {
1951 s->version = origv;
1952 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_SSL_VERSION);
1953 return 0;
1954 }
1955
1956 switch (s->method->version) {
1957 default:
1958 if (s->version != s->method->version) {
1959 s->version = origv;
1960 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_SSL_VERSION);
1961 return 0;
1962 }
1963 /*
1964 * If this SSL handle is not from a version flexible method we don't
1965 * (and never did) check min/max, FIPS or Suite B constraints. Hope
1966 * that's OK. It is up to the caller to not choose fixed protocol
1967 * versions they don't want. If not, then easy to fix, just return
1968 * ssl_method_error(s, s->method)
1969 */
1970 return 1;
1971 case TLS_ANY_VERSION:
1972 table = tls_version_table;
1973 break;
1974 case DTLS_ANY_VERSION:
1975 table = dtls_version_table;
1976 break;
1977 }
1978
1979 ret = ssl_get_min_max_version(s, &ver_min, &ver_max, &real_max);
1980 if (ret != 0) {
1981 s->version = origv;
1982 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, ret);
1983 return 0;
1984 }
1985 if (SSL_IS_DTLS(s) ? DTLS_VERSION_LT(s->version, ver_min)
1986 : s->version < ver_min) {
1987 s->version = origv;
1988 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
1989 return 0;
1990 } else if (SSL_IS_DTLS(s) ? DTLS_VERSION_GT(s->version, ver_max)
1991 : s->version > ver_max) {
1992 s->version = origv;
1993 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
1994 return 0;
1995 }
1996
1997 if ((s->mode & SSL_MODE_SEND_FALLBACK_SCSV) == 0)
1998 real_max = ver_max;
1999
2000 /* Check for downgrades */
2001 if (s->version == TLS1_2_VERSION && real_max > s->version) {
2002 if (memcmp(tls12downgrade,
2003 s->s3.server_random + SSL3_RANDOM_SIZE
2004 - sizeof(tls12downgrade),
2005 sizeof(tls12downgrade)) == 0) {
2006 s->version = origv;
2007 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2008 SSL_R_INAPPROPRIATE_FALLBACK);
2009 return 0;
2010 }
2011 } else if (!SSL_IS_DTLS(s)
2012 && s->version < TLS1_2_VERSION
2013 && real_max > s->version) {
2014 if (memcmp(tls11downgrade,
2015 s->s3.server_random + SSL3_RANDOM_SIZE
2016 - sizeof(tls11downgrade),
2017 sizeof(tls11downgrade)) == 0) {
2018 s->version = origv;
2019 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2020 SSL_R_INAPPROPRIATE_FALLBACK);
2021 return 0;
2022 }
2023 }
2024
2025 for (vent = table; vent->version != 0; ++vent) {
2026 if (vent->cmeth == NULL || s->version != vent->version)
2027 continue;
2028
2029 s->method = vent->cmeth();
2030 return 1;
2031 }
2032
2033 s->version = origv;
2034 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
2035 return 0;
2036 }
2037
2038 /*
2039 * ssl_get_min_max_version - get minimum and maximum protocol version
2040 * @s: The SSL connection
2041 * @min_version: The minimum supported version
2042 * @max_version: The maximum supported version
2043 * @real_max: The highest version below the lowest compile time version hole
2044 * where that hole lies above at least one run-time enabled
2045 * protocol.
2046 *
2047 * Work out what version we should be using for the initial ClientHello if the
2048 * version is initially (D)TLS_ANY_VERSION. We apply any explicit SSL_OP_NO_xxx
2049 * options, the MinProtocol and MaxProtocol configuration commands, any Suite B
2050 * constraints and any floor imposed by the security level here,
2051 * so we don't advertise the wrong protocol version to only reject the outcome later.
2052 *
2053 * Computing the right floor matters. If, e.g., TLS 1.0 and 1.2 are enabled,
2054 * TLS 1.1 is disabled, but the security level, Suite-B and/or MinProtocol
2055 * only allow TLS 1.2, we want to advertise TLS1.2, *not* TLS1.
2056 *
2057 * Returns 0 on success or an SSL error reason number on failure. On failure
2058 * min_version and max_version will also be set to 0.
2059 */
ssl_get_min_max_version(const SSL * s,int * min_version,int * max_version,int * real_max)2060 int ssl_get_min_max_version(const SSL *s, int *min_version, int *max_version,
2061 int *real_max)
2062 {
2063 int version, tmp_real_max;
2064 int hole;
2065 const SSL_METHOD *single = NULL;
2066 const SSL_METHOD *method;
2067 const version_info *table;
2068 const version_info *vent;
2069
2070 switch (s->method->version) {
2071 default:
2072 /*
2073 * If this SSL handle is not from a version flexible method we don't
2074 * (and never did) check min/max FIPS or Suite B constraints. Hope
2075 * that's OK. It is up to the caller to not choose fixed protocol
2076 * versions they don't want. If not, then easy to fix, just return
2077 * ssl_method_error(s, s->method)
2078 */
2079 *min_version = *max_version = s->version;
2080 /*
2081 * Providing a real_max only makes sense where we're using a version
2082 * flexible method.
2083 */
2084 if (!ossl_assert(real_max == NULL))
2085 return ERR_R_INTERNAL_ERROR;
2086 return 0;
2087 case TLS_ANY_VERSION:
2088 table = tls_version_table;
2089 break;
2090 case DTLS_ANY_VERSION:
2091 table = dtls_version_table;
2092 break;
2093 }
2094
2095 /*
2096 * SSL_OP_NO_X disables all protocols above X *if* there are some protocols
2097 * below X enabled. This is required in order to maintain the "version
2098 * capability" vector contiguous. Any versions with a NULL client method
2099 * (protocol version client is disabled at compile-time) is also a "hole".
2100 *
2101 * Our initial state is hole == 1, version == 0. That is, versions above
2102 * the first version in the method table are disabled (a "hole" above
2103 * the valid protocol entries) and we don't have a selected version yet.
2104 *
2105 * Whenever "hole == 1", and we hit an enabled method, its version becomes
2106 * the selected version, and the method becomes a candidate "single"
2107 * method. We're no longer in a hole, so "hole" becomes 0.
2108 *
2109 * If "hole == 0" and we hit an enabled method, then "single" is cleared,
2110 * as we support a contiguous range of at least two methods. If we hit
2111 * a disabled method, then hole becomes true again, but nothing else
2112 * changes yet, because all the remaining methods may be disabled too.
2113 * If we again hit an enabled method after the new hole, it becomes
2114 * selected, as we start from scratch.
2115 */
2116 *min_version = version = 0;
2117 hole = 1;
2118 if (real_max != NULL)
2119 *real_max = 0;
2120 tmp_real_max = 0;
2121 for (vent = table; vent->version != 0; ++vent) {
2122 /*
2123 * A table entry with a NULL client method is still a hole in the
2124 * "version capability" vector.
2125 */
2126 if (vent->cmeth == NULL) {
2127 hole = 1;
2128 tmp_real_max = 0;
2129 continue;
2130 }
2131 method = vent->cmeth();
2132
2133 if (hole == 1 && tmp_real_max == 0)
2134 tmp_real_max = vent->version;
2135
2136 if (ssl_method_error(s, method) != 0) {
2137 hole = 1;
2138 } else if (!hole) {
2139 single = NULL;
2140 *min_version = method->version;
2141 } else {
2142 if (real_max != NULL && tmp_real_max != 0)
2143 *real_max = tmp_real_max;
2144 version = (single = method)->version;
2145 *min_version = version;
2146 hole = 0;
2147 }
2148 }
2149
2150 *max_version = version;
2151
2152 /* Fail if everything is disabled */
2153 if (version == 0)
2154 return SSL_R_NO_PROTOCOLS_AVAILABLE;
2155
2156 return 0;
2157 }
2158
2159 /*
2160 * ssl_set_client_hello_version - Work out what version we should be using for
2161 * the initial ClientHello.legacy_version field.
2162 *
2163 * @s: client SSL handle.
2164 *
2165 * Returns 0 on success or an SSL error reason number on failure.
2166 */
ssl_set_client_hello_version(SSL * s)2167 int ssl_set_client_hello_version(SSL *s)
2168 {
2169 int ver_min, ver_max, ret;
2170
2171 /*
2172 * In a renegotiation we always send the same client_version that we sent
2173 * last time, regardless of which version we eventually negotiated.
2174 */
2175 if (!SSL_IS_FIRST_HANDSHAKE(s))
2176 return 0;
2177
2178 ret = ssl_get_min_max_version(s, &ver_min, &ver_max, NULL);
2179
2180 if (ret != 0)
2181 return ret;
2182
2183 s->version = ver_max;
2184
2185 /* TLS1.3 always uses TLS1.2 in the legacy_version field */
2186 if (!SSL_IS_DTLS(s) && ver_max > TLS1_2_VERSION)
2187 ver_max = TLS1_2_VERSION;
2188
2189 s->client_version = ver_max;
2190 return 0;
2191 }
2192
2193 /*
2194 * Checks a list of |groups| to determine if the |group_id| is in it. If it is
2195 * and |checkallow| is 1 then additionally check if the group is allowed to be
2196 * used. Returns 1 if the group is in the list (and allowed if |checkallow| is
2197 * 1) or 0 otherwise.
2198 */
check_in_list(SSL * s,uint16_t group_id,const uint16_t * groups,size_t num_groups,int checkallow)2199 int check_in_list(SSL *s, uint16_t group_id, const uint16_t *groups,
2200 size_t num_groups, int checkallow)
2201 {
2202 size_t i;
2203
2204 if (groups == NULL || num_groups == 0)
2205 return 0;
2206
2207 for (i = 0; i < num_groups; i++) {
2208 uint16_t group = groups[i];
2209
2210 if (group_id == group
2211 && (!checkallow
2212 || tls_group_allowed(s, group, SSL_SECOP_CURVE_CHECK))) {
2213 return 1;
2214 }
2215 }
2216
2217 return 0;
2218 }
2219
2220 /* Replace ClientHello1 in the transcript hash with a synthetic message */
create_synthetic_message_hash(SSL * s,const unsigned char * hashval,size_t hashlen,const unsigned char * hrr,size_t hrrlen)2221 int create_synthetic_message_hash(SSL *s, const unsigned char *hashval,
2222 size_t hashlen, const unsigned char *hrr,
2223 size_t hrrlen)
2224 {
2225 unsigned char hashvaltmp[EVP_MAX_MD_SIZE];
2226 unsigned char msghdr[SSL3_HM_HEADER_LENGTH];
2227
2228 memset(msghdr, 0, sizeof(msghdr));
2229
2230 if (hashval == NULL) {
2231 hashval = hashvaltmp;
2232 hashlen = 0;
2233 /* Get the hash of the initial ClientHello */
2234 if (!ssl3_digest_cached_records(s, 0)
2235 || !ssl_handshake_hash(s, hashvaltmp, sizeof(hashvaltmp),
2236 &hashlen)) {
2237 /* SSLfatal() already called */
2238 return 0;
2239 }
2240 }
2241
2242 /* Reinitialise the transcript hash */
2243 if (!ssl3_init_finished_mac(s)) {
2244 /* SSLfatal() already called */
2245 return 0;
2246 }
2247
2248 /* Inject the synthetic message_hash message */
2249 msghdr[0] = SSL3_MT_MESSAGE_HASH;
2250 msghdr[SSL3_HM_HEADER_LENGTH - 1] = (unsigned char)hashlen;
2251 if (!ssl3_finish_mac(s, msghdr, SSL3_HM_HEADER_LENGTH)
2252 || !ssl3_finish_mac(s, hashval, hashlen)) {
2253 /* SSLfatal() already called */
2254 return 0;
2255 }
2256
2257 /*
2258 * Now re-inject the HRR and current message if appropriate (we just deleted
2259 * it when we reinitialised the transcript hash above). Only necessary after
2260 * receiving a ClientHello2 with a cookie.
2261 */
2262 if (hrr != NULL
2263 && (!ssl3_finish_mac(s, hrr, hrrlen)
2264 || !ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
2265 s->s3.tmp.message_size
2266 + SSL3_HM_HEADER_LENGTH))) {
2267 /* SSLfatal() already called */
2268 return 0;
2269 }
2270
2271 return 1;
2272 }
2273
ca_dn_cmp(const X509_NAME * const * a,const X509_NAME * const * b)2274 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
2275 {
2276 return X509_NAME_cmp(*a, *b);
2277 }
2278
parse_ca_names(SSL * s,PACKET * pkt)2279 int parse_ca_names(SSL *s, PACKET *pkt)
2280 {
2281 STACK_OF(X509_NAME) *ca_sk = sk_X509_NAME_new(ca_dn_cmp);
2282 X509_NAME *xn = NULL;
2283 PACKET cadns;
2284
2285 if (ca_sk == NULL) {
2286 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
2287 goto err;
2288 }
2289 /* get the CA RDNs */
2290 if (!PACKET_get_length_prefixed_2(pkt, &cadns)) {
2291 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2292 goto err;
2293 }
2294
2295 while (PACKET_remaining(&cadns)) {
2296 const unsigned char *namestart, *namebytes;
2297 unsigned int name_len;
2298
2299 if (!PACKET_get_net_2(&cadns, &name_len)
2300 || !PACKET_get_bytes(&cadns, &namebytes, name_len)) {
2301 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2302 goto err;
2303 }
2304
2305 namestart = namebytes;
2306 if ((xn = d2i_X509_NAME(NULL, &namebytes, name_len)) == NULL) {
2307 SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_ASN1_LIB);
2308 goto err;
2309 }
2310 if (namebytes != (namestart + name_len)) {
2311 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CA_DN_LENGTH_MISMATCH);
2312 goto err;
2313 }
2314
2315 if (!sk_X509_NAME_push(ca_sk, xn)) {
2316 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
2317 goto err;
2318 }
2319 xn = NULL;
2320 }
2321
2322 sk_X509_NAME_pop_free(s->s3.tmp.peer_ca_names, X509_NAME_free);
2323 s->s3.tmp.peer_ca_names = ca_sk;
2324
2325 return 1;
2326
2327 err:
2328 sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
2329 X509_NAME_free(xn);
2330 return 0;
2331 }
2332
STACK_OF(X509_NAME)2333 const STACK_OF(X509_NAME) *get_ca_names(SSL *s)
2334 {
2335 const STACK_OF(X509_NAME) *ca_sk = NULL;;
2336
2337 if (s->server) {
2338 ca_sk = SSL_get_client_CA_list(s);
2339 if (ca_sk != NULL && sk_X509_NAME_num(ca_sk) == 0)
2340 ca_sk = NULL;
2341 }
2342
2343 if (ca_sk == NULL)
2344 ca_sk = SSL_get0_CA_list(s);
2345
2346 return ca_sk;
2347 }
2348
construct_ca_names(SSL * s,const STACK_OF (X509_NAME)* ca_sk,WPACKET * pkt)2349 int construct_ca_names(SSL *s, const STACK_OF(X509_NAME) *ca_sk, WPACKET *pkt)
2350 {
2351 /* Start sub-packet for client CA list */
2352 if (!WPACKET_start_sub_packet_u16(pkt)) {
2353 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2354 return 0;
2355 }
2356
2357 if ((ca_sk != NULL) && !(s->options & SSL_OP_DISABLE_TLSEXT_CA_NAMES)) {
2358 int i;
2359
2360 for (i = 0; i < sk_X509_NAME_num(ca_sk); i++) {
2361 unsigned char *namebytes;
2362 X509_NAME *name = sk_X509_NAME_value(ca_sk, i);
2363 int namelen;
2364
2365 if (name == NULL
2366 || (namelen = i2d_X509_NAME(name, NULL)) < 0
2367 || !WPACKET_sub_allocate_bytes_u16(pkt, namelen,
2368 &namebytes)
2369 || i2d_X509_NAME(name, &namebytes) != namelen) {
2370 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2371 return 0;
2372 }
2373 }
2374 }
2375
2376 if (!WPACKET_close(pkt)) {
2377 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2378 return 0;
2379 }
2380
2381 return 1;
2382 }
2383
2384 /* Create a buffer containing data to be signed for server key exchange */
construct_key_exchange_tbs(SSL * s,unsigned char ** ptbs,const void * param,size_t paramlen)2385 size_t construct_key_exchange_tbs(SSL *s, unsigned char **ptbs,
2386 const void *param, size_t paramlen)
2387 {
2388 size_t tbslen = 2 * SSL3_RANDOM_SIZE + paramlen;
2389 unsigned char *tbs = OPENSSL_malloc(tbslen);
2390
2391 if (tbs == NULL) {
2392 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
2393 return 0;
2394 }
2395 memcpy(tbs, s->s3.client_random, SSL3_RANDOM_SIZE);
2396 memcpy(tbs + SSL3_RANDOM_SIZE, s->s3.server_random, SSL3_RANDOM_SIZE);
2397
2398 memcpy(tbs + SSL3_RANDOM_SIZE * 2, param, paramlen);
2399
2400 *ptbs = tbs;
2401 return tbslen;
2402 }
2403
2404 /*
2405 * Saves the current handshake digest for Post-Handshake Auth,
2406 * Done after ClientFinished is processed, done exactly once
2407 */
tls13_save_handshake_digest_for_pha(SSL * s)2408 int tls13_save_handshake_digest_for_pha(SSL *s)
2409 {
2410 if (s->pha_dgst == NULL) {
2411 if (!ssl3_digest_cached_records(s, 1))
2412 /* SSLfatal() already called */
2413 return 0;
2414
2415 s->pha_dgst = EVP_MD_CTX_new();
2416 if (s->pha_dgst == NULL) {
2417 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2418 return 0;
2419 }
2420 if (!EVP_MD_CTX_copy_ex(s->pha_dgst,
2421 s->s3.handshake_dgst)) {
2422 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2423 EVP_MD_CTX_free(s->pha_dgst);
2424 s->pha_dgst = NULL;
2425 return 0;
2426 }
2427 }
2428 return 1;
2429 }
2430
2431 /*
2432 * Restores the Post-Handshake Auth handshake digest
2433 * Done just before sending/processing the Cert Request
2434 */
tls13_restore_handshake_digest_for_pha(SSL * s)2435 int tls13_restore_handshake_digest_for_pha(SSL *s)
2436 {
2437 if (s->pha_dgst == NULL) {
2438 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2439 return 0;
2440 }
2441 if (!EVP_MD_CTX_copy_ex(s->s3.handshake_dgst,
2442 s->pha_dgst)) {
2443 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2444 return 0;
2445 }
2446 return 1;
2447 }
2448