TrafficLimiter.php 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. <?php
  2. /**
  3. * PrivateBin
  4. *
  5. * a zero-knowledge paste bin
  6. *
  7. * @link https://github.com/PrivateBin/PrivateBin
  8. * @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
  9. * @license https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
  10. * @version 1.3.5
  11. */
  12. namespace PrivateBin\Persistence;
  13. use Exception;
  14. use IPLib\Factory;
  15. use PrivateBin\Configuration;
  16. /**
  17. * TrafficLimiter
  18. *
  19. * Handles traffic limiting, so no user does more than one call per 10 seconds.
  20. */
  21. class TrafficLimiter extends AbstractPersistence
  22. {
  23. /**
  24. * time limit in seconds, defaults to 10s
  25. *
  26. * @access private
  27. * @static
  28. * @var int
  29. */
  30. private static $_limit = 10;
  31. /**
  32. * listed ips are exempted from limits, defaults to null
  33. *
  34. * @access private
  35. * @static
  36. * @var string|null
  37. */
  38. private static $_exemptedIp = null;
  39. /**
  40. * key to fetch IP address
  41. *
  42. * @access private
  43. * @static
  44. * @var string
  45. */
  46. private static $_ipKey = 'REMOTE_ADDR';
  47. /**
  48. * set the time limit in seconds
  49. *
  50. * @access public
  51. * @static
  52. * @param int $limit
  53. */
  54. public static function setLimit($limit)
  55. {
  56. self::$_limit = $limit;
  57. }
  58. /**
  59. * set a list of ip(ranges) as string
  60. *
  61. * @access public
  62. * @static
  63. * @param string $exemptedIps
  64. */
  65. public static function setExemptedIp($exemptedIp)
  66. {
  67. self::$_exemptedIp = $exemptedIp;
  68. }
  69. /**
  70. * set configuration options of the traffic limiter
  71. *
  72. * @access public
  73. * @static
  74. * @param Configuration $conf
  75. */
  76. public static function setConfiguration(Configuration $conf)
  77. {
  78. self::setLimit($conf->getKey('limit', 'traffic'));
  79. self::setPath($conf->getKey('dir', 'traffic'));
  80. self::setExemptedIp($conf->getKey('exemptedIp', 'traffic'));
  81. if (($option = $conf->getKey('header', 'traffic')) !== null) {
  82. $httpHeader = 'HTTP_' . $option;
  83. if (array_key_exists($httpHeader, $_SERVER) && !empty($_SERVER[$httpHeader])) {
  84. self::$_ipKey = $httpHeader;
  85. }
  86. }
  87. }
  88. /**
  89. * get a HMAC of the current visitors IP address
  90. *
  91. * @access public
  92. * @static
  93. * @param string $algo
  94. * @return string
  95. */
  96. public static function getHash($algo = 'sha512')
  97. {
  98. return hash_hmac($algo, $_SERVER[self::$_ipKey], ServerSalt::get());
  99. }
  100. /**
  101. * Validate $_ipKey against configured ipranges. If matched we will ignore the ip
  102. *
  103. * @access private
  104. * @static
  105. * @param string $ipRange
  106. * @return bool
  107. */
  108. private static function matchIp($ipRange = null)
  109. {
  110. if (is_string($ipRange)) {
  111. $ipRange = trim($ipRange);
  112. }
  113. $address = Factory::addressFromString($_SERVER[self::$_ipKey]);
  114. $range = Factory::rangeFromString($ipRange);
  115. // address could not be parsed, we might not be in IP space and try a string comparison instead
  116. if ($address == null) {
  117. return $_SERVER[self::$_ipKey] === $ipRange;
  118. }
  119. // range could not be parsed, possibly an invalid ip range given in config
  120. if ($range == null) {
  121. return false;
  122. }
  123. // Ip-lib throws an exception when something goes wrong, if so we want to catch it and set contained to false
  124. try {
  125. return $address->matches($range);
  126. } catch (Exception $e) {
  127. // If something is wrong with matching the ip, we assume it doesn't match
  128. return false;
  129. }
  130. }
  131. /**
  132. * traffic limiter
  133. *
  134. * Make sure the IP address makes at most 1 request every 10 seconds.
  135. *
  136. * @access public
  137. * @static
  138. * @throws Exception
  139. * @return bool
  140. */
  141. public static function canPass()
  142. {
  143. // disable limits if set to less then 1
  144. if (self::$_limit < 1) {
  145. return true;
  146. }
  147. // Check if $_ipKey is exempted from ratelimiting
  148. if (!is_null(self::$_exemptedIp)) {
  149. $exIp_array = explode(',', self::$_exemptedIp);
  150. foreach ($exIp_array as $ipRange) {
  151. if (self::matchIp($ipRange) === true) {
  152. return true;
  153. }
  154. }
  155. }
  156. $file = 'traffic_limiter.php';
  157. if (self::_exists($file)) {
  158. require self::getPath($file);
  159. $tl = $GLOBALS['traffic_limiter'];
  160. } else {
  161. $tl = array();
  162. }
  163. // purge file of expired hashes to keep it small
  164. $now = time();
  165. foreach ($tl as $key => $time) {
  166. if ($time + self::$_limit < $now) {
  167. unset($tl[$key]);
  168. }
  169. }
  170. // this hash is used as an array key, hence a shorter algo is used
  171. $hash = self::getHash('sha256');
  172. if (array_key_exists($hash, $tl) && ($tl[$hash] + self::$_limit >= $now)) {
  173. $result = false;
  174. } else {
  175. $tl[$hash] = time();
  176. $result = true;
  177. }
  178. self::_store(
  179. $file,
  180. '<?php' . PHP_EOL .
  181. '$GLOBALS[\'traffic_limiter\'] = ' . var_export($tl, true) . ';'
  182. );
  183. return $result;
  184. }
  185. }