CON and NON Trade-Offs: CoAP Security Reference
More
Depth: Practitioner
Progress saves as you read. Mark sections complete as you go; your progress appears in the sidebar.
Start With the Decision
A hospital wearable sends a new vital-sign reading every 30 seconds. Suppose the gateway can tolerate a missing reading because the next reading replaces it. A non-confirmable (NON) CoAP message can suit that policy: CoAP does not acknowledge or retransmit it. Now the gateway changes the wearable’s sampling rate. If losing that change is unacceptable, a confirmable (CON) message provides acknowledgement and bounded retransmission when no acknowledgement arrives.
An acknowledgement (ACK) confirms receipt of a CON message; it does not by itself prove that a configuration change took effect. Check the application response and resulting state. CON can still fail after its retry limit.
Neither message type encrypts patient data. Datagram Transport Layer Security (DTLS) protects traffic between two security endpoints. Choose delivery behavior and the protected path separately, then check what security state survives the wearable’s sleep.
Route Overview
This is part 2 of 2. Review CoAP Security: Implementation and Operations for the preceding evidence.
Learning Objectives
- Choose CON or NON for a reading or configuration change, and explain what an ACK establishes.
- Identify who can read patient data when DTLS terminates at a gateway.
- Diagnose a failed send after sleep by checking retained security state before choosing recovery.
Chapter Roadmap
- Try It: CON vs NON Message Type Advisor
- Under the Hood: CoAP Security Trade-offs
- Worked Example: Hospital Wearable Device DTLS Configuration
- Decision Framework: CoAP Security Configuration Selection
- Common Mistake: Reusing DTLS Session Across Deep Sleep Cycles
- Checkpoint: Security Trade-offs
- Concept Relationships
- See Also
- Knowledge Check: Matching and Ordering
- Label the Diagram
- What’s Next
- Summary
- Key Takeaway
Under the Hood: CoAP Security Trade-offs
For the wearable, answer three questions in order: may this reading be lost, who may read it, and what state remains after sleep? Message type answers the first question. Security endpoints answer the second. The device and peer’s retained state answer the third. Increasing retries cannot repair missing keys or a broken security association.
Scenario: In this hypothetical hospital, 200 wearable monitors send heart rate, blood oxygen saturation (SpO2), and temperature readings every 30 seconds to a gateway. The gateway is an authorized reader of patient data. Occasional loss of a periodic reading is acceptable in this example; a sampling-rate change needs receipt evidence.
Work the delivery choice first. Use NON for replaceable readings under that loss policy. Use CON for the configuration change so that a missing ACK triggers bounded retries. Record the response and read back the sampling rate before claiming the change took effect. A clinical alarm would need its own deadline, failure handling, and application evidence; calling it CON alone would not establish safety.
Then draw the privacy boundary. Encrypting only the payload leaves the resource path, such as /patient/042/vitals, visible. Here that path identifies a patient. DTLS between the wearable and gateway protects the CoAP header, resource path, options, and payload on that association. Network observers can still see addresses, packet sizes, and timing. The gateway can read the decrypted message.
Choose credentials for that boundary. A pre-shared key (PSK) is a secret provisioned to the communicating peers. DTLS with PSK is a candidate if the hospital can securely provision, replace, and revoke device keys. Certificate authentication instead uses public-key credentials; neither credential choice extends protection past a terminating gateway. Transport encryption alone does not establish regulatory compliance.
Check the cost without inventing a lifespan. At the stated interval, one wearable sends 2,880 readings per day. Measure handshake frequency, record sizes, retries, radio energy, and sleep current on the intended device. Estimate battery lifetime only from measured energy use and usable battery capacity under the intended operating conditions. Keeping a usable association can reduce repeated establishment work, but only while both endpoints retain valid state.
Decision: NON readings and CON configuration changes can both use the same wearable-to-gateway DTLS boundary. If the gateway must not read the readings, change the security endpoints rather than changing CON to NON.
Implementation: The preserved Python fragment sketches the intended PSK association. It has not been validated against a particular aiocoap/TinyDTLS version; its credential assignment and example secrets are not a deployment recipe. Both example byte strings below contain 33 octets, so the 32-byte PSK comment is incorrect. That count does not establish which key lengths the implementation supports. Confirm the supported API and use securely provisioned credentials before implementing this design.
# Server setup (Python aiocoap with tinydtls)
import aiocoap
import aiocoap.credentials
server_credentials = aiocoap.credentials.CredentialsMap()
server_credentials[':dtls-psk'] = {
'device-042': b'32BytePresharedKeyForPatient042!!', # 32-byte PSK
'device-043': b'32BytePresharedKeyForPatient043!!',
}
context = await aiocoap.Context.create_server_context(
bind=('::', 5684), # CoAPS port
)
context.server_credentials = server_credentials

