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 * We can only handle messages from the next epoch if we have already
94 * processed all of the unprocessed records from the previous epoch
96 else if (rr->epoch == (unsigned long)(rl->epoch + 1)
97 && rl->unprocessed_rcds.epoch != rl->epoch) {
99 return &rl->next_bitmap;
105 static void dtls_set_in_init(OSSL_RECORD_LAYER *rl, int in_init)
107 rl->in_init = in_init;
110 static int dtls_process_record(OSSL_RECORD_LAYER *rl, DTLS_BITMAP *bitmap)
117 unsigned char md[EVP_MAX_MD_SIZE];
118 SSL_MAC_BUF macbuf = { NULL, 0 };
124 * At this point, rl->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length,
125 * and we have that many bytes in rl->packet
127 rr->input = &(rl->packet[DTLS1_RT_HEADER_LENGTH]);
130 * ok, we can now read from 'rl->packet' data into 'rr'. rr->input
131 * points at rr->length bytes, which need to be copied into rr->data by
132 * either the decryption or by the decompression. When the data is 'copied'
133 * into the rr->data buffer, rr->input will be pointed at the new buffer
137 * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
138 * bytes of encrypted compressed stuff.
141 /* check is not needed I believe */
142 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
143 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
147 /* decrypt in place in 'rr->input' */
148 rr->data = rr->input;
149 rr->orig_len = rr->length;
151 if (rl->md_ctx != NULL) {
152 const EVP_MD *tmpmd = EVP_MD_CTX_get0_md(rl->md_ctx);
155 imac_size = EVP_MD_get_size(tmpmd);
156 if (!ossl_assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE)) {
157 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
160 mac_size = (size_t)imac_size;
164 if (rl->use_etm && rl->md_ctx != NULL) {
167 if (rr->orig_len < mac_size) {
168 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
171 rr->length -= mac_size;
172 mac = rr->data + rr->length;
173 i = rl->funcs->mac(rl, rr, md, 0 /* not send */);
174 if (i == 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
175 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
176 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
180 * We've handled the mac now - there is no MAC inside the encrypted
187 * Set a mark around the packet decryption attempt. This is DTLS, so
188 * bad packets are just ignored, and we don't want to leave stray
189 * errors in the queue from processing bogus junk that we ignored.
192 enc_err = rl->funcs->cipher(rl, rr, 1, 0, &macbuf, mac_size);
196 * 0: if the record is publicly invalid, or an internal error, or AEAD
197 * decryption failed, or ETM decryption failed.
198 * 1: Success or MTE decryption failed (MAC will be randomised)
202 if (rl->alert != SSL_AD_NO_ALERT) {
203 /* RLAYERfatal() already called */
206 /* For DTLS we simply ignore bad packets. */
208 rl->packet_length = 0;
211 ERR_clear_last_mark();
212 OSSL_TRACE_BEGIN(TLS) {
213 BIO_printf(trc_out, "dec %zd\n", rr->length);
214 BIO_dump_indent(trc_out, rr->data, rr->length, 4);
215 } OSSL_TRACE_END(TLS);
217 /* r->length is now the compressed data plus mac */
219 && (rl->enc_ctx != NULL)
220 && (EVP_MD_CTX_get0_md(rl->md_ctx) != NULL)) {
221 /* rl->md_ctx != NULL => mac_size != -1 */
223 i = rl->funcs->mac(rl, rr, md, 0 /* not send */);
224 if (i == 0 || macbuf.mac == NULL
225 || CRYPTO_memcmp(md, macbuf.mac, mac_size) != 0)
227 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
232 /* decryption failed, silently discard message */
234 rl->packet_length = 0;
238 /* r->length is now just compressed */
239 if (rl->compctx != NULL) {
240 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
241 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
242 SSL_R_COMPRESSED_LENGTH_TOO_LONG);
245 if (!tls_do_uncompress(rl, rr)) {
246 RLAYERfatal(rl, SSL_AD_DECOMPRESSION_FAILURE, SSL_R_BAD_DECOMPRESSION);
252 * Check if the received packet overflows the current Max Fragment
255 if (rr->length > rl->max_frag_len) {
256 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
262 * So at this point the following is true
263 * ssl->s3.rrec.type is the type of record
264 * ssl->s3.rrec.length == number of bytes in record
265 * ssl->s3.rrec.off == offset to first valid byte
266 * ssl->s3.rrec.data == where to take bytes from, increment
270 /* we have pulled in a full packet so zero things */
271 rl->packet_length = 0;
273 /* Mark receipt of record. */
274 dtls_record_bitmap_update(rl, bitmap);
279 OPENSSL_free(macbuf.mac);
283 static int dtls_rlayer_buffer_record(OSSL_RECORD_LAYER *rl, record_pqueue *queue,
284 unsigned char *priority)
286 DTLS_RLAYER_RECORD_DATA *rdata;
289 /* Limit the size of the queue to prevent DOS attacks */
290 if (pqueue_size(queue->q) >= 100)
293 rdata = OPENSSL_malloc(sizeof(*rdata));
294 item = pitem_new(priority, rdata);
295 if (rdata == NULL || item == NULL) {
298 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
302 rdata->packet = rl->packet;
303 rdata->packet_length = rl->packet_length;
304 memcpy(&(rdata->rbuf), &rl->rbuf, sizeof(TLS_BUFFER));
305 memcpy(&(rdata->rrec), &rl->rrec[0], sizeof(TLS_RL_RECORD));
310 rl->packet_length = 0;
311 memset(&rl->rbuf, 0, sizeof(TLS_BUFFER));
312 memset(&rl->rrec[0], 0, sizeof(rl->rrec[0]));
314 if (!tls_setup_read_buffer(rl)) {
315 /* RLAYERfatal() already called */
316 OPENSSL_free(rdata->rbuf.buf);
322 if (pqueue_insert(queue->q, item) == NULL) {
323 /* Must be a duplicate so ignore it */
324 OPENSSL_free(rdata->rbuf.buf);
332 /* copy buffered record into OSSL_RECORD_LAYER structure */
333 static int dtls_copy_rlayer_record(OSSL_RECORD_LAYER *rl, pitem *item)
335 DTLS_RLAYER_RECORD_DATA *rdata;
337 rdata = (DTLS_RLAYER_RECORD_DATA *)item->data;
339 ossl_tls_buffer_release(&rl->rbuf);
341 rl->packet = rdata->packet;
342 rl->packet_length = rdata->packet_length;
343 memcpy(&rl->rbuf, &(rdata->rbuf), sizeof(TLS_BUFFER));
344 memcpy(&rl->rrec[0], &(rdata->rrec), sizeof(TLS_RL_RECORD));
346 /* Set proper sequence number for mac calculation */
347 memcpy(&(rl->sequence[2]), &(rdata->packet[5]), 6);
352 static int dtls_retrieve_rlayer_buffered_record(OSSL_RECORD_LAYER *rl,
353 record_pqueue *queue)
357 item = pqueue_pop(queue->q);
359 dtls_copy_rlayer_record(rl, item);
361 OPENSSL_free(item->data);
371 * Call this to get a new input record.
372 * It will return <= 0 if more data is needed, normally due to an error
373 * or non-blocking IO.
374 * When it finishes, one packet has been decoded and can be found in
375 * ssl->s3.rrec.type - is the type of record
376 * ssl->s3.rrec.data - data
377 * ssl->s3.rrec.length - number of bytes
379 int dtls_get_more_records(OSSL_RECORD_LAYER *rl)
381 int ssl_major, ssl_minor;
385 unsigned char *p = NULL;
387 unsigned int is_next_epoch;
391 rl->num_released = 0;
395 if (rl->rbuf.buf == NULL) {
396 if (!tls_setup_read_buffer(rl)) {
397 /* RLAYERfatal() already called */
398 return OSSL_RECORD_RETURN_FATAL;
403 /* if we're renegotiating, then there may be buffered records */
404 if (dtls_retrieve_rlayer_buffered_record(rl, &rl->processed_rcds)) {
406 return OSSL_RECORD_RETURN_SUCCESS;
409 /* get something from the wire */
411 /* check if we have the header */
412 if ((rl->rstate != SSL_ST_READ_BODY) ||
413 (rl->packet_length < DTLS1_RT_HEADER_LENGTH)) {
414 rret = rl->funcs->read_n(rl, DTLS1_RT_HEADER_LENGTH,
415 TLS_BUFFER_get_len(&rl->rbuf), 0, 1, &n);
416 /* read timeout is handled by dtls1_read_bytes */
417 if (rret < OSSL_RECORD_RETURN_SUCCESS) {
418 /* RLAYERfatal() already called if appropriate */
419 return rret; /* error or non-blocking */
422 /* this packet contained a partial record, dump it */
423 if (rl->packet_length != DTLS1_RT_HEADER_LENGTH) {
424 rl->packet_length = 0;
428 rl->rstate = SSL_ST_READ_BODY;
432 /* Pull apart the header into the DTLS1_RECORD */
436 rr->rec_version = (ssl_major << 8) | ssl_minor;
438 /* sequence number is 64 bits, with top 2 bytes = epoch */
441 memcpy(&(rl->sequence[2]), p, 6);
446 if (rl->msg_callback != NULL)
447 rl->msg_callback(0, rr->rec_version, SSL3_RT_HEADER, rl->packet, DTLS1_RT_HEADER_LENGTH,
451 * Lets check the version. We tolerate alerts that don't have the exact
452 * version number (e.g. because of protocol version errors)
454 if (!rl->is_first_record && rr->type != SSL3_RT_ALERT) {
455 if (rr->rec_version != rl->version) {
456 /* unexpected version, silently discard */
458 rl->packet_length = 0;
464 (rl->version == DTLS_ANY_VERSION ? DTLS1_VERSION_MAJOR
465 : rl->version >> 8)) {
466 /* wrong version, silently discard record */
468 rl->packet_length = 0;
472 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
473 /* record too long, silently discard it */
475 rl->packet_length = 0;
480 * If received packet overflows maximum possible fragment length then
481 * silently discard it
483 if (rr->length > rl->max_frag_len + SSL3_RT_MAX_ENCRYPTED_OVERHEAD) {
484 /* record too long, silently discard it */
486 rl->packet_length = 0;
490 /* now rl->rstate == SSL_ST_READ_BODY */
493 /* rl->rstate == SSL_ST_READ_BODY, get and decode the data */
495 if (rr->length > rl->packet_length - DTLS1_RT_HEADER_LENGTH) {
496 /* now rl->packet_length == DTLS1_RT_HEADER_LENGTH */
498 rret = rl->funcs->read_n(rl, more, more, 1, 1, &n);
499 /* this packet contained a partial record, dump it */
500 if (rret < OSSL_RECORD_RETURN_SUCCESS || n != more) {
501 if (rl->alert != SSL_AD_NO_ALERT) {
502 /* read_n() called RLAYERfatal() */
503 return OSSL_RECORD_RETURN_FATAL;
506 rl->packet_length = 0;
511 * now n == rr->length,
512 * and rl->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length
515 /* set state for later operations */
516 rl->rstate = SSL_ST_READ_HEADER;
518 /* match epochs. NULL means the packet is dropped on the floor */
519 bitmap = dtls_get_bitmap(rl, rr, &is_next_epoch);
520 if (bitmap == NULL) {
522 rl->packet_length = 0; /* dump this record */
523 goto again; /* get another record */
525 #ifndef OPENSSL_NO_SCTP
526 /* Only do replay check if no SCTP bio */
527 if (!BIO_dgram_is_sctp(rl->bio)) {
529 /* Check whether this is a repeat, or aged record. */
530 if (!dtls_record_replay_check(rl, bitmap)) {
532 rl->packet_length = 0; /* dump this record */
533 goto again; /* get another record */
535 #ifndef OPENSSL_NO_SCTP
539 /* just read a 0 length packet */
544 * If this record is from the next epoch (either HM or ALERT), and a
545 * handshake is currently in progress, buffer it since it cannot be
546 * processed at this time.
550 if (dtls_rlayer_buffer_record(rl, &(rl->unprocessed_rcds),
552 /* RLAYERfatal() already called */
553 return OSSL_RECORD_RETURN_FATAL;
557 rl->packet_length = 0;
561 if (!dtls_process_record(rl, bitmap)) {
562 if (rl->alert != SSL_AD_NO_ALERT) {
563 /* dtls_process_record() called RLAYERfatal */
564 return OSSL_RECORD_RETURN_FATAL;
567 rl->packet_length = 0; /* dump this record */
568 goto again; /* get another record */
571 if (rl->funcs->post_process_record && !rl->funcs->post_process_record(rl, rr)) {
572 /* RLAYERfatal already called */
573 return OSSL_RECORD_RETURN_FATAL;
577 return OSSL_RECORD_RETURN_SUCCESS;
580 static int dtls_free(OSSL_RECORD_LAYER *rl)
583 size_t left, written;
585 DTLS_RLAYER_RECORD_DATA *rdata;
593 * This record layer is closing but we still have data left in our
594 * buffer. It must be destined for the next epoch - so push it there.
596 ret = BIO_write_ex(rl->next, rbuf->buf + rbuf->offset, left, &written);
600 if (rl->unprocessed_rcds.q != NULL) {
601 while ((item = pqueue_pop(rl->unprocessed_rcds.q)) != NULL) {
602 rdata = (DTLS_RLAYER_RECORD_DATA *)item->data;
603 /* Push to the next record layer */
604 ret &= BIO_write_ex(rl->next, rdata->packet, rdata->packet_length,
606 OPENSSL_free(rdata->rbuf.buf);
607 OPENSSL_free(item->data);
610 pqueue_free(rl->unprocessed_rcds.q);
613 if (rl->processed_rcds.q != NULL) {
614 while ((item = pqueue_pop(rl->processed_rcds.q)) != NULL) {
615 rdata = (DTLS_RLAYER_RECORD_DATA *)item->data;
616 OPENSSL_free(rdata->rbuf.buf);
617 OPENSSL_free(item->data);
620 pqueue_free(rl->processed_rcds.q);
623 return tls_free(rl) && ret;
627 dtls_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
628 int role, int direction, int level, uint16_t epoch,
629 unsigned char *secret, size_t secretlen,
630 unsigned char *key, size_t keylen, unsigned char *iv,
631 size_t ivlen, unsigned char *mackey, size_t mackeylen,
632 const EVP_CIPHER *ciph, size_t taglen,
634 const EVP_MD *md, COMP_METHOD *comp,
635 const EVP_MD *kdfdigest, BIO *prev, BIO *transport,
636 BIO *next, BIO_ADDR *local, BIO_ADDR *peer,
637 const OSSL_PARAM *settings, const OSSL_PARAM *options,
638 const OSSL_DISPATCH *fns, void *cbarg, void *rlarg,
639 OSSL_RECORD_LAYER **retrl)
643 ret = tls_int_new_record_layer(libctx, propq, vers, role, direction, level,
644 key, keylen, iv, ivlen, mackey, mackeylen,
645 ciph, taglen, mactype, md, comp, prev,
646 transport, next, local, peer, settings,
647 options, fns, cbarg, retrl);
649 if (ret != OSSL_RECORD_RETURN_SUCCESS)
652 (*retrl)->unprocessed_rcds.q = pqueue_new();
653 (*retrl)->processed_rcds.q = pqueue_new();
654 if ((*retrl)->unprocessed_rcds.q == NULL
655 || (*retrl)->processed_rcds.q == NULL) {
658 ERR_raise(ERR_LIB_SSL, ERR_R_SSL_LIB);
659 return OSSL_RECORD_RETURN_FATAL;
662 (*retrl)->unprocessed_rcds.epoch = epoch + 1;
663 (*retrl)->processed_rcds.epoch = epoch;
665 (*retrl)->isdtls = 1;
666 (*retrl)->epoch = epoch;
667 (*retrl)->in_init = 1;
670 case DTLS_ANY_VERSION:
671 (*retrl)->funcs = &dtls_any_funcs;
673 case DTLS1_2_VERSION:
676 (*retrl)->funcs = &dtls_1_funcs;
679 /* Should not happen */
680 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
681 ret = OSSL_RECORD_RETURN_FATAL;
685 ret = (*retrl)->funcs->set_crypto_state(*retrl, level, key, keylen, iv,
686 ivlen, mackey, mackeylen, ciph,
687 taglen, mactype, md, comp);
690 if (ret != OSSL_RECORD_RETURN_SUCCESS) {
697 int dtls_prepare_record_header(OSSL_RECORD_LAYER *rl,
699 OSSL_RECORD_TEMPLATE *templ,
701 unsigned char **recdata)
707 maxcomplen = templ->buflen;
708 if (rl->compctx != NULL)
709 maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
711 if (!WPACKET_put_bytes_u8(thispkt, rectype)
712 || !WPACKET_put_bytes_u16(thispkt, templ->version)
713 || !WPACKET_put_bytes_u16(thispkt, rl->epoch)
714 || !WPACKET_memcpy(thispkt, &(rl->sequence[2]), 6)
715 || !WPACKET_start_sub_packet_u16(thispkt)
717 && !WPACKET_allocate_bytes(thispkt, rl->eivlen, NULL))
719 && !WPACKET_reserve_bytes(thispkt, maxcomplen,
721 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
728 int dtls_post_encryption_processing(OSSL_RECORD_LAYER *rl,
730 OSSL_RECORD_TEMPLATE *thistempl,
732 TLS_RL_RECORD *thiswr)
734 if (!tls_post_encryption_processing_default(rl, mac_size, thistempl,
736 /* RLAYERfatal() already called */
740 return tls_increment_sequence_ctr(rl);
743 static size_t dtls_get_max_record_overhead(OSSL_RECORD_LAYER *rl)
745 size_t blocksize = 0;
747 if (rl->enc_ctx != NULL &&
748 (EVP_CIPHER_CTX_get_mode(rl->enc_ctx) == EVP_CIPH_CBC_MODE))
749 blocksize = EVP_CIPHER_CTX_get_block_size(rl->enc_ctx);
752 * If we have a cipher in place then the tag is mandatory. If the cipher is
753 * CBC mode then an explicit IV is also mandatory. If we know the digest,
754 * then we check it is consistent with the taglen. In the case of stitched
755 * ciphers or AEAD ciphers we don't now the digest (or there isn't one) so
756 * we just trust that the taglen is correct.
758 assert(rl->enc_ctx == NULL || ((blocksize == 0 || rl->eivlen > 0)
760 assert(rl->md == NULL || (int)rl->taglen == EVP_MD_size(rl->md));
763 * Record overhead consists of the record header, the explicit IV, any
764 * expansion due to cbc padding, and the mac/tag len. There could be
765 * further expansion due to compression - but we don't know what this will
766 * be without knowing the length of the data. However when this function is
767 * called we don't know what the length will be yet - so this is a catch-22.
768 * We *could* use SSL_3_RT_MAX_COMPRESSED_OVERHEAD which is an upper limit
769 * for the maximum record size. But this value is larger than our fallback
770 * MTU size - so isn't very helpful. We just ignore potential expansion
771 * due to compression.
773 return DTLS1_RT_HEADER_LENGTH + rl->eivlen + blocksize + rl->taglen;
776 const OSSL_RECORD_METHOD ossl_dtls_record_method = {
777 dtls_new_record_layer,
779 tls_unprocessed_read_pending,
780 tls_processed_read_pending,
781 tls_app_data_pending,
784 tls_retry_write_records,
789 tls_set_protocol_version,
791 tls_set_first_handshake,
792 tls_set_max_pipelines,
797 tls_set_max_frag_len,
798 dtls_get_max_record_overhead,
799 tls_increment_sequence_ctr,