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

报告相同问题?

悬赏问题

  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系