diff --git a/PulseShift/src/ble_manager.cpp b/PulseShift/src/ble_manager.cpp index 0d38f9c..8eadbf2 100644 --- a/PulseShift/src/ble_manager.cpp +++ b/PulseShift/src/ble_manager.cpp @@ -338,6 +338,7 @@ void BleManager::updateCapabilitiesChar() { BLE_FEAT_STARTUP_LOOP; if (dualSlotDetected && PULSESHIFT_OTA_ENABLED) { featureMask |= BLE_FEAT_OTA_UPDATE; + if (OtaManager::instance().hasOfficialOtaLayout()) featureMask |= BLE_FEAT_OFFICIAL_OTA_LAYOUT; } caps.featureMask = featureMask; caps.currentRevision = ConfigManager::instance().activeRevision(); diff --git a/PulseShift/src/ble_protocol.h b/PulseShift/src/ble_protocol.h index 5c304ff..fbe3c70 100644 --- a/PulseShift/src/ble_protocol.h +++ b/PulseShift/src/ble_protocol.h @@ -117,7 +117,7 @@ struct BleLogChunkPacket { // Firmware version reported in the Capabilities packet. #define PULSESHIFT_FW_VERSION_MAJOR 2 #define PULSESHIFT_FW_VERSION_MINOR 6 -#define PULSESHIFT_FW_VERSION_PATCH 1 +#define PULSESHIFT_FW_VERSION_PATCH 3 // Configuration Opcodes enum BleConfigOpcode : uint8_t { @@ -244,7 +244,8 @@ enum BleFeatureMaskBits : uint32_t { BLE_FEAT_VERIFIED_SAVE = (1u << 22), // SAVE_CONFIG may include expected revision BLE_FEAT_LIGHTING_SETUP = (1u << 23), // Versioned strip/RPM/animation extension BLE_FEAT_IDLE_ANIMATION = (1u << 24), // Idle enablement and RPM thresholds in lighting setup v2 - BLE_FEAT_STARTUP_LOOP = (1u << 25) // Idle enablement repeats the selected startup animation + BLE_FEAT_STARTUP_LOOP = (1u << 25), // Idle enablement repeats the selected startup animation + BLE_FEAT_OFFICIAL_OTA_LAYOUT = (1u << 26) // Verified ESP32 DevKit V1 4 MiB dual-slot layout }; // BLE_RPM packet extended flags usage (schema 3): Bit 1 additionally requires diff --git a/PulseShift/src/ota_manager.cpp b/PulseShift/src/ota_manager.cpp index b2ad316..d72e151 100644 --- a/PulseShift/src/ota_manager.cpp +++ b/PulseShift/src/ota_manager.cpp @@ -4,6 +4,8 @@ #include #if defined(ARDUINO) +#include +#include #include #include #include @@ -232,6 +234,26 @@ bool OtaManager::isDualSlotSupported() const { #endif } +bool OtaManager::hasOfficialOtaLayout() const { +#if defined(ARDUINO) && defined(CONFIG_IDF_TARGET_ESP32) + uint32_t flashSize = 0; + if (esp_flash_get_size(nullptr, &flashSize) != ESP_OK || flashSize != 0x400000) return false; + auto matches = [](esp_partition_type_t type, esp_partition_subtype_t subtype, + const char* label, uint32_t address, uint32_t size) { + const auto* part = esp_partition_find_first(type, subtype, label); + return part && part->address == address && part->size == size; + }; + return matches(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_0, "app0", 0x10000, 0x140000) && + matches(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_1, "app1", 0x150000, 0x140000) && + matches(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_NVS, "nvs", 0x9000, 0x5000) && + matches(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_OTA, "otadata", 0xE000, 0x2000) && + matches(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_SPIFFS, "spiffs", 0x290000, 0x160000) && + matches(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_COREDUMP, "coredump", 0x3F0000, 0x10000); +#else + return false; +#endif +} + bool OtaManager::readRunningImageDigest(uint8_t out[32]) { if (!runningImageDigestValid_) { #if defined(ARDUINO) diff --git a/PulseShift/src/ota_manager.h b/PulseShift/src/ota_manager.h index b570e1a..7d68b0f 100644 --- a/PulseShift/src/ota_manager.h +++ b/PulseShift/src/ota_manager.h @@ -84,6 +84,7 @@ class OtaManager { // Query whether rollback is possible from hardware bootloader state bool isRollbackPossible() const; bool isDualSlotSupported() const; + bool hasOfficialOtaLayout() const; bool readRunningImageDigest(uint8_t out[32]); bool rollbackConfirmed() const { return rollbackConfirmed_; } diff --git a/docs/OTA-BENCH-TEST-PLAN.md b/docs/OTA-BENCH-TEST-PLAN.md index b0bfc5a..4167c7e 100644 --- a/docs/OTA-BENCH-TEST-PLAN.md +++ b/docs/OTA-BENCH-TEST-PLAN.md @@ -1,4 +1,4 @@ -# PulseShift v2.3.0 OTA Bench-Test Plan and Hardware Verification +# PulseShift OTA bench test and hardware verification This document defines the comprehensive hardware bench-test procedure for validating over-the-air (OTA) firmware updates, cryptographic authenticity, automatic bootloader rollback, and emergency recovery on physical ESP32 DevKit V1 hardware. @@ -53,24 +53,8 @@ The PulseShift OTA pipeline enforces cryptographic image authenticity using NIST ### 2.2 Compilation and Signing Workflow 1. Compile and verify the firmware with the [protected build entry point](WINDOWS-BUILD.md). Bootloader and partition files are build evidence for an application-only update. -2. Sign the binary and attach the 76-byte `PSOT` authentication trailer: - ```bash - uv run --with cryptography python tools/sign_firmware.py sign \ - --input D:\Development\PulseShift-Firmware\build\esp32.esp32.esp32doit-devkit-v1\PulseShift.ino.bin \ - --key tools/keys/pulseshift_ota_key.pem \ - --output PulseShift_signed.bin - ``` -3. Verify the signature locally before transmission: - ```bash - uv run --with cryptography python tools/sign_firmware.py verify \ - --input PulseShift_signed.bin \ - --public-key tools/keys/pulseshift_ota_key.pem - # Note: --key is also accepted as a convenience alias. - # You may also verify directly against the uncompressed SEC1 hex string from ota_public_key.h: - uv run --with cryptography python tools/sign_firmware.py verify \ - --input PulseShift_signed.bin \ - --public-key 040072cffa71b451afe19b5472fe56220653ceb6ae1b534459f7be14ddc6939336cb0ea85068b48c51fda40f3af4725473085b51f1c4b1660e017fd1073ed1e13a - ``` +2. Use [the stable OTA release procedure](OTA-RELEASES.md) to sign the application from `build/esp32-3.3.12/production/PulseShift.ino.bin` or the CI signing-input artifact with the original key. +3. Run the release verifier before transmission. It checks the manifest signature, the package hash and size, and the application's 76-byte `PSOT` signature against the public trust anchor. Use the verified `PulseShift.signed.bin` for both the online update bench test and the manual signed-file test. --- @@ -79,7 +63,7 @@ The PulseShift OTA pipeline enforces cryptographic image authenticity using NIST ### Scenario 1: Complete Valid Image Transfer and Boot Confirmation - **Objective:** Verify normal, end-to-end OTA update over BLE with MTU negotiation, signature validation, and clean boot. - **Steps:** - 1. Boot ESP32 into `app0` (firmware v2.3.0). Confirm serial shows active BLE advertising. + 1. Boot the ESP32 into an already-confirmed baseline image. The steps below use `app0` as the example baseline and `app1` as the update slot. Confirm serial shows active BLE advertising. 2. Open Android companion app and connect to PulseShift. 3. Record the actual negotiated MTU. Android uses up to 230 data bytes per chunk with a large MTU, and 11 data bytes at the baseline MTU. diff --git a/docs/OTA-RELEASES.md b/docs/OTA-RELEASES.md new file mode 100644 index 0000000..89018ed --- /dev/null +++ b/docs/OTA-RELEASES.md @@ -0,0 +1,33 @@ +# Stable OTA releases + +The Android updater checks published stable releases in `iamaritrasaha/PulseShift`. Each compatible release has three assets: + +- `PulseShift.signed.bin` is the application and its existing PSOT signature trailer. +- `PulseShift-ota.json` is the release manifest with the version, notes, source commit, package byte count and SHA-256 digest. It identifies the ESP32 DevKit V1 with 4 MiB flash and the verified dual 1,280 KiB application partition layout. +- `PulseShift-ota.json.sig` is the detached DER-encoded P-256 signature over `PulseShift OTA manifest v1`, a NUL byte, and the exact manifest bytes. It uses the installed OTA trust anchor. + +## Prepare and accept a candidate + +1. Run **Prepare firmware OTA candidate** on the commit to be tested. It uses the [protected build](WINDOWS-BUILD.md) with the pinned ESP32 3.3.12 release toolchain. It checks the startup guard, rollback configuration, bootloader, compiled partition table and OTA slot size. The read-only workflow stores the application binary, partition CSV and binary, build verification report and source commit in Actions. +2. On the trusted signing workstation, validate `SHA256SUMS.txt` from the artifact and check out the SHA recorded in `source.txt`. Use the original, locally held signing key. Keep the application binary separate from any bootloader, partition or merged flash image. Prepare the package with Python and `cryptography` installed. + + ```sh + python tools/ota_release.py package --app PulseShift.ino.bin --partitions partitions.csv \ + --notes release-notes.md --tag v2.6.3 --source "$(cat source.txt)" \ + --key /protected/path/original-ota-key.pem --out signed-release + python tools/ota_release.py verify --dir signed-release --tag v2.6.3 + ``` + +3. Complete [startup loop acceptance](STARTUP-LOOP-ACCEPTANCE.md) and the [OTA bench plan](OTA-BENCH-TEST-PLAN.md) using the exact signed asset. Record installed layout, stationary and CAN-traffic refusals, stable external supply, transfer interruption, reboot, digest and version, authenticated confirmation, forced rollback and state retention. Test the Android GitHub flow against a test service or signed fixture before exposing any production tag. +4. Once hardware acceptance is recorded, a maintainer may create a draft GitHub Release at the matching version tag and source commit. Attach the three verified files and use the same notes in GitHub. Review the draft, then publish manually as a stable release. Keep the private key on the signing workstation. The workflow neither holds signing credentials nor creates or publishes releases. + + ```sh + gh release create v2.6.3 --repo iamaritrasaha/PulseShift --draft \ + --target "$(cat source.txt)" --notes-file release-notes.md \ + signed-release/PulseShift.signed.bin signed-release/PulseShift-ota.json \ + signed-release/PulseShift-ota.json.sig + ``` + +## Controller prerequisites + +Online installation requires firmware 2.6.2 or newer to advertise the verified layout, a known active OTA slot, and support for authenticated running-image confirmation. An older compatible controller can be upgraded through the manual signed-file recovery path after acceptance. ROM boot, existing bootloader, NVS, LittleFS and CAN transmit isolation are retained during application-only OTA. Use a bench supply or regulated wired controller power with the motorcycle parked and ignition off. Controller-side OTA checks continue to reject an unhealthy CAN controller, active CAN traffic or running RPM, log recording, and an invalid rollback source. The hardware has no qualified voltage or vehicle-motion sensor, so the installer also requires the operator's power and stationary confirmation. diff --git a/test/test_ota_release.py b/test/test_ota_release.py new file mode 100644 index 0000000..d938adf --- /dev/null +++ b/test/test_ota_release.py @@ -0,0 +1,72 @@ +import sys +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +from cryptography.exceptions import InvalidSignature +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import ec + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) +import ota_release + + +class OtaReleaseTest(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + root = Path(tmp.name) + self.app = root / "application.bin" + payload = bytearray(65536) + payload[0] = 0xE9 + payload[32:36] = bytes.fromhex("3254cdab") + self.app.write_bytes(payload) + self.csv = root / "partitions.csv" + self.csv.write_text("".join(f"{name},{kind},{subtype},{address:#x},{size:#x},\n" + for name, (kind, subtype, address, size) in ota_release.PARTITIONS.items())) + self.notes = root / "notes.md" + self.notes.write_text("Phase and safety update.") + self.key = root / "signer.pem" + key = ec.generate_private_key(ec.SECP256R1()) + self.key.write_bytes(key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, + serialization.NoEncryption())) + anchor = key.public_key().public_bytes(serialization.Encoding.X962, serialization.PublicFormat.UncompressedPoint) + self.enterContext(patch.object(ota_release, "trusted_sec1", return_value=anchor)) + self.enterContext(patch.object(ota_release, "source_version", return_value="2.6.2")) + self.output = root / "signed" + + def prepare(self, tag="v2.6.2"): + ota_release.prepare(self.app, self.csv, self.notes, tag, "a" * 40, self.key, self.output) + + def test_signed_metadata_and_binary_are_bound(self): + self.prepare() + manifest = self.output / ota_release.MANIFEST + binary = self.output / ota_release.ASSET + original = binary.read_bytes() + binary.write_bytes(bytes([original[0] ^ 1]) + original[1:]) + with self.assertRaisesRegex(ValueError, "SHA-256"): + ota_release.verify_release(self.output, "v2.6.2") + binary.write_bytes(original) + manifest.write_bytes(manifest.read_bytes().replace(b"Phase", b"Other")) + with self.assertRaises(InvalidSignature): + ota_release.verify_release(self.output, "v2.6.2") + + def test_tag_layout_and_key_must_match(self): + with self.assertRaisesRegex(ValueError, "Tag must match"): + self.prepare("v2.6.2-rc.1") + with patch.object(ota_release, "trusted_sec1", return_value=bytes(65)): + with self.assertRaisesRegex(ValueError, "trust anchor"): + self.prepare() + self.csv.write_text(self.csv.read_text().replace("0x140000", "0x130000")) + with self.assertRaisesRegex(ValueError, "partition table"): + self.prepare() + + def test_rejects_non_application_artifacts(self): + self.app.write_bytes(b"PK\x03\x04" + bytes(65536)) + with self.assertRaisesRegex(ValueError, "application-only"): + self.prepare() + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/ota_release.py b/tools/ota_release.py new file mode 100644 index 0000000..9893adb --- /dev/null +++ b/tools/ota_release.py @@ -0,0 +1,144 @@ +"""Prepare or verify a PulseShift OTA release locally. No network access needed.""" + +import argparse +import csv +import hashlib +import json +import re +from pathlib import Path + +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec + +from sign_firmware import sign_binary, verify_binary + + +ASSET = "PulseShift.signed.bin" +MANIFEST = "PulseShift-ota.json" +LAYOUT = "esp32-devkit-v1-4m-dual-1280k" +DOMAIN = b"PulseShift OTA manifest v1\x00" +MAX_PACKAGE = 0x140000 +ROOT = Path(__file__).resolve().parents[1] +PROTOCOL = ROOT / "PulseShift/src/ble_protocol.h" +ANCHOR = ROOT / "PulseShift/src/ota_public_key.h" +PARTITIONS = { + "nvs": ("data", "nvs", 0x9000, 0x5000), + "otadata": ("data", "ota", 0xE000, 0x2000), + "app0": ("app", "ota_0", 0x10000, MAX_PACKAGE), + "app1": ("app", "ota_1", 0x150000, MAX_PACKAGE), + "spiffs": ("data", "spiffs", 0x290000, 0x160000), + "coredump": ("data", "coredump", 0x3F0000, 0x10000), +} + + +def number(value): + return int(value[:-1]) * 1024 if value.upper().endswith("K") else int(value, 0) + + +def check_layout(path): + lines = (line for line in path.read_text().splitlines() if line.strip() and not line.startswith("#")) + partitions = {} + for row in csv.reader(lines, skipinitialspace=True): + label, kind, subtype, address, size, *flags = (item.strip() for item in row) + if label in partitions or any(flags): + raise ValueError("Duplicate partition or unexpected partition flags") + partitions[label] = (kind, subtype, number(address), number(size)) + if partitions != PARTITIONS: + raise ValueError("The partition table does not match the supported PulseShift OTA layout") + + +def source_version(): + header = PROTOCOL.read_text() + return ".".join(re.search(rf"^#define PULSESHIFT_FW_VERSION_{part} (\d+)$", header, re.M)[1] + for part in ("MAJOR", "MINOR", "PATCH")) + + +def trusted_sec1(): + return bytes.fromhex("".join(re.findall(r"0x([0-9a-fA-F]{2})\b", ANCHOR.read_text()))) + + +def valid_version(value): + return (isinstance(value, str) and re.fullmatch(r"(0|[1-9][0-9]{0,2})(\.(0|[1-9][0-9]{0,2})){2}", value) + and all(int(part) <= 255 for part in value.split(".")) and not value.startswith("0.")) + + +def check_app(app): + if (not 65536 <= len(app) + 76 <= MAX_PACKAGE or app[0] != 0xE9 or app[12:14] != b"\0\0" + or app[32:36] != bytes.fromhex("3254cdab")): + raise ValueError("Expected an ESP32 application-only image that fits an OTA slot") + if app[23] not in (0, 1) or (app[23] == 1 and hashlib.sha256(app[:-32]).digest() != app[-32:]): + raise ValueError("Invalid ESP32 application digest") + + +def prepare(app, partitions, notes, tag, source, private_key, output): + version = source_version() + if not valid_version(version) or tag != f"v{version}" or not re.fullmatch(r"[0-9a-f]{40}", source): + raise ValueError("Tag must match the stable firmware source version and include its commit SHA") + check_layout(partitions) + check_app(app.read_bytes()) + release_notes = notes.read_text(encoding="utf-8").strip() + if not 1 <= len(release_notes.encode("utf-8")) <= 16384: + raise ValueError("Release notes must be between 1 and 16,384 UTF-8 bytes") + key = serialization.load_pem_private_key(private_key.read_bytes(), password=None) + anchor = trusted_sec1() + if key.public_key().public_bytes(serialization.Encoding.X962, + serialization.PublicFormat.UncompressedPoint) != anchor: + raise ValueError("The private key does not match the firmware trust anchor") + output.mkdir(parents=True, exist_ok=True) + asset = output / ASSET + sign_binary(str(private_key), str(app), str(asset)) + package = asset.read_bytes() + document = json.dumps({ + "schema": 1, "version": version, "asset": ASSET, "layout": LAYOUT, + "chip": "esp32", "slotSize": MAX_PACKAGE, "size": len(package), "source": source, + "sha256": hashlib.sha256(package).hexdigest(), "notes": release_notes, + }, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + (output / MANIFEST).write_bytes(document) + (output / (MANIFEST + ".sig")).write_bytes(key.sign(DOMAIN + document, ec.ECDSA(hashes.SHA256()))) + verify_release(output, tag) + + +def verify_release(directory, tag): + document = (directory / MANIFEST).read_bytes() + signature = (directory / (MANIFEST + ".sig")).read_bytes() + anchor = trusted_sec1() + key = ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256R1(), anchor) + key.verify(signature, DOMAIN + document, ec.ECDSA(hashes.SHA256())) + meta = json.loads(document) + if (meta["schema"] != 1 or not valid_version(meta["version"]) or tag != f'v{meta["version"]}' + or meta["asset"] != ASSET or meta["layout"] != LAYOUT or meta["chip"] != "esp32" + or meta["slotSize"] != MAX_PACKAGE or not re.fullmatch(r"[0-9a-f]{40}", meta["source"]) + or not 1 <= len(meta["notes"].encode("utf-8")) <= 16384): + raise ValueError("Incompatible OTA manifest") + asset = directory / ASSET + package = asset.read_bytes() + if len(package) != meta["size"] or hashlib.sha256(package).hexdigest() != meta["sha256"]: + raise ValueError("OTA package size or SHA-256 does not match its signed manifest") + check_app(package[:-76]) + verify_binary(anchor.hex(), str(asset)) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + package = commands.add_parser("package") + for name in ("app", "partitions", "notes", "key", "out"): + package.add_argument(f"--{name}", type=Path, required=True) + package.add_argument("--tag", required=True) + package.add_argument("--source", required=True) + verify = commands.add_parser("verify") + verify.add_argument("--dir", type=Path, required=True) + verify.add_argument("--tag", required=True) + layout = commands.add_parser("check-layout") + layout.add_argument("partitions", type=Path) + args = parser.parse_args() + if args.command == "package": + prepare(args.app, args.partitions, args.notes, args.tag, args.source, args.key, args.out) + elif args.command == "verify": + verify_release(args.dir, args.tag) + else: + check_layout(args.partitions) + + +if __name__ == "__main__": + main()