diff --git a/docs/cli_commands.md b/docs/cli_commands.md index 3497c1ad1..6232e88e9 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -2532,6 +2532,10 @@ Older Companion firmware is not a safe transport for this backup flow. **Default:** `password` +Repeaters and room servers send `CHANGE YOUR PASSWORD` as a separate CLI reply +after a successful admin radio login while the saved password still matches +the build's `ADMIN_PASSWORD`. Saving a different password stops the warning. + `get password` returns the current admin password only on a local connection: USB, Ethernet, or the authenticated LAN browser CLI. It is rejected over LoRa. ESP32 WiFi Companion instead reports management-password status without revealing diff --git a/docs/faq.md b/docs/faq.md index ee8357205..f88115e84 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -272,6 +272,8 @@ You can get the latitude and longitude from Google Maps by right-clicking the lo `password {new-password}` +Repeaters and rooms send `CHANGE YOUR PASSWORD` to admins on login while the +admin password still matches the firmware default. ### 3.4. Q: What is the password to join a room server? **A:** The default guest password to a room server is `hello`. Use the following command to change the guest password: diff --git a/examples/simple_repeater/MyMesh.cpp b/examples/simple_repeater/MyMesh.cpp index dc345efce..ef9df3098 100644 --- a/examples/simple_repeater/MyMesh.cpp +++ b/examples/simple_repeater/MyMesh.cpp @@ -1,4 +1,5 @@ #include "MyMesh.h" +#include #if defined(HELTEC_V4_R8_TFT) && defined(HELTEC_TFT_RUNTIME_ROTATION) \ && HELTEC_TFT_RUNTIME_ROTATION == 1 #include @@ -658,6 +659,29 @@ uint8_t MyMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t* secr return 13; // reply length } +void MyMesh::sendDefaultPasswordWarning(ClientInfo* client, + uint32_t sender_timestamp, + uint8_t path_hash_size) { + if (client == NULL || !client->isAdmin() + || !mesh::defaultAdminPasswordUnchanged( + _prefs.password, ADMIN_PASSWORD, sizeof(_prefs.password))) return; + uint8_t data[5 + sizeof(mesh::DEFAULT_PASSWORD_LOGIN_WARNING) - 1]; + uint32_t timestamp = getRTCClock()->getCurrentTimeUnique(); + if (timestamp == sender_timestamp) timestamp++; + memcpy(data, ×tamp, 4); + data[4] = TXT_TYPE_CLI_DATA << 2; + memcpy(data + 5, mesh::DEFAULT_PASSWORD_LOGIN_WARNING, sizeof(data) - 5); + mesh::Packet* warning = createDatagram(PAYLOAD_TYPE_TXT_MSG, client->id, + client->shared_secret, data, sizeof(data)); + if (warning == NULL) return; + warning->radio_reply = true; + if (mesh::Packet::isValidPathLen(client->out_path_len)) { + sendClientReply(client, warning, SERVER_RESPONSE_DELAY + 2000UL, path_hash_size); + } else { + sendFloodReply(warning, SERVER_RESPONSE_DELAY + 2000UL, path_hash_size); + } +} + // Comparison functions for qsort() - defined at file scope to avoid heap allocations static int cmp_neighbours_newest_to_oldest(const void* a, const void* b) { const NeighbourInfo* na = *(const NeighbourInfo**)a; @@ -2781,6 +2805,7 @@ void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const m memcpy(×tamp, data, 4); data[len] = 0; // ensure null terminator + const bool login_request = data[4] == 0 || data[4] >= ' '; uint8_t reply_len; reply_path_len = 0xFF; @@ -2816,6 +2841,8 @@ void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const m *client, OUT_PATH_UNKNOWN, futureMillis(LOGIN_PATH_OBSERVATION_TIMEOUT_MS)); } + if (login_request && login_path_sent) + sendDefaultPasswordWarning(client, timestamp, packet->getPathHashSize()); } return; } @@ -2823,13 +2850,16 @@ void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const m mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, secret, reply_data, reply_len); if (reply == NULL) return; + bool reply_queued; if (route == mesh::REPLY_ROUTE_DIRECT_SUPPLIED) { - sendDirect(reply, reply_path, reply_path_len, SERVER_RESPONSE_DELAY); + reply_queued = sendDirect(reply, reply_path, reply_path_len, SERVER_RESPONSE_DELAY); } else if (route == mesh::REPLY_ROUTE_DIRECT_OUT_PATH) { - sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY); + reply_queued = sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY); } else { - sendFloodReply(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize()); + reply_queued = sendFloodReply(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize()); } + if (login_request && reply_queued) + sendDefaultPasswordWarning(client, timestamp, packet->getPathHashSize()); } } diff --git a/examples/simple_repeater/MyMesh.h b/examples/simple_repeater/MyMesh.h index a939d4e9a..708ac056e 100644 --- a/examples/simple_repeater/MyMesh.h +++ b/examples/simple_repeater/MyMesh.h @@ -851,6 +851,8 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks void putNeighbour(const mesh::Identity& id, uint32_t timestamp, float snr, int16_t rssi); uint8_t handleLoginReq(const mesh::Identity& sender, const uint8_t* secret, uint32_t sender_timestamp, const uint8_t* data, bool is_flood); + void sendDefaultPasswordWarning(ClientInfo* client, uint32_t sender_timestamp, + uint8_t path_hash_size); uint8_t handleAnonRegionsReq(const mesh::Identity& sender, uint32_t sender_timestamp, const uint8_t* data, size_t data_len); uint8_t handleAnonOwnerReq(const mesh::Identity& sender, uint32_t sender_timestamp, const uint8_t* data, size_t data_len); uint8_t handleAnonClockReq(const mesh::Identity& sender, uint32_t sender_timestamp, const uint8_t* data, size_t data_len); diff --git a/examples/simple_room_server/MyMesh.cpp b/examples/simple_room_server/MyMesh.cpp index 92ed33085..d4596f560 100644 --- a/examples/simple_room_server/MyMesh.cpp +++ b/examples/simple_room_server/MyMesh.cpp @@ -1,4 +1,5 @@ #include "MyMesh.h" +#include #if defined(HELTEC_V4_R8_TFT) && defined(HELTEC_TFT_RUNTIME_ROTATION) \ && HELTEC_TFT_RUNTIME_ROTATION == 1 #include @@ -1836,6 +1837,25 @@ mesh::DispatcherAction MyMesh::onRecvPacket(mesh::Packet* pkt) { return action; } +void MyMesh::sendDefaultPasswordWarning(ClientInfo* client, + uint32_t sender_timestamp, + uint8_t path_hash_size) { + if (client == NULL || !client->isAdmin() + || !mesh::defaultAdminPasswordUnchanged( + _prefs.password, ADMIN_PASSWORD, sizeof(_prefs.password))) return; + uint8_t data[5 + sizeof(mesh::DEFAULT_PASSWORD_LOGIN_WARNING) - 1]; + uint32_t timestamp = getRTCClock()->getCurrentTimeUnique(); + if (timestamp == sender_timestamp) timestamp++; + memcpy(data, ×tamp, 4); + data[4] = TXT_TYPE_CLI_DATA << 2; + memcpy(data + 5, mesh::DEFAULT_PASSWORD_LOGIN_WARNING, sizeof(data) - 5); + mesh::Packet* warning = createDatagram(PAYLOAD_TYPE_TXT_MSG, client->id, + client->shared_secret, data, sizeof(data)); + if (warning == NULL) return; + warning->radio_reply = true; + sendClientReply(client, warning, SERVER_RESPONSE_DELAY + 2000UL, path_hash_size); +} + void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const mesh::Identity &sender, uint8_t *data, size_t len) { if (!room_access.allowsIdentity(sender.pub_key)) return; @@ -1934,23 +1954,27 @@ void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const m next_push = futureMillis(PUSH_NOTIFY_DELAY_MILLIS); // delay next push, give RESPONSE packet time to arrive first + bool login_reply_queued = false; if (packet->isRouteFlood()) { // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response mesh::Packet *path = createPathReturn(sender, client->shared_secret, packet->path, packet->path_len, PAYLOAD_TYPE_RESPONSE, reply_data, 13); - if (path && sendFloodReply(path, SERVER_RESPONSE_DELAY, packet->getPathHashSize())) { + if (path && (login_reply_queued = sendFloodReply( + path, SERVER_RESPONSE_DELAY, packet->getPathHashSize()))) { mesh::beginObservedClientPath(*client, OUT_PATH_UNKNOWN, futureMillis(60000)); } } else { mesh::Packet *reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, client->shared_secret, reply_data, 13); if (reply) { if (mesh::Packet::isValidPathLen(client->out_path_len)) { // we have an out_path, so send DIRECT - sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY); + login_reply_queued = sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY); } else { - sendFloodReply(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize()); + login_reply_queued = sendFloodReply(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize()); } } } + if (login_reply_queued) + sendDefaultPasswordWarning(client, sender_timestamp, packet->getPathHashSize()); } } diff --git a/examples/simple_room_server/MyMesh.h b/examples/simple_room_server/MyMesh.h index a2722510b..8782792e6 100644 --- a/examples/simple_room_server/MyMesh.h +++ b/examples/simple_room_server/MyMesh.h @@ -462,6 +462,8 @@ protected: bool allowPacketForward(const mesh::Packet* packet) override; bool allowPacketTransmit(const mesh::Packet* packet) const override; void onAnonDataRecv(mesh::Packet* packet, const uint8_t* secret, const mesh::Identity& sender, uint8_t* data, size_t len) override; + void sendDefaultPasswordWarning(ClientInfo* client, uint32_t sender_timestamp, + uint8_t path_hash_size); int searchPeersByHash(const uint8_t* hash) override ; void getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) override; void onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_idx, const uint8_t* secret, uint8_t* data, size_t len) override; diff --git a/src/helpers/DefaultPasswordWarning.h b/src/helpers/DefaultPasswordWarning.h new file mode 100644 index 000000000..0969ae022 --- /dev/null +++ b/src/helpers/DefaultPasswordWarning.h @@ -0,0 +1,19 @@ +#pragma once + +#include +#include + +namespace mesh { + +static constexpr char DEFAULT_PASSWORD_LOGIN_WARNING[] = "CHANGE YOUR PASSWORD"; + +inline bool defaultAdminPasswordUnchanged(const char* password, + const char* factory_password, + size_t capacity) { + // Match the same bounded value stored when the role initializes its prefs. + return password && factory_password && capacity > 1 && password[0] + && factory_password[0] + && strncmp(password, factory_password, capacity - 1) == 0; +} + +} // namespace mesh diff --git a/test/fixtures/protocol_parser_bounds/test.cpp b/test/fixtures/protocol_parser_bounds/test.cpp index 257559a0b..8eee5e3ca 100644 --- a/test/fixtures/protocol_parser_bounds/test.cpp +++ b/test/fixtures/protocol_parser_bounds/test.cpp @@ -68,6 +68,8 @@ struct MyMesh { uint8_t handleAnonOwnerReq(const mesh::Identity&, uint32_t, const uint8_t*, size_t); uint8_t handleAnonClockReq(const mesh::Identity&, uint32_t, const uint8_t*, size_t); void onAnonDataRecv(mesh::Packet*, const uint8_t*, const mesh::Identity&, uint8_t*, size_t); + // Warning authorization/transport is exercised by the full login suites. + void sendDefaultPasswordWarning(ClientInfo*, uint32_t, uint8_t) {} uint8_t handleLoginReq(const mesh::Identity&, const uint8_t*, uint32_t timestamp, const uint8_t* password, bool flood) { ++logins; diff --git a/test/test_repeater_guest_access.py b/test/test_repeater_guest_access.py index e8b177858..a858d8b2f 100644 --- a/test/test_repeater_guest_access.py +++ b/test/test_repeater_guest_access.py @@ -2,6 +2,7 @@ """Execute repeater guest authorization, saved toggles, and receive admission.""" from pathlib import Path import re +import json import shutil import subprocess import sys @@ -18,6 +19,8 @@ HARNESS = r''' #include #include #include +#include +#include #include #include #include @@ -25,10 +28,15 @@ HARNESS = r''' #include #include #include +#include #define PUB_KEY_SIZE 32 #define MAX_PATH_SIZE 64 #define MAX_PACKET_PAYLOAD 184 #define PAYLOAD_TYPE_ANON_REQ 0x07 +#define PAYLOAD_TYPE_RESPONSE 0x01 +#define PAYLOAD_TYPE_TXT_MSG 0x02 +#define TXT_TYPE_CLI_DATA 1 +#define ADMIN_PASSWORD "password" #define MAX_CLIENTS 16 #define MESH_CLIENT_REPEATER_ONLY 1 #define MESH_ENABLE_FLOOD_RULE_ENGINE 1 @@ -44,11 +52,19 @@ struct Identity { }; struct Packet { bool direct = true; + bool radio_reply = false, path_return = false; uint8_t type = PAYLOAD_TYPE_ANON_REQ; + uint8_t path_len = 0, path[MAX_PATH_SIZE]{}, payload[MAX_PACKET_PAYLOAD]{}; + size_t payload_len = 0; bool isRouteDirect() const { return direct; } bool isRouteFlood() const { return !direct; } uint8_t getPayloadType() const { return type; } + uint8_t getPathHashSize() const { return (path_len >> 6) + 1; } + static bool isValidPathLen(uint8_t); + static size_t writePath(uint8_t*, const uint8_t*, uint8_t); }; +@PACKET_HELPERS@ +@ROUTING_HELPERS@ } @CLIENT_INFO@; struct ClientACL { @@ -110,15 +126,57 @@ struct MyMesh { unsigned received = 0; unsigned anonymous_requests = 0; uint8_t reply_path_len = 0; + uint8_t reply_path[MAX_PATH_SIZE]{}; + struct Sent { mesh::Packet packet; unsigned long delay; uint8_t hash_size; }; + std::vector sent; + mesh::Packet response; + unsigned creations = 0, path_returns = 0, client_replies = 0, fail_creation_on = 0; + bool create_ok = true, queue_ok = true; + bool metadata_reply = false; MyMesh() { assert(guest_login.begin(&fs)); } Clock* getRTCClock() { return &clock; } RNG* getRNG() { return &rng; } unsigned long futureMillis(unsigned long delay) { return 10000 + delay; } uint8_t handleLoginReq(const mesh::Identity&, const uint8_t*, uint32_t, const uint8_t*, bool); void onAnonDataRecv(mesh::Packet*, const uint8_t*, const mesh::Identity&, uint8_t*, size_t); - uint8_t handleAnonRegionsReq(const mesh::Identity&, uint32_t, const uint8_t*, size_t) { ++anonymous_requests; return 0; } - uint8_t handleAnonOwnerReq(const mesh::Identity&, uint32_t, const uint8_t*, size_t) { ++anonymous_requests; return 0; } - uint8_t handleAnonClockReq(const mesh::Identity&, uint32_t, const uint8_t*, size_t) { ++anonymous_requests; return 0; } + void sendDefaultPasswordWarning(ClientInfo*, uint32_t, uint8_t); + mesh::Packet* createDatagram(uint8_t type, const mesh::Identity& to, const uint8_t* key, + const uint8_t* data, size_t length) { + ++creations; + assert(length <= sizeof(response.payload)); + assert(to.matches(acl.clients[0].id) && !memcmp(key, acl.clients[0].shared_secret, PUB_KEY_SIZE)); + if (!create_ok || creations == fail_creation_on) return nullptr; + response = mesh::Packet{}; response.type = type; response.payload_len = length; + memcpy(response.payload, data, length); return &response; + } + mesh::Packet* createPathReturn(const mesh::Identity& to, const uint8_t* key, + const uint8_t*, uint8_t, uint8_t type, const uint8_t* data, size_t length) { + ++path_returns; + auto* packet = createDatagram(type, to, key, data, length); + if (packet) packet->path_return = true; + return packet; + } + bool sendDirect(mesh::Packet* packet, const uint8_t*, uint8_t length, unsigned long delay) { + assert(packet && mesh::Packet::isValidPathLen(length)); + packet->direct = true; packet->path_len = length; + if (queue_ok) sent.push_back({*packet, delay, 0}); + return queue_ok; + } + bool sendFloodReply(mesh::Packet* packet, unsigned long delay, uint8_t hash_size) { + assert(packet); packet->direct = false; + if (queue_ok) sent.push_back({*packet, delay, hash_size}); + return queue_ok; + } + bool sendClientReply(ClientInfo* client, mesh::Packet* packet, unsigned long delay, uint8_t hash_size) { + ++client_replies; + assert(client); + return mesh::Packet::isValidPathLen(client->out_path_len) + ? sendDirect(packet, client->out_path, client->out_path_len, delay) + : sendFloodReply(packet, delay, hash_size); + } + uint8_t handleAnonRegionsReq(const mesh::Identity&, uint32_t, const uint8_t*, size_t) { ++anonymous_requests; return metadata_reply ? 13 : 0; } + uint8_t handleAnonOwnerReq(const mesh::Identity&, uint32_t, const uint8_t*, size_t) { ++anonymous_requests; return metadata_reply ? 13 : 0; } + uint8_t handleAnonClockReq(const mesh::Identity&, uint32_t, const uint8_t*, size_t) { ++anonymous_requests; return metadata_reply ? 13 : 0; } bool handleGuestCommand(const char*, char*, size_t); int searchPeersByHash(const uint8_t*); void onPeerDataRecv(mesh::Packet*, uint8_t, int, const uint8_t*, uint8_t*, size_t); @@ -127,6 +185,7 @@ struct MyMesh { void dispatch(ClientInfo*, const char*, char*); }; @LOGIN@ +@PASSWORD_WARNING@ @ANONYMOUS@ @COMMAND@ @SEARCH@ @@ -408,6 +467,72 @@ static void anonymousRequestsAreNotLogins() { history(mesh, 1, 1, LoginResult::GuestsDisabled); assert(mesh.anonymous_requests == 3); } +static void useFactoryPassword(MyMesh& mesh) { + memset(mesh._prefs.password, 0, sizeof(mesh._prefs.password)); + const size_t limit = sizeof(mesh._prefs.password) - 1; + const size_t length = strlen(ADMIN_PASSWORD) < limit ? strlen(ADMIN_PASSWORD) : limit; + memcpy(mesh._prefs.password, ADMIN_PASSWORD, length); +} +static void defaultPasswordWarnings() { + const auto dispatch = [](MyMesh& mesh, const char* password, bool flood, uint32_t timestamp = 100) { + guest_metadata_fs = &mesh.fs; + uint8_t data[40]{}; memcpy(data, ×tamp, 4); + memcpy(data + 4, password, strlen(password)); + mesh::Packet request; request.direct = !flood; request.path_len = 0x42; + mesh.onAnonDataRecv(&request, secret, identity(1), data, 4 + strlen(password)); + }; + for (bool flood : {false, true}) { + MyMesh mesh; useFactoryPassword(mesh); + dispatch(mesh, mesh._prefs.password, flood); + assert(mesh.sent.size() == 2 && mesh.creations == 2); + const auto& login = mesh.sent[0]; const auto& warning = mesh.sent[1]; + assert(login.packet.type == PAYLOAD_TYPE_RESPONSE && login.packet.payload_len == 13); + assert(login.packet.payload[4] == RESP_SERVER_LOGIN_OK && login.packet.payload[12] == FIRMWARE_VER_LEVEL); + assert(login.delay == SERVER_RESPONSE_DELAY); + assert(warning.packet.type == PAYLOAD_TYPE_TXT_MSG && warning.packet.payload_len == 25); + assert(warning.packet.payload[4] == (TXT_TYPE_CLI_DATA << 2)); + assert(!memcmp(warning.packet.payload + 5, "CHANGE YOUR PASSWORD", 20)); + assert(warning.packet.radio_reply && warning.delay == SERVER_RESPONSE_DELAY + 2000UL); + assert(!warning.packet.direct && warning.hash_size == 2); + assert(mesh.path_returns == (flood ? 1U : 0U)); + assert(mesh.client_replies == 0); // Unknown routes use the scoped flood reply boundary. + } + // An assigned administrator may reconnect without resending the password. + MyMesh assigned; useFactoryPassword(assigned); + add(assigned, 1, PERM_ACL_ADMIN); dispatch(assigned, "", false); + assert(assigned.sent.size() == 2 && assigned.sent[1].packet.direct); + assert(assigned.client_replies == 1); + assigned.metadata_reply = true; + uint8_t query[7]{}; query[4] = ANON_REQ_TYPE_OWNER; + mesh::Packet metadata; + assigned.onAnonDataRecv(&metadata, secret, identity(1), query, sizeof(query) - 1); + assert(assigned.sent.size() == 3 && assigned.client_replies == 1); + for (unsigned failure = 0; failure < 9; ++failure) { + MyMesh mesh; useFactoryPassword(mesh); + const char* password = mesh._prefs.password; + if (failure == 0) { strcpy(mesh._prefs.password, "changed-secret"); password = "changed-secret"; } + if (failure == 1) password = "wrong"; + if (failure == 2) { assert(mesh.guest_login.setEnabled(true)); password = ""; } + if (failure == 3) mesh.acl.authorize_ok = false; + if (failure == 4) mesh.create_ok = false; + if (failure == 5) mesh.queue_ok = false; + if (failure == 6) { add(mesh, 1, PERM_ACL_FILTER_MGR); password = ""; } + if (failure == 7) mesh.acl.allocate_ok = false; + if (failure == 8) mesh.fail_creation_on = 2; + dispatch(mesh, password, false); + assert(mesh.sent.size() == (failure == 0 || failure == 2 || failure == 6 || failure == 8 ? 1U : 0U)); + for (const auto& sent : mesh.sent) assert(sent.packet.type == PAYLOAD_TYPE_RESPONSE); + } + MyMesh replay; useFactoryPassword(replay); + dispatch(replay, replay._prefs.password, false); + dispatch(replay, replay._prefs.password, false); + assert(replay.sent.size() == 2); + MyMesh empty; auto* admin = add(empty, 1, PERM_ACL_ADMIN); + empty._prefs.password[0] = 0; + empty.sendDefaultPasswordWarning(admin, 100, 1); + empty.sendDefaultPasswordWarning(nullptr, 100, 1); + assert(empty.creations == 0 && empty.sent.empty()); +} int main(int argc, char** argv) { assert(argc == 2); if (!strcmp(argv[1], "passwords")) defaultsAndPasswords(); @@ -417,6 +542,7 @@ int main(int argc, char** argv) { else if (!strcmp(argv[1], "receive")) receiveAdmission(); else if (!strcmp(argv[1], "history")) loginHistoryDecisions(); else if (!strcmp(argv[1], "anonymous")) anonymousRequestsAreNotLogins(); + else if (!strcmp(argv[1], "default-password")) defaultPasswordWarnings(); else assert(false); printf("repeater guest %s passed\n", argv[1]); } @@ -437,6 +563,10 @@ class RepeaterGuestAccessTests(unittest.TestCase): for name in ("FIRMWARE_VER_LEVEL", "RESP_SERVER_LOGIN_OK", "LAZY_CONTACTS_WRITE_DELAY", "ANON_REQ_TYPE_REGIONS", "ANON_REQ_TYPE_OWNER", "ANON_REQ_TYPE_BASIC"): constants += "\n" + re.search(r"^#define\s+" + name + r"\s+.*$", source, re.MULTILINE).group() + constants += "\n" + re.search( + r"static constexpr uint32_t LOGIN_PATH_OBSERVATION_TIMEOUT_MS[^;]*;", source).group() + constants += "\n" + re.search(r"^\s*#define SERVER_RESPONSE_DELAY[^\n]*", + source, re.MULTILINE).group() manager_helpers = "\n".join(extract_braced(source, signature) for signature in ( "static bool commandFamilyMatches(", "static bool commandListMatches(", "static bool isCommonManagerReadOnlyAllowed(", "static bool isRegionMgrAllowed(", @@ -457,14 +587,20 @@ class RepeaterGuestAccessTests(unittest.TestCase): request = extract_braced(source, "int MyMesh::handleRequest(") request_admission = request[:request.index(" if (reply_capacity >")] + "++received; return 1;\n}" anonymous = extract_braced(source, "void MyMesh::onAnonDataRecv(") - anonymous = anonymous[:anonymous.index(" if (reply_len == 0) return;")] + " (void)reply_len;\n }\n}" cls.source_text = source + packet = (ROOT / "src/Packet.cpp").read_text() + routing = (ROOT / "src/helpers/RoutingPolicy.h").read_text() replacements = { "@CONSTANTS@": constants, "@CLIENT_INFO@": extract_braced(acl_header, "struct ClientInfo {"), "@REMOVE_GUESTS@": extract_braced(acl_source, "int ClientACL::removeGuestClients("), "@MANAGER_HELPERS@": manager_helpers, "@LOGIN@": extract_braced(source, "uint8_t MyMesh::handleLoginReq("), + "@PASSWORD_WARNING@": extract_braced(source, "void MyMesh::sendDefaultPasswordWarning("), + "@PACKET_HELPERS@": "\n".join(extract_braced(packet, signature) for signature in ( + "bool Packet::isValidPathLen(", "size_t Packet::writePath(")), + "@ROUTING_HELPERS@": extract_braced(routing, "enum ReplyRoute") + ";\n" + + extract_braced(routing, "inline ReplyRoute chooseReplyRoute("), "@ANONYMOUS@": anonymous, "@COMMAND@": extract_braced(source, "bool MyMesh::handleGuestCommand("), "@SEARCH@": extract_braced(source, "int MyMesh::searchPeersByHash("), @@ -485,15 +621,19 @@ class RepeaterGuestAccessTests(unittest.TestCase): sanitizer = (["-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-fno-omit-frame-pointer", "-fno-pie", "-no-pie"] if sys.platform.startswith("linux") else []) - result = subprocess.run([ + command = [ compiler, "-std=c++17", "-O1", "-g", "-Wall", "-Wextra", "-Werror", "-Wno-unused-parameter", "-Wno-sign-compare", "-Wno-misleading-indentation", "-DESP32_PLATFORM", "-DESP32", *sanitizer, "-I", str(FIXTURE / "mocks"), "-I", str(ROOT / "src"), str(cpp), str(ROOT / "src/helpers/GuestLoginSettings.cpp"), "-o", str(cls.binary), - ], capture_output=True, text=True, timeout=60) + ] + result = subprocess.run(command, capture_output=True, text=True, timeout=60) if result.returncode: raise AssertionError(result.stdout + result.stderr) + cls.generated = generated + cls.compile_command = command + cls.source = cpp def scenario(self, name): result = subprocess.run([str(self.binary), name], capture_output=True, text=True, timeout=15) @@ -521,6 +661,25 @@ class RepeaterGuestAccessTests(unittest.TestCase): def test_only_login_requests_enter_history(self): self.scenario("anonymous") + def test_default_password_admin_login_warns_after_the_binary_reply(self): + self.scenario("default-password") + + def test_custom_factory_password_and_bounded_long_factory_password(self): + for index, factory in enumerate(("factory-admin", "12345678901234567890")): + with self.subTest(factory=factory): + source = Path(self.work.name) / ("factory-" + str(index) + ".cpp") + source.write_text(self.generated.replace('#define ADMIN_PASSWORD "password"', + '#define ADMIN_PASSWORD ' + json.dumps(factory))) + binary = source.with_suffix("") + command = [str(source) if value == str(self.source) + else str(binary) if value == str(self.binary) else value + for value in self.compile_command] + built = subprocess.run(command, capture_output=True, text=True, timeout=60) + self.assertEqual(built.returncode, 0, built.stdout + built.stderr) + checked = subprocess.run([str(binary), "default-password"], + capture_output=True, text=True, timeout=15) + self.assertEqual(checked.returncode, 0, checked.stdout + checked.stderr) + def test_password_bytes_are_not_logged(self): login = extract_braced(self.source_text, "uint8_t MyMesh::handleLoginReq(") debug_calls = re.findall(r"MESH_DEBUG_PRINTLN\([\s\S]*?\);", login) diff --git a/test/test_room_login_integration.py b/test/test_room_login_integration.py index 3dce696ca..afbdd011d 100644 --- a/test/test_room_login_integration.py +++ b/test/test_room_login_integration.py @@ -2,6 +2,7 @@ """Execute the real room login/replay handlers against controlled storage faults.""" from pathlib import Path +import json import re import shutil import subprocess @@ -36,6 +37,8 @@ HARNESS = r''' #include #include #include +#include +#define ADMIN_PASSWORD "password" @CONSTANTS@ @STR_HELPER@ #define MESH_CLIENT_REPEATER_ONLY 0 @@ -190,8 +193,8 @@ struct MyMesh { mesh::Packet* createAck(uint32_t ack) { ++post_acks; response.payload_len = 4; memcpy(response.payload, &ack, 4); return &response; } mesh::Packet* createMultiAck(uint32_t ack, uint8_t) { return createAck(ack); } struct Prefs { - char password[32] = "admin"; - char guest_password[32] = "guest"; + char password[16] = "admin"; + char guest_password[16] = "guest"; bool allow_read_only = false; uint8_t direct_retry_enabled = 1; } _prefs; @@ -201,6 +204,10 @@ struct MyMesh { uint8_t contacts_save_failures = 0, reply_data[32] = {}; unsigned creations = 0, direct_sends = 0, flood_sends = 0, path_returns = 0; bool create_ok = true, queue_ok = true; + unsigned fail_creation_on = 0; + uint8_t created_type = 0; + struct Sent { uint8_t type; std::vector data; unsigned long delay; bool direct; bool radio_reply; uint8_t hash_size; }; + std::vector sent; mesh::Packet response; uint8_t response_secret[PUB_KEY_SIZE] = {}, response_key[PUB_KEY_SIZE] = {}; uint8_t returned_path[MAX_PATH_SIZE] = {}, direct_path[MAX_PATH_SIZE] = {}; @@ -218,13 +225,15 @@ struct MyMesh { mesh::Packet* createDatagram(uint8_t type, const mesh::Identity& sender, const uint8_t* secret, const uint8_t* data, size_t len) { ++creations; + created_type = type; + response.radio_reply = false; assert(type == PAYLOAD_TYPE_RESPONSE || type == PAYLOAD_TYPE_TXT_MSG); assert(len <= sizeof(captured_reply)); memcpy(response_key, sender.pub_key, PUB_KEY_SIZE); memcpy(response_secret, secret, PUB_KEY_SIZE); memcpy(captured_reply, data, len); captured_reply_length = len; - return create_ok ? &response : nullptr; + return create_ok && creations != fail_creation_on ? &response : nullptr; } mesh::Packet* createPathReturn(const mesh::Identity& sender, const uint8_t* secret, const uint8_t* path, uint8_t path_len, uint8_t type, const uint8_t* data, size_t len) { @@ -235,17 +244,23 @@ struct MyMesh { } bool sendDirect(mesh::Packet* packet, const uint8_t* path, uint8_t path_len, unsigned long delay) { - assert(packet == &response && (delay == SERVER_RESPONSE_DELAY || delay == TXT_ACK_DELAY)); + assert(packet == &response && (delay == SERVER_RESPONSE_DELAY || delay == TXT_ACK_DELAY + || (packet->radio_reply && delay == SERVER_RESPONSE_DELAY + 2000UL))); assert(mesh::Packet::isValidPathLen(path_len)); ++direct_sends; direct_path_len = path_len; memcpy(direct_path, path, (path_len & 63) * ((path_len >> 6) + 1)); + if (queue_ok) sent.push_back({created_type, std::vector(captured_reply, + captured_reply + captured_reply_length), delay, true, packet->radio_reply, 0}); return queue_ok; } bool sendFloodReply(mesh::Packet* packet, unsigned long delay, uint8_t hash_size) { - assert(packet == &response && (delay == SERVER_RESPONSE_DELAY || delay == TXT_ACK_DELAY)); + assert(packet == &response && (delay == SERVER_RESPONSE_DELAY || delay == TXT_ACK_DELAY + || (packet->radio_reply && delay == SERVER_RESPONSE_DELAY + 2000UL))); ++flood_sends; reply_hash_size = hash_size; + if (queue_ok) sent.push_back({created_type, std::vector(captured_reply, + captured_reply + captured_reply_length), delay, false, packet->radio_reply, hash_size}); return queue_ok; } bool store_ok = true; @@ -275,7 +290,9 @@ struct MyMesh { bool onPeerPathRecv(mesh::Packet*, int, const uint8_t*, uint8_t*, uint8_t, uint8_t, uint8_t*, uint8_t); void onAnonDataRecv(mesh::Packet*, const uint8_t*, const mesh::Identity&, uint8_t*, size_t); + void sendDefaultPasswordWarning(ClientInfo*, uint32_t, uint8_t); }; +@PASSWORD_WARNING@ @LOGIN_HANDLER@ @PEER_HANDLER@ @PATH_HANDLER@ @@ -818,6 +835,52 @@ static void allRequestQuotaCases() { } puts("actual request quota covers status, telemetry, ACL, board, and exact payload retries passed"); } +static void useFactoryPassword(MyMesh& mesh) { + memset(mesh._prefs.password, 0, sizeof(mesh._prefs.password)); + const size_t limit = sizeof(mesh._prefs.password) - 1; + const size_t length = strlen(ADMIN_PASSWORD) < limit ? strlen(ADMIN_PASSWORD) : limit; + memcpy(mesh._prefs.password, ADMIN_PASSWORD, length); +} +static void defaultPasswordWarnings() { + for (bool flood : {false, true}) { + MyMesh mesh; useFactoryPassword(mesh); + const uint32_t requested = mesh.clock.now + 2; // Force the warning timestamp collision guard. + login(mesh, mesh._prefs.password, requested, 0, flood); + assert(mesh.sent.size() == 2 && mesh.creations == 2); + const auto& response = mesh.sent[0]; const auto& warning = mesh.sent[1]; + assert(response.type == PAYLOAD_TYPE_RESPONSE && response.data.size() == 13); + assert(response.data[4] == RESP_SERVER_LOGIN_OK && response.data[12] == FIRMWARE_VER_LEVEL); + assert(response.delay == SERVER_RESPONSE_DELAY); + assert(warning.type == PAYLOAD_TYPE_TXT_MSG && warning.data.size() == 25); + assert(warning.data[4] == (TXT_TYPE_CLI_DATA << 2)); + assert(!memcmp(warning.data.data() + 5, "CHANGE YOUR PASSWORD", 20)); + uint32_t timestamp; memcpy(×tamp, warning.data.data(), 4); + assert(timestamp != requested && warning.radio_reply); + assert(warning.delay == SERVER_RESPONSE_DELAY + 2000UL && !warning.direct && warning.hash_size == 2); + assert(mesh.path_returns == (flood ? 1U : 0U)); + } + MyMesh assigned; useFactoryPassword(assigned); + seedKnown(assigned, PERM_ACL_ADMIN); login(assigned, ""); + assert(assigned.sent.size() == 2 && assigned.sent[1].direct); + for (unsigned failure = 0; failure < 7; ++failure) { + MyMesh mesh; useFactoryPassword(mesh); + const char* password = mesh._prefs.password; + if (failure == 0) { strcpy(mesh._prefs.password, "changed-secret"); password = "changed-secret"; } + if (failure == 1) password = "wrong"; + if (failure == 2) password = "guest"; + if (failure == 3) mesh.acl.storage.write_ok = false; + if (failure == 4) mesh.create_ok = false; + if (failure == 5) mesh.queue_ok = false; + if (failure == 6) mesh.fail_creation_on = 2; + login(mesh, password); + assert(mesh.sent.size() == (failure == 0 || failure == 2 || failure == 6 ? 1U : 0U)); + for (const auto& sent : mesh.sent) assert(sent.type == PAYLOAD_TYPE_RESPONSE); + } + MyMesh replay; useFactoryPassword(replay); + login(replay, replay._prefs.password); login(replay, replay._prefs.password); + assert(replay.sent.size() == 2); + puts("default password warning follows successful admin login without changing the binary response passed"); +} int main(int argc, char** argv) { assert(argc == 2); if (!strcmp(argv[1], "authorization")) authorizationCases(); @@ -830,6 +893,7 @@ int main(int argc, char** argv) { else if (!strcmp(argv[1], "requests")) allRequestQuotaCases(); else if (!strcmp(argv[1], "observed")) observedLoginPath(); else if (!strcmp(argv[1], "reconnect")) reconnectCursor(); + else if (!strcmp(argv[1], "default-password")) defaultPasswordWarnings(); else assert(false); } ''' @@ -898,6 +962,7 @@ class RoomLoginIntegrationTests(unittest.TestCase): room, "uint8_t MyMesh::getUnsyncedCount(")), "@ROOM_MAIL_STATUS@": extract_braced(room, "bool MyMesh::roomClientChatEnabled("), "@LOGIN_HANDLER@": extract_braced(room, "void MyMesh::onAnonDataRecv("), + "@PASSWORD_WARNING@": extract_braced(room, "void MyMesh::sendDefaultPasswordWarning("), } generated = HARNESS for marker, text in replacements.items(): @@ -930,6 +995,25 @@ class RoomLoginIntegrationTests(unittest.TestCase): def test_unknown_blank_read_only_disabled_passwords_and_payload_bounds(self): self.run_case("authorization", "real-handler credentials, disabled passwords, and minimum payload cases passed") + def test_default_password_admin_login_warns_after_the_binary_reply(self): + self.run_case("default-password", "default password warning follows successful admin login") + + def test_custom_factory_password_and_bounded_long_factory_password(self): + for index, factory in enumerate(("factory-admin", "12345678901234567890")): + with self.subTest(factory=factory): + source = Path(self.directory.name) / ("factory-" + str(index) + ".cpp") + source.write_text(self.generated.replace('#define ADMIN_PASSWORD "password"', + '#define ADMIN_PASSWORD ' + json.dumps(factory))) + binary = source.with_suffix("") + command = [str(source) if value == str(self.source) + else str(binary) if value == str(self.binary) else value + for value in self.compile_command] + built = subprocess.run(command, capture_output=True, text=True, timeout=60) + self.assertEqual(built.returncode, 0, built.stdout + built.stderr) + checked = subprocess.run([str(binary), "default-password"], + capture_output=True, text=True, timeout=15) + self.assertEqual(checked.returncode, 0, checked.stdout + checked.stderr) + def test_non_demotion_all_roles_and_exact_replay_preserve_session(self): self.run_case("roles", "2048 real-handler preserved roles and replay rejects plus 256 admin upgrades passed") diff --git a/test/test_room_login_replay_capacity.py b/test/test_room_login_replay_capacity.py index b55f19d85..e589ef1e5 100644 --- a/test/test_room_login_replay_capacity.py +++ b/test/test_room_login_replay_capacity.py @@ -73,7 +73,9 @@ struct MyMesh { return createDatagram(type, sender, secret, data, length); } bool sendFloodReply(mesh::Packet*, unsigned long, uint8_t) { return true; } - void sendDirect(mesh::Packet*, const uint8_t*, uint8_t, unsigned long) {} + bool sendDirect(mesh::Packet*, const uint8_t*, uint8_t, unsigned long) { return true; } + // The production warning sender is covered by RoomLoginIntegrationTests. + void sendDefaultPasswordWarning(ClientInfo*, uint32_t, uint8_t) {} static bool saveFilter(ClientInfo*); void onAnonDataRecv(mesh::Packet*, const uint8_t*, const mesh::Identity&, uint8_t*, size_t); };