16  Secure Data and Software

16.1 Overview

Secure data and software means protecting IoT systems from vulnerabilities in code (software security) and ensuring data remains confidential and unmodified throughout its lifecycle (data security). This comprehensive topic is covered across four focused chapters:

Chapter Navigation

This material is organized into four focused chapters for easier learning:

Chapter Topics Time
Software Vulnerabilities OWASP Top 10, XSS, SQL Injection, Local/Remote Exploits ~25 min
IoT Protocol Security MQTT Security, CoAP/DTLS, Protocol Comparison ~20 min
Authentication and Credentials Password Attacks, MFA, STRIDE, Risk Assessment ~20 min
Firmware Security Secure Boot, Code Signing, OTA Updates, Rollback Protection ~30 min

Recommended order: Start with Software Vulnerabilities, then Protocol Security, Authentication, and finally Firmware Security.

16.2 Learning Objectives

Authentication and access control for IoT determine who or what is allowed to interact with your system and what they can do. Think of it like a building security system: first you check someone’s ID badge (authentication), then you determine which rooms they can enter (access control). For IoT, this means verifying that devices and users are genuine before granting them access.

“Secure data and software covers EVERYTHING from the code running on devices to the data stored in the cloud,” Max the Microcontroller explained. “This is a big topic, so it has been split into four focused chapters.”

Sammy the Sensor outlined the journey. “First, Software Vulnerabilities teaches you the OWASP Top 10 – the most dangerous coding mistakes. Then IoT Protocol Security shows you how to protect MQTT and CoAP communications. Authentication and Credentials covers password attacks and multi-factor authentication. Finally, Firmware Security teaches secure boot and over-the-air updates.”

“Think of it like protecting a treasure,” Lila the LED suggested. “The treasure is your IoT data. Software vulnerabilities are holes in the treasure chest. Protocol security is the armored truck that transports it. Authentication is the guard who checks IDs before letting anyone near. And firmware security makes sure nobody swaps the real chest for a fake one!”

“Start with Software Vulnerabilities and work through in order,” Bella the Battery advised. “Each chapter builds on the previous one. By the end, you will understand the complete security picture – from writing safe code, to encrypting communications, to verifying identities, to keeping firmware tamper-proof. That is comprehensive data and software security!”

Across these chapters, you will be able to:

  • Identify Software Vulnerabilities: Recognize OWASP Top IoT vulnerabilities including authentication, access control, and injection flaws
  • Apply Secure Coding Practices: Implement input validation, output encoding, and secure memory management in IoT firmware
  • Protect Stored Data: Use encryption, secure storage, and proper key management for data at rest on IoT devices
  • Secure Data in Transit: Implement TLS/DTLS and application-layer encryption for IoT communications
  • Manage Firmware Security: Design secure update mechanisms with code signing and rollback protection
  • Audit and Test Security: Apply static analysis, dynamic testing, and penetration testing to IoT software

16.3 Prerequisites

Before diving into these chapters, you should be familiar with:

How It Works: Data Protection Across Three States

Data protection requires different techniques for each state in the data lifecycle:

State What It Means Real Example Protection
At Rest Stored on device Wi-Fi password in flash memory Encryption
In Transit Moving over network Sensor data going to cloud TLS/HTTPS
In Use Being processed Password being checked Secure memory

State 1: Data At Rest (Stored on Device)

  1. Identify sensitive data: WiFi passwords, API keys, encryption keys, user credentials
  2. Select encryption: AES-256-GCM for symmetric encryption, Argon2id for password hashing
  3. Key storage: Use hardware secure element (TPM, ATECC608) to protect encryption keys
  4. Access control: Operating system permissions restrict which processes can read stored data
  5. Example: ESP32 stores WiFi password in NVS flash partition encrypted with flash encryption key in eFuse

State 2: Data In Transit (Moving Over Network)

  1. Establish secure channel: TLS 1.3 handshake negotiates encryption keys between client and server
  2. Encrypt application data: AES-128-GCM encrypts MQTT payloads using session keys
  3. Verify integrity: HMAC or GCM authentication tag prevents tampering during transmission
  4. Mutual authentication: Server verifies device certificate AND device verifies server certificate
  5. Example: Sensor sends temperature reading over MQTTS, encrypted end-to-end from device to cloud

