RegisterThrottlePlugin.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. <?php
  2. /**
  3. * StatusNet - the distributed open-source microblogging tool
  4. * Copyright (C) 2010, StatusNet, Inc.
  5. *
  6. * Throttle registration by IP address
  7. *
  8. * PHP version 5
  9. *
  10. * This program is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU Affero General Public License as published by
  12. * the Free Software Foundation, either version 3 of the License, or
  13. * (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU Affero General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Affero General Public License
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. *
  23. * @category Spam
  24. * @package StatusNet
  25. * @author Evan Prodromou <evan@status.net>
  26. * @copyright 2010 StatusNet, Inc.
  27. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
  28. * @link http://status.net/
  29. */
  30. if (!defined('GNUSOCIAL')) { exit(1); }
  31. /**
  32. * Throttle registration by IP address
  33. *
  34. * We a) record IP address of registrants and b) throttle registrations.
  35. *
  36. * @category Spam
  37. * @package StatusNet
  38. * @author Evan Prodromou <evan@status.net>
  39. * @copyright 2010 StatusNet, Inc.
  40. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
  41. * @link http://status.net/
  42. */
  43. class RegisterThrottlePlugin extends Plugin
  44. {
  45. const PLUGIN_VERSION = '2.0.0';
  46. /**
  47. * Array of time spans in seconds to limits.
  48. *
  49. * Default is 3 registrations per hour, 5 per day, 10 per week.
  50. */
  51. public $regLimits = array(604800 => 10, // per week
  52. 86400 => 5, // per day
  53. 3600 => 3); // per hour
  54. /**
  55. * Disallow registration if a silenced user has registered from
  56. * this IP address.
  57. */
  58. public $silenced = true;
  59. /**
  60. * Auto-silence all other users from the same registration_ip
  61. * as the one being silenced. Caution: Many users may come from
  62. * the same IP (even entire countries) without having any sort
  63. * of relevant connection for moderation.
  64. */
  65. public $auto_silence_by_ip = false;
  66. /**
  67. * Whether we're enabled; prevents recursion.
  68. */
  69. static private $enabled = true;
  70. /**
  71. * Database schema setup
  72. *
  73. * We store user registrations in a table registration_ip.
  74. *
  75. * @return boolean hook value; true means continue processing, false means stop.
  76. */
  77. public function onCheckSchema()
  78. {
  79. $schema = Schema::get();
  80. // For storing user-submitted flags on profiles
  81. $schema->ensureTable('registration_ip', Registration_ip::schemaDef());
  82. return true;
  83. }
  84. public function onRouterInitialized(URLMapper $m)
  85. {
  86. $m->connect('main/ipregistrations/:ipaddress',
  87. ['action' => 'ipregistrations'],
  88. ['ipaddress' => '[0-9a-f\.\:]+']);
  89. }
  90. /**
  91. * Called when someone tries to register.
  92. *
  93. * We check the IP here to determine if it goes over any of our
  94. * configured limits.
  95. *
  96. * @param Action $action Action that is being executed
  97. *
  98. * @return boolean hook value
  99. */
  100. public function onStartRegistrationTry($action)
  101. {
  102. $ipaddress = $this->_getIpAddress();
  103. if (empty($ipaddress)) {
  104. // TRANS: Server exception thrown when no IP address can be found for a registation attempt.
  105. throw new ServerException(_m('Cannot find IP address.'));
  106. }
  107. foreach ($this->regLimits as $seconds => $limit) {
  108. $this->debug("Checking $seconds ($limit)");
  109. $reg = $this->_getNthReg($ipaddress, $limit);
  110. if (!empty($reg)) {
  111. $this->debug("Got a {$limit}th registration.");
  112. $regtime = strtotime($reg->created);
  113. $now = time();
  114. $this->debug("Comparing {$regtime} to {$now}");
  115. if ($now - $regtime < $seconds) {
  116. // TRANS: Exception thrown when too many user have registered from one IP address within a given time frame.
  117. throw new Exception(_m('Too many registrations. Take a break and try again later.'));
  118. }
  119. }
  120. }
  121. // Check for silenced users
  122. if ($this->silenced) {
  123. $ids = Registration_ip::usersByIP($ipaddress);
  124. foreach ($ids as $id) {
  125. $profile = Profile::getKV('id', $id);
  126. if ($profile && $profile->isSilenced()) {
  127. // TRANS: Exception thrown when attempting to register from an IP address from which silenced users have registered.
  128. throw new Exception(_m('A banned user has registered from this address.'));
  129. }
  130. }
  131. }
  132. return true;
  133. }
  134. function onEndShowSections(Action $action)
  135. {
  136. if (!$action instanceof ShowstreamAction) {
  137. // early return for actions we're not interested in
  138. return true;
  139. }
  140. $target = $action->getTarget();
  141. if (!$target->isSilenced()) {
  142. // Only show the IP of users who are not silenced.
  143. return true;
  144. }
  145. $scoped = $action->getScoped();
  146. if (!$scoped->hasRight(Right::SILENCEUSER)) {
  147. // only show registration IP if we have the right to silence users
  148. return true;
  149. }
  150. $ri = Registration_ip::getKV('user_id', $target->getID());
  151. $ipaddress = null;
  152. if ($ri instanceof Registration_ip) {
  153. $ipaddress = $ri->ipaddress;
  154. unset($ri);
  155. }
  156. $action->elementStart('div', array('id' => 'entity_mod_log',
  157. 'class' => 'section'));
  158. $action->element('h2', null, _('Registration IP'));
  159. // TRANS: Label for the information about which IP a users registered from.
  160. $action->element('strong', null, _('Registered from:'));
  161. $el = 'span';
  162. $attrs = ['class'=>'ipaddress'];
  163. if (!is_null($ipaddress)) {
  164. $el = 'a';
  165. $attrs['href'] = common_local_url('ipregistrations', array('ipaddress'=>$ipaddress));
  166. }
  167. $action->element($el, $attrs,
  168. // TRANS: Unknown IP address.
  169. $ipaddress ?: _('unknown'));
  170. $action->elementEnd('div');
  171. }
  172. /**
  173. * Called after someone registers, by any means.
  174. *
  175. * We record the successful registration and IP address.
  176. *
  177. * @param Profile $profile new user's profile
  178. *
  179. * @return boolean hook value
  180. */
  181. public function onEndUserRegister(Profile $profile)
  182. {
  183. $ipaddress = $this->_getIpAddress();
  184. if (empty($ipaddress)) {
  185. // User registration can happen from command-line scripts etc.
  186. return true;
  187. }
  188. $reg = new Registration_ip();
  189. $reg->user_id = $profile->getID();
  190. $reg->ipaddress = mb_strtolower($ipaddress);
  191. $reg->created = common_sql_now();
  192. $result = $reg->insert();
  193. if ($result === false) {
  194. common_log_db_error($reg, 'INSERT', __FILE__);
  195. // @todo throw an exception?
  196. }
  197. return true;
  198. }
  199. /**
  200. * Check the version of the plugin.
  201. *
  202. * @param array &$versions Version array.
  203. *
  204. * @return boolean hook value
  205. */
  206. public function onPluginVersion(array &$versions)
  207. {
  208. $versions[] = array('name' => 'RegisterThrottle',
  209. 'version' => self::PLUGIN_VERSION,
  210. 'author' => 'Evan Prodromou',
  211. 'homepage' => 'https://git.gnu.io/gnu/gnu-social/tree/master/plugins/RegisterThrottle',
  212. 'description' =>
  213. // TRANS: Plugin description.
  214. _m('Throttles excessive registration from a single IP address.'));
  215. return true;
  216. }
  217. /**
  218. * Gets the current IP address.
  219. *
  220. * @return string IP address or null if not found.
  221. */
  222. private function _getIpAddress()
  223. {
  224. $keys = array('HTTP_X_FORWARDED_FOR',
  225. 'HTTP_X_CLIENT',
  226. 'CLIENT-IP',
  227. 'REMOTE_ADDR');
  228. foreach ($keys as $k) {
  229. if (!empty($_SERVER[$k])) {
  230. return $_SERVER[$k];
  231. }
  232. }
  233. return null;
  234. }
  235. /**
  236. * Gets the Nth registration with the given IP address.
  237. *
  238. * @param string $ipaddress Address to key on
  239. * @param integer $n Nth address
  240. *
  241. * @return Registration_ip nth registration or null if not found.
  242. */
  243. private function _getNthReg($ipaddress, $n)
  244. {
  245. $reg = new Registration_ip();
  246. $reg->ipaddress = $ipaddress;
  247. $reg->orderBy('created DESC');
  248. $reg->limit($n - 1, 1);
  249. if ($reg->find(true)) {
  250. return $reg;
  251. } else {
  252. return null;
  253. }
  254. }
  255. /**
  256. * When silencing a user, silence all other users registered from that IP
  257. * address.
  258. *
  259. * @param Profile $profile Person getting a new role
  260. * @param string $role Role being assigned like 'moderator' or 'silenced'
  261. *
  262. * @return boolean hook value
  263. */
  264. public function onEndGrantRole($profile, $role)
  265. {
  266. if (!self::$enabled) {
  267. return true;
  268. }
  269. if ($role !== Profile_role::SILENCED) {
  270. return true;
  271. }
  272. if (!$this->auto_silence_by_ip) {
  273. return true;
  274. }
  275. $ri = Registration_ip::getKV('user_id', $profile->getID());
  276. if (empty($ri)) {
  277. return true;
  278. }
  279. $ids = Registration_ip::usersByIP($ri->ipaddress);
  280. foreach ($ids as $id) {
  281. if ($id == $profile->getID()) {
  282. continue;
  283. }
  284. try {
  285. $other = Profile::getByID($id);
  286. } catch (NoResultException $e) {
  287. continue;
  288. }
  289. if ($other->isSilenced()) {
  290. continue;
  291. }
  292. // 'enabled' here is used to prevent recursion, since
  293. // we'll end up in this function again on ->silence()
  294. // though I actually think it doesn't matter since we
  295. // do this in onEndGrantRole and that means the above
  296. // $other->isSilenced() test should've 'continue'd...
  297. $old = self::$enabled;
  298. self::$enabled = false;
  299. $other->silence();
  300. self::$enabled = $old;
  301. }
  302. }
  303. }