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条)

报告相同问题?

悬赏问题

  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?