Security.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  1. <?php
  2. /**
  3. * Simple Machines Forum (SMF)
  4. *
  5. * @package SMF
  6. * @author Simple Machines http://www.simplemachines.org
  7. * @copyright 2011 Simple Machines
  8. * @license http://www.simplemachines.org/about/smf/license.php BSD
  9. *
  10. * @version 2.0
  11. */
  12. if (!defined('SMF'))
  13. die('Hacking attempt...');
  14. /* This file has the very important job of insuring forum security. This
  15. task includes banning and permissions, namely. It does this by providing
  16. the following functions:
  17. void validateSession()
  18. - makes sure the user is who they claim to be by requiring a
  19. password to be typed in every hour.
  20. - is turned on and off by the securityDisable setting.
  21. - uses the adminLogin() function of Subs-Auth.php if they need to
  22. login, which saves all request (post and get) data.
  23. void is_not_guest(string message = '')
  24. - checks if the user is currently a guest, and if so asks them to
  25. login with a message telling them why.
  26. - message is what to tell them when asking them to login.
  27. void is_not_banned(bool force_check = false)
  28. - checks if the user is banned, and if so dies with an error.
  29. - caches this information for optimization purposes.
  30. - forces a recheck if force_check is true.
  31. void banPermissions()
  32. - applies any states of banning by removing permissions the user
  33. cannot have.
  34. void log_ban(array ban_ids = array(), string email = null)
  35. - log the current user in the ban logs.
  36. - increment the hit counters for the specified ban ID's (if any.)
  37. void isBannedEmail(string email, string restriction, string error)
  38. - check if a given email is banned.
  39. - performs an immediate ban if the turns turns out positive.
  40. string checkSession(string type = 'post', string from_action = none,
  41. is_fatal = true)
  42. - checks the current session, verifying that the person is who he or
  43. she should be.
  44. - also checks the referrer to make sure they didn't get sent here.
  45. - depends on the disableCheckUA setting, which is usually missing.
  46. - will check GET, POST, or REQUEST depending on the passed type.
  47. - also optionally checks the referring action if passed. (note that
  48. the referring action must be by GET.)
  49. - returns the error message if is_fatal is false.
  50. bool checkSubmitOnce(string action, bool is_fatal = true)
  51. - registers a sequence number for a form.
  52. - checks whether a submitted sequence number is registered in the
  53. current session.
  54. - depending on the value of is_fatal shows an error or returns true or
  55. false.
  56. - frees a sequence number from the stack after it's been checked.
  57. - frees a sequence number without checking if action == 'free'.
  58. bool allowedTo(string permission, array boards = current)
  59. - checks whether the user is allowed to do permission. (ie. post_new.)
  60. - if boards is specified, checks those boards instead of the current
  61. one.
  62. - always returns true if the user is an administrator.
  63. - returns true if he or she can do it, false otherwise.
  64. void isAllowedTo(string permission, array boards = current)
  65. - uses allowedTo() to check if the user is allowed to do permission.
  66. - checks the passed boards or current board for the permission.
  67. - if they are not, it loads the Errors language file and shows an
  68. error using $txt['cannot_' . $permission].
  69. - if they are a guest and cannot do it, this calls is_not_guest().
  70. array boardsAllowedTo(string permission, bool check_access = false)
  71. - returns a list of boards on which the user is allowed to do the
  72. specified permission.
  73. - returns an array with only a 0 in it if the user has permission
  74. to do this on every board.
  75. - returns an empty array if he or she cannot do this on any board.
  76. - if check_access is true will also make sure the group has proper access to that board.
  77. string showEmailAddress(string userProfile_hideEmail, int userProfile_id)
  78. - returns whether an email address should be shown and how.
  79. - possible outcomes are
  80. 'yes': show the full email address
  81. 'yes_permission_override': show the full email address, either you
  82. are a moderator or it's your own email address.
  83. 'no_through_forum': don't show the email address, but do allow
  84. things to be mailed using the built-in forum mailer.
  85. 'no': keep the email address hidden.
  86. */
  87. // Check if the user is who he/she says he is
  88. function validateSession()
  89. {
  90. global $modSettings, $sourcedir, $user_info, $sc, $user_settings;
  91. // We don't care if the option is off, because Guests should NEVER get past here.
  92. is_not_guest();
  93. // If we're using XML give an additional ten minutes grace as an admin can't log on in XML mode.
  94. $refreshTime = isset($_GET['xml']) ? 4200 : 3600;
  95. // Is the security option off? Or are they already logged in?
  96. if (!empty($modSettings['securityDisable']) || (!empty($_SESSION['admin_time']) && $_SESSION['admin_time'] + $refreshTime >= time()))
  97. return;
  98. require_once($sourcedir . '/Subs-Auth.php');
  99. // Hashed password, ahoy!
  100. if (isset($_POST['admin_hash_pass']) && strlen($_POST['admin_hash_pass']) == 40)
  101. {
  102. checkSession();
  103. $good_password = in_array(true, call_integration_hook('integrate_verify_password', array($user_info['username'], $_POST['admin_hash_pass'], true)), true);
  104. if ($good_password || $_POST['admin_hash_pass'] == sha1($user_info['passwd'] . $sc))
  105. {
  106. $_SESSION['admin_time'] = time();
  107. return;
  108. }
  109. }
  110. // Posting the password... check it.
  111. if (isset($_POST['admin_pass']))
  112. {
  113. checkSession();
  114. $good_password = in_array(true, call_integration_hook('integrate_verify_password', array($user_info['username'], $_POST['admin_pass'], false)), true);
  115. // Password correct?
  116. if ($good_password || sha1(strtolower($user_info['username']) . $_POST['admin_pass']) == $user_info['passwd'])
  117. {
  118. $_SESSION['admin_time'] = time();
  119. return;
  120. }
  121. }
  122. // OpenID?
  123. if (!empty($user_settings['openid_uri']))
  124. {
  125. require_once($sourcedir . '/Subs-OpenID.php');
  126. smf_openID_revalidate();
  127. $_SESSION['admin_time'] = time();
  128. return;
  129. }
  130. // Need to type in a password for that, man.
  131. adminLogin();
  132. }
  133. // Require a user who is logged in. (not a guest.)
  134. function is_not_guest($message = '')
  135. {
  136. global $user_info, $txt, $context, $scripturl;
  137. // Luckily, this person isn't a guest.
  138. if (!$user_info['is_guest'])
  139. return;
  140. // People always worry when they see people doing things they aren't actually doing...
  141. $_GET['action'] = '';
  142. $_GET['board'] = '';
  143. $_GET['topic'] = '';
  144. writeLog(true);
  145. // Just die.
  146. if (isset($_REQUEST['xml']))
  147. obExit(false);
  148. // Attempt to detect if they came from dlattach.
  149. if (!WIRELESS && SMF != 'SSI' && empty($context['theme_loaded']))
  150. loadTheme();
  151. // Never redirect to an attachment
  152. if (strpos($_SERVER['REQUEST_URL'], 'dlattach') === false)
  153. $_SESSION['login_url'] = $_SERVER['REQUEST_URL'];
  154. // Load the Login template and language file.
  155. loadLanguage('Login');
  156. // Are we in wireless mode?
  157. if (WIRELESS)
  158. {
  159. $context['login_error'] = $message ? $message : $txt['only_members_can_access'];
  160. $context['sub_template'] = WIRELESS_PROTOCOL . '_login';
  161. }
  162. // Apparently we're not in a position to handle this now. Let's go to a safer location for now.
  163. elseif (empty($context['template_layers']))
  164. {
  165. $_SESSION['login_url'] = $scripturl . '?' . $_SERVER['QUERY_STRING'];
  166. redirectexit('action=login');
  167. }
  168. else
  169. {
  170. loadTemplate('Login');
  171. $context['sub_template'] = 'kick_guest';
  172. $context['robot_no_index'] = true;
  173. }
  174. // Use the kick_guest sub template...
  175. $context['kick_message'] = $message;
  176. $context['page_title'] = $txt['login'];
  177. obExit();
  178. // We should never get to this point, but if we did we wouldn't know the user isn't a guest.
  179. trigger_error('Hacking attempt...', E_USER_ERROR);
  180. }
  181. // Do banning related stuff. (ie. disallow access....)
  182. function is_not_banned($forceCheck = false)
  183. {
  184. global $txt, $modSettings, $context, $user_info;
  185. global $sourcedir, $cookiename, $user_settings, $smcFunc;
  186. // You cannot be banned if you are an admin - doesn't help if you log out.
  187. if ($user_info['is_admin'])
  188. return;
  189. // Only check the ban every so often. (to reduce load.)
  190. if ($forceCheck || !isset($_SESSION['ban']) || empty($modSettings['banLastUpdated']) || ($_SESSION['ban']['last_checked'] < $modSettings['banLastUpdated']) || $_SESSION['ban']['id_member'] != $user_info['id'] || $_SESSION['ban']['ip'] != $user_info['ip'] || $_SESSION['ban']['ip2'] != $user_info['ip2'] || (isset($user_info['email'], $_SESSION['ban']['email']) && $_SESSION['ban']['email'] != $user_info['email']))
  191. {
  192. // Innocent until proven guilty. (but we know you are! :P)
  193. $_SESSION['ban'] = array(
  194. 'last_checked' => time(),
  195. 'id_member' => $user_info['id'],
  196. 'ip' => $user_info['ip'],
  197. 'ip2' => $user_info['ip2'],
  198. 'email' => $user_info['email'],
  199. );
  200. $ban_query = array();
  201. $ban_query_vars = array('current_time' => time());
  202. $flag_is_activated = false;
  203. // Check both IP addresses.
  204. foreach (array('ip', 'ip2') as $ip_number)
  205. {
  206. // Check if we have a valid IP address.
  207. if (preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $user_info[$ip_number], $ip_parts) == 1)
  208. {
  209. $ban_query[] = '((' . $ip_parts[1] . ' BETWEEN bi.ip_low1 AND bi.ip_high1)
  210. AND (' . $ip_parts[2] . ' BETWEEN bi.ip_low2 AND bi.ip_high2)
  211. AND (' . $ip_parts[3] . ' BETWEEN bi.ip_low3 AND bi.ip_high3)
  212. AND (' . $ip_parts[4] . ' BETWEEN bi.ip_low4 AND bi.ip_high4))';
  213. // IP was valid, maybe there's also a hostname...
  214. if (empty($modSettings['disableHostnameLookup']))
  215. {
  216. $hostname = host_from_ip($user_info[$ip_number]);
  217. if (strlen($hostname) > 0)
  218. {
  219. $ban_query[] = '({string:hostname} LIKE bi.hostname)';
  220. $ban_query_vars['hostname'] = $hostname;
  221. }
  222. }
  223. }
  224. // We use '255.255.255.255' for 'unknown' since it's not valid anyway.
  225. elseif ($user_info['ip'] == 'unknown')
  226. $ban_query[] = '(bi.ip_low1 = 255 AND bi.ip_high1 = 255
  227. AND bi.ip_low2 = 255 AND bi.ip_high2 = 255
  228. AND bi.ip_low3 = 255 AND bi.ip_high3 = 255
  229. AND bi.ip_low4 = 255 AND bi.ip_high4 = 255)';
  230. }
  231. // Is their email address banned?
  232. if (strlen($user_info['email']) != 0)
  233. {
  234. $ban_query[] = '({string:email} LIKE bi.email_address)';
  235. $ban_query_vars['email'] = $user_info['email'];
  236. }
  237. // How about this user?
  238. if (!$user_info['is_guest'] && !empty($user_info['id']))
  239. {
  240. $ban_query[] = 'bi.id_member = {int:id_member}';
  241. $ban_query_vars['id_member'] = $user_info['id'];
  242. }
  243. // Check the ban, if there's information.
  244. if (!empty($ban_query))
  245. {
  246. $restrictions = array(
  247. 'cannot_access',
  248. 'cannot_login',
  249. 'cannot_post',
  250. 'cannot_register',
  251. );
  252. $request = $smcFunc['db_query']('', '
  253. SELECT bi.id_ban, bi.email_address, bi.id_member, bg.cannot_access, bg.cannot_register,
  254. bg.cannot_post, bg.cannot_login, bg.reason, IFNULL(bg.expire_time, 0) AS expire_time
  255. FROM {db_prefix}ban_items AS bi
  256. INNER JOIN {db_prefix}ban_groups AS bg ON (bg.id_ban_group = bi.id_ban_group AND (bg.expire_time IS NULL OR bg.expire_time > {int:current_time}))
  257. WHERE
  258. (' . implode(' OR ', $ban_query) . ')',
  259. $ban_query_vars
  260. );
  261. // Store every type of ban that applies to you in your session.
  262. while ($row = $smcFunc['db_fetch_assoc']($request))
  263. {
  264. foreach ($restrictions as $restriction)
  265. if (!empty($row[$restriction]))
  266. {
  267. $_SESSION['ban'][$restriction]['reason'] = $row['reason'];
  268. $_SESSION['ban'][$restriction]['ids'][] = $row['id_ban'];
  269. if (!isset($_SESSION['ban']['expire_time']) || ($_SESSION['ban']['expire_time'] != 0 && ($row['expire_time'] == 0 || $row['expire_time'] > $_SESSION['ban']['expire_time'])))
  270. $_SESSION['ban']['expire_time'] = $row['expire_time'];
  271. if (!$user_info['is_guest'] && $restriction == 'cannot_access' && ($row['id_member'] == $user_info['id'] || $row['email_address'] == $user_info['email']))
  272. $flag_is_activated = true;
  273. }
  274. }
  275. $smcFunc['db_free_result']($request);
  276. }
  277. // Mark the cannot_access and cannot_post bans as being 'hit'.
  278. if (isset($_SESSION['ban']['cannot_access']) || isset($_SESSION['ban']['cannot_post']) || isset($_SESSION['ban']['cannot_login']))
  279. log_ban(array_merge(isset($_SESSION['ban']['cannot_access']) ? $_SESSION['ban']['cannot_access']['ids'] : array(), isset($_SESSION['ban']['cannot_post']) ? $_SESSION['ban']['cannot_post']['ids'] : array(), isset($_SESSION['ban']['cannot_login']) ? $_SESSION['ban']['cannot_login']['ids'] : array()));
  280. // If for whatever reason the is_activated flag seems wrong, do a little work to clear it up.
  281. if ($user_info['id'] && (($user_settings['is_activated'] >= 10 && !$flag_is_activated)
  282. || ($user_settings['is_activated'] < 10 && $flag_is_activated)))
  283. {
  284. require_once($sourcedir . '/ManageBans.php');
  285. updateBanMembers();
  286. }
  287. }
  288. // Hey, I know you! You're ehm...
  289. if (!isset($_SESSION['ban']['cannot_access']) && !empty($_COOKIE[$cookiename . '_']))
  290. {
  291. $bans = explode(',', $_COOKIE[$cookiename . '_']);
  292. foreach ($bans as $key => $value)
  293. $bans[$key] = (int) $value;
  294. $request = $smcFunc['db_query']('', '
  295. SELECT bi.id_ban, bg.reason
  296. FROM {db_prefix}ban_items AS bi
  297. INNER JOIN {db_prefix}ban_groups AS bg ON (bg.id_ban_group = bi.id_ban_group)
  298. WHERE bi.id_ban IN ({array_int:ban_list})
  299. AND (bg.expire_time IS NULL OR bg.expire_time > {int:current_time})
  300. AND bg.cannot_access = {int:cannot_access}
  301. LIMIT ' . count($bans),
  302. array(
  303. 'cannot_access' => 1,
  304. 'ban_list' => $bans,
  305. 'current_time' => time(),
  306. )
  307. );
  308. while ($row = $smcFunc['db_fetch_assoc']($request))
  309. {
  310. $_SESSION['ban']['cannot_access']['ids'][] = $row['id_ban'];
  311. $_SESSION['ban']['cannot_access']['reason'] = $row['reason'];
  312. }
  313. $smcFunc['db_free_result']($request);
  314. // My mistake. Next time better.
  315. if (!isset($_SESSION['ban']['cannot_access']))
  316. {
  317. require_once($sourcedir . '/Subs-Auth.php');
  318. $cookie_url = url_parts(!empty($modSettings['localCookies']), !empty($modSettings['globalCookies']));
  319. setcookie($cookiename . '_', '', time() - 3600, $cookie_url[1], $cookie_url[0], 0);
  320. }
  321. }
  322. // If you're fully banned, it's end of the story for you.
  323. if (isset($_SESSION['ban']['cannot_access']))
  324. {
  325. // We don't wanna see you!
  326. if (!$user_info['is_guest'])
  327. $smcFunc['db_query']('', '
  328. DELETE FROM {db_prefix}log_online
  329. WHERE id_member = {int:current_member}',
  330. array(
  331. 'current_member' => $user_info['id'],
  332. )
  333. );
  334. // 'Log' the user out. Can't have any funny business... (save the name!)
  335. $old_name = isset($user_info['name']) && $user_info['name'] != '' ? $user_info['name'] : $txt['guest_title'];
  336. $user_info['name'] = '';
  337. $user_info['username'] = '';
  338. $user_info['is_guest'] = true;
  339. $user_info['is_admin'] = false;
  340. $user_info['permissions'] = array();
  341. $user_info['id'] = 0;
  342. $context['user'] = array(
  343. 'id' => 0,
  344. 'username' => '',
  345. 'name' => $txt['guest_title'],
  346. 'is_guest' => true,
  347. 'is_logged' => false,
  348. 'is_admin' => false,
  349. 'is_mod' => false,
  350. 'can_mod' => false,
  351. 'language' => $user_info['language'],
  352. );
  353. // A goodbye present.
  354. require_once($sourcedir . '/Subs-Auth.php');
  355. $cookie_url = url_parts(!empty($modSettings['localCookies']), !empty($modSettings['globalCookies']));
  356. setcookie($cookiename . '_', implode(',', $_SESSION['ban']['cannot_access']['ids']), time() + 3153600, $cookie_url[1], $cookie_url[0], 0);
  357. // Don't scare anyone, now.
  358. $_GET['action'] = '';
  359. $_GET['board'] = '';
  360. $_GET['topic'] = '';
  361. writeLog(true);
  362. // You banned, sucka!
  363. fatal_error(sprintf($txt['your_ban'], $old_name) . (empty($_SESSION['ban']['cannot_access']['reason']) ? '' : '<br />' . $_SESSION['ban']['cannot_access']['reason']) . '<br />' . (!empty($_SESSION['ban']['expire_time']) ? sprintf($txt['your_ban_expires'], timeformat($_SESSION['ban']['expire_time'], false)) : $txt['your_ban_expires_never']), 'user');
  364. // If we get here, something's gone wrong.... but let's try anyway.
  365. trigger_error('Hacking attempt...', E_USER_ERROR);
  366. }
  367. // You're not allowed to log in but yet you are. Let's fix that.
  368. elseif (isset($_SESSION['ban']['cannot_login']) && !$user_info['is_guest'])
  369. {
  370. // We don't wanna see you!
  371. $smcFunc['db_query']('', '
  372. DELETE FROM {db_prefix}log_online
  373. WHERE id_member = {int:current_member}',
  374. array(
  375. 'current_member' => $user_info['id'],
  376. )
  377. );
  378. // 'Log' the user out. Can't have any funny business... (save the name!)
  379. $old_name = isset($user_info['name']) && $user_info['name'] != '' ? $user_info['name'] : $txt['guest_title'];
  380. $user_info['name'] = '';
  381. $user_info['username'] = '';
  382. $user_info['is_guest'] = true;
  383. $user_info['is_admin'] = false;
  384. $user_info['permissions'] = array();
  385. $user_info['id'] = 0;
  386. $context['user'] = array(
  387. 'id' => 0,
  388. 'username' => '',
  389. 'name' => $txt['guest_title'],
  390. 'is_guest' => true,
  391. 'is_logged' => false,
  392. 'is_admin' => false,
  393. 'is_mod' => false,
  394. 'can_mod' => false,
  395. 'language' => $user_info['language'],
  396. );
  397. // SMF's Wipe 'n Clean(r) erases all traces.
  398. $_GET['action'] = '';
  399. $_GET['board'] = '';
  400. $_GET['topic'] = '';
  401. writeLog(true);
  402. require_once($sourcedir . '/LogInOut.php');
  403. Logout(true, false);
  404. fatal_error(sprintf($txt['your_ban'], $old_name) . (empty($_SESSION['ban']['cannot_login']['reason']) ? '' : '<br />' . $_SESSION['ban']['cannot_login']['reason']) . '<br />' . (!empty($_SESSION['ban']['expire_time']) ? sprintf($txt['your_ban_expires'], timeformat($_SESSION['ban']['expire_time'], false)) : $txt['your_ban_expires_never']) . '<br />' . $txt['ban_continue_browse'], 'user');
  405. }
  406. // Fix up the banning permissions.
  407. if (isset($user_info['permissions']))
  408. banPermissions();
  409. }
  410. // Fix permissions according to ban status.
  411. function banPermissions()
  412. {
  413. global $user_info, $sourcedir, $modSettings, $context;
  414. // Somehow they got here, at least take away all permissions...
  415. if (isset($_SESSION['ban']['cannot_access']))
  416. $user_info['permissions'] = array();
  417. // Okay, well, you can watch, but don't touch a thing.
  418. elseif (isset($_SESSION['ban']['cannot_post']) || (!empty($modSettings['warning_mute']) && $modSettings['warning_mute'] <= $user_info['warning']))
  419. {
  420. $denied_permissions = array(
  421. 'pm_send',
  422. 'calendar_post', 'calendar_edit_own', 'calendar_edit_any',
  423. 'poll_post',
  424. 'poll_add_own', 'poll_add_any',
  425. 'poll_edit_own', 'poll_edit_any',
  426. 'poll_lock_own', 'poll_lock_any',
  427. 'poll_remove_own', 'poll_remove_any',
  428. 'manage_attachments', 'manage_smileys', 'manage_boards', 'admin_forum', 'manage_permissions',
  429. 'moderate_forum', 'manage_membergroups', 'manage_bans', 'send_mail', 'edit_news',
  430. 'profile_identity_any', 'profile_extra_any', 'profile_title_any',
  431. 'post_new', 'post_reply_own', 'post_reply_any',
  432. 'delete_own', 'delete_any', 'delete_replies',
  433. 'make_sticky',
  434. 'merge_any', 'split_any',
  435. 'modify_own', 'modify_any', 'modify_replies',
  436. 'move_any',
  437. 'send_topic',
  438. 'lock_own', 'lock_any',
  439. 'remove_own', 'remove_any',
  440. 'post_unapproved_topics', 'post_unapproved_replies_own', 'post_unapproved_replies_any',
  441. );
  442. $user_info['permissions'] = array_diff($user_info['permissions'], $denied_permissions);
  443. }
  444. // Are they absolutely under moderation?
  445. elseif (!empty($modSettings['warning_moderate']) && $modSettings['warning_moderate'] <= $user_info['warning'])
  446. {
  447. // Work out what permissions should change...
  448. $permission_change = array(
  449. 'post_new' => 'post_unapproved_topics',
  450. 'post_reply_own' => 'post_unapproved_replies_own',
  451. 'post_reply_any' => 'post_unapproved_replies_any',
  452. 'post_attachment' => 'post_unapproved_attachments',
  453. );
  454. foreach ($permission_change as $old => $new)
  455. {
  456. if (!in_array($old, $user_info['permissions']))
  457. unset($permission_change[$old]);
  458. else
  459. $user_info['permissions'][] = $new;
  460. }
  461. $user_info['permissions'] = array_diff($user_info['permissions'], array_keys($permission_change));
  462. }
  463. //!!! Find a better place to call this? Needs to be after permissions loaded!
  464. // Finally, some bits we cache in the session because it saves queries.
  465. if (isset($_SESSION['mc']) && $_SESSION['mc']['time'] > $modSettings['settings_updated'] && $_SESSION['mc']['id'] == $user_info['id'])
  466. $user_info['mod_cache'] = $_SESSION['mc'];
  467. else
  468. {
  469. require_once($sourcedir . '/Subs-Auth.php');
  470. rebuildModCache();
  471. }
  472. // Now that we have the mod cache taken care of lets setup a cache for the number of mod reports still open
  473. if (isset($_SESSION['rc']) && $_SESSION['rc']['time'] > $modSettings['last_mod_report_action'] && $_SESSION['rc']['id'] == $user_info['id'])
  474. $context['open_mod_reports'] = $_SESSION['rc']['reports'];
  475. elseif ($_SESSION['mc']['bq'] != '0=1')
  476. {
  477. require_once($sourcedir . '/ModerationCenter.php');
  478. recountOpenReports();
  479. }
  480. else
  481. $context['open_mod_reports'] = 0;
  482. }
  483. // Log a ban in the database.
  484. function log_ban($ban_ids = array(), $email = null)
  485. {
  486. global $user_info, $smcFunc;
  487. // Don't log web accelerators, it's very confusing...
  488. if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch')
  489. return;
  490. $smcFunc['db_insert']('',
  491. '{db_prefix}log_banned',
  492. array('id_member' => 'int', 'ip' => 'string-16', 'email' => 'string', 'log_time' => 'int'),
  493. array($user_info['id'], $user_info['ip'], ($email === null ? ($user_info['is_guest'] ? '' : $user_info['email']) : $email), time()),
  494. array('id_ban_log')
  495. );
  496. // One extra point for these bans.
  497. if (!empty($ban_ids))
  498. $smcFunc['db_query']('', '
  499. UPDATE {db_prefix}ban_items
  500. SET hits = hits + 1
  501. WHERE id_ban IN ({array_int:ban_ids})',
  502. array(
  503. 'ban_ids' => $ban_ids,
  504. )
  505. );
  506. }
  507. // Checks if a given email address might be banned.
  508. function isBannedEmail($email, $restriction, $error)
  509. {
  510. global $txt, $smcFunc;
  511. // Can't ban an empty email
  512. if (empty($email) || trim($email) == '')
  513. return;
  514. // Let's start with the bans based on your IP/hostname/memberID...
  515. $ban_ids = isset($_SESSION['ban'][$restriction]) ? $_SESSION['ban'][$restriction]['ids'] : array();
  516. $ban_reason = isset($_SESSION['ban'][$restriction]) ? $_SESSION['ban'][$restriction]['reason'] : '';
  517. // ...and add to that the email address you're trying to register.
  518. $request = $smcFunc['db_query']('', '
  519. SELECT bi.id_ban, bg.' . $restriction . ', bg.cannot_access, bg.reason
  520. FROM {db_prefix}ban_items AS bi
  521. INNER JOIN {db_prefix}ban_groups AS bg ON (bg.id_ban_group = bi.id_ban_group)
  522. WHERE {string:email} LIKE bi.email_address
  523. AND (bg.' . $restriction . ' = {int:cannot_access} OR bg.cannot_access = {int:cannot_access})
  524. AND (bg.expire_time IS NULL OR bg.expire_time >= {int:now})',
  525. array(
  526. 'email' => $email,
  527. 'cannot_access' => 1,
  528. 'now' => time(),
  529. )
  530. );
  531. while ($row = $smcFunc['db_fetch_assoc']($request))
  532. {
  533. if (!empty($row['cannot_access']))
  534. {
  535. $_SESSION['ban']['cannot_access']['ids'][] = $row['id_ban'];
  536. $_SESSION['ban']['cannot_access']['reason'] = $row['reason'];
  537. }
  538. if (!empty($row[$restriction]))
  539. {
  540. $ban_ids[] = $row['id_ban'];
  541. $ban_reason = $row['reason'];
  542. }
  543. }
  544. $smcFunc['db_free_result']($request);
  545. // You're in biiig trouble. Banned for the rest of this session!
  546. if (isset($_SESSION['ban']['cannot_access']))
  547. {
  548. log_ban($_SESSION['ban']['cannot_access']['ids']);
  549. $_SESSION['ban']['last_checked'] = time();
  550. fatal_error(sprintf($txt['your_ban'], $txt['guest_title']) . $_SESSION['ban']['cannot_access']['reason'], false);
  551. }
  552. if (!empty($ban_ids))
  553. {
  554. // Log this ban for future reference.
  555. log_ban($ban_ids, $email);
  556. fatal_error($error . $ban_reason, false);
  557. }
  558. }
  559. // Make sure the user's correct session was passed, and they came from here. (type can be post, get, or request.)
  560. function checkSession($type = 'post', $from_action = '', $is_fatal = true)
  561. {
  562. global $sc, $modSettings, $boardurl;
  563. // Is it in as $_POST['sc']?
  564. if ($type == 'post')
  565. {
  566. $check = isset($_POST[$_SESSION['session_var']]) ? $_POST[$_SESSION['session_var']] : (empty($modSettings['strictSessionCheck']) && isset($_POST['sc']) ? $_POST['sc'] : null);
  567. if ($check !== $sc)
  568. $error = 'session_timeout';
  569. }
  570. // How about $_GET['sesc']?
  571. elseif ($type == 'get')
  572. {
  573. $check = isset($_GET[$_SESSION['session_var']]) ? $_GET[$_SESSION['session_var']] : (empty($modSettings['strictSessionCheck']) && isset($_GET['sesc']) ? $_GET['sesc'] : null);
  574. if ($check !== $sc)
  575. $error = 'session_verify_fail';
  576. }
  577. // Or can it be in either?
  578. elseif ($type == 'request')
  579. {
  580. $check = isset($_GET[$_SESSION['session_var']]) ? $_GET[$_SESSION['session_var']] : (empty($modSettings['strictSessionCheck']) && isset($_GET['sesc']) ? $_GET['sesc'] : (isset($_POST[$_SESSION['session_var']]) ? $_POST[$_SESSION['session_var']] : (empty($modSettings['strictSessionCheck']) && isset($_POST['sc']) ? $_POST['sc'] : null)));
  581. if ($check !== $sc)
  582. $error = 'session_verify_fail';
  583. }
  584. // Verify that they aren't changing user agents on us - that could be bad.
  585. if ((!isset($_SESSION['USER_AGENT']) || $_SESSION['USER_AGENT'] != $_SERVER['HTTP_USER_AGENT']) && empty($modSettings['disableCheckUA']))
  586. $error = 'session_verify_fail';
  587. // Make sure a page with session check requirement is not being prefetched.
  588. if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch')
  589. {
  590. ob_end_clean();
  591. header('HTTP/1.1 403 Forbidden');
  592. die;
  593. }
  594. // Check the referring site - it should be the same server at least!
  595. $referrer = isset($_SERVER['HTTP_REFERER']) ? @parse_url($_SERVER['HTTP_REFERER']) : array();
  596. if (!empty($referrer['host']))
  597. {
  598. if (strpos($_SERVER['HTTP_HOST'], ':') !== false)
  599. $real_host = substr($_SERVER['HTTP_HOST'], 0, strpos($_SERVER['HTTP_HOST'], ':'));
  600. else
  601. $real_host = $_SERVER['HTTP_HOST'];
  602. $parsed_url = parse_url($boardurl);
  603. // Are global cookies on? If so, let's check them ;).
  604. if (!empty($modSettings['globalCookies']))
  605. {
  606. if (preg_match('~(?:[^\.]+\.)?([^\.]{3,}\..+)\z~i', $parsed_url['host'], $parts) == 1)
  607. $parsed_url['host'] = $parts[1];
  608. if (preg_match('~(?:[^\.]+\.)?([^\.]{3,}\..+)\z~i', $referrer['host'], $parts) == 1)
  609. $referrer['host'] = $parts[1];
  610. if (preg_match('~(?:[^\.]+\.)?([^\.]{3,}\..+)\z~i', $real_host, $parts) == 1)
  611. $real_host = $parts[1];
  612. }
  613. // Okay: referrer must either match parsed_url or real_host.
  614. if (isset($parsed_url['host']) && strtolower($referrer['host']) != strtolower($parsed_url['host']) && strtolower($referrer['host']) != strtolower($real_host))
  615. {
  616. $error = 'verify_url_fail';
  617. $log_error = true;
  618. }
  619. }
  620. // Well, first of all, if a from_action is specified you'd better have an old_url.
  621. if (!empty($from_action) && (!isset($_SESSION['old_url']) || preg_match('~[?;&]action=' . $from_action . '([;&]|$)~', $_SESSION['old_url']) == 0))
  622. {
  623. $error = 'verify_url_fail';
  624. $log_error = true;
  625. }
  626. if (strtolower($_SERVER['HTTP_USER_AGENT']) == 'hacker')
  627. fatal_error('Sound the alarm! It\'s a hacker! Close the castle gates!!', false);
  628. // Everything is ok, return an empty string.
  629. if (!isset($error))
  630. return '';
  631. // A session error occurred, show the error.
  632. elseif ($is_fatal)
  633. {
  634. if (isset($_GET['xml']))
  635. {
  636. ob_end_clean();
  637. header('HTTP/1.1 403 Forbidden - Session timeout');
  638. die;
  639. }
  640. else
  641. fatal_lang_error($error, isset($log_error) ? 'user' : false);
  642. }
  643. // A session error occurred, return the error to the calling function.
  644. else
  645. return $error;
  646. // We really should never fall through here, for very important reasons. Let's make sure.
  647. trigger_error('Hacking attempt...', E_USER_ERROR);
  648. }
  649. // Check if a specific confirm parameter was given.
  650. function checkConfirm($action)
  651. {
  652. global $modSettings;
  653. if (isset($_GET['confirm']) && isset($_SESSION['confirm_' . $action]) && md5($_GET['confirm'] . $_SERVER['HTTP_USER_AGENT']) == $_SESSION['confirm_' . $action])
  654. return true;
  655. else
  656. {
  657. $token = md5(mt_rand() . session_id() . (string) microtime() . $modSettings['rand_seed']);
  658. $_SESSION['confirm_' . $action] = md5($token . $_SERVER['HTTP_USER_AGENT']);
  659. return $token;
  660. }
  661. }
  662. // Check whether a form has been submitted twice.
  663. function checkSubmitOnce($action, $is_fatal = true)
  664. {
  665. global $context;
  666. if (!isset($_SESSION['forms']))
  667. $_SESSION['forms'] = array();
  668. // Register a form number and store it in the session stack. (use this on the page that has the form.)
  669. if ($action == 'register')
  670. {
  671. $context['form_sequence_number'] = 0;
  672. while (empty($context['form_sequence_number']) || in_array($context['form_sequence_number'], $_SESSION['forms']))
  673. $context['form_sequence_number'] = mt_rand(1, 16000000);
  674. }
  675. // Check whether the submitted number can be found in the session.
  676. elseif ($action == 'check')
  677. {
  678. if (!isset($_REQUEST['seqnum']))
  679. return true;
  680. elseif (!in_array($_REQUEST['seqnum'], $_SESSION['forms']))
  681. {
  682. $_SESSION['forms'][] = (int) $_REQUEST['seqnum'];
  683. return true;
  684. }
  685. elseif ($is_fatal)
  686. fatal_lang_error('error_form_already_submitted', false);
  687. else
  688. return false;
  689. }
  690. // Don't check, just free the stack number.
  691. elseif ($action == 'free' && isset($_REQUEST['seqnum']) && in_array($_REQUEST['seqnum'], $_SESSION['forms']))
  692. $_SESSION['forms'] = array_diff($_SESSION['forms'], array($_REQUEST['seqnum']));
  693. elseif ($action != 'free')
  694. trigger_error('checkSubmitOnce(): Invalid action \'' . $action . '\'', E_USER_WARNING);
  695. }
  696. // Check the user's permissions.
  697. function allowedTo($permission, $boards = null)
  698. {
  699. global $user_info, $modSettings, $smcFunc;
  700. // You're always allowed to do nothing. (unless you're a working man, MR. LAZY :P!)
  701. if (empty($permission))
  702. return true;
  703. // You're never allowed to do something if your data hasn't been loaded yet!
  704. if (empty($user_info))
  705. return false;
  706. // Administrators are supermen :P.
  707. if ($user_info['is_admin'])
  708. return true;
  709. // Are we checking the _current_ board, or some other boards?
  710. if ($boards === null)
  711. {
  712. // Check if they can do it.
  713. if (!is_array($permission) && in_array($permission, $user_info['permissions']))
  714. return true;
  715. // Search for any of a list of permissions.
  716. elseif (is_array($permission) && count(array_intersect($permission, $user_info['permissions'])) != 0)
  717. return true;
  718. // You aren't allowed, by default.
  719. else
  720. return false;
  721. }
  722. elseif (!is_array($boards))
  723. $boards = array($boards);
  724. $request = $smcFunc['db_query']('', '
  725. SELECT MIN(bp.add_deny) AS add_deny
  726. FROM {db_prefix}boards AS b
  727. INNER JOIN {db_prefix}board_permissions AS bp ON (bp.id_profile = b.id_profile)
  728. LEFT JOIN {db_prefix}moderators AS mods ON (mods.id_board = b.id_board AND mods.id_member = {int:current_member})
  729. WHERE b.id_board IN ({array_int:board_list})
  730. AND bp.id_group IN ({array_int:group_list}, {int:moderator_group})
  731. AND bp.permission {raw:permission_list}
  732. AND (mods.id_member IS NOT NULL OR bp.id_group != {int:moderator_group})
  733. GROUP BY b.id_board',
  734. array(
  735. 'current_member' => $user_info['id'],
  736. 'board_list' => $boards,
  737. 'group_list' => $user_info['groups'],
  738. 'moderator_group' => 3,
  739. 'permission_list' => (is_array($permission) ? 'IN (\'' . implode('\', \'', $permission) . '\')' : ' = \'' . $permission . '\''),
  740. )
  741. );
  742. // Make sure they can do it on all of the boards.
  743. if ($smcFunc['db_num_rows']($request) != count($boards))
  744. return false;
  745. $result = true;
  746. while ($row = $smcFunc['db_fetch_assoc']($request))
  747. $result &= !empty($row['add_deny']);
  748. $smcFunc['db_free_result']($request);
  749. // If the query returned 1, they can do it... otherwise, they can't.
  750. return $result;
  751. }
  752. // Fatal error if they cannot...
  753. function isAllowedTo($permission, $boards = null)
  754. {
  755. global $user_info, $txt;
  756. static $heavy_permissions = array(
  757. 'admin_forum',
  758. 'manage_attachments',
  759. 'manage_smileys',
  760. 'manage_boards',
  761. 'edit_news',
  762. 'moderate_forum',
  763. 'manage_bans',
  764. 'manage_membergroups',
  765. 'manage_permissions',
  766. );
  767. // Make it an array, even if a string was passed.
  768. $permission = is_array($permission) ? $permission : array($permission);
  769. // Check the permission and return an error...
  770. if (!allowedTo($permission, $boards))
  771. {
  772. // Pick the last array entry as the permission shown as the error.
  773. $error_permission = array_shift($permission);
  774. // If they are a guest, show a login. (because the error might be gone if they do!)
  775. if ($user_info['is_guest'])
  776. {
  777. loadLanguage('Errors');
  778. is_not_guest($txt['cannot_' . $error_permission]);
  779. }
  780. // Clear the action because they aren't really doing that!
  781. $_GET['action'] = '';
  782. $_GET['board'] = '';
  783. $_GET['topic'] = '';
  784. writeLog(true);
  785. fatal_lang_error('cannot_' . $error_permission, false);
  786. // Getting this far is a really big problem, but let's try our best to prevent any cases...
  787. trigger_error('Hacking attempt...', E_USER_ERROR);
  788. }
  789. // If you're doing something on behalf of some "heavy" permissions, validate your session.
  790. // (take out the heavy permissions, and if you can't do anything but those, you need a validated session.)
  791. if (!allowedTo(array_diff($permission, $heavy_permissions), $boards))
  792. validateSession();
  793. }
  794. // Return the boards a user has a certain (board) permission on. (array(0) if all.)
  795. function boardsAllowedTo($permissions, $check_access = true)
  796. {
  797. global $user_info, $modSettings, $smcFunc;
  798. // Administrators are all powerful, sorry.
  799. if ($user_info['is_admin'])
  800. return array(0);
  801. // Arrays are nice, most of the time.
  802. if (!is_array($permissions))
  803. $permissions = array($permissions);
  804. // All groups the user is in except 'moderator'.
  805. $groups = array_diff($user_info['groups'], array(3));
  806. $request = $smcFunc['db_query']('', '
  807. SELECT b.id_board, bp.add_deny
  808. FROM {db_prefix}board_permissions AS bp
  809. INNER JOIN {db_prefix}boards AS b ON (b.id_profile = bp.id_profile)
  810. LEFT JOIN {db_prefix}moderators AS mods ON (mods.id_board = b.id_board AND mods.id_member = {int:current_member})
  811. WHERE bp.id_group IN ({array_int:group_list}, {int:moderator_group})
  812. AND bp.permission IN ({array_string:permissions})
  813. AND (mods.id_member IS NOT NULL OR bp.id_group != {int:moderator_group})' .
  814. ($check_access ? ' AND {query_see_board}' : ''),
  815. array(
  816. 'current_member' => $user_info['id'],
  817. 'group_list' => $groups,
  818. 'moderator_group' => 3,
  819. 'permissions' => $permissions,
  820. )
  821. );
  822. $boards = array();
  823. $deny_boards = array();
  824. while ($row = $smcFunc['db_fetch_assoc']($request))
  825. {
  826. if (empty($row['add_deny']))
  827. $deny_boards[] = $row['id_board'];
  828. else
  829. $boards[] = $row['id_board'];
  830. }
  831. $smcFunc['db_free_result']($request);
  832. $boards = array_unique(array_values(array_diff($boards, $deny_boards)));
  833. return $boards;
  834. }
  835. function showEmailAddress($userProfile_hideEmail, $userProfile_id)
  836. {
  837. global $modSettings, $user_info;
  838. // Should this users email address be shown?
  839. // If you're guest and the forum is set to hide email for guests: no.
  840. // If the user is post-banned: no.
  841. // If it's your own profile and you've set your address hidden: yes_permission_override.
  842. // If you're a moderator with sufficient permissions: yes_permission_override.
  843. // If the user has set their email address to be hidden: no.
  844. // If the forum is set to show full email addresses: yes.
  845. // Otherwise: no_through_forum.
  846. return (!empty($modSettings['guest_hideContacts']) && $user_info['is_guest']) || isset($_SESSION['ban']['cannot_post']) ? 'no' : ((!$user_info['is_guest'] && $user_info['id'] == $userProfile_id && !$userProfile_hideEmail) || allowedTo('moderate_forum') ? 'yes_permission_override' : ($userProfile_hideEmail ? 'no' : (!empty($modSettings['make_email_viewable']) ? 'yes' : 'no_through_forum')));
  847. }
  848. /**
  849. * This function attempts to protect from spammed messages and the like.
  850. * The time taken depends on error_type - generally uses the modSetting.
  851. *
  852. * @param string $error_type, used also as a $txt index. (not an actual string.)
  853. * @return boolean
  854. */
  855. function spamProtection($error_type)
  856. {
  857. global $modSettings, $txt, $user_info, $smcFunc;
  858. // Certain types take less/more time.
  859. $timeOverrides = array(
  860. 'login' => 2,
  861. 'register' => 2,
  862. 'sendtopc' => $modSettings['spamWaitTime'] * 4,
  863. 'sendmail' => $modSettings['spamWaitTime'] * 5,
  864. 'reporttm' => $modSettings['spamWaitTime'] * 4,
  865. 'search' => !empty($modSettings['search_floodcontrol_time']) ? $modSettings['search_floodcontrol_time'] : 1,
  866. );
  867. // Moderators are free...
  868. if (!allowedTo('moderate_board'))
  869. $timeLimit = isset($timeOverrides[$error_type]) ? $timeOverrides[$error_type] : $modSettings['spamWaitTime'];
  870. else
  871. $timeLimit = 2;
  872. // Delete old entries...
  873. $smcFunc['db_query']('', '
  874. DELETE FROM {db_prefix}log_floodcontrol
  875. WHERE log_time < {int:log_time}
  876. AND log_type = {string:log_type}',
  877. array(
  878. 'log_time' => time() - $timeLimit,
  879. 'log_type' => $error_type,
  880. )
  881. );
  882. // Add a new entry, deleting the old if necessary.
  883. $smcFunc['db_insert']('replace',
  884. '{db_prefix}log_floodcontrol',
  885. array('ip' => 'string-16', 'log_time' => 'int', 'log_type' => 'string'),
  886. array($user_info['ip'], time(), $error_type),
  887. array('ip', 'log_type')
  888. );
  889. // If affected is 0 or 2, it was there already.
  890. if ($smcFunc['db_affected_rows']() != 1)
  891. {
  892. // Spammer! You only have to wait a *few* seconds!
  893. fatal_lang_error($error_type . 'WaitTime_broken', false, array($timeLimit));
  894. return true;
  895. }
  896. // They haven't posted within the limit.
  897. return false;
  898. }
  899. ?>