Skip to content

Commit

Permalink
Rate-limit client connection attempts
Browse files Browse the repository at this point in the history
  • Loading branch information
sfan5 committed Jan 17, 2024
1 parent 050152e commit b2f0a37
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/network/connectionthreads.cpp
Expand Up @@ -44,6 +44,8 @@ namespace con
// TODO: Clean this up.
#define LOG(a) a

#define MAX_NEW_PEERS_PER_SEC 30

static inline session_t readPeerId(const u8 *packetdata)
{
return readU16(&packetdata[4]);
Expand Down Expand Up @@ -971,7 +973,19 @@ void ConnectionReceiveThread::receive(SharedBuffer<u8> &packetdata,

// Someone new is trying to talk to us. Add them.
if (peer_id == PEER_ID_INEXISTENT) {
peer_id = m_connection->createPeer(sender, MTP_MINETEST_RELIABLE_UDP, 0);
auto &l = m_new_peer_ratelimit;
l.tick();
if (++l.counter > MAX_NEW_PEERS_PER_SEC) {
if (!l.logged) {
warningstream << m_connection->getDesc()
<< "Receive(): More than " << MAX_NEW_PEERS_PER_SEC
<< " new clients within 1s. Throttling." << std::endl;
}
l.logged = true;
// We simply drop the packet, the client can try again.
} else {
peer_id = m_connection->createPeer(sender, MTP_MINETEST_RELIABLE_UDP, 0);
}
}
}

Expand Down
17 changes: 17 additions & 0 deletions src/network/connectionthreads.h
Expand Up @@ -162,8 +162,25 @@ class ConnectionReceiveThread : public Thread
bool reliable);
};

struct RateLimitHelper {
u64 time = 0;
int counter = 0;
bool logged = false;

void tick() {
u64 now = porting::getTimeS();
if (time != now) {
time = now;
counter = 0;
logged = false;
}
}
};

static const PacketTypeHandler packetTypeRouter[PACKET_TYPE_MAX];

Connection *m_connection = nullptr;

RateLimitHelper m_new_peer_ratelimit;
};
}

0 comments on commit b2f0a37

Please sign in to comment.