Maths · guided foundations
The Real Cost of DTLS on a Coin Cell
Check the quantities and assumptions.
Transfer the boundary rule before comparing costs. Object Security for Constrained RESTful Environments (OSCORE) protects selected CoAP content between application endpoints, including through forwarding proxies. It does not hide every outer routing field or remove key and replay-state management.
| Requirement | Candidate | What still needs evidence |
|---|---|---|
| Gateway may read wearable data | DTLS from wearable to gateway | Peer authentication, application response, and protection on any onward path |
| Gateway must forward without reading protected content | OSCORE from wearable to final reader | Correct endpoint context, protected fields, and persistent sender/replay state |
| Peers share provisioned secrets | PSK authentication | Secure provisioning, replacement, and revocation |
| Peers use certificates | Certificate authentication | Trust configuration and credential lifecycle |
| Tight packet or battery budget | Measure the chosen design | Actual encoded sizes, wake behavior, retries, and complete energy use |
Apply the decision:
- State the allowed loss and deadline. Choose CON for useful bounded retries, or NON when loss is tolerable; define what happens if delivery fails.
- Name every allowed reader. If the gateway is one, DTLS can terminate there. If it is not, protect selected content from the wearable to the final reader with OSCORE.
- Choose credentials that the operators can provision and maintain. A certificate does not turn transport protection into message protection through a proxy.
- Check wake behavior. Establish a fresh DTLS association if required state was lost; do not send using a stale pointer or reset cryptographic counters.
- Measure the complete encoded exchange. Neither a fixed OSCORE byte allowance nor a fixed DTLS handshake size proves that it fits the path.
DTLS and OSCORE can be combined for different boundaries. OSCORE that starts at the gateway protects gateway-to-cloud content, while OSCORE that starts at the wearable can protect selected content from that gateway. The starting endpoint changes the claim.
Transfer scenario: A soil-moisture sensor sends hourly readings through a gateway that must not read the protected content. Its sleep mode loses ordinary volatile memory. Predict both the delivery choice and the failure after wake before reading the code.
NON may suit replaceable readings if the application accepts loss. OSCORE between the sensor and final reader addresses the untrusted gateway boundary, but it still needs security context that remains safe across restart. If DTLS is also used on a transport leg, check its state separately.
The Error: Treating an old DTLS object as usable after the state it depends on has been lost. An association includes keys and record sequence state shared with the peer. Sleep does not always destroy that state; what matters is what this device retains and what the peer still accepts.
The following C++ fragments are preserved conceptual sketches with unspecified APIs. Their handshake sizes, energy, battery-life, and error-message comments are unverified, not field results. In particular, the first sketch may establish a new association if setup() runs on every boot; it does not by itself prove stale-state reuse.
Attempted implementation (broken):
// WRONG: Trying to reuse DTLS session after deep sleep
void setup() {
dtls_session = dtls_new_session();
dtls_connect(dtls_session, SERVER_IP, 5684); // Handshake: 360 bytes, 45 mJ
}
void loop() {
float moisture = read_sensor();
dtls_send(dtls_session, coap_message); // Sends with stale sequence number
esp_deep_sleep(3600 * 1000000); // Sleep 1 hour (RAM lost!)
}
// After waking, `dtls_session` pointer is invalid, sequence numbers reset
// Server rejects messages with "Bad MAC" or "Decrypt error"
Diagnose the first failure rather than guessing from an error string:
- Record whether wake resumes execution or restarts the device, and which security context is actually retained.
- Trace whether a fresh handshake completes or a supported retained association is accepted before sending application data.
- Compare authenticated receive evidence before and after sleep. If a CON gets no ACK, distinguish path loss from failed security processing before changing retry settings.
Expected result: The peer accepts protected data under valid state, and the application records a current reading. Rejection or silence after wake means this result has not been established; it does not identify a unique cause. No rejection percentage or battery lifetime follows from these sketches.
The Fix (Option 1): Full handshake on every wake: Use fresh establishment when the prior association cannot safely continue. The sketch must wait for a successful handshake before sending; its placeholder calls do not demonstrate asynchronous completion.
void loop() {
// Establish NEW DTLS session every wake
dtls_session_t *session = dtls_new_session();
dtls_connect(session, SERVER_IP, 5684); // Handshake cost: 45 mJ
float moisture = read_sensor();
dtls_send(session, coap_message); // Message cost: 1.7 mJ
dtls_close(session); // Clean shutdown
esp_deep_sleep(3600 * 1000000); // Sleep 1 hour
}
// Battery cost: (45 + 1.7) mJ × 24/day = 1,121 mJ/day
// Battery life: ~6 months (acceptable for rechargeable solar)
The Fix (Option 2): OSCORE (session-less security): Here “session-less” means that a DTLS handshake is not required for every report; it does not mean stateless. The preserved sequence_number++ sketch is incomplete: resetting the counter under the same context after wake is unsafe. Use the implementation’s supported persistent sender and replay-state handling before sending.
// OSCORE: Pre-provisioned keys, no handshake needed
void loop() {
float moisture = read_sensor();
// Encrypt with OSCORE (uses pre-shared master secret)
coap_message = oscore_encrypt(moisture, MASTER_SECRET, sequence_number++);
coap_send(coap_message, SERVER_IP, 5683); // Plain CoAP port, encrypted payload
esp_deep_sleep(3600 * 1000000); // Sleep 1 hour
}
// Battery cost: 1.8 mJ × 24/day = 43 mJ/day (no handshake!)
// Battery life: ~18 months (26× improvement vs full DTLS handshake every wake)
The Fix (Option 3): DTLS session resumption with stored state: Retaining a live association and negotiating session resumption are different operations. The sketch only proposes save/restore calls; it does not demonstrate either a supported serialization format or a resumed handshake. A fixed RTC buffer cannot establish that all required state survives or that the peer still accepts it.
// Store DTLS session state in RTC memory (survives deep sleep on ESP32)
RTC_DATA_ATTR uint8_t session_state[256]; // RTC_DATA_ATTR = retained during deep sleep
void loop() {
dtls_session_t *session;
if (is_first_boot()) {
// Full handshake on first boot only
session = dtls_new_session();
dtls_connect(session, SERVER_IP, 5684);
dtls_save_session(session, session_state); // Persist to RTC memory
} else {
// Resume from RTC memory on subsequent wakes
session = dtls_restore_session(session_state);
}
float moisture = read_sensor();
dtls_send(session, coap_message);
dtls_save_session(session, session_state); // Update sequence numbers
esp_deep_sleep(3600 * 1000000);
}
// Battery cost: 45 mJ (first boot) + 1.8 mJ × 24/day = ~43 mJ/day amortized
// Battery life: ~18 months (resumption avoids handshake overhead)
Decision matrix:
- Fresh DTLS establishment: Use when required association state is gone; measure the handshake cost at the actual wake frequency.
- OSCORE: Use the intended application endpoints and preserve safe context across restart; no per-report DTLS handshake is needed solely for object protection.
- Retained DTLS association or negotiated resumption: Use only with explicit library support and peer acceptance. A copied pointer is insufficient.
- Plain CoAP: Supplies no confidentiality or peer authentication by itself; it does not meet either example’s protected-content requirement.
Transfer answer: NON can fit the soil readings’ loss policy, and OSCORE from sensor to final reader can fit the gateway restriction. Before sending after wake, demonstrate safe persistent context. Choosing CON instead would add retry behavior but would not repair lost security state or hide data from the gateway.
Checkpoint: Security Trade-offs
You now know:
Predict before checking the answers:
- The wearable receives an empty ACK for a sampling-rate change. May the operator claim the new rate is active? No: receipt is established, but the response and resulting sampling state still need checking.
- The sleeping sensor loses volatile state and receives no ACK after wake. Should it simply add retries? No: first establish whether valid security state and peer acceptance survived; retries cannot rebuild missing state.
- The gateway must not read protected readings. Is gateway-to-cloud OSCORE sufficient? No: protection must start at the sensor to exclude that gateway from the readers.
Concept Relationships
How CoAP security and applications connect to broader IoT security concepts:
Delivery and application evidence: CON adds acknowledgement and bounded retransmission; NON does not. Neither proves that a reading is fresh or a command took effect.
Transport and message protection: DTLS protects the association between its endpoints. OSCORE protects selected CoAP content between its application endpoints. A terminating gateway’s access depends on where protection starts and ends.
Credentials and lifecycle: PSKs and certificates support peer authentication using different credential arrangements. Both need provisioning and replacement. Sleep and restart add a separate requirement: preserve safe state or establish fresh state before use.
Privacy and application design: A patient identifier in a resource path needs attention even when the payload is encrypted. Privacy-Preserving Analytics extends that question to what happens after protected telemetry arrives.
See Also
Core CoAP Learning:
Start with the CoAP overview to place the security chapter, then review fundamentals for the message exchange it protects.
Security Deep Dives:
- DTLS Protocol - Handshake, cipher suites, session management
- OSCORE for CoAP - End-to-end object security (RFC 8613)
- Pre-Shared Key Management - Device manufacturing and distribution
- Certificate-Based Authentication - X.509 for device identity
Implementation Resources:
Compare the Python and Java DTLS libraries before you choose one.
Application Examples:
- Smart Meter CoAP - DTLS-PSK for utilities
- Medical Device Gateway - CoAPs with assessed safeguards
- Industrial Sensor Network - Certificate-based mutual auth
Protocol Comparisons:
- MQTT TLS vs CoAP DTLS - TCP vs UDP security trade-offs
- HTTPS vs CoAPS - Web vs IoT security patterns
- Security Protocol Selection - Decision frameworks
Debugging & Testing:
Use the Wireshark decryption guide to inspect captures, then the OpenSSL client guide to test a DTLS endpoint.
Advanced Topics:
- DTLS Session Resumption - Avoiding handshake overhead
- Hardware Security Modules - Protecting private keys
- DTLS Connection ID - RFC 9146 for NAT rebinding
Specifications:
Read CoAP security rules first. Then review how DTLS protects UDP traffic.
Match each scenario to the choice it justifies. For the ordering exercise, reconstruct the five numbered stages under “Apply the decision” for the hospital wearable, followed by application verification. This tests the stated framework sequence; reader-boundary and delivery choices are independent design decisions and can be considered in another order. Explain the reader boundary and wake-state evidence before checking the feedback below.

