Implementation and Operations: CoAP Security Reference
More
Depth: Practitioner
Progress saves as you read. Mark sections complete as you go; your progress appears in the sidebar.
Related reference: CoAP message types.
Start With the Decision
CoAP is a request-and-response protocol for constrained devices. A resource is a named target, such as /config/interval; PUT requests a change to its state. A client sends a confirmable (CON) PUT /config/interval to change a sensor’s reporting interval. The server sends an empty acknowledgment (ACK), then a separate 4.05 Method Not Allowed response carrying the request’s Token, the value used to correlate a response with its request. Should the operator increase the retry timeout?
No. The response shows that the request reached CoAP resource handling, but this resource does not support PUT. Check the resource’s method contract. The empty ACK alone showed receipt of the CON message; it did not prove the configuration changed.
| Observed evidence | Next lookup | Decision |
|---|---|---|
| No CoAP response; security handshake failed | Troubleshooting | Check security setup before resource handling |
| Empty ACK, no final response yet | Implementation patterns | Track the separate response using the Token |
| 4.04 or 4.05 response | Response codes | Check resource path or supported method |
| Large transfer fails | MTU pitfall | Inspect packet size and block-transfer evidence |
This reference covers base CoAP over the User Datagram Protocol (UDP) in RFC 7252, Observe notifications in RFC 7641, and block transfer, which splits a representation into smaller exchanges, in RFC 7959. Library behavior and deployment policy require separate verification.
Route Overview
Continue with CoAP Security: CON and NON Trade-Offs.
Part Objectives
- Use response and trace evidence to select the next diagnostic test.
- State the observation that would confirm or reject the diagnosis.
Start With the Situation
Keep the configuration request as the running example. A resource is a named target such as /config/interval. Its contract defines supported methods, accepted payload formats, permissions, and response meanings. Diagnose against that contract before changing transport settings.
Overview
An endpoint is the addressed protocol peer. Use the linked tables to distinguish a missing response from a returned error. Record the endpoint, method, path, Token, message identifiers, timestamps, and response or timeout. Record the security mode and non-secret identity reference; never log keys.
Review CoAP Security: Protection and Application Fit for the security design that precedes these operational checks.
Learning Objectives
By the end of this chapter, you will be able to:
- distinguish message receipt from a completed resource operation
- choose a diagnostic test from a response code or missing-response trace
- verify a proposed fix against the resource contract
Chapter Roadmap
- Start With the Situation
- Overview
- CoAP Implementation Patterns
- Practical CoAP Implementation Resources
- Checkpoint: Operational Debugging
- Try It: CoAP Response Code Reference
- Troubleshooting Common Issues
- Common Problems and Solutions
- Common Pitfalls
- Common Pitfall: CoAP Message Size Exceeds MTU
- Common Pitfall: Misusing CON vs NON Message Types
CoAP Implementation Patterns
For the configuration request, PUT specifies the requested resource operation. CON enables acknowledgment and bounded retransmission. A Message ID identifies the message for acknowledgment and duplicate handling; the Token correlates the response with the request. An empty ACK uses the request’s Message ID, while a separate response carries the request’s Token and its own Message ID.
| Contract | Inspect in the running example | What it establishes |
|---|---|---|
| Resource operation | PUT, /config/interval, payload format | Whether the requested change is supported |
| Message exchange | CON, ACK, Message ID, retries | Receipt or exchange failure; no actuation guarantee |
| Request/response | Token, endpoint and security context, final code | Which request the result belongs to |
| Observe, if used | GET with Observe option, Token and notification sequence | Updates to a resource representation; not a configuration write |
See RFC 7252 §§4.2, 4.5, 5.2–5.3 and 5.8 and RFC 7641 §§3.2–3.4. A CoAP stack implements message exchange; application code must still define permissions and verify the intended state.
Use Figure 1 as a role map. Observe notification order uses serial-number comparison, including wraparound; it is not an indefinitely increasing counter.
CoAP vs HTTP vs MQTT: Performance Comparison
A short fixed header is not a complete packet-size or energy comparison. For the configuration request, count the encoded path, Token, options, payload marker and payload, then UDP/IP and security overhead. Include acknowledgments, retries and any security handshake in an exchange measurement.
| Protocol scope | Header fact or old worksheet assumption | Limit of comparison |
|---|---|---|
| CoAP over UDP, RFC 7252 §3 | 4-byte fixed header | Token, options and payload framing add bytes |
| HTTP/1.1 over TCP | Old worksheet assumed 200 header bytes | Assumption, not a protocol minimum or measured request |
| MQTT over TCP | Old worksheet used the 2-byte minimum fixed header | A PUBLISH also needs variable-header fields, including a topic representation |
Do not select a protocol from these header rows. Measure complete exchanges on the target path, report bytes per completed operation and latency in milliseconds, and state connection/security reuse. The old per-message energy costs have no measurement source and cannot support a battery-life estimate.
Library and Tool Starting Points:
These links identify implementation projects, not guaranteed feature support. Check the installed version, security backend, Observe and block-transfer support before adopting an example.
- Python:
aiocoapviapip install aiocoapwith docs at aiocoap.readthedocs.io - Arduino/ESP32: CoAP Simple Library via Arduino Library Manager with docs at GitHub: coap-simple
- Node.js:
coapvianpm install coapwith docs at npmjs.com/package/coap - Java: Eclipse Californium via Maven dependency with docs at eclipse.org/californium
- C/C++: libcoap via system package with docs at libcoap.net
Testing and Debugging Tools:
Use a controlled local endpoint with a documented resource contract. Command options depend on the installed libcoap version; check its help before running these preserved examples.
-
coap-client(libcoap): Command-line CoAP client for testing# GET request coap-client -m get coap://localhost/temperature # POST with payload coap-client -m post coap://localhost/sensor -e "22.5" # Observe resource coap-client -m get -s 60 coap://localhost/temperature -
Wireshark: CoAP dissector included (filter:
coap) -
Record client and server versions alongside traces so a library-specific failure can be reproduced.
Example Implementation Patterns:
Pattern 1: Sensor Reading (CON exchange shown)
The preserved sketch below uses CON despite its former NON label. Its byte total and latency are unverified, and “Guaranteed” is incorrect: retries can end without a response. Use the message flow only; measure size and timing on the actual path.
Sensor → Gateway: CON GET /temperature
Gateway → Sensor: ACK 2.05 Content
Payload: 22.5°C
Overhead: 2 messages, ~50 bytes total
Latency: 1 RTT (~20-50ms on local network)
Reliability: Guaranteed (CON requires ACK)
Pattern 2: Frequent Updates (Observe)
This abbreviated flow omits the client ACKs required for the CON notifications shown. Observe extends GET; traffic and energy savings depend on update rate, polling policy and retries.
Client → Server: CON GET /temperature, Observe: 0
Server → Client: ACK 2.05 Content, Observe: 12
Initial value: 22.5°C
[30 seconds later]
Server → Client: CON 2.05 Content, Observe: 13
Updated value: 23.1°C
[30 seconds later]
Server → Client: CON 2.05 Content, Observe: 14
Updated value: 22.9°C
Overhead: 1 subscribe + N notifications
Battery savings: Avoid polling every 30s
Pattern 3: Multicast Discovery
FF02::FD is the link-local IPv6 All CoAP Nodes multicast address. Scope, interface membership and loss limit the replies; the sketch cannot establish that every device was found. Restrict discovery reachability and response volume to reduce reflection risk (RFC 7252 §§8,11.3,12.8).
Client → FF02::FD: NON GET /.well-known/core
Device1 → Client: NON 2.05 Content
</temperature>,</humidity>
Device2 → Client: NON 2.05 Content
</pressure>,</light>
Use case: Discover all CoAP devices on local network
Result: List of available resources from all devices
Checkpoint: Operational Debugging
Check the running example before changing a setting:
- The base RFC 7252 Token is 0–8 bytes. Match it within the endpoint and security context; do not use a Message ID alone to identify a separate response.
- Default ACK_TIMEOUT is 2 s, ACK_RANDOM_FACTOR is 1.5 and MAX_RETRANSMIT is 4. The first timeout is randomized between 2 and 3 s, then doubled. Maximum transmit span is 45 s and maximum transmit wait is 93 s (RFC 7252 §4.8); these are message-exchange bounds, not application deadlines.
- A returned 4.05 points to the method/resource contract. Increasing a retransmission timeout cannot make PUT supported.
CoAP Response Code Categories
| Class, base CoAP | Meaning | Diagnostic use |
|---|---|---|
| 2.xx | Success | Read the specific code; an empty ACK has no success code |
| 4.xx | Client error | Check request, resource contract and authorization |
| 5.xx | Server error | Check server or upstream evidence before retrying |
The tool lists selected base codes and block-transfer codes; it is not an exhaustive registry. See RFC 7252 §5.9 and RFC 7959 §4.
The troubleshooting material below reuses the same pattern: identify the failed layer first, then choose the smallest fix that matches that layer.
Hands-On Learning Resources
Use a local fixture rather than assuming a public server is available. These steps describe a practice test; no requests have been run for this page.
- Configure an isolated test server with
/temperaturesupporting GET and/config/intervalsupporting GET but rejecting PUT. Record the server version and this contract. Expected: both resources are registered. A missing resource would confound a method-rejection test. - Run the preserved local GET command above after confirming the fixture address. Expected:
2.05 Contentwith a response Token matching the request. A timeout calls for endpoint/transport checks;4.04calls for path/registration checks. - Send a CON PUT to
/config/intervalusing the installed client’s documented syntax and capture the exchange. Expected:4.05. If the server first sends an empty ACK, continue to the separate response.2.04means the fixture permits PUT; inspect the fixture before claiming the intended rejection test passed. - Record method, path, endpoint, Token, Message IDs, timestamps, final code and next test. Expected: “check supported methods,” with 4.05 as evidence. “Raise retry timeout” does not explain the returned rejection.
Transfer: a secure firmware upload produces a failed Datagram Transport Layer Security (DTLS) handshake and no CoAP response. First compare the configured security modes, identity references and non-secret error logs. Changing Block1 size is premature because no CoAP resource exchange has been established.
Implementation reading: Californium client example, aiocoap guided tour, and ESP32 CoAP example. Verify examples against the selected release; availability was not checked here.
Troubleshooting Common Issues
Locate the last successful boundary before changing settings. A timeout alone does not identify the cause.
| Observation | Next test | Evidence that narrows the diagnosis |
|---|---|---|
| No reply to CON | Check endpoint, listener and allowed UDP path; inspect both ends | Request absent at server suggests a path/endpoint issue; arrival without reply requires server evidence |
| Empty ACK, no final response | Track separate response by Token and application deadline | ACK proves message receipt; handler completion remains unknown |
| DTLS handshake fails | Compare configured security modes and identity setup | Non-secret handshake error precedes CoAP processing |
| 4.04 | Check exact path and registration | Correct endpoint responds but cannot find the target |
| 4.05 | Check supported methods on that path | Running example rejects PUT; transport tuning will not fix it |
| Block transfer stops | Inspect Block1/Block2 options, byte offsets and packet sizes | Smaller negotiated blocks help only if size/fragmentation is the cause |
| Observe updates stop | Check freshness, registration and reachability | Re-register if needed; silence alone does not prove a server crash |
| Multicast has no replies | Check interface, membership and multicast scope/routing | FF02::FD is link-local; FF05::FD is site-local, not evidence of device presence |
Debug Checklist:
- Endpoint and security: verify the configured UDP listener (defaults: 5683 for CoAP, 5684 for CoAP over DTLS), firewall and interface. Ping success does not prove UDP reachability. Record compatible DTLS configuration and peer verification results; do not disable production security to test connectivity.
- Request/response: record URI, method, message type, Token, Message ID and code. CON can be acknowledged with an empty ACK before a separate response; NON has no message-layer ACK but can still receive a response. Use the configured randomized retry schedule, not fixed 2/4/8/16 s expectations.
- Observe: registration uses GET with Observe=0. Freshness is whether a representation is still usable under its age limit. Match notifications to the registration and compare sequence values with wrap-aware rules (RFC 7641 §3.4); apply a freshness policy before declaring data current.
- Block transfer: Block1 carries request blocks; Block2 carries response blocks. Check byte offsets and consistent representation assembly, including block-size changes and retransmissions (RFC 7959 §2).
- Load and duplicates: measure retry rate, response latency and handler load. A duplicate CON normally receives the same acknowledgment while the request is processed once (RFC 7252 §4.5); simply dropping every duplicate can provoke more retries.
Common Error Codes:
| Code | Meaning and next check |
|---|---|
| 2.01 Created | Creation succeeded; check location where applicable; POST or PUT may create |
| 2.02 Deleted | Deletion succeeded |
| 2.03 Valid | Cached representation validated; use the ETag request option |
| 2.04 Changed | Change succeeded at the resource interface; verify physical action separately |
| 2.05 Content | Representation returned |
| 4.00 / 4.02 | Bad request / bad option; inspect request syntax or critical options |
| 4.01 / 4.03 | Missing appropriate authorization / refusal that authorization will not resolve |
| 4.04 / 4.05 | Missing resource / method unsupported on that resource |
| 5.00 / 5.03 | Unexpected server condition / temporary unavailability; inspect server evidence and any Max-Age retry hint |
Tools for Debugging:
Use libcoap client/server tools for controlled probes and Wireshark (coap) for decoded exchanges. The preserved tcpdump -i any port 5683 -vv command is scoped to that port and omits the default secure port. Encrypted application details require authorized endpoint logs. Californium and aiocoap logging depend on their installed versions.
Common Pitfalls
A large configuration may work over Wi-Fi but fail on a constrained path. The maximum transmission unit (MTU) is the largest IP packet the path can carry without IP fragmentation; it is not a CoAP payload allowance. Account for IP, UDP, security and CoAP fields before choosing a block size.
The mistake: treating a payload limit from one network as universally safe.
Symptoms: small requests succeed while larger requests or responses fail; a trace may show fragmentation without successful reassembly.
Why it happens: losing a required fragment prevents reassembly. CoAP retransmission repeats a message rather than selectively retransmitting IP fragments. Link-layer recovery is a separate mechanism. IPv6’s minimum MTU is 1280 bytes; a 127-byte IEEE 802.15.4 frame is a link-layer limit, not the IPv6 MTU. Header compression and security change the available payload budget (RFC 7252 §4.6).
The protected Python example below delegates block handling to the library but does not explicitly set the block size described in its comments. The C example uses placeholder helpers and illustrative 64/1024-byte thresholds; its “Safe” comments are unverified and do not establish a path budget.
The fix:
# Use CoAP Block-wise Transfer (RFC 7959) for large payloads
from aiocoap import Message, Context
from aiocoap.numbers.codes import GET
async def get_large_resource(uri):
context = await Context.create_client_context()
# Request with Block2 option - library handles chunking
request = Message(code=GET, uri=uri)
# Block size: 64 bytes (szx=2), 128 bytes (szx=3), 256 bytes (szx=4)
# Smaller blocks = more round trips but works on constrained networks
response = await context.request(request).response
return response.payload # Library reassembles blocks automatically
// Embedded C: Check payload size before sending
#define COAP_MAX_PAYLOAD_6LOWPAN 64 // Safe for 802.15.4
#define COAP_MAX_PAYLOAD_UDP 1024 // Safe for most networks
size_t max_payload = is_constrained_network() ?
COAP_MAX_PAYLOAD_6LOWPAN : COAP_MAX_PAYLOAD_UDP;
if (payload_len > max_payload) {
// Use Block1 (request) or Block2 (response) transfer
return coap_send_blockwise(payload, payload_len, max_payload);
}
Prevention: negotiate a supported block size and test the complete secured packet on the constrained path. Expected: all byte ranges arrive and the assembled representation is consistent. If smaller blocks still fail, inspect loss, authorization, total-size limits and server state before attributing the failure to MTU.
For the configuration request, CON provides bounded retries and receipt evidence. It cannot make an unsupported PUT succeed or prove an actuator changed state. NON omits message-layer acknowledgment; a NON request can still have a response.
The mistake: choosing one message type for every workload or treating a missing response as proof that no action happened.
Symptoms: unnecessary ACK/retry traffic for replaceable readings, or an unknown command outcome after a timeout.
Why it happens: the exchange policy is mistaken for the application result. A server may act and then lose its response. Before repeating an action, read back state or use application duplicate controls.
The protected Python below is a sketch: context must already exist and security is not configured. Its “~5x” battery comment is unverified; an ACK provides no security guarantee. is_successful() checks the response class, not the physical door state, and the exception branch means outcome unknown rather than proof the command failed.
The fix:
from aiocoap import Message, Context
from aiocoap.numbers.codes import GET, PUT
from aiocoap.numbers.types import CON, NON
# NON for periodic telemetry (loss acceptable, battery critical)
async def send_temperature_reading(temp):
request = Message(
code=PUT,
mtype=NON, # Fire-and-forget, ~5x better battery life
uri='coap://server/sensors/temp',
payload=f'{temp}'.encode()
)
await context.request(request).response
# CON for critical commands (must know if it worked)
async def unlock_door():
request = Message(
code=PUT,
mtype=CON, # Need acknowledgment for security
uri='coap://door/lock',
payload=b'unlock'
)
try:
response = await context.request(request).response
return response.code.is_successful()
except Exception:
return False # Command failed, alert user
# CON for configuration changes (must be applied)
async def update_reporting_interval(seconds):
request = Message(
code=PUT,
mtype=CON, # Config must be confirmed
uri='coap://sensor/config/interval',
payload=str(seconds).encode()
)
return await context.request(request).response
Decision matrix:
| Workload | Candidate policy | Required evidence |
|---|---|---|
| Replaceable periodic reading | NON if occasional loss is acceptable | Freshness and measured loss meet application needs |
| Alarm or command | CON if receipt/failure detection is needed | Application result, deadline and safe retry behavior |
| Configuration update | CON plus supported method and readback | Returned result and observed setting agree |
| Status query | CON or NON according to response needs | Result arrives before it becomes stale |
| Firmware download | Block2 with a suitable exchange policy | Complete, consistent representation; CON supplies ACK behavior, not Block2 |
Prevention: choose per workload and test a lost response. For the running example, fix the method contract first; for the secure-upload transfer example, resolve the handshake first.
Continue to the Next Part
Carry this evidence into CoAP Security: CON and NON Trade-Offs, which begins with Try It: CON vs NON Message Type Advisor.
Detail notes moved from the chapter
Historical protected source blocks retained for the chapter preservation check.




