66 lines
2.4 KiB
C
66 lines
2.4 KiB
C
#ifndef IP_BAN_H
|
|
#define IP_BAN_H
|
|
|
|
// IP Auth Failure Ban System
|
|
//
|
|
// Tracks auth failures per IP address and temporarily bans IPs that repeatedly
|
|
// fail NIP-42 authentication. Uses an in-memory fixed-size hash table — no
|
|
// database writes on the hot path. State is persisted to the ip_bans table
|
|
// every 5 minutes and loaded at startup.
|
|
//
|
|
// Config keys (all read from the config table at runtime):
|
|
// auth_fail_ban_enabled bool default: true (0 = disabled)
|
|
// auth_fail_ban_threshold int default: 3 (failures before ban)
|
|
// auth_fail_window_sec int default: 60 (window to count failures)
|
|
// auth_fail_ban_duration_sec int default: 300 (initial ban duration, doubles each time)
|
|
|
|
#include <time.h>
|
|
|
|
// Maximum number of IPs tracked simultaneously (fixed-size, no malloc)
|
|
#define IP_BAN_TABLE_SIZE 4096
|
|
|
|
// Initialize the IP ban table (call once at startup, before loading from DB)
|
|
void ip_ban_init(void);
|
|
|
|
// Load ban state from the ip_bans database table.
|
|
// Call after ip_ban_init() and after the database is open.
|
|
void ip_ban_load_from_db(void);
|
|
|
|
// Save current ban state to the ip_bans database table.
|
|
// Called every 5 minutes from the maintenance timer.
|
|
void ip_ban_save_to_db(void);
|
|
|
|
// Check if an IP is currently banned.
|
|
// Returns 1 if banned (connection should be rejected), 0 if allowed.
|
|
int ip_ban_is_banned(const char* ip);
|
|
|
|
// Record an auth failure for an IP.
|
|
// Called when a connection is closed due to auth timeout.
|
|
// May trigger a ban if the threshold is exceeded.
|
|
void ip_ban_record_failure(const char* ip);
|
|
|
|
// Record an idle/early-disconnect failure for an IP.
|
|
// Called when a connection closes without ever sending REQ or EVENT.
|
|
// May trigger a ban if the threshold is exceeded.
|
|
void ip_ban_record_idle_failure(const char* ip);
|
|
|
|
// Record a successful auth for an IP.
|
|
// Sets has_authed_successfully=1 and clears failure count.
|
|
void ip_ban_record_success(const char* ip);
|
|
|
|
// Record a new connection from an IP (increment total_connections).
|
|
void ip_ban_record_connection(const char* ip);
|
|
|
|
// Periodic cleanup: expire old entries (call from the connection age checker).
|
|
void ip_ban_cleanup(void);
|
|
|
|
// Emit a periodic WARN-level log summary of banned IPs (every 5 minutes).
|
|
// Also saves state to DB.
|
|
void ip_ban_log_stats(void);
|
|
|
|
// Get stats for logging/monitoring
|
|
int ip_ban_get_banned_count(void);
|
|
int ip_ban_get_tracked_count(void);
|
|
|
|
#endif // IP_BAN_H
|