2 * Copyright 2018-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
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 * Only HM and ALERT messages can be from the next epoch and only if we
94 * have already processed all of the unprocessed records from the last
97 else if (rr->epoch == (unsigned long)(rl->epoch + 1)
98 && rl->unprocessed_rcds.epoch != rl->epoch
99 && (rr->type == SSL3_RT_HANDSHAKE || rr->type == SSL3_RT_ALERT)) {
101 return &rl->next_bitmap;
107 static void dtls_set_in_init(OSSL_RECORD_LAYER *rl, int in_init)
109 rl->in_init = in_init;
112 static int dtls_process_record(OSSL_RECORD_LAYER *rl, DTLS_BITMAP *bitmap)
119 unsigned char md[EVP_MAX_MD_SIZE];
120 SSL_MAC_BUF macbuf = { NULL, 0 };
126 * At this point, rl->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length,
127 * and we have that many bytes in rl->packet
129 rr->input = &(rl->packet[DTLS1_RT_HEADER_LENGTH]);
132 * ok, we can now read from 'rl->packet' data into 'rr'. rr->input
133 * points at rr->length bytes, which need to be copied into rr->data by
134 * either the decryption or by the decompression. When the data is 'copied'
135 * into the rr->data buffer, rr->input will be pointed at the new buffer
139 * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
140 * bytes of encrypted compressed stuff.
143 /* check is not needed I believe */
144 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
145 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
149 /* decrypt in place in 'rr->input' */
150 rr->data = rr->input;
151 rr->orig_len = rr->length;
153 if (rl->md_ctx != NULL) {
154 const EVP_MD *tmpmd = EVP_MD_CTX_get0_md(rl->md_ctx);
157 imac_size = EVP_MD_get_size(tmpmd);
158 if (!ossl_assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE)) {
159 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
162 mac_size = (size_t)imac_size;
166 if (rl->use_etm && rl->md_ctx != NULL) {
169 if (rr->orig_len < mac_size) {
170 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
173 rr->length -= mac_size;
174 mac = rr->data + rr->length;
175 i = rl->funcs->mac(rl, rr, md, 0 /* not send */);
176 if (i == 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
177 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
178 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
182 * We've handled the mac now - there is no MAC inside the encrypted
189 * Set a mark around the packet decryption attempt. This is DTLS, so
190 * bad packets are just ignored, and we don't want to leave stray
191 * errors in the queue from processing bogus junk that we ignored.
194 enc_err = rl->funcs->cipher(rl, rr, 1, 0, &macbuf, mac_size);
198 * 0: if the record is publicly invalid, or an internal error, or AEAD
199 * decryption failed, or ETM decryption failed.
200 * 1: Success or MTE decryption failed (MAC will be randomised)
204 if (rl->alert != SSL_AD_NO_ALERT) {
205 /* RLAYERfatal() already called */
208 /* For DTLS we simply ignore bad packets. */
210 rl->packet_length = 0;
213 ERR_clear_last_mark();
214 OSSL_TRACE_BEGIN(TLS) {
215 BIO_printf(trc_out, "dec %zd\n", rr->length);
216 BIO_dump_indent(trc_out, rr->data, rr->length, 4);
217 } OSSL_TRACE_END(TLS);
219 /* r->length is now the compressed data plus mac */
221 && (rl->enc_ctx != NULL)
222 && (EVP_MD_CTX_get0_md(rl->md_ctx) != NULL)) {
223 /* rl->md_ctx != NULL => mac_size != -1 */
225 i = rl->funcs->mac(rl, rr, md, 0 /* not send */);
226 if (i == 0 || macbuf.mac == NULL
227 || CRYPTO_memcmp(md, macbuf.mac, mac_size) != 0)
229 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
234 /* decryption failed, silently discard message */
236 rl->packet_length = 0;
240 /* r->length is now just compressed */
241 if (rl->compctx != NULL) {
242 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
243 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
244 SSL_R_COMPRESSED_LENGTH_TOO_LONG);
247 if (!tls_do_uncompress(rl, rr)) {
248 RLAYERfatal(rl, SSL_AD_DECOMPRESSION_FAILURE, SSL_R_BAD_DECOMPRESSION);
254 * Check if the received packet overflows the current Max Fragment
257 if (rr->length > rl->max_frag_len) {
258 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
264 * So at this point the following is true
265 * ssl->s3.rrec.type is the type of record
266 * ssl->s3.rrec.length == number of bytes in record
267 * ssl->s3.rrec.off == offset to first valid byte
268 * ssl->s3.rrec.data == where to take bytes from, increment
272 /* we have pulled in a full packet so zero things */
273 rl->packet_length = 0;
275 /* Mark receipt of record. */
276 dtls_record_bitmap_update(rl, bitmap);
281 OPENSSL_free(macbuf.mac);
285 static int dtls_rlayer_buffer_record(OSSL_RECORD_LAYER *rl, record_pqueue *queue,
286 unsigned char *priority)
288 DTLS_RLAYER_RECORD_DATA *rdata;
291 /* Limit the size of the queue to prevent DOS attacks */
292 if (pqueue_size(queue->q) >= 100)
295 rdata = OPENSSL_malloc(sizeof(*rdata));
296 item = pitem_new(priority, rdata);
297 if (rdata == NULL || item == NULL) {
300 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
304 rdata->packet = rl->packet;
305 rdata->packet_length = rl->packet_length;
306 memcpy(&(rdata->rbuf), &rl->rbuf, sizeof(TLS_BUFFER));
307 memcpy(&(rdata->rrec), &rl->rrec[0], sizeof(TLS_RL_RECORD));
312 rl->packet_length = 0;
313 memset(&rl->rbuf, 0, sizeof(TLS_BUFFER));
314 memset(&rl->rrec[0], 0, sizeof(rl->rrec[0]));
316 if (!tls_setup_read_buffer(rl)) {
317 /* RLAYERfatal() already called */
318 OPENSSL_free(rdata->rbuf.buf);
324 if (pqueue_insert(queue->q, item) == NULL) {
325 /* Must be a duplicate so ignore it */
326 OPENSSL_free(rdata->rbuf.buf);
334 /* copy buffered record into OSSL_RECORD_LAYER structure */
335 static int dtls_copy_rlayer_record(OSSL_RECORD_LAYER *rl, pitem *item)
337 DTLS_RLAYER_RECORD_DATA *rdata;
339 rdata = (DTLS_RLAYER_RECORD_DATA *)item->data;
341 ossl_tls_buffer_release(&rl->rbuf);
343 rl->packet = rdata->packet;
344 rl->packet_length = rdata->packet_length;
345 memcpy(&rl->rbuf, &(rdata->rbuf), sizeof(TLS_BUFFER));
346 memcpy(&rl->rrec[0], &(rdata->rrec), sizeof(TLS_RL_RECORD));
348 /* Set proper sequence number for mac calculation */
349 memcpy(&(rl->sequence[2]), &(rdata->packet[5]), 6);
354 static int dtls_retrieve_rlayer_buffered_record(OSSL_RECORD_LAYER *rl,
355 record_pqueue *queue)
359 item = pqueue_pop(queue->q);
361 dtls_copy_rlayer_record(rl, item);
363 OPENSSL_free(item->data);
373 * Call this to get a new input record.
374 * It will return <= 0 if more data is needed, normally due to an error
375 * or non-blocking IO.
376 * When it finishes, one packet has been decoded and can be found in
377 * ssl->s3.rrec.type - is the type of record
378 * ssl->s3.rrec.data - data
379 * ssl->s3.rrec.length - number of bytes
381 int dtls_get_more_records(OSSL_RECORD_LAYER *rl)
383 int ssl_major, ssl_minor;
387 unsigned char *p = NULL;
388 unsigned short version;
390 unsigned int is_next_epoch;
394 rl->num_released = 0;
398 if (rl->rbuf.buf == NULL) {
399 if (!tls_setup_read_buffer(rl)) {
400 /* RLAYERfatal() already called */
401 return OSSL_RECORD_RETURN_FATAL;
406 /* if we're renegotiating, then there may be buffered records */
407 if (dtls_retrieve_rlayer_buffered_record(rl, &rl->processed_rcds)) {
409 return OSSL_RECORD_RETURN_SUCCESS;
412 /* get something from the wire */
414 /* check if we have the header */
415 if ((rl->rstate != SSL_ST_READ_BODY) ||
416 (rl->packet_length < DTLS1_RT_HEADER_LENGTH)) {
417 rret = rl->funcs->read_n(rl, DTLS1_RT_HEADER_LENGTH,
418 TLS_BUFFER_get_len(&rl->rbuf), 0, 1, &n);
419 /* read timeout is handled by dtls1_read_bytes */
420 if (rret < OSSL_RECORD_RETURN_SUCCESS) {
421 /* RLAYERfatal() already called if appropriate */
422 return rret; /* error or non-blocking */
425 /* this packet contained a partial record, dump it */
426 if (rl->packet_length != DTLS1_RT_HEADER_LENGTH) {
427 rl->packet_length = 0;
431 rl->rstate = SSL_ST_READ_BODY;
435 if (rl->msg_callback != NULL)
436 rl->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH,
439 /* Pull apart the header into the DTLS1_RECORD */
443 version = (ssl_major << 8) | ssl_minor;
445 /* sequence number is 64 bits, with top 2 bytes = epoch */
448 memcpy(&(rl->sequence[2]), p, 6);
454 * Lets check the version. We tolerate alerts that don't have the exact
455 * version number (e.g. because of protocol version errors)
457 if (!rl->is_first_record && rr->type != SSL3_RT_ALERT) {
458 if (version != rl->version) {
459 /* unexpected version, silently discard */
461 rl->packet_length = 0;
467 (rl->version == DTLS_ANY_VERSION ? DTLS1_VERSION_MAJOR
468 : rl->version >> 8)) {
469 /* wrong version, silently discard record */
471 rl->packet_length = 0;
475 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
476 /* record too long, silently discard it */
478 rl->packet_length = 0;
483 * If received packet overflows maximum possible fragment length then
484 * silently discard it
486 if (rr->length > rl->max_frag_len + SSL3_RT_MAX_ENCRYPTED_OVERHEAD) {
487 /* record too long, silently discard it */
489 rl->packet_length = 0;
493 /* now rl->rstate == SSL_ST_READ_BODY */
496 /* rl->rstate == SSL_ST_READ_BODY, get and decode the data */
498 if (rr->length > rl->packet_length - DTLS1_RT_HEADER_LENGTH) {
499 /* now rl->packet_length == DTLS1_RT_HEADER_LENGTH */
501 rret = rl->funcs->read_n(rl, more, more, 1, 1, &n);
502 /* this packet contained a partial record, dump it */
503 if (rret < OSSL_RECORD_RETURN_SUCCESS || n != more) {
504 if (rl->alert != SSL_AD_NO_ALERT) {
505 /* read_n() called RLAYERfatal() */
506 return OSSL_RECORD_RETURN_FATAL;
509 rl->packet_length = 0;
514 * now n == rr->length,
515 * and rl->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length
518 /* set state for later operations */
519 rl->rstate = SSL_ST_READ_HEADER;
521 /* match epochs. NULL means the packet is dropped on the floor */
522 bitmap = dtls_get_bitmap(rl, rr, &is_next_epoch);
523 if (bitmap == NULL) {
525 rl->packet_length = 0; /* dump this record */
526 goto again; /* get another record */
528 #ifndef OPENSSL_NO_SCTP
529 /* Only do replay check if no SCTP bio */
530 if (!BIO_dgram_is_sctp(rl->bio)) {
532 /* Check whether this is a repeat, or aged record. */
533 if (!dtls_record_replay_check(rl, bitmap)) {
535 rl->packet_length = 0; /* dump this record */
536 goto again; /* get another record */
538 #ifndef OPENSSL_NO_SCTP
542 /* just read a 0 length packet */
547 * If this record is from the next epoch (either HM or ALERT), and a
548 * handshake is currently in progress, buffer it since it cannot be
549 * processed at this time.
553 if (dtls_rlayer_buffer_record(rl, &(rl->unprocessed_rcds),
555 /* RLAYERfatal() already called */
556 return OSSL_RECORD_RETURN_FATAL;
560 rl->packet_length = 0;
564 if (!dtls_process_record(rl, bitmap)) {
565 if (rl->alert != SSL_AD_NO_ALERT) {
566 /* dtls_process_record() called RLAYERfatal */
567 return OSSL_RECORD_RETURN_FATAL;
570 rl->packet_length = 0; /* dump this record */
571 goto again; /* get another record */
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.q != NULL) {
599 while ((item = pqueue_pop(rl->unprocessed_rcds.q)) != 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.q);
611 if (rl->processed_rcds.q != NULL) {
612 while ((item = pqueue_pop(rl->processed_rcds.q)) != 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.q);
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 *key, size_t keylen, unsigned char *iv,
628 size_t ivlen, unsigned char *mackey, size_t mackeylen,
629 const EVP_CIPHER *ciph, size_t taglen,
631 const EVP_MD *md, COMP_METHOD *comp, BIO *prev,
632 BIO *transport, BIO *next, BIO_ADDR *local, BIO_ADDR *peer,
633 const OSSL_PARAM *settings, const OSSL_PARAM *options,
634 const OSSL_DISPATCH *fns, void *cbarg,
635 OSSL_RECORD_LAYER **retrl)
639 ret = tls_int_new_record_layer(libctx, propq, vers, role, direction, level,
640 key, keylen, iv, ivlen, mackey, mackeylen,
641 ciph, taglen, mactype, md, comp, prev,
642 transport, next, local, peer, settings,
643 options, fns, cbarg, retrl);
645 if (ret != OSSL_RECORD_RETURN_SUCCESS)
648 (*retrl)->unprocessed_rcds.q = pqueue_new();
649 (*retrl)->processed_rcds.q = pqueue_new();
650 if ((*retrl)->unprocessed_rcds.q == NULL
651 || (*retrl)->processed_rcds.q == NULL) {
654 ERR_raise(ERR_LIB_SSL, ERR_R_SSL_LIB);
655 return OSSL_RECORD_RETURN_FATAL;
658 (*retrl)->unprocessed_rcds.epoch = epoch + 1;
659 (*retrl)->processed_rcds.epoch = epoch;
661 (*retrl)->isdtls = 1;
662 (*retrl)->epoch = epoch;
663 (*retrl)->in_init = 1;
666 case DTLS_ANY_VERSION:
667 (*retrl)->funcs = &dtls_any_funcs;
669 case DTLS1_2_VERSION:
672 (*retrl)->funcs = &dtls_1_funcs;
675 /* Should not happen */
676 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
677 ret = OSSL_RECORD_RETURN_FATAL;
681 ret = (*retrl)->funcs->set_crypto_state(*retrl, level, key, keylen, iv,
682 ivlen, mackey, mackeylen, ciph,
683 taglen, mactype, md, comp);
686 if (ret != OSSL_RECORD_RETURN_SUCCESS) {
693 int dtls_prepare_record_header(OSSL_RECORD_LAYER *rl,
695 OSSL_RECORD_TEMPLATE *templ,
696 unsigned int rectype,
697 unsigned char **recdata)
703 maxcomplen = templ->buflen;
704 if (rl->compctx != NULL)
705 maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
707 if (!WPACKET_put_bytes_u8(thispkt, rectype)
708 || !WPACKET_put_bytes_u16(thispkt, templ->version)
709 || !WPACKET_put_bytes_u16(thispkt, rl->epoch)
710 || !WPACKET_memcpy(thispkt, &(rl->sequence[2]), 6)
711 || !WPACKET_start_sub_packet_u16(thispkt)
713 && !WPACKET_allocate_bytes(thispkt, rl->eivlen, NULL))
715 && !WPACKET_reserve_bytes(thispkt, maxcomplen,
717 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
724 int dtls_post_encryption_processing(OSSL_RECORD_LAYER *rl,
726 OSSL_RECORD_TEMPLATE *thistempl,
728 TLS_RL_RECORD *thiswr)
730 if (!tls_post_encryption_processing_default(rl, mac_size, thistempl,
732 /* RLAYERfatal() already called */
736 return tls_increment_sequence_ctr(rl);
739 static size_t dtls_get_max_record_overhead(OSSL_RECORD_LAYER *rl)
741 size_t blocksize = 0;
743 if (rl->enc_ctx != NULL &&
744 (EVP_CIPHER_CTX_get_mode(rl->enc_ctx) == EVP_CIPH_CBC_MODE))
745 blocksize = EVP_CIPHER_CTX_get_block_size(rl->enc_ctx);
748 * If we have a cipher in place then the tag is mandatory. If the cipher is
749 * CBC mode then an explicit IV is also mandatory. If we know the digest,
750 * then we check it is consistent with the taglen. In the case of stitched
751 * ciphers or AEAD ciphers we don't now the digest (or there isn't one) so
752 * we just trust that the taglen is correct.
754 assert(rl->enc_ctx == NULL || ((blocksize == 0 || rl->eivlen > 0)
756 assert(rl->md == NULL || (int)rl->taglen == EVP_MD_size(rl->md));
759 * Record overhead consists of the record header, the explicit IV, any
760 * expansion due to cbc padding, and the mac/tag len. There could be
761 * further expansion due to compression - but we don't know what this will
762 * be without knowing the length of the data. However when this function is
763 * called we don't know what the length will be yet - so this is a catch-22.
764 * We *could* use SSL_3_RT_MAX_COMPRESSED_OVERHEAD which is an upper limit
765 * for the maximum record size. But this value is larger than our fallback
766 * MTU size - so isn't very helpful. We just ignore potential expansion
767 * due to compression.
769 return DTLS1_RT_HEADER_LENGTH + rl->eivlen + blocksize + rl->taglen;
772 const OSSL_RECORD_METHOD ossl_dtls_record_method = {
773 dtls_new_record_layer,
775 tls_unprocessed_read_pending,
776 tls_processed_read_pending,
777 tls_app_data_pending,
780 tls_retry_write_records,
785 tls_set_protocol_version,
787 tls_set_first_handshake,
788 tls_set_max_pipelines,
793 tls_set_max_frag_len,
794 dtls_get_max_record_overhead,
795 tls_increment_sequence_ctr,