TLS 1.3 Handshake Overhead for Battery-Powered IoT:

Consider a smart agriculture sensor (ESP32, 2× AA batteries, 3000 mAh capacity) transmitting soil moisture data to AWS IoT Core over MQTTS (MQTT over TLS 1.3). Calculate the battery impact of TLS handshakes.

TLS 1.3 Handshake Energy Cost: \[ \text{Handshake duration} = 450 \text{ ms (ECDHE key exchange + certificate verification)} \]

\[ \text{Radio power during handshake} = 240 \text{ mA} \times 3.3\text{ V} = 792 \text{ mW} \]

\[ \text{Energy per handshake} = 792 \text{ mW} \times 0.45 \text{ s} = 356.4 \text{ mJ} \]

Data Transmission (Post-Handshake): \[ \text{Payload size} = 24 \text{ bytes (sensor reading + metadata)} \]

\[ \text{Transmission duration} = 80 \text{ ms (at 2.4 kbps effective)} \]

\[ \text{Energy per transmission} = 792 \text{ mW} \times 0.08 \text{ s} = 63.4 \text{ mJ} \]

Two Strategies Compared:

Strategy A: New handshake per reading (every 15 minutes): \[ \text{Daily handshakes} = \frac{24 \times 60}{15} = 96 \text{ handshakes/day} \]

\[ \text{Daily energy} = 96 \times (356.4 + 63.4) = 96 \times 419.8 = 40,300 \text{ mJ/day} \]

\[ \text{Battery life} = \frac{3000 \text{ mAh} \times 3.3\text{ V} \times 3600 \text{ s/h}}{40,300 \text{ mJ/day}} = \frac{35,640,000}{40,300} = 884 \text{ days} \]

Strategy B: Session resumption (1 handshake per 8 hours): \[ \text{Daily handshakes} = \frac{24}{8} = 3 \text{ handshakes/day} \]

\[ \text{Daily energy} = 3 \times 356.4 + 96 \times 63.4 = 1,069.2 + 6,086.4 = 7,155.6 \text{ mJ/day} \]

\[ \text{Battery life} = \frac{35,640,000}{7,155.6} = 4,980 \text{ days} \approx 13.6 \text{ years} \]

Key Insight: TLS session resumption extends battery life 5.6× longer (from 2.4 years to 13.6 years) by avoiding redundant handshakes while maintaining security.

Try adjusting the parameters below to see how different configurations affect battery life:

State 3: Data In Use (Being Processed)

  1. Secure memory handling: Clear sensitive data from RAM after use (explicit_bzero or memset_s – never plain memset, which compilers may optimize away)
  2. Avoid logging secrets: Never write passwords or keys to debug logs or serial output
  3. Constant-time operations: Password comparison uses XOR-based algorithm to prevent timing attacks
  4. Hardware isolation: Use Trusted Execution Environment (TEE) for cryptographic operations
  5. Example: Device decrypts WiFi password from flash into RAM, connects to network, then zeroes password in RAM

Defense-in-Depth Insight: Attackers must defeat MULTIPLE protections: - Network eavesdropper: Intercepts encrypted data → Cannot decrypt without session keys - Physical attacker: Extracts flash chip → Cannot decrypt without hardware key in secure element - Malware on device: Reads process memory → Finds data already zeroed after use

Diagram showing three data protection states: Data at Rest protected by encryption and secure key storage, Data in Transit protected by TLS/HTTPS and mutual authentication, and Data in Use protected by secure memory handling and hardware isolation
Figure 16.1: Three Data States: At Rest, In Transit, and In Use Protection Mechanisms

16.4 Key Security Concepts

16.4.1 Defense in Depth

Security requires 7 layers of protection:

  1. Network Security: TLS/DTLS encryption (confidentiality)
  2. Authentication: Username/password or certificates (identity)
  3. Authorization: Topic/resource-level access control (permissions)
  4. Input Validation: Whitelist approach (prevent injection)
  5. Secure Coding: Parameterized queries, output encoding (prevent exploitation)
  6. Updates: Regular patching (remediate discovered vulnerabilities)
  7. Monitoring: Audit logs and anomaly detection (detect breaches)

