2 * Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
10 #include <openssl/bio.h>
11 #include <openssl/ssl.h>
12 #include <openssl/err.h>
13 #include <openssl/core_names.h>
14 #include <openssl/rand.h>
15 #include "internal/e_os.h"
16 #include "internal/packet.h"
17 #include "../../ssl_local.h"
18 #include "../record_local.h"
20 /* Protocol version specific function pointers */
21 struct record_functions_st
23 int (*set_crypto_state)(OSSL_RECORD_LAYER *rl, int level,
24 unsigned char *key, size_t keylen,
25 unsigned char *iv, size_t ivlen,
26 unsigned char *mackey, size_t mackeylen,
27 const EVP_CIPHER *ciph,
29 /* TODO(RECLAYER): This probably should not be an int */
33 /* TODO(RECLAYER): Remove me */
35 int (*cipher)(OSSL_RECORD_LAYER *rl, SSL3_RECORD *recs, size_t n_recs,
36 int sending, SSL_MAC_BUF *macs, size_t macsize,
37 /* TODO(RECLAYER): Remove me */ SSL_CONNECTION *s);
38 int (*mac)(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec, unsigned char *md,
39 int sending, /* TODO(RECLAYER): Remove me */SSL_CONNECTION *ssl);
42 struct ossl_record_layer_st
51 /* Types match the equivalent structures in the SSL object */
54 * TODO(RECLAYER): Should we take the opportunity to make this uint64_t
55 * even though upper layer continue to use uint32_t?
59 /* read IO goes into here */
61 /* each decoded record goes in here */
62 SSL3_RECORD rrec[SSL_MAX_PIPELINES];
64 /* How many records have we got available in the rrec bufer */
67 /* The record number in the rrec buffer that can be read next */
70 /* The number of records that have been released via tls_release_record */
73 /* Set to true if this is the first record in a connection */
74 unsigned int is_first_record;
76 /* where we are when reading */
79 /* used internally to point at a raw packet */
80 unsigned char *packet;
86 * Read as many input bytes as possible (for
88 * TODO(RECLAYER): Why isn't this just an option?
92 /* The number of consecutive empty records we have received */
93 size_t empty_record_count;
95 /* cryptographic state */
96 EVP_CIPHER_CTX *enc_read_ctx;
97 /* TLSv1.3 static read IV */
98 unsigned char read_iv[EVP_MAX_IV_LENGTH];
99 /* used for mac generation */
100 EVP_MD_CTX *read_hash;
104 /* Function pointers for version specific functions */
105 /* Function pointers for version specific functions */
106 struct record_functions_st *funcs;
109 # define SSL_AD_NO_ALERT -1
111 static void rlayer_fatal(OSSL_RECORD_LAYER *rl, int al, int reason,
112 const char *fmt, ...)
117 ERR_vset_error(ERR_LIB_SSL, reason, fmt, args);
124 # define RLAYERfatal(rl, al, r) RLAYERfatal_data((rl), (al), (r), NULL)
125 # define RLAYERfatal_data \
127 ERR_set_debug(OPENSSL_FILE, OPENSSL_LINE, OPENSSL_FUNC), \
130 static int tls_provider_set_tls_parameters(OSSL_RECORD_LAYER *rl,
132 const EVP_CIPHER *ciph,
137 * Provided cipher, the TLS padding/MAC removal is performed provider
138 * side so we need to tell the ctx about our TLS version and mac size
140 OSSL_PARAM params[3], *pprm = params;
144 if ((EVP_CIPHER_get_flags(ciph) & EVP_CIPH_FLAG_AEAD_CIPHER) == 0
146 * We look at s->ext.use_etm instead of SSL_READ_ETM() or
147 * SSL_WRITE_ETM() because this test applies to both reading
151 imacsize = EVP_MD_get_size(md);
153 macsize = (size_t)imacsize;
155 *pprm++ = OSSL_PARAM_construct_int(OSSL_CIPHER_PARAM_TLS_VERSION,
157 *pprm++ = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_TLS_MAC_SIZE,
159 *pprm = OSSL_PARAM_construct_end();
161 if (!EVP_CIPHER_CTX_set_params(ctx, params)) {
162 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
169 static int tls_fail_set_crypto_state(OSSL_RECORD_LAYER *rl, int level,
170 unsigned char *key, size_t keylen,
171 unsigned char *iv, size_t ivlen,
172 unsigned char *mackey, size_t mackeylen,
173 const EVP_CIPHER *ciph,
175 /* TODO(RECLAYER): This probably should not be an int */
178 const SSL_COMP *comp,
179 /* TODO(RECLAYER): Remove me */
182 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
186 static int tls_any_set_crypto_state(OSSL_RECORD_LAYER *rl, int level,
187 unsigned char *key, size_t keylen,
188 unsigned char *iv, size_t ivlen,
189 unsigned char *mackey, size_t mackeylen,
190 const EVP_CIPHER *ciph,
192 /* TODO(RECLAYER): This probably should not be an int */
195 const SSL_COMP *comp,
196 /* TODO(RECLAYER): Remove me */
199 if (level != OSSL_RECORD_PROTECTION_LEVEL_NONE) {
200 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
204 /* No crypto protection at the "NONE" level so nothing to be done */
209 /* TODO(RECLAYER): Handle OPENSSL_NO_COMP */
210 static int tls1_set_crypto_state(OSSL_RECORD_LAYER *rl, int level,
211 unsigned char *key, size_t keylen,
212 unsigned char *iv, size_t ivlen,
213 unsigned char *mackey, size_t mackeylen,
214 const EVP_CIPHER *ciph,
216 /* TODO(RECLAYER): This probably should not be an int */
219 const SSL_COMP *comp,
220 /* TODO(RECLAYER): Remove me */
223 EVP_CIPHER_CTX *ciph_ctx;
226 if (level != OSSL_RECORD_PROTECTION_LEVEL_APPLICATION)
230 s->s3.flags |= TLS1_FLAGS_ENCRYPT_THEN_MAC_READ;
232 s->s3.flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC_READ;
234 if (s->s3.tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC)
235 s->mac_flags |= SSL_MAC_FLAG_READ_MAC_STREAM;
237 s->mac_flags &= ~SSL_MAC_FLAG_READ_MAC_STREAM;
239 if (s->s3.tmp.new_cipher->algorithm2 & TLS1_TLSTREE)
240 s->mac_flags |= SSL_MAC_FLAG_READ_MAC_TLSTREE;
242 s->mac_flags &= ~SSL_MAC_FLAG_READ_MAC_TLSTREE;
244 if ((rl->enc_read_ctx = EVP_CIPHER_CTX_new()) == NULL) {
245 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
249 ciph_ctx = rl->enc_read_ctx;
251 rl->read_hash = EVP_MD_CTX_new();
252 if (rl->read_hash == NULL) {
253 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
256 #ifndef OPENSSL_NO_COMP
258 rl->expand = COMP_CTX_new(comp->method);
259 if (rl->expand == NULL) {
260 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR,
261 SSL_R_COMPRESSION_LIBRARY_ERROR);
267 * this is done by dtls1_reset_seq_numbers for DTLS
270 RECORD_LAYER_reset_read_sequence(&s->rlayer);
273 * If we have an AEAD Cipher, then there is no separate MAC, so we can skip
274 * setting up the MAC key.
276 if (!(EVP_CIPHER_get_flags(ciph) & EVP_CIPH_FLAG_AEAD_CIPHER)) {
277 if (mactype == EVP_PKEY_HMAC) {
278 mac_key = EVP_PKEY_new_raw_private_key_ex(rl->libctx, "HMAC",
283 * If its not HMAC then the only other types of MAC we support are
284 * the GOST MACs, so we need to use the old style way of creating
287 mac_key = EVP_PKEY_new_mac_key(mactype, NULL, mackey,
291 || EVP_DigestSignInit_ex(rl->read_hash, NULL, EVP_MD_get0_name(md),
292 rl->libctx, rl->propq, mac_key,
294 EVP_PKEY_free(mac_key);
295 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
298 EVP_PKEY_free(mac_key);
301 if (EVP_CIPHER_get_mode(ciph) == EVP_CIPH_GCM_MODE) {
302 if (!EVP_DecryptInit_ex(ciph_ctx, ciph, NULL, key, NULL)
303 || !EVP_CIPHER_CTX_ctrl(ciph_ctx, EVP_CTRL_GCM_SET_IV_FIXED,
305 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
308 } else if (EVP_CIPHER_get_mode(ciph) == EVP_CIPH_CCM_MODE) {
309 if (!EVP_DecryptInit_ex(ciph_ctx, ciph, NULL, NULL, NULL)
310 || !EVP_CIPHER_CTX_ctrl(ciph_ctx, EVP_CTRL_AEAD_SET_IVLEN, 12,
312 || !EVP_CIPHER_CTX_ctrl(ciph_ctx, EVP_CTRL_AEAD_SET_TAG,
314 || !EVP_CIPHER_CTX_ctrl(ciph_ctx, EVP_CTRL_CCM_SET_IV_FIXED,
317 * TODO(RECLAYER): Why do we defer setting the key until here?
318 * why not in the initial EVP_DecryptInit_ex() call?
320 || !EVP_DecryptInit_ex(ciph_ctx, NULL, NULL, key, NULL)) {
321 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
325 if (!EVP_DecryptInit_ex(ciph_ctx, ciph, NULL, key, iv)) {
326 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
330 /* Needed for "composite" AEADs, such as RC4-HMAC-MD5 */
331 if ((EVP_CIPHER_get_flags(ciph) & EVP_CIPH_FLAG_AEAD_CIPHER) != 0
333 && !EVP_CIPHER_CTX_ctrl(ciph_ctx, EVP_CTRL_AEAD_SET_MAC_KEY,
334 (int)mackeylen, mackey)) {
335 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
338 if (EVP_CIPHER_get0_provider(ciph) != NULL
339 && !tls_provider_set_tls_parameters(rl, ciph_ctx, ciph, md, s)) {
340 /* SSLfatal already called */
347 static int tls_any_cipher(OSSL_RECORD_LAYER *rl, SSL3_RECORD *recs, size_t n_recs,
348 int sending, SSL_MAC_BUF *macs, size_t macsize,
349 /* TODO(RECLAYER): Remove me */ SSL_CONNECTION *s)
353 for (ctr = 0; ctr < n_recs; ctr++) {
354 memmove(recs[ctr].data, recs[ctr].input, recs[ctr].length);
355 recs[ctr].input = recs[ctr].data;
362 #define MAX_PADDING 256
364 * tls1_cipher encrypts/decrypts |n_recs| in |recs|. Calls SSLfatal on internal
365 * error, but not otherwise. It is the responsibility of the caller to report
366 * a bad_record_mac - if appropriate (DTLS just drops the record).
369 * 0: if the record is publicly invalid, or an internal error, or AEAD
370 * decryption failed, or Encrypt-then-mac decryption failed.
371 * 1: Success or Mac-then-encrypt decryption failed (MAC will be randomised)
373 static int tls1_cipher(OSSL_RECORD_LAYER *rl, SSL3_RECORD *recs, size_t n_recs,
374 int sending, SSL_MAC_BUF *macs, size_t macsize,
375 /* TODO(RECLAYER): Remove me */ SSL_CONNECTION *s)
378 size_t reclen[SSL_MAX_PIPELINES];
379 unsigned char buf[SSL_MAX_PIPELINES][EVP_AEAD_TLS1_AAD_LEN];
380 int i, pad = 0, tmpr, provided;
381 size_t bs, ctr, padnum, loop;
382 unsigned char padval;
383 const EVP_CIPHER *enc;
384 int tlstree_enc = sending ? (s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_TLSTREE)
385 : (s->mac_flags & SSL_MAC_FLAG_READ_MAC_TLSTREE);
386 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
389 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
396 if (EVP_MD_CTX_get0_md(s->write_hash)) {
397 int n = EVP_MD_CTX_get_size(s->write_hash);
398 if (!ossl_assert(n >= 0)) {
399 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
403 ds = s->enc_write_ctx;
404 if (!ossl_assert(s->enc_write_ctx)) {
405 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
409 enc = EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx);
410 /* For TLSv1.1 and later explicit IV */
411 if (SSL_USE_EXPLICIT_IV(s)
412 && EVP_CIPHER_get_mode(enc) == EVP_CIPH_CBC_MODE)
413 ivlen = EVP_CIPHER_get_iv_length(enc);
417 for (ctr = 0; ctr < n_recs; ctr++) {
418 if (recs[ctr].data != recs[ctr].input) {
420 * we can't write into the input stream: Can this ever
423 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
425 } else if (RAND_bytes_ex(sctx->libctx, recs[ctr].input,
427 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
433 if (EVP_MD_CTX_get0_md(rl->read_hash)) {
434 int n = EVP_MD_CTX_get_size(rl->read_hash);
435 if (!ossl_assert(n >= 0)) {
436 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
440 ds = rl->enc_read_ctx;
441 if (!ossl_assert(rl->enc_read_ctx)) {
442 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
446 enc = EVP_CIPHER_CTX_get0_cipher(rl->enc_read_ctx);
449 if ((s->session == NULL) || (enc == NULL)) {
450 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
454 provided = (EVP_CIPHER_get0_provider(enc) != NULL);
456 bs = EVP_CIPHER_get_block_size(EVP_CIPHER_CTX_get0_cipher(ds));
459 if ((EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ds))
460 & EVP_CIPH_FLAG_PIPELINE) == 0) {
462 * We shouldn't have been called with pipeline data if the
463 * cipher doesn't support pipelining
465 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_PIPELINE_FAILURE);
469 for (ctr = 0; ctr < n_recs; ctr++) {
470 reclen[ctr] = recs[ctr].length;
472 if ((EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ds))
473 & EVP_CIPH_FLAG_AEAD_CIPHER) != 0) {
476 seq = sending ? RECORD_LAYER_get_write_sequence(&s->rlayer)
477 : RECORD_LAYER_get_read_sequence(&s->rlayer);
479 if (SSL_CONNECTION_IS_DTLS(s)) {
480 /* DTLS does not support pipelining */
481 unsigned char dtlsseq[8], *p = dtlsseq;
483 s2n(sending ? DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) :
484 DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer), p);
485 memcpy(p, &seq[2], 6);
486 memcpy(buf[ctr], dtlsseq, 8);
488 memcpy(buf[ctr], seq, 8);
489 for (i = 7; i >= 0; i--) { /* increment */
496 buf[ctr][8] = recs[ctr].type;
497 buf[ctr][9] = (unsigned char)(rl->version >> 8);
498 buf[ctr][10] = (unsigned char)(rl->version);
499 buf[ctr][11] = (unsigned char)(recs[ctr].length >> 8);
500 buf[ctr][12] = (unsigned char)(recs[ctr].length & 0xff);
501 pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
502 EVP_AEAD_TLS1_AAD_LEN, buf[ctr]);
504 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
510 recs[ctr].length += pad;
513 } else if ((bs != 1) && sending && !provided) {
515 * We only do this for legacy ciphers. Provided ciphers add the
516 * padding on the provider side.
518 padnum = bs - (reclen[ctr] % bs);
520 /* Add weird padding of up to 256 bytes */
522 if (padnum > MAX_PADDING) {
523 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
526 /* we need to add 'padnum' padding bytes of value padval */
527 padval = (unsigned char)(padnum - 1);
528 for (loop = reclen[ctr]; loop < reclen[ctr] + padnum; loop++)
529 recs[ctr].input[loop] = padval;
530 reclen[ctr] += padnum;
531 recs[ctr].length += padnum;
535 if (reclen[ctr] == 0 || reclen[ctr] % bs != 0) {
536 /* Publicly invalid */
542 unsigned char *data[SSL_MAX_PIPELINES];
544 /* Set the output buffers */
545 for (ctr = 0; ctr < n_recs; ctr++) {
546 data[ctr] = recs[ctr].data;
548 if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS,
549 (int)n_recs, data) <= 0) {
550 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_PIPELINE_FAILURE);
553 /* Set the input buffers */
554 for (ctr = 0; ctr < n_recs; ctr++) {
555 data[ctr] = recs[ctr].input;
557 if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_BUFS,
558 (int)n_recs, data) <= 0
559 || EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_LENS,
560 (int)n_recs, reclen) <= 0) {
561 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_PIPELINE_FAILURE);
566 if (!SSL_CONNECTION_IS_DTLS(s) && tlstree_enc) {
568 int decrement_seq = 0;
571 * When sending, seq is incremented after MAC calculation.
572 * So if we are in ETM mode, we use seq 'as is' in the ctrl-function.
573 * Otherwise we have to decrease it in the implementation
575 if (sending && !SSL_WRITE_ETM(s))
578 seq = sending ? RECORD_LAYER_get_write_sequence(&s->rlayer)
579 : RECORD_LAYER_get_read_sequence(&s->rlayer);
580 if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_TLSTREE, decrement_seq, seq) <= 0) {
581 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
589 /* Provided cipher - we do not support pipelining on this path */
591 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
595 if (!EVP_CipherUpdate(ds, recs[0].data, &outlen, recs[0].input,
596 (unsigned int)reclen[0]))
598 recs[0].length = outlen;
601 * The length returned from EVP_CipherUpdate above is the actual
602 * payload length. We need to adjust the data/input ptr to skip over
606 if (EVP_CIPHER_get_mode(enc) == EVP_CIPH_GCM_MODE) {
607 recs[0].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
608 recs[0].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
609 } else if (EVP_CIPHER_get_mode(enc) == EVP_CIPH_CCM_MODE) {
610 recs[0].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
611 recs[0].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
612 } else if (bs != 1 && SSL_USE_EXPLICIT_IV(s)) {
615 recs[0].orig_len -= bs;
618 /* Now get a pointer to the MAC (if applicable) */
620 OSSL_PARAM params[2], *p = params;
625 *p++ = OSSL_PARAM_construct_octet_ptr(OSSL_CIPHER_PARAM_TLS_MAC,
626 (void **)&macs[0].mac,
628 *p = OSSL_PARAM_construct_end();
630 if (!EVP_CIPHER_CTX_get_params(ds, params)) {
631 /* Shouldn't normally happen */
632 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR,
633 ERR_R_INTERNAL_ERROR);
641 tmpr = EVP_Cipher(ds, recs[0].data, recs[0].input,
642 (unsigned int)reclen[0]);
643 if ((EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ds))
644 & EVP_CIPH_FLAG_CUSTOM_CIPHER) != 0
647 /* AEAD can fail to verify MAC */
652 for (ctr = 0; ctr < n_recs; ctr++) {
653 /* Adjust the record to remove the explicit IV/MAC/Tag */
654 if (EVP_CIPHER_get_mode(enc) == EVP_CIPH_GCM_MODE) {
655 recs[ctr].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
656 recs[ctr].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
657 recs[ctr].length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
658 } else if (EVP_CIPHER_get_mode(enc) == EVP_CIPH_CCM_MODE) {
659 recs[ctr].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
660 recs[ctr].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
661 recs[ctr].length -= EVP_CCM_TLS_EXPLICIT_IV_LEN;
662 } else if (bs != 1 && SSL_USE_EXPLICIT_IV(s)) {
663 if (recs[ctr].length < bs)
665 recs[ctr].data += bs;
666 recs[ctr].input += bs;
667 recs[ctr].length -= bs;
668 recs[ctr].orig_len -= bs;
672 * If using Mac-then-encrypt, then this will succeed but
673 * with a random MAC if padding is invalid
675 if (!tls1_cbc_remove_padding_and_mac(&recs[ctr].length,
678 (macs != NULL) ? &macs[ctr].mac : NULL,
679 (macs != NULL) ? &macs[ctr].alloced
682 pad ? (size_t)pad : macsize,
683 (EVP_CIPHER_get_flags(enc)
684 & EVP_CIPH_FLAG_AEAD_CIPHER) != 0,
693 static int tls1_mac(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec, unsigned char *md,
694 int sending, SSL_CONNECTION *ssl)
700 EVP_MD_CTX *hmac = NULL, *mac_ctx;
701 unsigned char header[13];
702 int stream_mac = sending ? (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM)
703 : (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM);
704 int tlstree_mac = sending ? (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_TLSTREE)
705 : (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_TLSTREE);
710 seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
711 hash = ssl->write_hash;
713 seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
714 hash = rl->read_hash;
717 t = EVP_MD_CTX_get_size(hash);
718 if (!ossl_assert(t >= 0))
722 /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
726 hmac = EVP_MD_CTX_new();
727 if (hmac == NULL || !EVP_MD_CTX_copy(hmac, hash)) {
735 && EVP_MD_CTX_ctrl(mac_ctx, EVP_MD_CTRL_TLSTREE, 0, seq) <= 0) {
740 unsigned char dtlsseq[8], *p = dtlsseq;
742 s2n(sending ? DTLS_RECORD_LAYER_get_w_epoch(&ssl->rlayer) :
743 DTLS_RECORD_LAYER_get_r_epoch(&ssl->rlayer), p);
744 memcpy(p, &seq[2], 6);
746 memcpy(header, dtlsseq, 8);
748 memcpy(header, seq, 8);
750 header[8] = rec->type;
751 header[9] = (unsigned char)(ssl->version >> 8);
752 header[10] = (unsigned char)(ssl->version);
753 header[11] = (unsigned char)(rec->length >> 8);
754 header[12] = (unsigned char)(rec->length & 0xff);
756 if (!sending && !SSL_READ_ETM(ssl)
757 && EVP_CIPHER_CTX_get_mode(rl->enc_read_ctx) == EVP_CIPH_CBC_MODE
758 && ssl3_cbc_record_digest_supported(mac_ctx)) {
759 OSSL_PARAM tls_hmac_params[2], *p = tls_hmac_params;
761 *p++ = OSSL_PARAM_construct_size_t(OSSL_MAC_PARAM_TLS_DATA_SIZE,
763 *p++ = OSSL_PARAM_construct_end();
765 if (!EVP_PKEY_CTX_set_params(EVP_MD_CTX_get_pkey_ctx(mac_ctx),
771 if (EVP_DigestSignUpdate(mac_ctx, header, sizeof(header)) <= 0
772 || EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length) <= 0
773 || EVP_DigestSignFinal(mac_ctx, md, &md_size) <= 0) {
777 OSSL_TRACE_BEGIN(TLS) {
778 BIO_printf(trc_out, "seq:\n");
779 BIO_dump_indent(trc_out, seq, 8, 4);
780 BIO_printf(trc_out, "rec:\n");
781 BIO_dump_indent(trc_out, rec->data, rec->length, 4);
782 } OSSL_TRACE_END(TLS);
784 if (!SSL_CONNECTION_IS_DTLS(ssl)) {
785 for (i = 7; i >= 0; i--) {
791 OSSL_TRACE_BEGIN(TLS) {
792 BIO_printf(trc_out, "md:\n");
793 BIO_dump_indent(trc_out, md, md_size, 4);
794 } OSSL_TRACE_END(TLS);
797 EVP_MD_CTX_free(hmac);
802 struct record_functions_st tls_any_funcs = {
803 tls_any_set_crypto_state,
808 struct record_functions_st tls_1_3_funcs = {
809 tls_fail_set_crypto_state,
814 struct record_functions_st tls_1_2_funcs = {
815 tls1_set_crypto_state,
820 struct record_functions_st tls_1_1_funcs = {
821 tls1_set_crypto_state,
826 struct record_functions_st tls_1_0_funcs = {
827 tls1_set_crypto_state,
832 struct record_functions_st ssl_3_0_funcs = {
833 tls_fail_set_crypto_state,
838 static int tls_set1_bio(OSSL_RECORD_LAYER *rl, BIO *bio);
840 static int rlayer_allow_compression(OSSL_RECORD_LAYER *rl)
842 if (rl->options & SSL_OP_NO_COMPRESSION)
845 /* TODO(RECLAYER): Implement ssl_security inside the record layer */
846 return ssl_security(s, SSL_SECOP_COMPRESSION, 0, 0, NULL);
852 static int rlayer_setup_read_buffer(OSSL_RECORD_LAYER *rl)
855 size_t len, align = 0, headerlen;
861 headerlen = DTLS1_RT_HEADER_LENGTH;
863 headerlen = SSL3_RT_HEADER_LENGTH;
865 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
866 align = (-SSL3_RT_HEADER_LENGTH) & (SSL3_ALIGN_PAYLOAD - 1);
869 if (b->buf == NULL) {
870 len = SSL3_RT_MAX_PLAIN_LENGTH
871 + SSL3_RT_MAX_ENCRYPTED_OVERHEAD + headerlen + align;
872 #ifndef OPENSSL_NO_COMP
873 if (rlayer_allow_compression(rl))
874 len += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
876 if (b->default_len > len)
877 len = b->default_len;
878 if ((p = OPENSSL_malloc(len)) == NULL) {
880 * We've got a malloc failure, and we're still initialising buffers.
881 * We assume we're so doomed that we won't even be able to send an
884 RLAYERfatal(rl, SSL_AD_NO_ALERT, ERR_R_MALLOC_FAILURE);
894 static int rlayer_release_read_buffer(OSSL_RECORD_LAYER *rl)
899 if (rl->options & SSL_OP_CLEANSE_PLAINTEXT)
900 OPENSSL_cleanse(b->buf, b->len);
901 OPENSSL_free(b->buf);
906 static void tls_reset_packet_length(OSSL_RECORD_LAYER *rl)
908 rl->packet_length = 0;
912 * Return values are as per SSL_read()
914 static int tls_read_n(OSSL_RECORD_LAYER *rl, size_t n, size_t max, int extend,
915 int clearold, size_t *readbytes)
918 * If extend == 0, obtain new n-byte packet; if extend == 1, increase
919 * packet by another n bytes. The packet will be in the sub-array of
920 * s->rlayer.rbuf.buf specified by s->rlayer.packet and
921 * s->rlayer.packet_length. (If s->rlayer.read_ahead is set, 'max' bytes may
922 * be stored in rbuf [plus s->rlayer.packet_length bytes if extend == 1].)
923 * if clearold == 1, move the packet to the start of the buffer; if
924 * clearold == 0 then leave any old packets where they were
926 size_t len, left, align = 0;
931 return OSSL_RECORD_RETURN_NON_FATAL_ERR;
934 if (rb->buf == NULL) {
935 if (!rlayer_setup_read_buffer(rl)) {
936 /* RLAYERfatal() already called */
937 return OSSL_RECORD_RETURN_FATAL;
942 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
943 align = (size_t)rb->buf + SSL3_RT_HEADER_LENGTH;
944 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
948 /* start with empty packet ... */
951 } else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH) {
953 * check if next packet length is large enough to justify payload
956 pkt = rb->buf + rb->offset;
957 if (pkt[0] == SSL3_RT_APPLICATION_DATA
958 && (pkt[3] << 8 | pkt[4]) >= 128) {
960 * Note that even if packet is corrupted and its length field
961 * is insane, we can only be led to wrong decision about
962 * whether memmove will occur or not. Header values has no
963 * effect on memmove arguments and therefore no buffer
964 * overrun can be triggered.
966 memmove(rb->buf + align, pkt, left);
970 rl->packet = rb->buf + rb->offset;
971 rl->packet_length = 0;
972 /* ... now we can act as if 'extend' was set */
975 len = rl->packet_length;
976 pkt = rb->buf + align;
978 * Move any available bytes to front of buffer: 'len' bytes already
979 * pointed to by 'packet', 'left' extra ones at the end
981 if (rl->packet != pkt && clearold == 1) {
982 memmove(pkt, rl->packet, len + left);
984 rb->offset = len + align;
988 * For DTLS/UDP reads should not span multiple packets because the read
989 * operation returns the whole packet at once (as long as it fits into
993 if (left == 0 && extend)
995 if (left > 0 && n > left)
999 /* if there is enough in the buffer from a previous read, take some */
1001 rl->packet_length += n;
1002 rb->left = left - n;
1005 return OSSL_RECORD_RETURN_SUCCESS;
1008 /* else we need to read more data */
1010 if (n > rb->len - rb->offset) {
1011 /* does not happen */
1012 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1013 return OSSL_RECORD_RETURN_FATAL;
1017 * Ktls always reads full records.
1018 * Also, we always act like read_ahead is set for DTLS.
1020 if (!BIO_get_ktls_recv(s->rbio) && !rl->read_ahead
1022 /* ignore max parameter */
1027 if (max > rb->len - rb->offset)
1028 max = rb->len - rb->offset;
1036 * Now we have len+left bytes at the front of s->s3.rbuf.buf and
1037 * need to read in more until we have len+n (up to len+max if
1042 if (rl->bio != NULL) {
1043 ret = BIO_read(rl->bio, pkt + len + left, max - left);
1046 ret = OSSL_RECORD_RETURN_SUCCESS;
1047 } else if (BIO_should_retry(rl->bio)) {
1048 ret = OSSL_RECORD_RETURN_RETRY;
1049 } else if (BIO_eof(rl->bio)) {
1050 ret = OSSL_RECORD_RETURN_EOF;
1052 ret = OSSL_RECORD_RETURN_FATAL;
1055 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_READ_BIO_NOT_SET);
1056 ret = OSSL_RECORD_RETURN_FATAL;
1059 if (ret <= OSSL_RECORD_RETURN_RETRY) {
1061 if (rl->mode & SSL_MODE_RELEASE_BUFFERS && !rl->isdtls)
1062 if (len + left == 0)
1063 rlayer_release_read_buffer(rl);
1068 * reads should *never* span multiple packets for DTLS because the
1069 * underlying transport protocol is message oriented as opposed to
1070 * byte oriented as in the TLS case.
1074 n = left; /* makes the while condition false */
1078 /* done reading, now the book-keeping */
1080 rb->left = left - n;
1081 rl->packet_length += n;
1083 return OSSL_RECORD_RETURN_SUCCESS;
1087 * Peeks ahead into "read_ahead" data to see if we have a whole record waiting
1088 * for us in the buffer.
1090 static int tls_record_app_data_waiting(OSSL_RECORD_LAYER *rl)
1098 p = SSL3_BUFFER_get_buf(rbuf);
1102 left = SSL3_BUFFER_get_left(rbuf);
1104 if (left < SSL3_RT_HEADER_LENGTH)
1107 p += SSL3_BUFFER_get_offset(rbuf);
1110 * We only check the type and record length, we will sanity check version
1113 if (*p != SSL3_RT_APPLICATION_DATA)
1119 if (left < SSL3_RT_HEADER_LENGTH + len)
1126 * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
1127 * will be processed per call to ssl3_get_record. Without this limit an
1128 * attacker could send empty records at a faster rate than we can process and
1129 * cause ssl3_get_record to loop forever.
1131 #define MAX_EMPTY_RECORDS 32
1133 #define SSL2_RT_HEADER_LENGTH 2
1136 * Call this to buffer new input records in rl->rrec.
1137 * It will return a OSSL_RECORD_RETURN_* value.
1138 * When it finishes successfully (OSSL_RECORD_RETURN_SUCCESS), |rl->num_recs|
1139 * records have been decoded. For each record 'i':
1140 * rrec[i].type - is the type of record
1141 * rrec[i].data, - data
1142 * rrec[i].length, - number of bytes
1143 * Multiple records will only be returned if the record types are all
1144 * SSL3_RT_APPLICATION_DATA. The number of records returned will always be <=
1147 static int tls_get_more_records(OSSL_RECORD_LAYER *rl,
1148 /* TODO(RECLAYER): Remove me */ SSL_CONNECTION *s)
1153 SSL3_RECORD *rr, *thisrr;
1157 unsigned char md[EVP_MAX_MD_SIZE];
1158 unsigned int version;
1159 size_t mac_size = 0;
1161 size_t num_recs = 0, max_recs, j;
1162 PACKET pkt, sslv2pkt;
1164 SSL_MAC_BUF *macbufs = NULL;
1165 int ret = OSSL_RECORD_RETURN_FATAL;
1166 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1171 max_recs = s->max_pipelines;
1177 * KTLS reads full records. If there is any data left,
1178 * then it is from before enabling ktls.
1180 using_ktls = BIO_get_ktls_recv(rl->bio) && SSL3_BUFFER_get_left(rbuf) == 0;
1183 thisrr = &rr[num_recs];
1185 /* check if we have the header */
1186 if ((rl->rstate != SSL_ST_READ_BODY) ||
1187 (rl->packet_length < SSL3_RT_HEADER_LENGTH)) {
1191 rret = tls_read_n(rl, SSL3_RT_HEADER_LENGTH,
1192 SSL3_BUFFER_get_len(rbuf), 0,
1193 num_recs == 0 ? 1 : 0, &n);
1195 if (rret < OSSL_RECORD_RETURN_SUCCESS) {
1196 #ifndef OPENSSL_NO_KTLS
1197 if (!BIO_get_ktls_recv(rl->bio) || rret == 0)
1198 return rret; /* error or non-blocking */
1201 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
1202 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
1205 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
1206 SSL_R_PACKET_LENGTH_TOO_LONG);
1209 RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION,
1210 SSL_R_WRONG_VERSION_NUMBER);
1218 rl->rstate = SSL_ST_READ_BODY;
1221 if (!PACKET_buf_init(&pkt, p, rl->packet_length)) {
1222 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1223 return OSSL_RECORD_RETURN_FATAL;
1226 if (!PACKET_get_net_2_len(&sslv2pkt, &sslv2len)
1227 || !PACKET_get_1(&sslv2pkt, &type)) {
1228 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
1229 return OSSL_RECORD_RETURN_FATAL;
1232 * The first record received by the server may be a V2ClientHello.
1234 if (rl->role == OSSL_RECORD_ROLE_SERVER
1235 && rl->is_first_record
1236 && (sslv2len & 0x8000) != 0
1237 && (type == SSL2_MT_CLIENT_HELLO)) {
1239 * SSLv2 style record
1241 * |num_recs| here will actually always be 0 because
1242 * |num_recs > 0| only ever occurs when we are processing
1243 * multiple app data records - which we know isn't the case here
1244 * because it is an SSLv2ClientHello. We keep it using
1245 * |num_recs| for the sake of consistency
1247 thisrr->type = SSL3_RT_HANDSHAKE;
1248 thisrr->rec_version = SSL2_VERSION;
1250 thisrr->length = sslv2len & 0x7fff;
1252 if (thisrr->length > SSL3_BUFFER_get_len(rbuf)
1253 - SSL2_RT_HEADER_LENGTH) {
1254 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
1255 SSL_R_PACKET_LENGTH_TOO_LONG);
1256 return OSSL_RECORD_RETURN_FATAL;
1259 if (thisrr->length < MIN_SSL2_RECORD_LEN) {
1260 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
1261 return OSSL_RECORD_RETURN_FATAL;
1264 /* SSLv3+ style record */
1266 /* Pull apart the header into the SSL3_RECORD */
1267 if (!PACKET_get_1(&pkt, &type)
1268 || !PACKET_get_net_2(&pkt, &version)
1269 || !PACKET_get_net_2_len(&pkt, &thisrr->length)) {
1270 if (s->msg_callback)
1271 s->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, ssl,
1272 s->msg_callback_arg);
1273 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
1274 return OSSL_RECORD_RETURN_FATAL;
1276 thisrr->type = type;
1277 thisrr->rec_version = version;
1279 if (s->msg_callback)
1280 s->msg_callback(0, version, SSL3_RT_HEADER, p, 5, ssl,
1281 s->msg_callback_arg);
1284 * Lets check version. In TLSv1.3 we only check this field
1285 * when encryption is occurring (see later check). For the
1286 * ServerHello after an HRR we haven't actually selected TLSv1.3
1287 * yet, but we still treat it as TLSv1.3, so we must check for
1290 if (!s->first_packet && !SSL_CONNECTION_IS_TLS13(s)
1291 && s->hello_retry_request != SSL_HRR_PENDING
1292 && version != (unsigned int)s->version) {
1293 if ((s->version & 0xFF00) == (version & 0xFF00)
1294 && !s->enc_write_ctx && !s->write_hash) {
1295 if (thisrr->type == SSL3_RT_ALERT) {
1297 * The record is using an incorrect version number,
1298 * but what we've got appears to be an alert. We
1299 * haven't read the body yet to check whether its a
1300 * fatal or not - but chances are it is. We probably
1301 * shouldn't send a fatal alert back. We'll just
1304 RLAYERfatal(rl, SSL_AD_NO_ALERT,
1305 SSL_R_WRONG_VERSION_NUMBER);
1306 return OSSL_RECORD_RETURN_FATAL;
1309 * Send back error using their minor version number :-)
1311 s->version = (unsigned short)version;
1313 RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION,
1314 SSL_R_WRONG_VERSION_NUMBER);
1315 return OSSL_RECORD_RETURN_FATAL;
1318 if ((version >> 8) != SSL3_VERSION_MAJOR) {
1319 if (rl->is_first_record) {
1320 /* Go back to start of packet, look at the five bytes
1323 if (HAS_PREFIX((char *)p, "GET ") ||
1324 HAS_PREFIX((char *)p, "POST ") ||
1325 HAS_PREFIX((char *)p, "HEAD ") ||
1326 HAS_PREFIX((char *)p, "PUT ")) {
1327 RLAYERfatal(rl, SSL_AD_NO_ALERT, SSL_R_HTTP_REQUEST);
1328 return OSSL_RECORD_RETURN_FATAL;
1329 } else if (HAS_PREFIX((char *)p, "CONNE")) {
1330 RLAYERfatal(rl, SSL_AD_NO_ALERT,
1331 SSL_R_HTTPS_PROXY_REQUEST);
1332 return OSSL_RECORD_RETURN_FATAL;
1335 /* Doesn't look like TLS - don't send an alert */
1336 RLAYERfatal(rl, SSL_AD_NO_ALERT,
1337 SSL_R_WRONG_VERSION_NUMBER);
1338 return OSSL_RECORD_RETURN_FATAL;
1340 RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION,
1341 SSL_R_WRONG_VERSION_NUMBER);
1342 return OSSL_RECORD_RETURN_FATAL;
1346 if (SSL_CONNECTION_IS_TLS13(s)
1347 && s->enc_read_ctx != NULL
1349 if (thisrr->type != SSL3_RT_APPLICATION_DATA
1350 && (thisrr->type != SSL3_RT_CHANGE_CIPHER_SPEC
1351 || !SSL_IS_FIRST_HANDSHAKE(s))
1352 && (thisrr->type != SSL3_RT_ALERT
1353 || s->statem.enc_read_state
1354 != ENC_READ_STATE_ALLOW_PLAIN_ALERTS)) {
1355 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
1356 SSL_R_BAD_RECORD_TYPE);
1357 return OSSL_RECORD_RETURN_FATAL;
1359 if (thisrr->rec_version != TLS1_2_VERSION) {
1360 RLAYERfatal(rl, SSL_AD_DECODE_ERROR,
1361 SSL_R_WRONG_VERSION_NUMBER);
1362 return OSSL_RECORD_RETURN_FATAL;
1366 if (thisrr->length >
1367 SSL3_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) {
1368 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
1369 SSL_R_PACKET_LENGTH_TOO_LONG);
1370 return OSSL_RECORD_RETURN_FATAL;
1374 /* now rl->rstate == SSL_ST_READ_BODY */
1377 if (SSL_CONNECTION_IS_TLS13(s)) {
1378 size_t len = SSL3_RT_MAX_TLS13_ENCRYPTED_LENGTH;
1380 /* KTLS strips the inner record type. */
1382 len = SSL3_RT_MAX_ENCRYPTED_LENGTH;
1384 if (thisrr->length > len) {
1385 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
1386 SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
1387 return OSSL_RECORD_RETURN_FATAL;
1390 size_t len = SSL3_RT_MAX_ENCRYPTED_LENGTH;
1392 #ifndef OPENSSL_NO_COMP
1394 * If OPENSSL_NO_COMP is defined then SSL3_RT_MAX_ENCRYPTED_LENGTH
1395 * does not include the compression overhead anyway.
1397 if (s->expand == NULL)
1398 len -= SSL3_RT_MAX_COMPRESSED_OVERHEAD;
1401 /* KTLS may use all of the buffer */
1403 len = SSL3_BUFFER_get_left(rbuf);
1405 if (thisrr->length > len) {
1406 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
1407 SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
1408 return OSSL_RECORD_RETURN_FATAL;
1413 * rl->rstate == SSL_ST_READ_BODY, get and decode the data. Calculate
1414 * how much more data we need to read for the rest of the record
1416 if (thisrr->rec_version == SSL2_VERSION) {
1417 more = thisrr->length + SSL2_RT_HEADER_LENGTH
1418 - SSL3_RT_HEADER_LENGTH;
1420 more = thisrr->length;
1424 /* now rl->packet_length == SSL3_RT_HEADER_LENGTH */
1426 rret = tls_read_n(rl, more, more, 1, 0, &n);
1427 if (rret < OSSL_RECORD_RETURN_SUCCESS)
1428 return rret; /* error or non-blocking io */
1431 /* set state for later operations */
1432 rl->rstate = SSL_ST_READ_HEADER;
1435 * At this point, rl->packet_length == SSL3_RT_HEADER_LENGTH
1436 * + thisrr->length, or rl->packet_length == SSL2_RT_HEADER_LENGTH
1437 * + thisrr->length and we have that many bytes in rl->packet
1439 if (thisrr->rec_version == SSL2_VERSION)
1440 thisrr->input = &(rl->packet[SSL2_RT_HEADER_LENGTH]);
1442 thisrr->input = &(rl->packet[SSL3_RT_HEADER_LENGTH]);
1445 * ok, we can now read from 'rl->packet' data into 'thisrr'.
1446 * thisrr->input points at thisrr->length bytes, which need to be copied
1447 * into thisrr->data by either the decryption or by the decompression.
1448 * When the data is 'copied' into the thisrr->data buffer,
1449 * thisrr->input will be updated to point at the new buffer
1453 * We now have - encrypted [ MAC [ compressed [ plain ] ] ]
1454 * thisrr->length bytes of encrypted compressed stuff.
1457 /* decrypt in place in 'thisrr->input' */
1458 thisrr->data = thisrr->input;
1459 thisrr->orig_len = thisrr->length;
1461 /* Mark this record as not read by upper layers yet */
1466 /* we have pulled in a full packet so zero things */
1467 tls_reset_packet_length(rl);
1468 rl->is_first_record = 0;
1469 } while (num_recs < max_recs
1470 && thisrr->type == SSL3_RT_APPLICATION_DATA
1471 && SSL_USE_EXPLICIT_IV(s)
1472 && rl->enc_read_ctx != NULL
1473 && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(rl->enc_read_ctx))
1474 & EVP_CIPH_FLAG_PIPELINE) != 0
1475 && tls_record_app_data_waiting(rl));
1478 && thisrr->type == SSL3_RT_CHANGE_CIPHER_SPEC
1479 && (SSL_CONNECTION_IS_TLS13(s) || s->hello_retry_request != SSL_HRR_NONE)
1480 && SSL_IS_FIRST_HANDSHAKE(s)) {
1482 * CCS messages must be exactly 1 byte long, containing the value 0x01
1484 if (thisrr->length != 1 || thisrr->data[0] != 0x01) {
1485 RLAYERfatal(rl, SSL_AD_ILLEGAL_PARAMETER,
1486 SSL_R_INVALID_CCS_MESSAGE);
1487 return OSSL_RECORD_RETURN_FATAL;
1490 * CCS messages are ignored in TLSv1.3. We treat it like an empty
1493 thisrr->type = SSL3_RT_HANDSHAKE;
1494 if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
1495 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
1496 SSL_R_UNEXPECTED_CCS_MESSAGE);
1497 return OSSL_RECORD_RETURN_FATAL;
1502 rl->num_released = 0;
1504 return OSSL_RECORD_RETURN_SUCCESS;
1508 goto skip_decryption;
1510 if (rl->read_hash != NULL) {
1511 const EVP_MD *tmpmd = EVP_MD_CTX_get0_md(rl->read_hash);
1513 if (tmpmd != NULL) {
1514 imac_size = EVP_MD_get_size(tmpmd);
1515 if (!ossl_assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE)) {
1516 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
1517 return OSSL_RECORD_RETURN_FATAL;
1519 mac_size = (size_t)imac_size;
1524 * If in encrypt-then-mac mode calculate mac from encrypted record. All
1525 * the details below are public so no timing details can leak.
1527 if (SSL_READ_ETM(s) && rl->read_hash) {
1530 for (j = 0; j < num_recs; j++) {
1533 if (thisrr->length < mac_size) {
1534 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
1535 return OSSL_RECORD_RETURN_FATAL;
1537 thisrr->length -= mac_size;
1538 mac = thisrr->data + thisrr->length;
1539 i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */, s);
1540 if (i == 0 || CRYPTO_memcmp(md, mac, mac_size) != 0) {
1541 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
1542 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
1543 return OSSL_RECORD_RETURN_FATAL;
1547 * We've handled the mac now - there is no MAC inside the encrypted
1554 macbufs = OPENSSL_zalloc(sizeof(*macbufs) * num_recs);
1555 if (macbufs == NULL) {
1556 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
1557 return OSSL_RECORD_RETURN_FATAL;
1562 * TODO(RECLAYER): Only call rl functions once TLSv1.3/SSLv3 is moved to new
1565 if (!SSL_CONNECTION_IS_TLS13(s))
1566 enc_err = rl->funcs->cipher(rl, rr, num_recs, 0, macbufs, mac_size, s);
1568 enc_err = ssl->method->ssl3_enc->enc(s, rr, num_recs, 0, macbufs, mac_size);
1572 * 0: if the record is publicly invalid, or an internal error, or AEAD
1573 * decryption failed, or ETM decryption failed.
1574 * 1: Success or MTE decryption failed (MAC will be randomised)
1577 if (ossl_statem_in_error(s)) {
1578 /* SSLfatal() already got called */
1581 if (num_recs == 1 && ossl_statem_skip_early_data(s)) {
1583 * Valid early_data that we cannot decrypt will fail here. We treat
1584 * it like an empty record.
1589 if (!ossl_early_data_count_ok(s, thisrr->length,
1590 EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
1591 /* SSLfatal() already called */
1599 rl->num_released = 0;
1600 RECORD_LAYER_reset_read_sequence(&s->rlayer);
1604 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
1605 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
1608 OSSL_TRACE_BEGIN(TLS) {
1609 BIO_printf(trc_out, "dec %lu\n", (unsigned long)rr[0].length);
1610 BIO_dump_indent(trc_out, rr[0].data, rr[0].length, 4);
1611 } OSSL_TRACE_END(TLS);
1613 /* r->length is now the compressed data plus mac */
1615 && (rl->enc_read_ctx != NULL)
1616 && (!SSL_READ_ETM(s) && EVP_MD_CTX_get0_md(rl->read_hash) != NULL)) {
1617 /* rl->read_hash != NULL => mac_size != -1 */
1619 for (j = 0; j < num_recs; j++) {
1620 SSL_MAC_BUF *thismb = &macbufs[j];
1623 i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */, s);
1624 if (i == 0 || thismb == NULL || thismb->mac == NULL
1625 || CRYPTO_memcmp(md, thismb->mac, (size_t)mac_size) != 0)
1627 if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
1633 if (ossl_statem_in_error(s)) {
1634 /* We already called SSLfatal() */
1638 * A separate 'decryption_failed' alert was introduced with TLS 1.0,
1639 * SSL 3.0 only has 'bad_record_mac'. But unless a decryption
1640 * failure is directly visible from the ciphertext anyway, we should
1641 * not reveal which kind of error occurred -- this might become
1642 * visible to an attacker (e.g. via a logfile)
1644 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
1645 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
1651 for (j = 0; j < num_recs; j++) {
1654 /* thisrr->length is now just compressed */
1655 if (s->expand != NULL) {
1656 if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
1657 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
1658 SSL_R_COMPRESSED_LENGTH_TOO_LONG);
1661 if (!ssl3_do_uncompress(s, thisrr)) {
1662 RLAYERfatal(rl, SSL_AD_DECOMPRESSION_FAILURE,
1663 SSL_R_BAD_DECOMPRESSION);
1668 if (SSL_CONNECTION_IS_TLS13(s)
1669 && s->enc_read_ctx != NULL
1670 && thisrr->type != SSL3_RT_ALERT) {
1672 * The following logic are irrelevant in KTLS: the kernel provides
1673 * unprotected record and thus record type represent the actual
1674 * content type, and padding is already removed and thisrr->type and
1675 * thisrr->length should have the correct values.
1680 if (thisrr->length == 0
1681 || thisrr->type != SSL3_RT_APPLICATION_DATA) {
1682 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
1683 SSL_R_BAD_RECORD_TYPE);
1687 /* Strip trailing padding */
1688 for (end = thisrr->length - 1; end > 0 && thisrr->data[end] == 0;
1692 thisrr->length = end;
1693 thisrr->type = thisrr->data[end];
1695 if (thisrr->type != SSL3_RT_APPLICATION_DATA
1696 && thisrr->type != SSL3_RT_ALERT
1697 && thisrr->type != SSL3_RT_HANDSHAKE) {
1698 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_RECORD_TYPE);
1701 if (s->msg_callback)
1702 s->msg_callback(0, s->version, SSL3_RT_INNER_CONTENT_TYPE,
1703 &thisrr->type, 1, ssl, s->msg_callback_arg);
1707 * TLSv1.3 alert and handshake records are required to be non-zero in
1710 if (SSL_CONNECTION_IS_TLS13(s)
1711 && (thisrr->type == SSL3_RT_HANDSHAKE
1712 || thisrr->type == SSL3_RT_ALERT)
1713 && thisrr->length == 0) {
1714 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_LENGTH);
1719 * Usually thisrr->length is the length of a single record, but when
1720 * KTLS handles the decryption, thisrr->length may be larger than
1721 * SSL3_RT_MAX_PLAIN_LENGTH because the kernel may have coalesced
1723 * Therefore we have to rely on KTLS to check the plaintext length
1724 * limit in the kernel.
1726 if (thisrr->length > SSL3_RT_MAX_PLAIN_LENGTH && !using_ktls) {
1727 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
1732 * Check if the received packet overflows the current
1733 * Max Fragment Length setting.
1734 * Note: USE_MAX_FRAGMENT_LENGTH_EXT and KTLS are mutually exclusive.
1736 if (s->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(s->session)
1737 && thisrr->length > GET_MAX_FRAGMENT_LENGTH(s->session)) {
1738 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
1744 * So at this point the following is true
1745 * thisrr->type is the type of record
1746 * thisrr->length == number of bytes in record
1747 * thisrr->off == offset to first valid byte
1748 * thisrr->data == where to take bytes from, increment after use :-).
1751 /* just read a 0 length packet */
1752 if (thisrr->length == 0) {
1753 if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
1754 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_RECORD_TOO_SMALL);
1758 rl->empty_record_count = 0;
1762 if (s->early_data_state == SSL_EARLY_DATA_READING) {
1764 if (thisrr->type == SSL3_RT_APPLICATION_DATA
1765 && !ossl_early_data_count_ok(s, thisrr->length, 0, 0)) {
1766 /* SSLfatal already called */
1771 rl->num_recs = num_recs;
1773 rl->num_released = 0;
1774 ret = OSSL_RECORD_RETURN_SUCCESS;
1776 if (macbufs != NULL) {
1777 for (j = 0; j < num_recs; j++) {
1778 if (macbufs[j].alloced)
1779 OPENSSL_free(macbufs[j].mac);
1781 OPENSSL_free(macbufs);
1786 static int tls_read_record(OSSL_RECORD_LAYER *rl, void **rechandle,
1787 int *rversion, int *type, unsigned char **data,
1788 size_t *datalen, uint16_t *epoch,
1789 unsigned char *seq_num,
1790 /* TODO(RECLAYER): Remove me */ SSL_CONNECTION *s)
1795 * tls_get_more_records() can return success without actually reading
1796 * anything useful (i.e. if empty records are read). We loop here until
1797 * we have something useful. tls_get_more_records() will eventually fail if
1798 * too many sequential empty records are read.
1800 while (rl->curr_rec >= rl->num_recs) {
1803 if (rl->num_released != rl->num_recs) {
1804 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_RECORDS_NOT_RELEASED);
1805 return OSSL_RECORD_RETURN_FATAL;
1808 ret = tls_get_more_records(rl, s);
1810 if (ret != OSSL_RECORD_RETURN_SUCCESS)
1815 * We have now got rl->num_recs records buffered in rl->rrec. rl->curr_rec
1816 * points to the next one to read.
1818 rec = &rl->rrec[rl->curr_rec++];
1821 *rversion = rec->rec_version;
1824 *datalen = rec->length;
1826 return OSSL_RECORD_RETURN_SUCCESS;
1829 static int tls_release_record(OSSL_RECORD_LAYER *rl, void *rechandle)
1831 if (!ossl_assert(rl->num_released < rl->curr_rec)
1832 || !ossl_assert(rechandle == &rl->rrec[rl->num_released])) {
1833 /* Should not happen */
1834 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_INVALID_RECORD);
1835 return OSSL_RECORD_RETURN_FATAL;
1840 return OSSL_RECORD_RETURN_SUCCESS;
1843 static OSSL_RECORD_LAYER *tls_new_record_layer(OSSL_LIB_CTX *libctx,
1844 const char *propq, int vers,
1845 int role, int direction,
1846 int level, unsigned char *key,
1850 unsigned char *mackey,
1852 const EVP_CIPHER *ciph,
1854 /* TODO(RECLAYER): This probably should not be an int */
1857 const SSL_COMP *comp,
1858 BIO *transport, BIO_ADDR *local,
1860 const OSSL_PARAM *settings,
1861 const OSSL_PARAM *options,
1862 /* TODO(RECLAYER): Remove me */
1865 OSSL_RECORD_LAYER *rl = OPENSSL_zalloc(sizeof(*rl));
1866 const OSSL_PARAM *p;
1869 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
1873 if (transport != NULL && !BIO_up_ref(transport)) {
1874 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
1878 p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS);
1879 if (p != NULL && !OSSL_PARAM_get_uint64(p, &rl->options)) {
1880 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_FAILED_TO_GET_PARAMETER);
1884 p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE);
1885 if (p != NULL && !OSSL_PARAM_get_uint32(p, &rl->mode)) {
1886 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_FAILED_TO_GET_PARAMETER);
1891 p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD);
1892 if (p != NULL && !OSSL_PARAM_get_int(p, &rl->read_ahead)) {
1893 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_FAILED_TO_GET_PARAMETER);
1897 rl->libctx = libctx;
1902 rl->direction = direction;
1905 rl->is_first_record = 1;
1907 if (!tls_set1_bio(rl, transport))
1911 case TLS_ANY_VERSION:
1912 rl->funcs = &tls_any_funcs;
1914 case TLS1_3_VERSION:
1915 rl->funcs = &tls_1_3_funcs;
1917 case TLS1_2_VERSION:
1918 rl->funcs = &tls_1_2_funcs;
1920 case TLS1_1_VERSION:
1921 rl->funcs = &tls_1_1_funcs;
1924 rl->funcs = &tls_1_0_funcs;
1927 rl->funcs = &ssl_3_0_funcs;
1930 /* Should not happen */
1931 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1935 if (!rl->funcs->set_crypto_state(rl, level, key, keylen, iv, ivlen,
1936 mackey, mackeylen, ciph, taglen,
1937 mactype, md, comp, s)) {
1938 /* RLAYERfatal already called */
1948 static OSSL_RECORD_LAYER *dtls_new_record_layer(OSSL_LIB_CTX *libctx,
1949 const char *propq, int vers,
1950 int role, int direction,
1951 int level, unsigned char *key,
1955 unsigned char *mackey,
1957 const EVP_CIPHER *ciph,
1959 /* TODO(RECLAYER): This probably should not be an int */
1962 const SSL_COMP *comp,
1963 BIO *transport, BIO_ADDR *local,
1965 const OSSL_PARAM *settings,
1966 const OSSL_PARAM *options,
1967 /* TODO(RECLAYER): Remove me */
1970 OSSL_RECORD_LAYER *rl = tls_new_record_layer(libctx, propq, vers, role,
1971 direction, level, key, keylen,
1972 iv, ivlen, mackey, mackeylen,
1973 ciph, taglen, mactype, md,
1974 comp, transport, local, peer,
1975 settings, options, s);
1985 static void tls_free(OSSL_RECORD_LAYER *rl)
1991 static int tls_reset(OSSL_RECORD_LAYER *rl)
1993 memset(rl, 0, sizeof(*rl));
1997 static int tls_unprocessed_read_pending(OSSL_RECORD_LAYER *rl)
1999 return SSL3_BUFFER_get_left(&rl->rbuf) != 0;;
2002 static int tls_processed_read_pending(OSSL_RECORD_LAYER *rl)
2004 return rl->curr_rec < rl->num_recs;
2007 static size_t tls_app_data_pending(OSSL_RECORD_LAYER *rl)
2012 static int tls_write_pending(OSSL_RECORD_LAYER *rl)
2017 static size_t tls_get_max_record_len(OSSL_RECORD_LAYER *rl)
2022 static size_t tls_get_max_records(OSSL_RECORD_LAYER *rl)
2027 static int tls_write_records(OSSL_RECORD_LAYER *rl,
2028 OSSL_RECORD_TEMPLATE **templates, size_t numtempl,
2029 size_t allowance, size_t *sent)
2034 static int tls_retry_write_records(OSSL_RECORD_LAYER *rl, size_t allowance,
2041 static int tls_get_alert_code(OSSL_RECORD_LAYER *rl)
2046 static int tls_set1_bio(OSSL_RECORD_LAYER *rl, BIO *bio)
2048 if (bio != NULL && !BIO_up_ref(bio))
2056 static SSL3_BUFFER *tls_get0_rbuf(OSSL_RECORD_LAYER *rl)
2061 static unsigned char *tls_get0_packet(OSSL_RECORD_LAYER *rl)
2066 static void tls_set0_packet(OSSL_RECORD_LAYER *rl, unsigned char *packet,
2069 rl->packet = packet;
2070 rl->packet_length = packetlen;
2073 static size_t tls_get_packet_length(OSSL_RECORD_LAYER *rl)
2075 return rl->packet_length;
2078 const OSSL_RECORD_METHOD ossl_tls_record_method = {
2079 tls_new_record_layer,
2082 tls_unprocessed_read_pending,
2083 tls_processed_read_pending,
2084 tls_app_data_pending,
2086 tls_get_max_record_len,
2087 tls_get_max_records,
2089 tls_retry_write_records,
2096 * TODO(RECLAYER): Remove these. These function pointers are temporary hacks
2097 * during the record layer refactoring. They need to be removed before the
2098 * refactor is complete.
2104 tls_get_packet_length,
2105 tls_reset_packet_length
2108 const OSSL_RECORD_METHOD ossl_dtls_record_method = {
2109 dtls_new_record_layer,
2112 tls_unprocessed_read_pending,
2113 tls_processed_read_pending,
2114 tls_app_data_pending,
2116 tls_get_max_record_len,
2117 tls_get_max_records,
2119 tls_retry_write_records,
2126 * TODO(RECLAYER): Remove these. These function pointers are temporary hacks
2127 * during the record layer refactoring. They need to be removed before the
2128 * refactor is complete.
2134 tls_get_packet_length,
2135 tls_reset_packet_length