Make it possible to exempt ips from the rate-limiter

This commit is contained in:
LinQhost Managed hosting 2021-05-04 10:29:25 +02:00
parent d65bf02d78
commit 7d82c82fd9
5 changed files with 128 additions and 3 deletions

View file

@ -1,4 +1,5 @@
<?php
/**
* PrivateBin
*
@ -29,6 +30,15 @@ class TrafficLimiter extends AbstractPersistence
* @var int
*/
private static $_limit = 10;
/**
* listed ips are exempted from limits, defaults to null
*
* @access private
* @static
* @var array
*/
private static $_exemptedIp = null;
/**
* key to fetch IP address
@ -51,6 +61,18 @@ class TrafficLimiter extends AbstractPersistence
self::$_limit = $limit;
}
/**
* set a list of ip(ranges) as array
*
* @access public
* @static
* @param array $exemptedIps
*/
public static function setExemptedIp($exemptedIp)
{
self::$_exemptedIp = $exemptedIp;
}
/**
* set configuration options of the traffic limiter
*
@ -60,8 +82,11 @@ class TrafficLimiter extends AbstractPersistence
*/
public static function setConfiguration(Configuration $conf)
{
self::setLimit($conf->getKey('limit', 'traffic'));
self::setPath($conf->getKey('dir', 'traffic'));
self::setExemptedIp($conf->getKey('exemptedIp', 'traffic'));
if (($option = $conf->getKey('header', 'traffic')) !== null) {
$httpHeader = 'HTTP_' . $option;
if (array_key_exists($httpHeader, $_SERVER) && !empty($_SERVER[$httpHeader])) {
@ -99,6 +124,32 @@ class TrafficLimiter extends AbstractPersistence
if (self::$_limit < 1) {
return true;
}
// Check if $_ipKey is exempted from ratelimiting
if (!is_null(self::$_exemptedIp)) {
$exIp_array = explode(",", self::$_exemptedIp);
foreach ($exIp_array as $ipRange) {
// Match $_ipKey to $ipRange and if it matches it will return with a true
$address = \IPLib\Factory::addressFromString($_SERVER[self::$_ipKey]);
$range = \IPLib\Factory::rangeFromString(trim($ipRange));
// If $range is null something went wrong (possible invalid ip given in config)
if ($range == null) {
$contained = false;
} else {
// Ip-lib does throws and exception when something goes wrong, if so we want to catch it and set contained to false
try {
$contained = $address->matches($range);
} catch (Exception $e) {
// If something is wrong with matching the ip, we set $contained to false
$contained = false;
}
}
// Matches return true!
if ($contained == true) {
return true;
}
}
}
$file = 'traffic_limiter.php';
if (self::_exists($file)) {