Chapters

20 CoAP Security: CON and NON Trade-Offs

coap
security

20.1 Start With the Decision

A confirmable CoAP message retries after loss; a non-confirmable one does not. The choice must match delay, traffic, and loss needs.

20.2 Route Overview

This is part 2 of 2. Review CoAP Security: Implementation and Operations for the preceding evidence.

20.3 Learning Objectives

  • Choose CON or NON CoAP messages from delivery and retry needs.
  • Configure DTLS for a sleeping hospital wearable without unsafe session reuse.

20.4 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
Try It: CON vs NON Message Type Advisor

Describe your IoT scenario and this tool recommends whether to use Confirmable (CON) or Non-confirmable (NON) messages, with energy and reliability analysis.

20.5 Under the Hood: CoAP Security Trade-offs

The final deep-dive shifts from syntax and debugging to lifecycle cost: what happens when devices sleep, reboot, move through gateways, or need stronger end-to-end protection than a single DTLS hop can provide.

Scenario: A hospital deploys 200 wireless vital signs monitors (heart rate, SpO2, temperature) on patients. Each device uses CoAP to report readings every 30 seconds to a centralized gateway. HIPAA compliance requires encryption of all patient data in transit.

Comparing security options:

Option A: Application-layer encryption (AES-128 on payload):

CoAP message structure:
  Plain CoAP header: 4 bytes
  Token: 2 bytes
  Uri-Path option: 12 bytes ("/patient/042/vitals")
  Content-Format option: 2 bytes
  Payload marker: 1 byte
  Encrypted JSON: 64 bytes (AES-128-CBC encrypted {"hr":72,"spo2":98,"temp":37.1})
  Total: 85 bytes

Security analysis:
  ✓ Payload encrypted
  ✗ URI path visible: "/patient/042/vitals" exposes patient ID
  ✗ Content-Format visible: Reveals JSON structure
  ✗ Message timing visible: Attacker knows when patient 042 has events
  ✗ HIPAA violation: Metadata is PHI (Protected Health Information)

Option B: DTLS with PSK (Transport-layer encryption):

DTLS handshake (one-time per session):
  ClientHello: 120 bytes
  ServerHello: 140 bytes
  ChangeCipherSpec: 40 bytes
  Finished: 60 bytes
  Total handshake: 360 bytes (amortized over 2,880 messages/day = 0.125 bytes/message)

Encrypted CoAP message:
  DTLS record header: 13 bytes
  Encrypted CoAP message: 85 bytes (entire message encrypted)
  DTLS MAC: 16 bytes (integrity check)
  Total: 114 bytes per message

Security analysis:
  ✓ Entire message encrypted (header, URI, options, payload)
  ✓ No metadata leakage
  ✓ HIPAA compliant
  ✓ Replay protection (DTLS sequence numbers)
  ✓ Mutual authentication (optional with certificates)

Energy cost comparison (CR2032 coin cell, 220 mAh):

Application-layer AES:

Per message energy:
  CoAP NON message: 1.2 mJ (radio time)
  AES-128 encryption: 0.3 mJ (software, no hw acceleration)
  Total: 1.5 mJ per message

Daily energy: 2,880 messages × 1.5 mJ = 4.32 J/day
Battery life: (220 mAh × 3V × 3600 s/h) ÷ 4.32 J/day = ~550 days

DTLS with PSK:

Per message energy:
  DTLS handshake (amortized): 45 mJ / 2,880 = 0.016 mJ
  CoAP NON message (encrypted): 1.3 mJ (radio time, +8% for larger message)
  DTLS encryption/MAC: 0.4 mJ
  Total: 1.72 mJ per message

Daily energy: 2,880 × 1.72 mJ = 4.95 J/day
Battery life: 2,376 J ÷ 4.95 J/day = ~480 days

Decision: DTLS with PSK

