comparison forum/Sources/Security.php @ 76:e3e11437ecea website

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