libcoap icon indicating copy to clipboard operation
libcoap copied to clipboard

Confirmable Duplicate Processing for Requests Depends on Optional Response Caching

Open LiD0209 opened this issue 6 months ago • 4 comments

Confirmable Duplicate Processing for Requests Depends on Optional Response Caching

Summary

libcoap has some duplicate-handling support for Confirmable traffic, but for incoming duplicate Confirmable requests the effective "process only once" behavior is not a default guarantee.

The key point is:

  • by default, duplicate Confirmable requests can be delivered to the application handler again
  • duplicate request replay protection is materially improved only when COAP_BLOCK_CACHE_RESPONSE is explicitly enabled

This keeps the finding in partial rather than satisfied: libcoap has a mitigation path, but it is optional and disabled by default.

Standard Requirement

CoAP standard: RFC 7252, Section 4.5

https://www.rfc-editor.org/rfc/rfc7252#section-4.5

Relevant RFC language:

SHOULD acknowledge each duplicate copy
process any request or response in a given message only once
within the EXCHANGE_LIFETIME

RFC 7252 does leave room for application semantics and idempotent handling, so this is not an unconditional MUST-style violation for every deployment. But the general expectation is that duplicate Confirmable messages should not repeatedly trigger non-idempotent processing.

Relevant Source Code

Source file: libcoap-develop/src/coap_net.c

Duplicate request replay is only attempted when cached-response mode is enabled and a cached ACK response exists:

if (COAP_PDU_IS_REQUEST(pdu) && session->cached_pdu &&
    (session->block_mode & COAP_BLOCK_CACHE_RESPONSE)) {
  coap_digest_t digest;

  coap_pdu_cksum(pdu, &digest);
  if (memcmp(&digest, &session->cached_pdu_cksum, sizeof(digest)) == 0) {
    coap_pdu_reference_lkd(session->cached_pdu);
    coap_log_debug("Retransmit response to duplicate request\n");
    if (coap_send_internal(session, session->cached_pdu, NULL) != COAP_INVALID_MID) {
      goto finish;
    }
  }
}

The cached response is only stored when COAP_BLOCK_CACHE_RESPONSE is set:

if ((session->block_mode & COAP_BLOCK_CACHE_RESPONSE) &&
    session->cached_pdu != pdu &&
    request_pdu && COAP_PROTO_NOT_RELIABLE(session->proto) &&
    COAP_PDU_IS_REQUEST(request_pdu) &&
    COAP_PDU_IS_RESPONSE(pdu) && pdu->type == COAP_MESSAGE_ACK) {
  coap_delete_pdu_lkd(session->cached_pdu);
  session->cached_pdu = pdu;
  coap_pdu_reference_lkd(session->cached_pdu);
  coap_pdu_cksum(request_pdu, &session->cached_pdu_cksum);
}

Some duplicate suppression exists for recent incoming CON/ACK response handling, but this is not a general request-side EXCHANGE_LIFETIME table:

if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
  if (rcvd->type == COAP_MESSAGE_CON) {
    if (rcvd->mid == session->last_con_mid) {
      /* Duplicate response: send ACK/RST, but don't process */
      if (session->last_con_handler_res == COAP_RESPONSE_OK)
        coap_send_ack_lkd(session, rcvd);
      else
        coap_send_rst_lkd(session, rcvd);
      return;
    }
    session->last_con_mid = rcvd->mid;
  } else if (rcvd->type == COAP_MESSAGE_ACK) {
    if (rcvd->mid == session->last_ack_mid) {
      /* Duplicate response */
      return;
    }
    session->last_ack_mid = rcvd->mid;
  }
}

Default context allocation starts zeroed:

c = coap_malloc_type(COAP_CONTEXT, sizeof(coap_context_t));
if (!c) {
  coap_log_emerg("coap_init: malloc: failed\n");
  return NULL;
}
memset(c, 0, sizeof(coap_context_t));

New sessions inherit context->block_mode:

session->block_mode = context->block_mode;

That means COAP_BLOCK_CACHE_RESPONSE is not on unless the application explicitly enables it through coap_context_set_block_mode().

Runtime Reproduction

Repro file:

  • test-libcoap/101-150/repro_id143_duplicate_confirmable_cache.c

The repro:

  • starts a UDP libcoap server
  • registers a non-idempotent POST /counter handler
  • increments a counter every time the handler runs
  • sends the exact same Confirmable POST twice
  • keeps the same MID and the same Token across both sends
  • runs two scenarios:
    • default configuration
    • COAP_BLOCK_CACHE_RESPONSE enabled

Build command:

gcc -ID:\project\conditionFuzzing\libcoap-develop\include -ID:\project\conditionFuzzing\libcoap-develop\include\coap3 -ID:\project\conditionFuzzing\build-libcoap-151-200-lib\include -ID:\project\conditionFuzzing\build-libcoap-151-200-lib -o D:\project\conditionFuzzing\test-libcoap\101-150\repro_id143_duplicate_confirmable_cache.exe D:\project\conditionFuzzing\test-libcoap\101-150\repro_id143_duplicate_confirmable_cache.c D:\project\conditionFuzzing\build-libcoap-151-200-lib\libcoap-3.a -lws2_32 -liphlpapi -lwinpthread

