Вход Регистрация
* -=(C)DRU987=- (Dev)

Система безопасности и фильтровки данных

  1. /*задаём основные настройки и стерлизацию*/
  2.  
  3. $usehtaccessbans = 1;# 1 = изменить .htaccess запретить IP-адреса, 0 = не запрещать IP-адреса.
  4. $filterGETvars = 1;# 1 = стерилизовать HTML-теги в GET переменных, 0 = нет
  5. $filterCOOKIEvars = 1; # 1 = стерилизовать HTML-теги в Cookie переменных, 0 = не
  6. $filterPOSTvars = 0; # 1 = стерилизовать HTML-теги в POST переменных, 0 = не
  7. $extraPOSTprotection = 1; # 1 = использовать дополнительную защиту POST, 0 = не
  8. $extraGETprotection = 0; # 1 = использовать дополнительную защиту GET, 0 = не (не рекомендуется!)
  9. $checkmultiPOST = 1; # 1 = разрешить только maxmultiPOST число последовательных сообщений, 0 = не волнует,
  10. $maxmultiPOST = 4; # Максимальное количество операций POST подряд, если checkmultipost включен.
  11. $zipcompress = 0; # 1 = Сжимать-страниц с использованием библиотеки GZIP (меньшую пропускную способность, что выше, CPU), 0 = нет
  12. $compresslevel = 9; # Уровень сжатия для zipcompressing от 1 (низкая) до 9 (максимум)
  13. $cpuloadmonitor = 0; # 1 = блокировать доступ, если в течение определенного загрузки системы, 0 = нет
  14. $cpumaxload = 10,0; # Максимальная 5 минут средняя загрузка системы перед блокированием доступа
  15. $ccisessionpath = ""; # Если не пустой, задает путь к каталогу для хранения файлов сессий.
  16.  
  17. /* шифрования и кодирование переменных*/
  18. $javababble = 0; # 1 = использовать кодировку / Шифрование (должен быть включен любой), 0 = нет
  19. $javaencrypt = 0; # У фактического Шифрование HTML, а не только избежать (предупреждение: может замедлить дисплей)
  20. $preservehead = 0; # 1 = Только кодирования / шифрования между телом теги, 0 = кодирование / шифрование весь документ
  21. /*Проверить в-Script переопределения*/
  22.  
  23. if (isset($zipoverride)) {
  24. if (!isset($_REQUEST["zipoverride"])) {
  25. $zipcompress = $zipoverride;
  26. unset($zipoverride);
  27. }
  28. }
  29.  
  30. if (isset($babbleoverride)) {
  31. if (!isset($_REQUEST["babbleoverride"])) {
  32. $javababble = $babbleoverride;
  33. unset($babbleoverride);
  34. }
  35. }
  36.  
  37. ##################
  38. #
  39. # Function: CCIJavaBabble
  40. #
  41. # Usage: Takes some HTML, url-encodes it (jumbles it) then returns the javascript needed to display it properly.
  42. #
  43. ##################
  44.  
  45. function CCIJavaBabble($myoutput) {
  46. global $mycrypto, $myalpha2, $javaencrypt, $preservehead;
  47. $s = $myoutput;
  48. $s = ereg_replace("\n","",$s);
  49.  
  50. if ($preservehead) {
  51. eregi("(^.+<body[^>]*>)",$s,$chunks);
  52. $outputstring = $chunks[1];
  53. eregi_replace($headpart,"",$s);
  54.  
  55. eregi("(</body[^>]*>.*)",$s,$chunks);
  56. $outputend = $chunks[1];
  57. eregi_replace($footpart,"",$s);
  58. } else {
  59. $outputstring = "";
  60. $outputend = "";
  61. }
  62.  
  63. if ($javaencrypt) {
  64. $s = strtr($s,$myalpha2,$mycrypto);
  65. $s = rawurlencode($s);
  66. $outputstring .= "<script>var cc=unescape('$s'); ";
  67. $outputstring .= "var index = document.cookie.indexOf('" . md5($_SERVER["REMOTE_ADDR"] . $_SERVER["SERVER_ADDR"]) . "='); " .
  68. "var aa = '$myalpha2'; " .
  69. "if (index > -1) { " .
  70. " index = document.cookie.indexOf('=', index) + 1; " .
  71. " var endstr = document.cookie.indexOf(';', index); " .
  72. " if (endstr == -1) endstr = document.cookie.length; " .
  73. " var bb = unescape(document.cookie.substring(index, endstr)); " .
  74. "} " .
  75. "cc = cc.replace(/[$myalpha2]/g,function(str) { return aa.substr(bb.indexOf(str),1) }); document.write(cc);";
  76. } else {
  77. $outputstring .= "<script>document.write(unescape('" . rawurlencode($s) . "'));";
  78. }
  79. $outputstring .= "</script><noscript>You must enable Javascript in order to view this webpage.</noscript>" . $outputend;
  80.  
  81. return $outputstring;
  82. }
  83.  
  84. ##################
  85. #
  86. # Function: CCIClearSession
  87. #
  88. # Format: CCIClearSession()
  89. # Returns: Nothing
  90. #
  91. # Usage: Clears all the data out of the session record other than data used for this script
  92. #
  93. ##################
  94.  
  95. function CCIClearSession() {
  96. $getvariables = array_keys($_SESSION);
  97. $count = 0;
  98. while($count < count($getvariables)) {
  99. if (substr($getvariables[$count],0,7) != "ccisec-") {
  100. session_unregister($getvariables[$count]);
  101. if (ini_get('register_globals')) unset($$getvariables[$count]);
  102. }
  103. $count++;
  104. }
  105. }
  106.  
  107. ##################
  108. #
  109. # Function: CCIBanIP
  110. #
  111. # Format: CCIBanIP(IPAddress)
  112. # Returns: Nothing
  113. #
  114. # Usage: Will open and add a deny line to the .htaccess file in the same directory to deny all
  115. # accessing by a given IP address.
  116. #
  117. ##################
  118.  
  119. function CCIBanIP($banip) {
  120. $filelocation = ".htaccess";
  121. $limitend = "# End of CCI Security Section\n";
  122. $newline = "deny from $banip\n";
  123. if (file_exists($filelocation)) {
  124. $mybans = file($filelocation);
  125. $lastline = "";
  126. if (in_array($newline,$mybans)) exit();
  127. if (in_array($limitend,$mybans)) {
  128. $i = count($mybans)-1;
  129. while ($mybans[$i] != $limitend) {
  130. $lastline = array_pop($mybans) . $lastline;
  131. $i--;
  132. }
  133. $lastline = array_pop($mybans) . $lastline;
  134. $lastline = array_pop($mybans) . $lastline;
  135. $lastline = array_pop($mybans) . $lastline;
  136. array_push($mybans,$newline,$lastline);
  137. } else {
  138. array_push($mybans,"\n\n# CCI Security Script\n","<Limit GET POST>\n","order allow,deny\n",$newline,"allow from all\n","</Limit>\n",$limitend);
  139. }
  140. } else {
  141. $mybans = array("# CCI Security Script\n","<Limit GET POST>\n","order allow,deny\n",$newline,"allow from all\n","</Limit>\n",$limitend);
  142. }
  143. $myfile = fopen($filelocation,"w");
  144. fwrite($myfile,implode($mybans,""));
  145. fclose($myfile);
  146.  
  147. }
  148.  
  149. ##################
  150. #
  151. # Function: CCIFloodCheck
  152. #
  153. # Format: CCIFloodCheck("identifier",interval,threshold)
  154. # Returns: 1 if requested without minimum interval, a threshold number of times. 0 if not.
  155. #
  156. # Usage: For functions that require flood control pass a unique identifier, the minimum number of
  157. # seconds that should be waited between repeats of the function, and a number of times that
  158. # function can be called too quickly before it sets off the flood trapping.
  159. #
  160. ##################
  161.  
  162. function CCIFloodCheck($identifier,$interval,$threshold=1) {
  163. $myresult = 0;
  164. if (isset($_SESSION["ccisec-" . $identifier])) {
  165. if ($_SESSION["ccisec-" . $identifier] > (time()-$interval)) {
  166. if ($threshold<2) {
  167. $myresult = 1;
  168. } else {
  169. if (!isset($_SESSION["ccisec-" . $identifier . "-counter"])) {
  170. $_SESSION["ccisec-" . $identifier . "-counter"] = 1;
  171. } else {
  172. $_SESSION["ccisec-" . $identifier . "-counter"]++;
  173. if ($_SESSION["ccisec-" . $identifier . "-counter"] >= $threshold) {
  174. $myresult = 1;
  175. }
  176. }
  177. }
  178. }
  179. $_SESSION["ccisec-" . $identifier] = time();
  180. }
  181. return $myresult;
  182. }
  183.  
  184. ################################################################################
  185.  
  186. if (eregi("ccisecurity\.php",$_SERVER["SCRIPT_NAME"])) exit();
  187.  
  188. if ($ccisessionpath != "") session_save_path($ccisessionpath);
  189. session_name(md5($_SERVER["REMOTE_ADDR"] . $_SERVER["HTTP_HOST"] . "CCI"));
  190.  
  191. ini_set("session.use_only_cookies","1");
  192. ini_set("session.use_trans_sid","0");
  193.  
  194. if (($zipcompress) && (eregi("gzip",$_SERVER["HTTP_ACCEPT_ENCODING"]))) {
  195. ini_set("zlib.output_compression","On");
  196. ini_set("zlib.output_compression_level",$compresslevel);
  197. ob_start("ob_gzhandler");
  198. }
  199. if ($javababble) {
  200. if ($javaencrypt) {
  201. $myalpha = array_merge(range("a","z"),range("A","Z"),range("0","9"));
  202. $myalpha2 = implode("",$myalpha);
  203. shuffle($myalpha);
  204. $mycrypto = implode("",$myalpha);
  205. setcookie(md5($_SERVER["REMOTE_ADDR"] . $_SERVER["SERVER_ADDR"]),$mycrypto);
  206. unset($myalpha);
  207. }
  208. ob_start("cciJavaBabble");
  209. }
  210.  
  211. if (substr_count($_SERVER["SERVER_NAME"],".")>1) {
  212. $cookiedomain = eregi_replace("^[^\.]+\.",".",$_SERVER["SERVER_NAME"]);
  213. } else $cookiedomain = "." . $_SERVER["SERVER_NAME"];
  214.  
  215. $ip = $_SERVER["REMOTE_ADDR"];
  216. $mykeyname = md5($_SERVER["REMOTE_ADDR"] . $_SERVER["HTTP_HOST"] . $_SERVER["DOCUMENT_ROOT"] . "CCI");
  217. $myposthashname = md5($_SERVER["REMOTE_ADDR"] . $_SERVER["HTTP_HOST"] . $_SERVER["PATH"] . "CCI");
  218.  
  219. $myhash = md5($_SERVER["REMOTE_ADDR"] . $_SERVER["HTTP_USER_AGENT"] .
  220. $_SERVER["HTTP_HOST"] . $_SERVER["DOCUMENT_ROOT"] .
  221. $_SERVER["SERVER_SOFTWARE"] . $_SERVER["PATH"] . "X");
  222.  
  223. $mysession = md5($_SERVER["REMOTE_ADDR"] . $_SERVER["HTTP_HOST"]);
  224. session_id($mysession);
  225.  
  226. if (!isset($_SESSION["ccisec-errors"])) $_SESSION["ccisec-errors"] = 0;
  227. if ($_SESSION["ccisec-errors"]>=10) {
  228. CCIBanIP($ip);
  229. exit();
  230. }
  231.  
  232. if ($_SESSION["ccisec-myhash"] != $myhash) {
  233. $_SESSION["ccisec-myhash"] = $myhash;
  234. $_SESSION["ccisec-errors"]++;
  235. Header("Location: http:// . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
  236. exit();
  237. }
  238.  
  239. if ((!isset($_COOKIE[$mykeyname])) || ($_COOKIE[$mykeyname] != $myhash)) {
  240.  
  241. if (!isset($_SESSION["ccisec-nocookie"])) {
  242. $_SESSION["ccisec-nocookie"] = 1;
  243. } else {
  244. $_SESSION["ccisec-nocookie"]++;
  245. }
  246.  
  247. if (($usehtaccessbans) && ($_SESSION["ccisec-nocookie"]>10)) CCIBanIP($ip);
  248.  
  249. setcookie($mykeyname,$myhash,0,"/",$cookiedomain);
  250.  
  251. if ($_SESSION["ccisec-nocookie"]>2) {
  252. echo "<b><h1>Access Denied</h1><br><br>You must enable cookies in order to access this website. Please do so before returning, as continued attempts to access without cookies may result in a banning of this ip ($ip).</b>";
  253. exit();
  254. }
  255. if ($extraGETprotection) {
  256. $_SESSION["ccisec-hash"] = md5(uniqid(time()));
  257. setcookie($myposthashname,$_SESSION["ccisec-hash"],0,"/",$cookiedomain);
  258. }
  259. CCIClearSession();
  260. Header("Location: http:// . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
  261. exit();
  262. } else $_SESSION["ccisec-nocookie"] = 0;
  263.  
  264. if (($usehtaccessbans) && ($_SESSION["ccisec-fastaccesses"]>40)) CCIBanIP($ip);
  265.  
  266. if ($_SESSION["ccisec-fastaccesses"]>10) {
  267. if ((time()-60) < $_SESSION["ccisec-lastaccess"]) {
  268. echo "<b><h1>Access Denied</h1><br><br>There have been too many rapid requests from this IP address ($ip). You must now wait a full 60 seconds before accessing this site again.</b>";
  269. $_SESSION["ccisec-fastaccesses"]++;
  270. $_SESSION["ccisec-lastaccess"]=time();
  271. exit();
  272. }
  273. }
  274.  
  275. if (!isset($_SESSION["ccisec-lastaccess"])) {
  276. $_SESSION["ccisec-lastaccess"]=time();
  277. } else {
  278. if ((time()-2) < $_SESSION["ccisec-lastaccess"]) {
  279. if (!isset($_SESSION["ccisec-fastaccesses"])) $_SESSION["ccisec-fastaccesses"] = 0;
  280. $_SESSION["ccisec-fastaccesses"]++;
  281. } else {
  282. $_SESSION["ccisec-fastaccesses"] = 0;
  283. }
  284. $_SESSION["ccisec-lastaccess"]=time();
  285. }
  286.  
  287. if ($_SERVER["REQUEST_METHOD"] == "POST") {
  288.  
  289. if ($checkmultiPOST) {
  290. if (($_SESSION["ccisec-lastoperation"] == "POST") && ($_SESSION["ccisec-opcount"] >= $maxmultiPOST)) {
  291. echo "<b><h1>Access Denied</h1><br><br>You may not make multiple POST operations in sequence - please return to the website and try again.</b>";
  292. $_SESSION["ccisec-errors"]++;
  293. exit();
  294. }
  295. }
  296.  
  297. if ($extraPOSTprotection) {
  298. if ((!isset($_COOKIE[$myposthashname])) || ($_COOKIE[$myposthashname] != $_SESSION["ccisec-hash"])) {
  299. echo "<b><h1>Access Denied</h1><br><br>Your browser did not send the correct security data needed to complete a POST operation. Make sure that you have cookies enabled and then try again, or contact the administration if you feel you are receiving this message in error.</b>";
  300. $_SESSION["ccisec-errors"]++;
  301. exit();
  302. }
  303. }
  304. } else if (($extraGETprotection) && ($_SERVER["REQUEST_METHOD"] == "GET")) {
  305. if ((!isset($_COOKIE[$myposthashname])) || ($_COOKIE[$myposthashname] != $_SESSION["ccisec-hash"])) {
  306. echo "<b><h1>Access Denied</h1><br><br>Your browser did not send the correct security data needed to complete a GET operation. Make sure that you have cookies enabled and then try again, or contact the administration if you feel you are receiving this message in error.</b>";
  307. $_SESSION["ccisec-errors"]++;
  308. exit();
  309. }
  310. } else if ($_SERVER["REQUEST_METHOD"] != "GET") {
  311. exit();
  312. }
  313.  
  314. if (($extraPOSTprotection) || ($extraGETprotection)) {
  315. srand(time());
  316. $_SESSION["ccisec-hash"] = md5(uniqid(time()));
  317. setcookie($myposthashname,$_SESSION["ccisec-hash"],0,"/",$cookiedomain);
  318. }
  319.  
  320. if ($_SESSION["ccisec-lastoperation"] == $_SERVER["REQUEST_METHOD"]) {
  321. if (!isset($_SESSION["ccisec-opcount"])) {
  322. $_SESSION["ccisec-opcount"] = 1;
  323. } else {
  324. $_SESSION["ccisec-opcount"]++;
  325. }
  326. } else $_SESSION["ccisec-lastoperation"] = $_SERVER["REQUEST_METHOD"];
  327.  
  328. # Make special characters safe in any GET based cgi variables.
  329.  
  330. if ($filterGETvars) {
  331. $getvariables = array_keys($_GET);
  332. $count = 0;
  333. while($count < count($getvariables)) {
  334. $_GET[$getvariables[$count]] = htmlspecialchars($_GET[$getvariables[$count]]);
  335. if (ini_get('register_globals')) $$getvariables[$count] = $_GET[$getvariables[$count]];
  336. $count++;
  337. }
  338. }
  339.  
  340. if ($filterPOSTvars) {
  341. $getvariables = array_keys($_POST);
  342. $count = 0;
  343. while($count < count($getvariables)) {
  344. $_POST[$getvariables[$count]] = htmlspecialchars($_POST[$getvariables[$count]]);
  345. if (ini_get('register_globals')) $$getvariables[$count] = $_POST[$getvariables[$count]];
  346. $count++;
  347. }
  348. }
  349.  
  350. if ($filterCOOKIEvars) {
  351. $getvariables = array_keys($_COOKIE);
  352. $count = 0;
  353. while($count < count($getvariables)) {
  354. $_COOKIE[$getvariables[$count]] = htmlspecialchars($_COOKIE[$getvariables[$count]]);
  355. if (ini_get('register_globals')) $$getvariables[$count] = $_COOKIE[$getvariables[$count]];
  356. $count++;
  357. }
  358. }
  359.  
  360. if ($cpuloadmonitor) {
  361. $myshelldata = shell_exec("uptime");
  362. $myshelldata = eregi_replace(".*average.*: ","",$myshelldata);
  363. $myshelldata = eregi_replace(", .*","",$myshelldata);
  364. if ($myshelldata >= $cpumaxload) {
  365. echo "<b><h1>Access Denied</h1><br><br>The server is currently too busy to serve your request. We apologize for the inconvenience.</b>";
  366. exit();
  367. }
  368. unset($myshelldata);
  369. }
  370.  
  371. unset($count);
  372. unset($getvariables);
  373. unset($ip);
  374. unset($cookiedomain);
  375. unset($mykeyname);
  376. unset($myposthashname);
  377. unset($myhash);
  378. unset($mysession);
  379.  
  380. $_SESSION["ccisec-errors"] = 0;
» Описание: Простая система безопасности для использоваия в существующих скриптах, содержит защиту от автоматических потоков запросов, фильтрует вводимую пользователем информация для удаления тегов, корректировки htaccess , блокировки IP-адресов, также содержит простые фукции которые вы можете использовать в своих скриптах
» Время добавления: 25 Апр 2015 в 15:29
» Посмотров: 2042
» textarea
» Рейтинг: [+2 | -0]
Комментарии [0]
Онлайн: 1
Реклама