drutjkpsr67393592 2011-11-05 12:09
浏览 144
已采纳

如何使用php检测和禁止攻击ips

I have a web hosting that does not allow to edit iptables. From to time I have light (about 300 requests/sec) DoS attacks (usually not distributed). I decided to write a PHP script that will block those ips. First I tried to store all requests for last 10 secs in database and look up abusing addresses for every request. But I quickly realized that this way I have to do at least 1 request to database for every DoS request, and it's not good. Then I optimized this approach as follows:

Read 'deny.txt' with blocked ip's
If it contains request ip, then die()
--- at this point we have filtered out all known attacking ips ---
store requesting ip in database
clean all requests older than 10 secs
count requests from this ip, if it is greater than threshold, add it to 'deny.txt'

This way, new attacking ip will make only Threshold requests to database and then gets blocked.

So, the question is, does this approach have optimal performance? Is there a better way to do this task?

  • 写回答

2条回答 默认 最新

  • dongtao9095 2011-11-22 12:43
    关注

    Here's my code:

    $ip = $_SERVER['REMOTE_ADDR'];
    
    // Log ip
    $query = "INSERT INTO Access (ip) VALUES ('$ip')";      
    mysql_query($query) or HandleException("Error on logging ip access: " . mysql_error() . "; Query: " . $query);  
    
    // Here should be database cleanup code
    
    // Count requests
    $query = "SELECT COUNT(*) FROM Access WHERE ip='$ip' AND time > SUBTIME(NOW(), '00:01:00')";        
    $result = mysql_query($query) or HandleException("Error on getting ip access count: " . mysql_error() . "; Query: " . $query);  
    $num = mysql_fetch_array($result);
    $accesses = $num[0];
    
    // Ban ip's that made more than 1000 requests in 1 minute
    if($accesses > 1000)
    {
        file_put_contents('.htaccess', 'deny from ' . $ip . "
    ", FILE_APPEND | LOCK_EX);
    }
    

    and .htaccess stub:

    order deny,allow
    deny from 111.222.33.44
    deny from 55.66.77.88
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用verilog实现tanh函数和softplus函数
  • ¥15 Hadoop集群部署启动Hadoop时碰到问题
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 QTableWidget重绘程序崩溃
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站