Observed runtime output:

=== default ===
enable_cache_response=0 handler_calls=2 recv_count=2
response1 len=18 type=2 code=2.04 mid=0x1234 tkl=4 payload="counter=1"
response2 len=18 type=2 code=2.04 mid=0x1234 tkl=4 payload="counter=2"
responses_identical=0
=== cache_response ===
enable_cache_response=1 handler_calls=1 recv_count=2
response1 len=18 type=2 code=2.04 mid=0x1234 tkl=4 payload="counter=1"
response2 len=18 type=2 code=2.04 mid=0x1234 tkl=4 payload="counter=1"
responses_identical=1

Interpretation:

  • under default settings, the same duplicate Confirmable request reached the application twice
  • with COAP_BLOCK_CACHE_RESPONSE enabled, the duplicate request was answered from cache and the handler ran only once

This runtime behavior matches the source-level reading: duplicate suppression for requests depends on optional response caching rather than being a default request-side lifetime guarantee.

Inconsistency Reason

The implementation has useful duplicate-handling components, but the default path does not demonstrate a complete received-request duplicate table retained for EXCHANGE_LIFETIME.

What exists:

  • optional cached ACK response replay when COAP_BLOCK_CACHE_RESPONSE is enabled
  • recent last_con_mid and last_ack_mid checks in some response-handling paths

What is missing or conditional:

  • a default, general request-side duplicate suppression mechanism keyed to peer + Message ID for the relevant lifetime

So the library can behave correctly for this scenario when optional response caching is turned on, but does not provide that as the default guarantee.

Security Impact

The security impact is application-dependent, but real.

If an application exposes non-idempotent Confirmable operations such as:

  • POST that creates records
  • POST or PUT that increments counters, quotas, balances, or usage state
  • actuator commands that trigger one-shot physical actions
  • webhook-style request handlers with external side effects

then duplicate delivery under default settings can cause repeated execution of the same operation.

Potential consequences include:

  • duplicated state changes
  • repeated financial or quota-consuming actions
  • duplicate job creation or message enqueueing
  • duplicate audit/log entries that hide the true execution path
  • denial-of-service amplification against expensive handlers by replaying the same valid Confirmable request

The impact is stronger when all of the following are true:

  • the deployment uses unsecured UDP CoAP or otherwise permits replay by an on-path attacker or a sender that can retransmit crafted duplicates
  • the application handler is non-idempotent
  • the deployment relies on libcoap core behavior for duplicate suppression and does not add its own application-side deduplication

The impact is weaker when:

  • handlers are idempotent
  • the application independently tracks processed requests
  • COAP_BLOCK_CACHE_RESPONSE is enabled and the traffic pattern matches the cached-response replay path

So this is best classified as a partial security-relevant inconsistency: not every libcoap deployment is vulnerable in practice, but the default behavior can allow duplicate non-idempotent processing.

Recheck Result

This remains a real partial inconsistency.

It should not be overstated as "libcoap always violates RFC 7252 duplicate handling", because:

  • RFC 7252 uses SHOULD language here
  • idempotent operations and application semantics matter
  • libcoap does provide an optional cached-response mitigation path

However, it is also not correct to treat the issue as purely theoretical, because the local runtime repro shows duplicate handler execution under default configuration and suppression only after explicitly enabling COAP_BLOCK_CACHE_RESPONSE.

Test / Check Result

The phase2 script was run from test-libcoap/101-150:

python worker_135_150_phase2_check.py

Observed result:

PASS: tx_mid randomized for non-reliable sessions
PASS: new MID implementation increments session->tx_mid
PASS: outgoing duplicate guard only scans session->delayqueue
PASS: no explicit EXCHANGE_LIFETIME MID cache found
PASS: ICMP destination unreachable mapped to -2
PASS: ICMP issue mapped to COAP_NACK_ICMP_ISSUE
PASS: no ICMP original CoAP header validation code found

Additional runtime confirmation from repro_id143_duplicate_confirmable_cache.exe:

default mode: duplicate CON POST invoked handler twice
cache-response mode: duplicate CON POST invoked handler once and replayed cached ACK response

LiD0209 avatar May 07 '26 07:05 LiD0209

I have a small related reproducer that appears to exercise a changed-token / changed-payload variant of this duplicate Confirmable request behavior.

reproduce_raw_coap_sequence.py
from __future__ import annotations

import argparse
import socket
import time

PACKETS = [
    (
        "same-mid-put-store-a",
        "4303356135b301b573746f726510ff6964656e7469666965722d736964652d6566666563742d41",
    ),
    (
        "same-mid-put-store-b",
        "4303356135b302b573746f726510ff6964656e7469666965722d736964652d6566666563742d42",
    ),
    (
        "fresh-get-store-after-same-mid",
        "4301356235b3ffb573746f7265",
    ),
]