Reasoning:

  • HIPAA compliant: Encrypts all PHI including metadata
  • Battery cost acceptable: 15% more energy for full protection
  • Simplified key management: PSK easier than distributing certificates to 200 devices
  • Industry standard: DTLS is the recommended CoAP security mechanism (RFC 7252)

Implementation:

# 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

  1. Broker Bex draws device, gateway, and cloud, marking which boundary may see the message contents.

    First, draw who may read each message.

  2. Bex chooses a protected link for a trusted gateway or a sealed message through an untrusted gateway.

    Choose link protection or message protection for that boundary.

  3. Bex tests key setup, a gateway acting as designed, and the added message size on the actual route.

    Test keys, gateways, and message cost on the real path.

CP-0063 decision strip: Hybrid approach: Many deployments use DTLS from device to gateway (transport security), then OSCORE from gateway to cloud (end-to-end security).

Choose the right security configuration based on deployment requirements:

FactorNo Security (CoAP)DTLS-PSK (Pre-Shared Key)DTLS-Cert (Certificates)OSCORE (Object Security)
Encryption strengthNoneAES-128AES-128/256AES-128
AuthenticationNoneSymmetric keyAsymmetric (PKI)Symmetric key
Handshake overhead0 bytes360 bytes (one-time)2-4 kB (one-time)0 bytes (pre-provisioned)
Per-message overhead0 bytes+29 bytes (header+MAC)+29 bytes+8-16 bytes
Key distributionN/AManual or secure channelPKI infrastructurePre-provisioned
End-to-end securityNoNo (broker can decrypt)No (broker can decrypt)Yes (survives proxies)
NAT traversalEasy (UDP)Easy (UDP)Easy (UDP)Easy (UDP)
Best forLab testing onlyIoT devices, constrained networksEnterprise, device identity criticalProxy/gateway networks

Decision tree:

  1. Is data sensitive or regulated (PII, HIPAA, financial)? → No: Consider plain CoAP (but use encryption anyway as best practice) → Yes: Continue

  2. Do you have PKI infrastructure (CA, certificate management)? → Yes: DTLS with Certificates (strong identity verification) → No: Continue

  3. Can you securely pre-provision keys to devices during manufacturing? → Yes: DTLS-PSK or OSCORE (both use symmetric keys) → No: You need to set up key distribution mechanism first

  4. Do messages pass through untrusted proxies or gateways? → Yes: OSCORE (end-to-end, proxy can’t decrypt) → No: DTLS-PSK (simpler, transport-layer security)

  5. Is per-message overhead critical (<10 bytes headroom)? → Yes: OSCORE (8-16 bytes vs DTLS’s 29 bytes) → No: DTLS-PSK (easier to debug, standard TLS tools work)

Hybrid approach: Many deployments use DTLS from device to gateway (transport security), then OSCORE from gateway to cloud (end-to-end security). This balances ease of debugging (DTLS is standard TLS) with proxy security (OSCORE protects against compromised gateways).

Common Mistake: Reusing DTLS Session Across Deep Sleep Cycles

The Error: Configuring battery-powered IoT devices to establish a DTLS session once, then sleep/wake multiple times expecting the session to remain valid.

Why It Happens: Developers assume DTLS sessions persist like HTTP cookies. The device wakes, sends an encrypted CoAP message, and expects the server to accept it. However, DTLS sessions have state (sequence numbers, cipher state) that’s lost when the device power-cycles RAM.

Real-World Impact: A smart agriculture deployment of 500 soil moisture sensors (ESP32, deep sleep mode):

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"

Symptoms:

  • 95% of messages after first wake rejected by server
  • Logs show: DTLS decrypt error: sequence number mismatch
  • Devices retry handshake, draining battery
  • Battery life: 3 months (expected: 18 months)

Root cause: DTLS maintains per-session state in RAM:

  • Cipher context: Encryption keys derived from handshake
  • Sequence numbers: Anti-replay protection (both sides increment per message)
  • Epoch: Changes on renegotiation

