防护代码 - 页面防注入、跨站

分类: 源代码 > PHP

/**

* 修改自360通用php防护代码

* 页面防注入、跨站

*/

if(!defined('IN_SYS')){

    header("HTTP/1.1 404 Not Found");

    die;

}

class Safer{

    private $get_filter = "'|(and|or)\\b.+?(>|<|=|in|like)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)";

    private $post_filter = "\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)";

    private $cookie_filter = "\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)";

    private $attack_info = array();

    /**

     * 检查 GET、POST、COOKIE

     * @param array $data

     * @param string $type

     * @return boolean

     */

    public function check($data, $type){

        $type = strtolower($type);

        if(!in_array($type, array('get', 'post', 'cookie'))){

            return false;

        }else if(empty($data) || !is_array($data)){

            return false;

        }

        $filter = "{$type}_filter";

        foreach($data as $key => $value){

            $result = $this->checkAttack($key, $value, $this->{$filter});

            if($result){

                return true;

            }

        }

        return false;

    }

    /**

     * 获取攻击信息

     * @return array

     */

    public function getAttackInfo(){

        return $this->attack_info;

    }

    /**

     * 检查是否有攻击

     * @param string $arg

     * @param string $value

     * @param string $filter

     * @return boolean

     */

    private function checkAttack($arg, $value, $filter){

        if(is_array($value)){

            $value = implode($value);

        }

        if (preg_match("/".$filter."/is", $value, $match) == 1){

            $this->attack_info = array(

                'ip' => $_SERVER["REMOTE_ADDR"],

                'datetime' => strftime("%Y-%m-%d %H:%M:%S"),

                'uri' => $_SERVER["REQUEST_URI"],

                'arg' => $arg,

                'value' => $value,

                'match' => json_encode($match),

            );

            return true;

        }

        return false;

    }

}

来源:原创 发布时间:2020-06-20 20:19:01