def coap_type_name(type_id: int) -> str:
    return {0: "CON", 1: "NON", 2: "ACK", 3: "RST"}.get(type_id, f"type-{type_id}")


def coap_code_name(code_byte: int) -> str:
    klass = code_byte >> 5
    detail = code_byte & 0x1F
    return f"{klass}.{detail:02d}"


def coap_token_hex(raw: bytes) -> str:
    if len(raw) < 4:
        return ""
    token_length = raw[0] & 0x0F
    return raw[4 : 4 + token_length].hex()


def payload_from_response(raw: bytes) -> str:
    if len(raw) < 4:
        return ""

    token_length = raw[0] & 0x0F
    index = 4 + token_length

    while index < len(raw):
        current = raw[index]

        if current == 0xFF:
            payload = raw[index + 1 :]
            try:
                return payload.decode("utf-8")
            except UnicodeDecodeError:
                return payload.hex()

        index += 1
        option_delta = current >> 4
        option_length = current & 0x0F

        if option_delta == 13:
            index += 1
        elif option_delta == 14:
            index += 2

        if option_length == 13:
            if index >= len(raw):
                return ""
            option_length = raw[index] + 13
            index += 1
        elif option_length == 14:
            if index + 1 >= len(raw):
                return ""
            option_length = int.from_bytes(raw[index : index + 2], "big") + 269
            index += 2
        elif option_length == 15:
            return ""

        index += option_length

    return ""


def main() -> int:
    parser = argparse.ArgumentParser(description="Replay raw CoAP datagrams for this issue")
    parser.add_argument("--host", default="127.0.0.1", help="target host/IP")
    parser.add_argument("--port", type=int, default=56831, help="target UDP port")
    parser.add_argument("--timeout", type=float, default=2.0, help="receive timeout per packet")
    parser.add_argument("--delay", type=float, default=0.15, help="delay between packets")
    args = parser.parse_args()

    addr = (args.host, args.port)
    print(f"target={args.host}:{args.port}")

    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
        sock.settimeout(args.timeout)

        for step, hex_bytes in PACKETS:
            raw = bytes.fromhex(hex_bytes)
            print(f"\n>>> {step}")
            print(f"sent_hex={hex_bytes}")

            sock.sendto(raw, addr)

            try:
                response, peer = sock.recvfrom(4096)
            except socket.timeout:
                print("response=timeout")
            else:
                msg_type = coap_type_name((response[0] >> 4) & 0x03) if response else "parse-error"
                code = coap_code_name(response[1]) if len(response) >= 2 else "parse-error"
                token = coap_token_hex(response)
                payload = payload_from_response(response)

                print(f"from={peer[0]}:{peer[1]}")
                print(f"response_type={msg_type}")
                print(f"response_code={code}")
                print(f"response_token={token}")
                print(f"response_payload={payload!r}")
                print(f"response_hex={response.hex()}")

            time.sleep(args.delay)

    return 0


if __name__ == "__main__":
    raise SystemExit(main())

In my test, I send three raw CoAP datagrams from the same UDP socket to a local libcoap server:

  1. Confirmable PUT /store, MID 0x3561, Token 35b301, payload identifier-side-effect-A
  2. Confirmable PUT /store, same MID 0x3561, changed Token 35b302, payload identifier-side-effect-B
  3. fresh Confirmable GET /store, MID 0x3562, Token 35b3ff

Observed with libcoap 4.3.5b:

python3 reproduce_raw_coap_sequence.py --host 127.0.0.1 --port 56831
>>> same-mid-put-store-a
response_type=ACK
response_code=2.04
response_token=35b301
response_hex=6344356135b301

>>> same-mid-put-store-b
response_type=ACK
response_code=2.04
response_token=35b302
response_hex=6344356135b302

>>> fresh-get-store-after-same-mid
response_type=ACK
response_code=2.05
response_token=35b3ff
response_payload='identifier-side-effect-B'
response_hex=6345356235b3ffc0ff6964656e7469666965722d736964652d6566666563742d42

The second response echoes the second Token 35b302, and the final GET shows that /store was updated to the second payload.

For comparison, Californium 3.14.0, aiocoap 0.4.17, and go-coap 3.5.1 treated the second same-MID datagram as a duplicate/replay case: the second response echoed the first Token 35b301, and the final /store value remained identifier-side-effect-A.

This is not exactly the same as the reproduction in this issue, because the duplicate datagram here changes Token and payload rather than repeating the exact same request. But it seems closely related to the same received-request duplicate handling path. I am sharing it here rather than opening a separate issue unless maintainers would prefer a standalone report for the changed-token case.

gahssi avatar Jun 23 '26 09:06 gahssi

@gahssi Thanks for providing the PoC code to be able to reproduce the issue. I will look at getting it fixed.

mrdeep1 avatar Jun 30 '26 12:06 mrdeep1

See #2089 for a fix. Please confirm this works for you.

mrdeep1 avatar Jul 11 '26 13:07 mrdeep1

Closed as fixed.

mrdeep1 avatar Jul 28 '26 15:07 mrdeep1