Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
8225a2a
Initial plan
Copilot Sep 14, 2025
54746c9
Implement OTA release compatibility checking system
Copilot Sep 14, 2025
e920d2e
Complete OTA release compatibility system with comprehensive testing
Copilot Sep 14, 2025
caf3d90
Fix OTA release checking to use flexible string search instead of har…
Copilot Sep 14, 2025
fb077ec
Improve OTA release checking with scoring-based candidate selection
Copilot Sep 14, 2025
2d8edfc
Remove build artifacts from repository
Copilot Sep 14, 2025
42ff73f
Implement metadata-based OTA release checking system
Copilot Sep 14, 2025
7d550ba
Replace metadata header approach with ESP-IDF custom description section
Copilot Sep 14, 2025
691c058
Fix runtime release name replacement - move to build-time
Copilot Sep 14, 2025
5c0c84e
Add ESP8266 support to OTA release compatibility system using .ver_nu…
Copilot Sep 14, 2025
18dfc70
Address review feedback: unify structures, remove code duplication, i…
Copilot Sep 14, 2025
f706c6c
Rename ignoreRelease to skipValidation in OTA validation system
Copilot Sep 14, 2025
70e8be6
Address review feedback: unify structures, fix C++11 compatibility, i…
Copilot Sep 17, 2025
71ad0d9
Address final review feedback: improve error handling, remove debug d…
Copilot Sep 17, 2025
6676705
Address final review feedback: revert unnecessary files, use F-string…
Copilot Sep 17, 2025
6149842
Fix file reverts and implement efficient metadata validation without …
Copilot Sep 20, 2025
196f579
Implement correct metadata validation logic as requested in review co…
Copilot Sep 20, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion wled00/data/update.htm
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,27 @@
}
window.open(getURL("/update?revert"),"_self");
}
function GetV() {/*injected values here*/}
function GetV() {
// Fetch device info via JSON API instead of compiling it in
fetch('/json/info')
.then(response => response.json())
.then(data => {
if (data.release) {
var releaseSpan = document.querySelector('.release-name');
if (releaseSpan) {
releaseSpan.textContent = data.release;
}
}
})
.catch(error => {
console.log('Could not fetch device info:', error);
// Fallback to compiled-in value if API call fails
var releaseSpan = document.querySelector('.release-name');
if (releaseSpan && releaseSpan.textContent === 'Loading...') {
releaseSpan.textContent = 'Unknown';
}
});
}
</script>
<style>
@import url("style.css");
Expand All @@ -28,10 +48,13 @@
<h2>WLED Software Update</h2>
<form method='POST' action='./update' id='upd' enctype='multipart/form-data' onsubmit="toggle('upd')">
Installed version: <span class="sip">WLED ##VERSION##</span><br>
Release: <span class="sip release-name">Loading...</span><br>
Download the latest binary: <a href="https://github.com/wled-dev/WLED/releases" target="_blank"
style="vertical-align: text-bottom; display: inline-flex;">
<img src="https://img.shields.io/github/release/wled-dev/WLED.svg?style=flat-square"></a><br>
<input type='file' name='update' required><br> <!--should have accept='.bin', but it prevents file upload from android app-->
<input type='checkbox' name='skipValidation' id='skipValidation'>
<label for='skipValidation'>Ignore firmware validation</label><br>
<button type="submit">Update!</button><br>
<hr class="sml">
<button id="rev" type="button" onclick="cR()">Revert update</button><br>
Expand Down
111 changes: 111 additions & 0 deletions wled00/ota_release_check.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
#include "ota_release_check.h"
#include "wled.h"

#ifdef ESP32
#include <esp_app_format.h>
#include <esp_ota_ops.h>
#endif

