能想到的常见攻击
1,利用字符过滤漏洞,提交恶意js代码,当用户打开页面时执行 2,需要填写图片地址或css等直接在页面加载时执行的地方,填写恶意js [javascript:xxxx],当用户打开包含图片的页面时,可以执行js。比如GET s1.game.com/fight/:id 表示发兵到某个用户,虽然做了用户验证,但没做来源验证,用户只需将这个地址发到同用户的论坛作为图片地址即可执行3,通过跳转页面漏洞,比如 refer.php?message=xxxx ,页面上直接用 $_GET['message'] 的话,就会造成xss漏洞,把message的参数换成js代码或恶意网址,即可盗取用户cookie,或执行恶意js,或跳转到钓鱼页面等
4,利用浏览器或服务器0day漏洞1,XSS主要是你的页面可以运行用户写的js,所以对所有的用户提交的数据进行过滤,对于判断用户是否登录状态的cookie信息进行加密,并且加上Ip信息,这样基本被盗取也无法获取登录权限
2,对update或delete的操作采用post方式提交,每次form里加一个唯一验证字符串,用hiden方式提交,用于服务器验证是否来自用户客户端 3,跳转程序需要对传递的url进行匹配判断,只允许特定的格式 4,时常关注安全方面的消息,一有漏洞即刻不上很多框架都提供XSS的过滤,下面这个类中的xss_clean是CI的过滤函数可以看下
这里有各种千奇百怪的xss方式
defined('MAGIC_QUOTES_GPC') || define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());class Helper_Input { public static function filterVar() { unset($GLOBALS, $_ENV, $HTTP_GET_VARS, $HTTP_POST_VARS,$HTTP_COOKIE_VARS, $HTTP_SERVER_VARS, $HTTP_ENV_VARS); $_GET = self::addslashes($_GET, 1, true); $_POST = self::addslashes($_POST, 1, true); $_COOKIE = self::addslashes($_COOKIE, 1, true); $_SERVER = self::addslashes($_SERVER); $_FILES = self::addslashes($_FILES); $_REQUEST = self::addslashes($_REQUEST, 1, true); } public static function addslashes($str, $force = 0, $strip = false) { if (!MAGIC_QUOTES_GPC || $force) { if (is_array($str)) { foreach ($str as $key => $value){ $str[$key] = self::addslashes($value, $force, $strip); } } else { $str = addslashes($strip ? stripslashes($str) : $str); } } return $str; } public static function stripslashes($str) { if(is_array($str)) { foreach($str as $key=>$value) { $str[$key] = self::stripslashes($value); } } else { $str = stripslashes($str); } return $str; } public static function htmlspecialchars($str) { if(is_array($str)) { foreach($str as $key => $val) { $str[$key] = self::htmlspecialchars($val); } } else { $str = preg_replace('/&(( #(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1', str_replace(array('&', '"', '<', '>'), array('&', '"', '<', '>'), $str)); } return $str; } /** * 过滤特殊字符 */ public static function filterSpecialWord($str){ return preg_replace('/>|<|,|\[|\]|\{|\}|\?|\/|\+|=|\||\'|\\|\"|:|;|\~|\!|\@|\ #|\*|\$|\%|\^|\&|\(|\)|`/i', "", $str); } /** * 过滤SQL注入攻击字符串 * * @param string $str 需要过滤的字符串 * @param resource $db 数据库连接,可以为空 * @return string */ public static function filterSql($str, $db = null) { if (!MAGIC_QUOTES_GPC) { if ($db) { return mysql_real_escape_string($str, $db); } return mysql_escape_string($str); } else { $str = self::addslashes($str, 1); } return $str; } /** * 过滤HTML标签 * * @param string text - 传递进去的文本内容 * @param bool $strict - 是否严格过滤(严格过滤将把所有已知HTML标签开头的内容过滤掉) * @return string 返回替换后的结果 */ public static function stripHtmlTag($text, $strict=false) { $text = strip_tags($text); if (!$strict){ return $text; } $html_tag = "/<[\/|!]?(html|head|body|div|span|DOCTYPE|title|link|meta|style|p|h1|h2|h3|h4|h5|h6|strong|em|abbr|acronym|address|bdo|blockquote|cite|q|code|ins|del|dfn|kbd|pre|samp|var|br|a|base|img|area|map|object|param|ul|ol|li|dl|dt|dd|table|tr|td|th|tbody|thead|tfoot|col|colgroup|caption|form|input|textarea|select|option|optgroup|button|label|fieldset|legend|script|noscript|b|i|tt|sub|sup|big|small|hr)[^>]*>/is"; return preg_replace($html_tag, "", $text); } /** * 文件名安全 * @param $str String 文件名 * @return String */ public static function secureFilename($str) { $bad = array( "../", "./", " ", "<", ">", "'", '"', '&', '$', ' #', '{', '}', '[', ']', '=', ';', '?', "%20", "%22", "%3c", // < "%253c", // < "%3e", // > "%0e", // > "%28", // ( "%29", // ) "%2528", // ( "%26", // & "%24", // $ "%3f", // ? "%3b", // ; "%3d" // = ); return stripslashes(str_replace($bad, '', $str)); } /** * Removes potential XSS code from an input string. * * Using an external class by Travis Puderbaugh* * @param string Input string * @param string s)replaceString for inserting in keywords (which destroyes the tag * @return string Input string with potential XSS code removed */ public static function cleanXSS($val, $replaceString = ' ') { // don't use empty $replaceString because then no XSS-remove will be done if ($replaceString == '') { $replaceString = ' '; } // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed // this prevents some character re-spacing such as // note that you have to handle splits with \n, \r, and \t later since they*are* allowed in some inputs $val = preg_replace('/([\x00-\x08][\x0b-\x0c][\x0e-\x19])/', '', $val); // straight replacements, the user should never need these since they're normal characters // this prevents like $search = '/& #[xX]0{0,8}(21|22|23|24|25|26|27|28|29|2a|2b|2d|2f|30|31|32|33|34|35|36|37|38|39|3a|3b|3d|3f|40|41|42|43|44|45|46|47|48|49|4a|4b|4c|4d|4e|4f|50|51|52|53|54|55|56|57|58|59|5a|5b|5c|5d|5e|5f|60|61|62|63|64|65|66|67|68|69|6a|6b|6c|6d|6e|6f|70|71|72|73|74|75|76|77|78|79|7a|7b|7c|7d|7e);?/ie'; $val = preg_replace($search, "chr(hexdec('\\1'))", $val); $search = '/?1?7{0,8}(33|34|35|36|37|38|39|40|41|42|43|45|47|48|49|50|51|52|53|54|55|56|57|58|59|61|63|64|65|66|67|68|69|70|71|72|73|74|75|76|77|78|79|80|81|82|83|84|85|86|87|88|89|90|91|92|93|94|95|96|97|98|99|100|101|102|103|104|105|106|107|108|109|110|111|112|113|114|115|116|117|118|119|120|121|122|123|124|125|126);?/ie'; $val = preg_replace($search, "chr('\\1')", $val); // now the only remaining whitespace attacks are \t, \n, and \r $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base', '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_tag = array('applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base'); $ra_attribute = array('style', '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_protocol = array('javascript', 'vbscript', 'expression'); //remove the potential & #xxx; stuff for testing $val2 = preg_replace('/(& #[xX]?0{0,8}(9|10|13|a|b);)*\s*/i', '', $val); $ra = array(); foreach ($ra1 as $ra1word) { //stripos is faster than the regular expressions used later //and because the words we're looking for only have chars < 0x80 //we can use the non-multibyte safe version if (stripos($val2, $ra1word ) !== false ) { //keep list of potential words that were found if (in_array($ra1word, $ra_protocol)) { $ra[] = array($ra1word, 'ra_protocol'); } if (in_array($ra1word, $ra_tag)) { $ra[] = array($ra1word, 'ra_tag'); } if (in_array($ra1word, $ra_attribute)) { $ra[] = array($ra1word, 'ra_attribute'); } //some keywords appear in more than one array //these get multiple entries in $ra, each with the appropriate type } } //only process potential words if (count($ra) > 0) { // keep replacing as long as the previous round replaced something $found = true; while ($found == true) { $val_before = $val; for ($i = 0; $i < sizeof($ra); $i++) { $pattern = ''; for ($j = 0; $j < strlen($ra[$i][0]); $j++) { if ($j > 0) { $pattern .= '((& #[xX]0{0,8}([9ab]);)|(?1?7{0,8}(9|10|13);)|\s)*'; } $pattern .= $ra[$i][0][$j]; } //handle each type a little different (extra conditions to prevent false positives a bit better) switch ($ra[$i][1]) { case 'ra_protocol': //these take the form of e.g. 'javascript:' $pattern .= '((& #[xX]0{0,8}([9ab]);)|(?1?7{0,8}(9|10|13);)|\s)*(?=:)'; break; case 'ra_tag': //these take the form of e.g. '
'[removed]', 'document.write' => '[removed]', '.parentNode' => '[removed]', '.innerHTML' => '[removed]', 'window.location' => '[removed]', '-moz-binding' => '[removed]', ' ' => '-->', ' ' '[removed]', "expression\s*(\(|&\#40;)" => '[removed]', // CSS and IE "vbscript\s*:" => '[removed]', // IE, surprise! "Redirect\s+302" => '[removed]' ); public function __construct() { } // -------------------------------------------------------------------- /** * XSS Clean * * Sanitizes data so that Cross Site Scripting Hacks can be * prevented. This function does a fair amount of work but * it is extremely thorough, designed to prevent even the * most obscure XSS attempts. Nothing is ever 100% foolproof, * of course, but I haven't been able to get anything passed * the filter. * * Note: This function should only be used to deal with data * upon submission. It's not something that should * be used for general runtime processing. * * This function was based in part on some code and ideas I * got from Bitflux: http://channel.bitflux.ch/wiki/XSS_Prevention * * To help develop this script I used this great list of * vulnerabilities along with a few other hacks I've * harvested from examining vulnerabilities in other programs: * http://ha.ckers.org/xss.html * * @access public * @param mixed string or array * @return string */ public function xss_clean($str) { /* * Is the string an array? * */ if (is_array($str)) { while (list($key) = each($str)) { $str[$key] = $this->xss_clean($str[$key]); } return $str; } /* * Remove Invisible Characters */ $str = remove_invisible_characters($str); /* * Protect GET variables in URLs */ // 901119URL5918AMP18930PROTECT8198 $str = preg_replace('|\&([a-z\_0-9\-]+)\=([a-z\_0-9\-]+)|i', $this->xss_hash()."\\1=\\2", $str); /* * Validate standard character entities * * Add a semicolon if missing. We do this to enable * the conversion of entities to ASCII later. * */ $str = preg_replace('#(&\#?[0-9a-z]{2,})([\x00-\x20])*;?#i', "\\1;\\2", $str); /* * Validate UTF16 two byte encoding (x00) * * Just as above, adds a semicolon if missing. * */ $str = preg_replace('#(&\#x?)([0-9A-F]+);?#i',"\\1\\2;",$str); /* * Un-Protect GET variables in URLs */ $str = str_replace($this->xss_hash(), '&', $str); /* * URL Decode * * Just in case stuff like this is submitted: * * Google * * Note: Use rawurldecode() so it does not remove plus signs * */ $str = rawurldecode($str); /* * Convert character entities to ASCII * * This permits our tests below to work reliably. * We only convert entities that are within tags since * these are the ones that will pose security problems. * */ $str = preg_replace_callback("/[a-z]+=([\'\"]).*?\\1/si", array($this, '_convert_attribute'), $str); $str = preg_replace_callback("/<\w+.*?(?=>|<|$)/si", array($this, '_decode_entity'), $str); /* * Remove Invisible Characters Again! */ $str = remove_invisible_characters($str); /* * Convert all tabs to spaces** This prevents strings like this: ja vascript * NOTE: we deal with spaces between characters later. * NOTE: preg_replace was found to be amazingly slow here on large blocks of data, * so we use str_replace. * */ if (strpos($str, "\t") !== FALSE) { $str = str_replace("\t", ' ', $str); } /* * Capture converted string for later comparison */ $converted_string = $str; /* * Not Allowed Under Any Conditions */ foreach ($this->never_allowed_str as $key => $val) { $str = str_replace($key, $val, $str); } foreach ($this->never_allowed_regex as $key => $val) { $str = preg_replace("#".$key."#i", $val, $str); } /* * Makes PHP tags safe * * Note: XML tags are inadvertently replaced too: * * '), array('', '?>'), $str); } /* * Compact any exploded words * * This corrects words like: j a v a s c r i p t* These words are compacted back to their correct state. * */ $words = array('javascript', 'expression', 'vbscript', 'script', 'applet', 'alert', 'document', 'write', 'cookie', 'window'); foreach ($words as $word){ $temp = ''; for ($i = 0, $wordlen = strlen($word); $i < $wordlen; $i++) { $temp .= substr($word, $i, 1)."\s*"; } // We only want to do this when it is followed by a non-word character // That way valid stuff like "dealer to" does not become "dealerto" $str = preg_replace_callback('#('.substr($temp, 0, -3).')(\W)#is', array($this, '_compact_exploded_words'), $str); } /* * Remove disallowed Javascript in links or img tags * We used to do some version comparisons and use of stripos for PHP5, but it is dog slow compared * to these simplified non-capturing preg_match(), especially if the pattern exists in the string */ do { $original = $str; if (preg_match("/]*?)(>|$)#si", array($this, '_js_link_removal'), $str); } if (preg_match("/]*?)(\s?/?>|$)#si", array($this, '_js_img_removal'), $str); } if (preg_match("/script/i", $str) OR preg_match("/xss/i", $str)) { $str = preg_replace("#<(/*)(script|xss)(.*?)\>#si", '[removed]', $str); } }while ($original != $str); unset($original); /* * Remove JavaScript Event Handlers * * Note: This code is a little blunt. It removes * the event handler and anything up to the closing >, * but it's unlikely to be a problem. * */ $event_handlers = array('[^a-z_\-]on\w*','xmlns'); $str = preg_replace("#<([^><]+?)(".implode('|', $event_handlers).")(\s*=\s*[^><]*)([><]*)#i", "<\\1\\4", $str); /* * Sanitize naughty HTML elements * * If a tag containing any of the words in the list * below is found, the tag gets converted to entities. * * So this: