Share the saved admin password across ESP32 management services

Use the committed node credential for setup WiFi, WebConfig and browser OTA. Add persistent ESP32 WiFi Companion management credentials without changing preferences layouts, revoke stale browser sessions on rotation, retain scoped save receipts, and coordinate credential changes with flash uploads. Keep external-service credentials and trusted TCP protocol compatibility independent. Update live join QR codes, failure handling and documentation.

Validated 51 native cases, 158 related host and browser methods, and serial Full V4 Companion, Station G3 Repeater, ESP32-C6 Room Server and V4 Sensor firmware builds.
This commit is contained in:
mikecarper committed 2026-10-18 13:09:48 -07:00
1 parent a6a3cb5ebc
commit cd02e55824
58 files changed
+5749 -2439

No files matched your search

+74 -4
View File
@@ -1,4 +1,6 @@
#include <atomic>
#define MESH_MANAGEMENT_PASSWORD_HOST_TEST 1
#include <helpers/esp32/ManagementPassword.h>
#include <cassert>
#include <cstdlib>
#include <cstring>
@@ -38,13 +40,15 @@ int xTaskCreate(Task task, const char*, unsigned, void*, unsigned, void*) {
// algorithm; both vectors are fixed independently of the uploader callbacks.
const char fixture_md5[]="7dea362b3fac8e00956a4952a3d4f474";
const char fixture_corrupt_md5[]="33cdeccccebe80329f1fdbee7f5874cb";
struct Parameter { String text=fixture_md5; String value() { return text; } };
struct Parameter { String text=fixture_md5; const String& value() { return text; } };
struct Response {
int code;
String body;
void addHeader(const char*, const char*) {}
std::vector<std::pair<String, String>> headers;
void addHeader(const char* key, const char* value) { headers.emplace_back(key, value); }
};
unsigned fixture_now=0;
unsigned millis() { return fixture_now; }
struct Client {
unsigned _rx_timeout=0, _rx_last_packet=fixture_now;
bool closed=false;
@@ -70,6 +74,10 @@ struct Request {
Response* queued_response=nullptr;
std::function<void()> disconnected;
Parameter md5;
Parameter authorization;
bool authorization_present = false;
bool hasHeader(const char*) { return authorization_present; }
Parameter* getHeader(const char*) { return &authorization; }
Client connection;
Request() { accept(&connection); }
~Request() { free(_tempObject); delete queued_response; }
@@ -92,9 +100,12 @@ using AsyncWebServerRequest=Request;
static AsyncWebServerRequest* ota_upload_owner=nullptr;
using AsyncWebServerResponse=Response;
struct AsyncWebServer {
std::vector<std::function<void(Request*)>> gets;
std::function<void(Request*)> completion;
std::function<void(Request*,String,size_t,uint8_t*,size_t,bool)> upload;
template<class F> void on(const char*, int, F) {}
template<class F> void on(const char*, int method, F callback) {
assert(method == HTTP_GET); gets.push_back(callback);
}
template<class F,class U> void on(const char*, int method, F callback, U chunks) {
assert(method==HTTP_POST); completion=callback; upload=chunks;
}
@@ -154,12 +165,14 @@ struct UpdateFake {
} Update;
struct AsyncElegantOtaClass {
AsyncWebServer* _server=nullptr;
bool _authRequired=false;
bool _authRequired=false, _managementPassword=false;
bool authenticateRequest(AsyncWebServerRequest*, uint32_t* generation=nullptr);
String _username, _password, _id="fixture";
void begin(AsyncWebServer*, const char*, const char*);
void restart();
bool setEnabled(bool);
};
@AUTH@
@BEGIN@
@RESTART@
@@ -178,6 +191,63 @@ int main() {
server.upload(&request,"firmware",0,data,sizeof(data),true);
in_network_callback=false;
};
#ifdef TEST_OTA_MANAGEMENT_PASSWORD
{
using namespace mesh::esp32::managementPassword;
ota._managementPassword = true;
Request unpublished;
server.gets[0](&unpublished); assert(unpublished.code == 503 && Update.begins == 0);
assert(publish("password"));
auto authorize = [](Request& request, const char* value = "Basic YWRtaW46cGFzc3dvcmQ=") {
request.authorization_present = true; request.authorization.text = value;
};
assert(server.gets.size() == 2);
for (auto& get : server.gets) {
Request absent; get(&absent); assert(absent.code == 401);
assert(absent.queued_response->headers.size() == 2);
assert(absent.queued_response->headers[0].first == "WWW-Authenticate"
&& absent.queued_response->headers[0].second == "Basic realm=\"MeshCore admin\", charset=\"UTF-8\"");
assert(absent.queued_response->headers[1].first == "Cache-Control"
&& absent.queued_response->headers[1].second == "no-store");
Request wrong; authorize(wrong, "Basic wrong"); get(&wrong); assert(wrong.code == 401);
Request good; authorize(good); get(&good); assert(good.code == 200);
}
Request wrong_post; authorize(wrong_post, "Basic wrong");
upload(wrong_post); complete(wrong_post);
assert(wrong_post.code == 401 && Update.begins == 0 && Update.writes == 0 && !uploadActive());
assert(publish("different"));
Request stale; authorize(stale); upload(stale); assert(stale.code == 401 && Update.begins == 0);
const char* updated = "Basic YWRtaW46ZGlmZmVyZW50";
{
ChangeGuard saving; assert(saving.acquired());
Request blocked; authorize(blocked, updated); upload(blocked);
assert(blocked.code == 409 && Update.begins == 0 && !uploadActive());
}
uint8_t half[4] = {};
Request partial; authorize(partial, updated);
server.upload(&partial, "firmware", 0, half, sizeof(half), false);
assert(Update.begins == 1 && Update.writes == 1 && uploadActive());
{
ChangeGuard changing; assert(!changing.acquired());
assert(!publish("not-committed"));
}
// Authentication is rechecked on every chunk before touching Update.
authorize(partial, "Basic wrong");
server.upload(&partial, "firmware", sizeof(half), half, sizeof(half), true);
assert(partial.code == 401 && Update.writes == 1 && Update.ends == 0);
in_network_callback = true; partial.disconnected(); in_network_callback = false;
assert(!uploadActive() && !ota_upload_busy.load() && Update.aborts == 1 && !pending_task);
Request valid; authorize(valid, updated); upload(valid);
assert(uploadActive() && Update.writes == 2);
complete(valid);
assert(valid.code == 200 && Update.boot_commits == 1 && uploadActive());
in_network_callback = true; valid.disconnected(); in_network_callback = false;
assert(!uploadActive() && pending_task);
auto task = pending_task; pending_task = nullptr; task(nullptr);
assert(ESP.restarts == 1);
return 0;
}
#endif
#if defined(TEST_OTA_SECOND_FILE) || defined(TEST_OTA_INCOMPLETE_POST)
{
Request rejected;
+32 -15
View File
@@ -8,6 +8,12 @@
#include <cstring>
#include <initializer_list>
#include <string>
#define MESH_MANAGEMENT_PASSWORD_HOST_TEST
#include <helpers/esp32/ManagementPassword.h>
namespace password = mesh::esp32::managementPassword;
#ifndef TEST_ADMIN_PASSWORD
#define TEST_ADMIN_PASSWORD ""
#endif
using esp_err_t = int;
using wifi_mode_t = int;
@@ -46,13 +52,14 @@ struct IPAddress {
struct wifi_config_t {
struct {
uint8_t ssid[32] = {};
uint8_t password[64] = {};
uint8_t ssid_len = 0, ssid_hidden = 0, channel = 1;
wifi_auth_mode_t authmode = WIFI_AUTH_OPEN;
} ap;
};
enum class Fault {
None, StaleSsid, HiddenSsid, WrongChannel, WrongProtocol, MissingMode,
NotStarted, ZeroIp, DelayedStart, StaleOnce, SetterFailure, WrongAuth, StillConnected,
NotStarted, ZeroIp, DelayedStart, StaleOnce, SetterFailure, WrongAuth, WrongPassword, StillConnected,
ModeSetterFailure, IpConfigSetterFailure, StaProtocolSetterFailure,
SdkModeReadFailure, SdkConfigReadFailure, SdkProtocolReadFailure
};
@@ -60,12 +67,8 @@ enum class ScanBehavior {
Complete, SlowComplete, Failure, Stuck, StopDelayed, Unstoppable,
FacadeFailedActive, FacadeFailedStopRejected
};
constexpr wifi_auth_mode_t expectedAuth() {
#ifdef WEBCONFIG_AP_PASSWORD
return WEBCONFIG_AP_PASSWORD[0] ? WIFI_AUTH_WPA2_PSK : WIFI_AUTH_OPEN;
#else
return WIFI_AUTH_OPEN;
#endif
wifi_auth_mode_t expectedAuth() {
return password::apPasswordEligible(TEST_ADMIN_PASSWORD) ? WIFI_AUTH_WPA2_PSK : WIFI_AUTH_OPEN;
}
void delay(unsigned amount);
struct WiFiFake {
@@ -122,11 +125,9 @@ struct WiFiFake {
return true;
}
bool softAP(const char* ssid, const char* password, int channel) {
#ifdef WEBCONFIG_AP_PASSWORD
assert(password != nullptr && strcmp(password, WEBCONFIG_AP_PASSWORD) == 0);
#else
assert(password == nullptr);
#endif
if (expectedAuth() == WIFI_AUTH_WPA2_PSK) {
assert(password != nullptr && strcmp(password, TEST_ADMIN_PASSWORD) == 0);
} else assert(password == nullptr);
assert(channel == 6);
++ap_calls; polls = 0;
if (fault == Fault::SetterFailure) return false;
@@ -142,6 +143,8 @@ struct WiFiFake {
live_config.ap.authmode = fault == Fault::WrongAuth
? (expectedAuth() == WIFI_AUTH_OPEN ? WIFI_AUTH_WPA2_PSK : WIFI_AUTH_OPEN)
: expectedAuth();
if (password) strcpy(reinterpret_cast<char*>(live_config.ap.password),
fault == Fault::WrongPassword ? "obsolete-key" : password);
ap_ip = fault == Fault::ZeroIp ? IPAddress() : planned_ip;
ap_started = fault != Fault::NotStarted && fault != Fault::DelayedStart;
// Every injected state error deliberately returns success here.
@@ -279,7 +282,7 @@ struct DNSServer {
};
unsigned DNSServer::starts = 0;
struct NodeSnapshot { char admin_password[16] = {}; };
struct Callbacks { void getNodeSnapshot(NodeSnapshot& node) { strcpy(node.admin_password, "configured"); } };
struct Callbacks { void getNodeSnapshot(NodeSnapshot& node) { strcpy(node.admin_password, TEST_ADMIN_PASSWORD); } };
struct AsyncResponseStream { std::string state; unsigned networks = 0; };
struct AsyncWebServerRequest {
int status = 0;
@@ -327,6 +330,9 @@ struct WebConfigServer {
bool _owns_wifi = true, _stopping = false;
bool _retry_saved_wifi_in_setup = true, _setup_reconnect_in_progress = true;
bool _was_setup_ap = false, _initial_setup = false;
bool _setup_provisioning_privilege = false;
uint32_t _ap_auth_generation = 0, _ap_rekey_generation = 0;
uint32_t _ap_rekey_after = 0, _ap_rekey_deadline = 0;
uint32_t _setup_reconnect_deadline = 5, _setup_started_at = 5, _last_activity = 0;
const uint8_t _pub_key[2] = {0x62, 0xF2};
char _ap_ssid[33] = {}, _wifi_ssid[32] = {};
@@ -339,6 +345,7 @@ struct WebConfigServer {
void createServer() { ++servers; }
void requestNetworkAccess() {}
void refreshNetworkPowerHold(uint32_t) {}
void initializeManagementPassword();
bool startSetupMode(char reply[]);
bool checkAuth(AsyncWebServerRequest*) const { return auth_allowed; }
void handleScan(AsyncWebServerRequest* req);
@@ -361,11 +368,20 @@ void requireEndpoint(const WebConfigServer& portal, const char* reply, bool cach
assert(WiFi.scan_result == (cached_scan ? 2 : WIFI_SCAN_FAILED));
assert(!WiFi.sdk_scan_active && WiFi.sdk_scan_stops == (stopped_scan ? 1u : 0u));
assert(!WiFi.auto_reconnect && !portal._retry_saved_wifi_in_setup);
assert(strstr(reply, "join 'MC-62F2' then open http://192.168.4.1/"));
assert(strstr(reply, "join 'MC-62F2', http://192.168.4.1/"));
assert(strstr(reply, expectedAuth() == WIFI_AUTH_WPA2_PSK
? "WiFi: admin password" : TEST_ADMIN_PASSWORD[0]
? "open WiFi; admin login required" : "open WiFi; no admin password"));
assert(portal._setup_provisioning_privilege == (expectedAuth() == WIFI_AUTH_WPA2_PSK));
if (expectedAuth() == WIFI_AUTH_WPA2_PSK)
assert(strcmp(reinterpret_cast<const char*>(WiFi.live_config.ap.password), TEST_ADMIN_PASSWORD) == 0);
assert(portal.servers == 1);
assert(WiFi.initialized && WiFi.driver_stops == 0 && WiFi.driver_deinits == 0);
}
void reset(Fault fault = Fault::None) {
auto& state = password::detail::state();
{ password::detail::Lock lock(state); state.current = {};
state.changing = state.uploading = state.rotating = false; }
WiFi = WiFiFake{}; WiFi.fault = fault;
clock_ms = 100;
DNSServer::starts = 0; mesh::wireless::control().disabled = false;
@@ -383,10 +399,11 @@ int main() {
}
for (Fault fault : {Fault::StaleSsid, Fault::HiddenSsid, Fault::WrongChannel,
Fault::WrongProtocol, Fault::MissingMode, Fault::NotStarted,
Fault::ZeroIp, Fault::SetterFailure, Fault::WrongAuth, Fault::StillConnected,
Fault::ZeroIp, Fault::SetterFailure, Fault::WrongAuth, Fault::WrongPassword, Fault::StillConnected,
Fault::ModeSetterFailure, Fault::IpConfigSetterFailure,
Fault::StaProtocolSetterFailure, Fault::SdkModeReadFailure,
Fault::SdkConfigReadFailure, Fault::SdkProtocolReadFailure}) {
if (fault == Fault::WrongPassword && expectedAuth() == WIFI_AUTH_OPEN) continue;
reset(fault); WiFi.shared_espnow = true;
WebConfigServer portal;
char reply[160] = {};
+13 -2
View File
@@ -5,6 +5,9 @@
#include <string>
#include <ArduinoJson.h>
#include <helpers/WebConfigLoginThrottle.h>
#define MESH_MANAGEMENT_PASSWORD_HOST_TEST
#include <helpers/esp32/ManagementPassword.h>
namespace password = mesh::esp32::managementPassword;
static uint32_t now_ms=100000, random_word=0x12345678;
uint32_t millis() { return now_ms; }
uint32_t esp_random() { return ++random_word; }
@@ -37,11 +40,17 @@ struct WebConfigServer {
enum { MODE_OFF, MODE_SETUP, MODE_LAN };
int _mode=MODE_SETUP, _mux=0;
char _wifi_ssid[33]="SavedNet", _session_token[33] = {};
bool _initial_setup=false;
bool _initial_setup=false, _setup_provisioning_privilege=false;
uint32_t _last_activity=0, _session_last_seen=0;
uint32_t _session_generation=0, _ap_auth_generation=0;
WebConfigLoginThrottle::Tracker _login_throttle;
Callback callback; Callback* _cb=&callback;
WebConfigServer() { strcpy(callback.node.admin_password, "existing-secret"); }
WebConfigServer() {
// A candidate preference can differ while a save is in flight or failed.
// The HTTP handler must authenticate the committed mirror instead.
strcpy(callback.node.admin_password, "temporary-RAM");
assert(password::publish("existing-secret"));
}
void noteNetworkActivity() {}
void handleLogin(AsyncWebServerRequest*);
};
@@ -64,6 +73,8 @@ int main() {
assert(login(portal, attacker, "existing-secret")==429 && last_reply==kLocked);
assert(login(portal, owner, "existing-secret")==200);
assert(strlen(portal._session_token)==32);
password::Snapshot committed; assert(password::snapshot(committed));
assert(portal._session_generation==committed.generation);
assert(login(portal, attacker, "existing-secret")==429 && last_reply==kLocked);
now_ms+=30000;
assert(login(portal, attacker, "existing-secret")==200);
+20
View File
@@ -42,19 +42,25 @@ struct WebConfigServer {
Mode _mode = MODE_LAN;
bool _stopping = false, _keep_wifi_on_stop = false, _was_setup_ap = false;
bool _owns_wifi = true, _stop_warned = false, _initial_setup = false;
bool _setup_provisioning_privilege = false;
bool _retry_saved_wifi_in_setup = false, _setup_reconnect_in_progress = false;
bool _batch_reboot_armed = false, _setup_wifi_handoff_pending = false;
bool _admin_pwd_set = false, _board_cmds_probed = false;
bool _batch_reauth_required = false, _batch_reauth_delivered = false;
uint32_t _stop_warn_at = 0, _setup_started_at = 0, _connect_deadline = 0;
uint32_t _setup_reconnect_deadline = 0, _reboot_at = 0, _batch_state = 0;
uint32_t _batch_next = 0, _setup_wifi_handoff_deadline = 0, _batch_kind = 0;
uint32_t _board_cmds = 0;
uint32_t _network_activity_until = 0;
uint32_t _ap_auth_generation = 0, _ap_rekey_generation = 0;
uint32_t _ap_rekey_after = 0, _ap_rekey_deadline = 0;
uint32_t _batch_reauth_until = 0, _session_generation = 0, _session_last_seen = 0;
void* _mux = nullptr;
struct Terminal { bool running = false; struct { bool pending = false; } queue; };
Terminal* _terminal = nullptr;
char _wifi_ssid[32] = {}, _setup_wifi_handoff_ip[16] = {};
char _session_token[16] = {}, _stats_json[16] = {};
char _batch_owner_token[33] = {};
bool routes = true;
void detachRoutes() { routes = false; }
void closeTerminal() {}
@@ -66,6 +72,7 @@ struct WebConfigServer {
void requestStop();
bool stopForOTA(char*);
void finalizeTeardown();
void clearSessionLocked();
~WebConfigServer() { delete _room_mailbox; }
};
@METHODS@
@@ -77,6 +84,13 @@ int main() {
portal._owns_wifi = owns_wifi;
portal._was_setup_ap = setup;
portal._mode = setup ? WebConfigServer::MODE_SETUP : WebConfigServer::MODE_LAN;
strcpy(portal._session_token, "old-session");
strcpy(portal._batch_owner_token, "old-batch-session");
portal._batch_reauth_required = true;
portal._batch_reauth_delivered = portal._setup_provisioning_privilege = true;
portal._ap_auth_generation = portal._ap_rekey_generation = 42;
portal._ap_rekey_after = portal._ap_rekey_deadline = 42;
portal._batch_reauth_until = portal._session_generation = portal._session_last_seen = 42;
WiFi = WiFiFake{};
WiFi.ap = setup;
WiFi.sta = !setup;
@@ -94,6 +108,12 @@ int main() {
portal.requestStop(); // A duplicate stop cannot revoke the handoff.
portal.finalizeTeardown(); // Existing requests have finally drained.
assert(portal._room_mailbox == nullptr);
assert(!portal._session_token[0] && !portal._batch_owner_token[0]);
assert(!portal._batch_reauth_required && !portal._batch_reauth_until
&& !portal._session_generation && !portal._session_last_seen);
assert(!portal._batch_reauth_delivered && !portal._setup_provisioning_privilege);
assert(!portal._ap_auth_generation && !portal._ap_rekey_generation
&& !portal._ap_rekey_after && !portal._ap_rekey_deadline);
assert(WiFi.ap && WiFi.sta && WiFi.stops == 0);
assert(WiFi.ap_stops == unsigned(setup));
assert(portal.callbacks.stops == 1 && !portal._keep_wifi_on_stop);
+79
View File
@@ -0,0 +1,79 @@
// Production generation gates and post-command commit handling, fake CLI only.
#include <cassert>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <mutex>
#define MESH_MANAGEMENT_PASSWORD_HOST_TEST
#include <helpers/esp32/ManagementPassword.h>
#include <helpers/WebConfigBatch.h>
namespace password = mesh::esp32::managementPassword;
using WCLock = std::lock_guard<std::mutex>;
uint32_t millis() { return 1000; }
struct Callbacks { unsigned starts = 0, ends = 0;
void onConfigBatchStart() { ++starts; }
void onConfigBatchEnd() { ++ends; }
};
struct WebConfigServer {
struct BatchEntry { char reply[160] = {}; } _batch[3];
enum State { BATCH_IDLE, BATCH_PENDING, BATCH_DONE } _batch_state = BATCH_PENDING;
unsigned _batch_next = 0, _batch_count = 3, executed = 0, reloads = 0;
bool _batch_started = false, _batch_all_ok = true, _standalone_wifi_dirty = false;
bool _batch_reauth_required = false, _batch_reauth_delivered = false, post_completed = false;
uint32_t _batch_auth_generation = 0, _batch_reauth_until = 0;
uint32_t _session_generation = 0, _session_last_seen = 5;
char _batch_owner_token[33] = {}, _session_token[33] = "0123456789abcdef0123456789abcdef";
std::mutex _mux;
Callbacks callbacks; Callbacks* _cb = &callbacks;
WebConfigServer() { password::Snapshot value; assert(password::snapshot(value));
_session_generation = value.generation; beginBatchAuthorizationLocked(value.generation); }
void reloadStandaloneWiFi() { ++reloads; }
void clearSessionLocked();
void beginBatchAuthorizationLocked(uint32_t);
void cancelStaleBatchLocked(uint32_t);
void startBatch(uint32_t);
void beforeCommand(uint32_t);
void afterCommand(bool, const char*, const char*, uint32_t);
};
@METHODS@
void reset() {
auto& state = password::detail::state();
{ password::detail::Lock lock(state); state.current = {}; state.changing = state.uploading = state.rotating = false; }
assert(password::initialize("original"));
}
void commit(const char* secret) {
password::ChangeGuard change; assert(change.acquired()); assert(change.publish(secret));
}
int main() {
reset(); WebConfigServer saved; saved.startBatch(100); assert(saved.callbacks.starts == 1);
saved.beforeCommand(100); assert(saved.executed == 1);
commit("next-password"); saved._batch_next = 1;
saved.afterCommand(true, "next-password", "OK", 100);
assert(saved.post_completed && saved._batch_reauth_required && saved._batch_reauth_until == 121000);
assert(!saved._session_token[0] && saved._session_generation == 0 && saved._session_last_seen == 0);
assert(saved._batch_owner_token[0]); // Only the scoped result receipt survives.
saved.beforeCommand(200); assert(saved.executed == 2); // Own batch may continue.
// Failed persistence changes no committed generation or general login.
reset(); WebConfigServer failed; failed.startBatch(100);
failed.afterCommand(true, "next-password", "Error: save unconfirmed", 100);
assert(failed.post_completed && !failed._batch_reauth_required && failed._session_token[0]);
// Saving the same password is a successful no-op, not a session rotation.
commit("original"); failed.afterCommand(true, "original", "OK", 100);
assert(!failed._batch_reauth_required && failed._session_token[0]);
// A different transport's change before any command prevents callback entry.
reset(); WebConfigServer stale; commit("external"); stale.startBatch(100);
assert(stale.callbacks.starts == 0 && stale._batch_state == WebConfigServer::BATCH_DONE);
assert(stale._batch_next == 3 && !stale._batch_all_ok && !stale._batch_owner_token[0]);
for (const auto& entry : stale._batch) assert(strstr(entry.reply, "sign in again"));
// A change between two commands balances the transaction and reloads staged WiFi.
reset(); WebConfigServer between; between.startBatch(100); between._batch_next = 1;
between._standalone_wifi_dirty = true; commit("external"); between.beforeCommand(200);
assert(between.executed == 0 && between.callbacks.ends == 1 && between.reloads == 1);
assert(!between._batch_started && !between._batch_reauth_required && !between._batch_all_ok);
// A mismatched successful-looking reply cannot mint a receipt for another save.
reset(); WebConfigServer mismatch; mismatch.startBatch(100); commit("external");
mismatch.afterCommand(true, "requested", "OK", 100);
assert(!mismatch.post_completed && !mismatch._batch_reauth_required && !mismatch._batch_owner_token[0]);
assert(mismatch.callbacks.ends == 1 && mismatch._batch_state == WebConfigServer::BATCH_DONE);
puts("WebConfig committed password/batch generation checks passed");
}
+45
View File
@@ -0,0 +1,45 @@
// Execute production result projection with real JSON. Auth capability gates
// are exercised separately by webconfig_recovery_auth.cpp.
#include <cassert>
#include <cstring>
#include <string>
#include <ArduinoJson.h>
#include <helpers/WebConfigBatch.h>
struct Entry { char key[16]; char reply[160]; };
struct Results {
int _batch_count = 4;
Entry _batch[4] = {
{"password", "OK"},
{"other", "> arbitrary-private-value"},
{"other", "Error: arbitrary-private-error"},
{"other", "OK - arbitrary-private-success"}
};
std::string config(bool authenticated) {
DynamicJsonDocument doc(4096);
JsonArray results = doc.createNestedArray("results");
@CONFIG_LOOP@
std::string out; serializeJson(doc, out); return out;
}
std::string cli(bool receipt_only) {
const int from = 0, page = _batch_count;
DynamicJsonDocument doc(4096);
JsonArray results = doc.createNestedArray("results");
@CLI_LOOP@
std::string out; serializeJson(doc, out); return out;
}
};
int main() {
Results value;
const auto config_receipt = value.config(false), cli_receipt = value.cli(true);
for (const auto* receipt : {&config_receipt, &cli_receipt}) {
assert(receipt->find("arbitrary-private") == std::string::npos);
assert(receipt->find("OK") != std::string::npos);
assert(receipt->find("sign in again") != std::string::npos);
}
assert(cli_receipt.find("Sign in again to read this result") != std::string::npos);
// Fresh current-generation authentication permits the same batch to be
// reread with complete details, without executing its commands again.
assert(value.config(true).find("arbitrary-private-error") != std::string::npos);
assert(value.cli(false).find("arbitrary-private-value") != std::string::npos);
assert(value.cli(false).find("arbitrary-private-success") != std::string::npos);
}
+104
View File
@@ -0,0 +1,104 @@
// Only WiFi endpoints and clock are doubles; the service method is production.
#include <cassert>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <mutex>
#include <string>
#define MESH_MANAGEMENT_PASSWORD_HOST_TEST
#include <helpers/esp32/ManagementPassword.h>
#include <helpers/WebConfigBatch.h>
namespace password = mesh::esp32::managementPassword;
using WCLock = std::lock_guard<std::mutex>;
struct WiFiFake {
bool ap_live = true, sta_live = true;
unsigned disconnects = 0;
bool softAPdisconnect(bool off) {
assert(off); ++disconnects; ap_live = false; return true;
}
} WiFi;
namespace mesh {
struct Debug { void println(const char*) {} };
Debug& usbDebugPort() { static Debug port; return port; }
namespace wifi {
bool ready = true;
unsigned starts = 0;
std::string last_password;
bool startAccessPoint(const char* ssid, bool reuse, const char* secret) {
assert(strcmp(ssid, "MC-1234") == 0 && reuse);
++starts; last_password = secret ? secret : "";
// Independent SDK model: mode(STA) may fail before touching the existing AP.
if (!ready) return false;
WiFi.ap_live = true; return true;
}
}}
struct WebConfigServer {
enum Mode { MODE_OFF, MODE_LAN, MODE_SETUP } _mode = MODE_SETUP;
enum BatchState { BATCH_IDLE, BATCH_PENDING, BATCH_DONE } _batch_state = BATCH_IDLE;
bool _stopping = false, _setup_provisioning_privilege = true;
bool _batch_reauth_required = false, _batch_reauth_delivered = false;
uint32_t _ap_auth_generation = 0, _ap_rekey_generation = 0;
uint32_t _ap_rekey_after = 0, _ap_rekey_deadline = 0, _reboot_at = 0;
char _ap_ssid[33] = "MC-1234";
std::mutex _mux;
unsigned refs = 0;
unsigned handlerRefCount() const { return refs; }
WebConfigServer() { password::Snapshot value; assert(password::snapshot(value)); _ap_auth_generation = value.generation; }
void serviceSetupPassword(uint32_t now);
};
@METHODS@
void reset() {
auto& state = password::detail::state();
{ password::detail::Lock lock(state); state.current = {}; state.changing = state.uploading = state.rotating = false; }
assert(password::initialize("original"));
WiFi = {}; mesh::wifi::ready = true; mesh::wifi::starts = 0; mesh::wifi::last_password.clear();
}
void commit(const char* secret) {
password::ChangeGuard change; assert(change.acquired()); assert(change.publish(secret));
}
int main() {
reset(); WebConfigServer portal;
portal.serviceSetupPassword(100); assert(mesh::wifi::starts == 0);
commit("next-password");
portal._batch_state = WebConfigServer::BATCH_PENDING;
portal.serviceSetupPassword(100); portal.serviceSetupPassword(4000);
assert(mesh::wifi::starts == 0);
portal._batch_state = WebConfigServer::BATCH_DONE; portal.refs = 1;
portal.serviceSetupPassword(4000); assert(mesh::wifi::starts == 0);
portal.refs = 0; portal._batch_reauth_required = true;
portal.serviceSetupPassword(4000); assert(mesh::wifi::starts == 0);
// Delivery gets a bounded grace period, then the live key follows the saved one.
portal._batch_reauth_delivered = true; portal._ap_rekey_after = 7000;
portal.serviceSetupPassword(6999); assert(mesh::wifi::starts == 0);
password::Snapshot current; assert(password::snapshot(current));
assert(password::beginUpload(current.generation));
portal.serviceSetupPassword(7000); assert(mesh::wifi::starts == 0);
password::endUpload(); portal.serviceSetupPassword(7000);
assert(mesh::wifi::starts == 1 && mesh::wifi::last_password == "next-password");
assert(portal._ap_auth_generation == current.generation && portal._ap_rekey_generation == 0);
assert(WiFi.ap_live && WiFi.sta_live && WiFi.disconnects == 0);
// A client that never receives its receipt cannot postpone rekey indefinitely.
reset(); WebConfigServer no_receipt; commit("another-pass");
no_receipt._batch_reauth_required = true;
no_receipt.serviceSetupPassword(100); no_receipt.serviceSetupPassword(30099);
assert(mesh::wifi::starts == 0);
no_receipt.serviceSetupPassword(30100); assert(mesh::wifi::starts == 1);
// Legacy short/non-ASCII admin credentials retain HTTP access on an open AP.
for (const char* secret : {"short", "long-\xc3\xa9-pass"}) {
reset(); WebConfigServer legacy; commit(secret);
legacy.serviceSetupPassword(100); legacy.serviceSetupPassword(3100);
assert(mesh::wifi::starts == 1 && mesh::wifi::last_password.empty());
assert(!legacy._setup_provisioning_privilege && WiFi.ap_live && WiFi.sta_live);
}
// A failed restart must not leave an indefinitely usable old-key AP behind.
reset(); WebConfigServer failed; const auto old_generation = failed._ap_auth_generation;
commit("next-password"); mesh::wifi::ready = false;
failed.serviceSetupPassword(100); failed.serviceSetupPassword(3100);
assert(mesh::wifi::starts == 1 && !WiFi.ap_live && WiFi.sta_live && WiFi.disconnects == 1);
assert(failed._ap_auth_generation == old_generation && failed._ap_rekey_generation != 0);
failed.serviceSetupPassword(8099); assert(mesh::wifi::starts == 1);
mesh::wifi::ready = true; failed.serviceSetupPassword(8100);
assert(mesh::wifi::starts == 2 && WiFi.ap_live && WiFi.sta_live);
assert(failed._ap_auth_generation != old_generation && failed._ap_rekey_generation == 0);
puts("WebConfig password session/rekey checks passed");
}
+128 -7
View File
@@ -5,6 +5,23 @@
#include <string>
#include <ArduinoJson.h>
#include <helpers/WebConfigLoginThrottle.h>
#include <helpers/WebConfigBatch.h>
#define MESH_MANAGEMENT_PASSWORD_HOST_TEST
#include <helpers/esp32/ManagementPassword.h>
namespace password = mesh::esp32::managementPassword;
static void resetCredential(const char* value) {
{
auto& state = password::detail::state();
password::detail::Lock lock(state);
state.current = password::Snapshot{};
state.changing = state.uploading = state.rotating = false;
}
assert(password::initialize(value));
}
static void commitCredential(const char* value) {
password::ChangeGuard change;
assert(change.acquired() && change.publish(value));
}
struct String : std::string {
using std::string::string;
String(std::string value) : std::string(std::move(value)) {}
@@ -12,15 +29,22 @@ struct String : std::string {
String substring(int begin, int end) const { return substr(begin, end-begin); }
};
static uint32_t now_ms=10, random_word=0x12345678;
static bool rotate_during_login=false;
uint32_t millis() { return now_ms; }
uint32_t esp_random() { return ++random_word; }
uint32_t esp_random() {
if (rotate_during_login) {
rotate_during_login=false;
commitCredential("rotated-secret");
}
return ++random_word;
}
static constexpr uint32_t WEBCONFIG_SESSION_TTL_MS=10000;
struct NodeSnapshot { char admin_password[16] = {}; };
struct Callback {
NodeSnapshot node;
void getNodeSnapshot(NodeSnapshot& result) { result=node; }
};
struct WCLock { explicit WCLock(int) {} };
struct WCLock { std::unique_lock<std::mutex> lock; explicit WCLock(std::mutex& m) : lock(m) {} };
struct WiFiMock { int softAPIP() const { return 4; } } WiFi;
struct Client {
int local_ip=4; uint32_t remote=0;
@@ -46,15 +70,26 @@ struct AsyncWebServerRequest {
};
struct WebConfigServer {
enum { MODE_OFF, MODE_SETUP, MODE_LAN };
int _mode=MODE_SETUP, _mux=0;
enum BatchKind { BATCH_CONFIG, BATCH_CLI };
int _mode=MODE_SETUP;
std::mutex _mux;
char _wifi_ssid[33]="SavedNet", _session_token[33] = {};
bool _initial_setup=false, config_accepted=false;
bool _initial_setup=false, _setup_provisioning_privilege=false, config_accepted=false;
uint32_t _last_activity=0, _session_last_seen=0;
uint32_t _session_generation=0, _ap_auth_generation=0;
uint32_t _batch_auth_generation=0, _batch_reauth_until=0;
bool _batch_reauth_required=false, _batch_reauth_delivered=false, _batch_started=false;
BatchKind _batch_kind=BATCH_CONFIG;
char _batch_owner_token[33]={}, _batch_reqid[24]="0123456789abcdef";
WebConfigLoginThrottle::Tracker _login_throttle; Callback callback; Callback* _cb=&callback;
WebConfigServer() { strcpy(callback.node.admin_password, "existing-secret"); }
WebConfigServer() { strcpy(callback.node.admin_password, "existing-secret"); resetCredential("existing-secret"); }
unsigned network_activity = 0;
void noteNetworkActivity() { ++network_activity; }
bool checkAuth(AsyncWebServerRequest*);
bool checkAuthLocked(AsyncWebServerRequest*, uint32_t* generation=nullptr);
void clearSessionLocked();
void beginBatchAuthorizationLocked(uint32_t);
bool resultReceiptAllowedLocked(AsyncWebServerRequest*, const char*, BatchKind, uint32_t);
void handleLogin(AsyncWebServerRequest*);
void handleLogout(AsyncWebServerRequest*);
void checkConfigPost(AsyncWebServerRequest*);
@@ -101,14 +136,18 @@ int main() {
// First provisioning remains possible and retains its AP-only privilege
// through a save batch that changes SSID before the confirmation arrives.
portal._mode=WebConfigServer::MODE_SETUP; portal._wifi_ssid[0]=0;
portal._setup_provisioning_privilege=true;
password::Snapshot credential; assert(password::snapshot(credential));
portal._ap_auth_generation=credential.generation;
portal._initial_setup=true; assert(portal.checkAuth(&attacker));
strcpy(portal._wifi_ssid, "ProvisionedNet"); assert(portal.checkAuth(&attacker));
portal.handleLogin(&attacker); assert(attacker.status==200);
attacker.socket.local_ip=9; assert(!portal.checkAuth(&attacker));
portal.handleLogin(&attacker); assert(attacker.status==401); attacker.socket.local_ip=4;
// Companion images deliberately have no administrator password or CLI
// password management. Keep that explicit no-password deployment policy.
// Explicit legacy passwordless deployments retain their no-password policy.
portal._initial_setup=false; portal.callback.node.admin_password[0]=0;
portal._setup_provisioning_privilege=false;
resetCredential("");
assert(portal.checkAuth(&attacker)); portal.handleLogin(&attacker); assert(attacker.status==200);
// A spent login budget blocks new logins without revoking an existing
// authenticated session, on either the saved-network AP or the LAN.
@@ -130,5 +169,87 @@ int main() {
active.checkConfigPost(&owner); assert(active.config_accepted);
assert(token==active._session_token);
}
for (int mode : {WebConfigServer::MODE_SETUP, WebConfigServer::MODE_LAN}) {
WebConfigServer active; active._mode=mode;
AsyncWebServerRequest owner; owner.password("existing-secret");
active.handleLogin(&owner); assert(owner.status==200);
owner.header.cookies=std::string("wcs=")+active._session_token;
const std::string original_cookie=owner.header.cookies;
password::Snapshot before; assert(password::snapshot(before));
active.beginBatchAuthorizationLocked(before.generation);
// A setter's temporary RAM and failed-save rollback never reach auth.
strcpy(active.callback.node.admin_password, "temporary");
assert(active.checkAuth(&owner));
AsyncWebServerRequest unsaved; unsaved.password("temporary");
active.handleLogin(&unsaved); assert(unsaved.status==401);
strcpy(active.callback.node.admin_password, "existing-secret");
commitCredential("existing-secret");
assert(active.checkAuth(&owner)); // same credential is not a rotation
commitCredential("new-secret");
password::Snapshot after; assert(password::snapshot(after));
assert(after.generation!=before.generation);
assert(!active.checkAuth(&owner));
active.config_accepted=false; active.checkConfigPost(&owner);
assert(owner.status==401 && !active.config_accepted);
// Only an actual owning password batch grants this short-lived result
// receipt; external rotation alone does not create one.
assert(!active.resultReceiptAllowedLocked(&owner, active._batch_reqid,
WebConfigServer::BATCH_CONFIG, now_ms));
active._batch_auth_generation=after.generation;
active._batch_reauth_required=true;
active._batch_reauth_until=WebConfigBatch::scheduleAt(now_ms, WebConfigBatch::kReauthReceiptMs);
assert(active.resultReceiptAllowedLocked(&owner, active._batch_reqid,
WebConfigServer::BATCH_CONFIG, now_ms));
assert(!active.resultReceiptAllowedLocked(&owner, "fedcba9876543210",
WebConfigServer::BATCH_CONFIG, now_ms));
assert(!active.resultReceiptAllowedLocked(&owner, active._batch_reqid,
WebConfigServer::BATCH_CLI, now_ms));
AsyncWebServerRequest other; other.header.cookies="wcs=00000000000000000000000000000000";
assert(!active.resultReceiptAllowedLocked(&other, active._batch_reqid,
WebConfigServer::BATCH_CONFIG, now_ms));
assert(!active.resultReceiptAllowedLocked(&owner, active._batch_reqid,
WebConfigServer::BATCH_CONFIG, active._batch_reauth_until));
owner.password("existing-secret"); active.handleLogin(&owner); assert(owner.status==401);
owner.password("new-secret"); active.handleLogin(&owner); assert(owner.status==200);
owner.header.cookies=std::string("wcs=")+active._session_token;
assert(active.checkAuth(&owner));
owner.header.cookies=original_cookie; assert(!active.checkAuth(&owner));
// Even changing back cannot revive the first generation's cookie/receipt.
commitCredential("existing-secret");
assert(!active.checkAuth(&owner));
assert(!active.resultReceiptAllowedLocked(&owner, active._batch_reqid,
WebConfigServer::BATCH_CONFIG, now_ms));
}
{
WebConfigServer active;
AsyncWebServerRequest first_setup;
active._wifi_ssid[0]=0;
active._initial_setup=active._setup_provisioning_privilege=true;
password::Snapshot before; assert(password::snapshot(before));
active._ap_auth_generation=before.generation;
assert(active.checkAuth(&first_setup));
active.beginBatchAuthorizationLocked(before.generation); // no initial cookie
commitCredential("new-secret");
assert(!active.checkAuth(&first_setup)); // old WPA association is not auth
first_setup.password("new-secret"); active.handleLogin(&first_setup);
assert(first_setup.status==200 && active._session_token[0]);
first_setup.header.cookies=std::string("wcs=")+active._session_token;
assert(active.checkAuth(&first_setup));
}
{
WebConfigServer active;
active._wifi_ssid[0]=0; active._initial_setup=true;
commitCredential("short");
AsyncWebServerRequest open_ap;
assert(!active.checkAuth(&open_ap)); // short legacy password still needs HTTP login
open_ap.password("short"); active.handleLogin(&open_ap); assert(open_ap.status==200);
}
{
WebConfigServer active; AsyncWebServerRequest login;
login.password("existing-secret"); rotate_during_login=true;
active.handleLogin(&login);
assert(login.status==401 && active._session_token[0]==0);
}
puts("WebConfig recovery authentication regression checks passed");
}
+11 -2
View File
@@ -9,6 +9,9 @@
#include <initializer_list>
#include <string>
#include <helpers/WirelessControl.h>
#define MESH_MANAGEMENT_PASSWORD_HOST_TEST 1
#include <helpers/esp32/ManagementPassword.h>
static const bool published_password = mesh::esp32::managementPassword::publish("short");
#define MESH_DEBUG_PRINTLN(...) ((void)0)
constexpr int WL_CONNECTED = 3;
@@ -17,7 +20,7 @@ using wifi_mode_t = int;
constexpr int WIFI_OFF = 0, WIFI_STA = 1, WIFI_AP = 2;
constexpr int WIFI_MODE_NULL = WIFI_OFF, WIFI_MODE_AP = WIFI_AP;
constexpr int ESP_OK = 0, WIFI_IF_AP = 1, WIFI_IF_STA = 0;
constexpr int WIFI_AUTH_OPEN = 0;
constexpr int WIFI_AUTH_OPEN = 0, WIFI_AUTH_WPA2_PSK = 3;
constexpr int WIFI_SCAN_RUNNING = -1, WIFI_SCAN_FAILED = -2, AP_STARTED_BIT = 1;
constexpr int LISTEN = 10;
bool async_bind_allowed = true;
@@ -29,6 +32,7 @@ bool constrain_espnow_channel = true;
struct wifi_config_t {
struct {
uint8_t ssid[32] = {};
uint8_t password[64] = {};
uint8_t ssid_len = 0, ssid_hidden = 0, channel = 1;
int authmode = WIFI_AUTH_OPEN;
} ap;
@@ -86,11 +90,13 @@ struct WiFiFake {
return allow_ap;
}
bool softAP(const char* ssid, const char* password, int channel = 1) {
assert(ssid && strlen(ssid) <= 32 && password == nullptr);
assert(ssid && strlen(ssid) <= 32);
ap_channel = channel;
++starts; ap = allow_ap; radio = true;
if (ap) {
live_config = {};
live_config.ap.authmode = password && password[0] ? WIFI_AUTH_WPA2_PSK : WIFI_AUTH_OPEN;
if (password) strcpy(reinterpret_cast<char*>(live_config.ap.password), password);
const char* live_ssid = fault == Fault::Ssid ? "old-hotspot" : ssid;
live_config.ap.ssid_len = uint8_t(strlen(live_ssid));
memcpy(live_config.ap.ssid, live_ssid, strlen(live_ssid));
@@ -181,6 +187,8 @@ struct AsyncWebServer {
struct Elegant {
bool busy = false;
void setID(const char*) {}
void useManagementPassword() {}
bool authenticateRequest(AsyncWebServerRequest*) { return true; }
void begin(AsyncWebServer*) {}
bool setEnabled(bool enabled) { return enabled || !busy; }
} AsyncElegantOTA;
@@ -198,6 +206,7 @@ struct ESP32Board {
const char* getManufacturerName() const { return "test"; }
bool startOTAUpdate(const char*, char*, bool);
bool stopOTAUpdate(char*);
static bool rotateOTAAccessPoint(void*) { return true; }
};
struct LightweightServer {
bool allow = true, running = false, allow_stop = true;