bool extractWledCustomDesc(const uint8_t* binaryData, size_t dataSize, wled_custom_desc_t* extractedDesc) {
if (!binaryData || !extractedDesc || dataSize < 64) {
return false;
}

// Search in first 8KB only. This range was chosen because:
// - ESP32 .rodata.wled_desc sections appear early in the binary (typically within first 2-4KB)
// - ESP8266 .ver_number sections also appear early (typically within first 1-2KB)
// - 8KB provides ample coverage for metadata discovery while minimizing processing time
// - Larger firmware files (>1MB) would take significantly longer to process with full search
// - Analysis of typical WLED binary layouts shows metadata appears well within this range
const size_t search_limit = min(dataSize, (size_t)8192);

for (size_t offset = 0; offset <= search_limit - sizeof(wled_custom_desc_t); offset++) {
const wled_custom_desc_t* custom_desc = (const wled_custom_desc_t*)(binaryData + offset);

// Check for magic number
if (custom_desc->magic == WLED_CUSTOM_DESC_MAGIC) {
// Found potential match, validate version
if (custom_desc->version != WLED_CUSTOM_DESC_VERSION) {
DEBUG_PRINTF_P(PSTR("Found WLED structure at offset %u but version mismatch: %u\n"),
offset, custom_desc->version);
continue;
}

// Validate hash using runtime function
uint32_t expected_hash = djb2_hash_runtime(custom_desc->release_name);
if (custom_desc->crc32 != expected_hash) {
DEBUG_PRINTF_P(PSTR("Found WLED structure at offset %u but hash mismatch\n"), offset);
continue;
}

// Valid structure found - copy entire structure
memcpy(extractedDesc, custom_desc, sizeof(wled_custom_desc_t));

DEBUG_PRINTF_P(PSTR("Extracted WLED structure at offset %u: '%s'\n"),
offset, extractedDesc->release_name);
return true;
}
}

DEBUG_PRINTLN(F("No WLED custom description found in binary"));
return false;
}

bool validateReleaseCompatibility(const char* extractedRelease) {
if (!extractedRelease) {
return false;
}

// Ensure extractedRelease is properly null terminated (guard against fixed-length buffer issues)
char safeRelease[WLED_RELEASE_NAME_MAX_LEN];
strncpy(safeRelease, extractedRelease, WLED_RELEASE_NAME_MAX_LEN - 1);
safeRelease[WLED_RELEASE_NAME_MAX_LEN - 1] = '\0';

if (strlen(safeRelease) == 0) {
return false;
}

// Simple string comparison - releases must match exactly
bool match = strcmp(releaseString, safeRelease) == 0;

DEBUG_PRINTF_P(PSTR("Release compatibility check: current='%s', uploaded='%s', match=%s\n"),
releaseString, safeRelease, match ? "YES" : "NO");

return match;
}

bool shouldAllowOTA(const uint8_t* binaryData, size_t dataSize, char* errorMessage, size_t errorMessageLen) {
// Clear error message
if (errorMessage && errorMessageLen > 0) {
errorMessage[0] = '\0';
}

// Ensure our custom description structure is referenced (prevents optimization)
const wled_custom_desc_t* local_desc = getWledCustomDesc();
(void)local_desc; // Suppress unused variable warning

// Try to extract WLED structure directly from binary data
wled_custom_desc_t extractedDesc;
bool hasCustomDesc = extractWledCustomDesc(binaryData, dataSize, &extractedDesc);

if (!hasCustomDesc) {
// No custom description - this could be a legacy binary
if (errorMessage && errorMessageLen > 0) {
strncpy_P(errorMessage, PSTR("This firmware file is missing compatibility metadata. Enable 'Ignore firmware validation' to proceed anyway."), errorMessageLen - 1);
errorMessage[errorMessageLen - 1] = '\0';
}
return false;
}

// Validate compatibility using extracted release name
if (!validateReleaseCompatibility(extractedDesc.release_name)) {
if (errorMessage && errorMessageLen > 0) {
snprintf_P(errorMessage, errorMessageLen, PSTR("Firmware compatibility mismatch: current='%s', uploaded='%s'. Enable 'Ignore firmware validation' to proceed anyway."),
releaseString, extractedDesc.release_name);
errorMessage[errorMessageLen - 1] = '\0'; // Ensure null termination
}
return false;
}

return true;
}
90 changes: 90 additions & 0 deletions wled00/ota_release_check.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
#ifndef WLED_OTA_RELEASE_CHECK_H
#define WLED_OTA_RELEASE_CHECK_H

/*
* OTA Release Compatibility Checking using ESP-IDF Custom Description Section
* Functions to extract and validate release names from uploaded binary files using embedded metadata
*/

#include <Arduino.h>

#ifdef ESP32
#include <esp_app_format.h>
#endif

