Protection and Application Fit: 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.
Overview
A ward sensor exposes a medicine-temperature resource: a named value a client can read through CoAP. The nurse needs the reading; an unknown reader should receive no private data. Decide what protects the path, who may read it, and what evidence shows it arrived.
CoAP is the Constrained Application Protocol. A constrained device has limited power, memory, or link capacity. This page separates protection from delivery, then transfers that decision to building controls. Continue with CoAP Security: Implementation and Operations for implementation reference.
Start With the Private Reading
Worked example: protect a reading and its route.
The ward sensor returns a medicine temperature to the nurse’s client. The payload is the message content. Its URI, the address naming the resource, also contains a patient identifier. Encrypting only the payload hides the temperature but leaves that identifier exposed in the CoAP request.
Choose Datagram Transport Layer Security (DTLS) between the client and sensor. DTLS encrypts the CoAP message on that transport link, detects changes to protected data, and authenticates peers using configured credentials. A pre-shared key (PSK) is a secret provisioned to both peers; a certificate binds a public key to an identity under a trusted issuer. Authentication establishes the configured peer identity. Authorization is the separate rule permitting that identity to read or write a resource.
Now draw a gateway between sensor and nurse. If DTLS ends at the gateway, the gateway can read the CoAP message. A second protected hop does not hide it from that gateway. Object Security for Constrained RESTful Environments (OSCORE) protects selected CoAP message content between its security endpoints; use the linked security-contract lesson to examine that alternative. Neither choice hides all network addresses or traffic timing.
The nurse’s client sends a unicast GET to the sensor, which returns the temperature. Assume this requested reading is needed for the current check: losing the request or response leaves the nurse without that reading, so waiting for the next periodic sample is insufficient. Choose a Confirmable (CON) request for acknowledgement and bounded retransmission. If the sensor sends a separate response, use CON for that response too. Require a successful resource response matched to the request and a client record of the reading; an empty ACK alone proves neither receipt of the temperature nor completion of the check. If retries fail, record the missing reading and follow the ward’s defined recovery procedure.
For this design, grant the nurse read access and deny an unknown reader. Test a valid credential, a wrong credential, and an authenticated identity without read permission. Expect a private reading only for the allowed reader. A successful handshake establishes transport protection; the resource response and client record establish what the application received. Neither proves the physical sensor is accurate. Also test a retired credential after removing it from the accepted configuration and ending sessions that used it: expect no private reading through that credential. Modify protected bytes in transit: expect integrity rejection and no changed reading accepted. Replay a captured protected record: expect replay rejection and no new application delivery. Separately, induce loss of an ACK to test legitimate CoAP retransmission: duplicate handling should avoid processing the request twice while allowing the exchange to complete. A repeated CoAP request carried in a fresh protected record is not the same test as replaying captured protected bytes.
Record the peers, credential owner, protected hop, allowed method, refusal result, and reading received. Recheck after credential replacement, a gateway change, or device sleep. Choose local failure behavior explicitly rather than treating loss of a remote service as permission to expose data.
- Trace which ward-sensor fields DTLS protects and what a gateway can see.
- Inspect the PSK example and separate illustrative radio arithmetic from measured cost.
- Transfer protection and delivery decisions to meters, buildings, and industrial resources.
- Test access, response correlation, retry behavior, and public exposure in the lab and pitfalls.
The linked security-contract and implementation pages cover deeper protection and operations questions.
Learning Objectives
- Mark DTLS protection endpoints and metadata that remains visible.
- Distinguish peer authentication from permission to read or change a resource.
- Choose acknowledgement and retry behavior from the consequence of loss.
- Diagnose a failed exchange using credential, response, Token, and retry evidence.
- Identify which measurements a battery or packet-size estimate still needs.
- CON (Confirmable): asks for an acknowledgement (ACK) and uses bounded retries if none arrives. An ACK alone does not establish application success.
- NON (Non-confirmable): has no message-layer ACK; use it when the application can tolerate or recover from a lost message.
- Observe: lets a client register for later notifications about a resource.
- Block-wise transfer: divides a representation across CoAP exchanges.
- Token: matches responses or Observe notifications to a request within the peer context.
- Integrity: detects changes to protected data. Confidentiality hides that data from parties without the key.
For Beginners: CoAP Security
For the ward sensor, ask two questions separately: can this peer establish the protected exchange, and may that peer read this resource? Then inspect the client response. A protected path does not prove the application received a current reading.
“If I lock the temperature value, is the patient identifier hidden too?” asks Terry.
“Only if the protection includes the field carrying that identifier,” Bex replies. “DTLS covers the CoAP URI on its protected hop. A gateway sees it if the protection ends there.”
“And the battery?”
“Measure connection setup and repeated messages separately. Reuse security state when the implementation and device lifecycle permit it; do not assume it survives sleep.”
Continue: CoAP DTLS and OSCORE Security Contracts
The main chapter below stays focused on CoAP security and application practice. For the deeper contract behind DTLS security modes, proxy termination, OSCORE inner and outer options, and replay protection, continue to CoAP DTLS and OSCORE Security Contracts.
Security with DTLS
Return to the ward request: the patient identifier is in a CoAP URI option. DTLS covers that field as well as the payload between its configured peers. It provides confidentiality, integrity, and credential-based authentication; the resource still needs an authorization rule.
For the UDP transport used here, coap:// defaults to port 5683 and DTLS-protected coaps:// defaults to 5684. These defaults do not establish that a service is configured correctly.
the figure in the parent chapter compares DTLS over UDP with TLS over TCP, a reliable ordered stream transport. Follow the DTLS column to see why message protection does not replace CoAP’s delivery checks.
In the figure in the parent chapter, read the DTLS side through UDP loss, reordering, and the cookie check, then contrast it with TLS running over TCP’s ordered byte stream. Both can provide confidentiality, integrity, and peer authentication, but DTLS must handle datagram behavior explicitly and does not make UDP reliable. That boundary matters when the knowledge check asks what payload-only encryption leaves exposed.
DTLS Setup: Pre-Shared Key Example
Use the preserved PSK sketch to locate the secure URI, identity, and credential map. It is incomplete and unexecuted: TemperatureResource and its resource import are missing, and server credential attachment needs verification against the installed aiocoap backend. The example keys are placeholders; use properly provisioned test credentials. The fixed latency comments are unverified examples.
The sketch is not a working server or a security test receipt. The lab asks for observed success and refusal on an available implementation.
# pip install aiocoap[dtls]
# Requires: tinydtls library (pip install DTLSSocket)
import asyncio
import aiocoap
import aiocoap.credentials
# --- Server side: CoAPs on port 5684 ---
async def create_secure_server():
"""Start a CoAP server with DTLS-PSK on port 5684."""
root = aiocoap.resource.Site()
root.add_resource(['temperature'],
TemperatureResource())
# Define server credentials: map client identities to PSKs
server_credentials = aiocoap.credentials.CredentialsMap()
server_credentials.load_from_dict({
# Identity "sensor-042" uses this 16-byte pre-shared key
':dtls-psk': {
'sensor-042': b'MySecret16ByteK!',
'sensor-043': b'AnotherKey16Byt!',
}
})
context = await aiocoap.Context.create_server_context(
root,
bind=('::', 5684), # Secure CoAP port
)
context.client_credentials = server_credentials
return context
# --- Client side: connect with PSK identity ---
async def secure_get_temperature():
"""GET coaps://server/temperature with DTLS-PSK."""
context = await aiocoap.Context.create_client_context()
# Set client identity and PSK
context.client_credentials.load_from_dict({
'coaps://server/*': {
'dtls': {
'psk': b'MySecret16ByteK!',
'client-identity': b'sensor-042'
}
}
})
request = aiocoap.Message(
code=aiocoap.GET,
uri='coaps://server/temperature' # Note: coaps:// not coap://
)
response = await context.request(request).response
print(f"Secure response: {response.payload.decode()}")
# What to observe:
# - URI scheme is coaps:// (port 5684) vs coap:// (port 5683)
# - DTLS handshake adds ~200ms on first request (key exchange)
# - Subsequent requests reuse session (~5ms overhead)
# - If PSK doesn't match: handshake fails, no data exchanged

