Merge branch 'api-ip-exempt' of https://github.com/rodehoed/PrivateBin into api-ip-exempt

This commit is contained in:
LinQhost Managed hosting
2021-05-05 08:43:32 +02:00
5 changed files with 130 additions and 6 deletions

View File

@@ -79,9 +79,10 @@ class Configuration
'markdown' => 'Markdown',
),
'traffic' => array(
'limit' => 10,
'header' => null,
'dir' => 'data',
'limit' => 10,
'header' => null,
'dir' => 'data',
'exemptedIp' => null,
),
'purge' => array(
'limit' => 300,

View File

@@ -1,4 +1,5 @@
<?php
/**
* PrivateBin
*
@@ -30,6 +31,15 @@ class TrafficLimiter extends AbstractPersistence
*/
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 string
*
* @access public
* @static
* @param string $exemptedIps
*/
public static function setExemptedIp($exemptedIp)
{
self::$_exemptedIp = $exemptedIp;
}
/**
* set configuration options of the traffic limiter
*
@@ -62,6 +84,8 @@ class TrafficLimiter extends AbstractPersistence
{
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])) {
@@ -100,6 +124,32 @@ class TrafficLimiter extends AbstractPersistence
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)) {
require self::getPath($file);