#define WLED_CUSTOM_DESC_MAGIC 0x57535453 // "WSTS" (WLED System Tag Structure)
#define WLED_CUSTOM_DESC_VERSION 1
#define WLED_RELEASE_NAME_MAX_LEN 48

// Platform-specific metadata offset in binary file
#ifdef ESP32
#define METADATA_OFFSET 0 // ESP32: metadata appears at beginning
#elif defined(ESP8266)
#define METADATA_OFFSET 0x1000 // ESP8266: metadata appears at 4KB offset
#endif

/**
* DJB2 hash function (C++11 compatible constexpr)
* Used for compile-time hash computation of release names
*/
constexpr uint32_t djb2_hash_constexpr(const char* str, uint32_t hash = 5381) {
return (*str == '\0') ? hash : djb2_hash_constexpr(str + 1, ((hash << 5) + hash) + *str);
}

/**
* Runtime DJB2 hash function for validation
*/
inline uint32_t djb2_hash_runtime(const char* str) {
uint32_t hash = 5381;
while (*str) {
hash = ((hash << 5) + hash) + *str++;
}
return hash;
}

/**
* WLED Custom Description Structure
* This structure is embedded in platform-specific sections at a fixed offset
* in ESP32/ESP8266 binaries, allowing extraction without modifying the binary format
*/
typedef struct {
uint32_t magic; // Magic number to identify WLED custom description
uint32_t version; // Structure version for future compatibility
char release_name[WLED_RELEASE_NAME_MAX_LEN]; // Release name (null-terminated)
uint32_t crc32; // CRC32 of the above fields for integrity check
} __attribute__((packed)) wled_custom_desc_t;

/**
* Extract WLED custom description structure from binary
* @param binaryData Pointer to binary file data
* @param dataSize Size of binary data in bytes
* @param extractedDesc Buffer to store extracted custom description structure
* @return true if structure was found and extracted, false otherwise
*/
bool extractWledCustomDesc(const uint8_t* binaryData, size_t dataSize, wled_custom_desc_t* extractedDesc);

/**
* Validate if extracted release name matches current release
* @param extractedRelease Release name from uploaded binary
* @return true if releases match (OTA should proceed), false if they don't match
*/
bool validateReleaseCompatibility(const char* extractedRelease);

/**
* Check if OTA should be allowed based on release compatibility using custom description
* @param binaryData Pointer to binary file data (not modified)
* @param dataSize Size of binary data in bytes
* @param errorMessage Buffer to store error message if validation fails
* @param errorMessageLen Maximum length of error message buffer
* @return true if OTA should proceed, false if it should be blocked
*/
bool shouldAllowOTA(const uint8_t* binaryData, size_t dataSize, char* errorMessage, size_t errorMessageLen);

/**
* Get pointer to the embedded custom description structure
* This ensures the structure is referenced and not optimized out
* @return pointer to the custom description structure
*/
const wled_custom_desc_t* getWledCustomDesc();

#endif // WLED_OTA_RELEASE_CHECK_H
29 changes: 29 additions & 0 deletions wled00/wled_custom_desc.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#include "ota_release_check.h"
#include "wled.h"

// Platform-specific section definition
#ifdef ESP32
#define WLED_CUSTOM_DESC_SECTION ".rodata.wled_desc"
#elif defined(ESP8266)
#define WLED_CUSTOM_DESC_SECTION ".ver_number"
#endif

// Single structure definition for both platforms
const wled_custom_desc_t __attribute__((section(WLED_CUSTOM_DESC_SECTION))) wled_custom_description = {
WLED_CUSTOM_DESC_MAGIC, // magic
WLED_CUSTOM_DESC_VERSION, // version
WLED_RELEASE_NAME, // release_name
djb2_hash_constexpr(WLED_RELEASE_NAME) // crc32 - computed at compile time
};

// Compile-time validation that release name doesn't exceed maximum length
static_assert(sizeof(WLED_RELEASE_NAME) <= WLED_RELEASE_NAME_MAX_LEN,
"WLED_RELEASE_NAME exceeds maximum length of WLED_RELEASE_NAME_MAX_LEN characters");

// Single reference to ensure it's not optimized away
const wled_custom_desc_t* __attribute__((used)) wled_custom_desc_ref = &wled_custom_description;

// Function to ensure the structure is referenced by code
const wled_custom_desc_t* getWledCustomDesc() {
return &wled_custom_description;
}
Loading