diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 45779248..5776c517 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -89,12 +89,27 @@ jobs: key: deck-panel-pio-6.2.0-${{ hashFiles('tools/deck-panel/platformio.ini') }} - name: PlatformIO run: pip install platformio==6.2.0 + # The host tests check release signatures and image hashes with the system libsodium (#690); the board links the + # copy in the ESP32 libs. Two builds of one library: the shared RFC 8032 and CryptoKit vectors tie them together. + # Same guard as the Arm toolchain (#640): a stalled transfer gives up after 30 s, an attempt over 2 minutes is cut + # off and tried once more, so it can't hang the merge queue. + - name: libsodium + run: | + apt="-o Acquire::http::Timeout=30 -o Acquire::Retries=3" + for attempt in 1 2; do + timeout 120 sudo apt-get $apt update && timeout 120 sudo apt-get $apt install -y --no-install-recommends \ + libsodium-dev && break + [ "$attempt" = 2 ] && exit 1 + echo "libsodium download attempt $attempt failed or stalled; trying once more" + done + echo "libsodium $(dpkg-query -W -f='${Version}' libsodium-dev)" - name: Deck panel host tests run: | pio test -d tools/deck-panel -e native python3 -I tools/deck-panel/test_secret_logs.py python3 -I tools/deck-panel/check_secret_logs.py python3 -I tools/deck-panel/test_deck_logo.py + python3 -I tools/deck-panel/test_release_keys.py python3 -I tools/deck-panel/test_git_sha.py # The panel keeps its Wi-Fi in NVS, set from a phone (#622): nothing to build in. - name: Deck panel firmware build diff --git a/docs/DECK-PANEL-UPDATE-PROTOCOL.md b/docs/DECK-PANEL-UPDATE-PROTOCOL.md new file mode 100644 index 00000000..0a4a05b8 --- /dev/null +++ b/docs/DECK-PANEL-UPDATE-PROTOCOL.md @@ -0,0 +1,79 @@ +# Deck panel update protocol + +How the firmware updater (#691) sends a signed firmware release to a deck panel over Wi-Fi (#690). The signing and +the manifest are ADR 0012's; this is the wire between the Mac and the panel. The panel's side is +`tools/deck-panel/lib/update_link` and `lib/update_session`, tested in the native env. + +## Connection + +- TCP, port **3310** on the panel. The display feed is UDP; nothing else uses this port. +- **One connection at a time.** A second one gets `refused busy` and is closed; the first carries on. +- The connection is the update: it ends with a switch or a refusal, and the panel closes it. + +## Frames, Mac to panel + +Each frame is one type byte, a 4-byte **little-endian** length, then that many bytes. + +| Type | Payload | Cap (checked from the header, before a byte is kept) | +|---|---|---| +| `M` | the release's `manifest.json`, its exact bytes | 32 KB | +| `S` | `manifest.sig`: the 64-byte Ed25519 signature over those bytes | exactly 64 | +| `I` | the next piece of the deck panel image | 4 KB | +| `D` | done: the image is all sent | 0 | + +The order is always `M`, `S`, then `I`... and `D`. Any other order, an unknown type or a frame over its cap is +refused, and the connection is closed. + +## Lines, panel to Mac + +One text line per step, ending in `\n`: + +| Line | When | +|---|---| +| `ok manifest` | the signature checked out and every rule passed; the panel has erased the image's size in its spare slot | +| `progress ` | after each `I` frame: image bytes taken so far | +| `ok switched ` | after `D`: size and SHA-256 match, the new image is set to boot. The panel then closes the connection and restarts into it | +| `refused ` | anything else, then the panel closes the connection. The old firmware keeps running | + +Reasons: `busy`, `no-manifest`, `too-large`, `unreadable`, `unknown-key`, `bad-signature`, `unknown-format`, +`no-image`, `too-old`, `too-big`, `mismatch`, `timeout`, `slot-error`. + +## What the panel checks, in order + +1. **Nothing touches flash before the signature.** Until `S` checks out, the only thing read from the manifest is + the name of the key that signed it. +2. **Signature:** the key the manifest names must be one the panel trusts (`lib/release_keys`, the same list as the + app's `ReleaseKeys.swift`; empty until the owner makes the keys, so every update is `unknown-key` until then). + The signature is checked over the manifest's exact bytes. +3. **Rules:** + - `format` must be 1. + - There must be a `deck-panel` file. + - Its version must not be below the panel's **floor** or the manifest's `lowest_allowed`. The floor is kept in + the panel's NVS and only ever raised: to the manifest's `lowest_allowed`, once the new image has confirmed + itself. So a validly signed older image can't be sent back after a security fix. + - It must fit the spare slot. +4. **Image:** + - It is hashed as it arrives. + - More bytes than the manifest's size are refused at the first extra byte. + - At `D`, the size and SHA-256 must equal the manifest's, or the update is `mismatch` and the slot is never booted. +5. **After the switch:** + - The new image boots as a trial. + - It confirms itself once what recovery needs is up, within 120 s: its saved Wi-Fi joined, or, with no saved + Wi-Fi, its setup network up. The update server must be listening too. + - If that doesn't happen, the panel restarts into the previous image. + - The display feed is not asked for, so an update with DeckBridge closed doesn't roll a good image back. + +## Timeouts and a dropped link + +- **Before the signature has checked out:** 3 s with nothing received ends the connection (`refused timeout`). A + stray connection can't hold `busy`. +- **Mid-image:** 10 s with nothing received ends it. +- **The connection closing before `ok switched`:** nothing is switched. The bytes written so far are dropped and the + old firmware keeps running. Power loss mid-transfer is the same: the boot slot was never changed. + +## Open points for #691 + +- **Finding the panel.** Today the panel's address is shown on its waiting screen, so the app can take it typed in. + Later: an mDNS name or a UDP answer to a broadcast. +- **What the app shows during the update:** the panel shows a still "Updating" screen while it writes flash, + because flash writes make the picture tear. diff --git a/scripts/ci_changes.py b/scripts/ci_changes.py index 7934c652..fea766cd 100644 --- a/scripts/ci_changes.py +++ b/scripts/ci_changes.py @@ -30,7 +30,9 @@ "tools/lc6000-display-fw/arm/upper_header.py"] # What the Deck panel job (#615) builds and tests, and CI itself, so a change to the job runs it. The icon SVG the # panel's logo is made from (#651), whose drift test the job runs (#669). -DECK_PANEL = ["tools/deck-panel/*", ".github/workflows/ci.yml", "design/icon/icon-1-deck-ring.svg"] +# The app's release keys, which the panel must trust too (#690). +DECK_PANEL = ["tools/deck-panel/*", ".github/workflows/ci.yml", "design/icon/icon-1-deck-ring.svg", + "Packages/FirmwareUpdaterKit/Sources/FirmwareRelease/ReleaseKeys.swift"] def site_only(path): diff --git a/scripts/test_ci_changes.py b/scripts/test_ci_changes.py index 5dd41b86..0d37a968 100644 --- a/scripts/test_ci_changes.py +++ b/scripts/test_ci_changes.py @@ -96,6 +96,10 @@ def test_the_icon_svg_the_logo_is_made_from_runs_it(self): self.assertTrue(ci_changes.needs_deck_panel(["design/icon/icon-1-deck-ring.svg"])) self.assertFalse(ci_changes.needs_deck_panel(["design/icon/menubar-deck-ring-16.svg"])) + def test_the_app_release_keys_run_it(self): + # the panel must trust the same keys (#690); test_release_keys.py, run by the Deck panel job, compares them + self.assertTrue(ci_changes.needs_deck_panel(["Packages/FirmwareUpdaterKit/Sources/FirmwareRelease/ReleaseKeys.swift"])) + def test_a_change_to_the_ci_workflow_runs_it(self): self.assertTrue(ci_changes.needs_deck_panel([".github/workflows/ci.yml"])) diff --git a/tools/deck-panel/lib/release_check/release_check.cpp b/tools/deck-panel/lib/release_check/release_check.cpp new file mode 100644 index 00000000..ca19397e --- /dev/null +++ b/tools/deck-panel/lib/release_check/release_check.cpp @@ -0,0 +1,27 @@ +#include "release_check.h" + +#include + +namespace release_check { + +bool signature_ok(const uint8_t public_key[32], const uint8_t* message, size_t length, const uint8_t signature[64]) { + // sodium_init is safe to call again and returns 1 once it has run; -1 means libsodium can't be used. + if (sodium_init() < 0) return false; + static const uint8_t empty = 0; + return crypto_sign_verify_detached(signature, message ? message : &empty, length, public_key) == 0; +} + +Sha256::Sha256() : state_() { start(); } + +void Sha256::start() { + // libsodium asks for sodium_init before any call; SHA-256 has no setup that can fail, so its result doesn't matter here. + const int ready = sodium_init(); + (void)ready; + crypto_hash_sha256_init(&state_); +} + +void Sha256::update(const uint8_t* data, size_t length) { crypto_hash_sha256_update(&state_, data, length); } + +void Sha256::finish(uint8_t out[32]) { crypto_hash_sha256_final(&state_, out); } + +} // namespace release_check diff --git a/tools/deck-panel/lib/release_check/release_check.h b/tools/deck-panel/lib/release_check/release_check.h new file mode 100644 index 00000000..809e8a86 --- /dev/null +++ b/tools/deck-panel/lib/release_check/release_check.h @@ -0,0 +1,28 @@ +// Checks a signed firmware release on the panel (#690, ADR 0012): the Ed25519 signature over the manifest's exact bytes. +#pragma once + +#include +#include + +#include + +#include "update_session.h" + +namespace release_check { + +/// Whether `signature` is `public_key`'s Ed25519 signature (RFC 8032) over exactly `message`. +bool signature_ok(const uint8_t public_key[32], const uint8_t* message, size_t length, const uint8_t signature[64]); + +/// SHA-256 (FIPS 180-4) of an image that arrives in chunks: the session's hasher on the panel and in native tests. +class Sha256 : public update_session::Hasher { + public: + Sha256(); + void start() override; + void update(const uint8_t* data, size_t length) override; + void finish(uint8_t out[32]) override; + + private: + crypto_hash_sha256_state state_; +}; + +} // namespace release_check diff --git a/tools/deck-panel/lib/release_keys/release_keys.cpp b/tools/deck-panel/lib/release_keys/release_keys.cpp new file mode 100644 index 00000000..6bc63e62 --- /dev/null +++ b/tools/deck-panel/lib/release_keys/release_keys.cpp @@ -0,0 +1,32 @@ +#include "release_keys.h" + +#include + +namespace release_keys { +namespace { + +int nibble(char c) { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + return -1; +} + +} // namespace + +size_t trusted(const Listed* list, update_session::TrustedKey* out, size_t max) { + size_t n = 0; + for (const Listed* entry = list; entry->id && n < max; ++entry) { + if (std::strlen(entry->hex) != 64) continue; + update_session::TrustedKey key{entry->id, {}}; + bool ok = true; + for (size_t i = 0; i < 32 && ok; ++i) { + const int hi = nibble(entry->hex[2 * i]), lo = nibble(entry->hex[2 * i + 1]); + ok = hi >= 0 && lo >= 0; + key.public_key[i] = static_cast(hi * 16 + lo); + } + if (ok) out[n++] = key; + } + return n; +} + +} // namespace release_keys diff --git a/tools/deck-panel/lib/release_keys/release_keys.h b/tools/deck-panel/lib/release_keys/release_keys.h new file mode 100644 index 00000000..cce91fde --- /dev/null +++ b/tools/deck-panel/lib/release_keys/release_keys.h @@ -0,0 +1,29 @@ +// The release keys the panel trusts (#690, ADR 0012): the maintainer's primary key and the offline backup key, the +// same pairs as the updater app's ReleaseKeys.swift (test_release_keys.py checks they match). +// +// The owner made them on 2026-11-23 (#689, docs/FIRMWARE-RELEASE-SIGNING.md). Public halves only. +#pragma once + +#include + +#include "update_session.h" + +namespace release_keys { + +struct Listed { + const char* id; + const char* hex; ///< the public key as 64 hex characters, as `firmware-release public-key` prints it +}; + +// Each entry: {"primary", "<64 hex>"}, then {"backup", "<64 hex>"}. Ends with the {nullptr, nullptr} marker. +constexpr Listed kListed[] = { + {"primary", "26739c2c075965fd9a99330f97c3b09a28d11f85c1fa4d81bd5495cb67c1a5f8"}, + {"backup", "2e972a79fd40b287a151166dcdc723d07e84afe9ffc933fb211c670873c07cbe"}, + {nullptr, nullptr}, +}; + +/// The keys in `list` (ending with the {nullptr, nullptr} marker) as the update session takes them: up to `max` into +/// `out`, leaving out any that isn't 64 lowercase hex characters. Returns how many. +size_t trusted(const Listed* list, update_session::TrustedKey* out, size_t max); + +} // namespace release_keys diff --git a/tools/deck-panel/lib/update_boot/update_boot.cpp b/tools/deck-panel/lib/update_boot/update_boot.cpp new file mode 100644 index 00000000..5491d954 --- /dev/null +++ b/tools/deck-panel/lib/update_boot/update_boot.cpp @@ -0,0 +1,12 @@ +#include "update_boot.h" + +namespace update_boot { + +Decision decide(const State& s) { + if (!s.trial) return Decision::nothing; + const bool network = s.saved_wifi ? s.wifi_joined : s.setup_network_up; + if (network && s.update_listening) return Decision::confirm; + return s.since_boot_ms >= kTrialMs ? Decision::roll_back : Decision::wait; +} + +} // namespace update_boot diff --git a/tools/deck-panel/lib/update_boot/update_boot.h b/tools/deck-panel/lib/update_boot/update_boot.h new file mode 100644 index 00000000..aab1f946 --- /dev/null +++ b/tools/deck-panel/lib/update_boot/update_boot.h @@ -0,0 +1,28 @@ +// Whether a newly switched-to image confirms itself (#690). It boots as a trial (ESP-IDF rollback); it confirms only +// once it has brought up what recovery needs, so a bad release can always be replaced over Wi-Fi: +// - with saved Wi-Fi: joined, and the update server listening; +// - with none (setup mode, #622): the setup network up, and the update server listening on it. +// Not the display feed: a panel updated with DeckBridge closed would otherwise roll a good image back every time. +// If that isn't reached within kTrialMs, the panel restarts into the previous image. +#pragma once + +#include + +namespace update_boot { + +constexpr uint32_t kTrialMs = 120000; + +struct State { + bool trial = false; ///< this image runs as a trial: switched to, not yet confirmed + bool saved_wifi = false; + bool wifi_joined = false; + bool setup_network_up = false; + bool update_listening = false; + uint32_t since_boot_ms = 0; +}; + +enum class Decision { nothing, wait, confirm, roll_back }; + +Decision decide(const State& state); + +} // namespace update_boot diff --git a/tools/deck-panel/lib/update_floor/update_floor.cpp b/tools/deck-panel/lib/update_floor/update_floor.cpp new file mode 100644 index 00000000..d68dc7a3 --- /dev/null +++ b/tools/deck-panel/lib/update_floor/update_floor.cpp @@ -0,0 +1,12 @@ +#include "update_floor.h" + +#include "update_session.h" + +namespace update_floor { + +std::string raised(const std::string& current, const std::string& pending) { + if (!update_session::is_version(pending) || update_session::below(pending, current)) return current; + return pending; +} + +} // namespace update_floor diff --git a/tools/deck-panel/lib/update_floor/update_floor.h b/tools/deck-panel/lib/update_floor/update_floor.h new file mode 100644 index 00000000..e2506628 --- /dev/null +++ b/tools/deck-panel/lib/update_floor/update_floor.h @@ -0,0 +1,13 @@ +// The panel's floor (#690, docs/DECK-PANEL-UPDATE-PROTOCOL.md): the lowest version it takes over Wi-Fi. The board keeps +// it in NVS; this says what to keep when a new image confirms itself with the floor its manifest asked for. +#pragma once + +#include + +namespace update_floor { + +/// The floor to keep: `pending` when it is a version not below `current`, else `current`. Never lower, and never +/// something that isn't a version (that would count every version below it and refuse every update for good). +std::string raised(const std::string& current, const std::string& pending); + +} // namespace update_floor diff --git a/tools/deck-panel/lib/update_link/update_link.cpp b/tools/deck-panel/lib/update_link/update_link.cpp new file mode 100644 index 00000000..41eef736 --- /dev/null +++ b/tools/deck-panel/lib/update_link/update_link.cpp @@ -0,0 +1,125 @@ +#include "update_link.h" + +#include + +namespace update_link { + +using update_session::Refusal; +using update_session::Reply; + +namespace { + +const char* reason(Refusal refusal) { + switch (refusal) { + case Refusal::none: return "none"; + case Refusal::busy: return "busy"; + case Refusal::no_manifest: return "no-manifest"; + case Refusal::too_large: return "too-large"; + case Refusal::unreadable: return "unreadable"; + case Refusal::unknown_key: return "unknown-key"; + case Refusal::bad_signature: return "bad-signature"; + case Refusal::unknown_format: return "unknown-format"; + case Refusal::no_image: return "no-image"; + case Refusal::too_old: return "too-old"; + case Refusal::too_big: return "too-big"; + case Refusal::mismatch: return "mismatch"; + case Refusal::timeout: return "timeout"; + case Refusal::slot_error: return "slot-error"; + } + return "unknown"; +} + +} // namespace + +std::string line(const Reply& reply) { + switch (reply.kind) { + case Reply::ok_manifest: return "ok manifest"; + case Reply::progress: return "progress " + std::to_string(reply.bytes); + case Reply::switched: return "ok switched " + reply.version; + case Reply::refused: return std::string("refused ") + reason(reply.refusal); + case Reply::nothing: break; + } + return ""; +} + +bool Link::accept(int connection, uint32_t now_ms, Out& out) { + if (session_) { + out.lines.push_back("refused busy"); + out.close = true; + return false; + } + connection_ = connection; + last_ms_ = now_ms; + session_.emplace(config_); + header_have_ = 0; + payload_.clear(); + return true; +} + +void Link::finish(Out& out) { + out.close = true; + session_.reset(); + connection_ = -1; +} + +void Link::handle(const Reply& reply, Out& out) { + if (reply.kind == Reply::nothing) return; + out.lines.push_back(line(reply)); + if (reply.kind == Reply::refused) finish(out); + if (reply.kind == Reply::switched) { + out.reboot = true; + out.floor = reply.floor; + finish(out); + } +} + +Out Link::received(int connection, const uint8_t* bytes, size_t length, uint32_t now_ms) { + Out out; + if (connection != connection_ || !session_) return out; + last_ms_ = now_ms; + for (size_t i = 0; i < length && session_;) { + if (header_have_ < 5) { + header_[header_have_++] = bytes[i++]; + if (header_have_ < 5) continue; + payload_want_ = static_cast(header_[1]) | static_cast(header_[2]) << 8 | + static_cast(header_[3]) << 16 | static_cast(header_[4]) << 24; + payload_.clear(); + // Caps from the header alone, before a byte of the payload is kept. + const char type = static_cast(header_[0]); + const bool known = type == 'M' || type == 'S' || type == 'I' || type == 'D'; + if (!known) { handle(session_->stop(Refusal::no_manifest), out); break; } + const bool fits = (type == 'M' && payload_want_ <= kMaxManifest) || (type == 'S' && payload_want_ == 64) || + (type == 'I' && payload_want_ <= kMaxChunk) || (type == 'D' && payload_want_ == 0); + if (!fits) { handle(session_->stop(Refusal::too_large), out); break; } + } + const size_t take = std::min(length - i, static_cast(payload_want_) - payload_.size()); + payload_.insert(payload_.end(), bytes + i, bytes + i + take); + i += take; + if (payload_.size() < payload_want_) continue; + header_have_ = 0; + switch (static_cast(header_[0])) { + case 'M': handle(session_->manifest(payload_.data(), payload_.size()), out); break; + case 'S': handle(session_->signature(payload_.data(), payload_.size()), out); break; + case 'I': handle(session_->chunk(payload_.data(), payload_.size()), out); break; + default: handle(session_->done(), out); break; + } + } + return out; +} + +Out Link::tick(uint32_t now_ms) { + Out out; + if (!session_) return out; + const uint32_t limit = session_->receiving_image() ? kIdleMidImageMs : kIdleBeforeManifestMs; + if (now_ms - last_ms_ >= limit) handle(session_->stop(Refusal::timeout), out); + return out; +} + +void Link::closed(int connection) { + if (connection != connection_ || !session_) return; + session_->stop(Refusal::timeout); + session_.reset(); + connection_ = -1; +} + +} // namespace update_link diff --git a/tools/deck-panel/lib/update_link/update_link.h b/tools/deck-panel/lib/update_link/update_link.h new file mode 100644 index 00000000..fc86a912 --- /dev/null +++ b/tools/deck-panel/lib/update_link/update_link.h @@ -0,0 +1,60 @@ +// The panel's side of the update connection (#690): one TCP connection at a time, framed bytes in, one text line per +// step out. The protocol is in docs/DECK-PANEL-UPDATE-PROTOCOL.md; the board's task owns the socket and calls this. +// +// A frame is one type byte, a 4-byte little-endian length, then that many bytes: +// 'M' manifest (at most kMaxManifest), 'S' signature (64), 'I' image chunk (at most kMaxChunk), 'D' done (0). +#pragma once + +#include +#include +#include +#include +#include + +#include "update_session.h" + +namespace update_link { + +constexpr size_t kMaxManifest = 32 * 1024; +constexpr size_t kMaxChunk = 4096; +constexpr uint32_t kIdleBeforeManifestMs = 3000; ///< a stray connection can't hold "busy" for long +constexpr uint32_t kIdleMidImageMs = 10000; + +struct Out { + std::vector lines; ///< to send, each followed by "\n" + bool close = false; ///< close the connection after sending + bool reboot = false; ///< a new image is set to boot: restart into it after closing + std::string floor; ///< with reboot: the floor to keep once the new image confirms itself +}; + +class Link { + public: + explicit Link(const update_session::Config& config) : config_(config) {} + + /// A new connection. False while one is running: send `out.lines` and close it. + bool accept(int connection, uint32_t now_ms, Out& out); + /// Bytes from `connection`, in any split. + Out received(int connection, const uint8_t* bytes, size_t length, uint32_t now_ms); + /// Time passing with nothing received: ends an idle connection. + Out tick(uint32_t now_ms); + /// The connection went away. + void closed(int connection); + + private: + void handle(const update_session::Reply& reply, Out& out); + void finish(Out& out); + + update_session::Config config_; + std::optional session_; + int connection_ = -1; + uint32_t last_ms_ = 0; + uint8_t header_[5] = {}; + size_t header_have_ = 0; + std::vector payload_; + uint32_t payload_want_ = 0; +}; + +/// The text line for a reply, as the app reads it. +std::string line(const update_session::Reply& reply); + +} // namespace update_link diff --git a/tools/deck-panel/lib/update_manifest/update_manifest.cpp b/tools/deck-panel/lib/update_manifest/update_manifest.cpp new file mode 100644 index 00000000..a3381fa6 --- /dev/null +++ b/tools/deck-panel/lib/update_manifest/update_manifest.cpp @@ -0,0 +1,183 @@ +#include "update_manifest.h" + +namespace update_manifest { +namespace { + +// A small strict JSON reader for the manifest: objects, arrays, strings, numbers, true, false, null. It reads only +// what the panel needs and steps over the rest (the catalog), with a depth limit so no input can recurse deeply. +class Reader { + public: + Reader(const char* text, size_t length) : p_(text), end_(text + length) {} + + bool manifest(Manifest& out) { + bool ok = object([&](const std::string& key) { + if (key == "format") return integer(out.format); + if (key == "key") return string(&out.key); + if (key == "lowest_allowed") return object([&](const std::string& device) { + return device == "deck-panel" ? string(&out.lowest_allowed) : skip(); + }); + if (key == "files") return array([&] { return file(out); }); + return skip(); + }); + space(); + return ok && p_ == end_; + } + + private: + static constexpr int kMaxDepth = 16; + + bool file(Manifest& out) { + std::string device, name, version, sha; + long long size = -1; + if (!object([&](const std::string& key) { + if (key == "device") return string(&device); + if (key == "name") return string(&name); + if (key == "version") return string(&version); + if (key == "sha256") return string(&sha); + if (key == "size") return integer(size); + return skip(); + })) + return false; + if (device != "deck-panel") return true; + if (out.has_image || size < 0 || size > 0xFFFFFFFFLL || !hex32(sha, out.image.sha256)) return false; + out.has_image = true; + out.image.name = name; + out.image.version = version; + out.image.size = static_cast(size); + return true; + } + + static bool hex32(const std::string& text, uint8_t out[32]) { + if (text.size() != 64) return false; + for (size_t i = 0; i < 32; ++i) { + int hi = digit(text[2 * i]), lo = digit(text[2 * i + 1]); + if (hi < 0 || lo < 0) return false; + out[i] = static_cast(hi * 16 + lo); + } + return true; + } + + static int digit(char c) { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + if (c >= 'A' && c <= 'F') return c - 'A' + 10; + return -1; + } + + void space() { + while (p_ < end_ && (*p_ == ' ' || *p_ == '\n' || *p_ == '\r' || *p_ == '\t')) ++p_; + } + + bool take(char c) { + space(); + if (p_ < end_ && *p_ == c) { ++p_; return true; } + return false; + } + + template + bool object(Member member) { + if (!take('{') || ++depth_ > kMaxDepth) return false; + if (!take('}')) { + do { + std::string key; + if (!string(&key) || !take(':') || !member(key)) return false; + } while (take(',')); + if (!take('}')) return false; + } + --depth_; + return true; + } + + template + bool array(Element element) { + if (!take('[') || ++depth_ > kMaxDepth) return false; + if (!take(']')) { + do { + if (!element()) return false; + } while (take(',')); + if (!take(']')) return false; + } + --depth_; + return true; + } + + // A string, kept in `out` if given. Escapes are kept as-is but for \" and \\: no field the panel reads has others. + bool string(std::string* out) { + if (!take('"')) return false; + std::string value; + while (p_ < end_ && *p_ != '"') { + char c = *p_++; + if (static_cast(c) < 0x20) return false; + if (c == '\\') { + if (p_ == end_) return false; + c = *p_++; + if (c == 'u') { + for (int i = 0; i < 4; ++i) + if (p_ == end_ || digit(*p_++) < 0) return false; + c = '?'; + } else if (c != '"' && c != '\\' && c != '/' && c != 'b' && c != 'f' && c != 'n' && c != 'r' && c != 't') { + return false; + } + } + value.push_back(c); + } + if (p_ == end_) return false; + ++p_; + if (out) *out = value; + return true; + } + + template + bool integer(Int& out) { + space(); + long long value = 0; + const char* start = p_; + while (p_ < end_ && *p_ >= '0' && *p_ <= '9') { + if (value > 0xFFFFFFFFLL) return false; + value = value * 10 + (*p_++ - '0'); + } + if (p_ == start) return false; + out = static_cast(value); + return true; + } + + bool literal(const char* word) { + for (const char* w = word; *w; ++w) + if (p_ == end_ || *p_++ != *w) return false; + return true; + } + + bool skip() { + space(); + if (p_ == end_) return false; + switch (*p_) { + case '{': return object([&](const std::string&) { return skip(); }); + case '[': return array([&] { return skip(); }); + case '"': return string(nullptr); + case 't': return literal("true"); + case 'f': return literal("false"); + case 'n': return literal("null"); + default: break; + } + if (*p_ == '-') ++p_; + const char* start = p_; + while (p_ < end_ && ((*p_ >= '0' && *p_ <= '9') || *p_ == '.' || *p_ == 'e' || *p_ == 'E' || *p_ == '+' || *p_ == '-')) ++p_; + return p_ != start; + } + + const char* p_; + const char* end_; + int depth_ = 0; +}; + +} // namespace + +bool parse(const char* text, size_t length, Manifest& out) { + out = Manifest{}; + Reader reader(text, length); + if (reader.manifest(out)) return true; + out = Manifest{}; + return false; +} + +} // namespace update_manifest diff --git a/tools/deck-panel/lib/update_manifest/update_manifest.h b/tools/deck-panel/lib/update_manifest/update_manifest.h new file mode 100644 index 00000000..329631b0 --- /dev/null +++ b/tools/deck-panel/lib/update_manifest/update_manifest.h @@ -0,0 +1,31 @@ +// A signed firmware release's manifest, as the panel reads it (#690, ADR 0012). Only the fields the panel acts on: +// which key signed it, the format, the lowest panel version allowed, and the deck panel image's name, version, size +// and SHA-256. The signature covers the manifest's exact bytes, so nothing here is used before it checks out, except +// `key`, which names the key to check it with. +#pragma once + +#include +#include +#include + +namespace update_manifest { + +struct Image { + std::string name; + std::string version; + uint32_t size = 0; + uint8_t sha256[32] = {}; +}; + +struct Manifest { + int format = 0; + std::string key; + std::string lowest_allowed; ///< for "deck-panel"; empty if the manifest sets none + bool has_image = false; ///< a file whose device is "deck-panel" + Image image; +}; + +/// Reads `text` into `out`. False if it isn't a manifest: not JSON, or a field of the wrong shape. +bool parse(const char* text, size_t length, Manifest& out); + +} // namespace update_manifest diff --git a/tools/deck-panel/lib/update_session/update_session.cpp b/tools/deck-panel/lib/update_session/update_session.cpp new file mode 100644 index 00000000..9bba260c --- /dev/null +++ b/tools/deck-panel/lib/update_session/update_session.cpp @@ -0,0 +1,118 @@ +#include "update_session.h" + +#include +#include + +namespace update_session { +namespace { + +// A dotted version such as "1.10.0" as its numbers; false if it isn't one. +bool numbers(const std::string& text, std::vector& out) { + out.clear(); + unsigned long part = 0; + bool digit = false; + for (char c : text) { + if (c >= '0' && c <= '9') { + if (part > 100000000UL) return false; + part = part * 10 + static_cast(c - '0'); + digit = true; + } else if (c == '.' && digit) { + out.push_back(part); + part = 0; + digit = false; + } else { + return false; + } + } + if (!digit) return false; + out.push_back(part); + return true; +} + +} // namespace + +bool is_version(const std::string& text) { + std::vector parts; + return numbers(text, parts); +} + +bool below(const std::string& version, const std::string& floor) { + if (floor.empty()) return false; + std::vector v, f; + if (!numbers(version, v) || !numbers(floor, f)) return true; + for (size_t i = 0; i < v.size() || i < f.size(); ++i) { + const unsigned long a = i < v.size() ? v[i] : 0, b = i < f.size() ? f[i] : 0; + if (a != b) return a < b; + } + return false; +} + +Reply Session::refuse(Refusal why) { + // Anything written so far is dropped: the running firmware stays the one that boots. + if (state_ == State::image) config_.slot->abort(); + state_ = State::over; + Reply reply; + reply.kind = Reply::refused; + reply.refusal = why; + return reply; +} + +Reply Session::manifest(const uint8_t* bytes, size_t length) { + if (state_ != State::manifest) return refuse(Refusal::no_manifest); + state_ = State::signature; + manifest_.assign(reinterpret_cast(bytes), length); + return {}; +} + +Reply Session::signature(const uint8_t* bytes, size_t length) { + if (state_ != State::signature) return refuse(Refusal::no_manifest); + // Only the key's name is read before the signature checks out; the rest of the manifest is acted on after. + if (!update_manifest::parse(manifest_.data(), manifest_.size(), parsed_)) return refuse(Refusal::unreadable); + const TrustedKey* key = nullptr; + for (size_t i = 0; i < config_.key_count; ++i) + if (parsed_.key == config_.keys[i].id) key = &config_.keys[i]; + if (!key) return refuse(Refusal::unknown_key); + if (length != 64 || !config_.verify(key->public_key, reinterpret_cast(manifest_.data()), + manifest_.size(), bytes)) + return refuse(Refusal::bad_signature); + if (parsed_.format != 1) return refuse(Refusal::unknown_format); + if (!parsed_.has_image) return refuse(Refusal::no_image); + if (below(parsed_.image.version, config_.floor) || below(parsed_.image.version, parsed_.lowest_allowed)) + return refuse(Refusal::too_old); + if (parsed_.image.size > config_.slot->capacity()) return refuse(Refusal::too_big); + if (!config_.slot->begin(parsed_.image.size)) return refuse(Refusal::slot_error); + config_.hasher->start(); + state_ = State::image; + Reply reply; + reply.kind = Reply::ok_manifest; + return reply; +} + +Reply Session::chunk(const uint8_t* bytes, size_t length) { + if (state_ != State::image) return refuse(Refusal::no_manifest); + if (length > parsed_.image.size - received_) return refuse(Refusal::mismatch); + if (!config_.slot->write(bytes, length)) return refuse(Refusal::slot_error); + config_.hasher->update(bytes, length); + received_ += static_cast(length); + Reply reply; + reply.kind = Reply::progress; + reply.bytes = received_; + return reply; +} + +Reply Session::done() { + if (state_ != State::image) return refuse(Refusal::no_manifest); + uint8_t hash[32]; + config_.hasher->finish(hash); + if (received_ != parsed_.image.size || std::memcmp(hash, parsed_.image.sha256, 32) != 0) return refuse(Refusal::mismatch); + if (!config_.slot->end() || !config_.slot->set_boot()) return refuse(Refusal::slot_error); + state_ = State::over; + Reply reply; + reply.kind = Reply::switched; + reply.version = parsed_.image.version; + reply.floor = below(parsed_.lowest_allowed, config_.floor) || parsed_.lowest_allowed.empty() ? config_.floor + : parsed_.lowest_allowed; + return reply; +} + +} // namespace update_session diff --git a/tools/deck-panel/lib/update_session/update_session.h b/tools/deck-panel/lib/update_session/update_session.h new file mode 100644 index 00000000..b5966c5f --- /dev/null +++ b/tools/deck-panel/lib/update_session/update_session.h @@ -0,0 +1,110 @@ +// One firmware update over Wi-Fi (#690, ADR 0012), as the panel runs it: a signed manifest, then the image, into the +// spare slot, switched to only when the image's size and SHA-256 match the manifest. Nothing touches the slot before +// the manifest's signature checks out. The wire protocol is in docs/DECK-PANEL-UPDATE-PROTOCOL.md. +// +// Portable: the signature check, the hash and the slot are seams, so the native tests drive it with fakes and the +// board plugs in the real ones (Ed25519, SHA-256, esp_ota). +#pragma once + +#include +#include +#include + +#include "update_manifest.h" + +namespace update_session { + +/// Whether `text` is a dotted version such as "1.10.0": numbers and single dots, nothing else. +bool is_version(const std::string& text); +/// Whether `version` is below `floor`, number by number (a missing part counts as 0). An empty floor is no floor; a +/// version that isn't one is always below. +bool below(const std::string& version, const std::string& floor); + +struct TrustedKey { + const char* id; + uint8_t public_key[32]; +}; + +/// Whether `signature` is `public_key`'s Ed25519 signature over exactly `message`. +using Verify = bool (*)(const uint8_t public_key[32], const uint8_t* message, size_t length, const uint8_t signature[64]); + +class Hasher { + public: + virtual ~Hasher() = default; + virtual void start() = 0; + virtual void update(const uint8_t* data, size_t length) = 0; + virtual void finish(uint8_t out[32]) = 0; +}; + +/// The spare app slot. +class Slot { + public: + virtual ~Slot() = default; + virtual uint32_t capacity() const = 0; + virtual bool begin(uint32_t size) = 0; ///< erases only `size` bytes + virtual bool write(const uint8_t* data, size_t length) = 0; + virtual bool end() = 0; ///< the image is complete; not yet the boot slot + virtual bool set_boot() = 0; ///< boot it next, as a trial until it confirms itself + virtual void abort() = 0; ///< drop what was written; the running firmware stays the boot slot +}; + +struct Config { + const TrustedKey* keys; + size_t key_count; + Verify verify; + Hasher* hasher; + Slot* slot; + std::string floor; ///< the lowest version this panel takes (NVS, only ever raised) +}; + +enum class Refusal { + none, + busy, + no_manifest, ///< anything but a manifest and its signature first + too_large, ///< a manifest or chunk over its cap + unreadable, ///< not a manifest + unknown_key, + bad_signature, + unknown_format, + no_image, ///< signed, but nothing in it for a deck panel + too_old, ///< below the floor or the manifest's lowest allowed version + too_big, ///< bigger than the spare slot + mismatch, ///< the image's size or SHA-256 differs from the manifest + timeout, + slot_error, +}; + +struct Reply { + enum Kind { nothing, ok_manifest, progress, switched, refused } kind = nothing; + Refusal refusal = Refusal::none; + uint32_t bytes = 0; ///< progress: received so far + std::string version; ///< switched: the version now set to boot + std::string floor; ///< switched: the floor to keep once that version confirms itself (never lower) +}; + +class Session { + public: + explicit Session(const Config& config) : config_(config) {} + + Reply manifest(const uint8_t* bytes, size_t length); + Reply signature(const uint8_t* bytes, size_t length); + Reply chunk(const uint8_t* bytes, size_t length); + Reply done(); + /// Ends the update for a reason outside the frames (a cap, a timeout, a dropped link): nothing is switched. + Reply stop(Refusal why) { return refuse(why); } + /// Whether the manifest checked out and image bytes are coming. + bool receiving_image() const { return state_ == State::image; } + + private: + Reply refuse(Refusal why); + + enum class State { manifest, signature, image, over }; + + Config config_; + State state_ = State::manifest; + std::string manifest_; + update_manifest::Manifest parsed_; + uint32_t received_ = 0; +}; + +} // namespace update_session diff --git a/tools/deck-panel/platformio.ini b/tools/deck-panel/platformio.ini index 8b2711b8..014ff157 100644 --- a/tools/deck-panel/platformio.ini +++ b/tools/deck-panel/platformio.ini @@ -9,7 +9,9 @@ default_envs = native ; Host tests for the portable code in lib/ (no Arduino, no board). [env:native] platform = native +; libsodium (#690): the system copy, from brew on the Mac and libsodium-dev on CI. The board links the ESP32 libs' own. build_flags = -std=c++17 -Wall -Wextra -Werror + -isystem /opt/homebrew/include -L/opt/homebrew/lib -lsodium ; The panel: Elecrow CrowPanel Advance 7.0-HMI, ESP32-S3-WROOM-1-N16R8, hardware V1.4. Board settings from the owner's ; phrasedeck firmware, which follow robominds' Crowpanel-Advance-7.0-HMI-Display (MIT, LICENSE.crowpanel-drivers). @@ -58,7 +60,7 @@ monitor_speed = 921600 ; pio run -e crowpanel-test [env:crowpanel-test] extends = env:crowpanel -build_src_filter = +<*> - - - - +build_src_filter = +<*> - - - - - build_flags = ${env:crowpanel.build_flags} -DDECK_PANEL_TEST_SCREEN diff --git a/tools/deck-panel/src/main.cpp b/tools/deck-panel/src/main.cpp index a0732fc5..e83d5b4a 100644 --- a/tools/deck-panel/src/main.cpp +++ b/tools/deck-panel/src/main.cpp @@ -37,6 +37,7 @@ #include "feed_intake.h" #include "feed_udp.h" #include "hold_reset.h" +#include "update_wifi.h" #include "wifi_link.h" #endif @@ -364,6 +365,7 @@ class PanelBoard : public frame_clock::Board { #ifdef DECK_PANEL_TEST_SCREEN test_screen::show_touch(); #else + if (update_wifi::hold_render()) return; // an update is writing flash: the still screen, not the deck (#690) // Read after the drain, so a datagram stamped then is never in the future of the render. g_core.render(g_screen, millis()); #endif @@ -371,6 +373,9 @@ class PanelBoard : public frame_clock::Board { void refresh() override { MARK(refresh); +#ifndef DECK_PANEL_TEST_SCREEN + if (update_wifi::hold_refresh()) return; +#endif display_refresh(); } @@ -388,6 +393,7 @@ class PanelBoard : public frame_clock::Board { MARK(wifi); wifi_link::poll(now); g_core.set_network(wifi_link::state(), wifi_link::ip()); + update_wifi::chores(now); MARK(udp); // For the receive task, which opens the socket on each join and closes it off Wi-Fi (FeedUdp::poll); wifi_link // is this task's, so it's told, not asked. A join seen a millisecond before its state only reopens late. @@ -496,6 +502,7 @@ void setup() { receive_begin(); // before Wi-Fi, so the first join's socket opens on it #endif wifi_link::begin(); // after the backlight: joining takes seconds and must not hold the first frame + update_wifi::begin(); Serial.println("deck panel: deck view up"); #endif } diff --git a/tools/deck-panel/src/update_wifi.cpp b/tools/deck-panel/src/update_wifi.cpp new file mode 100644 index 00000000..6fdc9458 --- /dev/null +++ b/tools/deck-panel/src/update_wifi.cpp @@ -0,0 +1,449 @@ +#include "update_wifi.h" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "release_check.h" +#include "release_keys.h" +#include "update_boot.h" +#include "update_floor.h" +#include "update_link.h" +#include "update_session.h" +#include "wifi_link.h" + +LV_FONT_DECLARE(geist_semibold_36) +LV_FONT_DECLARE(geist_regular_24) + +// Arduino's initArduino() marks a PENDING_VERIFY image valid at once unless this returns true +// (cores/esp32/esp32-hal-misc.c, a weak C symbol under CONFIG_APP_ROLLBACK_ENABLE, which the shipped sdkconfig sets). +// C linkage, or it wouldn't replace the weak one and every new image would confirm itself unseen. The trial below +// decides instead. +extern "C" bool verifyRollbackLater() { return true; } + +namespace update_wifi { +namespace { + +constexpr uint16_t kPort = 3310; +// The task's stack. Its deepest path is Link::received -> Session::signature -> crypto_sign_verify_detached +// (libsodium's ref10 double scalar mult: 8 cached points of 160 B, two 256-byte slide arrays, a SHA-512 state; about +// 2.5-3 KB) beside update_manifest::parse (depth-limited, a few hundred bytes) and the frame's std::string copies, +// which are on the heap. esp_ota_write and lwIP's send/recv add about 1 KB. 8 KB leaves over half spare; the high-water +// mark is printed after each connection, so a run on the board shows the real figure. +constexpr uint32_t kStackBytes = 8192; +// Above idle (0) and Arduino's timer task (1), below everything the update needs to run under it on core 0: lwIP's +// tcpip task (18), esp_timer (22, it times the loop's draw hold), Wi-Fi (23). #664's feed task should sit above this. +constexpr UBaseType_t kPriority = 2; +constexpr BaseType_t kCore = 0; +constexpr uint32_t kSelectMs = 100; // tick() resolution: the link's timeouts are 3 s and 10 s +constexpr uint32_t kSendTimeoutMs = 2000; // a peer that stops reading can't hold the task +constexpr uint32_t kStillWaitMs = 500; // longest the first flash write waits for the still screen +constexpr uint32_t kCloseGraceMs = 300; // "ok switched" reaches the Mac before the restart +constexpr size_t kMaxKeys = 4; + +// The floor and the pending record, in their own NVS namespace: wifi_link's is "deckpanel" (key "wifi"), and forgetting +// the Wi-Fi only ever removes that key, so a hold-reset can never lower the floor. +constexpr const char* kNamespace = "deckupdate"; +constexpr const char* kFloorKey = "floor"; +constexpr const char* kPendFloorKey = "pend_floor"; // the floor Out.floor asked for, set at the switch +constexpr const char* kPendSlotKey = "pend_slot"; // the slot it belongs to (partition label) + +// --- Shared between the loop (core 1) and the task (core 0) ------------------------------------------------------- +std::atomic g_network_up{false}; +std::atomic g_listening{false}; +std::atomic g_still_wanted{false}; +std::atomic g_still_on_glass{false}; +std::atomic g_floor_changed{false}; + +// --- NVS ---------------------------------------------------------------------------------------------------------- + +std::string nvs_get(const char* key) { + Preferences prefs; + if (!prefs.begin(kNamespace, true)) return ""; // read-only fails when the namespace was never written + char value[32] = ""; + if (prefs.isKey(key)) prefs.getString(key, value, sizeof value); + prefs.end(); + return value; +} + +bool nvs_put(const char* key, const std::string& value) { + Preferences prefs; + if (!prefs.begin(kNamespace, false)) return false; + const bool ok = prefs.putString(key, value.c_str()) == value.size(); + prefs.end(); + return ok; +} + +void nvs_drop_pending() { + Preferences prefs; + if (!prefs.begin(kNamespace, false)) return; + if (prefs.isKey(kPendFloorKey)) prefs.remove(kPendFloorKey); + if (prefs.isKey(kPendSlotKey)) prefs.remove(kPendSlotKey); + prefs.end(); +} + +/// Raises the floor to the pending one (never lowers it: lib/update_floor) and drops the record. +void apply_pending() { + const std::string floor = nvs_get(kFloorKey); + const std::string next = update_floor::raised(floor, nvs_get(kPendFloorKey)); + if (next != floor) { + if (nvs_put(kFloorKey, next)) { + Serial.printf("deck panel: update floor now %s\n", next.c_str()); + g_floor_changed = true; + } else { + Serial.println("deck panel: update floor not saved; kept for the next boot"); + return; // the record stays, and the next boot tries again + } + } + nvs_drop_pending(); +} + +// --- The still screen --------------------------------------------------------------------------------------------- +// The task asks for it (g_still_wanted) and waits until the loop has it on glass (g_still_on_glass) before the first +// flash erase. The task never calls LVGL. + +lv_obj_t* g_still = nullptr; +bool g_shown = false; // loop task only +bool g_drawn = false; // the refresh that puts it up has run + +void build_still() { + g_still = lv_obj_create(lv_layer_top()); + lv_obj_remove_style_all(g_still); + lv_obj_set_size(g_still, LV_PCT(100), LV_PCT(100)); + lv_obj_set_style_bg_color(g_still, lv_color_black(), 0); + lv_obj_set_style_bg_opa(g_still, LV_OPA_COVER, 0); + lv_obj_t* headline = lv_label_create(g_still); + lv_obj_set_style_text_font(headline, &geist_semibold_36, 0); + lv_obj_set_style_text_color(headline, lv_color_white(), 0); + lv_label_set_text(headline, "Updating\xE2\x80\xA6"); // U+2026, in the font + lv_obj_align(headline, LV_ALIGN_CENTER, 0, -24); + lv_obj_t* detail = lv_label_create(g_still); + lv_obj_set_style_text_font(detail, &geist_regular_24, 0); + lv_obj_set_style_text_color(detail, lv_color_hex(0x9A9A9A), 0); + lv_label_set_text(detail, "Keep the panel powered. It restarts when done."); + lv_obj_align(detail, LV_ALIGN_CENTER, 0, 28); + lv_obj_add_flag(g_still, LV_OBJ_FLAG_HIDDEN); +} + +/// Task side: asks for the still screen and waits, bounded, until it is on glass. On a timeout (a stopped panel) the +/// update goes on: the screen is for the eye, not for the flash. +void want_still() { + g_still_on_glass = false; + g_still_wanted = true; + for (uint32_t waited = 0; !g_still_on_glass && waited < kStillWaitMs; waited += 10) vTaskDelay(pdMS_TO_TICKS(10)); +} + +void release_still() { g_still_wanted = false; } + +// --- The spare slot over esp_ota ---------------------------------------------------------------------------------- + +class OtaSlot : public update_session::Slot { + public: + uint32_t capacity() const override { + const esp_partition_t* next = esp_ota_get_next_update_partition(nullptr); + return next ? next->size : 0; // no spare slot: every image is too big + } + + bool begin(uint32_t size) override { + part_ = esp_ota_get_next_update_partition(nullptr); + if (part_ == nullptr) return false; + // The erase below is the longest stretch with the caches off: the screen goes still first. + want_still(); + // The real size: only that much is erased (rounded up to sectors), not the whole 6.25 MB slot. + const esp_err_t err = esp_ota_begin(part_, size, &handle_); + if (err != ESP_OK) { + // ESP_ERR_OTA_ROLLBACK_INVALID_STATE: this image is still on trial (it confirms within seconds of Wi-Fi). + Serial.printf("deck panel: update slot not opened (%s)\n", esp_err_to_name(err)); + release_still(); + return false; + } + open_ = true; + return true; + } + + bool write(const uint8_t* data, size_t length) override { + const esp_err_t err = esp_ota_write(handle_, data, length); + if (err != ESP_OK) Serial.printf("deck panel: update write failed (%s)\n", esp_err_to_name(err)); + return err == ESP_OK; + } + + bool end() override { + open_ = false; // esp_ota_end frees the handle whatever it returns + const esp_err_t err = esp_ota_end(handle_); // also checks the image's own header and checksum + if (err != ESP_OK) Serial.printf("deck panel: update image not accepted (%s)\n", esp_err_to_name(err)); + return err == ESP_OK; + } + + bool set_boot() override { + const esp_err_t err = esp_ota_set_boot_partition(part_); + if (err != ESP_OK) Serial.printf("deck panel: update not set to boot (%s)\n", esp_err_to_name(err)); + return err == ESP_OK; + } + + void abort() override { + if (open_) esp_ota_abort(handle_); + open_ = false; + release_still(); + } + + const char* label() const { return part_ ? part_->label : ""; } + + private: + const esp_partition_t* part_ = nullptr; + esp_ota_handle_t handle_ = 0; + bool open_ = false; +}; + +// --- The task ----------------------------------------------------------------------------------------------------- +// Everything below is the task's alone once begin() has started it. + +OtaSlot g_slot; +release_check::Sha256 g_hasher; +update_session::TrustedKey g_keys[kMaxKeys]; +size_t g_key_count = 0; +std::optional g_link; +uint8_t g_rx[1460]; // one TCP segment; static, off the task's stack + +/// The link over the floor now in NVS. Link copies its Config, so a raised floor needs a new link (idle only). +void make_link() { + update_session::Config config{g_keys, g_key_count, release_check::signature_ok, &g_hasher, &g_slot, + nvs_get(kFloorKey)}; + g_link.emplace(config); +} + +int open_listener() { + const int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_IP); + if (fd < 0) return -1; + const int yes = 1; + setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes); + sockaddr_in addr = {}; + addr.sin_family = AF_INET; + addr.sin_port = htons(kPort); + addr.sin_addr.s_addr = htonl(INADDR_ANY); // the station's address and the setup network's alike + if (bind(fd, reinterpret_cast(&addr), sizeof addr) != 0 || listen(fd, 1) != 0) { + close(fd); + return -1; + } + return fd; +} + +void set_client_options(int fd) { + timeval timeout = {static_cast(kSendTimeoutMs / 1000), static_cast(kSendTimeoutMs % 1000 * 1000)}; + setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof timeout); + const int yes = 1; + setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof yes); +} + +void send_lines(int fd, const update_link::Out& out) { + for (const std::string& text : out.lines) { + const std::string line = text + "\n"; + size_t sent = 0; + while (sent < line.size()) { + const int n = send(fd, line.data() + sent, line.size() - sent, 0); + if (n <= 0) return; // the send timeout or a dead peer: the close follows + sent += static_cast(n); + } + } +} + +void log_stack() { + Serial.printf("deck panel: update task stack free %u B\n", + unsigned(uxTaskGetStackHighWaterMark(nullptr) * sizeof(StackType_t))); +} + +/// Acts on what the link said; returns true when `client` is closed. +bool act(int client, const update_link::Out& out) { + send_lines(client, out); + if (out.reboot) { + // The floor is only raised once the new image confirms itself; until then it waits here, tied to its slot. + if (!out.floor.empty() && !(nvs_put(kPendSlotKey, g_slot.label()) && nvs_put(kPendFloorKey, out.floor))) + Serial.println("deck panel: update floor not kept for the new image"); + shutdown(client, SHUT_WR); + vTaskDelay(pdMS_TO_TICKS(kCloseGraceMs)); + close(client); + Serial.println("deck panel: update switched, restarting"); + Serial.flush(); + esp_restart(); + } + if (!out.close) return false; + close(client); + log_stack(); + return true; +} + +void run(void*) { + int listener = -1; + int client = -1; + for (;;) { + if (listener < 0) { + // lwIP isn't up until wifi_link starts Wi-Fi; wait for the network, then listen on any address. + if (!g_network_up) { + vTaskDelay(pdMS_TO_TICKS(250)); + continue; + } + listener = open_listener(); + if (listener < 0) { + Serial.printf("deck panel: update server not listening (errno %d); retrying\n", errno); + vTaskDelay(pdMS_TO_TICKS(1000)); + continue; + } + g_listening = true; + Serial.printf("deck panel: update server on port %u\n", unsigned(kPort)); + } + if (client < 0 && g_floor_changed.exchange(false)) make_link(); + + fd_set readable; + FD_ZERO(&readable); + FD_SET(listener, &readable); + if (client >= 0) FD_SET(client, &readable); + timeval wait = {0, static_cast(kSelectMs * 1000)}; + const int ready = select((client > listener ? client : listener) + 1, &readable, nullptr, nullptr, &wait); + const uint32_t now = millis(); + if (ready < 0) { + vTaskDelay(pdMS_TO_TICKS(kSelectMs)); + continue; + } + if (ready == 0) { + if (client >= 0 && act(client, g_link->tick(now))) client = -1; + continue; + } + if (FD_ISSET(listener, &readable)) { + const int fd = accept(listener, nullptr, nullptr); + if (fd >= 0) { + set_client_options(fd); + update_link::Out out; + if (g_link->accept(fd, now, out)) { + client = fd; + } else { + send_lines(fd, out); // "refused busy"; the running one carries on + close(fd); + } + } + } + if (client >= 0 && FD_ISSET(client, &readable)) { + const int got = recv(client, g_rx, sizeof g_rx, MSG_DONTWAIT); + if (got > 0) { + const update_link::Out out = g_link->received(client, g_rx, static_cast(got), now); + // The erase inside a signature frame takes seconds: the sender's idle time starts now, not before it. + g_link->received(client, g_rx, 0, millis()); + if (act(client, out)) client = -1; + } else if (got == 0 || (errno != EAGAIN && errno != EWOULDBLOCK)) { + g_link->closed(client); // mid-image: the slot is dropped, the old firmware stays + close(client); + client = -1; + log_stack(); + } + } + } +} + +// --- The trial (loop task) ---------------------------------------------------------------------------------------- + +bool g_trial = false; // read once at boot: this image is PENDING_VERIFY + +void trial_chores(uint32_t now_ms) { + if (!g_trial) return; + update_boot::State state; + state.trial = true; + state.saved_wifi = wifi_link::state() != deck_core::Network::setup; + state.wifi_joined = wifi_link::state() == deck_core::Network::connected; + state.setup_network_up = wifi_link::setup_up(); + state.update_listening = g_listening; + state.since_boot_ms = now_ms; + switch (update_boot::decide(state)) { + case update_boot::Decision::confirm: { + g_trial = false; + const esp_err_t err = esp_ota_mark_app_valid_cancel_rollback(); + if (err != ESP_OK) { + Serial.printf("deck panel: update not confirmed (%s)\n", esp_err_to_name(err)); + return; // stays a trial in otadata: the next reset rolls back + } + Serial.println("deck panel: update confirmed"); + apply_pending(); + return; + } + case update_boot::Decision::roll_back: { + g_trial = false; // once: a failed rollback isn't retried every frame + Serial.println("deck panel: update didn't bring Wi-Fi and the update server up; rolling back"); + Serial.flush(); + nvs_drop_pending(); + const esp_err_t err = esp_ota_mark_app_invalid_rollback_and_reboot(); // returns only on failure + Serial.printf("deck panel: rollback failed (%s); running on\n", esp_err_to_name(err)); + return; + } + default: return; + } +} + +} // namespace + +void begin() { + const esp_partition_t* running = esp_ota_get_running_partition(); + esp_ota_img_states_t ota_state; + g_trial = running != nullptr && esp_ota_get_state_partition(running, &ota_state) == ESP_OK && + ota_state == ESP_OTA_IMG_PENDING_VERIFY; + // A pending floor belongs to the slot it was sent for. Running another slot: a rollback, or a cable flash, so drop + // it. Running that slot but not on trial: it confirmed and lost power before the floor was saved, so save it now. + const std::string pending_slot = nvs_get(kPendSlotKey); + if (!pending_slot.empty() || !nvs_get(kPendFloorKey).empty()) { + if (running == nullptr || pending_slot != running->label) { + nvs_drop_pending(); + } else if (!g_trial) { + apply_pending(); + } + } + if (g_trial) Serial.printf("deck panel: new image on trial, %u s to bring Wi-Fi up\n", unsigned(update_boot::kTrialMs / 1000)); + + g_key_count = release_keys::trusted(release_keys::kListed, g_keys, kMaxKeys); + if (g_key_count == 0) Serial.println("deck panel: no release keys built in; Wi-Fi updates are refused"); + g_floor_changed = false; + make_link(); + build_still(); + if (xTaskCreatePinnedToCore(run, "update", kStackBytes, nullptr, kPriority, nullptr, kCore) != pdPASS) { + // No server: a trial can't confirm and rolls back, which is right; a confirmed image runs on without updates. + Serial.println("deck panel: no update task; Wi-Fi updates are off"); + } +} + +void chores(uint32_t now_ms) { + g_network_up = wifi_link::state() == deck_core::Network::connected || wifi_link::setup_up(); + trial_chores(now_ms); +} + +bool hold_render() { + const bool want = g_still_wanted; + if (want && !g_shown) { + lv_obj_remove_flag(g_still, LV_OBJ_FLAG_HIDDEN); + g_shown = true; + g_drawn = false; + return true; + } + if (!want && g_shown) { + // The update ended without a switch: the deck underneath redraws where the still screen was. + lv_obj_add_flag(g_still, LV_OBJ_FLAG_HIDDEN); + g_shown = false; + g_still_on_glass = false; + return false; + } + // render() runs after the frame's latch wait: a refresh handed over last frame is on glass by now. + if (g_shown && g_drawn) g_still_on_glass = true; + return g_shown; +} + +bool hold_refresh() { + if (!g_shown) return false; + if (g_drawn) return true; + g_drawn = true; + return false; +} + +} // namespace update_wifi diff --git a/tools/deck-panel/src/update_wifi.h b/tools/deck-panel/src/update_wifi.h new file mode 100644 index 00000000..63f07376 --- /dev/null +++ b/tools/deck-panel/src/update_wifi.h @@ -0,0 +1,30 @@ +// The firmware update over Wi-Fi, board side (#690, ADR 0012, docs/DECK-PANEL-UPDATE-PROTOCOL.md): the TCP server +// on port 3310 in its own task on core 0, the spare slot over esp_ota, the floor in NVS, the still "Updating" screen, +// and the trial after a switch (confirm, or roll back to the previous image). The protocol and the rules are +// lib/update_link, lib/update_session and lib/update_boot; this only plugs the board into their seams. +// +// Everything here but the task is called from the loop task (Arduino's, core 1). The task and the loop share only +// atomics: the network being up, the server listening, the still screen wanted and on glass, the floor changed. +#pragma once + +#include + +namespace update_wifi { + +/// Call once in setup(), after display_init() and wifi_link::begin(): reads the floor and the trial state from flash, +/// builds the still screen (hidden) and starts the update task. The task listens once the network is up. +void begin(); + +/// Every frame, from the chores: tells the task whether the network is up, and runs the trial after an update +/// (lib/update_boot): confirms the image, raising the floor, or rolls back and restarts. Cheap when not on trial. +void chores(uint32_t now_ms); + +/// In render(): true while an update holds the screen; skip drawing the deck. The first call that returns true puts +/// the still screen up (LVGL, loop task); the call after the update ends hides it again and returns false. +bool hold_render(); + +/// In refresh(): true when there's nothing to hand the panel. While held, one refresh puts the still screen on glass, +/// then none until the update ends. +bool hold_refresh(); + +} // namespace update_wifi diff --git a/tools/deck-panel/src/wifi_link.cpp b/tools/deck-panel/src/wifi_link.cpp index 0ce94d30..b6ec3245 100644 --- a/tools/deck-panel/src/wifi_link.cpp +++ b/tools/deck-panel/src/wifi_link.cpp @@ -445,6 +445,8 @@ const char* setup_password() { return g_setup_password; } +bool setup_up() { return g_state == Network::setup && g_setup_up; } + uint32_t joins() { return g_joins; } void forget_and_restart() { diff --git a/tools/deck-panel/src/wifi_link.h b/tools/deck-panel/src/wifi_link.h index 9aad454d..5a2ab4cb 100644 --- a/tools/deck-panel/src/wifi_link.h +++ b/tools/deck-panel/src/wifi_link.h @@ -26,6 +26,9 @@ const char* ip(); const char* setup_name(); const char* setup_password(); +/// Whether the setup network (AP, DNS, web server) is running: in setup only. For the update's trial (#690). +bool setup_up(); + /// Counts connections: changes each time the station (re)joins, so the UDP socket knows to open again. uint32_t joins(); diff --git a/tools/deck-panel/test/test_release_check/test_main.cpp b/tools/deck-panel/test/test_release_check/test_main.cpp new file mode 100644 index 00000000..acee4331 --- /dev/null +++ b/tools/deck-panel/test/test_release_check/test_main.cpp @@ -0,0 +1,183 @@ +// The panel's Ed25519 check (#690, ADR 0012) against the two vectors the updater checks too (#689): RFC 8032 TEST 1, +// and the randomized CryptoKit signature in the updater's own fixture file, read from it here so the two can't drift. +#include + +#include +#include +#include +#include +#include + +#include "release_check.h" +#include "update_session.h" + +namespace { + +std::vector hex(const std::string& text) { + std::vector out; + for (size_t i = 0; i + 1 < text.size(); i += 2) out.push_back(static_cast(std::stoi(text.substr(i, 2), nullptr, 16))); + return out; +} + +// The value of "key" in the fixture's flat JSON object of strings. +std::string field(const std::string& json, const std::string& key) { + const size_t at = json.find("\"" + key + "\""); + const size_t open = json.find('"', json.find(':', at) + 1); + return json.substr(open + 1, json.find('"', open + 1) - open - 1); +} + +void test_the_rfc_8032_test_vector_verifies_and_a_changed_message_does_not() { + const auto key = hex("d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a"); + const auto sig = hex("e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"); + TEST_ASSERT_TRUE(release_check::signature_ok(key.data(), nullptr, 0, sig.data())); + const uint8_t one = 0; + TEST_ASSERT_FALSE(release_check::signature_ok(key.data(), &one, 1, sig.data())); +} + +void test_the_updaters_cryptokit_vector_verifies_and_a_one_bit_flip_does_not() { + FILE* file = std::fopen("../../Packages/FirmwareUpdaterKit/Tests/FirmwareReleaseTests/Fixtures/cryptokit-ed25519.json", "r"); + TEST_ASSERT_NOT_NULL_MESSAGE(file, "the updater's shared vector file"); + std::string json; + char buffer[512]; + for (size_t n; (n = std::fread(buffer, 1, sizeof buffer, file)) > 0;) json.append(buffer, n); + std::fclose(file); + const auto key = hex(field(json, "public_key")); + const auto message = hex(field(json, "message")); + auto sig = hex(field(json, "signature")); + TEST_ASSERT_EQUAL(32, key.size()); + TEST_ASSERT_EQUAL(64, sig.size()); + TEST_ASSERT_TRUE(release_check::signature_ok(key.data(), message.data(), message.size(), sig.data())); + sig[0] ^= 1; + TEST_ASSERT_FALSE(release_check::signature_ok(key.data(), message.data(), message.size(), sig.data())); +} + +std::string hex_of(const uint8_t* bytes, size_t length) { + std::string out; + char pair[3]; + for (size_t i = 0; i < length; ++i) { + std::snprintf(pair, sizeof pair, "%02x", bytes[i]); + out += pair; + } + return out; +} + +// FIPS 180-2 appendix B.1 and B.2, fed in uneven pieces, then the same hasher started again on the empty string. +void test_sha256_of_an_image_fed_in_pieces_matches_the_fips_vectors_and_start_begins_again() { + release_check::Sha256 hasher; + uint8_t digest[32]; + hasher.start(); + hasher.update(reinterpret_cast("a"), 1); + hasher.update(reinterpret_cast("bc"), 2); + hasher.finish(digest); + TEST_ASSERT_EQUAL_STRING("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", hex_of(digest, 32).c_str()); + + const char* two_blocks = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"; + hasher.start(); + hasher.update(reinterpret_cast(two_blocks), 7); + hasher.update(reinterpret_cast(two_blocks) + 7, 49); + hasher.finish(digest); + TEST_ASSERT_EQUAL_STRING("248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1", hex_of(digest, 32).c_str()); + + hasher.start(); + hasher.update(reinterpret_cast("abc"), 3); + hasher.start(); + hasher.finish(digest); + TEST_ASSERT_EQUAL_STRING("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", hex_of(digest, 32).c_str()); +} + +class MemorySlot : public update_session::Slot { + public: + uint32_t capacity() const override { return 6553600; } + bool begin(uint32_t) override { return true; } + bool write(const uint8_t* data, size_t length) override { written.insert(written.end(), data, data + length); return true; } + bool end() override { return true; } + bool set_boot() override { boot = true; return true; } + void abort() override {} + bool boot = false; + std::vector written; +}; + +// One whole update through the session with the real checks: a manifest signed with a key made here from a fixed +// test seed (never a release key), and a 10,000-byte image sent in the link's 4 KB chunks. +struct RealUpdate { + uint8_t public_key[32]; + uint8_t secret_key[64]; + std::vector image; + std::string manifest; + + RealUpdate() : image(10000) { + TEST_ASSERT_TRUE(sodium_init() >= 0); + const std::vector seed(32, 0x42); + crypto_sign_seed_keypair(public_key, secret_key, seed.data()); + for (size_t i = 0; i < image.size(); ++i) image[i] = static_cast(i * 7 + 3); + uint8_t digest[32]; + crypto_hash_sha256(digest, image.data(), image.size()); + manifest = "{\"format\": 1, \"key\": \"primary\", \"lowest_allowed\": {\"deck-panel\": \"1.0.0\"}, \"files\": " + "[{\"device\": \"deck-panel\", \"name\": \"p.bin\", \"version\": \"1.2.0\", \"size\": 10000, " + "\"sha256\": \"" + hex_of(digest, 32) + "\"}]}"; + } + + // Signs the manifest, then sends `sent` (the manifest, or a changed copy) and `payload`; the last reply. + update_session::Reply run(MemorySlot& slot, const std::string& sent, const std::vector& payload) { + uint8_t signature[64]; + crypto_sign_detached(signature, nullptr, reinterpret_cast(manifest.data()), manifest.size(), secret_key); + update_session::TrustedKey keys[1] = {{"primary", {}}}; + std::memcpy(keys[0].public_key, public_key, 32); + release_check::Sha256 hasher; + update_session::Session session( + update_session::Config{keys, 1, release_check::signature_ok, &hasher, &slot, "1.0.0"}); + update_session::Reply reply = session.manifest(reinterpret_cast(sent.data()), sent.size()); + if (reply.kind == update_session::Reply::refused) return reply; + reply = session.signature(signature, sizeof signature); + if (reply.kind == update_session::Reply::refused) return reply; + for (size_t at = 0; at < payload.size(); at += 4096) { + reply = session.chunk(payload.data() + at, std::min(4096, payload.size() - at)); + if (reply.kind == update_session::Reply::refused) return reply; + } + return session.done(); + } +}; + +void test_a_really_signed_update_switches_with_libsodium_checking_the_signature_and_the_image() { + RealUpdate update; + MemorySlot slot; + const update_session::Reply reply = update.run(slot, update.manifest, update.image); + TEST_ASSERT_EQUAL(update_session::Reply::switched, reply.kind); + TEST_ASSERT_EQUAL_STRING("1.2.0", reply.version.c_str()); + TEST_ASSERT_TRUE(slot.boot); + TEST_ASSERT_TRUE(slot.written == update.image); +} + +void test_one_changed_image_byte_is_a_mismatch_and_nothing_is_set_to_boot() { + RealUpdate update; + MemorySlot slot; + std::vector changed = update.image; + changed[9000] ^= 0x80; + const update_session::Reply reply = update.run(slot, update.manifest, changed); + TEST_ASSERT_EQUAL(static_cast(update_session::Refusal::mismatch), static_cast(reply.refusal)); + TEST_ASSERT_FALSE(slot.boot); +} + +void test_a_manifest_changed_after_signing_is_a_bad_signature_and_the_slot_untouched() { + RealUpdate update; + MemorySlot slot; + std::string changed = update.manifest; + changed.replace(changed.find("1.2.0"), 5, "9.2.0"); + const update_session::Reply reply = update.run(slot, changed, update.image); + TEST_ASSERT_EQUAL(static_cast(update_session::Refusal::bad_signature), static_cast(reply.refusal)); + TEST_ASSERT_TRUE(slot.written.empty()); + TEST_ASSERT_FALSE(slot.boot); +} + +} // namespace + +int main() { + UNITY_BEGIN(); + RUN_TEST(test_the_rfc_8032_test_vector_verifies_and_a_changed_message_does_not); + RUN_TEST(test_the_updaters_cryptokit_vector_verifies_and_a_one_bit_flip_does_not); + RUN_TEST(test_sha256_of_an_image_fed_in_pieces_matches_the_fips_vectors_and_start_begins_again); + RUN_TEST(test_a_really_signed_update_switches_with_libsodium_checking_the_signature_and_the_image); + RUN_TEST(test_one_changed_image_byte_is_a_mismatch_and_nothing_is_set_to_boot); + RUN_TEST(test_a_manifest_changed_after_signing_is_a_bad_signature_and_the_slot_untouched); + return UNITY_END(); +} diff --git a/tools/deck-panel/test/test_release_keys/test_main.cpp b/tools/deck-panel/test/test_release_keys/test_main.cpp new file mode 100644 index 00000000..5bcc322f --- /dev/null +++ b/tools/deck-panel/test/test_release_keys/test_main.cpp @@ -0,0 +1,43 @@ +// The panel's release keys (#690) as the update session takes them: a mistyped key isn't trusted, silently or not. +#include + +#include "release_keys.h" + +using release_keys::Listed; + +namespace { + +void test_listed_keys_become_trusted_keys_and_a_mistyped_one_is_left_out() { + const Listed list[] = { + {"primary", "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a"}, + {"backup", "zz5a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a"}, // not hex + {"backup", "d75a98"}, // too short + {nullptr, nullptr}, + }; + update_session::TrustedKey out[4]; + TEST_ASSERT_EQUAL(1, release_keys::trusted(list, out, 4)); + TEST_ASSERT_EQUAL_STRING("primary", out[0].id); + TEST_ASSERT_EQUAL_HEX8(0xd7, out[0].public_key[0]); + TEST_ASSERT_EQUAL_HEX8(0x1a, out[0].public_key[31]); +} + +// The owner's keys (#689, made 2026-11-23), as `firmware-release public-key` printed them: primary, then backup. +void test_the_shipped_list_trusts_the_owners_primary_and_backup_keys() { + update_session::TrustedKey out[3]; + TEST_ASSERT_EQUAL(2, release_keys::trusted(release_keys::kListed, out, 3)); + TEST_ASSERT_EQUAL_STRING("primary", out[0].id); + TEST_ASSERT_EQUAL_HEX8(0x26, out[0].public_key[0]); + TEST_ASSERT_EQUAL_HEX8(0xf8, out[0].public_key[31]); + TEST_ASSERT_EQUAL_STRING("backup", out[1].id); + TEST_ASSERT_EQUAL_HEX8(0x2e, out[1].public_key[0]); + TEST_ASSERT_EQUAL_HEX8(0xbe, out[1].public_key[31]); +} + +} // namespace + +int main() { + UNITY_BEGIN(); + RUN_TEST(test_listed_keys_become_trusted_keys_and_a_mistyped_one_is_left_out); + RUN_TEST(test_the_shipped_list_trusts_the_owners_primary_and_backup_keys); + return UNITY_END(); +} diff --git a/tools/deck-panel/test/test_update_boot/test_main.cpp b/tools/deck-panel/test/test_update_boot/test_main.cpp new file mode 100644 index 00000000..46d614d3 --- /dev/null +++ b/tools/deck-panel/test/test_update_boot/test_main.cpp @@ -0,0 +1,81 @@ +// When a new image confirms itself or rolls back (#690): on what recovery needs, never on the display feed. +#include + +#include "update_boot.h" + +using update_boot::Decision; +using update_boot::State; + +namespace { + +int decided(State s) { return static_cast(update_boot::decide(s)); } + +State trial_with_wifi() { + State s; + s.trial = true; + s.saved_wifi = true; + return s; +} + +void test_an_image_that_is_not_a_trial_does_nothing() { + State s; + s.wifi_joined = s.update_listening = true; + TEST_ASSERT_EQUAL(static_cast(Decision::nothing), decided(s)); +} + +void test_a_trial_with_wifi_joined_and_the_update_server_listening_confirms() { + State s = trial_with_wifi(); + s.wifi_joined = s.update_listening = true; + s.since_boot_ms = 9000; + TEST_ASSERT_EQUAL(static_cast(Decision::confirm), decided(s)); +} + +void test_a_trial_waits_while_either_is_missing_inside_the_trial_time() { + State joined = trial_with_wifi(); + joined.wifi_joined = true; + joined.since_boot_ms = update_boot::kTrialMs - 1; + TEST_ASSERT_EQUAL(static_cast(Decision::wait), decided(joined)); + State listening = trial_with_wifi(); + listening.update_listening = true; + TEST_ASSERT_EQUAL(static_cast(Decision::wait), decided(listening)); +} + +void test_a_trial_that_has_not_brought_recovery_up_in_time_rolls_back() { + State s = trial_with_wifi(); + s.wifi_joined = true; // joined, but no update server: a bad release couldn't be replaced + s.since_boot_ms = update_boot::kTrialMs; + TEST_ASSERT_EQUAL(static_cast(Decision::roll_back), decided(s)); +} + +// A panel with no saved Wi-Fi runs its setup network (#622): it confirms when that is up and the update server +// listens on it, since the app can reach the panel there. Joining a network isn't asked of it. +void test_a_trial_in_setup_mode_confirms_on_its_setup_network_and_the_update_server() { + State s; + s.trial = true; + s.setup_network_up = s.update_listening = true; + TEST_ASSERT_EQUAL(static_cast(Decision::confirm), decided(s)); + State down; + down.trial = true; + down.update_listening = true; + down.since_boot_ms = update_boot::kTrialMs; + TEST_ASSERT_EQUAL(static_cast(Decision::roll_back), decided(down)); +} + +void test_a_panel_with_saved_wifi_does_not_confirm_on_a_setup_network_alone() { + State s = trial_with_wifi(); + s.setup_network_up = s.update_listening = true; + TEST_ASSERT_EQUAL(static_cast(Decision::wait), decided(s)); +} + +} // namespace + +int main() { + UNITY_BEGIN(); + RUN_TEST(test_an_image_that_is_not_a_trial_does_nothing); + RUN_TEST(test_a_trial_with_wifi_joined_and_the_update_server_listening_confirms); + RUN_TEST(test_a_trial_waits_while_either_is_missing_inside_the_trial_time); + RUN_TEST(test_a_trial_that_has_not_brought_recovery_up_in_time_rolls_back); + RUN_TEST(test_a_trial_in_setup_mode_confirms_on_its_setup_network_and_the_update_server); + RUN_TEST(test_a_panel_with_saved_wifi_does_not_confirm_on_a_setup_network_alone); + return UNITY_END(); +} diff --git a/tools/deck-panel/test/test_update_floor/test_main.cpp b/tools/deck-panel/test/test_update_floor/test_main.cpp new file mode 100644 index 00000000..0fd716bf --- /dev/null +++ b/tools/deck-panel/test/test_update_floor/test_main.cpp @@ -0,0 +1,44 @@ +// The panel's floor (#690): the lowest version it takes over Wi-Fi, kept in NVS and only ever raised, once a new image +// has confirmed itself. +#include + +#include + +#include "update_floor.h" + +using update_floor::raised; + +namespace { + +void test_a_higher_pending_floor_is_kept() { + TEST_ASSERT_EQUAL_STRING("1.4.0", raised("1.2.0", "1.4.0").c_str()); + TEST_ASSERT_EQUAL_STRING("1.10.0", raised("1.9.3", "1.10.0").c_str()); // number by number, not as text +} + +void test_a_lower_pending_floor_never_lowers_it() { + TEST_ASSERT_EQUAL_STRING("1.4.0", raised("1.4.0", "1.2.0").c_str()); + TEST_ASSERT_EQUAL_STRING("1.10.0", raised("1.10.0", "1.9.9").c_str()); +} + +void test_no_floor_yet_takes_the_pending_one() { TEST_ASSERT_EQUAL_STRING("1.1.0", raised("", "1.1.0").c_str()); } + +void test_no_pending_floor_keeps_the_floor() { TEST_ASSERT_EQUAL_STRING("1.4.0", raised("1.4.0", "").c_str()); } + +// A floor that isn't a version counts every version as below it, so keeping one would refuse every update for good. +void test_a_pending_floor_that_is_not_a_version_is_never_kept() { + TEST_ASSERT_EQUAL_STRING("", raised("", "1.x").c_str()); + TEST_ASSERT_EQUAL_STRING("1.4.0", raised("1.4.0", "9.9.9 ").c_str()); + TEST_ASSERT_EQUAL_STRING("1.4.0", raised("1.4.0", "v2").c_str()); +} + +} // namespace + +int main() { + UNITY_BEGIN(); + RUN_TEST(test_a_higher_pending_floor_is_kept); + RUN_TEST(test_a_lower_pending_floor_never_lowers_it); + RUN_TEST(test_no_floor_yet_takes_the_pending_one); + RUN_TEST(test_no_pending_floor_keeps_the_floor); + RUN_TEST(test_a_pending_floor_that_is_not_a_version_is_never_kept); + return UNITY_END(); +} diff --git a/tools/deck-panel/test/test_update_link/test_main.cpp b/tools/deck-panel/test/test_update_link/test_main.cpp new file mode 100644 index 00000000..cdc06ab2 --- /dev/null +++ b/tools/deck-panel/test/test_update_link/test_main.cpp @@ -0,0 +1,237 @@ +// The update connection (#690): framed bytes in, text lines out, one connection at a time, idle timeouts. +#include + +#include +#include +#include + +#include "update_link.h" + +using namespace update_session; +using update_link::Link; +using update_link::Out; + +namespace { + +bool fake_verify(const uint8_t key[32], const uint8_t*, size_t, const uint8_t signature[64]) { return signature[0] == key[0]; } + +const TrustedKey kKeys[] = {{"primary", {0x11}}}; + +class FakeHasher : public Hasher { + public: + void start() override { sum_ = 0; } + void update(const uint8_t* data, size_t length) override { for (size_t i = 0; i < length; ++i) sum_ += data[i]; } + void finish(uint8_t out[32]) override { std::memset(out, 0, 32); out[0] = static_cast(sum_); } + private: + unsigned sum_ = 0; +}; + +class FakeSlot : public Slot { + public: + uint32_t capacity() const override { return 6553600; } + bool begin(uint32_t) override { begun = true; return true; } + bool write(const uint8_t* data, size_t length) override { written.insert(written.end(), data, data + length); return true; } + bool end() override { return true; } + bool set_boot() override { boot = true; return true; } + void abort() override { aborted = true; } + bool begun = false, boot = false, aborted = false; + std::vector written; +}; + +const std::string kManifest = std::string("{\"format\": 1, \"key\": \"primary\", \"lowest_allowed\": {\"deck-panel\": \"1.0.0\"}, ") + + "\"files\": [{\"device\": \"deck-panel\", \"name\": \"p.bin\", \"version\": \"1.1.0\", \"size\": 4, \"sha256\": \"0a" + + std::string(62, '0') + "\"}]}"; + +std::vector frame(char type, const std::vector& payload) { + std::vector out{static_cast(type)}; + const uint32_t n = static_cast(payload.size()); + for (int i = 0; i < 4; ++i) out.push_back(static_cast(n >> (8 * i))); + out.insert(out.end(), payload.begin(), payload.end()); + return out; +} + +std::vector whole_update() { + std::vector bytes = frame('M', std::vector(kManifest.begin(), kManifest.end())); + std::vector signature(64, 0); + signature[0] = 0x11; + for (const auto& f : {frame('S', signature), frame('I', {1, 2, 3, 4}), frame('D', {})}) bytes.insert(bytes.end(), f.begin(), f.end()); + return bytes; +} + +struct Panel { + FakeHasher hasher; + FakeSlot slot; + Link link{Config{kKeys, 1, fake_verify, &hasher, &slot, "1.0.0"}}; +}; + +std::vector lines_of(const std::vector& outs) { + std::vector all; + for (const auto& out : outs) all.insert(all.end(), out.lines.begin(), out.lines.end()); + return all; +} + +void test_a_whole_update_in_one_go_switches_and_asks_for_a_restart() { + Panel panel; + Out out; + TEST_ASSERT_TRUE(panel.link.accept(1, 0, out)); + const auto bytes = whole_update(); + out = panel.link.received(1, bytes.data(), bytes.size(), 10); + const std::vector expected{"ok manifest", "progress 4", "ok switched 1.1.0"}; + TEST_ASSERT_EQUAL(expected.size(), out.lines.size()); + for (size_t i = 0; i < expected.size(); ++i) TEST_ASSERT_EQUAL_STRING(expected[i].c_str(), out.lines[i].c_str()); + TEST_ASSERT_TRUE(out.close); + TEST_ASSERT_TRUE(out.reboot); + TEST_ASSERT_EQUAL_STRING("1.0.0", out.floor.c_str()); +} + +void test_the_same_update_a_byte_at_a_time_gives_the_same_lines() { + Panel panel; + Out out; + panel.link.accept(1, 0, out); + std::vector outs; + for (uint8_t byte : whole_update()) outs.push_back(panel.link.received(1, &byte, 1, 10)); + const auto all = lines_of(outs); + TEST_ASSERT_EQUAL(3, all.size()); + TEST_ASSERT_EQUAL_STRING("ok switched 1.1.0", all.back().c_str()); + TEST_ASSERT_TRUE(outs.back().reboot); +} + +Out connected_and_sent(Panel& panel, const std::vector& bytes) { + Out out; + panel.link.accept(1, 0, out); + return panel.link.received(1, bytes.data(), bytes.size(), 10); +} + +void expect_refused(const Out& out, const char* expected) { + TEST_ASSERT_EQUAL(1, out.lines.size()); + TEST_ASSERT_EQUAL_STRING(expected, out.lines[0].c_str()); + TEST_ASSERT_TRUE(out.close); + TEST_ASSERT_FALSE(out.reboot); +} + +// The caps are checked from the frame's header, before its bytes are kept: no one can make the panel buffer more. +void test_a_manifest_frame_over_the_cap_is_refused_from_its_header() { + Panel panel; + std::vector header{'M', 0, 0, 0, 0}; + const uint32_t n = update_link::kMaxManifest + 1; + for (int i = 0; i < 4; ++i) header[1 + i] = static_cast(n >> (8 * i)); + expect_refused(connected_and_sent(panel, header), "refused too-large"); +} + +void test_an_image_chunk_over_the_cap_is_refused_and_nothing_is_written() { + Panel panel; + auto bytes = whole_update(); + bytes.resize(bytes.size() - 2 * 5 - 4); // up to the signature: then a chunk over the cap + std::vector header{'I', 0, 0, 0, 0}; + const uint32_t n = update_link::kMaxChunk + 1; + for (int i = 0; i < 4; ++i) header[1 + i] = static_cast(n >> (8 * i)); + bytes.insert(bytes.end(), header.begin(), header.end()); + Out out; + panel.link.accept(1, 0, out); + out = panel.link.received(1, bytes.data(), bytes.size(), 10); + TEST_ASSERT_EQUAL_STRING("refused too-large", out.lines.back().c_str()); + TEST_ASSERT_TRUE(panel.slot.written.empty()); + TEST_ASSERT_TRUE(panel.slot.aborted); +} + +void test_a_signature_frame_that_is_not_64_bytes_is_refused() { + Panel panel; + auto bytes = frame('M', std::vector(kManifest.begin(), kManifest.end())); + const auto signature = frame('S', std::vector(65, 0x11)); + bytes.insert(bytes.end(), signature.begin(), signature.end()); + expect_refused(connected_and_sent(panel, bytes), "refused too-large"); +} + +void test_a_frame_of_an_unknown_type_is_refused() { + Panel panel; + expect_refused(connected_and_sent(panel, frame('X', {1})), "refused no-manifest"); +} + +// One update at a time: a second sender is told "busy" and closed, and the first carries on. +void test_a_second_sender_is_refused_busy_while_one_runs() { + Panel panel; + Out out; + panel.link.accept(1, 0, out); + Out second; + TEST_ASSERT_FALSE(panel.link.accept(2, 5, second)); + TEST_ASSERT_EQUAL_STRING("refused busy", second.lines[0].c_str()); + TEST_ASSERT_TRUE(second.close); + const auto bytes = whole_update(); + TEST_ASSERT_TRUE(panel.link.received(1, bytes.data(), bytes.size(), 10).reboot); +} + +// A connection that sends nothing (or no manifest) is dropped quickly, so a stray one can't hold "busy". +void test_a_connection_idle_before_its_manifest_times_out_quickly() { + Panel panel; + Out out; + panel.link.accept(1, 0, out); + TEST_ASSERT_TRUE(panel.link.tick(update_link::kIdleBeforeManifestMs - 1).lines.empty()); + const Out late = panel.link.tick(update_link::kIdleBeforeManifestMs); + TEST_ASSERT_EQUAL_STRING("refused timeout", late.lines[0].c_str()); + TEST_ASSERT_TRUE(late.close); + Out next; + TEST_ASSERT_TRUE(panel.link.accept(2, update_link::kIdleBeforeManifestMs + 1, next)); +} + +// Mid-image the link gets longer, but a stalled transfer still ends with nothing switched. +void test_a_transfer_that_stalls_mid_image_times_out_and_nothing_is_switched() { + Panel panel; + auto bytes = whole_update(); + bytes.resize(bytes.size() - 5 - 2); // through the signature and half the image chunk + Out out; + panel.link.accept(1, 0, out); + panel.link.received(1, bytes.data(), bytes.size(), 100); + TEST_ASSERT_TRUE(panel.link.tick(100 + update_link::kIdleBeforeManifestMs).lines.empty()); + const Out late = panel.link.tick(100 + update_link::kIdleMidImageMs); + TEST_ASSERT_EQUAL_STRING("refused timeout", late.lines[0].c_str()); + TEST_ASSERT_TRUE(panel.slot.aborted); + TEST_ASSERT_FALSE(panel.slot.boot); +} + +// The sender going away mid-image (a dropped link, power off at the Mac) leaves the old firmware. +void test_a_connection_closed_mid_image_leaves_nothing_switched_and_frees_the_link() { + Panel panel; + auto bytes = whole_update(); + bytes.resize(bytes.size() - 5 - 2); + Out out; + panel.link.accept(1, 0, out); + panel.link.received(1, bytes.data(), bytes.size(), 100); + panel.link.closed(1); + TEST_ASSERT_TRUE(panel.slot.aborted); + TEST_ASSERT_FALSE(panel.slot.boot); + TEST_ASSERT_TRUE(panel.link.accept(2, 200, out)); +} + +// The board erases the slot inside the signature frame's received() (seconds, for a big image), and only then sends +// "ok manifest". It then passes a zero-length read stamped after the erase: the idle clock runs from there, not from +// before the erase, so the sender isn't timed out for the panel's own work. +void test_a_zero_length_read_restarts_the_idle_clock() { + Panel panel; + auto bytes = whole_update(); + bytes.resize(bytes.size() - 5 - 2); + Out out; + panel.link.accept(1, 0, out); + panel.link.received(1, bytes.data(), bytes.size(), 100); + const uint32_t erased = 100 + 9000; + TEST_ASSERT_TRUE(panel.link.received(1, bytes.data(), 0, erased).lines.empty()); + TEST_ASSERT_TRUE(panel.link.tick(100 + update_link::kIdleMidImageMs).lines.empty()); + TEST_ASSERT_EQUAL_STRING("refused timeout", panel.link.tick(erased + update_link::kIdleMidImageMs).lines[0].c_str()); +} + +} // namespace + +int main() { + UNITY_BEGIN(); + RUN_TEST(test_a_whole_update_in_one_go_switches_and_asks_for_a_restart); + RUN_TEST(test_the_same_update_a_byte_at_a_time_gives_the_same_lines); + RUN_TEST(test_a_manifest_frame_over_the_cap_is_refused_from_its_header); + RUN_TEST(test_an_image_chunk_over_the_cap_is_refused_and_nothing_is_written); + RUN_TEST(test_a_signature_frame_that_is_not_64_bytes_is_refused); + RUN_TEST(test_a_frame_of_an_unknown_type_is_refused); + RUN_TEST(test_a_second_sender_is_refused_busy_while_one_runs); + RUN_TEST(test_a_connection_idle_before_its_manifest_times_out_quickly); + RUN_TEST(test_a_transfer_that_stalls_mid_image_times_out_and_nothing_is_switched); + RUN_TEST(test_a_connection_closed_mid_image_leaves_nothing_switched_and_frees_the_link); + RUN_TEST(test_a_zero_length_read_restarts_the_idle_clock); + return UNITY_END(); +} diff --git a/tools/deck-panel/test/test_update_manifest/test_main.cpp b/tools/deck-panel/test/test_update_manifest/test_main.cpp new file mode 100644 index 00000000..eb77048d --- /dev/null +++ b/tools/deck-panel/test/test_update_manifest/test_main.cpp @@ -0,0 +1,103 @@ +// The panel's reading of a signed release manifest (#690, ADR 0012), in the shape the updater's signer writes +// (ReleaseSigner, #689: JSONSerialization, pretty-printed, sorted keys). +#include + +#include +#include + +#include "update_manifest.h" + +namespace { + +const char* const kSigned = R"({ + "catalog" : { + "lc6000" : [], + "panel" : [ { "image" : "deck-panel-1.1.0-1d0683f.bin", "sha" : "1d0683f", "version" : "1.1.0" } ] + }, + "files" : [ + { + "device" : "lc6000-wd", + "name" : "wd-00.50-show-slot-16.patch", + "sha256" : "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff", + "size" : 554, + "version" : "00.50" + }, + { + "device" : "deck-panel", + "name" : "deck-panel-1.1.0-1d0683f.bin", + "sha256" : "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08", + "size" : 1761280, + "version" : "1.1.0" + } + ], + "format" : 1, + "key" : "primary", + "lowest_allowed" : { + "deck-panel" : "1.0.5" + } +})"; + +update_manifest::Manifest parsed(const char* text) { + update_manifest::Manifest manifest; + TEST_ASSERT_TRUE(update_manifest::parse(text, std::strlen(text), manifest)); + return manifest; +} + +void test_the_panels_image_and_the_rules_are_read_from_a_signed_manifest() { + const auto manifest = parsed(kSigned); + TEST_ASSERT_EQUAL(1, manifest.format); + TEST_ASSERT_EQUAL_STRING("primary", manifest.key.c_str()); + TEST_ASSERT_EQUAL_STRING("1.0.5", manifest.lowest_allowed.c_str()); + TEST_ASSERT_TRUE(manifest.has_image); + TEST_ASSERT_EQUAL_STRING("deck-panel-1.1.0-1d0683f.bin", manifest.image.name.c_str()); + TEST_ASSERT_EQUAL_STRING("1.1.0", manifest.image.version.c_str()); + TEST_ASSERT_EQUAL_UINT32(1761280, manifest.image.size); + const uint8_t first[4] = {0x9f, 0x86, 0xd0, 0x81}; + TEST_ASSERT_EQUAL_HEX8_ARRAY(first, manifest.image.sha256, 4); + TEST_ASSERT_EQUAL_HEX8(0x08, manifest.image.sha256[31]); +} + +bool reads(const std::string& text) { + update_manifest::Manifest manifest; + return update_manifest::parse(text.data(), text.size(), manifest); +} + +std::string with(const std::string& from, const std::string& to) { + std::string text = kSigned; + text.replace(text.find(from), from.size(), to); + return text; +} + +// Nothing here is trusted yet when `key` is read: any input, cut short or built to hurt, is just "not a manifest". +void test_anything_but_a_well_formed_manifest_is_not_read() { + const std::string whole = kSigned; + for (size_t cut = 0; cut < whole.size(); cut += 7) TEST_ASSERT_FALSE(reads(whole.substr(0, cut))); + TEST_ASSERT_FALSE(reads(whole + "x")); + TEST_ASSERT_FALSE(reads("[]")); + TEST_ASSERT_FALSE(reads(with("\"lc6000\" : []", "\"lc6000\" : " + std::string(40, '[') + std::string(40, ']')))); + TEST_ASSERT_FALSE(reads(with("\"size\" : 1761280", "\"size\" : 99999999999"))); + TEST_ASSERT_FALSE(reads(with("9f86d081884c", "9f86d081884"))); // a hash one digit short + TEST_ASSERT_FALSE(reads(with("\"size\" : 1761280", "\"size\" : \"1761280\""))); +} + +void test_two_deck_panel_images_in_one_manifest_are_not_read() { + TEST_ASSERT_FALSE(reads(with("\"device\" : \"lc6000-wd\"", "\"device\" : \"deck-panel\""))); +} + +void test_a_manifest_with_no_panel_image_reads_with_none() { + std::string text = with("\"device\" : \"deck-panel\"", "\"device\" : \"lc6000-tp\""); + update_manifest::Manifest manifest; + TEST_ASSERT_TRUE(update_manifest::parse(text.data(), text.size(), manifest)); + TEST_ASSERT_FALSE(manifest.has_image); +} + +} // namespace + +int main() { + UNITY_BEGIN(); + RUN_TEST(test_the_panels_image_and_the_rules_are_read_from_a_signed_manifest); + RUN_TEST(test_anything_but_a_well_formed_manifest_is_not_read); + RUN_TEST(test_two_deck_panel_images_in_one_manifest_are_not_read); + RUN_TEST(test_a_manifest_with_no_panel_image_reads_with_none); + return UNITY_END(); +} diff --git a/tools/deck-panel/test/test_update_session/test_main.cpp b/tools/deck-panel/test/test_update_session/test_main.cpp new file mode 100644 index 00000000..df2c6735 --- /dev/null +++ b/tools/deck-panel/test/test_update_session/test_main.cpp @@ -0,0 +1,244 @@ +// One update over Wi-Fi (#690), driven frame by frame with a fake signature check, hash and slot. +#include + +#include +#include +#include + +#include "update_session.h" + +using namespace update_session; + +namespace { + +// The fake signature check: a signature is "valid" when it is the key's first byte, then the message length, then 0s. +bool fake_verify(const uint8_t key[32], const uint8_t*, size_t length, const uint8_t signature[64]) { + return signature[0] == key[0] && signature[1] == static_cast(length); +} + +std::vector signed_by(uint8_t key_first, size_t length) { + std::vector signature(64, 0); + signature[0] = key_first; + signature[1] = static_cast(length); + return signature; +} + +const TrustedKey kKeys[] = {{"primary", {0x11}}, {"backup", {0x22}}}; + +class FakeHasher : public Hasher { + public: + void start() override { sum_ = 0; } + void update(const uint8_t* data, size_t length) override { for (size_t i = 0; i < length; ++i) sum_ += data[i]; } + void finish(uint8_t out[32]) override { std::memset(out, 0, 32); out[0] = static_cast(sum_); } + private: + unsigned sum_ = 0; +}; + +class FakeSlot : public Slot { + public: + uint32_t capacity() const override { return 6553600; } + bool begin(uint32_t size) override { begun = true; erased = size; return true; } + bool write(const uint8_t* data, size_t length) override { written.insert(written.end(), data, data + length); return true; } + bool end() override { ended = true; return true; } + bool set_boot() override { boot = true; return true; } + void abort() override { aborted = true; } + bool begun = false, ended = false, boot = false, aborted = false; + uint32_t erased = 0; + std::vector written; +}; + +std::string manifest_text(const char* key = "primary", const char* version = "1.1.0", uint32_t size = 4, + const char* lowest = "1.0.0", int format = 1) { + // The fake hash of {1, 2, 3, 4} is 10: 0a, then 31 zero bytes. + return std::string("{\"format\": ") + std::to_string(format) + ", \"key\": \"" + key + + "\", \"lowest_allowed\": {\"deck-panel\": \"" + lowest + + "\"}, \"files\": [{\"device\": \"deck-panel\", \"name\": \"p.bin\", \"version\": \"" + version + + "\", \"size\": " + std::to_string(size) + ", \"sha256\": \"0a" + std::string(62, '0') + "\"}]}"; +} + +struct Panel { + explicit Panel(const char* floor = "1.0.0") : session(Config{kKeys, 2, fake_verify, &hasher, &slot, floor}) {} + FakeHasher hasher; + FakeSlot slot; + Session session; + + Reply send_manifest(const std::string& text, uint8_t key_first) { + Reply first = session.manifest(reinterpret_cast(text.data()), text.size()); + if (first.kind == Reply::refused) return first; + const auto signature = signed_by(key_first, text.size()); + return session.signature(signature.data(), signature.size()); + } +}; + +void test_a_manifest_signed_by_a_trusted_key_is_taken() { + Panel panel; + TEST_ASSERT_EQUAL(Reply::ok_manifest, panel.send_manifest(manifest_text(), 0x11).kind); +} + +void test_the_backup_key_is_trusted_too() { + Panel panel; + TEST_ASSERT_EQUAL(Reply::ok_manifest, panel.send_manifest(manifest_text("backup"), 0x22).kind); +} + +void test_a_manifest_naming_a_key_the_panel_does_not_trust_is_refused_and_the_slot_untouched() { + Panel panel; + const Reply reply = panel.send_manifest(manifest_text("someone-else"), 0x11); + TEST_ASSERT_EQUAL(Reply::refused, reply.kind); + TEST_ASSERT_EQUAL(static_cast(Refusal::unknown_key), static_cast(reply.refusal)); + TEST_ASSERT_FALSE(panel.slot.begun); +} + +void test_a_bad_signature_is_refused_and_the_slot_untouched() { + Panel panel; + const Reply reply = panel.send_manifest(manifest_text(), 0x22); // the backup's signature, claiming the primary + TEST_ASSERT_EQUAL(static_cast(Refusal::bad_signature), static_cast(reply.refusal)); + TEST_ASSERT_FALSE(panel.slot.begun); +} + +const uint8_t kImage[] = {1, 2, 3, 4}; + +// Nothing reaches the slot unless a signed manifest came first: image bytes, "done" or a lone signature are refused. +void test_image_bytes_before_a_signed_manifest_are_refused_and_never_written() { + Panel panel; + TEST_ASSERT_EQUAL(static_cast(Refusal::no_manifest), static_cast(panel.session.chunk(kImage, 4).refusal)); + TEST_ASSERT_FALSE(panel.slot.begun); + TEST_ASSERT_TRUE(panel.slot.written.empty()); +} + +void test_done_or_a_signature_before_a_manifest_is_refused() { + Panel a; + TEST_ASSERT_EQUAL(static_cast(Refusal::no_manifest), static_cast(a.session.done().refusal)); + Panel b; + const auto signature = signed_by(0x11, 0); + TEST_ASSERT_EQUAL(static_cast(Refusal::no_manifest), static_cast(b.session.signature(signature.data(), 64).refusal)); + TEST_ASSERT_FALSE(a.slot.begun || b.slot.begun); +} + +void test_image_bytes_after_a_refused_manifest_are_refused_too() { + Panel panel; + panel.send_manifest(manifest_text(), 0x22); + TEST_ASSERT_EQUAL(static_cast(Refusal::no_manifest), static_cast(panel.session.chunk(kImage, 4).refusal)); + TEST_ASSERT_TRUE(panel.slot.written.empty()); +} + +void test_an_image_matching_the_manifest_is_written_and_set_to_boot() { + Panel panel; + panel.send_manifest(manifest_text(), 0x11); + TEST_ASSERT_TRUE(panel.slot.begun); + TEST_ASSERT_EQUAL_UINT32(4, panel.slot.erased); // only the image's own size is erased + const Reply first = panel.session.chunk(kImage, 3); + TEST_ASSERT_EQUAL(Reply::progress, first.kind); + TEST_ASSERT_EQUAL_UINT32(3, first.bytes); + TEST_ASSERT_EQUAL_UINT32(4, panel.session.chunk(kImage + 3, 1).bytes); + const Reply last = panel.session.done(); + TEST_ASSERT_EQUAL(Reply::switched, last.kind); + TEST_ASSERT_EQUAL_STRING("1.1.0", last.version.c_str()); + TEST_ASSERT_EQUAL_UINT8_ARRAY(kImage, panel.slot.written.data(), 4); + TEST_ASSERT_TRUE(panel.slot.ended); + TEST_ASSERT_TRUE(panel.slot.boot); +} + +void expect_mismatch(Panel& panel, const Reply& reply) { + TEST_ASSERT_EQUAL(static_cast(Refusal::mismatch), static_cast(reply.refusal)); + TEST_ASSERT_TRUE(panel.slot.aborted); + TEST_ASSERT_FALSE(panel.slot.boot); +} + +void test_an_altered_image_is_refused_and_never_booted() { + Panel panel; + panel.send_manifest(manifest_text(), 0x11); + const uint8_t altered[] = {1, 2, 3, 5}; + panel.session.chunk(altered, 4); + expect_mismatch(panel, panel.session.done()); +} + +void test_an_image_cut_short_is_refused_and_never_booted() { + Panel panel; + panel.send_manifest(manifest_text(), 0x11); + panel.session.chunk(kImage, 3); + expect_mismatch(panel, panel.session.done()); +} + +void test_an_image_longer_than_the_manifest_says_is_refused_at_the_first_extra_byte() { + Panel panel; + panel.send_manifest(manifest_text(), 0x11); + panel.session.chunk(kImage, 4); + const uint8_t extra = 0; + expect_mismatch(panel, panel.session.chunk(&extra, 1)); + TEST_ASSERT_EQUAL(4, panel.slot.written.size()); +} + +void expect_refused_untouched(Panel& panel, const std::string& manifest, Refusal why) { + const Reply reply = panel.send_manifest(manifest, 0x11); + TEST_ASSERT_EQUAL(static_cast(why), static_cast(reply.refusal)); + TEST_ASSERT_FALSE(panel.slot.begun); +} + +// ADR 0012: an image below the panel's floor (kept in NVS, only ever raised) or the manifest's lowest allowed +// version is refused, so a validly signed old image can't be sent back after a security fix. +void test_an_image_below_the_panels_floor_is_refused() { + Panel panel("1.5.0"); + expect_refused_untouched(panel, manifest_text("primary", "1.4.9"), Refusal::too_old); +} + +void test_an_image_below_the_manifests_own_lowest_allowed_version_is_refused() { + Panel panel; + expect_refused_untouched(panel, manifest_text("primary", "1.1.0", 4, "1.2.0"), Refusal::too_old); +} + +void test_an_image_at_the_floor_is_taken_and_versions_compare_by_number() { + Panel at("1.10.0"); + TEST_ASSERT_EQUAL(Reply::ok_manifest, at.send_manifest(manifest_text("primary", "1.10.0"), 0x11).kind); + Panel below("1.10.0"); + expect_refused_untouched(below, manifest_text("primary", "1.9.99"), Refusal::too_old); +} + +void test_a_manifest_in_another_format_or_without_a_panel_image_is_refused() { + Panel a; + expect_refused_untouched(a, manifest_text("primary", "1.1.0", 4, "1.0.0", 2), Refusal::unknown_format); + std::string lc6000_only = manifest_text(); + lc6000_only.replace(lc6000_only.find("deck-panel\", \"name"), 10, "lc6000-wd"); + Panel b; + expect_refused_untouched(b, lc6000_only, Refusal::no_image); +} + +void test_an_image_bigger_than_the_spare_slot_is_refused() { + Panel panel; + expect_refused_untouched(panel, manifest_text("primary", "1.1.0", 6553601), Refusal::too_big); +} + +// The floor only ever rises: the switched reply says what to keep once the new image has confirmed itself. +void test_a_switch_names_the_floor_to_keep_once_confirmed() { + Panel raised("1.0.0"); + raised.send_manifest(manifest_text("primary", "1.3.0", 4, "1.2.0"), 0x11); + raised.session.chunk(kImage, 4); + TEST_ASSERT_EQUAL_STRING("1.2.0", raised.session.done().floor.c_str()); + Panel kept("1.5.0"); + kept.send_manifest(manifest_text("primary", "1.6.0", 4, "1.2.0"), 0x11); + kept.session.chunk(kImage, 4); + TEST_ASSERT_EQUAL_STRING("1.5.0", kept.session.done().floor.c_str()); +} + +} // namespace + +int main() { + UNITY_BEGIN(); + RUN_TEST(test_a_manifest_signed_by_a_trusted_key_is_taken); + RUN_TEST(test_the_backup_key_is_trusted_too); + RUN_TEST(test_a_manifest_naming_a_key_the_panel_does_not_trust_is_refused_and_the_slot_untouched); + RUN_TEST(test_a_bad_signature_is_refused_and_the_slot_untouched); + RUN_TEST(test_image_bytes_before_a_signed_manifest_are_refused_and_never_written); + RUN_TEST(test_done_or_a_signature_before_a_manifest_is_refused); + RUN_TEST(test_image_bytes_after_a_refused_manifest_are_refused_too); + RUN_TEST(test_an_image_matching_the_manifest_is_written_and_set_to_boot); + RUN_TEST(test_an_altered_image_is_refused_and_never_booted); + RUN_TEST(test_an_image_cut_short_is_refused_and_never_booted); + RUN_TEST(test_an_image_longer_than_the_manifest_says_is_refused_at_the_first_extra_byte); + RUN_TEST(test_an_image_below_the_panels_floor_is_refused); + RUN_TEST(test_an_image_below_the_manifests_own_lowest_allowed_version_is_refused); + RUN_TEST(test_an_image_at_the_floor_is_taken_and_versions_compare_by_number); + RUN_TEST(test_a_manifest_in_another_format_or_without_a_panel_image_is_refused); + RUN_TEST(test_an_image_bigger_than_the_spare_slot_is_refused); + RUN_TEST(test_a_switch_names_the_floor_to_keep_once_confirmed); + return UNITY_END(); +} diff --git a/tools/deck-panel/test_release_keys.py b/tools/deck-panel/test_release_keys.py new file mode 100644 index 00000000..5905f5b2 --- /dev/null +++ b/tools/deck-panel/test_release_keys.py @@ -0,0 +1,40 @@ +"""The deck panel trusts exactly the release keys the updater app trusts (#690, ADR 0012): the panel's list in +lib/release_keys/release_keys.h and the app's in ReleaseKeys.swift must hold the same (id, public key) pairs, so a +release the app accepts is one the panel accepts too. Both hold the owner's primary and backup keys (#689).""" +import pathlib +import re +import unittest + +ROOT = pathlib.Path(__file__).resolve().parents[2] +PANEL = ROOT / "tools/deck-panel/lib/release_keys/release_keys.h" +APP = ROOT / "Packages/FirmwareUpdaterKit/Sources/FirmwareRelease/ReleaseKeys.swift" +PAIR = re.compile(r'\(\s*"(primary|backup)"\s*,\s*"([0-9a-f]{64})"\s*\)|\{\s*"(primary|backup)"\s*,\s*"([0-9a-f]{64})"\s*\}') + + +def pairs(path): + found = [] + for match in PAIR.finditer(path.read_text()): + id_, key = (match.group(1), match.group(2)) if match.group(1) else (match.group(3), match.group(4)) + found.append((id_, key)) + return sorted(found) + + +class ReleaseKeys(unittest.TestCase): + def test_the_panel_and_the_app_trust_the_same_keys(self): + self.assertEqual(pairs(PANEL), pairs(APP)) + + def test_the_pattern_reads_both_spellings(self): + # So an entry can't hide from the comparison by its form. + self.assertEqual(pairs_of('("primary", "' + "ab" * 32 + '")'), [("primary", "ab" * 32)]) + self.assertEqual(pairs_of('{"backup", "' + "cd" * 32 + '"}'), [("backup", "cd" * 32)]) + + +def pairs_of(text): + import tempfile + with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as f: + f.write(text) + return pairs(pathlib.Path(f.name)) + + +if __name__ == "__main__": + unittest.main()