feat(repeater): antispam — FairnessLimiter (port #1502) + kanálový deny list

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
tthandClaude Fable 5 committed 2026-09-05 21:35:36 +02:00
1 parent de5bd52bd9
commit 6f90c80dcc
15 files changed
+1098 -112

No files matched your search

+11 -6
View File
@@ -11,9 +11,12 @@ void Mesh::loop() {
Dispatcher::loop();
}
bool Mesh::allowPacketForward(const mesh::Packet* packet) {
bool Mesh::allowPacketForward(const mesh::Packet* packet) {
return false; // by default, Transport NOT enabled
}
bool Mesh::takeForwardingRateLimit(const mesh::Packet* packet) {
return true; // by default, rate limiting is not implemented
}
uint32_t Mesh::getRetransmitDelay(const mesh::Packet* packet) {
uint32_t t = (_radio->getEstAirtimeFor(packet->getRawLength()) * 52 / 50) / 2;
@@ -60,7 +63,8 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
if (offset >= len) { // TRACE has reached end of given path
onTraceRecv(pkt, trace_tag, auth_code, flags, pkt->path, &pkt->payload[i], len);
} else if ((size_t)i + offset + (1u << path_sz) <= pkt->payload_len
&& self_id.isHashMatch(&pkt->payload[i + offset], 1 << path_sz) && allowPacketForward(pkt) && !_tables->wasSeen(pkt)) {
&& self_id.isHashMatch(&pkt->payload[i + offset], 1 << path_sz) && allowPacketForward(pkt) && !_tables->wasSeen(pkt)
&& takeForwardingRateLimit(pkt)) {
_tables->markSeen(pkt);
// append SNR (Not hash!)
pkt->path[pkt->path_len++] = (int8_t) (pkt->getSNR()*4);
@@ -103,12 +107,12 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
return ACTION_RELEASE;
}
if (!_tables->wasSeen(pkt)) {
if (!_tables->wasSeen(pkt) && takeForwardingRateLimit(pkt)) {
_tables->markSeen(pkt);
removeSelfFromPath(pkt);
uint32_t d = getDirectRetransmitDelay(pkt);
return ACTION_RETRANSMIT_DELAYED(0, d); // Routed traffic is HIGHEST priority
return ACTION_RETRANSMIT_DELAYED(0, d); // Routed traffic is HIGHEST priority
}
}
return ACTION_RELEASE; // this node is NOT the next hop (OR this packet has already been forwarded), so discard.
@@ -355,7 +359,8 @@ void Mesh::removeSelfFromPath(Packet* pkt) {
DispatcherAction Mesh::routeRecvPacket(Packet* packet) {
uint8_t n = packet->getPathHashCount();
if (packet->isRouteFlood() && !packet->isMarkedDoNotRetransmit()
&& (n + 1)*packet->getPathHashSize() <= MAX_PATH_SIZE && allowPacketForward(packet)) {
&& (n + 1)*packet->getPathHashSize() <= MAX_PATH_SIZE && allowPacketForward(packet)
&& takeForwardingRateLimit(packet)) {
// append this node's hash to 'path'
self_id.copyHashTo(&packet->path[n * packet->getPathHashSize()], packet->getPathHashSize());
packet->setPathHashCount(n + 1);
@@ -388,7 +393,7 @@ DispatcherAction Mesh::forwardMultipartDirect(Packet* pkt) {
}
void Mesh::routeDirectRecvAcks(Packet* packet, uint32_t delay_millis) {
if (!packet->isMarkedDoNotRetransmit()) {
if (!packet->isMarkedDoNotRetransmit() && takeForwardingRateLimit(packet)) {
uint8_t extra = getExtraAckTransmitCount();
while (extra > 0) {
delay_millis += getDirectRetransmitDelay(packet) + 300;
+8
View File
@@ -56,6 +56,14 @@ protected:
*/
virtual bool allowPacketForward(const Packet* packet);
/**
* \brief Takes a token from the rate-limiter, deciding whether this packet should be forwarded.
* May CONSUME limiter state, so callers keep it as the LAST condition of a forward decision
* and call it at most once per packet. (CUSTOM TeTeHacko: port of upstream proposal #1502.)
* \returns true, if the packet should be forwarded
*/
virtual bool takeForwardingRateLimit(const Packet* packet);
/**
* \returns number of milliseconds delay to apply to retransmitting the given packet.
*/
+8
View File
@@ -72,6 +72,11 @@ public:
uint8_t loop_detect = 0;
uint8_t cad_enabled = 0; // hardware Channel Activity Detection before TX (boolean)
uint8_t extra_sf[4];
// CUSTOM (TeTeHacko): antispam knobs of simple_repeater. Live here so that the
// existing savePrefs()/loadPrefs() machinery persists them; other examples
// just leave them at defaults.
uint8_t fairness_enabled = 0; // FairnessLimiter runtime kill switch
char filter_deny[128]; // channel-filter deny list, comma-separated node names
private:
class RadioPrefs : public CommonRadioPrefs {
@@ -186,6 +191,8 @@ private:
def("f_max_uns", _parent->flood_max_unscoped);
def("f_max_adv", _parent->flood_max_advert);
def("loop", _parent->loop_detect);
def("fair_en", _parent->fairness_enabled);
def("f_deny", _parent->filter_deny, sizeof(_parent->filter_deny));
}
public:
RepeatPrefs(NodePrefs* parent) : _parent(parent) { }
@@ -231,6 +238,7 @@ public:
guest_password[0] = 0;
bridge_secret[0] = 0;
owner_info[0] = 0;
filter_deny[0] = 0;
}
CommonRadioPrefs* getRadioPrefs() { return &radio; }
+154
View File
@@ -0,0 +1,154 @@
#include "FairnessLimiter.h"
#include <MeshCore.h>
uint8_t FairnessLimiter::peekGroup(const uint8_t* hash) {
auto i = group_idx(hash);
if (i >= GROUP_MAP_SIZE) {
return 0;
}
return group_map[i];
}
bool FairnessLimiter::takeGroup(const uint8_t* hash) {
auto i = group_idx(hash);
bool allow = false;
if (i < GROUP_MAP_SIZE && group_map[i] > 0) {
group_map[i]--;
allow = true;
} else {
denied_group++;
}
MESH_DEBUG_PRINTLN("FAIR, group=%02X allow=%u", (uint32_t)hash[0], (uint32_t)allow);
return allow;
}
void FairnessLimiter::refillGroup() {
for (int i = 0; i < GROUP_MAP_SIZE; i++) {
if (group_map[i] < group_cap) {
group_map[i]++;
}
}
}
uint8_t FairnessLimiter::peekSenderNormal(const uint8_t* hash) {
// Always zero as 0x00 and 0xFF are reserved
if (hash[0] == 0x00 || hash[0] == 0xFF) {
return 0;
}
auto i = sender_normal_idx(hash);
if (i >= SENDER_NORMAL_MAP_SIZE) {
return 0;
}
return sender_normal_map[i];
}
bool FairnessLimiter::takeSenderNormal(const uint8_t* hash) {
// Always false as 0x00 and 0xFF are reserved
if (hash[0] == 0x00 || hash[0] == 0xFF) {
return false;
}
auto i = sender_normal_idx(hash);
bool allow = false;
if (i < SENDER_NORMAL_MAP_SIZE && sender_normal_map[i] > 0) {
sender_normal_map[i]--;
allow = true;
} else {
denied_sender_normal++;
}
MESH_DEBUG_PRINTLN("FAIR, sender=%02X prio=normal allow=%u", (uint32_t)hash[0], (uint32_t)allow);
return allow;
}
void FairnessLimiter::refillSenderNormal() {
for (int i = 0; i < SENDER_NORMAL_MAP_SIZE; i++) {
if (sender_normal_map[i] < sender_normal_cap) {
sender_normal_map[i]++;
}
}
}
uint8_t FairnessLimiter::peekSenderLow(const uint8_t* hash) {
// Always zero as 0x00 and 0xFF are reserved
if (hash[0] == 0x00 || hash[0] == 0xFF) {
return 0;
}
auto i = sender_low_idx(hash);
if (i >= SENDER_LOW_MAP_SIZE) {
return 0;
}
return sender_low_map[i];
}
bool FairnessLimiter::takeSenderLow(const uint8_t* hash) {
// Always false as 0x00 and 0xFF are reserved
if (hash[0] == 0x00 || hash[0] == 0xFF) {
return false;
}
auto i = sender_low_idx(hash);
bool allow = false;
if (i < SENDER_LOW_MAP_SIZE && sender_low_map[i] > 0) {
sender_low_map[i]--;
allow = true;
} else {
denied_sender_low++;
}
MESH_DEBUG_PRINTLN("FAIR, sender=%02X prio=low allow=%u", (uint32_t)hash[0], (uint32_t)allow);
return allow;
}
void FairnessLimiter::refillSenderLow() {
for (int i = 0; i < SENDER_LOW_MAP_SIZE; i++) {
if (sender_low_map[i] < sender_low_cap) {
sender_low_map[i]++;
}
}
}
bool FairnessLimiter::allowPacket(const mesh::Packet* pkt) {
// Don't limit versions we don't understand.
if (pkt->getPayloadVer() != PAYLOAD_VER_1) {
return true;
}
#if FAIRNESS_ALLOW_DIRECT
// Don't limit direct
if (!pkt->isRouteFlood()) {
return true;
}
#endif
uint8_t hash[1] = { 0x00 };
auto type = pkt->getPayloadType();
// Packets by group channel hash
if (type == PAYLOAD_TYPE_GRP_TXT || type == PAYLOAD_TYPE_GRP_DATA) {
if (pkt->payload_len < 1) return true; // malformed, not ours to judge
hash[0] = pkt->payload[0];
return takeGroup(hash);
}
// Packets with a plaintext 1-byte src hash at payload[1] (see Mesh.cpp,
// PAYLOAD_TYPE_PATH/REQ/RESPONSE/TXT_MSG parse: dest_hash, then src_hash)
if (type == PAYLOAD_TYPE_PATH || type == PAYLOAD_TYPE_REQ || type == PAYLOAD_TYPE_RESPONSE ||
type == PAYLOAD_TYPE_TXT_MSG || type == PAYLOAD_TYPE_ANON_REQ) {
if (pkt->payload_len < 2) return true; // malformed, not ours to judge
hash[0] = pkt->payload[1];
return takeSenderNormal(hash);
}
if (type == PAYLOAD_TYPE_ADVERT) {
if (pkt->payload_len < 1) return true; // malformed, not ours to judge
hash[0] = pkt->payload[0]; // first byte of sender pub key
return takeSenderLow(hash);
}
// Not classified (allowed through):
// PAYLOAD_TYPE_ACK, PAYLOAD_TYPE_TRACE, PAYLOAD_TYPE_MULTIPART,
// PAYLOAD_TYPE_CONTROL, PAYLOAD_TYPE_RAW_CUSTOM
return true;
}
+115
View File
@@ -0,0 +1,115 @@
#pragma once
// CUSTOM (TeTeHacko): port of Beanow's "fairness limiter" (upstream proposal
// meshcore-dev/MeshCore#1502, branch beanow/wp-repeat). Token-bucket rate
// limiting of FORWARDED packets, bucketed by the 1-byte identifiers that are
// already in the clear on the air -- so it needs no protocol change and no
// decryption. It is an approximation by design: buckets collide (masks below)
// and every key is sender-controlled, so this is containment of accidental or
// lazy floods, not security. DIRECT (routed) traffic is never limited.
//
// Deviations from Beanow's branch, on purpose:
// * no RTCClock dependency -- it was only feeding log timestamps; logging
// goes through MESH_DEBUG_PRINTLN like the rest of this tree, which also
// lets the class run in native unit tests without a clock mock.
// * allowPacket() bounds-checks payload_len before reading payload bytes.
// The whole CI suite runs under ASAN because of earlier OOB parses; a
// limiter keyed on payload[1] must not be the next one.
#include <Packet.h>
#include <stdint.h>
// For senders 0x00 and 0xFF are reserved (Identity.cpp rejects them as path
// hash prefixes). Group channel hashes are pure sha256, so no reserved values.
// Note: mask, cap and refill interval are highly connected parameters.
#define GROUP_MASK 0b00011111 // 5-bit address
#define SENDER_NORMAL_MASK 0b00111111 // 6-bit address
#define SENDER_LOW_MASK 0b01111111 // 7-bit address
// Refill intervals: ONE token per bucket per interval. Steady-state rate is
// 1/interval, cap bounds the burst. Overridable per env from platformio ini.
#ifndef FAIRNESS_GROUP_REFILL_MS
#define FAIRNESS_GROUP_REFILL_MS (3 * 60 * 1000)
#endif
#ifndef FAIRNESS_SENDER_NORMAL_REFILL_MS
#define FAIRNESS_SENDER_NORMAL_REFILL_MS (4 * 60 * 1000)
#endif
#ifndef FAIRNESS_SENDER_LOW_REFILL_MS
#define FAIRNESS_SENDER_LOW_REFILL_MS (120 * 60 * 1000)
#endif
// Capacity (max burst) per bucket.
#ifndef FAIRNESS_GROUP_CAP
#define FAIRNESS_GROUP_CAP 20
#endif
#ifndef FAIRNESS_SENDER_NORMAL_CAP
#define FAIRNESS_SENDER_NORMAL_CAP 30
#endif
#ifndef FAIRNESS_SENDER_LOW_CAP
#define FAIRNESS_SENDER_LOW_CAP 4
#endif
// Simply allow all direct messages?
#ifndef FAIRNESS_ALLOW_DIRECT
#define FAIRNESS_ALLOW_DIRECT 1
#endif
// Derived from the masks, WONT fit in uint8 when full 0xFF mask.
#define GROUP_MAP_SIZE (GROUP_MASK + 1)
#define SENDER_NORMAL_MAP_SIZE (SENDER_NORMAL_MASK + 1)
#define SENDER_LOW_MAP_SIZE (SENDER_LOW_MASK + 1)
/**
* A token bucket rate limiter, which attempts to limit by sender or group channel.
*
* It provides some mitigation against accidental spam, as well as DoS attacks.
* However it's merely an approximation, as there will be ID collisions and easy
* ways to game it.
*
* Until a V2 protocol provides new means of limiting, the goal is a "better than
* nothing" reduction in wasteful repeats, freeing airtime for useful repeats.
*/
class FairnessLimiter {
// Capacity of when a bucket is full.
uint8_t group_cap = FAIRNESS_GROUP_CAP, sender_normal_cap = FAIRNESS_SENDER_NORMAL_CAP,
sender_low_cap = FAIRNESS_SENDER_LOW_CAP;
// Deny stats
uint32_t denied_group = 0, denied_sender_normal = 0, denied_sender_low = 0;
// Token buckets
uint8_t sender_normal_map[SENDER_NORMAL_MAP_SIZE] = {};
uint8_t sender_low_map[SENDER_LOW_MAP_SIZE] = {};
uint8_t group_map[GROUP_MAP_SIZE] = {};
public:
FairnessLimiter() {}
uint8_t peekGroup(const uint8_t* hash);
void refillGroup();
uint8_t peekSenderNormal(const uint8_t* hash);
void refillSenderNormal();
uint8_t peekSenderLow(const uint8_t* hash);
void refillSenderLow();
/**
* \brief Classify the packet and take a token from the matching bucket.
* CONSUMES a token when one is available -- call it only for a packet that
* would otherwise be forwarded, and only once per packet.
* \returns true if the packet should be forwarded
*/
bool allowPacket(const mesh::Packet* pkt);
// Inspect stats
uint32_t deniedSenderNormal() const { return denied_sender_normal; }
uint32_t deniedSenderLow() const { return denied_sender_low; }
uint32_t deniedGroup() const { return denied_group; }
static int sender_normal_idx(const uint8_t* hash) { return hash[0] & SENDER_NORMAL_MASK; }
static int sender_low_idx(const uint8_t* hash) { return hash[0] & SENDER_LOW_MASK; }
static int group_idx(const uint8_t* hash) { return hash[0] & GROUP_MASK; }
protected:
bool takeSenderNormal(const uint8_t* hash);
bool takeSenderLow(const uint8_t* hash);
bool takeGroup(const uint8_t* hash);
};