source: trunk/lib/Auth_SQL.inc.php @ 275

Last change on this file since 275 was 275, checked in by quinn, 17 years ago

Added match_remote_ip_exempt_usernames function for trendease (ported from codebase 1.1dev).

File size: 45.9 KB
Line 
1<?php
2/**
3 * The Auth_SQL class provides a SQL implementation for authentication.
4 *
5 * @author  Quinn Comendant <quinn@strangecode.com>
6 * @version 2.1
7 */
8
9// Available encryption types for class Auth_SQL.
10define('AUTH_ENCRYPT_PLAINTEXT', 1);
11define('AUTH_ENCRYPT_CRYPT', 2);
12define('AUTH_ENCRYPT_SHA1', 3);
13define('AUTH_ENCRYPT_SHA1_HARDENED', 4);
14define('AUTH_ENCRYPT_MD5', 5);
15define('AUTH_ENCRYPT_MD5_HARDENED', 6);
16
17require_once dirname(__FILE__) . '/Email.inc.php';
18
19class Auth_SQL {
20       
21    // Namespace of this auth object.
22    var $_ns;
23   
24    // Static var for test.
25    var $_authentication_tested;
26
27    // Paramters to be configured by setParam.
28    var $_params = array();
29    var $_default_params = array(
30
31        // Automatically create table and verify columns. Better set to false after site launch.
32        'create_table' => true,
33
34        // The database table containing users to authenticate.
35        'db_table' => 'user_tbl',
36
37        // The name of the primary key for the db_table.
38        'db_primary_key' => 'user_id',
39
40        // The name of the username key for the db_table.
41        'db_username_column' => 'username',
42
43        // If using the db_login_table feature, specify the db_login_table. The primary key must match the primary key for the db_table.
44        'db_login_table' => 'user_login_tbl',
45
46        // The type of encryption to use for passwords stored in the db_table. Use one of the AUTH_ENCRYPT_* types specified above.
47        // Hardened password hashes rely on the same key/salt being used to compare encryptions.
48        // Be aware that when using one of the hardened types the App signing_key or $more_salt below cannot change!
49        'encryption_type' => AUTH_ENCRYPT_MD5,
50
51        // The URL to the login script.
52        'login_url' => '/',
53
54        // The maximum amount of time a user is allowed to be logged in. They will be forced to login again if they expire.
55        // In seconds. 21600 seconds = 6 hours.
56        'login_timeout' => 21600,
57
58        // The maximum amount of time a user is allowed to be idle before their session expires. They will be forced to login again if they expire.
59        // In seconds. 3600 seconds = 1 hour.
60        'idle_timeout' => 3600,
61
62        // The period of time to compare login abuse attempts. If a threshold of logins is reached in this amount of time the account is blocked.
63        // Days and hours, like this: 'DD:HH'
64        'login_abuse_timeframe' => '04:00',
65
66        // The number of warnings a user will receive (and their password reset each time) before their account is completely blocked.
67        'login_abuse_warnings' => 3,
68
69        // The maximum number of IP addresses a user can login with over the timeout period before their account is blocked.
70        'login_abuse_max_ips' => 5,
71
72        // The IP address subnet size threshold. Uses a CIDR notation network mask (see CIDR cheatsheet at bottom).
73        // Any integar between 0 and 32 is permitted. Setting this to '24' permits any address in a
74        // class C network (255.255.255.0) to be considered the same. Setting to '32' compares each IP absolutely.
75        // Setting to '0' ignores all IPs, thus disabling login_abuse checking.
76        'login_abuse_ip_bitmask' => 32,
77
78        // Specify usernames to exclude from the account abuse detection system. This is specified as a hardcoded array provided at
79        // class instantiation time, or can be saved in the db_table under the login_abuse_exempt field.
80        'login_abuse_exempt_usernames' => array(),
81
82        // Specify usernames to exclude from remote_ip matching. Users behind proxy servers should be appended to this array so their shifting remote IP will not log them out.
83        'match_remote_ip_exempt_usernames' => array(),
84
85        // Match the user's current remote IP against the one they logged in with.
86        'match_remote_ip' => true,
87
88        // An array of IP blocks that are bypass the remote_ip comparison check. Useful for dynamic IPs or those behind proxy servers.
89        'trusted_networks' => array(),
90
91        // Allow user accounts to be blocked? Requires the user table to have the columns 'blocked' and 'blocked_reason'
92        'blocking' => false,
93
94        // Use a db_login_table to detect excessive logins. This requires blocking to be enabled.
95        'abuse_detection' => false,
96    );
97
98    /**
99     * Constructs a new authentication object.
100     *
101     * @access public
102     * @param optional array $params  A hash containing parameters.
103     */
104    function Auth_SQL($namespace='')
105    {
106        $app =& App::getInstance();
107       
108        $this->_ns = $namespace;
109       
110        // Initialize default parameters.
111        $this->setParam($this->_default_params);
112
113        // Get create tables config from global context.
114        if (!is_null($app->getParam('db_create_tables'))) {
115            $this->setParam(array('create_table' => $app->getParam('db_create_tables')));
116        }
117
118        if (!isset($_SESSION['_auth_sql'][$this->_ns])) {
119            $this->clear();
120        }
121    }
122
123    /**
124     * Setup the database tables for this class.
125     *
126     * @access  public
127     * @author  Quinn Comendant <quinn@strangecode.com>
128     * @since   26 Aug 2005 17:09:36
129     */
130    function initDB($recreate_db=false)
131    {
132        $app =& App::getInstance();
133        $db =& DB::getInstance();
134   
135   
136        static $_db_tested = false;
137
138        if ($recreate_db || !$_db_tested && $this->getParam('create_table')) {
139
140            // User table.
141            if ($recreate_db) {
142                $db->query("DROP TABLE IF EXISTS " . $this->getParam('db_table'));
143                $app->logMsg(sprintf('Dropping and recreating table %s.', $this->getParam('db_table')), LOG_INFO, __FILE__, __LINE__);
144            }
145
146            // The minimal columns for a table compatable with the Auth_SQL class.
147            $db->query("CREATE TABLE IF NOT EXISTS " . $db->escapeString($this->getParam('db_table')) . " (
148                " . $this->getParam('db_primary_key') . " smallint(11) NOT NULL auto_increment,
149                " . $this->getParam('db_username_column') . " varchar(255) NOT NULL default '',
150                userpass VARCHAR(255) NOT NULL DEFAULT '',
151                first_name VARCHAR(255) NOT NULL DEFAULT '',
152                last_name VARCHAR(255) NOT NULL DEFAULT '',
153                email VARCHAR(255) NOT NULL DEFAULT '',
154                login_abuse_exempt ENUM('TRUE') DEFAULT NULL,
155                blocked ENUM('TRUE') DEFAULT NULL,
156                blocked_reason VARCHAR(255) NOT NULL DEFAULT '',
157                abuse_warning_level TINYINT(4) NOT NULL DEFAULT '0',
158                seconds_online INT(11) NOT NULL DEFAULT '0',
159                last_login_datetime DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
160                last_access_datetime DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
161                last_login_ip VARCHAR(255) NOT NULL DEFAULT '0.0.0.0',
162                added_by_user_id SMALLINT(11) DEFAULT NULL,
163                modified_by_user_id SMALLINT(11) DEFAULT NULL,
164                added_datetime DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
165                modified_datetime DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
166                PRIMARY KEY (" . $this->getParam('db_primary_key') . "),
167                KEY " . $this->getParam('db_username_column') . " (" . $this->getParam('db_username_column') . "),
168                KEY userpass (userpass),
169                KEY email (email)
170            )");
171
172            if (!$db->columnExists($this->getParam('db_table'), array(
173                $this->getParam('db_primary_key'),
174                $this->getParam('db_username_column'),
175                'userpass',
176                'first_name',
177                'last_name',
178                'email',
179                'login_abuse_exempt',
180                'blocked',
181                'blocked_reason',
182                'abuse_warning_level',
183                'seconds_online',
184                'last_login_datetime',
185                'last_access_datetime',
186                'last_login_ip',
187                'added_by_user_id',
188                'modified_by_user_id',
189                'added_datetime',
190                'modified_datetime',
191            ), false, false)) {
192                $app->logMsg(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), LOG_ALERT, __FILE__, __LINE__);
193                trigger_error(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), E_USER_ERROR);
194            }
195
196            // Login table is used for abuse_detection features.
197            if ($this->getParam('abuse_detection')) {
198                if ($recreate_db) {
199                    $db->query("DROP TABLE IF EXISTS " . $this->getParam('db_login_table'));
200                    $app->logMsg(sprintf('Dropping and recreating table %s.', $this->getParam('db_login_table')), LOG_INFO, __FILE__, __LINE__);
201                }
202                $db->query("CREATE TABLE IF NOT EXISTS " . $this->getParam('db_login_table') . " (
203                    " . $this->getParam('db_primary_key') . " SMALLINT(11) NOT NULL DEFAULT '0',
204                    login_datetime DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
205                    remote_ip_binary CHAR(32) NOT NULL DEFAULT '',
206                    KEY " . $this->getParam('db_primary_key') . " (" . $this->getParam('db_primary_key') . "),
207                    KEY login_datetime (login_datetime),
208                    KEY remote_ip_binary (remote_ip_binary)
209                )");
210
211                if (!$db->columnExists($this->getParam('db_login_table'), array(
212                    $this->getParam('db_primary_key'),
213                    'login_datetime',
214                    'remote_ip_binary',
215                ), false, false)) {
216                    $app->logMsg(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_login_table')), LOG_ALERT, __FILE__, __LINE__);
217                    trigger_error(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_login_table')), E_USER_ERROR);
218                }
219            }
220        }
221        $_db_tested = true;
222    }
223
224    /**
225     * Set the params of an auth object.
226     *
227     * @param  array $params   Array of parameter keys and value to set.
228     * @return bool true on success, false on failure
229     */
230    function setParam($params)
231    {
232        if (isset($params) && is_array($params)) {
233            // Merge new parameters with old overriding only those passed.
234            $this->_params = array_merge($this->_params, $params);
235        }
236    }
237
238    /**
239     * Return the value of a parameter, if it exists.
240     *
241     * @access public
242     * @param string $param        Which parameter to return.
243     * @return mixed               Configured parameter value.
244     */
245    function getParam($param)
246    {
247        $app =& App::getInstance();
248   
249        if (isset($this->_params[$param])) {
250            return $this->_params[$param];
251        } else {
252            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
253            return null;
254        }
255    }
256
257    /**
258     * Clear any authentication tokens in the current session. A.K.A. logout.
259     *
260     * @access public
261     */
262    function clear()
263    {
264        $db =& DB::getInstance();
265   
266        $this->initDB();
267
268        if ($this->get('user_id', false)) {
269            // FIX ME: Should we check if the session is active?
270            $db->query("
271                UPDATE " . $this->_params['db_table'] . " SET
272                seconds_online = seconds_online + (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_access_datetime)),
273                last_login_datetime = '0000-00-00 00:00:00'
274                WHERE " . $this->_params['db_primary_key'] . " = '" . $this->get('user_id') . "'
275            ");
276        }
277        $_SESSION['_auth_sql'][$this->_ns] = array('authenticated' => false);
278    }
279
280    /**
281     * Sets a variable into a registered auth session.
282     *
283     * @access public
284     * @param mixed $key      Which value to set.
285     * @param mixed $val      Value to set variable to.
286     */
287    function set($key, $val)
288    {
289        if (!isset($_SESSION['_auth_sql'][$this->_ns]['user_data'])) {
290            $_SESSION['_auth_sql'][$this->_ns]['user_data'] = array();
291        }
292        $_SESSION['_auth_sql'][$this->_ns]['user_data'][$key] = $val;
293    }
294
295    /**
296     * Returns a specified value from a registered auth session.
297     *
298     * @access public
299     * @param mixed $key      Which value to return.
300     * @param mixed $default  Value to return if key not found in user_data.
301     * @return mixed          Value stored in session.
302     */
303    function get($key, $default='')
304    {
305        if (isset($_SESSION['_auth_sql'][$this->_ns][$key])) {
306            return $_SESSION['_auth_sql'][$this->_ns][$key];
307        } else if (isset($_SESSION['_auth_sql'][$this->_ns]['user_data'][$key])) {
308            return $_SESSION['_auth_sql'][$this->_ns]['user_data'][$key];
309        } else {
310            return $default;
311        }
312    }
313
314    /**
315     * Find out if a set of login credentials are valid.
316     *
317     * @access private
318     * @param string $username      The username to check.
319     * @param string $password      The password to compare to username.
320     * @return mixed  False if credentials not found in DB, or returns DB row matching credentials.
321     */
322    function authenticate($username, $password)
323    {
324        $app =& App::getInstance();
325        $db =& DB::getInstance();
326
327        $this->initDB();
328
329        switch ($this->_params['encryption_type']) {
330        case AUTH_ENCRYPT_CRYPT :
331            // Query DB for user matching credentials. Compare cyphertext with salted-encrypted password.
332            $qid = $db->query("
333                SELECT *, " . $this->_params['db_primary_key'] . " AS user_id
334                FROM " . $this->_params['db_table'] . "
335                WHERE " . $this->_params['db_username_column'] . " = '" . $db->escapeString($username) . "'
336                AND BINARY userpass = ENCRYPT('" . $db->escapeString($password) . "', LEFT(userpass, 2)))
337            ");
338            break;
339        case AUTH_ENCRYPT_PLAINTEXT :
340        case AUTH_ENCRYPT_MD5 :
341        case AUTH_ENCRYPT_SHA1 :
342        default :
343            // Query DB for user matching credentials. Directly compare cyphertext with result from encryptPassword().
344            $qid = $db->query("
345                SELECT *, " . $this->_params['db_primary_key'] . " AS user_id
346                FROM " . $this->_params['db_table'] . "
347                WHERE " . $this->_params['db_username_column'] . " = '" . $db->escapeString($username) . "'
348                AND BINARY userpass = '" . $db->escapeString($this->encryptPassword($password)) . "'
349            ");
350            break;
351        }
352
353        // Return user data if found.
354        if ($user_data = mysql_fetch_assoc($qid)) {
355            // Don't return password value.
356            unset($user_data['userpass']);
357            $app->logMsg(sprintf('Authentication successful for user %s (%s)', $user_data['user_id'], $username), LOG_INFO, __FILE__, __LINE__);
358            return $user_data;
359        } else {
360            $app->logMsg(sprintf('Authentication failed for user %s (encrypted attempted password: %s)', $username, $this->encryptPassword($password)), LOG_NOTICE, __FILE__, __LINE__);
361            return false;
362        }
363    }
364
365    /**
366     * If user authenticated, register login into session.
367     *
368     * @access private
369     * @param string $username     The username to check.
370     * @param string $password     The password to compare to username.
371     * @return boolean  Whether or not the credentials are valid.
372     */
373    function login($username, $password)
374    {
375        $app =& App::getInstance();
376        $db =& DB::getInstance();
377   
378        $this->initDB();
379
380        $this->clear();
381
382        if (!$user_data = $this->authenticate($username, $password)) {
383            // No login: failed authentication!
384            return false;
385        }
386
387        // Register authenticated session.
388        $_SESSION['_auth_sql'][$this->_ns] = array(
389            'authenticated'         => true,
390            'user_id'               => $user_data['user_id'],
391            'username'              => $username,
392            'login_datetime'        => date('Y-m-d H:i:s'),
393            'last_access_datetime'  => date('Y-m-d H:i:s'),
394            'remote_ip'             => getRemoteAddr(),
395            'login_abuse_exempt'    => isset($user_data['login_abuse_exempt']) ? !empty($user_data['login_abuse_exempt']) : in_array(strtolower($username), $this->_params['login_abuse_exempt_usernames']),
396            'match_remote_ip_exempt'=> isset($user_data['match_remote_ip_exempt']) ? !empty($user_data['match_remote_ip_exempt']) : in_array(strtolower($username), $this->_params['match_remote_ip_exempt_usernames']),
397            'user_data'             => $user_data
398        );
399
400        /**
401         * Check if the account is blocked, respond in context to reason. Cancel the login if blocked.
402         */
403        if ($this->getParam('blocking')) {
404            if (!empty($user_data['blocked'])) {
405
406                $app->logMsg(sprintf('User %s (%s) login failed due to blocked account: %s', $this->get('user_id'), $this->get('username'), $this->get('blocked_reason')), LOG_NOTICE, __FILE__, __LINE__);
407
408                switch ($user_data['blocked_reason']) {
409                    case 'account abuse' :
410                        $app->raiseMsg(sprintf(_("This account has been blocked due to possible account abuse. Please contact us to reactivate."), null), MSG_WARNING, __FILE__, __LINE__);
411                        break;
412                    default :
413                        $app->raiseMsg(sprintf(_("This account is currently not active. %s"), $user_data['blocked_reason']), MSG_WARNING, __FILE__, __LINE__);
414                        break;
415                }
416
417                // No login: user is blocked!
418                $this->clear();
419                return false;
420            }
421        }
422
423        /**
424         * Check the db_login_table for too many logins under this account.
425         * (1) Count the number of unique IP addresses that logged in under this user within the login_abuse_timeframe
426         * (2) If this number exceeds the login_abuse_max_ips, assume multiple people are logging in under the same account.
427        **/
428        if ($this->getParam('abuse_detection') && !$this->get('login_abuse_exempt')) {
429            $qid = $db->query("
430                SELECT COUNT(DISTINCT LEFT(remote_ip_binary, " . $this->_params['login_abuse_ip_bitmask'] . "))
431                FROM " . $this->_params['db_login_table'] . "
432                WHERE " . $this->_params['db_primary_key'] . " = '" . $this->get('user_id') . "'
433                AND DATE_ADD(login_datetime, INTERVAL '" . $this->_params['login_abuse_timeframe'] . "' DAY_HOUR) > NOW()
434            ");
435            list($distinct_ips) = mysql_fetch_row($qid);
436            if ($distinct_ips > $this->_params['login_abuse_max_ips']) {
437                if ($this->get('abuse_warning_level') < $this->_params['login_abuse_warnings']) {
438                    // Warn the user with a password reset.
439                    $this->resetPassword(null, _("This is a security precaution. We have detected this account has been accessed from multiple computers simultaneously. It is against policy to share login information with others. If further account abuse is detected this account will be blocked."));
440                    $app->raiseMsg(_("Your password has been reset as a security precaution. Please check your email for more information."), MSG_NOTICE, __FILE__, __LINE__);
441                    $app->logMsg(sprintf('Account abuse detected for user %s (%s) from IP %s', $this->get('user_id'), $this->get('username'), $this->get('remote_ip')), LOG_WARNING, __FILE__, __LINE__);
442                } else {
443                    // Block the account with the reason of account abuse.
444                    $this->blockAccount(null, 'account abuse');
445                    $app->raiseMsg(_("Your account has been blocked as a security precaution. Please contact us for more information."), MSG_NOTICE, __FILE__, __LINE__);
446                    $app->logMsg(sprintf('Account blocked for user %s (%s) from IP %s', $this->get('user_id'), $this->get('username'), $this->get('remote_ip')), LOG_ALERT, __FILE__, __LINE__);
447                }
448                // Increment user's warning level.
449                $db->query("UPDATE " . $this->_params['db_table'] . " SET abuse_warning_level = abuse_warning_level + 1 WHERE " . $this->_params['db_primary_key'] . " = '" . $this->get('user_id') . "'");
450                // Reset the login counter for this user.
451                $db->query("DELETE FROM " . $this->_params['db_login_table'] . " WHERE " . $this->_params['db_primary_key'] . " = '" . $this->get('user_id') . "'");
452                // No login: reset password because of account abuse!
453                $this->clear();
454                return false;
455            }
456
457            // Update the login counter table with this login access. Convert IP to binary.
458            // TODO: after MySQL 5.0.23 is released this query could benefit from INSERT DELAYED.
459            $db->query("
460                INSERT INTO " . $this->_params['db_login_table'] . " (
461                    " . $this->_params['db_primary_key'] . ",
462                    login_datetime,
463                    remote_ip_binary
464                ) VALUES (
465                    '" . $this->get('user_id') . "',
466                    '" . $this->get('login_datetime') . "',
467                    '" . sprintf('%032b', ip2long($this->get('remote_ip'))) . "'
468                )
469            ");
470        }
471
472        // Update user table with this login.
473        $db->query("
474            UPDATE " . $this->_params['db_table'] . " SET
475                last_login_datetime = '" . $this->get('login_datetime') . "',
476                last_access_datetime = '" . $this->get('login_datetime') . "',
477                last_login_ip = '" . $this->get('remote_ip') . "'
478            WHERE " . $this->_params['db_primary_key'] . " = '" . $this->get('user_id') . "'
479        ");
480
481        // We're logged-in!
482        return true;
483    }
484
485    /**
486     * Test if user has a currently logged-in session.
487     *  - authentication flag set to true
488     *  - username not empty
489     *  - total logged-in time is not greater than login_timeout
490     *  - idle time is not greater than idle_timeout
491     *  - remote address is the same as the login remote address (aol users excluded).
492     *
493     * @access public
494     */
495    function isLoggedIn($user_id=null)
496    {
497        $app =& App::getInstance();
498        $db =& DB::getInstance();
499   
500        $this->initDB();
501
502        if (isset($user_id)) {
503            // Check the login status of a specific user.
504            $qid = $db->query("
505                SELECT 1 FROM " . $this->_params['db_table'] . "
506                WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
507                AND DATE_ADD(last_login_datetime, INTERVAL '" . $this->_params['login_timeout'] . "' SECOND) > NOW()
508                AND DATE_ADD(last_access_datetime, INTERVAL '" . $this->_params['idle_timeout'] . "' SECOND) > NOW()
509            ");
510            return (mysql_num_rows($qid) > 0);
511        }
512
513        // User login test need only be run once per script execution. We cache the result in the session.
514        if ($this->_authentication_tested && isset($_SESSION['_auth_sql'][$this->_ns]['authenticated'])) {
515            return $_SESSION['_auth_sql'][$this->_ns]['authenticated'];
516        }
517
518        // Tesing login should occur once. This is the first time. Set flag.
519        $this->_authentication_tested = true;
520
521        // Some users will access from networks with a changing IP number (i.e. behind a proxy server). These users must be allowed entry by adding their IP to the list of trusted_networks.
522        if ($trusted_net = ipInRange(getRemoteAddr(), $this->_params['trusted_networks'])) {
523            $user_in_trusted_network = true;
524            $app->logMsg(sprintf('User %s accessing from trusted network %s',
525                ($this->get('user_id') ? ' ' . $this->get('user_id') . ' (' .  $this->get('username') . ')' : ''),
526                $trusted_net
527            ), LOG_DEBUG, __FILE__, __LINE__);
528        } else if (preg_match('/proxy.aol.com$/i', getRemoteAddr(true))) {
529            $user_in_trusted_network = true;
530            $app->logMsg(sprintf('User %s accessing from trusted network proxy.aol.com',
531                ($this->get('user_id') ? ' ' . $this->get('user_id') . ' (' .  $this->get('username') . ')' : '')
532            ), LOG_DEBUG, __FILE__, __LINE__);
533        } else {
534            $user_in_trusted_network = false;
535        }
536       
537        // Do we match the user's remote IP at all? Yes, if set in config and not disabled for specific user.
538        if ($this->getParam('match_remote_ip') && !$this->get('match_remote_ip_exempt')) {
539            $remote_ip_is_matched = ($_SESSION['_auth_sql'][$this->_ns]['remote_ip'] == getRemoteAddr() || $user_in_trusted_network);
540        } else {
541            $app->logMsg(sprintf('User %s exempt from remote_ip match.', 
542                ($this->get('user_id') ? ' ' . $this->get('user_id') . ' (' .  $this->get('username') . ')' : '')
543            ), LOG_DEBUG, __FILE__, __LINE__);
544            $remote_ip_is_matched = true;
545        }
546
547        // Test login with information stored in session. Skip IP matching for users from trusted networks.
548        if (isset($_SESSION['_auth_sql'][$this->_ns]['authenticated']) 
549            && true === $_SESSION['_auth_sql'][$this->_ns]['authenticated']
550            && !empty($_SESSION['_auth_sql'][$this->_ns]['username'])
551            && strtotime($_SESSION['_auth_sql'][$this->_ns]['login_datetime']) > time() - $this->_params['login_timeout']
552            && strtotime($_SESSION['_auth_sql'][$this->_ns]['last_access_datetime']) > time() - $this->_params['idle_timeout']
553            && $remote_ip_is_matched
554        ) {
555            // User is authenticated!
556            $_SESSION['_auth_sql'][$this->_ns]['last_access_datetime'] = date('Y-m-d H:i:s');
557
558            // Update the DB with the last_access_datetime and increment the seconds_online.
559            $db->query("
560                UPDATE " . $this->_params['db_table'] . " SET
561                seconds_online = seconds_online + (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_access_datetime)) + 1,
562                last_access_datetime = '" . $this->get('last_access_datetime') . "'
563                WHERE " . $this->_params['db_primary_key'] . " = '" . $this->get('user_id') . "'
564            ");
565            if (mysql_affected_rows($db->getDBH()) > 0) {
566                // User record still exists in DB. Do this to ensure user was not delete from DB between accesses. Notice "+ 1" in SQL above to ensure record is modified.
567                return true;
568            } else {
569                $app->logMsg(sprintf('User update failed. Record not found for user %s (%s).', $this->get('user_id'), $this->get('username')), LOG_NOTICE, __FILE__, __LINE__);
570            }
571        } else if (isset($_SESSION['_auth_sql'][$this->_ns]['authenticated']) && true === $_SESSION['_auth_sql'][$this->_ns]['authenticated']) {
572            // User is authenticated, but login has expired.
573            if (strtotime($_SESSION['_auth_sql'][$this->_ns]['last_access_datetime']) > time() - 43200) {
574                // Only raise message if last session is less than 12 hours old.
575                $app->raiseMsg(_("Your session has expired. You need to log-in again."), MSG_NOTICE, __FILE__, __LINE__);
576            }
577
578            // Log the reason for login expiration.
579            $expire_reasons = array();
580            if (empty($_SESSION['_auth_sql'][$this->_ns]['username'])) {
581                $expire_reasons[] = 'username not found';
582            }
583            if (strtotime($_SESSION['_auth_sql'][$this->_ns]['login_datetime']) <= time() - $this->_params['login_timeout']) {
584                $expire_reasons[] = 'login_timeout expired';
585            }
586            if (strtotime($_SESSION['_auth_sql'][$this->_ns]['last_access_datetime']) <= time() - $this->_params['idle_timeout']) {
587                $expire_reasons[] = 'idle_timeout expired';
588            }
589            if ($_SESSION['_auth_sql'][$this->_ns]['remote_ip'] != getRemoteAddr() && !$user_in_trusted_network) {
590                if ($this->getFeature('match_remote_ip') && !$this->getVal('match_remote_ip_exempt')) {
591                    $expire_reasons[] = sprintf('remote_ip not matched (%s != %s)', $_SESSION['_auth_sql'][$this->_ns]['remote_ip'], getRemoteAddr());
592                } else {
593                    $expire_reasons[] = sprintf('remote_ip not matched but user was exempt from this check (%s != %s)', $_SESSION['_auth_sql'][$this->_ns]['remote_ip'], getRemoteAddr());
594                }
595            }
596            $app->logMsg(sprintf('User %s (%s) session expired: %s', $this->get('user_id'), $this->get('username'), join(', ', $expire_reasons)), LOG_INFO, __FILE__, __LINE__);
597        }
598
599        // User is not authenticated.
600        $this->clear();
601        return false;
602    }
603
604    /**
605     * Redirect user to login page if they are not logged in.
606     *
607     * @param string $message The text description of a message to raise.
608     * @param int    $type    The type of message: MSG_NOTICE,
609     *                        MSG_SUCCESS, MSG_WARNING, or MSG_ERR.
610     * @param string $file    __FILE__.
611     * @param string $line    __LINE__.
612     * @access public
613     */
614    function requireLogin($message='', $type=MSG_NOTICE, $file=null, $line=null)
615    {
616        $app =& App::getInstance();
617   
618        if (!$this->isLoggedIn()) {
619            // Display message for requiring login. (RaiseMsg will ignore empty strings.)
620            if ('' != $message) {
621                $app->raiseMsg($message, $type, $file, $line);
622            }
623
624            // Login scripts must have the same 'login' tag for boomerangURL verification/manipulation.
625            $app->setBoomerangURL(absoluteMe(), 'login');
626            $app->dieURL($this->_params['login_url']);
627        }
628    }
629
630    /**
631     * This sets the 'blocked' field for a user in the db_table, and also
632     * adds an optional reason
633     *
634     * @param  string   $reason      The reason for blocking the account.
635     */
636    function blockAccount($user_id=null, $reason='')
637    {
638        $app =& App::getInstance();
639        $db =& DB::getInstance();
640   
641        $this->initDB();
642
643        if ($this->getParam('blocking')) {
644            if (mb_strlen($db->escapeString($reason)) > 255) {
645                // blocked_reason field is varchar(255).
646                $app->logMsg(sprintf('Blocked reason provided is greater than 255 characters: %s', $reason), LOG_WARNING, __FILE__, __LINE__);
647            }
648
649            // Get user_id if specified.
650            $user_id = isset($user_id) ? $user_id : $this->get('user_id');
651            $db->query("
652                UPDATE " . $this->_params['db_table'] . " SET
653                blocked = 'true',
654                blocked_reason = '" . $db->escapeString($reason) . "'
655                WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
656            ");
657        }
658    }
659
660    /**
661     * Tests if the "blocked" flag is set for a user.
662     *
663     * @param  int      $user_id    User id to look for.
664     * @return boolean              True if the user is blocked, false otherwise.
665     */
666    function isBlocked($user_id=null)
667    {
668        $db =& DB::getInstance();
669
670        $this->initDB();
671
672        if ($this->getParam('blocking')) {
673            // Get user_id if specified.
674            $user_id = isset($user_id) ? $user_id : $this->getVal('user_id');
675            $qid = $db->query("
676                SELECT 1
677                FROM " . $this->_params['db_table'] . "
678                WHERE blocked = 'true'
679                AND " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
680            ");
681            return mysql_num_rows($qid) === 1;
682        }
683    }
684
685    /**
686     * Unblocks a user in the db_table, and clears any blocked_reason.
687     */
688    function unblockAccount($user_id=null)
689    {
690        $db =& DB::getInstance();
691   
692        $this->initDB();
693   
694        if ($this->getParam('blocking')) {
695            // Get user_id if specified.
696            $user_id = isset($user_id) ? $user_id : $this->get('user_id');
697            $db->query("
698                UPDATE " . $this->_params['db_table'] . " SET
699                blocked = '',
700                blocked_reason = ''
701                WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
702            ");
703        }
704    }
705
706    /**
707     * Returns true if username already exists in database.
708     *
709     * @param  string  $username    Username to look for.
710     * @return bool                 True if username exists.
711     */
712    function usernameExists($username)
713    {
714        $db =& DB::getInstance();
715   
716        $this->initDB();
717
718        $qid = $db->query("
719            SELECT 1
720            FROM " . $this->_params['db_table'] . "
721            WHERE " . $this->_params['db_username_column'] . " = '" . $db->escapeString($username) . "'
722        ");
723        return (mysql_num_rows($qid) > 0);
724    }
725
726    /**
727     * Returns a username for a specified user id.
728     *
729     * @param  string  $user_id     User id to look for.
730     * @return string               Username, or false if none found.
731     */
732    function getUsername($user_id)
733    {
734        $db =& DB::getInstance();
735   
736        $this->initDB();
737
738        $qid = $db->query("
739            SELECT " . $this->_params['db_username_column'] . "
740            FROM " . $this->_params['db_table'] . "
741            WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
742        ");
743        if (list($username) = mysql_fetch_row($qid)) {
744            return $username;
745        } else {
746            return false;
747        }
748    }
749
750    /**
751     * Returns a randomly generated password based on $pattern. The pattern is any
752     * sequence of 'x', 'V', 'C', 'v', 'c', or 'd' and if it is something like 'cvccv' this
753     * function will generate a pronouncable password. Recommend using more complex
754     * patterns, at minimum the US State Department standard: cvcddcvc.
755     *
756     * - x    a random upper or lower alpha character or digit
757     * - C    a random upper or lower consanant
758     * - V    a random upper or lower vowel
759     * - c    a random lowercase consanant
760     * - v    a random lowercase vowel
761     * - d    a random digit
762     *
763     * @param  string $pattern  a sequence of character types, above.
764     * @return string           a password
765     */
766    function generatePassword($pattern='CvcdCvc')
767    {
768        $app =& App::getInstance();
769        if (preg_match('/[^xCVcvd]/', $pattern)) {
770            $app->logMsg(sprintf('Invalid pattern: %s', $pattern), LOG_WARNING, __FILE__, __LINE__);
771            $pattern='CvcdCvc';
772        }
773        $str = '';
774        for ($i=0; $i<mb_strlen($pattern); $i++) {
775            $x = mb_substr('bcdfghjklmnprstvwxzBCDFGHJKLMNPRSTVWXZaeiouyAEIOUY0123456789!@#%&*-=+.?', (mt_rand() % 71), 1);
776            $c = mb_substr('bcdfghjklmnprstvwxz', (mt_rand() % 19), 1);
777            $C = mb_substr('bcdfghjklmnprstvwxzBCDFGHJKLMNPRSTVWXZ', (mt_rand() % 38), 1);
778            $v = mb_substr('aeiouy', (mt_rand() % 6), 1);
779            $V = mb_substr('aeiouyAEIOUY', (mt_rand() % 12), 1);
780            $d = mb_substr('0123456789', (mt_rand() % 10), 1);
781            $str .= $$pattern[$i];
782        }
783        return $str;
784    }
785
786    /**
787     *
788     */
789    function encryptPassword($password, $salt=null)
790    {
791        $app =& App::getInstance();
792       
793        // Existing password hashes rely on the same key/salt being used to compare encryptions.
794        // Don't change this unless you know existing hashes or signatures will not be affected!
795        $more_salt = 'B36D18E5-3FE4-4D58-8150-F26642852B81';
796       
797        switch ($this->_params['encryption_type']) {
798        case AUTH_ENCRYPT_PLAINTEXT :
799            return $password;
800            break;
801
802        case AUTH_ENCRYPT_CRYPT :
803            // If comparing plaintext password with a hash, provide first two chars of the hash as the salt.
804            return isset($salt) ? crypt($password, mb_substr($salt, 0, 2)) : crypt($password);
805            break;
806
807        case AUTH_ENCRYPT_SHA1 :
808            return sha1($password);
809            break;
810
811        case AUTH_ENCRYPT_SHA1_HARDENED :
812            $hash = sha1($app->getParam('signing_key') . $password . $more_salt);
813            // Increase key strength by 12 bits.
814            for ($i=0; $i < 4096; $i++) { 
815                $hash = sha1($hash); 
816            } 
817            return $hash;
818            break;
819
820        case AUTH_ENCRYPT_MD5 :
821            return md5($password);
822            break;
823
824        case AUTH_ENCRYPT_MD5_HARDENED :
825            // Include salt to improve hash
826            $hash = md5($app->getParam('signing_key') . $password . $more_salt);
827            // Increase key strength by 12 bits.
828            for ($i=0; $i < 4096; $i++) { 
829                $hash = md5($hash); 
830            } 
831            return $hash;
832            break;
833        default :
834            $app->logMsg(sprintf('Authentication encrypt type specified is unrecognized: %s', $this->_params['encryption_type']), LOG_NOTICE, __FILE__, __LINE__);
835            return false;
836            break;
837        }
838    }
839
840    /**
841     *
842     */
843    function setPassword($user_id=null, $password)
844    {
845        $app =& App::getInstance();
846        $db =& DB::getInstance();
847   
848        $this->initDB();
849
850        // Get user_id if specified.
851        $user_id = isset($user_id) ? $user_id : $this->get('user_id');
852
853        // Get old password.
854        $qid = $db->query("
855            SELECT userpass
856            FROM " . $this->_params['db_table'] . "
857            WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
858        ");
859        if (!list($old_encrypted_password) = mysql_fetch_row($qid)) {
860            $app->logMsg(sprintf('Cannot set password for nonexistant user_id %s', $user_id), LOG_NOTICE, __FILE__, __LINE__);
861            return false;
862        }
863       
864        // Compare old with new to ensure we're actually *changing* the password.
865        $encrypted_password = $this->encryptPassword($password);
866        if ($old_encrypted_password == $encrypted_password) {
867            $app->logMsg(sprintf('Not setting password: new is the same as old.', null), LOG_INFO, __FILE__, __LINE__);
868            return false;
869        }
870
871        // Issue the password change query.
872        $db->query("
873            UPDATE " . $this->_params['db_table'] . "
874            SET userpass = '" . $db->escapeString($encrypted_password) . "'
875            WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
876        ");
877       
878        if (mysql_affected_rows($db->getDBH()) != 1) {
879            $app->logMsg(sprintf('Failed to update password for user %s', $user_id), LOG_WARNING, __FILE__, __LINE__);
880            return false;
881        }
882       
883        return true;
884    }
885
886    /**
887     * Resets the password for the user with the specified id.
888     *
889     * @param  string $user_id   The id of the user to reset.
890     * @param  string $reason    Additional message to add to the reset email.
891     * @return string            The user's new password.
892     */
893    function resetPassword($user_id=null, $reason='')
894    {
895        $app =& App::getInstance();
896        $db =& DB::getInstance();
897   
898        $this->initDB();
899
900        // Get user_id if specified.
901        $user_id = isset($user_id) ? $user_id : $this->get('user_id');
902
903        // Reset password of a specific user.
904        $qid = $db->query("
905            SELECT * FROM " . $this->_params['db_table'] . "
906            WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
907        ");
908        if (!$user_data = mysql_fetch_assoc($qid)) {
909            $app->logMsg(sprintf('Reset password failed. User %s not found.', $user_id), LOG_NOTICE, __FILE__, __LINE__);
910            return false;
911        }
912
913        // Get new password.
914        $password = $this->generatePassword();
915
916        // Update password query.
917        $this->setPassword($user_id, $password);
918
919        // Make sure user has an email on record before continuing.
920        if (!isset($user_data['email']) || '' == trim($user_data['email'])) {
921            $app->logMsg(sprintf('Password reset but notification failed, no email address for user %s (%s).', $user_data[$this->_params['db_primary_key']], $user_data[$this->_params['db_username_column']]), LOG_NOTICE, __FILE__, __LINE__);
922        } else {
923            // Send the new password in an email.
924            $email = new Email(array(
925                'to' => $user_data['email'],
926                'from' => sprintf('%s <%s>', $app->getParam('site_name'), $app->getParam('site_email')),
927                'subject' => sprintf('%s password change', $app->getParam('site_name'))
928            ));
929            $email->setTemplate('codebase/services/templates/email_reset_password.txt');
930            $email->replace(array(
931                'SITE_NAME' => $app->getParam('site_name'),
932                'SITE_URL' => $app->getParam('site_url'),
933                'SITE_EMAIL' => $app->getParam('site_email'),
934                'NAME' => ('' != $user_data['first_name'] . $user_data['last_name'] ? $user_data['first_name'] . ' ' . $user_data['last_name'] : $user_data[$this->_params['db_username_column']]),
935                'USERNAME' => $user_data[$this->_params['db_username_column']],
936                'PASSWORD' => $password,
937                'REASON' => ('' == trim($reason) ? '' : trim($reason) . ' '), // Add a space after the reason if it exists for better fromatting.
938            ));
939            $email->send();
940        }
941
942        return array(
943            'username' => $user_data[$this->_params['db_username_column']],
944            'userpass' => $password
945        );
946    }
947
948    /**
949     * If the current user has access to the specified $security_zone, return true.
950     * If the optional $user_type is supplied, test that against the zone.
951     *
952     * NOTE: "user_type" used to be called "priv" in some older implementations.
953     *
954     * @param  constant $security_zone   string of comma delimited priviliges for the zone
955     * @param  string   $user_type       a privilege that might be found in a zone
956     * @return bool     true if user is a member of security zone, false otherwise
957     */
958    function inClearanceZone($security_zone, $user_type='')
959    {
960        return true;
961        $zone_members = preg_split('/,\s*/', $security_zone);
962        $user_type = empty($user_type) ? $this->get('user_type') : $user_type;
963
964        // If the current user's privilege level is NOT in that array or if the
965        // user has no privilege, return false. Otherwise the user is clear.
966        if (!in_array($user_type, $zone_members) || empty($user_type)) {
967            return false;
968        } else {
969            return true;
970        }
971    }
972
973    /**
974     * This function tests a list of arguments $security_zone against the priv that the current user has.
975     * If the user doesn't have one of the supplied privs, die.
976     *
977     * NOTE: "user_type" used to be called "priv" in some older implementations.
978     *
979     * @param  constant $security_zone   string of comma delimited priviliges for the zone
980     */
981    function requireAccessClearance($security_zone, $message='')
982    {
983        $app =& App::getInstance();
984   
985        return true;
986        $zone_members = preg_split('/,\s*/', $security_zone);
987
988        /* If the current user's privilege level is NOT in that array or if the
989         * user has no privilege, DIE with a message. */
990        if (!in_array($this->get('user_type'), $zone_members) || !$this->get('user_type')) {
991            $message = empty($message) ? _("You have insufficient privileges to view that page.") : $message;
992            $app->raiseMsg($message, MSG_NOTICE, __FILE__, __LINE__);
993            $app->dieBoomerangURL();
994        }
995    }
996
997} // end class
998
999// CIDR cheat-sheet
1000//
1001// Netmask              Netmask (binary)                 CIDR     Notes
1002// _____________________________________________________________________________
1003// 255.255.255.255  11111111.11111111.11111111.11111111  /32  Host (single addr)
1004// 255.255.255.254  11111111.11111111.11111111.11111110  /31  Unusable
1005// 255.255.255.252  11111111.11111111.11111111.11111100  /30    2  useable
1006// 255.255.255.248  11111111.11111111.11111111.11111000  /29    6  useable
1007// 255.255.255.240  11111111.11111111.11111111.11110000  /28   14  useable
1008// 255.255.255.224  11111111.11111111.11111111.11100000  /27   30  useable
1009// 255.255.255.192  11111111.11111111.11111111.11000000  /26   62  useable
1010// 255.255.255.128  11111111.11111111.11111111.10000000  /25  126  useable
1011// 255.255.255.0    11111111.11111111.11111111.00000000  /24 "Class C" 254 useable
1012//
1013// 255.255.254.0    11111111.11111111.11111110.00000000  /23    2  Class C's
1014// 255.255.252.0    11111111.11111111.11111100.00000000  /22    4  Class C's
1015// 255.255.248.0    11111111.11111111.11111000.00000000  /21    8  Class C's
1016// 255.255.240.0    11111111.11111111.11110000.00000000  /20   16  Class C's
1017// 255.255.224.0    11111111.11111111.11100000.00000000  /19   32  Class C's
1018// 255.255.192.0    11111111.11111111.11000000.00000000  /18   64  Class C's
1019// 255.255.128.0    11111111.11111111.10000000.00000000  /17  128  Class C's
1020// 255.255.0.0      11111111.11111111.00000000.00000000  /16  "Class B"
1021//
1022// 255.254.0.0      11111111.11111110.00000000.00000000  /15    2  Class B's
1023// 255.252.0.0      11111111.11111100.00000000.00000000  /14    4  Class B's
1024// 255.248.0.0      11111111.11111000.00000000.00000000  /13    8  Class B's
1025// 255.240.0.0      11111111.11110000.00000000.00000000  /12   16  Class B's
1026// 255.224.0.0      11111111.11100000.00000000.00000000  /11   32  Class B's
1027// 255.192.0.0      11111111.11000000.00000000.00000000  /10   64  Class B's
1028// 255.128.0.0      11111111.10000000.00000000.00000000  /9   128  Class B's
1029// 255.0.0.0        11111111.00000000.00000000.00000000  /8   "Class A"
1030//
1031// 254.0.0.0        11111110.00000000.00000000.00000000  /7
1032// 252.0.0.0        11111100.00000000.00000000.00000000  /6
1033// 248.0.0.0        11111000.00000000.00000000.00000000  /5
1034// 240.0.0.0        11110000.00000000.00000000.00000000  /4
1035// 224.0.0.0        11100000.00000000.00000000.00000000  /3
1036// 192.0.0.0        11000000.00000000.00000000.00000000  /2
1037// 128.0.0.0        10000000.00000000.00000000.00000000  /1
1038// 0.0.0.0          00000000.00000000.00000000.00000000  /0   IP space
1039?>
Note: See TracBrowser for help on using the repository browser.