Anti Ddos Em Php 28.11.11 14:32
Primeiro : Abra O Bloco De Notas e Cole esse Codigo :
Segundo : Salve como anti_ddos.php
Terceiro : Coloque Esse Codigo Abaixo No arquivo Index.php :
Dabaixo Da Tag :
~~ Print ~~
[Tens de ter uma conta e sessão iniciada para poderes visualizar esta imagem]
Creditos :
Pixel team e kekomundo
Obs: Meu Primeiro Post No Forum !!!
- Código:
#!/usr/bin/php -q
<?php
/*
* ----------------------------------------------------------------
* AUTHOR: ViniciusMentez
* DATE: 15th June 2005
* FILE: AntiDoS
* PURPOSE:
* offending IP
* CONTACT: [Tens de ter uma conta e sessão iniciada para poderes visualizar este link]
* COPYRIGHT: Copyright to Prism Hosting 2005
* DONATE: If you liked this script and thought it helped you,
* please feel free to make a small donation via
* paypal to: [Tens de ter uma conta e sessão iniciada para poderes visualizar este link]
*
* You might wonder what the point in donating would
* be, well the main purpose of donating would be
* either as a small thank-you or as an encouragement
* for me to develop this further so that it might be
* improved to help you, the user.
*
* COMMENTS: Please send suggestions and comments to
* david@thewishingtree.me.uk
*
* VERSION: 1.0
* ----------------------------------------------------------------------
*/
// CONFIGURATION VARIABLES:
// The following variable is the one that will need tweaking per server.
// If legitament IP's are being banned raise this number. Or if it isn't
// having the desired effect, lower this number.
$maxConnsPerIP = 80;
// Probably best not editing any of the following. Unless you wish to
// Add more ports. An example of adding more ports:
// $ports = array(25, 80, 443);
// If more ports are added, it is advisable to increase $maxConnsPerIP.
$ports = array(80);
// These do not normally need changed, however please check them!
// The root directory where the logs will reside.
$logRoot = "/var/log/";
// The name of the log containing all ban information.
// Set to 0 to disable.
$logNameBan = "antidos.ban";
// The name of the log containing run information.
// Set to 0 to disable.
$logNameRun = "antidos.run";
// Location of netstat
$netstatCmd = "/bin/netstat -neepa";
// Location of information from netstat, this must be set!
$netstatOutput = "./netstat.out";
// The APF deny command.
$apfDeny = "/usr/local/sbin/apf -d ";
// The APF deny_hosts.rules file
$apfDenyHostRules = "/etc/apf/deny_hosts.rules";
// Format of date, using PHP's date() function (www.php.net)
$dateFormat = "m.d.y g:i a";
// DO NOT EDIT BELOW THIS LINE
// ----------------------------------------------------------------------
// Define an object to store all the info.
class NetStatInfo
{
var $proto;
var $recvq;
var $sendq;
var $localaddr = array();
var $foreignaddr = array();
var $state;
var $user;
var $inode;
var $pid;
var $program;
function NetStatInfo()
{
// Empty Contructor
}
}
// Storage container for all the NetStatInfo's
$connections = array();
$num = 0;
// Run the netstat command: "/bin/netstat -neepa > netstat.out"
exec($netstatCmd . " > " . $netstatOutput);
// Read the file into an array of lines
$lines = file($netstatOutput);
// Parse each line
foreach ($lines as $line_num => $line)
{
// Only parse line if the first 3 chars are TCP (or UDP?)
if (eregi("(tcp)|(udp)", $line))
{
// A very important line, DO NOT TOUCH!
$regexp = "(tcp|udp|raw)([[:space:]]+)([0-9]+)([[:space:]]+)([0-9]+)([[:space:]]+)([0-9\.:\*]+)([[:space:]]+)([0-9\.:\*]+)([[:space:]]+)([A-Za-z0-9_]+)([[:space:]]+)([0-9]+)([[:space:]]+)([0-9]+)([[:space:]]+)(.+)";
$args = array();
if (eregi($regexp, $line, $args))
{
$connections[$num] = new NetStatInfo();
$localaddr = explode(":", $args[7]);
$foreignaddr = explode(":", $args[9]);
$connections[$num]->proto = $args[1];
$connections[$num]->recvq = $args[3];
$connections[$num]->sendq = $args[5];
$connections[$num]->localaddr[0] = $localaddr[0];
$connections[$num]->localaddr[1] = $localaddr[1];
$connections[$num]->foreignaddr[0] = $foreignaddr[0];
$connections[$num]->foreignaddr[1] = $foreignaddr[1];
$connections[$num]->state = $args[11];
$connections[$num]->user = $args[13];
$connections[$num]->inode = $args[15];
// TODO: Parse program info, into program name and pid (seperator = /)
$connections[$num]->pid = $args[17];
$connections[$num]->program = $args[17];
$num++;
}
}
}
// Counter array - for every new ip found - it will be added to the array, and its counter incremented
// i.e. $counter[0][0] = 192.168.1.100
// $counter[0][1] = 13
$counter = array();
$num_conns = $num;
$num = 0;
// Flag to determine if the IP was found in the counter.
$found = false;
// Check for multiple connections on the following local ports.
// *** Now a configuration setting at top
// Determine if there are multiple records!
for ($i = 0; $i < $num_conns; $i++)
{
$found = false;
for ($j = 0; $j < count($counter); $j++)
{
if ($counter[$j][0] == $connections[$i]->foreignaddr[0]
&& in_array($connections[$i]->localaddr[1], $ports)
&& ($connections[$i]->status != "TIME_WAIT"))
{
// IP already exists in counter array, (incr. count)
$counter[$j][1]++;
$found = true;
}
}
if (!$found)
{
if (in_array($connections[$i]->localaddr[1], $ports))
{
// IP wasn't found in counter array, so add it.
$counter[$num] = array();
$counter[$num][0] = $connections[$i]->foreignaddr[0];
$counter[$num][1] = 1;
$num++;
}
}
}
// Flag to denote an IP was banned
$banned = false;
$bancount = 0;
// Use the counter array to ban any users over X connections
for ($i = 0; $i < count($counter); $i++)
{
if ($counter[$i][1] > $maxConnsPerIP)
{
// BAN IP IN APF
exec($apfDeny . $counter[$i][0]);
// Add comment to APF deny_hosts.rules
$apfComment = "echo \"# {AntiDoS - ".$counter[$i][0]."\t- ".$counter[$i][1]." open connections\t- ".date($dateFormat)."}\"";
exec($apfComment . " >> " . $apfDenyHostRules);
$banned = true;
$logComment = "echo \"** Banned " . $counter[$i][0] . " - " . $counter[$i][1] . " open connections. (" . date($dateFormat) . ")\" >> " . $logRoot . $logNameBan;
exec($logComment);
$bancount++;
}
}
if ($banned)
{
exec("echo \"\tBanned a total of $bancount IPs.\" >> " . $logRoot . $logNameRun);
exec("echo \"\tRestarting APF\" >> " . $logRoot . $logNameRun);
exec("service apf restart");
}
exec("echo -e \"Test complete: ".date($dateFormat)."\n----------------\" >> " . $logRoot . $logNameRun);
?>
<?php
define ('BLACKLIST','black.list');
$list=file(BLACKLIST);
foreach ($list as $addr) {
$addr=trim($addr);
$host_addr=$_SERVER['REMOTE_ADDR'];
// Semplice indirizzo IP
if ($host_addr==$addr)
die ("Your IP is {$addr} and you're not allowed to view this page\n");
// Subnet di classe C
else if (preg_match('/(\d+\.\d+\.\d+)\.0\/24/',$addr,$sub)) {
$subnet=trim($sub[1]);
if (preg_match("/^{$subnet}/",$host_addr))
die ("Your IP is {$host_addr} and you're not allowed to view this page\n");
}
// Subnet di classe B
else if (preg_match('/(\d+\.\d+)\.0\.0\/16/',$addr,$sub)) {
$subnet=trim($sub[1]);
if (preg_match("/^{$subnet}/",$host_addr))
die ("Your IP is {$host_addr} and you're not allowed to view this page\n");
}
// Subnet di classe A
else if (preg_match('/(\d+)\.0\.0\.0\/8/',$addr,$sub)) {
$subnet=trim($sub[1]);
if (preg_match("/^{$subnet}/",$host_addr))
die ("Your IP is {$host_addr} and you're not allowed to view this page\n");
}
}
?>
<?php
/*
CHMOD /iplog/ to 777
Create and CHMOD /iplog/iplogfile.dat to 666
add the following line in any important .php file in the same directory as your anti_dos.php file so it can check IPs when that file is loaded, best example is index.php if you have it.
include("anti_dos.php"); //anti-DoS, prevents rapid accessing
if you have a known cookie on your site,
you can use this, otherwise just ignore this, it will set a different limit
for people with this cookie
I use yourothercookie as the cookie ID for the forum, my forum uses ID
greater than 0 for all members and -1 for guests and members who have logged out,
so making it match greater than zero means members will get better access and
guests with or without cookies won't
Also I use these cookies in the "flood alert" emails to make sure an important user didn't get banned. Someone could fake a cookie, so always be suspicious. Tez
*/
$cookie = $_COOKIE['yourcookie'];
$othercookie = $_COOKIE['yourothercookie'];
if($cookie && $othercookie > 0) $iptime = 20; // Minimum number of seconds between visits for users with certain cookie
else $iptime = 10; // Minimum number of seconds between visits for everyone else
$ippenalty = 60; // Seconds before visitor is allowed back
if($cookie && $othercookie > 0)$ipmaxvisit = 30; // Maximum visits, per $iptime segment
else $ipmaxvisit = 20; // Maximum visits per $iptime segment
$iplogdir = "./iplog/";
$iplogfile = "iplog.dat";
$ipfile = substr(md5($_SERVER["REMOTE_ADDR"]), -2);
$oldtime = 0;
if (file_exists($iplogdir.$ipfile)) $oldtime = filemtime($iplogdir.$ipfile);
$time = time();
if ($oldtime < $time) $oldtime = $time;
$newtime = $oldtime + $iptime;
if ($newtime >= $time + $iptime*$ipmaxvisit)
{
touch($iplogdir.$ipfile, $time + $iptime*($ipmaxvisit-1) + $ippenalty);
$oldref = $_SERVER['HTTP_REFERER'];
header("HTTP/1.0 503 Service Temporarily Unavailable");
header("Connection: close");
header("Content-Type: text/html");
echo "<html><body bgcolor=#999999 text=#ffffff link=#ffff00>
<font face='Verdana, Arial'><p><b>
<h1>Temporary Access Denial</h1>Too many quick page views by your IP address (more than ".$ipmaxvisit." visits within ".$iptime." seconds).</b>
";
echo "
Please wait ".$ippenalty." seconds and reload.</p></font></body></html>";
touch($iplogdir.$iplogfile); //create if not existing
$fp = fopen($iplogdir.$iplogfile, "a");
$yourdomain = $_SERVER['HTTP_HOST'];
if ($fp)
{
$useragent = "<unknown user agent>";
if (isset($_SERVER["HTTP_USER_AGENT"])) $useragent = $_SERVER["HTTP_USER_AGENT"];
fputs($fp, $_SERVER["REMOTE_ADDR"]." ".date("d/m/Y H:i:s")." ".$useragent."\n");
fclose($fp);
$yourdomain = $_SERVER['HTTP_HOST'];
//the @ symbol before @mail means 'supress errors' so you wont see errors on the page if email fails.
if($_SESSION['reportedflood'] < 1 && ($newtime < $time + $iptime + $iptime*$ipmaxvisit))
@mail('flood_alert@'.$yourdomain, 'site flooded by '.$cookie.' '
.$_SERVER['REMOTE_ADDR'],'http://'.$yourdomain.' rapid website access flood occured and ban for IP '.$_SERVER['REMOTE_ADDR'].' at http://'.$yourdomain.$_SERVER['REQUEST_URI'].' from '.$oldref.' agent '.$_SERVER['HTTP_USER_AGENT'].' '
.$cookie.' '.$othercookie, "From: ".$yourdomain."\n");
$_SESSION['reportedflood'] = 1;
}
exit();
}
else $_SESSION['reportedflood'] = 0;
//echo("loaded ".$cookie.$iplogdir.$iplogfile.$ipfile.$newtime);
touch($iplogdir.$ipfile, $newtime); //this just updates the IP file access date or creates a new file if it doesn't exist in /iplog
?>
Segundo : Salve como anti_ddos.php
Terceiro : Coloque Esse Codigo Abaixo No arquivo Index.php :
- Código:
<?php include("anti_ddos.php"); ?>
Dabaixo Da Tag :
- Código:
<head>
~~ Print ~~
[Tens de ter uma conta e sessão iniciada para poderes visualizar esta imagem]
Creditos :
Pixel team e kekomundo
Obs: Meu Primeiro Post No Forum !!!