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

Last change on this file since 362 was 362, checked in by quinn, 15 years ago

Added a GPL license info header to all source files. Updated license to GPL v3.

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