Knowledge check · self-test
Knowledge check
Test your understanding.
The matching answers separate three decisions: message loss, allowed readers, and safe state after wake. A CON choice cannot substitute for either protection or state recovery. The ordering answer reproduces the stated framework: loss/deadline and message type → reader boundary → credentials → wake behavior → complete exchange measurement, followed by application verification. It does not impose technical dependencies between the independent design decisions. A transport receipt is never proof of a completed configuration change.
What’s Next
Use the DTLS and OSCORE contracts to refine the reader and restart boundaries, then practice tracing the resulting exchanges.
- CoAP DTLS and OSCORE Security Contracts: Security-mode selection, proxy termination, OSCORE inner/outer options, replay guards, and credential tradeoffs.
- CoAP Practice and Exercises: Visual reference gallery, worked examples, and hands-on exercises. Reinforce and test everything covered in this chapter with real calculations and problem sets.
- CoAP Observe Extension: Server-push notifications and subscription lifecycle. Understand how observe patterns interact with DTLS sessions and token management.
- CoAP Methods and Features: RESTful operations, block transfer, and multicast. Deepen knowledge of the CoAP features used in the real-world applications in this chapter.
- CoAP Fundamentals and Architecture: Message types, reliability, and header structure. Review the foundations of CON vs NON and token matching discussed in the implementation pitfalls.
- IoT Security Threats: Attack vectors and threat modelling for IoT. Learn what DTLS protects against: eavesdropping, replay, and man-in-the-middle attacks.
- Cryptography for IoT: AES, key management, and cipher suites. Understand the cryptographic primitives that underpin DTLS-PSK and DTLS-Certificate modes.

Simulation · interactive
OSCORE and EDHOC Security Workbench
Explore how the system behaves.
Summary
For the hospital wearable, tolerated reading loss supports NON; a configuration change benefits from CON’s bounded retries. DTLS can protect both to an authorized gateway, but an ACK does not prove that the sampling rate changed. If the gateway must not read selected content, start OSCORE at the sensor and end it at the final reader. For either security design, check retained state after sleep before sending again. Record the response, resulting application state, and first failure after wake rather than inferring success from a message type.
Key Takeaway
Choose retries from the loss policy, protection from the allowed readers, and recovery from the state that survives wake. Verify application results separately from transport receipt.
Continue Your Route
This is the last part of this chapter. Return to CoAP Security: Implementation and Operations or continue from the coap module index.