16.4.2 Common Misconception: “Encryption Alone Makes My IoT System Secure”

Encryption protects confidentiality (data in transit) but doesn’t address authentication (who is connecting?) or authorization (what can they access?). The 2016 Mirai botnet compromised 600,000+ IoT devices using default passwords—many of which supported encrypted protocols but didn’t enforce authentication.

16.5 Chapter Summaries

16.5.1 1. Software Vulnerabilities and Web Security

  • OWASP Top 10 IoT vulnerabilities and prioritization
  • Cross-Site Scripting (XSS) attack mechanisms and prevention
  • SQL Injection and parameterized query defenses
  • Local vs remote exploit categories
  • Defense-in-depth layered security model

16.5.2 2. IoT Protocol Security

  • MQTT publish-subscribe architecture and security configuration
  • UTF-8 validation DoS attacks and mitigation
  • CoAP/DTLS for constrained devices
  • Amplification attack prevention
  • Protocol selection guide (MQTT vs CoAP vs HTTP)

16.5.3 3. Authentication and Credential Security

  • Password attack methods: brute force, dictionary, rainbow tables
  • Secure password storage with bcrypt/Argon2 and salting
  • Multi-factor authentication implementation
  • Default credential elimination strategies
  • STRIDE threat modeling and risk assessment

16.5.4 4. Firmware Security and Secure Updates

  • Secure boot chain design with hardware root of trust
  • Code signing with certificate hierarchies
  • Anti-rollback protection using OTP fuses
  • A/B partition schemes for atomic updates
  • Automatic rollback on boot failure
  • Hands-on ESP32 secure boot lab

16.6 Quick Reference: Secure Coding Checklist

Essential Security Controls

Application Security:

Authentication:

Data Protection:

Firmware:

16.7 Knowledge Check

Scenario: Smart meter manufacturer needs to patch a critical vulnerability in 100,000 deployed devices. Design a secure OTA update mechanism with rollback protection.

Update Requirements:

  • Firmware size: 512 KB
  • Download time per device: 45 seconds
  • Success rate target: >99%
  • Rollback if boot fails after 3 attempts

Security Architecture:

1. Code Signing (mandatory):
   - Private key: HSM-protected RSA-4096
   - Signature: SHA-256 hash + RSA signature (512 bytes)
   - Verification: Device checks signature BEFORE flashing

2. Encrypted Transport:
   - TLS 1.3 for firmware download
   - Certificate pinning (reject unknown CAs)

3. Anti-Rollback:
   - Firmware version stored in OTP fuse
   - Cannot downgrade to vulnerable versions
   - Version increments: 1.2.3 → 1.2.4 (patch)

4. Atomic Update:
   - A/B partition scheme
   - Download to inactive partition
   - Boot from new partition only if valid
   - Automatic rollback on 3 failed boots

Phased Rollout Plan:

Day 1: 1% (1,000 devices) - Canary deployment
  Monitor for 24 hours
  Success rate: 99.3% (7 failures investigated)

Day 2-3: 10% (10,000 devices)
  Success rate: 99.6%
  No critical issues

Day 4-7: 50% (50,000 devices)
  Success rate: 99.5%
  Total time: 625 hours (26 days if sequential)

Day 8-14: 100% (all devices)
  Final success rate: 99.4%
  Failed devices: 600 (require manual intervention)

Failure Analysis:

  • 400 devices: Network timeouts (retry succeeded)
  • 150 devices: Power loss during flash (auto-rollback worked)
  • 50 devices: Corrupt flash memory (hardware replacement needed)

Cost Breakdown:

  • Code signing infrastructure: $15,000/year (HSM)
  • Bandwidth: 512 KB × 100,000 = 51.2 GB × $0.09/GB = $5 (negligible)
  • Engineering time: 320 hours × $150/hr = $48,000
  • Manual fixes: 50 devices × $200 = $10,000
  • Total: $73,005 for critical security patch
Encryption Level CPU Overhead Storage Overhead Key Management Use Case
None (plaintext) 0% 0% N/A Public data only
Application-level 5-10% +16 bytes/block Simple (hardcoded key) Low-value secrets
Filesystem encryption 10-15% +5% (metadata) Medium (key in flash) Moderate security
Secure enclave 15-20% +10% (overhead) Complex (hardware key) High-value credentials

