2 * Copyright 2018-2023 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
11 #include "../../ssl_local.h"
12 #include "../record_local.h"
13 #include "recmethod_local.h"
15 /* mod 128 saturating subtract of two 64-bit values in big-endian order */
16 static int satsub64be(const unsigned char *v1, const unsigned char *v2)
26 /* We do not permit wrap-around */
27 if (l1 > l2 && ret < 0)
29 else if (l2 > l1 && ret > 0)
40 static int dtls_record_replay_check(OSSL_RECORD_LAYER *rl, DTLS_BITMAP *bitmap)
44 const unsigned char *seq = rl->sequence;
46 cmp = satsub64be(seq, bitmap->max_seq_num);
48 ossl_tls_rl_record_set_seq_num(&rl->rrec[0], seq);
49 return 1; /* this record in new */
52 if (shift >= sizeof(bitmap->map) * 8)
53 return 0; /* stale, outside the window */
54 else if (bitmap->map & ((uint64_t)1 << shift))
55 return 0; /* record previously received */
57 ossl_tls_rl_record_set_seq_num(&rl->rrec[0], seq);
61 static void dtls_record_bitmap_update(OSSL_RECORD_LAYER *rl,
66 const unsigned char *seq = rl->sequence;
68 cmp = satsub64be(seq, bitmap->max_seq_num);
71 if (shift < sizeof(bitmap->map) * 8)
72 bitmap->map <<= shift, bitmap->map |= 1UL;
75 memcpy(bitmap->max_seq_num, seq, SEQ_NUM_SIZE);
78 if (shift < sizeof(bitmap->map) * 8)
79 bitmap->map |= (uint64_t)1 << shift;
83 static DTLS_BITMAP *dtls_get_bitmap(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rr,
84 unsigned int *is_next_epoch)
88 /* In current epoch, accept HM, CCS, DATA, & ALERT */
89 if (rr->epoch == rl->epoch)
93 * Check if the message is from the next epoch
95 else if (rr->epoch == rl->epoch + 1) {
97 return &rl->next_bitmap;
103 static void dtls_set_in_init(OSSL_RECORD_LAYER *rl, int in_init)
105 rl->in_init = in_init;
108 static int dtls_process_record(OSSL_RECORD_LAYER *rl, DTLS_BITMAP *bitmap)
115 unsigned char md[EVP_MAX_MD_SIZE];
116 SSL_MAC_BUF macbuf = { NULL, 0 };
122 * At this point, rl->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length,
123 * and we have that many bytes in rl->packet
125 rr->input = &(rl->packet[DTLS1_RT_HEADER_LENGTH]);
128 * ok, we can now read from 'rl->packet' data into 'rr'. rr->input
129 * points at rr->length bytes, which need to be copied into rr->data by
130 * either the decryption or by the decompression. When the data is 'copied'
131 * into the rr->data buffer, rr->input will be pointed at the new buffer
135 * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
136 * bytes of encrypted compressed stuff.
139 /* check is not needed I believe */
140 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
141 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
145 /* decrypt in place in 'rr->input' */
146 rr->data = rr->input;
147 rr->orig_len = rr->length;
149 if (rl->md_ctx != NULL) {
150 const EVP_MD *tmpmd = EVP_MD_CTX_get0_md(rl->md_ctx);
153 imac_size = EVP_MD_get_size(tmpmd);
154 if (!ossl_assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE)) {
155 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
158 mac_size = (size_t)imac_size;
162 if (rl->use_etm && rl->md_ctx != NULL) {
165 if (rr->orig_len < mac_size) {
166 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
169 rr->length -= mac_size;
170 mac = rr->data + rr->length;
171 i = rl->funcs->mac(rl, rr, md, 0 /* not send */);
172 if (i == 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
173 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
174 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
178 * We've handled the mac now - there is no MAC inside the encrypted
185 * Set a mark around the packet decryption attempt. This is DTLS, so
186 * bad packets are just ignored, and we don't want to leave stray
187 * errors in the queue from processing bogus junk that we ignored.
190 enc_err = rl->funcs->cipher(rl, rr, 1, 0, &macbuf, mac_size);
194 * 0: if the record is publicly invalid, or an internal error, or AEAD
195 * decryption failed, or ETM decryption failed.
196 * 1: Success or MTE decryption failed (MAC will be randomised)
200 if (rl->alert != SSL_AD_NO_ALERT) {
201 /* RLAYERfatal() already called */
204 /* For DTLS we simply ignore bad packets. */
206 rl->packet_length = 0;
209 ERR_clear_last_mark();
210 OSSL_TRACE_BEGIN(TLS) {
211 BIO_printf(trc_out, "dec %zd\n", rr->length);
212 BIO_dump_indent(trc_out, rr->data, rr->length, 4);
213 } OSSL_TRACE_END(TLS);
215 /* r->length is now the compressed data plus mac */
217 && (rl->enc_ctx != NULL)
218 && (EVP_MD_CTX_get0_md(rl->md_ctx) != NULL)) {
219 /* rl->md_ctx != NULL => mac_size != -1 */
221 i = rl->funcs->mac(rl, rr, md, 0 /* not send */);
222 if (i == 0 || macbuf.mac == NULL
223 || CRYPTO_memcmp(md, macbuf.mac, mac_size) != 0)
225 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
230 /* decryption failed, silently discard message */
232 rl->packet_length = 0;
236 /* r->length is now just compressed */
237 if (rl->compctx != NULL) {
238 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
239 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
240 SSL_R_COMPRESSED_LENGTH_TOO_LONG);
243 if (!tls_do_uncompress(rl, rr)) {
244 RLAYERfatal(rl, SSL_AD_DECOMPRESSION_FAILURE, SSL_R_BAD_DECOMPRESSION);
250 * Check if the received packet overflows the current Max Fragment
253 if (rr->length > rl->max_frag_len) {
254 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
260 * So at this point the following is true
261 * ssl->s3.rrec.type is the type of record
262 * ssl->s3.rrec.length == number of bytes in record
263 * ssl->s3.rrec.off == offset to first valid byte
264 * ssl->s3.rrec.data == where to take bytes from, increment
268 /* we have pulled in a full packet so zero things */
269 rl->packet_length = 0;
271 /* Mark receipt of record. */
272 dtls_record_bitmap_update(rl, bitmap);
277 OPENSSL_free(macbuf.mac);
281 static int dtls_rlayer_buffer_record(OSSL_RECORD_LAYER *rl, struct pqueue_st *queue,
282 unsigned char *priority)
284 DTLS_RLAYER_RECORD_DATA *rdata;
287 /* Limit the size of the queue to prevent DOS attacks */
288 if (pqueue_size(queue) >= 100)
291 rdata = OPENSSL_malloc(sizeof(*rdata));
292 item = pitem_new(priority, rdata);
293 if (rdata == NULL || item == NULL) {
296 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
300 rdata->packet = rl->packet;
301 rdata->packet_length = rl->packet_length;
302 memcpy(&(rdata->rbuf), &rl->rbuf, sizeof(TLS_BUFFER));
303 memcpy(&(rdata->rrec), &rl->rrec[0], sizeof(TLS_RL_RECORD));
308 rl->packet_length = 0;
309 memset(&rl->rbuf, 0, sizeof(TLS_BUFFER));
310 memset(&rl->rrec[0], 0, sizeof(rl->rrec[0]));
312 if (!tls_setup_read_buffer(rl)) {
313 /* RLAYERfatal() already called */
314 OPENSSL_free(rdata->rbuf.buf);
320 if (pqueue_insert(queue, item) == NULL) {
321 /* Must be a duplicate so ignore it */
322 OPENSSL_free(rdata->rbuf.buf);
330 /* copy buffered record into OSSL_RECORD_LAYER structure */
331 static int dtls_copy_rlayer_record(OSSL_RECORD_LAYER *rl, pitem *item)
333 DTLS_RLAYER_RECORD_DATA *rdata;
335 rdata = (DTLS_RLAYER_RECORD_DATA *)item->data;
337 ossl_tls_buffer_release(&rl->rbuf);
339 rl->packet = rdata->packet;
340 rl->packet_length = rdata->packet_length;
341 memcpy(&rl->rbuf, &(rdata->rbuf), sizeof(TLS_BUFFER));
342 memcpy(&rl->rrec[0], &(rdata->rrec), sizeof(TLS_RL_RECORD));
344 /* Set proper sequence number for mac calculation */
345 memcpy(&(rl->sequence[2]), &(rdata->packet[5]), 6);
350 static int dtls_retrieve_rlayer_buffered_record(OSSL_RECORD_LAYER *rl,
351 struct pqueue_st *queue)
355 item = pqueue_pop(queue);
357 dtls_copy_rlayer_record(rl, item);
359 OPENSSL_free(item->data);
369 * Call this to get a new input record.
370 * It will return <= 0 if more data is needed, normally due to an error
371 * or non-blocking IO.
372 * When it finishes, one packet has been decoded and can be found in
373 * ssl->s3.rrec.type - is the type of record
374 * ssl->s3.rrec.data - data
375 * ssl->s3.rrec.length - number of bytes
377 int dtls_get_more_records(OSSL_RECORD_LAYER *rl)
379 int ssl_major, ssl_minor;
383 unsigned char *p = NULL;
385 unsigned int is_next_epoch;
389 rl->num_released = 0;
393 if (rl->rbuf.buf == NULL) {
394 if (!tls_setup_read_buffer(rl)) {
395 /* RLAYERfatal() already called */
396 return OSSL_RECORD_RETURN_FATAL;
401 /* if we're renegotiating, then there may be buffered records */
402 if (dtls_retrieve_rlayer_buffered_record(rl, rl->processed_rcds)) {
404 return OSSL_RECORD_RETURN_SUCCESS;
407 /* get something from the wire */
409 /* check if we have the header */
410 if ((rl->rstate != SSL_ST_READ_BODY) ||
411 (rl->packet_length < DTLS1_RT_HEADER_LENGTH)) {
412 rret = rl->funcs->read_n(rl, DTLS1_RT_HEADER_LENGTH,
413 TLS_BUFFER_get_len(&rl->rbuf), 0, 1, &n);
414 /* read timeout is handled by dtls1_read_bytes */
415 if (rret < OSSL_RECORD_RETURN_SUCCESS) {
416 /* RLAYERfatal() already called if appropriate */
417 return rret; /* error or non-blocking */
420 /* this packet contained a partial record, dump it */
421 if (rl->packet_length != DTLS1_RT_HEADER_LENGTH) {
422 rl->packet_length = 0;
426 rl->rstate = SSL_ST_READ_BODY;
430 /* Pull apart the header into the DTLS1_RECORD */
434 rr->rec_version = (ssl_major << 8) | ssl_minor;
436 /* sequence number is 64 bits, with top 2 bytes = epoch */
439 memcpy(&(rl->sequence[2]), p, 6);
444 if (rl->msg_callback != NULL)
445 rl->msg_callback(0, rr->rec_version, SSL3_RT_HEADER, rl->packet, DTLS1_RT_HEADER_LENGTH,
449 * Lets check the version. We tolerate alerts that don't have the exact
450 * version number (e.g. because of protocol version errors)
452 if (!rl->is_first_record && rr->type != SSL3_RT_ALERT) {
453 if (rr->rec_version != rl->version) {
454 /* unexpected version, silently discard */
456 rl->packet_length = 0;
462 (rl->version == DTLS_ANY_VERSION ? DTLS1_VERSION_MAJOR
463 : rl->version >> 8)) {
464 /* wrong version, silently discard record */
466 rl->packet_length = 0;
470 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
471 /* record too long, silently discard it */
473 rl->packet_length = 0;
478 * If received packet overflows maximum possible fragment length then
479 * silently discard it
481 if (rr->length > rl->max_frag_len + SSL3_RT_MAX_ENCRYPTED_OVERHEAD) {
482 /* record too long, silently discard it */
484 rl->packet_length = 0;
488 /* now rl->rstate == SSL_ST_READ_BODY */
491 /* rl->rstate == SSL_ST_READ_BODY, get and decode the data */
493 if (rr->length > rl->packet_length - DTLS1_RT_HEADER_LENGTH) {
494 /* now rl->packet_length == DTLS1_RT_HEADER_LENGTH */
496 rret = rl->funcs->read_n(rl, more, more, 1, 1, &n);
497 /* this packet contained a partial record, dump it */
498 if (rret < OSSL_RECORD_RETURN_SUCCESS || n != more) {
499 if (rl->alert != SSL_AD_NO_ALERT) {
500 /* read_n() called RLAYERfatal() */
501 return OSSL_RECORD_RETURN_FATAL;
504 rl->packet_length = 0;
509 * now n == rr->length,
510 * and rl->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length
513 /* set state for later operations */
514 rl->rstate = SSL_ST_READ_HEADER;
516 /* match epochs. NULL means the packet is dropped on the floor */
517 bitmap = dtls_get_bitmap(rl, rr, &is_next_epoch);
518 if (bitmap == NULL) {
520 rl->packet_length = 0; /* dump this record */
521 goto again; /* get another record */
523 #ifndef OPENSSL_NO_SCTP
524 /* Only do replay check if no SCTP bio */
525 if (!BIO_dgram_is_sctp(rl->bio)) {
527 /* Check whether this is a repeat, or aged record. */
528 if (!dtls_record_replay_check(rl, bitmap)) {
530 rl->packet_length = 0; /* dump this record */
531 goto again; /* get another record */
533 #ifndef OPENSSL_NO_SCTP
537 /* just read a 0 length packet */
542 * If this record is from the next epoch (either HM or ALERT), and a
543 * handshake is currently in progress, buffer it since it cannot be
544 * processed at this time.
548 if (dtls_rlayer_buffer_record(rl, rl->unprocessed_rcds,
550 /* RLAYERfatal() already called */
551 return OSSL_RECORD_RETURN_FATAL;
555 rl->packet_length = 0;
559 if (!dtls_process_record(rl, bitmap)) {
560 if (rl->alert != SSL_AD_NO_ALERT) {
561 /* dtls_process_record() called RLAYERfatal */
562 return OSSL_RECORD_RETURN_FATAL;
565 rl->packet_length = 0; /* dump this record */
566 goto again; /* get another record */
569 if (rl->funcs->post_process_record && !rl->funcs->post_process_record(rl, rr)) {
570 /* RLAYERfatal already called */
571 return OSSL_RECORD_RETURN_FATAL;
575 return OSSL_RECORD_RETURN_SUCCESS;
578 static int dtls_free(OSSL_RECORD_LAYER *rl)
581 size_t left, written;
583 DTLS_RLAYER_RECORD_DATA *rdata;
591 * This record layer is closing but we still have data left in our
592 * buffer. It must be destined for the next epoch - so push it there.
594 ret = BIO_write_ex(rl->next, rbuf->buf + rbuf->offset, left, &written);
598 if (rl->unprocessed_rcds != NULL) {
599 while ((item = pqueue_pop(rl->unprocessed_rcds)) != NULL) {
600 rdata = (DTLS_RLAYER_RECORD_DATA *)item->data;
601 /* Push to the next record layer */
602 ret &= BIO_write_ex(rl->next, rdata->packet, rdata->packet_length,
604 OPENSSL_free(rdata->rbuf.buf);
605 OPENSSL_free(item->data);
608 pqueue_free(rl->unprocessed_rcds);
611 if (rl->processed_rcds!= NULL) {
612 while ((item = pqueue_pop(rl->processed_rcds)) != NULL) {
613 rdata = (DTLS_RLAYER_RECORD_DATA *)item->data;
614 OPENSSL_free(rdata->rbuf.buf);
615 OPENSSL_free(item->data);
618 pqueue_free(rl->processed_rcds);
621 return tls_free(rl) && ret;
625 dtls_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
626 int role, int direction, int level, uint16_t epoch,
627 unsigned char *secret, size_t secretlen,
628 unsigned char *key, size_t keylen, unsigned char *iv,
629 size_t ivlen, unsigned char *mackey, size_t mackeylen,
630 const EVP_CIPHER *ciph, size_t taglen,
632 const EVP_MD *md, COMP_METHOD *comp,
633 const EVP_MD *kdfdigest, BIO *prev, BIO *transport,
634 BIO *next, BIO_ADDR *local, BIO_ADDR *peer,
635 const OSSL_PARAM *settings, const OSSL_PARAM *options,
636 const OSSL_DISPATCH *fns, void *cbarg, void *rlarg,
637 OSSL_RECORD_LAYER **retrl)
641 ret = tls_int_new_record_layer(libctx, propq, vers, role, direction, level,
642 ciph, taglen, md, comp, prev,
643 transport, next, settings,
644 options, fns, cbarg, retrl);
646 if (ret != OSSL_RECORD_RETURN_SUCCESS)
649 (*retrl)->unprocessed_rcds = pqueue_new();
650 (*retrl)->processed_rcds = pqueue_new();
652 if ((*retrl)->unprocessed_rcds == NULL
653 || (*retrl)->processed_rcds == NULL) {
656 ERR_raise(ERR_LIB_SSL, ERR_R_SSL_LIB);
657 return OSSL_RECORD_RETURN_FATAL;
660 (*retrl)->isdtls = 1;
661 (*retrl)->epoch = epoch;
662 (*retrl)->in_init = 1;
665 case DTLS_ANY_VERSION:
666 (*retrl)->funcs = &dtls_any_funcs;
668 case DTLS1_2_VERSION:
671 (*retrl)->funcs = &dtls_1_funcs;
674 /* Should not happen */
675 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
676 ret = OSSL_RECORD_RETURN_FATAL;
680 ret = (*retrl)->funcs->set_crypto_state(*retrl, level, key, keylen, iv,
681 ivlen, mackey, mackeylen, ciph,
682 taglen, mactype, md, comp);
685 if (ret != OSSL_RECORD_RETURN_SUCCESS) {
692 int dtls_prepare_record_header(OSSL_RECORD_LAYER *rl,
694 OSSL_RECORD_TEMPLATE *templ,
696 unsigned char **recdata)
702 maxcomplen = templ->buflen;
703 if (rl->compctx != NULL)
704 maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
706 if (!WPACKET_put_bytes_u8(thispkt, rectype)
707 || !WPACKET_put_bytes_u16(thispkt, templ->version)
708 || !WPACKET_put_bytes_u16(thispkt, rl->epoch)
709 || !WPACKET_memcpy(thispkt, &(rl->sequence[2]), 6)
710 || !WPACKET_start_sub_packet_u16(thispkt)
712 && !WPACKET_allocate_bytes(thispkt, rl->eivlen, NULL))
714 && !WPACKET_reserve_bytes(thispkt, maxcomplen,
716 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
723 int dtls_post_encryption_processing(OSSL_RECORD_LAYER *rl,
725 OSSL_RECORD_TEMPLATE *thistempl,
727 TLS_RL_RECORD *thiswr)
729 if (!tls_post_encryption_processing_default(rl, mac_size, thistempl,
731 /* RLAYERfatal() already called */
735 return tls_increment_sequence_ctr(rl);
738 static size_t dtls_get_max_record_overhead(OSSL_RECORD_LAYER *rl)
740 size_t blocksize = 0;
742 if (rl->enc_ctx != NULL &&
743 (EVP_CIPHER_CTX_get_mode(rl->enc_ctx) == EVP_CIPH_CBC_MODE))
744 blocksize = EVP_CIPHER_CTX_get_block_size(rl->enc_ctx);
747 * If we have a cipher in place then the tag is mandatory. If the cipher is
748 * CBC mode then an explicit IV is also mandatory. If we know the digest,
749 * then we check it is consistent with the taglen. In the case of stitched
750 * ciphers or AEAD ciphers we don't now the digest (or there isn't one) so
751 * we just trust that the taglen is correct.
753 assert(rl->enc_ctx == NULL || ((blocksize == 0 || rl->eivlen > 0)
755 assert(rl->md == NULL || (int)rl->taglen == EVP_MD_size(rl->md));
758 * Record overhead consists of the record header, the explicit IV, any
759 * expansion due to cbc padding, and the mac/tag len. There could be
760 * further expansion due to compression - but we don't know what this will
761 * be without knowing the length of the data. However when this function is
762 * called we don't know what the length will be yet - so this is a catch-22.
763 * We *could* use SSL_3_RT_MAX_COMPRESSED_OVERHEAD which is an upper limit
764 * for the maximum record size. But this value is larger than our fallback
765 * MTU size - so isn't very helpful. We just ignore potential expansion
766 * due to compression.
768 return DTLS1_RT_HEADER_LENGTH + rl->eivlen + blocksize + rl->taglen;
771 const OSSL_RECORD_METHOD ossl_dtls_record_method = {
772 dtls_new_record_layer,
774 tls_unprocessed_read_pending,
775 tls_processed_read_pending,
776 tls_app_data_pending,
779 tls_retry_write_records,
784 tls_set_protocol_version,
786 tls_set_first_handshake,
787 tls_set_max_pipelines,
792 tls_set_max_frag_len,
793 dtls_get_max_record_overhead,
794 tls_increment_sequence_ctr,