When ESP32 deep sleeps, RAM is powered off. On wake, all session state is lost. The device can’t resume the DTLS session.

The Fix (Option 1): Full handshake on every wake:

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):

// 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:

// 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:

  • Handshake every wake: Handshake on every message (about 24/day), ~45 mJ per message, about 6 months of battery life, not recommended.
  • OSCORE: No handshake after provisioning, ~1.8 mJ per message, about 18 months of battery life, best for deep-sleep devices.
  • Session resumption (RTC memory): Handshake once per reboot, ~1.8 mJ per message, about 18 months of battery life, best for ESP32 with RTC memory.
  • Plain CoAP (no security): No handshake, ~1.2 mJ per message, about 24 months of battery life, suitable only for lab testing.

Prevention: For deep-sleep devices, default to OSCORE unless you have a specific reason to use DTLS. If DTLS is required, implement session resumption with RTC-persisted state.

Broker BexCheckpoint: Security Trade-offs

You now know:

  • In the hospital wearable example, DTLS-PSK protects metadata that payload-only AES leaves visible, trading about 480 days of battery life for HIPAA-suitable protection instead of about 550 days.
  • For 500 ESP32 soil sensors in deep sleep, replay and sequence state can be lost; the chapter shows 95% rejection after first wake when state is reused incorrectly.
  • OSCORE or RTC-backed DTLS resumption can avoid a 45 mJ handshake on every wake and recover about 18 months of battery life instead of about 6 months.

20.6 Concept Relationships

How CoAP security and applications connect to broader IoT security concepts:

DTLS Security Builds On:

Read these points as one connected sequence: start with TLS Fundamentals - Transport Layer Security adapted for UDP datagrams; then Symmetric Cryptography - AES-128/256 cipher suites; and finish with Key Management - Pre-shared keys vs certificate infrastructure.

  • TLS Fundamentals - Transport Layer Security adapted for UDP datagrams
  • Symmetric Cryptography - AES-128/256 cipher suites
  • Key Management - Pre-shared keys vs certificate infrastructure

DTLS vs Application Encryption:

Read these points as one connected sequence: start with End-to-End Security - Transport vs payload-only protection; then Metadata Privacy - HIPAA compliance requires URI encryption; and finish with Security Layering - Multiple protection levels.

  • End-to-End Security - Transport vs payload-only protection
  • Metadata Privacy - HIPAA compliance requires URI encryption
  • Security Layering - Multiple protection levels

Real-World Applications:

Read these points as one connected sequence: start with Smart Energy AMI - Meter reading with DTLS authentication; then Building Automation - HVAC/lighting RESTful control; then Industrial IoT - Asset tracking and sensor networks; and finish with Healthcare Wearables - HIPAA-compliant vital signs.

  • Smart Energy AMI - Meter reading with DTLS authentication
  • Building Automation - HVAC/lighting RESTful control
  • Industrial IoT - Asset tracking and sensor networks
  • Healthcare Wearables - HIPAA-compliant vital signs

Implementation Pitfalls Connect To:

Read these points as one connected sequence: start with Token Management - Matching Observe notifications; then Retransmission Logic - Exponential backoff vs fixed intervals; and finish with MTU Awareness - Block transfer for large payloads.

  • Token Management - Matching Observe notifications
  • Retransmission Logic - Exponential backoff vs fixed intervals
  • MTU Awareness - Block transfer for large payloads

CoAP Security Enables:

Read these points as one connected sequence: start with Zero Trust IoT - Mutual authentication with certificates; then Privacy-Preserving Analytics - Encrypted telemetry aggregation; and finish with Secure OTA Updates - DTLS-protected block transfers.

  • Zero Trust IoT - Mutual authentication with certificates
  • Privacy-Preserving Analytics - Encrypted telemetry aggregation
  • Secure OTA Updates - DTLS-protected block transfers

20.7 See Also

Core CoAP Learning:

