博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
XXS常见攻击相关
阅读量:7140 次
发布时间:2019-06-28

本文共 31580 字,大约阅读时间需要 105 分钟。

hot3.png

能想到的常见攻击

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. '
to nerf the tag $replacement = substr_replace($ra[$i][0], $replaceString, 2, 0); // filter out the hex tags $val = preg_replace($pattern, $replacement, $val); if ($val_before == $val) { // no replacements were made, so exit the loop $found = false; } } } } return $val; }}

 

'[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: * Becomes: * */ $naughty = 'alert|applet|audio|basefont|base|behavior|bgsound|blink|body|embed|expression|form|frameset|frame|head|html|ilayer|iframe|input|isindex|layer|link|meta|object|plaintext|style|script|textarea|title|video|xml|xss'; $str = preg_replace_callback('#<(/*\s*)('.$naughty.')([^><]*)([><]*)#is', array($this, '_sanitize_naughty_html'), $str); /* * Sanitize naughty scripting elements * * Similar to above, only instead of looking for * tags it looks for PHP and JavaScript commands * that are disallowed. Rather than removing the * code, it simply converts the parenthesis to entities * rendering the code un-executable. * * For example: eval('some code') * Becomes: eval('some code') * */ $str = preg_replace('#(alert|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si', "\\1\\2(\\3)", $str); /* * Final clean up** This adds a bit of extra precaution in case * something got through the above filters * */ 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); } return $str; } // -------------------------------------------------------------------- /** * Random Hash for protecting URLs * * @access public * @return string */ public function xss_hash() { if ($this->xss_hash == '') { if (phpversion() >= 4.2) mt_srand(); else mt_srand(hexdec(substr(md5(microtime()), -8)) & 0x7fffffff); $this->xss_hash = md5(time() + mt_rand(0, 1999999999)); } return $this->xss_hash; } // -------------------------------------------------------------------- /* * * Compact Exploded Words * * Callback function for xss_clean() to remove whitespace from * things like j a v a s c r i p t * * @access private * @param type * @return type */ private function _compact_exploded_words($matches) { return preg_replace('/\s+/s', '', $matches[1]).$matches[2]; } // -------------------------------------------------------------------- /* * * Sanitize Naughty HTML * * Callback function for xss_clean() to remove naughty HTML elements * * @access private * @param array * @return string */ private function _sanitize_naughty_html($matches){ // encode opening brace $str = '<'.$matches[1].$matches[2].$matches[3]; // encode captured opening or closing brace to prevent recursive vectors $str .= str_replace(array('>', '<'), array('>', '<'), $matches[4]); return $str; } // -------------------------------------------------------------------- /** * JS Link Removal * * Callback function for xss_clean() to sanitize links * This limits the PCRE backtracks, making it more performance friendly * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in * PHP 5.2+ on link-heavy strings * * @access private * @param array * @return string */ private function _js_link_removal($match) { $attributes = $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1])); return str_replace($match[1], preg_replace("#href=.*?(alert\(|alert&\#40;|javascript\:|charset\=|window\.|document\.|\.cookie|_filter_attributes(str_replace(array('<', '>'), '', $match[1])); return str_replace($match[1], preg_replace("#src=.*?(alert\(|alert&\#40;|javascript\:|charset\=|window\.|document\.|\.cookie|', '<', '\\'), array('>', '<', '\\\\'), $match[0]); } // -------------------------------------------------------------------- /** * Filter Attributes * * Filters tag attributes for consistency and safety * * @access private * @param string * @return string */ private function _filter_attributes($str) { $out = ''; if (preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#is', $str, $matches)){ foreach ($matches[0] as $match) { $out .= preg_replace("#/\*.*?\*/#s", '', $match); } } return $out; } // -------------------------------------------------------------------- /** * HTML Entity Decode Callback * * Used as a callback for XSS Clean * * @access private * @param array * @return string */ private function _decode_entity($match) { return $this->entity_decode($match[0], 'UTF-8'); } // -------------------------------------------------------------------- /** * HTML Entities Decode * * This function is a replacement for html_entity_decode() * * In some versions of PHP the native function does not work * when UTF-8 is the specified character set, so this gives us * a work-around. More info here: * http://bugs.php.net/bug.php?id=25670 * * NOTE: html_entity_decode() has a bug in some PHP versions when UTF-8 is the * character set, and the PHP developers said they were not back porting the * fix to versions other than PHP 5.x. * * @access public * @param string * @param string * @return string */ public function entity_decode($str, $charset='UTF-8') { if (stristr($str, '&') === FALSE) return $str; // The reason we are not using html_entity_decode() by itself is because // while it is not technically correct to leave out the semicolon // at the end of an entity most browsers will still interpret the entity // correctly. html_entity_decode() does not convert entities without // semicolons, so we are left with our own little solution here. Bummer. if (function_exists('html_entity_decode') && (strtolower($charset) != 'utf-8' OR is_php('5.0.0'))){ $str = html_entity_decode($str, ENT_COMPAT, $charset); $str = preg_replace('~&#x(0*[0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str); return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str); } // Numeric Entities $str = preg_replace('~&#x(0*[0-9a-f]{2,5});{0,1}~ei', 'chr(hexdec("\\1"))', $str); $str = preg_replace('~&#([0-9]{2,4});{0,1}~e', 'chr(\\1)', $str); // Literal Entities - Slightly slow so we do another check if (stristr($str, '&') === FALSE){ $str = strtr($str, array_flip(get_html_translation_table(HTML_ENTITIES))); } return $str; } // -------------------------------------------------------------------- /** * Filename Security * * @access public * @param string * @return string */ public function sanitize_filename($str, $relative_path = FALSE) { $bad = array( "../", "", "<", ">", "'", '"', '&', '$', '#', '{', '}', '[', ']', '=', ';', '?', "%20", "%22", "%3c", // < "%253c", // < "%3e", // > "%0e", // > "%28", // ( "%29", // ) "%2528", // ( "%26", // & "%24", // $ "%3f", // ? "%3b", // ; "%3d" // = ); if ( ! $relative_path){ $bad[] = './'; $bad[] = '/'; } return stripslashes(str_replace($bad, '', $str)); }}]]>

