Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
name: Build

on:
push:
branches: [main]
pull_request:

permissions:
contents: read

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7

- uses: actions/setup-python@v7
with:
python-version: "3.13"

- uses: actions/cache@v6
with:
path: ~/.platformio
key: pio-${{ hashFiles('platformio.ini') }}

- name: Install PlatformIO
run: pip install platformio

- name: Build
run: pio run

- uses: actions/upload-artifact@v7
with:
name: firmware-dev
path: .pio/build/SpaceStateSwitch/firmware.bin
92 changes: 92 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
# Builds, signs and publishes firmware when a version tag (e.g. v1.2.3) is pushed.
# Devices install the newest release's firmware.bin automatically on boot.
name: Release

on:
push:
tags: ["v*"]

permissions:
contents: write # Create the GitHub release

jobs:
release:
runs-on: ubuntu-latest
environment: release # Optional: add required reviewers to gate signing
env:
TAG: ${{ github.ref_name }}
steps:
- name: Validate tag
run: |
if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "::error::Release tags must look like v1.2.3 (got '$TAG')"
exit 1
fi

- uses: actions/checkout@v7
with:
fetch-depth: 0 # Needed to find the previous release's public key

- name: Check signing setup
env:
OTA_SIGNING_KEY: ${{ secrets.OTA_SIGNING_KEY }}
run: |
if [[ ! -s keys/ota_signing_key.pub.pem ]]; then
echo "::error::keys/ota_signing_key.pub.pem is empty, run scripts/generate-ota-signing-key.sh (see README)"
exit 1
fi
if [[ -z "$OTA_SIGNING_KEY" ]]; then
echo "::error::The OTA_SIGNING_KEY secret is not set (see README)"
exit 1
fi

- uses: actions/setup-python@v7
with:
python-version: "3.13"

- uses: actions/cache@v6
with:
path: ~/.platformio
key: pio-${{ hashFiles('platformio.ini') }}

- name: Install tools
run: pip install platformio cryptography

- name: Build
run: FIRMWARE_VERSION="$TAG" pio run

- name: Sign
env:
OTA_SIGNING_KEY: ${{ secrets.OTA_SIGNING_KEY }}
run: |
set -euo pipefail
signer=~/.platformio/packages/framework-arduinoespressif32/tools/bin_signing.py
key="$RUNNER_TEMP/ota_signing_key.pem"
trap 'rm -f "$key"' EXIT
(umask 077 && printf '%s\n' "$OTA_SIGNING_KEY" > "$key")

mkdir -p dist
python "$signer" --bin .pio/build/SpaceStateSwitch/firmware.bin --key "$key" --out dist/firmware.bin

# Make sure devices will accept it. Devices check against the key in the firmware
# they're running, i.e. the previous release's key (which differs during rotation).
trusted_key="$RUNNER_TEMP/trusted_key.pub.pem"
previous_tag=$(git describe --tags --abbrev=0 --match 'v*' "$TAG^" 2>/dev/null || true)
if [[ -n "$previous_tag" ]] && git show "$previous_tag:keys/ota_signing_key.pub.pem" > "$trusted_key" 2>/dev/null && [[ -s "$trusted_key" ]]; then
echo "Verifying against the public key of $previous_tag"
else
echo "Verifying against the committed public key"
cp keys/ota_signing_key.pub.pem "$trusted_key"
fi
python "$signer" --verify dist/firmware.bin --pubkey "$trusted_key" | tee verify.log
grep -q "SUCCESSFUL" verify.log

# The device checks the signed image really contains this version.
grep -qaF $'\x1f'"SSS-FW-VERSION:${TAG#v}"$'\x1f' dist/firmware.bin

(cd dist && sha256sum firmware.bin > firmware.bin.sha256)

- name: Publish release
env:
GH_TOKEN: ${{ github.token }}
run: gh release create "$TAG" dist/firmware.bin dist/firmware.bin.sha256 --verify-tag --generate-notes --title "$TAG"
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,7 @@
.vscode/launch.json
.vscode/ipch
/src/Secrets.h

