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

Last change on this file since 371 was 371, checked in by quinn, 14 years ago

Minor update.

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