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

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

Q - while we're changing interfaces I'm going to change ->clearAuth() to ->clear().

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