↓ Skip to main content
  1. Engineering Notes & Articles/

IoT Security Fundamentals: TLS/SSL, X.509 Certificates, and Securing Embedded Devices

Practical IoT Engineering - This article is part of a series.
Part 6: This Article

During firmware development, hitting a TLS certificate verification error on a microcontroller is a familiar rite of passage. The stack trace complains about an untrusted root certificate or a handshake timeout, and a quick search turns up a one-line fix: espClient.setInsecure(). Suddenly, the error disappears, messages flow to the MQTT broker, and development moves on.

Leaving that single line in production firmware quietly disables the most important defense in modern transport security. Without server certificate verification, your microcontroller encrypts its packets—yet willingly hands its credentials and telemetry to any rogue access point or spoofed broker performing a man-in-the-middle (MITM) attack.

Securing embedded IoT devices requires moving beyond quick development shortcuts. Unlike cloud servers with gigabytes of RAM and automated certificate daemons, microcontrollers must negotiate modern cryptography inside tight SRAM budgets, validate server identities across multi-year lifespans, and protect unique device private keys from physical extraction.


Why Plaintext MQTT and setInsecure() Fail in the Field
#

In traditional web browsers, users see a prominent warning icon when a site’s TLS certificate fails validation. Headless IoT nodes have no screen and no human operator to click “Proceed Anyway”—so firmware libraries either reject the connection outright or accept everything blindly when certificate checks are turned off.

Running unencrypted MQTT (port 1883) or unverified TLS (setInsecure()) exposes deployed fleets to three concrete risks:

  • Credential Theft via Passive Sniffing: Over unencrypted connections, MQTT usernames, passwords, and topic structures travel in plaintext across local Wi-Fi networks and upstream routers.
  • Man-in-the-Middle (MITM) Spoofing: Even with TLS encryption enabled, skipping Root CA verification means an attacker spoofing DNS or ARP on a local network can present their own self-signed certificate. The microcontroller completes the handshake, transmits its broker password, and accepts forged actuator commands.
  • Fleet-Wide Blast Radius from Shared Secrets: Embedding a single hardcoded broker password or API key across 500 field devices means extracting the flash memory from one stolen outdoor node compromises the entire fleet.

How TLS Works on Memory-Constrained Microcontrollers
#

Transport Layer Security (TLS 1.2 and TLS 1.3) provides three cryptographic guarantees: confidentiality (encryption), integrity (tamper detection), and authentication (proving who is on the other end of the wire).

The Resource Cost of a TLS Handshake
#

While symmetric encryption of ongoing MQTT packets (such as AES-128-GCM or ChaCha20-Poly1305) is fast and lightweight, the initial TLS handshake relies on asymmetric public-key cryptography (ECDSA or RSA), which is computationally expensive and memory-intensive:

  • SRAM Overhead: A full TLS session context on an embedded stack like mbedTLS typically consumes 30 KB to 60 KB of heap SRAM during the handshake—mostly for input/output record buffers (often 16 KB each in standard TLS) and X.509 certificate parsing. On an ESP32 with 320 KB+ SRAM this fits comfortably, whereas on smaller Cortex-M microcontrollers it requires careful buffer tuning (such as TLS Maximum Fragment Length negotiation).
  • Hardware Crypto Acceleration: Modern IoT microcontrollers (such as ESP32-S3, STM32U5, and Nordic nRF52840/nRF5340) include dedicated hardware accelerators for AES, SHA-256, Elliptic Curve Cryptography (ECC), and True Random Number Generators (TRNG). Hardware ECC cuts an ECDSA handshake from seconds down to tens of milliseconds—saving significant battery energy during wake cycles.
  • Session Resumption: For battery-powered nodes waking periodically, TLS session tickets or PSK (Pre-Shared Key) resumption allow the device to skip full asymmetric certificate exchanges on subsequent connections, trimming both airtime and milliamps.

X.509 Certificates: Server Auth vs. Mutual TLS (mTLS)
#

To authenticate endpoints without hardcoding shared passwords, IoT architectures rely on X.509 Public Key Infrastructure (PKI). Depending on security requirements and operational scale, deployments typically use one of two authentication models (with certificate lifespans and provisioning workflows varying by broker platform):

Authentication Model How Identity Is Verified Credential Stored on MCU Operational Trade-Off
One-Way TLS + Username/Password Device verifies the broker’s server certificate against a trusted Root CA; device authenticates via per-device token or password. Broker’s Root CA public certificate (plus device password/token). Simpler initial provisioning; still relies on secret tokens that must be rotated carefully.
Mutual TLS (mTLS) Both sides exchange and verify X.509 certificates signed by trusted Certificate Authorities—eliminating passwords entirely. Root CA cert + unique Device Client Certificate + Device Private Key. Highest cryptographic assurance (standard on AWS IoT Core & enterprise brokers); requires per-device key generation and lifecycle management.

Avoiding the Root CA Expiration Trap
#

