RegisterThrottlePlugin.php 11 KB

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