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