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

Last change on this file since 201 was 201, checked in by scdev, 18 years ago

Q - increased some LOG_DEBUG messages to LOG_INFO so we can run with debugging off and still get the important ones.

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