搜索
查看: 603|回复: 0

过滤XSS攻击和SQL注入函数

[复制链接]

432

主题

573

帖子

2543

积分

核心成员

Rank: 8Rank: 8

积分
2543
发表于 2014-4-9 16:22:48 | 显示全部楼层 |阅读模式
  1. /**
  2. +----------------------------------------------------------
  3. * The goal of this function is to be a generic function that can be used to parse almost any input and     * render it xss safe. For more information on actual XSS attacks, check out http://ha.ckers.org/xss.html. * Another excellent site is the XSS Database which details each attack and how it works.
  4. * XSS过滤
  5. +----------------------------------------------------------
  6. * @param mixed $value 变量
  7. +----------------------------------------------------------
  8. * @return mixed 过滤后的字符串
  9. +----------------------------------------------------------
  10. */
  11. function RemoveXSS($val) {
  12. // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
  13. // this prevents some character re-spacing such as <java\0script>
  14. // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some          // inputs
  15. $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);
  16. // straight replacements, the user should never need these since they're normal characters
  17. // this prevents like <IMG SRC=@avascript:alert('XSS')>
  18. $search = 'abcdefghijklmnopqrstuvwxyz';
  19. $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  20. $search .= '1234567890!@#$%^&*()';
  21. $search .= '~`";:?+/={}[]-_|\'\\';
  22. for ($i = 0; $i < strlen($search); $i++) {
  23. // ;? matches the ;, which is optional
  24. // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
  25. // @ @ search for the hex values
  26. $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val);//with a ;
  27. // @ @ 0{0,7} matches '0' zero to seven times
  28. $val = preg_replace('/({0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
  29. }
  30. // now the only remaining whitespace attacks are \t, \n, and \r
  31. $ra1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
  32. $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');
  33. $ra = array_merge($ra1, $ra2);
  34. $found = true; // keep replacing as long as the previous round replaced something
  35. while ($found == true) {
  36. $val_before = $val;
  37. for ($i = 0; $i < sizeof($ra); $i++) {
  38. $pattern = '/';
  39. for ($j = 0; $j < strlen($ra[$i]); $j++) {
  40. if ($j > 0) {
  41. $pattern .= '(';
  42. $pattern .= '(&#[xX]0{0,8}([9ab]);)';
  43. $pattern .= '|';
  44. $pattern .= '|({0,8}([9|10|13]);)';
  45. $pattern .= ')*';
  46. }
  47. $pattern .= $ra[$i][$j];
  48. }
  49. $pattern .= '/i';
  50. $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
  51. $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
  52. if ($val_before == $val) {
  53. // no replacements were made, so exit the loop
  54. $found = false;
  55. }
  56. }
  57. }
  58. return $val;
  59. }
  60. /*
  61. +----------------------------------------------------------
  62. * 函数名称:inject_check()
  63. +----------------------------------------------------------
  64. * 函数作用:检测提交的值是不是含有 sql 注射的字符,防止注射,保护服务器安全
  65. +----------------------------------------------------------
  66. * @param mixed $sql_str: 提交的变量
  67. +----------------------------------------------------------
  68. * @return mixed 返回检测结果,ture or false
  69. +----------------------------------------------------------
  70. */
  71. function inject_check($sql_str) {
  72. return $sql_str = preg_replace('select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile','', $sql_str);    // 进行过滤

  73. /*
  74. +----------------------------------------------------------
  75. * 函数名称:escapeMysql()
  76. * SQL注入主要是提交不安全的数据给数据库来达到攻击目的。为了防止SQL注入攻击,PHP自带一个功能可以对输入的字符串进行处理,可以在较底层对 * 输入进行安全上的初步处理,也即Magic Quotes。(php.ini magic_quotes_gpc)。如果magic_quotes_gpc选项启用,那么输入的字符串    * 中的单引号,双引号和其它一些字符前将会被自动加上反斜杠\。
  77. * 但Magic Quotes并不是一个很通用的解决方案,没能屏蔽所有有潜在危险的字符,并且在许多服务器上Magic Quotes并没有被启用。所以,我们    * 还需要使用其它多种方法来防止SQL注入。许多数据库本身就提供这种输入数据处理功能。例如PHP的MySQL操作函数中有一个叫                 * mysql_real_escape_string()的函数,可将特殊字符和可能引起数据库操作出错的字符转义。
  78. +----------------------------------------------------------
  79. * 函数作用:检测提交的值是不是含有SQL注射的字符,防止注射,保护服务器安全
  80. +----------------------------------------------------------
  81. * @param mixed $sql_str: 提交的变量
  82. +----------------------------------------------------------
  83. * @return mixed 返回检测结果,ture or false
  84. +----------------------------------------------------------
  85. */
  86. function escapeMysql($el){
  87. if(is_array($el))
  88. {
  89. return   array_map("escapeMysql",   $el   );
  90. }else{
  91. /*如果Magic Quotes功用启用    */
  92. if (!get_magic_quotes_gpc()) {
  93. $el = mysql_real_escape_string(trim($el));
  94. }
  95. $el    =    str_ireplace("%5d%5c", "'", $el);
  96. $el = str_replace("_", "\_", $el);    // 把 '_'过滤掉
  97. $el = str_replace("%", "\%", $el);    // 把 '%'过滤掉
  98. $el = nl2br($el);    // 回车转换
  99. return   $el;
  100. }
  101. }
  102. /**
  103. +----------------------------------------------------------
  104. * 变量过滤
  105. +----------------------------------------------------------
  106. * @param mixed $value 变量
  107. +----------------------------------------------------------
  108. * @return mixed
  109. +----------------------------------------------------------
  110. */
  111. function var_filter_deep($value) {
  112. return $value;
  113. if(is_array($value))
  114. {
  115. return $value =   array_map("var_filter_deep",   $value   );
  116. }else{
  117. $value = RemoveXSS($value);
  118. //$value = inject_check($value);
  119. $value = escapeMysql($value);
  120. return $value;
  121. }
  122. }
  123. /*
  124. +----------------------------------------------------------
  125. * 函数名称:verify_id()
  126. +----------------------------------------------------------
  127. * 函数作用:校验提交的ID类值是否合法
  128. +----------------------------------------------------------
  129. * 参 数:$id: 提交的ID值
  130. +----------------------------------------------------------
  131. * 返 回 值:返回处理后的ID
  132. +----------------------------------------------------------
  133. */
  134. function verify_id($id=null) {
  135. if (!$id) { exit('没有提交参数!'); }    // 是否为空判断
  136. elseif (inject_check($id)) { exit('提交的参数非法!'); }    // 注射判断
  137. elseif (!is_numeric($id)) { exit('提交的参数非法!'); }    // 数字判断
  138. $id = intval($id);    // 整型化
  139. return $id;
  140. }
  141. /**
  142. +----------------------------------------------------------
  143. * 变量安全过滤
  144. +----------------------------------------------------------
  145. * @static
  146. * @access public
  147. +----------------------------------------------------------
  148. * @return string
  149. +----------------------------------------------------------
  150. */
  151. function varFilter ()
  152. {
  153. $_SERVER = array_map(   "var_filter_deep", $_SERVER );
  154. $_REQUEST = array_map(   "var_filter_deep", $_REQUEST);
  155. $_POST    = array_map(   "var_filter_deep", $_POST   );
  156. $_GET     = array_map(   "var_filter_deep", $_GET    );
  157. $_COOKIE = array_map(   "var_filter_deep", $_COOKIE );
  158. //print_r($_POST);
  159. }
复制代码
您可以更新记录, 让好友们知道您在做什么...
您需要登录后才可以回帖 登录 | Join BUC

本版积分规则

Powered by Discuz!

© 2012-2015 Baiker Union of China.

快速回复 返回顶部 返回列表