A classic field failure occurs when developers embed a short-lived leaf server certificate directly into firmware instead of the Root Certificate Authority (CA) certificate. Leaf certificates (such as Let’s Encrypt certificates) routinely expire every 90 days. Once a leaf certificate rotates on the server, every deployed microcontroller with that hardcoded leaf cert loses connectivity permanently unless physically reflashed.

Always pin the Root CA certificate (which typically remains valid for 10 to 20 years)—or bundle two trusted Root CAs (a primary and a backup) so your fleet survives upstream CA transitions seamlessly.

#include <WiFiClientSecure.h>
#include <PubSubClient.h>

// Embed the long-lived Root CA certificate (NOT the 90-day leaf cert)
const char* root_ca_pem = R"EOF(
-----BEGIN CERTIFICATE-----
MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF
... (Root CA PEM content) ...
-----END CERTIFICATE-----
)EOF";

WiFiClientSecure tlsClient;
PubSubClient mqttClient(tlsClient);

void setupSecureMqtt() {
  // 1. Sync system clock via NTP (required so mbedTLS can validate cert expiry dates)
  configTime(0, 0, "pool.ntp.org", "time.nist.gov");
  time_t now = time(nullptr);
  while (now < 1700000000) {
    delay(200);
    now = time(nullptr);
  }

  // 2. Enforce strict Root CA validation (never use setInsecure() in production)
  tlsClient.setCACert(root_ca_pem);

  // Optional for Mutual TLS (mTLS):
  // tlsClient.setCertificate(device_client_cert_pem);
  // tlsClient.setPrivateKey(device_private_key_pem);

  mqttClient.setServer("mqtt.rikode.com", 8883);
}

Watch out for the 1970 clock trap: Notice the NTP time synchronization step before initiating the TLS handshake. X.509 certificates carry Not Before and Not After validity timestamps. A freshly booted microcontroller without a battery-backed Real-Time Clock (RTC) thinks the year is 1970, causing mbedTLS to reject valid server certificates as “not yet valid.”


Protecting Keys and Firmware in Hardware
#

Software encryption alone cannot stop an attacker who gains physical access to a deployed sensor box, desolders the external SPI flash chip, and reads its contents with a $10 programmer. Modern microcontrollers provide hardware security features to close physical attack surfaces:

  • NVS Encryption & Flash Encryption: Encrypts the contents of external SPI flash using a unique AES key burned into on-chip eFuses (one-time programmable memory) that software cannot read back directly. Even if an attacker dumps the raw flash chip, private keys and Wi-Fi credentials appear as random ciphertext.
  • Secure Boot (v2): Verifies the cryptographic signature (such as RSA-3072 or ECDSA) of the bootloader and application firmware at every power-on before executing a single instruction—preventing attackers from flashing modified firmware onto recovered hardware.
  • Secure Elements (ATECC608 / SE050): For high-value industrial or commercial products, dedicated tamper-resistant cryptographic coprocessors generate and store private keys inside isolated silicon where the raw key never enters the main microcontroller’s SRAM.
  • Disabling Debug Interfaces (JTAG / SWD): Before shipping field units, disable or lock JTAG/SWD debug ports via eFuses or option bytes so an attacker cannot attach a debugger and dump SRAM while keys are loaded in memory.

4 Common Embedded Security Mistakes to Avoid
#

  1. Shipping setInsecure() or Disabling Certificate Verification: Bypassing server certificate checks leaves devices vulnerable to trivial DNS/ARP spoofing attacks on public or shared networks. Always validate against a trusted Root CA and verify system clock synchronization via NTP beforehand.
  2. Using RSA-4096 Certificates on Battery-Powered MCUs: While RSA-2048/4096 works fine on desktop servers, verifying RSA signatures and performing private-key operations on a microcontroller takes significantly more CPU cycles and RAM than ECC (Elliptic Curve Cryptography, e.g., P-256 / secp256r1) at equivalent cryptographic strength. Prefer ECDSA P-256 certificates for embedded fleets.
  3. Sharing One Client Certificate or API Key Across Every Device: If all 200 nodes share a single client certificate or static password, revoking one compromised node forces you to revoke access for the entire fleet simultaneously. Provision unique per-device credentials tied to individual broker Access Control Lists (ACLs) so node-01 can only publish to .../node-01/#.
  4. Hardcoding Private Keys Inside Version-Controlled Source Files: Committing device_private_key.h into a Git repository exposes cryptographic secrets permanently in commit history. Inject unique keys and certificates into a dedicated factory NVS partition during manufacturing or secure provisioning.

Moving Forward in the Series
#

With TLS encryption, Root CA validation, per-device X.509 identities, and hardware flash encryption in place, your devices can authenticate safely and protect sensitive telemetry in transit and at rest. Yet even the most secure firmware will eventually need bug fixes, security patches for newly discovered TLS vulnerabilities, or updated Root CA bundles years after installation.

In Part 6: OTA (Over-The-Air) Firmware Updates: Safe Deployment, Partition Tables, and Rollback, we examine how to update deployed fleets safely without ever touching a USB cable—covering dual-bank flash layouts, cryptographic firmware signing, and automatic bootloader rollback.

Practical IoT Engineering - This article is part of a series.
Part 6: This Article