Recommendation: Use secure enclave (TPM/TEE) for WiFi passwords and API keys. Accept 15-20% performance hit for security gain.

Common Mistake: Firmware Update Without Signature Verification

Vulnerable Code:

// BAD: No signature check
void updateFirmware(uint8_t* data, size_t len) {
    flashWrite(FIRMWARE_PARTITION, data, len);
    ESP.restart();  // Boot new firmware immediately
}

Attack: Man-in-the-middle attacker intercepts firmware download and injects malware. Device accepts and runs malicious firmware.

Secure Implementation:

// GOOD: Verify signature before flashing
bool updateFirmware(uint8_t* data, size_t len, uint8_t* signature) {
    // 1. Hash the firmware
    uint8_t hash[32];
    sha256(data, len, hash);

    // 2. Verify signature with public key
    if (!rsaVerify(hash, 32, signature, publicKey)) {
        Serial.println("Signature invalid - REJECTING update");
        return false;
    }

    // 3. Flash to inactive partition
    flashWrite(INACTIVE_PARTITION, data, len);

    // 4. Mark new partition as bootable
    setBootPartition(INACTIVE_PARTITION);

    return true;
}

Real incident (2016): The Mirai botnet compromised 600,000+ IoT devices primarily through default credentials, but unsigned firmware mechanisms would have allowed attackers to persist across reboots by injecting malicious firmware updates.

Common Pitfalls

Using the device identity certificate to also sign firmware updates means key compromise allows both impersonating the device and pushing malicious firmware. Use separate keys for device identity and firmware signing, stored in separate HSMs or secure elements.

If new firmware fails to boot (application crash, peripheral initialization failure), a device without rollback capability becomes permanently bricked. Always implement a watchdog-triggered rollback to the previous known-good firmware version on consecutive boot failures.

AES-ECB (Electronic Code Book) mode produces the same ciphertext for the same plaintext block, leaking information about data patterns in encrypted flash. Always use AES-CBC, AES-CTR, or AES-GCM mode for flash encryption, which eliminate this pattern leakage.

The encryption key must not be stored in the same flash it encrypts. Use eFuse (one-time programmable memory) or a secure element to store encryption keys where they cannot be read by normal flash read operations.

16.8 What’s Next

If you want to… Read this
Learn authentication for IoT systems Authentication and Access Control
Explore secure credential management Credential Security
Apply zero trust security principles Zero Trust Security
Study cryptographic foundations Encryption Principles
Understand IoT security threats Threat Modelling and Mitigation

Start with the first chapter in this series:

Software Vulnerabilities and Web Security - Learn about OWASP Top 10, XSS, SQL Injection, and defense-in-depth strategies.

After completing all four chapters, continue to User Experience Design to explore human factors in IoT systems.

Key Concepts

  • Encryption at Rest: Encrypting data stored in device flash or database using symmetric encryption (AES-256-GCM); protects against physical device extraction attacks
  • Encryption in Transit: Using TLS 1.3 or DTLS to encrypt data during transmission; prevents eavesdropping and man-in-the-middle attacks on the network
  • Secure Boot: A boot process that cryptographically verifies each firmware component’s signature before executing it; prevents booting modified or malicious firmware
  • Code Signing: Applying a cryptographic signature to firmware images so devices can verify authenticity before installation; the foundation of secure OTA updates
  • OTA (Over-the-Air) Update: Remote firmware delivery to deployed devices; must be authenticated, integrity-verified, and rolled back if the new firmware fails to boot
  • Secure Element (Hardware): A tamper-resistant chip for storing encryption keys and performing cryptographic operations; protects against key extraction through physical attacks
  • Flash Encryption: Encrypting the device’s flash storage so the firmware and data are unintelligible if the flash chip is physically removed and read externally
In 60 Seconds

Secure IoT data and software protection combines encrypted storage (AES-256), authenticated transmission (TLS 1.3), secure boot with cryptographic verification, and signed OTA firmware updates — creating defense-in-depth where compromising any single layer does not immediately expose device data or enable unauthorized code execution.