Read these points as one connected sequence: start with CoAP Overview - 5-chapter learning path index; then CoAP Fundamentals - Message types and reliability; then CoAP Methods - RESTful operations and multicast; and finish with CoAP Observe - Server-push notifications.

Security Deep Dives:

Read these points as one connected sequence: start with DTLS Protocol - Handshake, cipher suites, session management; then OSCORE for CoAP - End-to-end object security (RFC 8613); then Pre-Shared Key Management - Device manufacturing and distribution; and finish with Certificate-Based Authentication - X.509 for device identity.

  • 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:

Read these points as one connected sequence: start with aiocoap TinyDTLS Transport - Python with tinydtls; then Californium DTLS - Java Scandium library; and finish with libcoap DTLS API - C implementation.

Application Examples:

Read these points as one connected sequence: start with Smart Meter CoAP - DTLS-PSK for utilities; then Medical Device Gateway - HIPAA-compliant CoAPs; and finish with Industrial Sensor Network - Certificate-based mutual auth.

  • Smart Meter CoAP - DTLS-PSK for utilities
  • Medical Device Gateway - HIPAA-compliant CoAPs
  • Industrial Sensor Network - Certificate-based mutual auth

Protocol Comparisons:

Read these points as one connected sequence: start with MQTT TLS vs CoAP DTLS - TCP vs UDP security trade-offs; then HTTPS vs CoAPS - Web vs IoT security patterns; and finish with Security Protocol Selection - Decision frameworks.

  • 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:

Read these points as one connected sequence: start with Wireshark DTLS Decryption - Inspecting encrypted traffic; then OpenSSL s_client for DTLS - Testing handshakes; and finish with coap-client with PSK - Command-line DTLS.

Advanced Topics:

Read these points as one connected sequence: start with DTLS Session Resumption - Avoiding handshake overhead; then Hardware Security Modules - Protecting private keys; and finish with DTLS Connection ID - RFC 9146 for NAT rebinding.

  • DTLS Session Resumption - Avoiding handshake overhead
  • Hardware Security Modules - Protecting private keys
  • DTLS Connection ID - RFC 9146 for NAT rebinding

Specifications:

Read these points as one connected sequence: start with RFC 7252 Section 9 - CoAP security considerations; then RFC 6347 - DTLS 1.2 - Datagram TLS protocol; then RFC 8613 - OSCORE - Object security for CoAP; and finish with RFC 9147 - DTLS 1.3 - Latest DTLS version.

Knowledge Check: Matching and Ordering

Test your understanding of CoAP security concepts with the quizzes below.

Label the Diagram

20.8 What’s Next

Now that you understand CoAP security and implementation patterns, continue with these related chapters:

Read these points as one connected sequence: start with CoAP DTLS and OSCORE Security Contracts: Security-mode selection, proxy termination, OSCORE inner/outer options, replay guards, and credential tradeoffs; then 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; then CoAP Observe Extension: Server-push notifications and subscription lifecycle. Understand how observe patterns interact with DTLS sessions and token management; then 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; then 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; then IoT Security Threats: Attack vectors and threat modelling for IoT. Learn what DTLS protects against: eavesdropping, replay, and man-in-the-middle attacks; and finish with Cryptography for IoT: AES, key management, and cipher suites. Understand the cryptographic primitives that underpin DTLS-PSK and DTLS-Certificate modes.

  • 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.

20.9 Summary

CoAP security decisions depend on the device, transport, and deployment model. DTLS, OSCORE, credentials, gateways, and provisioning all need to be matched to battery budget, multicast needs, and operational update paths.

20.10 Key Takeaway

Do not treat CoAP security as a final wrapper. Choose the security model while designing resources and deployment flow, because credential provisioning, group communication, and gateway translation affect the whole architecture.

20.11 Continue Your Route

This final part closes the route from Try It: CON vs NON Message Type Advisor through Key Takeaway. Return to CoAP Security: Implementation and Operations or continue from the coap module index.