# OTA signing private keys must never be committed (the public key in keys/ is fine)
*.pem
!keys/*.pub.pem
112 changes: 111 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,113 @@
# SpaceStateSwitch

This contains the code of the Arduino of the SpaceState Switch at the hackerspace. Code created by DiverAlpha, referencing the old code of royvandongen.
Firmware for the space state switch at Pixelbar. It runs on an ESP32 (Wemos D1 Mini32). It reads the physical switch and publishes the state to [spacestate.pixelbar.nl](https://spacestate.pixelbar.nl), to MQTT (with Home Assistant discovery) and to a small local JSON API. On every boot it checks GitHub for a newer release and installs it over the air.

Code created by DiverAlpha, referencing the old code of royvandongen.

## Behaviour

| LED colour | Meaning |
| --- | --- |
| Green | Space is open |
| Red | Space is closed |
| Blue | Not connected to WiFi |
| Purple (blinking) | Installing a firmware update |

- If the switch changes, the new state is sent to the [space state API](https://pixelbar.nl/spacestate/) (`POST /api/v1/state`). Network and server errors are retried every 10 seconds; a rejected API key is logged and not retried.
- Every 10 minutes the online state is fetched. If someone changed the state on the website, that override is shown until the switch is flipped again.
- **Double press reset** to open the config portal. It runs as WiFi network `space-state-switch` with password `1337hacker` and closes after 2 minutes. In the portal you set the WiFi network, the MQTT broker and the space state API key (an API key with the `write` role) and user. Password and API key fields start empty; leave them empty to keep the stored value.

### HTTP API

`http://space-state-switch.local/`

- `GET /`: current state (`is_open`, `state`, `is_overwritten`, `physical_state`)
- `GET /info`: device, network and firmware info
- `GET /heap`: memory usage

### MQTT

- `space-state-switch/state`: `1` (open) or `0` (closed), retained and re-published every 5 minutes
- `space-state-switch/LWT`: `online` / `offline`
- Home Assistant discovery on `homeassistant/binary_sensor/space-state-switch/config`

## Building

This uses [PlatformIO](https://platformio.org) with the [pioarduino](https://github.com/pioarduino/platform-espressif32) platform (Arduino-ESP32 3.x / ESP-IDF 5.x).

```sh
pio run # build
pio run -t upload # flash over USB
pio device monitor # serial logs
```

Local builds report version `dev` and **never update themselves**, so a build you flashed by hand won't be replaced by the latest release. To put a device back on automatic updates, flash a release build (see below), for example by building it locally with `FIRMWARE_VERSION=v1.2.3 pio run -t upload`.

### Migrating from the old firmware

The partition table changed to make room for two OTA slots, and partition tables can't be changed over the air. Flash the first version of this firmware **over USB** with `pio run -t upload`. WiFi and MQTT settings are kept.

Space state credentials are no longer compiled in. Enter them in the config portal, or put them in `src/Secrets.h` (see `src/Secrets_example.h`) for that first USB flash. They are then stored on the device.

The switch uses the new space state API with a Bearer API key, not the legacy `togglestate.php` token. A device that already has a legacy token stored still needs an API key with the `write` role: ask a spacestate maintainer for one and enter it in the config portal. The stored user is kept.

## OTA updates

On boot, after connecting to WiFi, the device:

1. Fetches `https://api.github.com/repos/pixelbar/SpaceStateSwitch/releases/latest`.
2. Stops if the release tag (`vX.Y.Z`) isn't newer than the running version.
3. Streams the release's `firmware.bin` into the inactive OTA partition.
4. Checks the image's ECDSA signature and checks that the signed image contains the version the tag claims. If either check fails, the update is thrown away and the current firmware keeps running.
5. Reboots into the new firmware. If the new firmware doesn't get as far as connecting to WiFi (it crashes, or the config portal times out), the bootloader rolls back to the previous version.

### Security model

- **Transport:** every connection uses TLS. Certificates are checked against the Mozilla CA bundle that ships with ESP-IDF.
- **Authenticity:** TLS only proves the bytes came from GitHub. Devices also require a signature from the project's private key. Someone who gets into the GitHub repository or the release assets still can't install their own firmware without that key.
- **No downgrades:** only strictly newer versions are installed. The version is checked against a marker inside the signed image, so an older signed image can't be re-uploaded under a newer tag.
- **No secrets in firmware:** release binaries are public, so credentials live in the device's NVS, not in the binary.

### One-time setup

1. Generate the signing key pair:

```sh
scripts/generate-ota-signing-key.sh
```

This writes `keys/ota_signing_key.pub.pem` (commit it) and `ota_signing_key.pem` (private, git-ignored).

2. Store the private key as a GitHub Actions secret, keep a copy in the space's password manager, then delete the local file:

```sh
gh secret set OTA_SIGNING_KEY < ota_signing_key.pem
rm ota_signing_key.pem
```

3. Commit the public key. Flash a release build to the device over USB once, because the device needs firmware that contains the public key.

Until a public key is committed, OTA is disabled and the release workflow fails rather than publishing unsigned firmware.

### Releasing

```sh
git tag v1.2.3
git push origin v1.2.3
```

The [release workflow](.github/workflows/release.yml) builds with that version, signs the binary, checks the signature against the committed public key, and publishes a GitHub release with `firmware.bin`. Devices pick it up the next time they boot.

The workflow runs in a `release` GitHub environment. Add required reviewers to that environment if you want someone to approve each signing.

### Rotating the signing key

A device only accepts updates signed with the key built into the firmware it's running. To rotate the key:

1. Run `FORCE=1 scripts/generate-ota-signing-key.sh new_key.pem` and commit the new public key.
2. Release a version while `OTA_SIGNING_KEY` still holds the **old** private key. Devices accept it because it's signed with the key they trust, and it contains the new public key.
3. Once devices have updated, set `OTA_SIGNING_KEY` to the new private key (`gh secret set OTA_SIGNING_KEY < new_key.pem`).

The release workflow checks each release against the public key of the *previous* release, which is the key devices actually trust, so it catches a key that was swapped too early. Devices still on firmware older than the rotation release will reject new releases and have to be updated over USB.

If the private key is lost, devices have to be re-flashed over USB.
4 changes: 4 additions & 0 deletions keys/ota_signing_key.pub.pem
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE87f8oZKt9QiqJ2AkYkRsnobvhwgy
7NmuewOB2OLLFRRhiCG4MPFWtvIbVZDNXcGxWWSuWv0Zfb6yNW2eEj/wAA==
-----END PUBLIC KEY-----
52 changes: 36 additions & 16 deletions platformio.ini
Original file line number Diff line number Diff line change
@@ -1,24 +1,44 @@
; PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html

[platformio]
default_envs = SpaceStateSwitch

[env:SpaceStateSwitch]
platform = espressif32
; The official PlatformIO espressif32 platform is stuck on Arduino-ESP32 2.x.
; pioarduino is the community-maintained platform that tracks the current
; Arduino-ESP32 3.x releases (ESP-IDF 5.x). Pinned for reproducible builds.
platform = https://github.com/pioarduino/platform-espressif32/releases/download/55.03.312-1/platform-espressif32.zip
board = wemos_d1_mini32
framework = arduino

upload_speed = 921600
monitor_speed = 115200
lib_deps =
me-no-dev/AsyncTCP@1.1.1
https://github.com/me-no-dev/ESPAsyncWebServer.git#f71e3d4
https://github.com/tzapu/WiFiManager.git#88c378f
bblanchon/ArduinoJson@^6.19.4
adafruit/Adafruit NeoPixel@^1.10.5
knolleary/PubSubClient@^2.8
khoih-prog/ESP_DoubleResetDetector@^1.3.2
monitor_filters = esp32_exception_decoder

; Two 1.9MB OTA app slots (the default table only has 1.25MB slots, which is
; too tight for an Arduino 3.x + TLS build). NVS lives at the same offset as in
; the default table, so WiFi / MQTT settings survive the switch.
; NOTE: partition tables cannot be changed over OTA, the first flash after this
; change must be done over USB.
board_build.partitions = min_spiffs.csv

; Public key used to verify OTA firmware signatures. See README.md.
board_build.embed_txtfiles = keys/ota_signing_key.pub.pem

; Sets FIRMWARE_VERSION from the FIRMWARE_VERSION environment variable (CI) or
; "dev" for local builds.
extra_scripts = pre:scripts/firmware_version.py

build_flags =
-DUPDATE_SIGN ; Enable signature verification in the Update library
-DCORE_DEBUG_LEVEL=3 ; Info level logging (log_i / log_w / log_e)
build_src_flags =
-Wall -Wextra

lib_deps =
esp32async/AsyncTCP@^3.5.0
esp32async/ESPAsyncWebServer@^3.12.1
tzapu/WiFiManager@^2.0.17
bblanchon/ArduinoJson@^7.4.3
adafruit/Adafruit NeoPixel@^1.15.5
20 changes: 20 additions & 0 deletions scripts/firmware_version.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# PlatformIO pre-build script: injects FIRMWARE_VERSION into the build.
#
# CI sets the FIRMWARE_VERSION environment variable from the release tag
# (e.g. "1.2.3"). Local builds default to "dev", which disables OTA updates
# so a development build flashed over USB is not immediately replaced by the
# latest release.
import os

Import("env") # noqa: F821 - provided by PlatformIO/SCons

version = os.environ.get("FIRMWARE_VERSION", "").strip() or "dev"
if version.startswith("v"):
version = version[1:]

print(f"Firmware version: {version}")
env.Append(CPPDEFINES=[("FIRMWARE_VERSION", env.StringifyMacro(version))]) # noqa: F821

# Development-only features (e.g. serial commands that simulate the switch).
if version == "dev":
env.Append(CPPDEFINES=["DEV_BUILD"]) # noqa: F821
38 changes: 38 additions & 0 deletions scripts/generate-ota-signing-key.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#!/usr/bin/env bash
# Generates the ECDSA P-256 key pair used to sign OTA firmware updates.
#
# scripts/generate-ota-signing-key.sh [private-key-path]
#
# Writes the public key to keys/ota_signing_key.pub.pem (commit this) and the
# private key to the given path (default: ./ota_signing_key.pem, git-ignored).
# Store the private key as the OTA_SIGNING_KEY GitHub Actions secret and in a
# password manager, then delete the local copy. See README.md.
set -euo pipefail

cd "$(dirname "$0")/.."
private_key="${1:-ota_signing_key.pem}"
public_key="keys/ota_signing_key.pub.pem"

if [[ -e "$private_key" ]]; then
echo "error: $private_key already exists" >&2
exit 1
fi
if [[ -s "$public_key" && "${FORCE:-}" != "1" ]]; then
cat >&2 <<MSG
error: $public_key already contains a key.
Devices only accept updates signed with the key compiled into their current
firmware, so replacing it will cut them off from future updates unless you first
ship a release (signed with the old key) that contains the new public key.
Re-run with FORCE=1 if you really want to replace it.
MSG
exit 1
fi

umask 077
openssl ecparam -name prime256v1 -genkey -noout -out "$private_key"
openssl ec -in "$private_key" -pubout -out "$public_key" 2>/dev/null

echo "Private key: $private_key (keep secret, do NOT commit)"
echo "Public key: $public_key (commit this)"
echo
echo "Next: gh secret set OTA_SIGNING_KEY < \"$private_key\""
Loading
Loading