您的位置:首页 > 编程语言 > PHP开发

【安全 PHP】sql防注入和xss安全 方案 请喷

2016-08-29 16:19 621 查看
<?php

/**

 *sql注入和xss去除

 */

class sqlxss_safe {

    const getfilter="'|(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)";

    const postfilter="\\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)";

    const cookiefilter="\\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)";

 

    public function __construct() {

 

    }

 

    public function initLogHacker() {

         

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

            $this->StopAttack($key,$value,self::getfilter);

            $_GET[$key] = $this->safe_replace($value);

            $_GET[$key] = $this->remove_xss($_GET[$key]);

        }

         

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

            $this->StopAttack($key,$value,self::cookiefilter);

        }

         

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

            if (!is_array($value)) {

                $_POST[$key] = $this->trim_script($value);

            }

            $this->StopAttack($key,$value,self::postfilter);

        }

    }

     

    private function StopAttack($StrFiltKey,$StrFiltValue,$ArrFiltReq){

        if(is_array($StrFiltValue)) {

            $StrFiltValue=implode($StrFiltValue);

        }     

        if (preg_match("/".$ArrFiltReq."/is",$StrFiltValue)==1){

            $this->writeslog($_SERVER["REMOTE_ADDR"]."    ".strftime("%Y-%m-%d %H:%M:%S")."    ".$_SERVER["PHP_SELF"]."    ".$_SERVER["REQUEST_METHOD"]."    ".$StrFiltKey."    ".$StrFiltValue);

            echo '您提交的参数非法,系统已记录您的本次操作!';

            die();

        }

    }

     

    /**

     * 安全过滤函数

     *

     * @param $string

     * @return string

     */

    private function safe_replace($string) {//"and" 比较常见输入,不替换

    $unsafeword = array("\""," ","select","insert","delete","update","use","create","drop","or","union","load_file","outfile","TRUNCATE","alter","table");

        $string= str_ireplace($unsafeword,"",$string);//不区分大小写的替换

        $string = str_replace('%20', '', $string);

        $string = str_replace('%27', '', $string);

        $string = str_replace('%2527', '', $string);

        $string = str_replace('*', '', $string);

        $string = str_replace('"', '"', $string);

        $string = str_replace("'", '', $string);

        $string = str_replace('"', '', $string);

        $string = str_replace(';', '', $string);

        $string = str_replace('<', '<', $string);

        $string = str_replace('>', '>', $string);

        $string = str_replace("{", '', $string);

        $string = str_replace('}', '', $string);

        $string = str_replace('\\', '', $string);

        return $string;

    }

     

    /**

     * 转义 javascript 代码标记

     *

     * @param $str

     * @return mixed

     */

    private function trim_script($str) {

        if (is_array($str)) {

            foreach ($str as $key => $val) {

                $str[$key] = trim_script($val);

            }

        } else {

            $str = preg_replace('/\<([\/]?)script([^\>]*?)\>/si', '<\\1script\\2>', $str);

            $str = preg_replace('/\<([\/]?)iframe([^\>]*?)\>/si', '<\\1iframe\\2>', $str);

            $str = preg_replace('/\<([\/]?)frame([^\>]*?)\>/si', '<\\1frame\\2>', $str);

            $str = preg_replace('/]]\>/si', ']] >', $str);

        }

        return $str;

    }

     

    /**

     * 防止XSS攻击,用在表单textarea中内容过滤较多

     *

     * @param $str

     * @return mixed

     */

    private function remove_xss($val) {

        $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);

        $search = 'abcdefghijklmnopqrstuvwxyz';

        $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

        $search .= '1234567890!@#$%^&*()';

        $search .= '~`";:?+/={}[]-_|\'\\';

        for ($i = 0; $i < strlen($search); $i++) {

            $val = preg_replace('/(&#[xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val); // with a ;

            $val = preg_replace('/(�{0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val); // with a ;

        }

 

        $ra1 = array(

            'javascript',

            'vbscript',

            'expression',

            'applet',

            'meta',

            'xml',

            'blink',

            'link',

            'style',

            'script',

            'embed',

            'object',

            'iframe',

            'frame',

            'frameset',

            'ilayer',

            'layer',

            'bgsound',

            'title',

            'base'

            );

            $ra2 = array(

            'onabort',

            'onactivate',

            'onafterprint',

            'onafterupdate',

            'onbeforeactivate',

            'onbeforecopy',

            'onbeforecut',

            'onbeforedeactivate',

            'onbeforeeditfocus',

            'onbeforepaste',

            'onbeforeprint',

            'onbeforeunload',

            'onbeforeupdate',

            'onblur',

            'onbounce',

            'oncellchange',

            'onchange',

            'onclick',

            'oncontextmenu',

            'oncontrolselect',

            'oncopy',

            'oncut',

            'ondataavailable',

            'ondatasetchanged',

            'ondatasetcomplete',

            'ondblclick',

            'ondeactivate',

            'ondrag',

            'ondragend',

            'ondragenter',

            'ondragleave',

            'ondragover',

            'ondragstart',

            'ondrop',

            'onerror',

            'onerrorupdate',

            'onfilterchange',

            'onfinish',

            'onfocus',

            'onfocusin',

            'onfocusout',

            'onhelp',

            'onkeydown',

            'onkeypress',

            'onkeyup',

            'onlayoutcomplete',

            'onload',

            'onlosecapture',

            'onmousedown',

            'onmouseenter',

            'onmouseleave',

            'onmousemove',

            'onmouseout',

            'onmouseover',

            'onmouseup',

            'onmousewheel',

            'onmove',

            'onmoveend',

            'onmovestart',

            'onpaste',

            'onpropertychange',

            'onreadystatechange',

            'onreset',

            'onresize',

            'onresizeend',

            'onresizestart',

            'onrowenter',

            'onrowexit',

            'onrowsdelete',

            'onrowsinserted',

            'onscroll',

            'onselect',

            'onselectionchange',

            'onselectstart',

            'onstart',

            'onstop',

            'onsubmit',

            'onunload'

            );

            $ra = array_merge($ra1, $ra2);

 

            $found = true; // keep replacing as long as the previous round replaced something

            while ($found == true) {

                $val_before = $val;

                for ($i = 0; $i < sizeof($ra); $i++) {

                    $pattern = '/';

                    for ($j = 0; $j < strlen($ra[$i]); $j++) {

                        if ($j > 0) {

                            $pattern .= '(';

                            $pattern .= '(&#[xX]0{0,8}([9ab]);)';

                            $pattern .= '|';

                            $pattern .= '|(�{0,8}([9|10|13]);)';

                            $pattern .= ')*';

                        }

                        $pattern .= $ra[$i][$j];

                    }

                    $pattern .= '/i';

                    $replacement = substr($ra[$i], 0, 2) . '<x>' . substr($ra[$i], 2); // add in <> to nerf the tag

                    $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags

                    if ($val_before == $val) {

                        // no replacements were made, so exit the loop

                        $found = false;

                    }

                }

            }

            return $val;

    }

    /**

     * SQL注入日志

     */

    private function writeslog($log){

        $log_path = 'sql_log.txt';

        $ts = fopen($log_path,"a+");

        fputs($ts,$log."\r\n");

        fclose($ts);

    }

}

 

?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: