A PHP script for dealing with DoS attacks

One or my PHP web application had a DoS attack recently so I tried hard to fix it and it was not that hard becasue a lot of resources out there abuot DoS and how to fix it. This script is to let you deal with DoS attack

<?php

## Functions ##

function getIP($line) {
    ereg("[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}",$line,$regMatch);
    $ip = $regMatch[0];
    if($ip) return $ip; else return "false";
}

function processString($string, $size = 18) {
    $string = "[ ".$string;
    $length = strlen($string);
    $toAdd = $size - $length;

    for($x = 0; $x < $toAdd; $x++) {
        $string = $string." ";
    }
    $string = $string."]";
    return $string;
}

## Code ##

while (true) {
    $cmd = "netstat -n | awk '{ print $5 }'";
    exec($cmd, $netstatArray);
    $ipArray = array();

    foreach($netstatArray as $line) {
        $ip = getIP($line);
        if($ip != "false" && ip != "127.0.0.1") {
            if(array_key_exists($ip, $ipArray))
                         {
                                    $ipArray[$ip]+=1;
                         }
                         else // if not, count=1
                         {
                                    $ipArray[$ip] = 1;
                         }
        }
    }

    asort($ipArray);

    system("clear");
    foreach($ipArray as $ip => $count) {
        if ($count < 15)
            continue;
        echo processString($ip);
        echo "\t" .processString(gethostbyaddr($ip), 55);
        echo "\tTimes Accessed: " .$count ."\n";
    }

    echo str_repeat("-", 50) ."\n";
    exec("top -n 1", $top_str);
    preg_match("#load average:(.+)#i", $top_str[0], $match);
    echo "Load Average: " .$match[1] ."\n";
    echo str_repeat("-", 50) ."\n";
    echo 'Showing $count >= 15: (Escape with ctrl+c)' ."\n";

    sleep(10);
}

?>

 

Source : http://codingrecipes.com/a-php-script-for-dealing-with-dos-attacks

Tags: