IoT Security
IoT security is engineering under constraints that most security guidance ignores. The device may have sixty-four kilobytes of memory, a ten-year expected service life, a serial port on the board, no screen, no keyboard, and an owner who will never log in to change a default password. It may be a controller inside a pump, a camera in a hospital, or a meter on a pole two hours from the nearest technician. Everything you decide has to survive those conditions, which is why IoT security is less about exotic cryptography and more about identity, transport, segmentation and update design decided before the first unit ships.
Constraints that break standard security practice
Each common assumption fails somewhere in a fleet, and the failures compound at scale.
| Constraint | Standard advice that fails | What works instead |
|---|---|---|
| Limited CPU and memory | Full TLS on every connection, heavy agents | Hardware-accelerated TLS, DTLS, gateway offload |
| No user interface | Ask the user to set a password | Per-device certificates provisioned at manufacture |
| Long lifecycle, rare patching | Monthly patch cycle | Signed, staged updates with rollback |
| Physical access in the field | Restrict local ports | Tamper response, encrypted storage, secure boot chain |
| Enormous scale | Manual device inventory | Automated enrollment with signed attestations |
| Flaky connectivity | Assume acknowledgements arrive | Store-and-forward, idempotent commands |
| Heterogeneous protocols | One VPN for everything | Gateway-enforced protocol translation and policy |
The gateway row deserves emphasis. When the edge device cannot enforce policy, push enforcement to a gateway you can patch, and treat the device-to-gateway link as the hostile hop it may well be.
Protocols and what each one actually protects
Protocol choice determines which protections you must bolt on yourself. Nothing on this list is safe by default; each needs explicit configuration.
| Protocol | Typical use | Security mechanism | Common misconfiguration |
|---|---|---|---|
| MQTT over TCP | Telemetry, commands | TLS with client certificates | Broker accepting anonymous sessions on 1883 |
| CoAP | Constrained REST | DTLS | Skipping DTLS because udp is easier to debug |
| Zigbee | Home and building automation | AES-128 link key | Using the well-known install code from the manual |
| BLE | Wearables, beacons | Pairing and bonding | Just-works pairing for anything sensitive |
| LoRaWAN | Long-range, low power | AES-128 network and app session keys | Hardcoded app keys shared across a fleet |
| HTTP APIs | Cloud uplinks | TLS plus tokens | Tokens with no expiry, embedded in firmware |
Choose the transport that gives you mutual authentication cheaply: MQTT with per-device client certificates and a broker that rejects unauthenticated connects covers most telemetry designs. Then decide what happens when the link drops â a device that retries forever with an expired credential becomes a self-inflicted denial of service on your broker.
Identity for a device with no keyboard
The identity problem is the heart of IoT security. A shared password across ten thousand units means one reverse-engineered firmware discloses the entire fleet, so each device needs its own key pair, generated on the device where possible, provenance recorded, and revocable individually. Manufacturing-time provisioning gives you that, and the enrollment flow below shows the shape: the device proves possession of a key, receives a certificate, and can be revoked later without touching its neighbours.
import json, ssl, socket, datetime
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
def generate_keypair():
"""Generated on-device: the private key never leaves the secure element."""
key = ec.generate_private_key(ec.SECP256R1())
return key
def build_csr(device_id, key):
csr = (x509.CertificateSigningRequestBuilder()
.subject_name(x509.Name([
x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, device_id),
x509.NameAttribute(x509.oid.NameOID.ORGANIZATION_NAME, "fleet-a"),
]))
.sign(key, hashes.SHA256()))
return csr
def enroll(device_id, csr_pem, factory_token, endpoint="https://pki.example.com/enroll"):
"""Device proves factory provenance, receives an identity certificate."""
resp = requests.post(endpoint, timeout=10,
json={"device_id": device_id, "csr": csr_pem,
"token": factory_token,
"fw_version": current_firmware_version()},
headers={"content-type": "application/json"})
if resp.status_code == 409:
raise RuntimeError("device already enrolled - check revocation status")
resp.raise_for_status()
issued = resp.json()
store_cert(issued["certificate"], issued["chain"])
return issued["not_after"]
def connect_tls(host, port, certfile, keyfile):
ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH,
cafile="/etc/fleet/ca.pem")
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
ctx.load_cert_chain(certfile, keyfile)
# the broker must demand our certificate; refusing anonymous is the point
ctx.set_ciphers("ECDHE+AESGCM")
return ctx.wrap_socket(socket.create_connection((host, port), timeout=10),
server_hostname=host)
Revocation deserves as much design as issuance. Store every issued certificate in a directory with a revocation reason and timestamp, publish revocation to brokers and gateways, and give the support team a way to kill a single device from a console without an engineering ticket. When a camera model is cracked in the wild, minutes matter and your lever is per-device revocation.
Boot integrity and the update problem
Secure boot establishes that the code running is the code you signed, from the boot ROM through the bootloader into the application image. It only helps if the verification key is not replaceable by the same update mechanism it protects, and if a failed verification results in a known state rather than a bricked unit. Alongside it, encrypt sensitive material at rest so a harvested device yields ciphertext rather than firmware secrets and customer data.
Updates are where long-lived fleets are won or lost. Sign every image, verify before applying, keep the previous image intact for rollback, and stage the rollout so a bad build stops at one percent of the fleet.
#!/usr/bin/env bash
# verify-and-apply.sh - run by the device agent before any firmware change
set -euo pipefail
IMAGE="$1"
PUBKEY="/etc/fleet/ota-public.pem"
STAGING="/var/lib/fleet/staging"
ACTIVE="/dev/mmcblk0p2" # A/B slot: never overwrite the running image
# 1. signature first, always - never parse an unsigned payload
if ! openssl dgst -sha256 -verify "$PUBKEY" -signature "$IMAGE.sig" "$IMAGE"; then
echo "REJECT: signature verification failed for $IMAGE" >&2
exit 1
fi
# 2. manifest: version must move forward, hardware must match
MANIFEST="$(dd if="$IMAGE" bs=1 count=4096 2>/dev/null | strings | grep '^FW:' | head -1)"
echo "$MANIFEST" | grep -q "HW=$(cat /etc/fleet/hw-rev)" || { echo "REJECT: wrong hardware"; exit 1; }
NEW_VER="$(echo "$MANIFEST" | sed -n 's/^FW:VERSION=//p')"
CURRENT_VER="$(cat /etc/fleet/version)"
if [ "$(printf '%s\n%s\n' "$CURRENT_VER" "$NEW_VER" | sort -V | tail -1)" != "$NEW_VER" ]; then
echo "REJECT: downgrade attempted ($CURRENT_VER -> $NEW_VER)"; exit 1
fi
# 3. write to the inactive slot, mark bootable, and reboot into it
cp "$IMAGE" "$STAGING/slot-b.img"
dd if="$STAGING/slot-b.img" of="$ACTIVE" bs=1M conv=fsync status=none
fw_setenv boot_slot b
echo "APPLIED $NEW_VER - rollback armed until health check passes"
The health check matters as much as the signature. After reboot, the device must report healthy within a window or the bootloader reverts to the previous slot, which converts a failed update from a truck roll into a logged event.
Segmenting a fleet you cannot fully inventory
You will not be able to profile every device, so assume compromise and contain it. Put devices in their own network zone with egress restricted to the broker or gateway they need, deny device-to-device traffic by default, and log every denied flow â a camera opening an outbound connection to an unfamiliar range is an incident, not a curiosity.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: iot-fleet-egress
namespace: iot
spec:
podSelector:
matchLabels:
tier: device-gateway
policyTypes: [Ingress, Egress]
ingress:
- from:
- ipBlock:
cidr: 10.40.0.0/16 # device VLAN only
ports:
- protocol: TCP
port: 8883 # MQTT over TLS
egress:
- to:
- ipBlock:
cidr: 10.40.10.5/32 # broker, nothing else
ports:
- protocol: TCP
port: 8883
- to:
- namespaceSelector:
matchLabels:
name: kube-system
ports:
- protocol: UDP
port: 53
- to:
- ipBlock:
cidr: 0.0.0.0/0
except:
- 169.254.169.254/32 # metadata service never reachable
ports:
- protocol: TCP
port: 443 # firmware and telemetry endpoints, allow-listed by FQDN at the proxy
Segmentation also protects the rest of your network from the device. A compromised thermostat should not be able to reach the domain controller, and the only reliable way to guarantee that is to never place it on a flat network in the first place.
When the device is already deployed in the field
Most fleets include units you cannot recall. For those, shift effort to the parts you still control: broker configuration, gateway policy and cloud credentials. Enforce mutual TLS on the broker and disable anonymous access, which forces legacy devices through a gateway you can update. Revoke and reissue fleet-wide credentials where a shared secret was baked in, and add network-level anomaly detection keyed to each device's known baseline â first-seen destinations, unusual command rates, out-of-hours reconnects. Finally, negotiate support windows with suppliers and record the end-of-support date per model, because the day a device stops receiving fixes is a scheduled risk acceptance that should appear on the register with an owner.
Retirement needs a plan too. Decommissioning a device means revoking its certificate, removing its broker credentials, deleting its cloud identity, and confirming that nothing downstream still references it â a forgotten device that reappears with valid credentials years later is a quiet backdoor. Keep a retirement checklist per model alongside the enrollment record, and run a sample of it whenever a batch is removed from service. The teams that handle this well treat device identity with the same lifecycle discipline as employee accounts: provisioned deliberately, reviewed periodically, revoked on the day the relationship ends.
â ī¸Assume firmware will be extracted
Common Mistakes
Shipping one shared password or key across the entire product line
Fix: Provision per-device key pairs at manufacture and support individual revocation from day one.
Running the broker without mutual TLS to make debugging easier
Fix: Require client certificates and reject anonymous sessions, using a gateway for legacy devices that cannot negotiate them.
Applying firmware updates without signature and rollback checks
Fix: Verify signatures before parsing, block downgrades, write to an inactive slot and revert if health checks fail.
Placing devices on the corporate network because segmentation is inconvenient
Fix: Isolate devices in their own zone with default-deny egress to named endpoints only.
Ignoring end-of-support dates for hardware already deployed
Fix: Record per-model support expiry on the risk register with an owner, a mitigation and a replacement budget.
Best Practices
- Generate keys on-device in a secure element so extraction yields only one identity
- Design enrollment and revocation before the first unit ships; retrofitting either is far more expensive
- Choose MQTT with client certificates and a broker that refuses unauthenticated connections
- Stage firmware rollouts in percentages with an automatic rollback window
- Baseline each device's network behavior and alert on first-seen destinations
Key Takeaways
- IoT security is constraint engineering: identity, transport, update and segmentation decided at design time
- Shared credentials turn one reverse-engineered firmware into a fleet-wide compromise
- Secure boot only helps when the verification key is not writable by the update path itself
- Verified, staged, reversible updates are what make a ten-year device survivable
- Assume field devices are compromised and contain them with default-deny egress and per-device revocation