Compare commits

..

No commits in common. "bc1089be217133ad5699f4f007f0363603256477" and "645e98cd6a17259dfb9f8429a07352b7dc537b6f" have entirely different histories.

1 changed files with 38 additions and 61 deletions

View File

@ -4,45 +4,30 @@ class RateLimiter {
private $db; private $db;
private $maxAttempts = 5; // Maximum login attempts private $maxAttempts = 5; // Maximum login attempts
private $decayMinutes = 15; // Time window in minutes private $decayMinutes = 15; // Time window in minutes
private $ratelimitTable = 'login_attempts'; private $tableName = 'login_attempts';
private $whitelistTable = 'ip_whitelist';
private $whitelistedIps = []; // Whitelisted IPs private $whitelistedIps = []; // Whitelisted IPs
private $whitelistedNetworks = []; // Whitelisted CIDR ranges private $whitelistedNetworks = []; // Whitelisted CIDR ranges
public function __construct($database) { public function __construct($database) {
$this->db = $database->getConnection(); $this->db = $database->getConnection();
$this->createTablesIfNotExists(); $this->createTableIfNotExists();
$this->loadWhitelist(); $this->loadWhitelist();
} }
// Database preparation private function createTableIfNotExists() {
private function createTablesIfNotExists() { $sql = "CREATE TABLE IF NOT EXISTS {$this->tableName} (
// Login attempts table
$sql = "CREATE TABLE IF NOT EXISTS {$this->ratelimitTable} (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
ip_address VARCHAR(45) NOT NULL, ip_address VARCHAR(45) NOT NULL,
username VARCHAR(255) NOT NULL, username VARCHAR(255) NOT NULL,
attempted_at DATETIME DEFAULT CURRENT_TIMESTAMP, attempted_at DATETIME DEFAULT CURRENT_TIMESTAMP,
INDEX idx_ip_username (ip_address, username) INDEX idx_ip_username (ip_address, username)
)"; )";
$this->db->exec($sql);
// IP whitelist table
$sql = "CREATE TABLE IF NOT EXISTS {$this->whitelistTable} (
id int(11) PRIMARY KEY AUTO_INCREMENT,
ip_address VARCHAR(45) NOT NULL,
is_network BOOLEAN DEFAULT FALSE,
description VARCHAR(255),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
created_by VARCHAR(255),
UNIQUE KEY unique_ip (ip_address)
)";
$this->db->exec($sql); $this->db->exec($sql);
} }
// List of IPs to bypass rate limiting
private function loadWhitelist() { private function loadWhitelist() {
// FIXME Load from database or config // Load from database or config
$this->whitelistedIps = [ $this->whitelistedIps = [
'127.0.0.1', // localhost '127.0.0.1', // localhost
'::1' // localhost IPv6 '::1' // localhost IPv6
@ -55,25 +40,20 @@ class RateLimiter {
]; ];
} }
// Check if IP is whitelisted
private function isIpWhitelisted($ip) { private function isIpWhitelisted($ip) {
// Check exact IP match and CIDR ranges // Check exact IP match
$stmt = $this->db->prepare("SELECT ip_address, is_network FROM {$this->whitelistTable}"); if (in_array($ip, $this->whitelistedIps)) {
$stmt->execute(); return true;
}
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { // Check CIDR ranges
if ($row['is_network']) { foreach ($this->whitelistedNetworks as $network) {
if ($this->ipInRange($ip, $row['ip_address'])) { if ($this->ipInRange($ip, $network)) {
return true; return true;
} }
} else { }
if ($ip === $row['ip_address']) {
return true;
}
}
}
return false; return false;
} }
private function ipInRange($ip, $cidr) { private function ipInRange($ip, $cidr) {
@ -87,31 +67,28 @@ class RateLimiter {
return ($ip & $mask) == $subnet; return ($ip & $mask) == $subnet;
} }
// Add to whitelist public function addToWhitelist($ip, $isNetwork = false) {
public function addToWhitelist($ip, $isNetwork = false, $description = '', $createdBy = 'system') { if ($isNetwork) {
$stmt = $this->db->prepare("INSERT INTO {$this->whitelistTable} if (!in_array($ip, $this->whitelistedNetworks)) {
(ip_address, is_network, description, created_by) $this->whitelistedNetworks[] = $ip;
VALUES (?, ?, ?, ?) }
ON DUPLICATE KEY UPDATE } else {
is_network = VALUES(is_network), if (!in_array($ip, $this->whitelistedIps)) {
description = VALUES(description), $this->whitelistedIps[] = $ip;
created_by = VALUES(created_by)"); }
}
return $stmt->execute([$ip, $isNetwork, $description, $createdBy]);
} }
// Remove from whitelist
public function removeFromWhitelist($ip) { public function removeFromWhitelist($ip) {
$stmt = $this->db->prepare("DELETE FROM {$this->whitelistTable} WHERE ip_address = ?"); $indexIp = array_search($ip, $this->whitelistedIps);
if ($indexIp !== false) {
unset($this->whitelistedIps[$indexIp]);
}
return $stmt->execute([$ip]); $indexNetwork = array_search($ip, $this->whitelistedNetworks);
} if ($indexNetwork !== false) {
unset($this->whitelistedNetworks[$indexNetwork]);
public function getWhitelistedIps() { }
$stmt = $this->db->prepare("SELECT * FROM {$this->whitelistTable} ORDER BY created_at DESC");
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
} }
public function attempt($username, $ipAddress) { public function attempt($username, $ipAddress) {
@ -124,7 +101,7 @@ class RateLimiter {
$this->clearOldAttempts(); $this->clearOldAttempts();
// Record this attempt // Record this attempt
$sql = "INSERT INTO {$this->ratelimitTable} (ip_address, username) VALUES (:ip, :username)"; $sql = "INSERT INTO {$this->tableName} (ip_address, username) VALUES (:ip, :username)";
$stmt = $this->db->prepare($sql); $stmt = $this->db->prepare($sql);
$stmt->execute([ $stmt->execute([
':ip' => $ipAddress, ':ip' => $ipAddress,
@ -137,7 +114,7 @@ class RateLimiter {
public function tooManyAttempts($username, $ipAddress) { public function tooManyAttempts($username, $ipAddress) {
$sql = "SELECT COUNT(*) as attempts $sql = "SELECT COUNT(*) as attempts
FROM {$this->ratelimitTable} FROM {$this->tableName}
WHERE ip_address = :ip WHERE ip_address = :ip
AND username = :username AND username = :username
AND attempted_at > datetime('now', '-' || :minutes || ' minutes')"; AND attempted_at > datetime('now', '-' || :minutes || ' minutes')";
@ -154,7 +131,7 @@ class RateLimiter {
} }
public function clearOldAttempts() { public function clearOldAttempts() {
$sql = "DELETE FROM {$this->ratelimitTable} $sql = "DELETE FROM {$this->tableName}
WHERE attempted_at < datetime('now', '-' || :minutes || ' minutes')"; WHERE attempted_at < datetime('now', '-' || :minutes || ' minutes')";
$stmt = $this->db->prepare($sql); $stmt = $this->db->prepare($sql);
@ -165,7 +142,7 @@ class RateLimiter {
public function getRemainingAttempts($username, $ipAddress) { public function getRemainingAttempts($username, $ipAddress) {
$sql = "SELECT COUNT(*) as attempts $sql = "SELECT COUNT(*) as attempts
FROM {$this->ratelimitTable} FROM {$this->tableName}
WHERE ip_address = :ip WHERE ip_address = :ip
AND username = :username AND username = :username
AND attempted_at > datetime('now', '-' || :minutes || ' minutes')"; AND attempted_at > datetime('now', '-' || :minutes || ' minutes')";