Sub topic 12
Securing a connected device
This chapter assumes you can already connect a board to Wi-Fi, make HTTP and HTTPS requests with WiFiClient and WiFiSSLClient, publish MQTT messages, and serve a page with WiFiServer. The examples use WiFiNINA boards such as the MKR WiFi 1010 or Nano 33 IoT. The ideas apply to other boards, but class names and certificate tools differ.
A board on your network is a small computer that other people can reach. It usually has no screen, no login prompt, and no automatic updates. Securing it means deciding who can talk to it, what it will accept, and what happens if someone gets a copy of its code.
Threats a hobby device actually faces
Most attacks on small devices are opportunistic, so focus on the likely ones.
| Threat | Example | Main defense |
|---|---|---|
| Leaked secrets | Wi-Fi password pushed to a public repository | Separate secrets file, `.gitignore`, rotation |
| Eavesdropping | Reading an API key from plain HTTP or MQTT traffic | TLS on port 443 or 8883 |
| Unauthorized control | Anyone on the LAN opens `/led/on` | Authentication, network segmentation |
| Malformed input | Very long request line exhausts memory | Length and count limits, validation |
| Exposure to the internet | Router forwards port 80 to the board | Do not port-forward; use outbound connections |
| Stale firmware | Known bug in the Wi-Fi module firmware | Update the module firmware and libraries |
Keep secrets out of the sketch and out of Git
You already store credentials in arduino_secrets.h. That only helps if the file never reaches version control. Add it to .gitignore before the first commit:
arduino_secrets.hThen commit a template that has the same names and harmless values, so other people know what to fill in. Name it arduino_secrets.h.example:
#define SECRET_SSID "your-network-name"
#define SECRET_PASS "your-password"
#define SECRET_MQTT_USER "your-mqtt-user"
#define SECRET_MQTT_PASS "your-mqtt-password"
#define SECRET_API_TOKEN "a-long-random-string"Keep these points in mind:
- Ignoring a file does not remove it from history. If you committed
arduino_secrets.honce, the password stays in earlier commits. Change the password, then clean the history if the repository is public. - Secrets are compiled into the firmware. Anyone who can read the board's flash, or who has the compiled
.binor.elffile, can extract them. Treat a lost or sold board as a compromised credential. - Use one credential per device and per purpose. A separate MQTT user for each board lets you revoke one device without touching the others.
- Generate tokens with a password manager or
openssl rand -hex 24. Do not invent them by hand.
Encrypt traffic with TLS
Plain HTTP and plain MQTT on port 1883 send everything in readable form. Anyone on the same Wi-Fi network, or on the path to the server, can read API keys and sensor data and can alter messages in transit.
TLS (Transport Layer Security) fixes both problems. It encrypts the connection, and it lets the client check that the server holds a certificate issued by an authority the client trusts. With WiFiNINA, WiFiSSLClient performs this check inside the Wi-Fi module. The module can only validate a server whose root certificate is in its certificate store. If it is missing, client.connect() returns 0. This is a safe failure: the board refuses to talk to a server it cannot verify.
When a TLS connection fails, check these causes in order:
- The root certificate for that site is not installed. Use the IDE's Firmware Updater tool to add it to the module.
- The module firmware is old. Update it with the same tool.
- The board's clock is wrong. Certificates have validity dates, and the module normally gets the time from the network.
- The server needs a protocol or cipher the module does not support. Test the server from a desktop with
openssl s_client -connect host:443.
Do not disable verification to make an error go away. A TLS connection that accepts any certificate is encrypted but not authenticated, so anyone able to intercept the connection can impersonate the server.
MQTT over TLS with credentials
MQTT brokers usually offer an encrypted listener on port 8883. Pairing it with a username and password gives you both confidentiality and access control. The only code change is the client class, the port, and the credentials:
#include <WiFiNINA.h>
#include <ArduinoMqttClient.h>
#include "arduino_secrets.h"
WiFiSSLClient wifiClient;
MqttClient mqttClient(wifiClient);
const char broker[] = "broker.example.com";
const int port = 8883;
const char topic[] = "demo/uptime";
unsigned long lastSend = 0;
void setup() {
Serial.begin(115200);
while (!Serial && millis() < 5000) {}
while (WiFi.begin(SECRET_SSID, SECRET_PASS) != WL_CONNECTED) {
delay(5000);
}
mqttClient.setUsernamePassword(SECRET_MQTT_USER, SECRET_MQTT_PASS);
if (!mqttClient.connect(broker, port)) {
Serial.print("MQTT connection failed, error ");
Serial.println(mqttClient.connectError());
while (true) {}
}
}
void loop() {
mqttClient.poll();
if (millis() - lastSend >= 5000) {
lastSend = millis();
mqttClient.beginMessage(topic);
mqttClient.print(millis() / 1000);
mqttClient.endMessage();
}
}On the broker side, give this user permission to publish only to demo/# or to its own topic prefix. If the board is compromised, the attacker then cannot read or write other devices' topics.
Decide what the web server should allow
The WiFiServer example from the earlier chapter answers anyone who can reach port 80. That is acceptable for a read-only uptime page on a home network. It is not acceptable once a request can change something, such as switching a relay.
Three rules keep a board-hosted page safe enough for a trusted network:
- Never forward a port from your router to the board. A forwarded port makes the board visible to internet-wide scanners within hours. If you need remote access, have the board make outbound connections to a service, such as an MQTT broker over TLS, and talk to that instead.
- Require a secret for any request that changes state. Without HTTPS the secret travels in readable form on your LAN, so this only stops casual or accidental use. It does not stop someone who can sniff your network.
- Bound everything you read. The board has a few kilobytes of RAM. A client that sends an endless header line should be cut off, not buffered.
The next sketch applies those rules. It reads the request line and at most 20 header lines, rejects any line longer than 120 characters, and requires an X-Token header before it changes the LED.
#include <WiFiNINA.h>
#include "arduino_secrets.h"
WiFiServer server(80);
const size_t MAX_LINE = 120;
const int MAX_HEADERS = 20;
void reply(WiFiClient &client, int code, const char *reason, const char *body) {
client.print("HTTP/1.1 ");
client.print(code);
client.print(" ");
client.println(reason);
client.println("Content-Type: text/plain");
client.println("Connection: close");
client.println();
client.println(body);
}
void handleClient(WiFiClient &client) {
String requestLine = client.readStringUntil('\n');
requestLine.trim();
if (requestLine.length() == 0 || requestLine.length() > MAX_LINE) {
reply(client, 400, "Bad Request", "Bad request");
return;
}
bool authorized = false;
for (int i = 0; i < MAX_HEADERS; i++) {
String line = client.readStringUntil('\n');
line.trim();
if (line.length() == 0) break;
if (line.length() > MAX_LINE) {
reply(client, 400, "Bad Request", "Header too long");
return;
}
if (line.startsWith("X-Token: ") && line.substring(9) == SECRET_API_TOKEN) {
authorized = true;
}
}
if (requestLine.startsWith("GET /status ")) {
reply(client, 200, "OK", "ok");
} else if (requestLine.startsWith("GET /led/on ") ||
requestLine.startsWith("GET /led/off ")) {
if (!authorized) {
reply(client, 401, "Unauthorized", "Token required");
return;
}
digitalWrite(LED_BUILTIN, requestLine.startsWith("GET /led/on ") ? HIGH : LOW);
reply(client, 200, "OK", "done");
} else {
reply(client, 404, "Not Found", "Not found");
}
}
void setup() {
Serial.begin(115200);
while (!Serial && millis() < 5000) {}
pinMode(LED_BUILTIN, OUTPUT);
while (WiFi.begin(SECRET_SSID, SECRET_PASS) != WL_CONNECTED) {
delay(5000);
}
server.begin();
Serial.print("Listening on ");
Serial.println(WiFi.localIP());
}
void loop() {
WiFiClient client = server.available();
if (!client) return;
handleClient(client);
client.stop();
}You can test it from a computer on the same network:
curl -i http://192.168.1.50/led/on
curl -i -H "X-Token: a-long-random-string" http://192.168.1.50/led/onThe first call returns 401 Unauthorized. The second switches the LED on. Replace the address and token with your own values.
Two details matter here. The code matches fixed routes and never builds file paths or commands from request text, so there is nothing for an attacker to inject into. The readStringUntil calls also stop after the default one-second timeout, so a client that stalls cannot hold the board for long. The server is still single-threaded, so one slow client delays all others. That is a reliability limit, not only a security one.
Reduce exposure at the network level
Some of the best protection is outside the sketch:
- Use WPA2 or WPA3 on the Wi-Fi network, with a long passphrase. An open or WEP network offers no confidentiality at all.
- Put IoT devices on a guest network or a separate VLAN if your router supports it. A compromised board then cannot reach your computers or file shares.
- Give the board a DHCP reservation so its address stays stable. Then firewall rules and bookmarks stay correct.
- Block inbound traffic to the board at the router, and allow only the outbound connections it needs.
Keep firmware and libraries current
A WiFiNINA board runs two programs: your sketch on the main processor, and the NINA firmware on the Wi-Fi module. Security fixes for TLS and the network stack live in the module firmware and the root certificate list. Check for updates with the IDE's Firmware Updater tool when you set up a project and again every few months. Update the WiFiNINA and ArduinoMqttClient libraries through the Library Manager, and read release notes before updating a deployed device.
Also review what the device logs over Serial. Debug output that prints the password, token, or full request is a leak if someone connects a USB cable.
Checklist before you deploy
arduino_secrets.his ignored by Git, and no earlier commit contains real values.- Every connection that carries a credential or private data uses TLS.
- The board has its own broker user, limited to its own topics.
- Any request that changes state needs a token, and input length is bounded.
- No router port is forwarded to the board.
- Module firmware, root certificates, and libraries are up to date.
Exercise
Your WiFiSSLClient.connect("api.example.org", 443) call returns 0, but the same URL works in a desktop browser. Name two likely causes on the board and the tool you would use to address them. Why is switching back to plain WiFiClient on port 80 a poor fix?
Show answer
Likely causes are that the module's certificate store lacks the root certificate for that site, or that the module firmware is outdated. A wrong clock is a third possibility. Use the IDE's Firmware Updater tool to update the firmware and upload the site's root certificate. Switching to plain HTTP removes encryption and server verification, so credentials and data become readable and modifiable on the network.
Exercise
You committed arduino_secrets.h with your real Wi-Fi password in a public repository, then added the file to .gitignore. Is the password now safe? List the steps you should take.
Show answer
No. .gitignore only affects files that are not yet tracked, and the password remains in earlier commits. Change the Wi-Fi password first. Then remove the file from tracking with git rm --cached arduino_secrets.h. Rewrite the history if you need it clean. Update the local arduino_secrets.h with the new password and commit a placeholder arduino_secrets.h.example.