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

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

Setting usernames in whitelists to lowercase to ensure match.

File size: 47.5 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        // Register authenticated session.
415        $_SESSION['_auth_sql'][$this->_ns] = array(
416            'authenticated'         => true,
417            'user_id'               => $user_data['user_id'],
418            'username'              => $username,
419            'login_datetime'        => date('Y-m-d H:i:s'),
420            'last_access_datetime'  => date('Y-m-d H:i:s'),
421            'remote_ip'             => getRemoteAddr(),
422            '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']),
423            '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']),
424            'user_data'             => $user_data
425        );
426
427        /**
428         * Check if the account is blocked, respond in context to reason. Cancel the login if blocked.
429         */
430        if ($this->getParam('blocking')) {
431            if (!empty($user_data['blocked'])) {
432
433                $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__);
434
435                switch ($user_data['blocked_reason']) {
436                    case 'account abuse' :
437                        $app->raiseMsg(sprintf(_("This account has been blocked due to possible account abuse. Please contact us to reactivate."), null), MSG_WARNING, __FILE__, __LINE__);
438                        break;
439                    default :
440                        $app->raiseMsg(sprintf(_("This account is currently not active. %s"), $user_data['blocked_reason']), MSG_WARNING, __FILE__, __LINE__);
441                        break;
442                }
443
444                // No login: user is blocked!
445                $this->clear();
446                return false;
447            }
448        }
449
450        /**
451         * Check the db_login_table for too many logins under this account.
452         * (1) Count the number of unique IP addresses that logged in under this user within the login_abuse_timeframe
453         * (2) If this number exceeds the login_abuse_max_ips, assume multiple people are logging in under the same account.
454        **/
455        if ($this->getParam('abuse_detection') && !$this->get('login_abuse_exempt')) {
456            $qid = $db->query("
457                SELECT COUNT(DISTINCT LEFT(remote_ip_binary, " . $this->_params['login_abuse_ip_bitmask'] . "))
458                FROM " . $this->_params['db_login_table'] . "
459                WHERE " . $this->_params['db_primary_key'] . " = '" . $this->get('user_id') . "'
460                AND DATE_ADD(login_datetime, INTERVAL '" . $this->_params['login_abuse_timeframe'] . "' DAY_HOUR) > NOW()
461            ");
462            list($distinct_ips) = mysql_fetch_row($qid);
463            if ($distinct_ips > $this->_params['login_abuse_max_ips']) {
464                if ($this->get('abuse_warning_level') < $this->_params['login_abuse_warnings']) {
465                    // Warn the user with a password reset.
466                    $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."));
467                    $app->raiseMsg(_("Your password has been reset as a security precaution. Please check your email for more information."), MSG_NOTICE, __FILE__, __LINE__);
468                    $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__);
469                } else {
470                    // Block the account with the reason of account abuse.
471                    $this->blockAccount(null, 'account abuse');
472                    $app->raiseMsg(_("Your account has been blocked as a security precaution. Please contact us for more information."), MSG_NOTICE, __FILE__, __LINE__);
473                    $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__);
474                }
475                // Increment user's warning level.
476                $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') . "'");
477                // Reset the login counter for this user.
478                $db->query("DELETE FROM " . $this->_params['db_login_table'] . " WHERE " . $this->_params['db_primary_key'] . " = '" . $this->get('user_id') . "'");
479                // No login: reset password because of account abuse!
480                $this->clear();
481                return false;
482            }
483
484            // Update the login counter table with this login access. Convert IP to binary.
485            // TODO: after MySQL 5.0.23 is released this query could benefit from INSERT DELAYED.
486            $db->query("
487                INSERT INTO " . $this->_params['db_login_table'] . " (
488                    " . $this->_params['db_primary_key'] . ",
489                    login_datetime,
490                    remote_ip_binary
491                ) VALUES (
492                    '" . $this->get('user_id') . "',
493                    '" . $this->get('login_datetime') . "',
494                    '" . sprintf('%032b', ip2long($this->get('remote_ip'))) . "'
495                )
496            ");
497        }
498
499        // Update user table with this login.
500        $db->query("
501            UPDATE " . $this->_params['db_table'] . " SET
502                last_login_datetime = '" . $this->get('login_datetime') . "',
503                last_access_datetime = '" . $this->get('login_datetime') . "',
504                last_login_ip = '" . $this->get('remote_ip') . "'
505            WHERE " . $this->_params['db_primary_key'] . " = '" . $this->get('user_id') . "'
506        ");
507
508        // We're logged-in!
509        return true;
510    }
511
512    /**
513     * Test if user has a currently logged-in session.
514     *  - authentication flag set to true
515     *  - username not empty
516     *  - total logged-in time is not greater than login_timeout
517     *  - idle time is not greater than idle_timeout
518     *  - remote address is the same as the login remote address (aol users excluded).
519     *
520     * @access public
521     */
522    function isLoggedIn($user_id=null)
523    {
524        $app =& App::getInstance();
525        $db =& DB::getInstance();
526   
527        $this->initDB();
528
529        if (isset($user_id)) {
530            // Check the login status of a specific user.
531            $qid = $db->query("
532                SELECT 1 FROM " . $this->_params['db_table'] . "
533                WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
534                AND DATE_ADD(last_login_datetime, INTERVAL '" . $this->_params['login_timeout'] . "' SECOND) > NOW()
535                AND DATE_ADD(last_access_datetime, INTERVAL '" . $this->_params['idle_timeout'] . "' SECOND) > NOW()
536            ");
537            return (mysql_num_rows($qid) > 0);
538        }
539
540        // User login test need only be run once per script execution. We cache the result in the session.
541        if ($this->_authentication_tested && isset($_SESSION['_auth_sql'][$this->_ns]['authenticated'])) {
542            return $_SESSION['_auth_sql'][$this->_ns]['authenticated'];
543        }
544
545        // Tesing login should occur once. This is the first time. Set flag.
546        $this->_authentication_tested = true;
547
548        // 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.
549        if ($trusted_net = ipInRange(getRemoteAddr(), $this->_params['trusted_networks'])) {
550            $user_in_trusted_network = true;
551            $app->logMsg(sprintf('User %s accessing from trusted network %s',
552                ($this->get('user_id') ? ' ' . $this->get('user_id') . ' (' .  $this->get('username') . ')' : ''),
553                $trusted_net
554            ), LOG_DEBUG, __FILE__, __LINE__);
555        } else if (preg_match('/proxy.aol.com$/i', getRemoteAddr(true))) {
556            $user_in_trusted_network = true;
557            $app->logMsg(sprintf('User %s accessing from trusted network proxy.aol.com',
558                ($this->get('user_id') ? ' ' . $this->get('user_id') . ' (' .  $this->get('username') . ')' : '')
559            ), LOG_DEBUG, __FILE__, __LINE__);
560        } else {
561            $user_in_trusted_network = false;
562        }
563       
564        // Do we match the user's remote IP at all? Yes, if set in config and not disabled for specific user.
565        if ($this->getParam('match_remote_ip') && !$this->get('match_remote_ip_exempt')) {
566            $remote_ip_is_matched = (isset($_SESSION['_auth_sql'][$this->_ns]['remote_ip']) && $_SESSION['_auth_sql'][$this->_ns]['remote_ip'] == getRemoteAddr()) || $user_in_trusted_network;
567        } else {
568            $app->logMsg(sprintf('User %s exempt from remote_ip match (comparing %s == %s)', 
569                ($this->get('user_id') ? ' ' . $this->get('user_id') . ' (' .  $this->get('username') . ')' : ''),
570                $_SESSION['_auth_sql'][$this->_ns]['remote_ip'],
571                getRemoteAddr()
572            ), LOG_DEBUG, __FILE__, __LINE__);
573            $remote_ip_is_matched = true;
574        }
575
576        // Test login with information stored in session. Skip IP matching for users from trusted networks.
577        if (isset($_SESSION['_auth_sql'][$this->_ns]['authenticated']) 
578            && true === $_SESSION['_auth_sql'][$this->_ns]['authenticated']
579            && !empty($_SESSION['_auth_sql'][$this->_ns]['username'])
580            && strtotime($_SESSION['_auth_sql'][$this->_ns]['login_datetime']) > time() - $this->_params['login_timeout']
581            && strtotime($_SESSION['_auth_sql'][$this->_ns]['last_access_datetime']) > time() - $this->_params['idle_timeout']
582            && $remote_ip_is_matched
583        ) {
584            // User is authenticated!
585            $_SESSION['_auth_sql'][$this->_ns]['last_access_datetime'] = date('Y-m-d H:i:s');
586
587            // Update the DB with the last_access_datetime and increment the seconds_online.
588            $db->query("
589                UPDATE " . $this->_params['db_table'] . " SET
590                seconds_online = seconds_online + (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_access_datetime)) + 1,
591                last_access_datetime = '" . $this->get('last_access_datetime') . "'
592                WHERE " . $this->_params['db_primary_key'] . " = '" . $this->get('user_id') . "'
593            ");
594            if (mysql_affected_rows($db->getDBH()) > 0) {
595                // 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.
596                return true;
597            } else {
598                $app->logMsg(sprintf('User update failed. Record not found for user %s (%s).', $this->get('user_id'), $this->get('username')), LOG_NOTICE, __FILE__, __LINE__);
599            }
600        } else if (isset($_SESSION['_auth_sql'][$this->_ns]['authenticated']) && true === $_SESSION['_auth_sql'][$this->_ns]['authenticated']) {
601            // User is authenticated, but login has expired.
602            if (strtotime($_SESSION['_auth_sql'][$this->_ns]['last_access_datetime']) > time() - 43200) {
603                // Only raise message if last session is less than 12 hours old.
604                $app->raiseMsg(_("Your session has expired. You need to log-in again."), MSG_NOTICE, __FILE__, __LINE__);
605            }
606
607            // Log the reason for login expiration.
608            $expire_reasons = array();
609            if (empty($_SESSION['_auth_sql'][$this->_ns]['username'])) {
610                $expire_reasons[] = 'username not found';
611            }
612            if (strtotime($_SESSION['_auth_sql'][$this->_ns]['login_datetime']) <= time() - $this->_params['login_timeout']) {
613                $expire_reasons[] = 'login_timeout expired';
614            }
615            if (strtotime($_SESSION['_auth_sql'][$this->_ns]['last_access_datetime']) <= time() - $this->_params['idle_timeout']) {
616                $expire_reasons[] = 'idle_timeout expired';
617            }
618            if ($_SESSION['_auth_sql'][$this->_ns]['remote_ip'] != getRemoteAddr() && !$user_in_trusted_network) {
619                if ($this->getParam('match_remote_ip') && !$this->get('match_remote_ip_exempt')) {
620                    $expire_reasons[] = sprintf('remote_ip not matched (%s != %s)', $_SESSION['_auth_sql'][$this->_ns]['remote_ip'], getRemoteAddr());
621                } else {
622                    $expire_reasons[] = sprintf('remote_ip not matched but user was exempt from this check (%s != %s)', $_SESSION['_auth_sql'][$this->_ns]['remote_ip'], getRemoteAddr());
623                }
624            }
625            $app->logMsg(sprintf('User %s (%s) session expired: %s', $this->get('user_id'), $this->get('username'), join(', ', $expire_reasons)), LOG_INFO, __FILE__, __LINE__);
626        }
627
628        // User is not authenticated.
629        $this->clear();
630        return false;
631    }
632
633    /**
634     * Redirect user to login page if they are not logged in.
635     *
636     * @param string $message The text description of a message to raise.
637     * @param int    $type    The type of message: MSG_NOTICE,
638     *                        MSG_SUCCESS, MSG_WARNING, or MSG_ERR.
639     * @param string $file    __FILE__.
640     * @param string $line    __LINE__.
641     * @access public
642     */
643    function requireLogin($message='', $type=MSG_NOTICE, $file=null, $line=null)
644    {
645        $app =& App::getInstance();
646   
647        if (!$this->isLoggedIn()) {
648            // Display message for requiring login. (RaiseMsg will ignore empty strings.)
649            if ('' != $message) {
650                $app->raiseMsg($message, $type, $file, $line);
651            }
652
653            // Login scripts must have the same 'login' tag for boomerangURL verification/manipulation.
654            $app->setBoomerangURL(absoluteMe(), 'login');
655            $app->dieURL($this->_params['login_url']);
656        }
657    }
658
659    /**
660     * This sets the 'blocked' field for a user in the db_table, and also
661     * adds an optional reason
662     *
663     * @param  string   $reason      The reason for blocking the account.
664     */
665    function blockAccount($user_id=null, $reason='')
666    {
667        $app =& App::getInstance();
668        $db =& DB::getInstance();
669   
670        $this->initDB();
671
672        if ($this->getParam('blocking')) {
673            if (mb_strlen($db->escapeString($reason)) > 255) {
674                // blocked_reason field is varchar(255).
675                $app->logMsg(sprintf('Blocked reason provided is greater than 255 characters: %s', $reason), LOG_WARNING, __FILE__, __LINE__);
676            }
677
678            // Get user_id if specified.
679            $user_id = isset($user_id) ? $user_id : $this->get('user_id');
680            $db->query("
681                UPDATE " . $this->_params['db_table'] . " SET
682                blocked = 'true',
683                blocked_reason = '" . $db->escapeString($reason) . "'
684                WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
685            ");
686        }
687    }
688
689    /**
690     * Tests if the "blocked" flag is set for a user.
691     *
692     * @param  int      $user_id    User id to look for.
693     * @return boolean              True if the user is blocked, false otherwise.
694     */
695    function isBlocked($user_id=null)
696    {
697        $db =& DB::getInstance();
698
699        $this->initDB();
700
701        if ($this->getParam('blocking')) {
702            // Get user_id if specified.
703            $user_id = isset($user_id) ? $user_id : $this->getVal('user_id');
704            $qid = $db->query("
705                SELECT 1
706                FROM " . $this->_params['db_table'] . "
707                WHERE blocked = 'true'
708                AND " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
709            ");
710            return mysql_num_rows($qid) === 1;
711        }
712    }
713
714    /**
715     * Unblocks a user in the db_table, and clears any blocked_reason.
716     */
717    function unblockAccount($user_id=null)
718    {
719        $db =& DB::getInstance();
720   
721        $this->initDB();
722   
723        if ($this->getParam('blocking')) {
724            // Get user_id if specified.
725            $user_id = isset($user_id) ? $user_id : $this->get('user_id');
726            $db->query("
727                UPDATE " . $this->_params['db_table'] . " SET
728                blocked = '',
729                blocked_reason = ''
730                WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
731            ");
732        }
733    }
734
735    /**
736     * Returns true if username already exists in database.
737     *
738     * @param  string  $username    Username to look for.
739     * @return bool                 True if username exists.
740     */
741    function usernameExists($username)
742    {
743        $db =& DB::getInstance();
744   
745        $this->initDB();
746
747        $qid = $db->query("
748            SELECT 1
749            FROM " . $this->_params['db_table'] . "
750            WHERE " . $this->_params['db_username_column'] . " = '" . $db->escapeString($username) . "'
751        ");
752        return (mysql_num_rows($qid) > 0);
753    }
754
755    /**
756     * Returns a username for a specified user id.
757     *
758     * @param  string  $user_id     User id to look for.
759     * @return string               Username, or false if none found.
760     */
761    function getUsername($user_id)
762    {
763        $db =& DB::getInstance();
764   
765        $this->initDB();
766
767        $qid = $db->query("
768            SELECT " . $this->_params['db_username_column'] . "
769            FROM " . $this->_params['db_table'] . "
770            WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
771        ");
772        if (list($username) = mysql_fetch_row($qid)) {
773            return $username;
774        } else {
775            return false;
776        }
777    }
778
779    /**
780     * Returns a randomly generated password based on $pattern. The pattern is any
781     * sequence of 'x', 'V', 'C', 'v', 'c', or 'd' and if it is something like 'cvccv' this
782     * function will generate a pronounceable password. Recommend using more complex
783     * patterns, at minimum the US State Department standard: cvcddcvc.
784     *
785     * - x    a random upper or lower alpha character or digit
786     * - C    a random upper or lower consonant
787     * - V    a random upper or lower vowel
788     * - c    a random lowercase consonant
789     * - v    a random lowercase vowel
790     * - d    a random digit
791     *
792     * @param  string $pattern  a sequence of character types, above.
793     * @return string           a password
794     */
795    function generatePassword($pattern='CvcdCvc')
796    {
797        $app =& App::getInstance();
798        if (preg_match('/[^xCVcvd]/', $pattern)) {
799            $app->logMsg(sprintf('Invalid pattern: %s', $pattern), LOG_WARNING, __FILE__, __LINE__);
800            $pattern='CvcdCvc';
801        }
802        $str = '';
803        for ($i=0; $i<mb_strlen($pattern); $i++) {
804            $x = mb_substr('bcdfghjklmnprstvwxzBCDFGHJKLMNPRSTVWXZaeiouyAEIOUY0123456789!@#%&*-=+.?', (mt_rand() % 71), 1);
805            $c = mb_substr('bcdfghjklmnprstvwxz', (mt_rand() % 19), 1);
806            $C = mb_substr('bcdfghjklmnprstvwxzBCDFGHJKLMNPRSTVWXZ', (mt_rand() % 38), 1);
807            $v = mb_substr('aeiouy', (mt_rand() % 6), 1);
808            $V = mb_substr('aeiouyAEIOUY', (mt_rand() % 12), 1);
809            $d = mb_substr('0123456789', (mt_rand() % 10), 1);
810            $str .= $$pattern[$i];
811        }
812        return $str;
813    }
814
815    /**
816     *
817     */
818    function encryptPassword($password, $salt=null)
819    {
820        $app =& App::getInstance();
821       
822        // Existing password hashes rely on the same key/salt being used to compare encryptions.
823        // Don't change this (or the value applied to signing_key) unless you know existing hashes or signatures will not be affected!
824        $more_salt = 'B36D18E5-3FE4-4D58-8150-F26642852B81';
825       
826        switch ($this->_params['encryption_type']) {
827        case AUTH_ENCRYPT_PLAINTEXT :
828            return $password;
829            break;
830
831        case AUTH_ENCRYPT_CRYPT :
832            // If comparing plaintext password with a hash, provide first two chars of the hash as the salt.
833            return isset($salt) ? crypt($password, mb_substr($salt, 0, 2)) : crypt($password);
834            break;
835
836        case AUTH_ENCRYPT_SHA1 :
837            return sha1($password);
838            break;
839
840        case AUTH_ENCRYPT_SHA1_HARDENED :
841            $hash = sha1($app->getParam('signing_key') . $password . $more_salt);
842            // Increase key strength by 12 bits.
843            for ($i=0; $i < 4096; $i++) { 
844                $hash = sha1($hash); 
845            } 
846            return $hash;
847            break;
848
849        case AUTH_ENCRYPT_MD5 :
850            return md5($password);
851            break;
852
853        case AUTH_ENCRYPT_MD5_HARDENED :
854            // Include salt to improve hash
855            $hash = md5($app->getParam('signing_key') . $password . $more_salt);
856            // Increase key strength by 12 bits.
857            for ($i=0; $i < 4096; $i++) { 
858                $hash = md5($hash); 
859            } 
860            return $hash;
861            break;
862        default :
863            $app->logMsg(sprintf('Authentication encrypt type specified is unrecognized: %s', $this->_params['encryption_type']), LOG_NOTICE, __FILE__, __LINE__);
864            return false;
865            break;
866        }
867    }
868
869    /**
870     *
871     */
872    function setPassword($user_id=null, $password)
873    {
874        $app =& App::getInstance();
875        $db =& DB::getInstance();
876   
877        $this->initDB();
878
879        // Get user_id if specified.
880        $user_id = isset($user_id) ? $user_id : $this->get('user_id');
881
882        // Get old password.
883        $qid = $db->query("
884            SELECT userpass
885            FROM " . $this->_params['db_table'] . "
886            WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
887        ");
888        if (!list($old_encrypted_password) = mysql_fetch_row($qid)) {
889            $app->logMsg(sprintf('Cannot set password for nonexistent user_id %s', $user_id), LOG_NOTICE, __FILE__, __LINE__);
890            return false;
891        }
892       
893        // Compare old with new to ensure we're actually *changing* the password.
894        $encrypted_password = $this->encryptPassword($password);
895        if ($old_encrypted_password == $encrypted_password) {
896            $app->logMsg(sprintf('Not setting password: new is the same as old.', null), LOG_INFO, __FILE__, __LINE__);
897            return false;
898        }
899
900        // Issue the password change query.
901        $db->query("
902            UPDATE " . $this->_params['db_table'] . "
903            SET userpass = '" . $db->escapeString($encrypted_password) . "'
904            WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
905        ");
906       
907        if (mysql_affected_rows($db->getDBH()) != 1) {
908            $app->logMsg(sprintf('Failed to update password for user %s', $user_id), LOG_WARNING, __FILE__, __LINE__);
909            return false;
910        }
911       
912        return true;
913    }
914
915    /**
916     * Resets the password for the user with the specified id.
917     *
918     * @param  string $user_id   The id of the user to reset.
919     * @param  string $reason    Additional message to add to the reset email.
920     * @return string            The user's new password.
921     */
922    function resetPassword($user_id=null, $reason='')
923    {
924        $app =& App::getInstance();
925        $db =& DB::getInstance();
926   
927        $this->initDB();
928
929        // Get user_id if specified.
930        $user_id = isset($user_id) ? $user_id : $this->get('user_id');
931
932        // Reset password of a specific user.
933        $qid = $db->query("
934            SELECT * FROM " . $this->_params['db_table'] . "
935            WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
936        ");
937        if (!$user_data = mysql_fetch_assoc($qid)) {
938            $app->logMsg(sprintf('Reset password failed. User %s not found.', $user_id), LOG_NOTICE, __FILE__, __LINE__);
939            return false;
940        }
941
942        // Get new password.
943        $password = $this->generatePassword();
944
945        // Update password query.
946        $this->setPassword($user_id, $password);
947
948        // Make sure user has an email on record before continuing.
949        if (!isset($user_data['email']) || '' == trim($user_data['email'])) {
950            $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__);
951        } else {
952            // Send the new password in an email.
953            $email = new Email(array(
954                'to' => $user_data['email'],
955                'from' => sprintf('%s <%s>', $app->getParam('site_name'), $app->getParam('site_email')),
956                'subject' => sprintf('%s password change', $app->getParam('site_name'))
957            ));
958            $email->setTemplate('codebase/services/templates/email_reset_password.txt');
959            $email->replace(array(
960                'SITE_NAME' => $app->getParam('site_name'),
961                'SITE_URL' => $app->getParam('site_url'),
962                'SITE_EMAIL' => $app->getParam('site_email'),
963                'NAME' => ('' != $user_data['first_name'] . $user_data['last_name'] ? $user_data['first_name'] . ' ' . $user_data['last_name'] : $user_data[$this->_params['db_username_column']]),
964                'USERNAME' => $user_data[$this->_params['db_username_column']],
965                'PASSWORD' => $password,
966                'REASON' => ('' == trim($reason) ? '' : trim($reason) . ' '), // Add a space after the reason if it exists for better formatting.
967            ));
968            $email->send();
969        }
970
971        return array(
972            'username' => $user_data[$this->_params['db_username_column']],
973            'userpass' => $password
974        );
975    }
976
977    /**
978     * If the current user has access to the specified $security_zone, return true.
979     * If the optional $user_type is supplied, test that against the zone.
980     *
981     * NOTE: "user_type" used to be called "priv" in some older implementations.
982     *
983     * @param  constant $security_zone   string of comma delimited privileges for the zone
984     * @param  string   $user_type       a privilege that might be found in a zone
985     * @return bool     true if user is a member of security zone, false otherwise
986     */
987    function inClearanceZone($security_zone, $user_type='')
988    {
989        // return true; /// WTF?
990        $zone_members = preg_split('/,\s*/', $security_zone);
991        $user_type = empty($user_type) ? $this->get('user_type') : $user_type;
992
993        // If the current user's privilege level is NOT in that array or if the
994        // user has no privilege, return false. Otherwise the user is clear.
995        if (!in_array($user_type, $zone_members) || empty($user_type)) {
996            return false;
997        } else {
998            return true;
999        }
1000    }
1001
1002    /**
1003     * This function tests a list of arguments $security_zone against the priv that the current user has.
1004     * If the user doesn't have one of the supplied privs, die.
1005     *
1006     * NOTE: "user_type" used to be called "priv" in some older implementations.
1007     *
1008     * @param  constant $security_zone   string of comma delimited privileges for the zone
1009     */
1010    function requireAccessClearance($security_zone, $message='')
1011    {
1012        $app =& App::getInstance();
1013   
1014        // return true; /// WTF?
1015        $zone_members = preg_split('/,\s*/', $security_zone);
1016
1017        /* If the current user's privilege level is NOT in that array or if the
1018         * user has no privilege, DIE with a message. */
1019        if (!in_array($this->get('user_type'), $zone_members) || !$this->get('user_type')) {
1020            $message = empty($message) ? _("You have insufficient privileges to view that page.") : $message;
1021            $app->raiseMsg($message, MSG_NOTICE, __FILE__, __LINE__);
1022            $app->dieBoomerangURL();
1023        }
1024    }
1025
1026} // end class
1027
1028// CIDR cheat-sheet
1029//
1030// Netmask              Netmask (binary)                 CIDR     Notes
1031// _____________________________________________________________________________
1032// 255.255.255.255  11111111.11111111.11111111.11111111  /32  Host (single addr)
1033// 255.255.255.254  11111111.11111111.11111111.11111110  /31  Unusable
1034// 255.255.255.252  11111111.11111111.11111111.11111100  /30    2  useable
1035// 255.255.255.248  11111111.11111111.11111111.11111000  /29    6  useable
1036// 255.255.255.240  11111111.11111111.11111111.11110000  /28   14  useable
1037// 255.255.255.224  11111111.11111111.11111111.11100000  /27   30  useable
1038// 255.255.255.192  11111111.11111111.11111111.11000000  /26   62  useable
1039// 255.255.255.128  11111111.11111111.11111111.10000000  /25  126  useable
1040// 255.255.255.0    11111111.11111111.11111111.00000000  /24 "Class C" 254 useable
1041//
1042// 255.255.254.0    11111111.11111111.11111110.00000000  /23    2  Class C's
1043// 255.255.252.0    11111111.11111111.11111100.00000000  /22    4  Class C's
1044// 255.255.248.0    11111111.11111111.11111000.00000000  /21    8  Class C's
1045// 255.255.240.0    11111111.11111111.11110000.00000000  /20   16  Class C's
1046// 255.255.224.0    11111111.11111111.11100000.00000000  /19   32  Class C's
1047// 255.255.192.0    11111111.11111111.11000000.00000000  /18   64  Class C's
1048// 255.255.128.0    11111111.11111111.10000000.00000000  /17  128  Class C's
1049// 255.255.0.0      11111111.11111111.00000000.00000000  /16  "Class B"
1050//
1051// 255.254.0.0      11111111.11111110.00000000.00000000  /15    2  Class B's
1052// 255.252.0.0      11111111.11111100.00000000.00000000  /14    4  Class B's
1053// 255.248.0.0      11111111.11111000.00000000.00000000  /13    8  Class B's
1054// 255.240.0.0      11111111.11110000.00000000.00000000  /12   16  Class B's
1055// 255.224.0.0      11111111.11100000.00000000.00000000  /11   32  Class B's
1056// 255.192.0.0      11111111.11000000.00000000.00000000  /10   64  Class B's
1057// 255.128.0.0      11111111.10000000.00000000.00000000  /9   128  Class B's
1058// 255.0.0.0        11111111.00000000.00000000.00000000  /8   "Class A"
1059//
1060// 254.0.0.0        11111110.00000000.00000000.00000000  /7
1061// 252.0.0.0        11111100.00000000.00000000.00000000  /6
1062// 248.0.0.0        11111000.00000000.00000000.00000000  /5
1063// 240.0.0.0        11110000.00000000.00000000.00000000  /4
1064// 224.0.0.0        11100000.00000000.00000000.00000000  /3
1065// 192.0.0.0        11000000.00000000.00000000.00000000  /2
1066// 128.0.0.0        10000000.00000000.00000000.00000000  /1
1067// 0.0.0.0          00000000.00000000.00000000.00000000  /0   IP space
1068?>
Note: See TracBrowser for help on using the repository browser.