XSS攻击分为存储型和反射型漏洞。

存储型XSS:在可编辑的地方构造,会写入DB(或静态页面)。客户端请求页面时运行JS、VbS脚本可以盗取Cookie、挂马。
反射型XSS:客户端浏览器会把URL中的参数一起显示。比如:请求 i=new Image;i.src=">
keyword后为构造的JS内容,执行后可以获得用户Cookie。
前端html漏洞位置为:<input type="text" value="装备" name="keyword" style="width:200px;"> 装备位置是keyword=后跟的查询字段,使用">闭合前面的value="。

对于这两种XSS的攻击,只需要过滤掉"引号"、“<”、“>”等特殊符号,可以使用htmlspecialchars函数把提交过来的参数过滤一下。

Error number: [$errno],error on line $errline in $errfile
"; die (); } set_error_handler ( "customError", E_ERROR ); $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)"; $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)"; $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)"; function StopAttack($StrFiltKey, $StrFiltValue, $ArrFiltReq) { if (is_array ( $StrFiltValue )) { $StrFiltValue = implode ( $StrFiltValue ); } if (preg_match ( "/" . $ArrFiltReq . "/is", $StrFiltValue ) == 1) { // slog("
操作IP: ".$_SERVER["REMOTE_ADDR"]."
操作时间: // ".strftime("%Y-%m-%d // %H:%M:%S")."
操作页面:".$_SERVER["PHP_SELF"]."
提交方式: // ".$_SERVER["REQUEST_METHOD"]."
提交参数: ".$StrFiltKey."
提交数据: // ".$StrFiltValue); print "360websec notice:Illegal operation!"; exit (); } } // $ArrPGC=array_merge($_GET,$_POST,$_COOKIE); foreach ( $_GET as $key => $value ) { StopAttack ( $key, $value, $getfilter ); } foreach ( $_POST as $key => $value ) { StopAttack ( $key, $value, $postfilter ); } foreach ( $_COOKIE as $key => $value ) { StopAttack ( $key, $value, $cookiefilter ); } if (file_exists ( 'update360.php' )) { echo "请重命名文件update360.php,防止黑客利用
"; die (); } function slog($logs) { $toppath = $_SERVER ["DOCUMENT_ROOT"] . "/log.htm"; $Ts = fopen ( $toppath, "a+" ); fputs ( $Ts, $logs . "\r\n" ); fclose ( $Ts ); }?>

客户端(浏览器)安全

同源策略(Same Origin Policy)

同源策略阻止从一个源加载的文档或脚本获取或设置另一个源加载的文档的属性。

如:

不能通过Ajax获取另一个源的数据;
JavaScript不能访问页面中iframe加载的跨域资源。

对 同源检测

跨域限制

浏览器中,script、img、iframe、link等标签,可以跨域引用或加载资源。

不同于 XMLHttpRequest,通过src属性加载的资源,浏览器限制了JavaScript的权限,使其不能读、写返回的内容。
XMLHttpRequest 也受到也同源策略的约束,不能跨域访问资源。

JSONP
为了解决 XMLHttpRequest 同源策略的局限性,JSONP出现了。
JSONP并不是一个官方的协议,它是利用script标签中src属性具有跨域加载资源的特性,而衍生出来的跨域数据访问方式。

CORS(Cross-Origin Resource Sharing)
CORS,即:跨域资源共享。
这是W3C委员会制定的一个新标准,用于解决 XMLHttpRequest 不能跨域访问资源的问题。目前支持情况良好(特指移动端)。
想了解更多,可查看之前的文章:《CORS(Cross-Origin Resource Sharing) 跨域资源共享》

 

XSS(Cross Site Script)

XSS(Cross Site Script) 即:跨站脚本攻击。
本来缩写其应该是CSS,不过为了避免和CSS层叠样式表 (Cascading Style Sheets)重复,所以在安全领域叫做 XSS 。

XSS 分类

XSS 主要分为两种形态

反射型XSS(非持久型XSS)。需要诱惑用户去激活的XSS攻击,如:点击恶意链接。

存储型XSS。混杂有恶意代码的数据被存储在服务器端,当用户访问输出该数据的页面时,就会促发XSS攻击。具有很强的稳定性。

XSS Payload
XSS Payload,是指那些用于完成各种具体功能的恶意脚本。
由于实现XSS攻击可以通过JavaScript、ActiveX控件、Flash插件、Java插件等技术手段实现,下面只讨论JavaScript的XSS Payload。

通过JavaScript实现的XSS Payload,一般有以下几种:

Cookie劫持

构造请求
XSS钓鱼
CSS History Hack

Cookie劫持
由于Cookie中,往往会存储着一些用户安全级别较高的信息,如:用户的登陆凭证。
当用户所访问的网站被注入恶意代码,它只需通过 document.cookie 这句简单的JavaScript代码,就可以顺利获取到用户当前访问网站的cookies。
如果攻击者能获取到用户登陆凭证的Cookie,甚至可以绕开登陆流程,直接设置这个cookie的值,来访问用户的账号。

构造请求

JavaScript 可以通过多种方式向服务器发送GET与POST请求。
网站的数据访问和操作,基本上都是通过向服务器发送请求而实现的。
如果让恶意代码顺利模拟用户操作,向服务器发送有效请求,将对用户造成重大损失。
例如:更改用户资料、删除用户信息等...

XSS钓鱼

关于网站钓鱼,详细大家应该也不陌生了。
就是伪造一个高度相似的网站,欺骗用户在钓鱼网站上面填写账号密码或者进行交易。
而XSS钓鱼也是利用同样的原理。
注入页面的恶意代码,会弹出一个想死的弹窗,提示用户输入账号密码登陆。
当用户输入后点击发送,这些资料已经去到了攻击者的服务器上了。

如:

 

CSS History Hack

CSS History Hack是一个有意思的东西。它结合 浏览器历史记录 和 CSS的伪类:a:visited,通过遍历一个网址列表来获取其中<a>标签的颜色,就能知道用户访问过什么网站。
相关链接:
PS:目前最新版的Chrome、Firefox、Safari已经无效,Opera 和 IE8以下 还可以使用。

XSS Worm

XSS Worm,即XSS蠕虫,是一种具有自我传播能力的XSS攻击,杀伤力很大。
引发 XSS蠕虫 的条件比较高,需要在用户之间发生交互行为的页面,这样才能形成有效的传播。一般要同时结合 反射型XSS 和 存储型XSS 。
案例:Samy Worm、新浪微博XSS攻击

新浪微博XSS攻击

这张图,其实已经是XSS蠕虫传播阶段的截图了。
攻击者要让XSS蠕虫成功被激活,应该是通过 私信 或者 @微博 的方式,诱惑一些微博大号上当。
当这些大号中有人点击了攻击链接后,XSS蠕虫就被激活,开始传播了。

这个XSS的漏洞,其实就是没有对地址中的变量进行过滤。

把上一页的链接decode了之后,我们就可以很容易的看出,这个链接的猫腻在哪里。
链接上带的变量,直接输出页面,导致外部JavaScript代码成功注入。

传播链接:

把链接decode之后: src=//www.2kt.cn/images/t.js></script>?type=update

相关XSS代码这里就不贴了,Google一下就有。

其实也要感谢攻击者只是恶作剧了一下,让用户没有造成实际的损失。
网上也有人提到,如果这个漏洞结合XSS钓鱼,再配合隐性传播,那样杀伤力会更大。

 

XSS 防御技巧

HttpOnly

服务器端在设置安全级别高的Cookie时,带上HttpOnly的属性,就能防止JavaScript获取。
PHP设置HttpOnly:

1 <?

2 header("Set-Cookie: a=1;", false);
3 header("Set-Cookie: b=1;httponly", false);
4 setcookie("c", "1", NULL, NULL, NULL, NULL, ture);

PS:手机上的QQ浏览器4.0,居然不支持httponly,而3.7的版本却没问题。测试平台是安卓4.0版本。
估计是一个低级的bug,已经向QQ浏览器那边反映了情。
截止时间:2013-01-28

输入检查
任何用户输入的数据,都是“不可信”的。
输入检查,一般是用于输入格式检查,例如:邮箱、电话号码、用户名这些...
都要按照规定的格式输入:电话号码必须纯是数字和规定长度;用户名除 中英文数字 外,仅允许输入几个安全的符号。
输入过滤不能完全交由前端负责,前端的输入过滤只是为了避免普通用户的错误输入,减轻服务器的负担。
因为攻击者完全可以绕过正常输入流程,直接利用相关接口向服务器发送设置。
所以,前端和后端要做相同的过滤检查。

输出检查
相比输入检查,前端更适合做输出检查。

可以看到,HttpOnly和前端没直接关系,输入检查的关键点也不在于前端。

那XSS的防御就和前端没关系了?
当然不是,随着移动端web开发发展起来了,Ajax的使用越来越普遍,越来越多的操作都交给前端来处理。
前端也需要做好XSS防御。
JavaScript直接通过Ajax向服务器请求数据,接口把数据以JSON格式返回。前端整合处理数据后,输出页面。
所以,前端的XSS防御点,在于输出检查。
但也要结合XSS可能发生的场景。

XSS注意场景

在HTML标签中输出
如:<a href=# >{$var}</a>
风险:{$var} 为 <img src=# οnerrοr="/xss/" />
防御手段:变量HtmlEncode后输出

在HTML属性中输出

如:<div data-num="{$var}"></div>
风险:{$var} 为 " οnclick="/xss/
防御手段:变量HtmlEncode后输出

在<script>标签中输出

如:<script>var num = {$var};</script>
风险:{$var} 为 1; alert(/xss/)
防御手段:确保输出变量在引号里面,再让变量JavaScriptEncode后输出。

在事件中输出

如:<span οnclick="fun({$var})">hello!click me!</span>
风险:{$var} 为 ); alert(/xss/); //
防御手段:确保输出变量在引号里面,再让变量JavaScriptEncode后输出。

在CSS中输出

一般来说,尽量禁止用户可控制的变量在<style>标签和style属性中输出。

在地址中输出

如:<a href="}">
风险:{$var} 为 " οnclick="alert(/xss/)
防御手段:对URL中除 协议(Protocal) 和 主机(Host) 外进行URLEncode。如果整个链接都由变量输出,则需要判断是不是http开头。

HtmlEncode

对下列字符实现编码
& ——》 &amp;
< ——》 &lt;

——》 &gt;

" ——》 &quot;
' ——》 &#39; (IE不支持&apos;)
/ ——》 &#x2F;

JavaScriptEncode

对下列字符加上反斜杠
" ——》 \"
' ——》 \'
\ ——》 \
\n ——》 \n
\r ——》 \r (Windows下的换行符)

例子: "\".replace(/\/g, "\\"); //return \

推荐一个JavaScript的模板引擎:artTemplate

URLEncode

使用以下JS原生方法进行URI编码和解码:

encodeURI

decodeURI
decodeURIComponent
encodeURIComponent

 

CSRF(Cross-site request forgery)

CSRF 即:跨站点请求伪造

网站A :为恶意网站。
网站B :用户已登录的网站。
当用户访问 A站 时,A站 私自访问 B站 的操作链接,模拟用户操作。

假设B站有一个删除评论的链接:

A站 直接访问该链接,就能删除用户在 B站 的评论。

CSRF 的攻击策略

因为浏览器访问 B站 相关链接时,会向其服务器发送 B站 保存在本地的Cookie,以判断用户是否登陆。所以通过 A站 访问的链接,也能顺利执行。

 

CSRF 防御技巧

验证码
几乎所有人都知道验证码,但验证码不单单用来防止注册机的暴力破解,还可以有效防止CSRF的攻击。
验证码算是对抗CSRF攻击最简洁有效的方法。
但使用验证码的问题在于,不可能在用户的所有操作上都需要输入验证码。
只有一些关键的操作,才能要求输入验证码。
不过随着HTML5的发展。
利用canvas标签,前端也能识别验证码的字符,让CSRF生效。

Referer Check

Referer Check即来源检测。
HTTP Referer 是 Request Headers 的一部分,当浏览器向web服务器发出请求的时候,一般会带上Referer,告诉服务器用户从哪个站点链接过来的。
服务器通过判断请求头中的referer,也能避免CSRF的攻击。

Token

CSRF能攻击成功,根本原因是:操作所带的参数均被攻击者猜测到。

既然知道根本原因,我们就对症下药,利用Token。
当向服务器传参数时,带上Token。这个Token是一个随机值,并且由服务器和用户同时持有。
Token可以存放在用户浏览器的Cookie中,
当用户提交表单时带上Token值,服务器就能验证表单和Cookie中的Token是否一致。
(前提,网站没有XSS漏洞,攻击者不能通过脚本获取用户的Cookie)

 

转载于:https://my.oschina.net/lovelong1/blog/217622

你可能感兴趣的文章
linux下samba共享服务器介绍与配置
查看>>
三步配置SSH 免密码登录
查看>>
iptables的规则整理使用
查看>>
touch命令
查看>>
php 和mysql 时间转换时间戳的一点问题
查看>>
mt2523 How to configure MT2523 HDK charging curren
查看>>
Active Directory Domain Service
查看>>
OS启动说明
查看>>
ActiveMQ 学习笔记系列
查看>>
[翻译完成] 开源LCD触摸屏驱动
查看>>
webpack 引入css-loader 应对多入口的问题
查看>>
Docker 是什么?
查看>>
【腾讯Bugly干货分享】从0到1打造直播 App
查看>>
Java static关键字
查看>>
关于Tps和Qps的个人理解
查看>>
iOS手动加载Main.storyboard
查看>>
用友U8:数据源读取失败,用户sa无法登录
查看>>
郭霖老师最全Glide大百科
查看>>
ARouter解析七:降级策略
查看>>
【Android】TextView的文字长度测量及各种padding解析
查看>>