home *** CD-ROM | disk | FTP | other *** search
/ Cricao de Sites - 650 Layouts Prontos / WebMasters.iso / CMS / xoops-2.0.18.1.exe / xoops-2.0.18.1 / htdocs / class / xoopssecurity.php < prev    next >
Encoding:
PHP Script  |  2007-12-06  |  9.8 KB  |  262 lines

  1. <?php
  2. // $Id: xoopssecurity.php 1153 2007-12-05 13:37:51Z phppp $
  3. //  ------------------------------------------------------------------------ //
  4. //                XOOPS - PHP Content Management System                      //
  5. //                    Copyright (c) 2000 XOOPS.org                           //
  6. //                       <http://www.xoops.org/>                             //
  7. //  ------------------------------------------------------------------------ //
  8. //  This program is free software; you can redistribute it and/or modify     //
  9. //  it under the terms of the GNU General Public License as published by     //
  10. //  the Free Software Foundation; either version 2 of the License, or        //
  11. //  (at your option) any later version.                                      //
  12. //                                                                           //
  13. //  You may not change or alter any portion of this comment or credits       //
  14. //  of supporting developers from this source code or any supporting         //
  15. //  source code which is considered copyrighted (c) material of the          //
  16. //  original comment or credit authors.                                      //
  17. //                                                                           //
  18. //  This program is distributed in the hope that it will be useful,          //
  19. //  but WITHOUT ANY WARRANTY; without even the implied warranty of           //
  20. //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            //
  21. //  GNU General Public License for more details.                             //
  22. //                                                                           //
  23. //  You should have received a copy of the GNU General Public License        //
  24. //  along with this program; if not, write to the Free Software              //
  25. //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA //
  26. //  ------------------------------------------------------------------------ //
  27. // Author: Kazumi Ono (AKA onokazu)                                          //
  28. // URL: http://www.myweb.ne.jp/, http://www.xoops.org/, http://jp.xoops.org/ //
  29. // Project: The XOOPS Project                                                //
  30. // ------------------------------------------------------------------------- //
  31. /*
  32.  * Class for managing security aspects such as checking referers, applying tokens and checking global variables for contamination
  33.  *
  34.  * @package        kernel
  35.  * @subpackage    core
  36.  *
  37.  * @author        Jan Pedersen     <mithrandir@xoops.org>
  38.  * @copyright    (c) 2000-2005 The Xoops Project - www.xoops.org
  39.  */
  40.  
  41. class XoopsSecurity {
  42.     var $errors = array();
  43.     /**
  44.      * Constructor
  45.      *
  46.      **/
  47.     function XoopsSecurity() {
  48.     }
  49.  
  50.     /**
  51.     * Check if there is a valid token in $_REQUEST[$name . '_REQUEST'] - can be expanded for more wide use, later (Mith)
  52.     *
  53.     * @param bool   $clearIfValid whether to clear the token after validation
  54.     * @param string $token token to validate
  55.     * @param string $name session name
  56.     *
  57.     * @return bool
  58.     */
  59.     function check($clearIfValid = true, $token = false, $name = 'XOOPS_TOKEN') {
  60.         return $this->validateToken($token, $clearIfValid, $name);
  61.     }
  62.  
  63.     /**
  64.     * Create a token in the user's session
  65.     *
  66.     * @param int $timeout time in seconds the token should be valid
  67.     * @param string $name session name
  68.     *
  69.     * @return string token value
  70.     */
  71.     function createToken($timeout = 0, $name = 'XOOPS_TOKEN')
  72.     {
  73.         $this->garbageCollection($name);
  74.         if ($timeout == 0) {
  75.             $timeout = $GLOBALS['xoopsConfig']['session_expire'] * 60; //session_expire is in minutes, we need seconds
  76.         }
  77.         $token_id = md5(uniqid(rand(), true));
  78.         // save token data on the server
  79.         if (!isset($_SESSION[$name . '_SESSION'])) {
  80.             $_SESSION[$name . '_SESSION'] = array();
  81.         }
  82.         $token_data = array('id' => $token_id, 'expire' => time() + intval($timeout));
  83.         array_push($_SESSION[$name . '_SESSION'], $token_data);
  84.         return md5($token_id.$_SERVER['HTTP_USER_AGENT'].XOOPS_DB_PREFIX);
  85.     }
  86.  
  87.     /**
  88.     * Check if a token is valid. If no token is specified, $_REQUEST[$name . '_REQUEST'] is checked
  89.     *
  90.     * @param string $token token to validate
  91.     * @param bool   $clearIfValid whether to clear the token value if valid
  92.     * @param string $name session name to validate
  93.     *
  94.     * @return bool
  95.     **/
  96.     function validateToken($token = false, $clearIfValid = true, $name = 'XOOPS_TOKEN')
  97.     {
  98.         global $xoopsLogger;
  99.         $token = ($token !== false) ? $token : ( isset($_REQUEST[$name . '_REQUEST']) ? $_REQUEST[$name . '_REQUEST'] : '' );
  100.         if (empty($token) || empty($_SESSION[$name . '_SESSION'])) {
  101.             $xoopsLogger->addExtra('Token Validation', 'No valid token found in request/session');
  102.             return false;
  103.         }
  104.         $validFound = false;
  105.         $token_data =& $_SESSION[$name . '_SESSION'];
  106.         foreach (array_keys($token_data) as $i) {
  107.             if ($token === md5($token_data[$i]['id'].$_SERVER['HTTP_USER_AGENT'].XOOPS_DB_PREFIX)) {
  108.                 if ($this->filterToken($token_data[$i])) {
  109.                     if ($clearIfValid) {
  110.                         // token should be valid once, so clear it once validated
  111.                         unset($token_data[$i]);
  112.                     }
  113.                     $xoopsLogger->addExtra('Token Validation', 'Valid token found');
  114.                     $validFound = true;
  115.                 } else {
  116.                     $str = 'Valid token expired';
  117.                     $this->setErrors($str);
  118.                     $xoopsLogger->addExtra('Token Validation', $str);
  119.                 }
  120.             }
  121.         }
  122.         if (!$validFound) {
  123.             $xoopsLogger->addExtra('Token Validation', 'No valid token found');
  124.         }
  125.         $this->garbageCollection($name);
  126.         return $validFound;
  127.     }
  128.  
  129.     /**
  130.     * Clear all token values from user's session
  131.     *
  132.     * @param string $name session name
  133.     **/
  134.     function clearTokens($name = 'XOOPS_TOKEN')
  135.     {
  136.         $_SESSION[$name . '_SESSION'] = array();
  137.     }
  138.  
  139.     /**
  140.     * Check whether a token value is expired or not
  141.     *
  142.     * @param string $token
  143.     *
  144.     * @return bool
  145.     **/
  146.     function filterToken($token)
  147.     {
  148.         return (!empty($token['expire']) && $token['expire'] >= time());
  149.     }
  150.  
  151.     /**
  152.     * Perform garbage collection, clearing expired tokens
  153.     *
  154.     * @param string $name session name
  155.     *
  156.     * @return void
  157.     **/
  158.     function garbageCollection($name = 'XOOPS_TOKEN') {
  159.         if (isset($_SESSION[$name . '_SESSION']) && count($_SESSION[$name . '_SESSION']) > 0) {
  160.             $_SESSION[$name . '_SESSION'] = array_filter($_SESSION[$name . '_SESSION'], array($this, 'filterToken'));
  161.         }
  162.     }
  163.     /**
  164.     * Check the user agent's HTTP REFERER against XOOPS_URL
  165.     *
  166.     * @param int $docheck 0 to not check the referer (used with XML-RPC), 1 to actively check it
  167.     *
  168.     * @return bool
  169.     **/
  170.     function checkReferer($docheck = 1)
  171.     {
  172.         $ref = xoops_getenv('HTTP_REFERER');
  173.         if ($docheck == 0) {
  174.             return true;
  175.         }
  176.         if ($ref == '') {
  177.             return false;
  178.         }
  179.         if (strpos($ref, XOOPS_URL) !== 0 ) {
  180.             return false;
  181.         }
  182.         return true;
  183.     }
  184.  
  185.     /**
  186.     * Check superglobals for contamination
  187.     *
  188.     * @return void
  189.     **/
  190.     function checkSuperglobals() {
  191.         foreach (array('GLOBALS', '_SESSION', 'HTTP_SESSION_VARS', '_GET', 'HTTP_GET_VARS', '_POST', 'HTTP_POST_VARS', '_COOKIE', 'HTTP_COOKIE_VARS', '_REQUEST', '_SERVER', 'HTTP_SERVER_VARS', '_ENV', 'HTTP_ENV_VARS', '_FILES', 'HTTP_POST_FILES', 'xoopsDB', 'xoopsUser', 'xoopsUserId', 'xoopsUserGroups', 'xoopsUserIsAdmin', 'xoopsConfig', 'xoopsOption', 'xoopsModule', 'xoopsModuleConfig', 'xoopsRequestUri') as $bad_global) {
  192.             if (isset($_REQUEST[$bad_global])) {
  193.                 header('Location: '.XOOPS_URL.'/');
  194.                 exit();
  195.             }
  196.         }
  197.     }
  198.  
  199.     /**
  200.     * Check if visitor's IP address is banned
  201.     * Should be changed to return bool and let the action be up to the calling script
  202.     *
  203.     * @return void
  204.     **/
  205.     function checkBadips() {
  206.         global $xoopsConfig;
  207.         if ($xoopsConfig['enable_badips'] == 1 && isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] != '') {
  208.             foreach ($xoopsConfig['bad_ips'] as $bi) {
  209.                 if (!empty($bi) && preg_match("/".$bi."/", $_SERVER['REMOTE_ADDR'])) {
  210.                     exit();
  211.                 }
  212.             }
  213.         }
  214.         unset($bi);
  215.         unset($bad_ips);
  216.         unset($xoopsConfig['badips']);
  217.     }
  218.  
  219.     /**
  220.     * Get the HTML code for a XoopsFormHiddenToken object - used in forms that do not use XoopsForm elements
  221.     *
  222.     * @return string
  223.     **/
  224.     function getTokenHTML($name = 'XOOPS_TOKEN') {
  225.         require_once(XOOPS_ROOT_PATH."/class/xoopsformloader.php");
  226.         $token = new XoopsFormHiddenToken($name);
  227.         return $token->render();
  228.     }
  229.  
  230.     /**
  231.      * Add an error
  232.      *
  233.      * @param   string  $error
  234.      **/
  235.     function setErrors($error)
  236.     {
  237.         $this->errors[] = trim($error);
  238.     }
  239.  
  240.     /**
  241.      * Get generated errors
  242.      *
  243.      * @param    bool    $ashtml Format using HTML?
  244.      *
  245.      * @return    array|string    Array of array messages OR HTML string
  246.      */
  247.     function &getErrors($ashtml = false)
  248.     {
  249.         if (!$ashtml) {
  250.             return $this->errors;
  251.         } else {
  252.             $ret = '';
  253.             if (count($this->errors) > 0) {
  254.                 foreach ($this->errors as $error) {
  255.                     $ret .= $error.'<br />';
  256.                 }
  257.             }
  258.             return $ret;
  259.         }
  260.     }
  261. }
  262. ?>