Knowledge check · self-test
Knowledge check
Test your understanding.
Testing DTLS with CLI tools:
Use this preserved command against a configured local test server. Expect protected application records after a successful handshake; packet names vary by DTLS version. A capture alone cannot show that the reader is authorized or that the nurse application stored the value.
# Generate a PSK identity file for coap-client
# coap-client supports DTLS-PSK natively
# Secure GET request
coap-client -m get coaps://localhost/temperature \
-k "MySecret16ByteK!" \
-u "sensor-042"
# Verify encryption with Wireshark:
# Filter: dtls && udp.port == 5684
# You should see:
# ClientHello -> ServerHello -> ChangeCipherSpec
# Then encrypted ApplicationData (CoAP payload not readable)
DTLS overhead comparison:
The following preserved comparison is an unverified sketch. Its fixed RTT, millisecond, header, and tag counts depend on version and negotiated protection. The handshake charge expression omits airtime, so it cannot establish charge. CoAP also carries Tokens and options beyond its base header.
Plain CoAP (UDP port 5683):
Request: 4-byte header + payload
Response: 4-byte header + payload
Latency: 1 RTT (~20ms LAN)
Secure CoAP (DTLS port 5684):
First request: DTLS handshake (4-6 messages) + encrypted payload
Latency: 3 RTTs for handshake + 1 RTT for data = ~80ms first request
Overhead: 13 bytes DTLS record header per message
Subsequent requests (session reuse):
Latency: 1 RTT + ~5ms DTLS overhead = ~25ms
Overhead: 13 bytes header + 8-16 bytes MAC (integrity)
Energy cost of DTLS handshake (one-time per session):
6 messages x 100 bytes avg x 10 mA TX = 0.6 mAs
Amortized over 1000 messages: 0.0006 mAs each (negligible)
Keep DTLS sessions alive to avoid repeated handshakes.
Use the reporting schedule to separate message count from radio cost. One reading per minute gives readings per day.
For an arithmetic exercise, assume a 53-byte transmitted unit and compare it with 20 bytes. At 250 kbps, their transmit times are 1.696 ms and 0.640 ms. At 20 mA, charge in µAh is current in mA multiplied by time in ms and divided by 3,600: 0.00942 µAh versus 0.00356 µAh per send.
The charge ratio is 53/20 = 2.65 under those assumptions. It is not a measured DTLS penalty. The original 53-byte construction and handshake charge are unverified, so do not use them to size a deployment. Measure actual protected records, handshakes, receives, retries, idle current, and processing; account for usable cell capacity separately.
Checkpoint: Secure Transport
For the ward reading, identify the two DTLS peers, then ask:
- Is the URI protected to the intended reader, or can a terminating gateway see it?
- Does the authenticated identity have read permission?
- Does the resource response show the client received the reading?
Keep measured radio costs separate from illustrative byte arithmetic.
Interactive Security Calculators
Use these preserved models to ask which inputs a ward-sensor estimate needs. Their outputs are illustrative and include the limitations stated before each model; they do not select an acceptable security policy.
DTLS Energy Cost Calculator
This model assumes one handshake per day, fixed 29-byte per-message overhead, and transmit current only. Its “energy” unit mAh measures charge; receive, processing, sleep, and retry costs are omitted.
Battery Life Estimator: CON vs NON
Compare the assumed traffic costs only. The displayed charge and lifetime are invalid: dividing joules by volts yields coulombs, but the model labels that result mAh without converting units. Its fixed costs also omit retries and other device loads.
Protocol Overhead Comparison
The bars compare selected constants, not complete packets. CoAP Tokens and options, MQTT topic fields, and transport/security costs are omitted. The displayed “winner” cannot establish which protocol costs less for this exchange.
Block Transfer Size Optimizer
The displayed block size omits IP/UDP headers, the Token, and other options; it is not a verified fit within the path maximum transmission unit (MTU). The network-type selector changes the label, not the arithmetic. Measure the full packet before choosing a block size.
Security vs Battery Trade-off Analyzer
These fixed costs are unverified and disagree in unit scale with the earlier handshake example. OSCORE setup cost is omitted. Treat recommendations as model output only: the ward reading still requires its protection boundary regardless of a cost percentage.
Key Insights from Calculators:
For the ward sensor, keep three records: measured packet sizes, measured device charge, and the required protection boundary. A cheaper model output cannot authorize exposing patient identifiers. A larger block or a NON message is acceptable only after checking packet fit and the consequence of loss.
Real-World Applications
Transfer the ward decision by changing the resource and the consequence of loss. A domain name alone cannot choose credentials, permissions, or acknowledgement behavior.
Smart Energy
Smart Meters:
In this illustrative API, reading consumption, updating a tariff, and requesting load control need separate permissions. The resource names below are not a recommendation to expose billing or control traffic without protection.
- Read consumption (GET)
- Update tariffs (PUT)
- Control load (POST)
coap://meter.home/consumption
coap://meter.home/tariff
coap://meter.home/switch
Building Automation
Transfer example. A building controller reads temperature and writes a thermostat setpoint. Suppose a lost periodic reading is acceptable because a later reading replaces it. NON can suit that stream. A lost setpoint change leaves the wrong state, so choose an authenticated, authorized CON write and inspect its resource response; an empty ACK alone is insufficient. Read the setpoint back when the application needs confirmation of stored state.
Use the ward rule again: name the protection endpoints, give the display read permission, and reserve write permission for the controller. Lighting status and brightness control need the same distinction. If group control uses multicast, review its security and response behavior separately from this unicast exchange.
Decide before reading on: would changing the write to NON repair a rejected credential? Answer: no. Delivery type does not change authentication or grant write permission.
Industrial IoT
Industrial CoAP designs should separate observation from control. A sensor network may poll values frequently with replaceable NON traffic, but a sampling-rate change needs an authenticated, authorized, confirmable write and a traceable 2.04 Changed outcome. Firmware update metadata and blocks add integrity, rollback, and power requirements beyond delivery alone. Asset tracking follows the same consequence test: a periodic location or status update may tolerate loss, whereas an alert notification can require confirmable delivery, deduplication, and escalation evidence. The protocol choice stays connected to the operational risk of each resource.
Checkpoint: Application Fit
Apply the same test to a new resource:
- Identify what a lost read or write would change.
- Choose CON when acknowledgement and bounded retries help, then define recovery if retries fail.
- Name the authorized reader or writer and the protection endpoints.
- Request application evidence, such as a stored reading or setpoint response, separately from an ACK.
A firmware transfer also needs integrity and update-policy checks; blocks and CON alone cannot establish a safe update.
Lab Exercise
Goal: demonstrate allowed access, refused access, and correctly correlated notifications on a local test system. Use simulated temperature and humidity values, or an ESP32 with a DHT22 sensor. Keep the exercise on a controlled network with test credentials.
- Prepare the resources. Use an available CoAP stack on a Raspberry Pi or PC to expose
/temperatureand/humidity. Record units and allowed methods. Complete and verify the PSK sketch against your backend before using it. Expected: GET returns the named resource and unit. If it does not: inspect reachability, resource registration, and response code before testing security. - Test the protected read. Configure matching DTLS test credentials. Send GET requests every 30 seconds and record peer, resource, Token, response code, and value. Repeat with a wrong credential, then with an authenticated identity denied read permission. Expected: only the permitted reader obtains the private value. If it does not: distinguish handshake failure from resource authorization failure.
- Test credential retirement, integrity, and replay. Retire a test credential, remove it from the accepted configuration, end its existing sessions, and attempt a fresh protected read with it. Then, using a valid test session and a controlled packet tool, alter protected bytes in transit and replay a captured protected record. Expected: the retired credential yields no private reading; altered bytes fail integrity checks; the replay produces no new application delivery and is rejected by replay protection. Record security diagnostics and application delivery counts, since silence alone does not identify the cause. Separately drop an ACK to trigger a legitimate CoAP retransmission carried in a fresh protected record. Expected: duplicate handling prevents a second application operation while the exchange can complete. If these results differ: inspect credential/session retirement, integrity and replay enforcement, and CoAP duplicate handling separately.
- Separate ACK from outcome. Add a test setpoint resource with an authorized PUT. Record its response and read back the stored value. Try a write from a read-only identity. Expected: the allowed write changes the setpoint; the read-only attempt leaves it unchanged. If it does not: inspect method permissions and handler behavior. An ACK without the application result does not settle this test.
- Test Observe correlation. Register separate observations of temperature and humidity. Change one simulated value and record the notification’s peer, Token, resource mapping, and payload. Expected: the value reaches the correct stream without a new GET for each update. If it does not: check registration and peer/Token matching before blaming the sensor. Test cancellation and reconnect separately.
- Test scoped discovery. Send a multicast discovery request on the controlled network and record advertised resources. Expected: responding servers advertise their available resources; discovery is multicast, not broadcast. If no reply arrives: inspect multicast routing and server support. A discovery reply does not prove read permission; repeat the protected read against the discovered peer.
Challenge: add a CoAP-to-MQTT bridge and draw where protection ends. Submit the allowed/refused access traces, setpoint response/read-back, and notification mapping. Explain whether the bridge can read the private resource.
When to Use CoAP
Choose CoAP when:
The device needs a resource request/response API and its memory, link, and power budgets fit the measured implementation. Direct access, scoped multicast discovery, and constrained IPv6 networks can favor this design; none guarantees low total energy.
Choose HTTP when:
Browser access and existing web infrastructure matter more than fitting this CoAP resource exchange. Compare implementation cost and authentication integration; complex authentication alone does not exclude CoAP.
Choose MQTT when:
Many producers and consumers need topic-based routing through a broker. Evaluate its delivery levels and operations against application evidence requirements. With any protocol, repeat the ward test for protection endpoints, permission, and observed receipt.
Common Implementation Pitfalls
Once the protocol choice is made, reliability depends on small implementation details that UDP will not fix for you.
The Mistake: Implementing CoAP Observe without properly tracking tokens, causing clients to misattribute notifications to the wrong resources when observing multiple endpoints simultaneously.
Why It Happens: Developers familiar with HTTP assume response correlation is automatic. In CoAP, the token (0-8 bytes) links requests to responses. When observing /temperature and /humidity concurrently, both notification streams arrive on the same UDP socket and must be matched by token.
The Fix: Maintain a token-to-resource mapping for all active observations:
# BAD: Ignoring tokens
def on_notification(response):
print(f"Got value: {response.payload}") # Which resource?
# GOOD: Token-based dispatch
observations = {} # token -> resource_uri mapping
def observe_resource(uri):
token = generate_unique_token()
observations[token] = uri
send_observe_request(uri, token)
def on_notification(response):
uri = observations.get(response.token)
if uri:
print(f"Resource {uri} = {response.payload}")
else:
print(f"Unknown token, sending RST")
send_reset(response.mid)
Treat the preserved code as dispatch pseudocode. Track the peer and security context as well as the Token, avoid collisions among active exchanges to that peer, and remove cancelled observations. For an unknown notification, check its message type before responding: the sketch’s unconditional RST is not a general rule for every response or ACK.
The Mistake: Using aggressive fixed-interval retransmissions for CON messages instead of exponential backoff, causing network congestion when packet loss occurs.
Why It Happens: Developers implement simple “retry every 2 seconds” logic without realizing that CoAP specifies exponential backoff (RFC 7252). On a lossy wireless network, aggressive fixed-interval retries can multiply traffic and worsen congestion; use CoAP’s exponential backoff and measure the retry load.
The Fix: Implement RFC 7252 compliant retransmission with exponential backoff:
# BAD: Fixed interval retry (network flooding)
RETRY_INTERVAL = 2.0 # seconds
for attempt in range(MAX_RETRIES):
send_message(msg)
if wait_for_ack(RETRY_INTERVAL):
break
# GOOD: Exponential backoff per RFC 7252
ACK_TIMEOUT = 2.0 # Initial timeout (2 seconds)
ACK_RANDOM_FACTOR = 1.5 # Randomization factor
MAX_RETRANSMIT = 4 # Maximum retries
def coap_transmit(msg):
timeout = ACK_TIMEOUT * (1 + random.random() * (ACK_RANDOM_FACTOR - 1))
for attempt in range(MAX_RETRANSMIT + 1):
send_message(msg)
if wait_for_ack(timeout):
return True
timeout *= 2 # Double the randomized timeout after each attempt
return False # Default worst-case wait can reach MAX_TRANSMIT_WAIT = 93 s
With default backoff: timeouts of 2–3 s, then 4–6, 8–12 and 16–24 s, so retransmissions occur at about 2–3, 6–9, 14–21 and 30–45 s after the first send. The maximum span from first to last send is 45 s; the sender may wait up to 93 s from the first send before giving up on ACK or RST (RFC 7252 §4.8.2).
The Mistake: Leaving a NoSec coap:// endpoint reachable from the public internet, on the assumption that CoAP’s security risk starts and ends with eavesdropping on the device’s own traffic.
Why It Happens: CoAP inherits UDP’s connectionless model, so there is no handshake like TCP’s SYN/ACK for a server to confirm that a request’s source address is genuine. An attacker can put a victim’s IP address in the source field of a small spoofed CoAP request and send it to any publicly reachable CoAP server. The server replies as designed, but the reply goes to the spoofed address, not to the attacker. Because a CoAP response can be much larger than a short spoofed request, an exposed NoSec server can amplify reflected traffic; the factor depends on the resource and request/response sizes. The device is not the target; it becomes an unwitting reflector in a DDoS attack against someone else.
The Fix: Do not place a NoSec CoAP resource directly on the public internet.
Restrict exposed resources with a gateway or firewall and require authenticated, authorized access to private data. A DTLS cookie exchange can check return reachability before costly handshake work; it does not establish client identity or resource permission. See CoAP DTLS and OSCORE Security Contracts. Limit response size and rate as additional controls, and test aggregate limits because spoofed addresses can evade a simple per-source policy.



