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
10 #include "../../ssl_local.h"
11 #include "../record_local.h"
12 #include "recmethod_local.h"
14 /* mod 128 saturating subtract of two 64-bit values in big-endian order */
15 static int satsub64be(const unsigned char *v1, const unsigned char *v2)
25 /* We do not permit wrap-around */
26 if (l1 > l2 && ret < 0)
28 else if (l2 > l1 && ret > 0)
39 static int dtls_record_replay_check(OSSL_RECORD_LAYER *rl, DTLS1_BITMAP *bitmap)
43 const unsigned char *seq = rl->sequence;
45 cmp = satsub64be(seq, bitmap->max_seq_num);
47 SSL3_RECORD_set_seq_num(&rl->rrec[0], seq);
48 return 1; /* this record in new */
51 if (shift >= sizeof(bitmap->map) * 8)
52 return 0; /* stale, outside the window */
53 else if (bitmap->map & (1UL << shift))
54 return 0; /* record previously received */
56 SSL3_RECORD_set_seq_num(&rl->rrec[0], seq);
60 static void dtls_record_bitmap_update(OSSL_RECORD_LAYER *rl,
65 const unsigned char *seq = rl->sequence;
67 cmp = satsub64be(seq, bitmap->max_seq_num);
70 if (shift < sizeof(bitmap->map) * 8)
71 bitmap->map <<= shift, bitmap->map |= 1UL;
74 memcpy(bitmap->max_seq_num, seq, SEQ_NUM_SIZE);
77 if (shift < sizeof(bitmap->map) * 8)
78 bitmap->map |= 1UL << shift;
82 static DTLS1_BITMAP *dtls_get_bitmap(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rr,
83 unsigned int *is_next_epoch)
87 /* In current epoch, accept HM, CCS, DATA, & ALERT */
88 if (rr->epoch == rl->epoch)
92 * Only HM and ALERT messages can be from the next epoch and only if we
93 * have already processed all of the unprocessed records from the last
96 else if (rr->epoch == (unsigned long)(rl->epoch + 1) &&
97 rl->unprocessed_rcds.epoch != rl->epoch &&
98 (rr->type == SSL3_RT_HANDSHAKE || rr->type == SSL3_RT_ALERT)) {
100 return &rl->next_bitmap;
106 static void dtls_set_in_init(OSSL_RECORD_LAYER *rl, int in_init)
108 rl->in_init = in_init;
111 static int dtls_process_record(OSSL_RECORD_LAYER *rl, DTLS1_BITMAP *bitmap)
118 unsigned char md[EVP_MAX_MD_SIZE];
119 SSL_MAC_BUF macbuf = { NULL, 0 };
125 * At this point, rl->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
126 * and we have that many bytes in rl->packet
128 rr->input = &(rl->packet[DTLS1_RT_HEADER_LENGTH]);
131 * ok, we can now read from 'rl->packet' data into 'rr'. rr->input
132 * points at rr->length bytes, which need to be copied into rr->data by
133 * either the decryption or by the decompression. When the data is 'copied'
134 * into the rr->data buffer, rr->input will be pointed at the new buffer
138 * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
139 * bytes of encrypted compressed stuff.
142 /* check is not needed I believe */
143 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
144 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
148 /* decrypt in place in 'rr->input' */
149 rr->data = rr->input;
150 rr->orig_len = rr->length;
152 if (rl->md_ctx != NULL) {
153 const EVP_MD *tmpmd = EVP_MD_CTX_get0_md(rl->md_ctx);
156 imac_size = EVP_MD_get_size(tmpmd);
157 if (!ossl_assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE)) {
158 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
161 mac_size = (size_t)imac_size;
165 if (rl->use_etm && rl->md_ctx) {
168 if (rr->orig_len < mac_size) {
169 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
172 rr->length -= mac_size;
173 mac = rr->data + rr->length;
174 i = rl->funcs->mac(rl, rr, md, 0 /* not send */);
175 if (i == 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
176 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
177 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
181 * We've handled the mac now - there is no MAC inside the encrypted
188 * Set a mark around the packet decryption attempt. This is DTLS, so
189 * bad packets are just ignored, and we don't want to leave stray
190 * errors in the queue from processing bogus junk that we ignored.
193 enc_err = rl->funcs->cipher(rl, rr, 1, 0, &macbuf, mac_size);
197 * 0: if the record is publicly invalid, or an internal error, or AEAD
198 * decryption failed, or ETM decryption failed.
199 * 1: Success or MTE decryption failed (MAC will be randomised)
203 if (rl->alert != 0) {
204 /* SSLfatal() got called */
207 /* For DTLS we simply ignore bad packets. */
209 rl->packet_length = 0;
212 ERR_clear_last_mark();
213 OSSL_TRACE_BEGIN(TLS) {
214 BIO_printf(trc_out, "dec %zd\n", rr->length);
215 BIO_dump_indent(trc_out, rr->data, rr->length, 4);
216 } OSSL_TRACE_END(TLS);
218 /* r->length is now the compressed data plus mac */
220 && (rl->enc_ctx != NULL)
221 && (EVP_MD_CTX_get0_md(rl->md_ctx) != NULL)) {
222 /* rl->md_ctx != NULL => mac_size != -1 */
224 i = rl->funcs->mac(rl, rr, md, 0 /* not send */ );
225 if (i == 0 || macbuf.mac == NULL
226 || CRYPTO_memcmp(md, macbuf.mac, mac_size) != 0)
228 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
233 /* decryption failed, silently discard message */
235 rl->packet_length = 0;
239 /* r->length is now just compressed */
240 if (rl->expand != NULL) {
241 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
242 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
243 SSL_R_COMPRESSED_LENGTH_TOO_LONG);
246 if (!tls_do_uncompress(rl, rr)) {
247 RLAYERfatal(rl, SSL_AD_DECOMPRESSION_FAILURE, SSL_R_BAD_DECOMPRESSION);
253 * Check if the received packet overflows the current Max Fragment
256 if (rl->max_frag_len > 0 && rr->length > rl->max_frag_len) {
257 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(SSL3_BUFFER));
307 memcpy(&(rdata->rrec), &rl->rrec[0], sizeof(SSL3_RECORD));
312 rl->packet_length = 0;
313 memset(&rl->rbuf, 0, sizeof(SSL3_BUFFER));
314 memset(&rl->rrec[0], 0, sizeof(rl->rrec[0]));
317 if (!rlayer_setup_read_buffer(rl)) {
318 /* SSLfatal() already called */
319 OPENSSL_free(rdata->rbuf.buf);
325 if (pqueue_insert(queue->q, item) == NULL) {
326 /* Must be a duplicate so ignore it */
327 OPENSSL_free(rdata->rbuf.buf);
335 /* copy buffered record into OSSL_RECORD_LAYER structure */
336 static int dtls_copy_rlayer_record(OSSL_RECORD_LAYER *rl, pitem *item)
338 DTLS_RLAYER_RECORD_DATA *rdata;
340 rdata = (DTLS_RLAYER_RECORD_DATA *)item->data;
342 SSL3_BUFFER_release(&rl->rbuf);
344 rl->packet = rdata->packet;
345 rl->packet_length = rdata->packet_length;
346 memcpy(&rl->rbuf, &(rdata->rbuf), sizeof(SSL3_BUFFER));
347 memcpy(&rl->rrec[0], &(rdata->rrec), sizeof(SSL3_RECORD));
349 /* Set proper sequence number for mac calculation */
350 memcpy(&(rl->sequence[2]), &(rdata->packet[5]), 6);
355 static int dtls_retrieve_rlayer_buffered_record(OSSL_RECORD_LAYER *rl,
356 record_pqueue *queue)
360 item = pqueue_pop(queue->q);
362 dtls_copy_rlayer_record(rl, item);
364 OPENSSL_free(item->data);
374 * Call this to get a new input record.
375 * It will return <= 0 if more data is needed, normally due to an error
376 * or non-blocking IO.
377 * When it finishes, one packet has been decoded and can be found in
378 * ssl->s3.rrec.type - is the type of record
379 * ssl->s3.rrec.data - data
380 * ssl->s3.rrec.length - number of bytes
382 int dtls_get_more_records(OSSL_RECORD_LAYER *rl)
384 int ssl_major, ssl_minor;
388 unsigned char *p = NULL;
389 unsigned short version;
390 DTLS1_BITMAP *bitmap;
391 unsigned int is_next_epoch;
395 rl->num_released = 0;
399 if (rl->rbuf.buf == NULL) {
400 if (!rlayer_setup_read_buffer(rl)) {
401 /* RLAYERfatal() already called */
402 return OSSL_RECORD_RETURN_FATAL;
407 /* if we're renegotiating, then there may be buffered records */
408 if (dtls_retrieve_rlayer_buffered_record(rl, &rl->processed_rcds)) {
410 return OSSL_RECORD_RETURN_SUCCESS;
413 /* get something from the wire */
415 /* check if we have the header */
416 if ((rl->rstate != SSL_ST_READ_BODY) ||
417 (rl->packet_length < DTLS1_RT_HEADER_LENGTH)) {
418 rret = rl->funcs->read_n(rl, DTLS1_RT_HEADER_LENGTH,
419 SSL3_BUFFER_get_len(&rl->rbuf), 0, 1, &n);
420 /* read timeout is handled by dtls1_read_bytes */
421 if (rret < OSSL_RECORD_RETURN_SUCCESS) {
422 /* SSLfatal() already called if appropriate */
423 return rret; /* error or non-blocking */
426 /* this packet contained a partial record, dump it */
427 if (rl->packet_length != DTLS1_RT_HEADER_LENGTH) {
428 rl->packet_length = 0;
432 rl->rstate = SSL_ST_READ_BODY;
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);
455 * Lets check the version. We tolerate alerts that don't have the exact
456 * version number (e.g. because of protocol version errors)
458 if (!rl->is_first_record && rr->type != SSL3_RT_ALERT) {
459 if (version != rl->version) {
460 /* unexpected version, silently discard */
463 rl->packet_length = 0;
470 (rl->version == DTLS_ANY_VERSION ? DTLS1_VERSION_MAJOR
471 : rl->version >> 8)) {
472 /* wrong version, silently discard record */
475 rl->packet_length = 0;
479 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
480 /* record too long, silently discard it */
483 rl->packet_length = 0;
489 * If received packet overflows maximum possible fragment length then
490 * silently discard it
492 if (rl->max_frag_len > 0
493 && rr->length > rl->max_frag_len + SSL3_RT_MAX_ENCRYPTED_OVERHEAD) {
494 /* record too long, silently discard it */
497 rl->packet_length = 0;
501 /* now rl->rstate == SSL_ST_READ_BODY */
504 /* rl->rstate == SSL_ST_READ_BODY, get and decode the data */
507 rl->packet_length - DTLS1_RT_HEADER_LENGTH) {
508 /* now rl->packet_length == DTLS1_RT_HEADER_LENGTH */
510 rret = rl->funcs->read_n(rl, more, more, 1, 1, &n);
511 /* this packet contained a partial record, dump it */
512 if (rret < OSSL_RECORD_RETURN_SUCCESS || n != more) {
513 if (rl->alert != 0) {
514 /* read_n() called RLAYERfatal() */
515 return OSSL_RECORD_RETURN_FATAL;
519 rl->packet_length = 0;
524 * now n == rr->length,
525 * and rl->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length
528 /* set state for later operations */
529 rl->rstate = SSL_ST_READ_HEADER;
531 /* match epochs. NULL means the packet is dropped on the floor */
532 bitmap = dtls_get_bitmap(rl, rr, &is_next_epoch);
533 if (bitmap == NULL) {
535 rl->packet_length = 0; /* dump this record */
536 goto again; /* get another record */
538 #ifndef OPENSSL_NO_SCTP
539 /* Only do replay check if no SCTP bio */
540 if (!BIO_dgram_is_sctp(rl->bio)) {
542 /* Check whether this is a repeat, or aged record. */
543 if (!dtls_record_replay_check(rl, bitmap)) {
546 rl->packet_length = 0; /* dump this record */
547 goto again; /* get another record */
549 #ifndef OPENSSL_NO_SCTP
553 /* just read a 0 length packet */
554 if (rr->length == 0) {
560 * If this record is from the next epoch (either HM or ALERT), and a
561 * handshake is currently in progress, buffer it since it cannot be
562 * processed at this time.
566 if (dtls_rlayer_buffer_record(rl,
567 &(rl->unprocessed_rcds),
569 /* SSLfatal() already called */
570 return OSSL_RECORD_RETURN_FATAL;
575 rl->packet_length = 0;
579 if (!dtls_process_record(rl, bitmap)) {
580 if (rl->alert != 0) {
581 /* dtls_process_record() called RLAYERfatal */
582 return OSSL_RECORD_RETURN_FATAL;
586 rl->packet_length = 0; /* dump this record */
587 goto again; /* get another record */
591 return OSSL_RECORD_RETURN_SUCCESS;
595 static int dtls_free(OSSL_RECORD_LAYER *rl)
598 size_t left, written;
600 DTLS_RLAYER_RECORD_DATA *rdata;
608 * This record layer is closing but we still have data left in our
609 * buffer. It must be destined for the next epoch - so push it there.
611 ret = BIO_write_ex(rl->next, rbuf->buf + rbuf->offset, left, &written);
615 if (rl->unprocessed_rcds.q != NULL) {
616 while ((item = pqueue_pop(rl->unprocessed_rcds.q)) != NULL) {
617 rdata = (DTLS_RLAYER_RECORD_DATA *)item->data;
618 /* Push to the next record layer */
619 /* TODO(RECLAYER): Handle SCTP meta data */
620 ret &= BIO_write_ex(rl->next, rdata->packet, rdata->packet_length,
622 OPENSSL_free(rdata->rbuf.buf);
623 OPENSSL_free(item->data);
626 pqueue_free(rl->unprocessed_rcds.q);
629 if (rl->processed_rcds.q != NULL) {
630 while ((item = pqueue_pop(rl->processed_rcds.q)) != NULL) {
631 rdata = (DTLS_RLAYER_RECORD_DATA *)item->data;
632 OPENSSL_free(rdata->rbuf.buf);
633 OPENSSL_free(item->data);
636 pqueue_free(rl->processed_rcds.q);
639 return tls_free(rl) && ret;
643 dtls_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
644 int role, int direction, int level, unsigned int epoch,
645 unsigned char *key, size_t keylen, unsigned char *iv,
646 size_t ivlen, unsigned char *mackey, size_t mackeylen,
647 const EVP_CIPHER *ciph, size_t taglen,
648 /* TODO(RECLAYER): This probably should not be an int */
650 const EVP_MD *md, const SSL_COMP *comp, BIO *prev,
651 BIO *transport, BIO *next, BIO_ADDR *local, BIO_ADDR *peer,
652 const OSSL_PARAM *settings, const OSSL_PARAM *options,
653 const OSSL_DISPATCH *fns, void *cbarg,
654 OSSL_RECORD_LAYER **retrl)
659 ret = tls_int_new_record_layer(libctx, propq, vers, role, direction, level,
660 key, keylen, iv, ivlen, mackey, mackeylen,
661 ciph, taglen, mactype, md, comp, prev,
662 transport, next, local, peer, settings,
663 options, fns, cbarg, retrl);
665 if (ret != OSSL_RECORD_RETURN_SUCCESS)
668 (*retrl)->unprocessed_rcds.q = pqueue_new();
669 (*retrl)->processed_rcds.q = pqueue_new();
670 if ((*retrl)->unprocessed_rcds.q == NULL || (*retrl)->processed_rcds.q == NULL) {
673 RLAYERfatal(*retrl, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
674 return OSSL_RECORD_RETURN_FATAL;
677 (*retrl)->unprocessed_rcds.epoch = epoch + 1;
678 (*retrl)->processed_rcds.epoch = epoch;
680 (*retrl)->isdtls = 1;
681 (*retrl)->epoch = epoch;
682 (*retrl)->in_init = 1;
685 case DTLS_ANY_VERSION:
686 (*retrl)->funcs = &dtls_any_funcs;
688 case DTLS1_2_VERSION:
691 (*retrl)->funcs = &dtls_1_funcs;
694 /* Should not happen */
695 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
696 ret = OSSL_RECORD_RETURN_FATAL;
700 ret = (*retrl)->funcs->set_crypto_state(*retrl, level, key, keylen, iv,
701 ivlen, mackey, mackeylen, ciph,
702 taglen, mactype, md, comp);
705 if (ret != OSSL_RECORD_RETURN_SUCCESS) {
706 OPENSSL_free(*retrl);
712 const OSSL_RECORD_METHOD ossl_dtls_record_method = {
713 dtls_new_record_layer,
716 tls_unprocessed_read_pending,
717 tls_processed_read_pending,
718 tls_app_data_pending,
720 tls_get_max_record_len,
723 tls_retry_write_records,
728 tls_set_protocol_version,
730 tls_set_first_handshake,
731 tls_set_max_pipelines,