TLS for embedded systems
Handshakes, certificates, PSK, DTLS and fitting TLS in RAM.
Why devices need TLS
Without encryption, anyone on the path (a compromised router, a public Wi-Fi, a cellular operator) can read a device's data, change commands, or pretend to be the server and push malicious firmware. TLS (Transport Layer Security) provides three things on top of TCP:
- Confidentiality: data is encrypted.
- Integrity: tampering is detected.
- Authentication: the device knows it is talking to the real server (and, with client certificates, the server knows which device it is).
Every major IoT cloud requires TLS, usually with mutual authentication (both sides present certificates).
The handshake (TLS 1.2)
client server
ClientHello (versions, cipher suites, random) ->
<- ServerHello (chosen suite, random)
<- Certificate (server's certificate chain)
<- ServerKeyExchange (ephemeral ECDHE public key, signed)
<- CertificateRequest (for mutual auth)
<- ServerHelloDone
Certificate (client's), ClientKeyExchange (ECDHE key),
CertificateVerify (proves it holds the private key),
ChangeCipherSpec, Finished ->
<- ChangeCipherSpec, Finished
application data <-> application data
Two round trips before any data. The client must:
- validate the server's certificate chain against a trusted root CA it stores, and check the hostname matches and the certificate is within its validity dates (so the device needs the correct time, from NTP or a cellular network)
- agree an ephemeral key with ECDHE, which gives forward secrecy: recording traffic and later stealing a key does not decrypt past sessions
TLS 1.3
TLS 1.3 removes obsolete algorithms (RSA key exchange, CBC, SHA-1, static Diffie-Hellman), encrypts most of the handshake, and needs only one round trip (the client sends its key share in ClientHello). Resumed sessions can even send data in the first flight ("0-RTT"), at the cost of replay risk. Prefer TLS 1.3 where the server and library support it.
Cipher suites for constrained devices
| Suite (TLS 1.2 name) | Notes |
|---|---|
ECDHE-ECDSA-AES128-GCM-SHA256 | Common modern choice; ECC keys are small; uses AES hardware |
ECDHE-ECDSA-CHACHA20-POLY1305 | Fast in software on MCUs without AES acceleration |
PSK-AES128-CCM8 | No certificates or public-key maths: tiny and fast |
ECC (P-256 or Curve25519) is preferred over RSA on microcontrollers: a 256-bit ECC key is as strong as 3072-bit RSA, signatures are faster and keys smaller. Many MCUs and secure elements accelerate AES, SHA-256 and ECC.
Pre-shared keys
With PSK, both sides share a symmetric secret configured in advance, and the handshake needs no certificates or public-key operations. It is fast, small and well suited to closed systems with a few hundred devices. The downsides: the server must store every device's key, a leaked key compromises that device's past traffic unless combined with ECDHE (ECDHE-PSK), and provisioning and rotating keys at scale is harder than issuing certificates.
DTLS
DTLS is TLS adapted for UDP: it adds sequence numbers and retransmission for handshake messages, and tolerates loss and reordering of records. It secures CoAP (CoAPS, port 5684) and LwM2M, which suit NB-IoT and other lossy, low-power links. DTLS 1.2 Connection ID lets a session survive the device's IP address changing (common behind cellular NAT), avoiding a full handshake after every sleep.
Certificates and keys on the device
What a device stores:
- Trusted root CA certificate(s) to verify servers. Plan for rotation: roots expire and clouds change CAs; ship two, and allow updating them.
- For mutual TLS, its own device certificate and private key.
The private key is the crown jewel. Options, from weakest to strongest:
| Storage | Risk |
|---|---|
| Plain in flash | Read out with a debugger or a firmware dump; disable debug ports at minimum |
| Encrypted in flash with a device-unique key | Better; key derivation from hardware unique ID or PUF |
| MCU secure storage / TrustZone secure world | Key never leaves the secure side |
| Secure element (ATECC608, SE050, OPTIGA Trust M) | Key generated inside and never exportable; signing happens in the chip |
Generate the key on the device (or in the secure element) and issue a certificate for it during manufacturing, rather than copying the same key to many devices.
Fitting TLS in RAM
Libraries: mbedTLS (now TF-PSA-Crypto/Mbed TLS), wolfSSL, BearSSL, and vendor-integrated variants. RAM is usually the constraint:
- A TLS record can be 16 KB, so by default each connection needs about 16 KB for input plus output buffers. The maximum fragment length extension (or record size limit) lets both sides agree on smaller records (512 bytes to 4 KB), if the server supports it.
- The handshake temporarily needs extra RAM for certificate parsing and ECC operations; check peak usage, not steady state.
- Limit the certificate chain length and use ECC certificates to reduce parsing memory.
- Session resumption (session tickets or IDs) skips the expensive handshake on reconnect, saving time and energy after each wake-up.
#include <stdio.h>
int main(void) {
/* Rough RAM budget for one TLS connection on an MCU, in bytes. */
int in_buf = 4096 + 29, out_buf = 4096 + 29; /* records limited to 4 KB with max fragment length */
int handshake_peak = 6000; /* certificate parsing and ECC maths */
int session = 1500; /* keys, state, ticket */
printf("steady state: %d bytes\n", in_buf + out_buf + session);
printf("peak during handshake: %d bytes\n", in_buf + out_buf + session + handshake_peak);
printf("with default 16 KB records: %d bytes\n", 2 * (16384 + 29) + session + handshake_peak);
return 0;
}
Pitfall: Disabling certificate verification "to get it working" (
MBEDTLS_SSL_VERIFY_NONE) and shipping it leaves the device open to any man-in-the-middle. It is one of the most common IoT vulnerabilities found in audits.
Interview question: How would you store a device's TLS private key securely?
Answer: Ideally generate it inside a secure element (or the MCU's secure world under TrustZone) so it never exists outside protected hardware; the TLS library asks the secure element to sign during the handshake. Issue a per-device certificate for it in manufacturing. If no secure hardware exists, keep the key encrypted in flash with a device-unique key, enable flash read-out protection, disable or lock debug ports in production, and never reuse one key across devices, so one compromised device does not expose the fleet.
Interview question: Your MCU has 64 KB of RAM. How do you make TLS fit?
Answer: Use ECC rather than RSA certificates, limit the record size with the maximum fragment length or record size limit extension so buffers are a few KB instead of 16 KB each, restrict cipher suites to one or two, use hardware crypto acceleration, keep the certificate chain short and the trusted root list small, and measure peak heap use during the handshake. Use session resumption to avoid repeated full handshakes. If it still does not fit, consider PSK cipher suites or offloading TLS to a network module or secure element that supports it.
Build it: trust only the real cloud server
This is step 3 of the module project, the office air-quality monitor. Its connection to the cloud now runs over TLS. The TLS library checks that the server's certificate chain is signed correctly, but the monitor's firmware still decides whether that certificate belongs to the server it meant to reach and whether it is valid now. Skip either and anyone with a certificate for some other site, or a monitor whose clock is still at 1970, breaks the security.
Lab: Check the server certificate's name, issuer and dates
host_match(pattern, host)returns 1 when a certificate name matches the host name, ignoring case. A pattern may start with*., and then the*stands for exactly one whole label:*.airsense.examplematcheseu.airsense.example, but notairsense.exampleora.eu.airsense.example. A*anywhere else never matches.cert_check(c, host, now)returns, checking in this order:CERT_NO_TIMEwhennowis beforeBUILD_TIME: the clock has not been set yet, so no dates can be checked (get the time first, then connect);CERT_UNKNOWN_CAwhen the issuer is not one of theTRUSTED_ROOTS(the monitor ships two, so the cloud can change CA);CERT_NOT_YETorCERT_EXPIREDwhennowis outsidenot_beforetonot_after(both inclusive);CERT_WRONG_HOSTwhen no name matches. If the certificate has subject alternative names (san_count > 0), only they count and the common name is ignored; otherwise the common name is used;- otherwise
CERT_OK.
Going deeper
Interview question: How would you secure a smart lock's connection to its cloud?
Answer: TLS with the server's certificate verified against a pinned or bundled CA, a unique client certificate per device provisioned at the factory with its private key in secure hardware, correct time (for certificate validity) from a trusted source, and session resumption to save energy. Plan for certificate renewal and revocation.
Interview question: What is certificate pinning and what are its risks?
Answer: Instead of trusting any certificate chained to a trusted root, the device accepts only a specific certificate or public key (or a specific intermediate CA) for its server. It defends against a compromised or mis-issued certificate from another CA. The risk is that when the server's certificate or key changes, pinned devices can no longer connect unless the pin can be updated, so pin to a key you control, include backup pins and have an update path.
Interview question: How does session resumption save energy on a battery device?
Answer: A full TLS handshake needs public-key operations (ECDHE and signature verification) and several round trips, costing milliseconds to seconds of CPU and radio time. Resumption (session tickets or IDs, or TLS 1.3 PSK resumption) reuses keys from a previous session, skipping the expensive asymmetric operations and certificate checks and reducing round trips, which matters when a device reconnects after every sleep.
Explain it: In your own words, explain what a TLS client checks before trusting a server.
Answer: The server sends its certificate chain. The client checks that each certificate is signed by the next one up and that the chain ends at a root certificate it already trusts and stores. It checks that the certificate is within its validity dates, which needs a correct clock, that it is meant for server authentication, and that the name in it matches the server it intended to connect to. Finally, the handshake proves the server holds the private key for that certificate. Only if all of these pass does it trust the connection.