Files
meshcore-tth/src/helpers/ClientACL.cpp
T

277 lines
9.5 KiB
C++

#include "ClientACL.h"
static File openWrite(FILESYSTEM* _fs, const char* filename) {
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
_fs->remove(filename);
return _fs->open(filename, FILE_O_WRITE);
#elif defined(RP2040_PLATFORM)
return _fs->open(filename, "w");
#else
return _fs->open(filename, "w", true);
#endif
}
void ClientACL::load(FILESYSTEM* fs, const mesh::LocalIdentity& self_id) {
_fs = fs;
num_clients = 0;
if (_fs->exists("/s_contacts")) {
#if defined(RP2040_PLATFORM)
File file = _fs->open("/s_contacts", "r");
#else
File file = _fs->open("/s_contacts");
#endif
if (file) {
bool full = false;
while (!full) {
ClientInfo c;
uint8_t pub_key[32];
uint8_t unused[2];
memset(&c, 0, sizeof(c));
bool success = (file.read(pub_key, 32) == 32);
success = success && (file.read((uint8_t *) &c.permissions, 1) == 1);
success = success && (file.read((uint8_t *) &c.extra.room.sync_since, 4) == 4);
success = success && (file.read(unused, 2) == 2);
success = success && (file.read((uint8_t *)&c.out_path_len, 1) == 1);
success = success && (file.read(c.out_path, 64) == 64);
success = success && (file.read(c.shared_secret, PUB_KEY_SIZE) == PUB_KEY_SIZE); // will be recalculated below
if (!success) break; // EOF
c.id = mesh::Identity(pub_key);
self_id.calcSharedSecret(c.shared_secret, pub_key); // recalculate shared secrets in case our private key changed
if (num_clients < MAX_CLIENTS) {
clients[num_clients++] = c;
} else {
full = true;
}
}
file.close();
}
}
loadTimestamps();
}
// CUSTOM (TeTeHacko): /s_acl_ts0 and /s_acl_ts1 are written alternately, each
// {pubkey prefix 8, timestamp 4} * n + seq 4 + sha256 tag 4. A write torn by a
// power cut leaves the other slot intact, and the floor is the max over both
// valid slots, so it can only ever move forward. The next write always goes over
// the OLDER slot (lower seq) -- and a torn write means the command it guarded
// never ran, so nothing executed is lost.
#define ACL_TS_PREFIX 8
#define ACL_TS_RECORD (ACL_TS_PREFIX + 4)
static const char* tsFilename(uint8_t slot) { return slot ? "/s_acl_ts1" : "/s_acl_ts0"; }
void ClientACL::loadTimestamps() {
static uint8_t buf[2 * MAX_CLIENTS * ACL_TS_RECORD + 8];
_num_ts_orphans = 0;
_ts_seq = 0;
_ts_slot = 0;
bool have_newest = false;
for (uint8_t slot = 0; slot < 2; slot++) {
if (!_fs->exists(tsFilename(slot))) continue;
#if defined(RP2040_PLATFORM)
File file = _fs->open(tsFilename(slot), "r");
#else
File file = _fs->open(tsFilename(slot));
#endif
if (!file) continue;
int len = file.read(buf, sizeof(buf));
file.close();
if (len < 8 || (len - 8) % ACL_TS_RECORD != 0) continue;
uint8_t tag[4];
mesh::Utils::sha256(tag, 4, buf, len - 4);
if (memcmp(tag, &buf[len - 4], 4) != 0) continue; // torn write: ignore this slot
uint32_t seq;
memcpy(&seq, &buf[len - 8], 4);
if (!have_newest || seq > _ts_seq) {
_ts_seq = seq;
_ts_slot = slot ^ 1; // next write goes over the other, older slot
have_newest = true;
}
for (int ofs = 0; ofs < len - 8; ofs += ACL_TS_RECORD) {
uint32_t ts;
memcpy(&ts, &buf[ofs + ACL_TS_PREFIX], 4);
ClientInfo* c = getClient(&buf[ofs], ACL_TS_PREFIX);
if (c) {
if (ts > c->saved_timestamp) c->saved_timestamp = ts;
continue;
}
// Not in /s_contacts: a fresh login whose lazy ACL write a reboot beat, or an
// evicted guest. Keep the floor, or replaying their login would re-admit them.
int j = 0;
while (j < _num_ts_orphans && memcmp(_ts_orphans[j].prefix, &buf[ofs], ACL_TS_PREFIX) != 0) j++;
if (j == _num_ts_orphans) {
if (j == MAX_CLIENTS) continue;
memcpy(_ts_orphans[j].prefix, &buf[ofs], ACL_TS_PREFIX);
_ts_orphans[j].ts = 0;
_num_ts_orphans++;
}
if (ts > _ts_orphans[j].ts) _ts_orphans[j].ts = ts;
}
}
for (int i = 0; i < num_clients; i++) {
clients[i].last_timestamp = clients[i].saved_timestamp;
}
}
void ClientACL::saveTimestamps() {
if (!_fs) return;
static uint8_t buf[2 * MAX_CLIENTS * ACL_TS_RECORD + 8];
int len = 0;
for (int i = 0; i < num_clients; i++) {
if (clients[i].saved_timestamp == 0) continue;
memcpy(&buf[len], clients[i].id.pub_key, ACL_TS_PREFIX);
memcpy(&buf[len + ACL_TS_PREFIX], &clients[i].saved_timestamp, 4);
len += ACL_TS_RECORD;
}
for (int i = 0; i < _num_ts_orphans; i++) {
memcpy(&buf[len], _ts_orphans[i].prefix, ACL_TS_PREFIX);
memcpy(&buf[len + ACL_TS_PREFIX], &_ts_orphans[i].ts, 4);
len += ACL_TS_RECORD;
}
_ts_seq++;
memcpy(&buf[len], &_ts_seq, 4);
len += 4;
mesh::Utils::sha256(&buf[len], 4, buf, len);
len += 4;
File file = openWrite(_fs, tsFilename(_ts_slot));
if (file) {
file.write(buf, len);
file.close();
}
_ts_slot ^= 1;
}
void ClientACL::orphanTimestamp(const ClientInfo* c) {
if (c->saved_timestamp == 0) return;
if (_num_ts_orphans == MAX_CLIENTS) { // full: drop the oldest
memmove(&_ts_orphans[0], &_ts_orphans[1], (MAX_CLIENTS - 1) * sizeof(TsOrphan));
_num_ts_orphans--;
}
memcpy(_ts_orphans[_num_ts_orphans].prefix, c->id.pub_key, ACL_TS_PREFIX);
_ts_orphans[_num_ts_orphans].ts = c->saved_timestamp;
_num_ts_orphans++;
}
void ClientACL::persistTimestamp(ClientInfo* c, uint32_t sender_timestamp, uint32_t now) {
// Admins only. A guest can only read, and anybody gets in as one when the
// guest password is empty (the default): its every request would be a flash
// write, and its floors would push the admins' out of the orphan list. Its
// floor stays in RAM, as upstream.
if (!c->isAdmin()) return;
if (sender_timestamp <= c->saved_timestamp) return; // retry, or nothing new
if (sender_timestamp > now + ACL_TS_MAX_AHEAD) return; // runaway sender clock
c->saved_timestamp = sender_timestamp;
saveTimestamps();
}
void ClientACL::save(FILESYSTEM* fs, bool (*filter)(ClientInfo*)) {
_fs = fs;
File file = openWrite(_fs, "/s_contacts");
if (file) {
uint8_t unused[2];
memset(unused, 0, sizeof(unused));
for (int i = 0; i < num_clients; i++) {
auto c = &clients[i];
if (c->permissions == 0 || (filter && !filter(c))) continue; // skip deleted entries, or by filter function
bool success = (file.write(c->id.pub_key, 32) == 32);
success = success && (file.write((uint8_t *) &c->permissions, 1) == 1);
success = success && (file.write((uint8_t *) &c->extra.room.sync_since, 4) == 4);
success = success && (file.write(unused, 2) == 2);
success = success && (file.write((uint8_t *)&c->out_path_len, 1) == 1);
success = success && (file.write(c->out_path, 64) == 64);
success = success && (file.write(c->shared_secret, PUB_KEY_SIZE) == PUB_KEY_SIZE);
if (!success) break; // write failed
}
file.close();
}
}
bool ClientACL::clear() {
if (!_fs) return false; // no filesystem, nothing to clear
if (_fs->exists("/s_contacts")) {
_fs->remove("/s_contacts");
}
// The replay floors outlive the ACL: with them gone, a captured password login
// would be accepted again.
for (int i = 0; i < num_clients; i++) orphanTimestamp(&clients[i]);
memset(clients, 0, sizeof(clients));
num_clients = 0;
saveTimestamps();
return true;
}
ClientInfo* ClientACL::getClient(const uint8_t* pubkey, int key_len) {
for (int i = 0; i < num_clients; i++) {
if (memcmp(pubkey, clients[i].id.pub_key, key_len) == 0) return &clients[i]; // already known
}
return NULL; // not found
}
ClientInfo* ClientACL::putClient(const mesh::Identity& id, uint8_t init_perms) {
uint32_t min_time = 0xFFFFFFFF;
ClientInfo* oldest = &clients[MAX_CLIENTS - 1];
for (int i = 0; i < num_clients; i++) {
if (id.matches(clients[i].id)) return &clients[i]; // already known
if (!clients[i].isAdmin() && clients[i].last_activity < min_time) {
oldest = &clients[i];
min_time = oldest->last_activity;
}
}
ClientInfo* c;
if (num_clients < MAX_CLIENTS) {
c = &clients[num_clients++];
} else {
c = oldest; // evict least active contact
orphanTimestamp(c);
}
memset(c, 0, sizeof(*c));
c->permissions = init_perms;
c->id = id;
c->out_path_len = OUT_PATH_UNKNOWN;
for (int i = 0; i < _num_ts_orphans; i++) { // known before: its replay floor comes back
if (memcmp(_ts_orphans[i].prefix, id.pub_key, ACL_TS_PREFIX) == 0) {
c->saved_timestamp = c->last_timestamp = _ts_orphans[i].ts;
_num_ts_orphans--;
memmove(&_ts_orphans[i], &_ts_orphans[i + 1], (_num_ts_orphans - i) * sizeof(TsOrphan));
break;
}
}
return c;
}
bool ClientACL::applyPermissions(const mesh::LocalIdentity& self_id, const uint8_t* pubkey, int key_len, uint8_t perms) {
ClientInfo* c;
if ((perms & PERM_ACL_ROLE_MASK) == PERM_ACL_GUEST) { // guest role is not persisted in contacts
c = getClient(pubkey, key_len);
if (c == NULL) return false; // partial pubkey not found
orphanTimestamp(c);
num_clients--; // delete from contacts[]
int i = c - clients;
while (i < num_clients) {
clients[i] = clients[i + 1];
i++;
}
} else {
if (key_len < PUB_KEY_SIZE) return false; // need complete pubkey when adding/modifying
mesh::Identity id(pubkey);
c = putClient(id, 0);
c->permissions = perms; // update their permissions
self_id.calcSharedSecret(c->shared_secret, pubkey);
}
return true;
}