TrafficLimiter.php 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. <?php declare(strict_types=1);
  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. */
  11. namespace PrivateBin\Persistence;
  12. use Exception;
  13. use IPLib\Factory;
  14. use IPLib\ParseStringFlag;
  15. use PrivateBin\Configuration;
  16. use PrivateBin\I18n;
  17. /**
  18. * TrafficLimiter
  19. *
  20. * Handles traffic limiting, so no user does more than one call per 10 seconds.
  21. */
  22. class TrafficLimiter extends AbstractPersistence
  23. {
  24. /**
  25. * listed IPs are the only ones allowed to create, defaults to null
  26. *
  27. * @access private
  28. * @static
  29. * @var string|null
  30. */
  31. private static $_creators = null;
  32. /**
  33. * listed IPs are exempted from limits, defaults to null
  34. *
  35. * @access private
  36. * @static
  37. * @var string|null
  38. */
  39. private static $_exempted = null;
  40. /**
  41. * key to fetch IP address
  42. *
  43. * @access private
  44. * @static
  45. * @var string
  46. */
  47. private static $_ipKey = 'REMOTE_ADDR';
  48. /**
  49. * time limit in seconds, defaults to 10s
  50. *
  51. * @access private
  52. * @static
  53. * @var int
  54. */
  55. private static $_limit = 10;
  56. /**
  57. * set configuration options of the traffic limiter
  58. *
  59. * @access public
  60. * @static
  61. * @param Configuration $conf
  62. */
  63. public static function setConfiguration(Configuration $conf)
  64. {
  65. self::setCreators($conf->getKey('creators', 'traffic'));
  66. self::setExempted($conf->getKey('exempted', 'traffic'));
  67. self::setLimit($conf->getKey('limit', 'traffic'));
  68. if (($option = $conf->getKey('header', 'traffic')) !== '') {
  69. $httpHeader = 'HTTP_' . $option;
  70. if (array_key_exists($httpHeader, $_SERVER) && !empty($_SERVER[$httpHeader])) {
  71. self::$_ipKey = $httpHeader;
  72. }
  73. }
  74. }
  75. /**
  76. * set a list of creator IP(-ranges) as string
  77. *
  78. * @access public
  79. * @static
  80. * @param string $creators
  81. */
  82. public static function setCreators($creators)
  83. {
  84. self::$_creators = $creators;
  85. }
  86. /**
  87. * set a list of exempted IP(-ranges) as string
  88. *
  89. * @access public
  90. * @static
  91. * @param string $exempted
  92. */
  93. public static function setExempted($exempted)
  94. {
  95. self::$_exempted = $exempted;
  96. }
  97. /**
  98. * set the time limit in seconds
  99. *
  100. * @access public
  101. * @static
  102. * @param int $limit
  103. */
  104. public static function setLimit($limit)
  105. {
  106. self::$_limit = $limit;
  107. }
  108. /**
  109. * get a HMAC of the current visitors IP address
  110. *
  111. * @access public
  112. * @static
  113. * @param string $algo
  114. * @return string
  115. */
  116. public static function getHash($algo = 'sha512')
  117. {
  118. return hash_hmac($algo, $_SERVER[self::$_ipKey], ServerSalt::get());
  119. }
  120. /**
  121. * validate $_ipKey against configured ipranges. If matched we will ignore the ip
  122. *
  123. * @access private
  124. * @static
  125. * @param string $ipRange
  126. * @return bool
  127. */
  128. private static function matchIp($ipRange = null)
  129. {
  130. if (is_string($ipRange)) {
  131. $ipRange = trim($ipRange);
  132. }
  133. $address = Factory::parseAddressString($_SERVER[self::$_ipKey]);
  134. $range = Factory::parseRangeString(
  135. $ipRange,
  136. ParseStringFlag::IPV4_MAYBE_NON_DECIMAL | ParseStringFlag::IPV4SUBNET_MAYBE_COMPACT | ParseStringFlag::IPV4ADDRESS_MAYBE_NON_QUAD_DOTTED
  137. );
  138. // address could not be parsed, we might not be in IP space and try a string comparison instead
  139. if (is_null($address)) {
  140. return $_SERVER[self::$_ipKey] === $ipRange;
  141. }
  142. // range could not be parsed, possibly an invalid ip range given in config
  143. if (is_null($range)) {
  144. return false;
  145. }
  146. return $address->matches($range);
  147. }
  148. /**
  149. * make sure the IP address is allowed to perfom a request
  150. *
  151. * @access public
  152. * @static
  153. * @throws Exception
  154. * @return true
  155. */
  156. public static function canPass()
  157. {
  158. // if creators are defined, the traffic limiter will only allow creation
  159. // for these, with no limits, and skip any other rules
  160. if (!empty(self::$_creators)) {
  161. $creatorIps = explode(',', self::$_creators);
  162. foreach ($creatorIps as $ipRange) {
  163. if (self::matchIp($ipRange) === true) {
  164. return true;
  165. }
  166. }
  167. throw new Exception(I18n::_('Your IP is not authorized to create documents.'));
  168. }
  169. // disable limits if set to less then 1
  170. if (self::$_limit < 1) {
  171. return true;
  172. }
  173. // check if $_ipKey is exempted from ratelimiting
  174. if (!empty(self::$_exempted)) {
  175. $exIp_array = explode(',', self::$_exempted);
  176. foreach ($exIp_array as $ipRange) {
  177. if (self::matchIp($ipRange) === true) {
  178. return true;
  179. }
  180. }
  181. }
  182. // used as array key, which are limited in length, hence using algo with shorter range
  183. $hash = self::getHash('sha256');
  184. $now = time();
  185. $tl = (int) self::$_store->getValue('traffic_limiter', $hash);
  186. self::$_store->purgeValues('traffic_limiter', $now - self::$_limit);
  187. if ($tl > 0 && ($tl + self::$_limit >= $now)) {
  188. $result = false;
  189. } else {
  190. $tl = time();
  191. $result = true;
  192. }
  193. if (!self::$_store->setValue((string) $tl, 'traffic_limiter', $hash)) {
  194. error_log('failed to store the traffic limiter, it probably contains outdated information');
  195. }
  196. if ($result) {
  197. return true;
  198. }
  199. throw new Exception(I18n::_(
  200. 'Please wait %d seconds between each post.',
  201. self::$_limit
  202. ));
  203. }
  204. }