草庐IT

PHP、.htaccess、DDoS 和快速请求保护

coder 2024-04-19 原文

我有一个问题,我构建了这个小脚本来检查某个 ip 是否正在淹没我的网站。 当它出现时,我拒绝 .htaccess 文件中的 ip。我的问题是,有人可以告诉我这个脚本是否完全无用或值得尝试...该脚本在配置文件中调用,因此它在每次页面加载时运行。

<?php
#get the visitor ip
$ip = $_SERVER["REMOTE_ADDR"];

#start the session
@session_start();

#check if the ip is banned
if( $_SESSION['~b'] ){

#check if we can open htaccess
$fp = @fopen('./.htaccess','a'); 
    if($fp){
        #add the ip to htaccess
        @fwrite($fp,"\r\ndeny from $ip"); 
        #close
        @fclose($fp);
        #destroy the session
        @session_destroy();
        @mail("my-email","IP Banned","Ip: $ip");
    }
    #let the user know why we deny him or her access
    die('To many requests.');
    }
#get the filename and location
$f = './log/'.@ip2long($ip);

#check if the file exists
if ( @is_file($f) ) {
        #get the last filetime
        $a = @filemtime($f);
        #touch the file, give a new filetime
        @touch($f,time());
        #the ip is not banned
        $_SESSION['~b']  = false;
        #add the time diff
        $_SESSION['~r'] += @time()-$a;
        #add the latest hit
        $_SESSION['~h'] += 1;
    }else{
        #create the file if it doesn't exist
        @file_put_contents($f,''); #size: 0kb
        #if touch() doesn't work
        #chmod($ipfile,0755); 
    }

#calculate the diff after 10 hits, and ban when the avg is smaller than 0.25 seconds
if( $_SESSION['~h'] > 10 && ($_SESSION['~r']/$_SESSION['~h']) < 0.25 ) $_SESSION['~b'] = true;
?>

只是听从了避免 SESSIONS 的建议,所以我让它基于文件,而不必依赖于 cookie 和 session :

<?php
# get the visitor ip
$i = $_SERVER["REMOTE_ADDR"];
# get the filename and location
$f = './log/'.ip2long($i).'.dat';
# check if the file exists and we can write
if ( is_file($f) ) {
    # get the last filetime
    $a = filemtime($f);
    # get the file content
    $b = file_get_contents($f);
    # create array from hits & seconds
    $d = explode(':',$b);
    # calculate the new result
    $h = (int)$d[0] + 1;
    $s = (int)$d[1] + (time()-$a);  
    # add the new data tot text file
    file_put_contents($f,"$h:$s",LOCK_EX);
    unset($d);
}else{
    # create the file if it doesn't exist hits:seconds
    file_put_contents($f,"1:1",LOCK_EX); #size: 3kb
    # to make sure we can write
    # chmod($f,0755); 
    # set the hits to zero
    $h = 0;
}
# create a result var
$r = $h > 10 ? (float)$s/$h : (float)1;
# calculate the diff after 10 hits, and ban when the avg is smaller than 0.20 seconds (5 hits per second)
if( $r < 0.20 ) {
    # check if we can open htaccess
    $fp = @fopen('./.htaccess','a'); 
    if($fp){
        # add the ip to htaccess
        @fwrite($fp,"\r\ndeny from $i"); 
        # close
        @fclose($fp);
        # mail the admin
        @mail("email","IP Banned","Ip: $i with $r sbh (Seconds Between Hits)");
    }
    # let the user know why we deny him or her access
    die('To many requests.');
    # remove the file
    unlink($f);
}
# if the user leaves, reset
if( $r > 30 ) {
    unlink($f);
}
echo 'Result: '.$r.'sbh (Seconds Between Hits)';
?>

最佳答案

如果您想阻止临时用户在特定时间内发送过多请求,那么,该脚本可以工作。调出一个验证码屏幕,您就可以开始工作了。

但是

真正的答案是

此代码的主要错误是根据 session 来确定用户事件的频率。 “好”的攻击者可以用禁用 cookie 的请求淹没您的服务器,并欺骗他/她的 IP。

阻止攻击的一种方法是进入服务器级别,并安装 iptables。事实上,iptables 与大多数 Linux 发行版一起提供。它几乎不需要配置,开箱即用。

另一种方法,如果您对服务器具有根访问权限,则将 session 处理移至 Memcached。有个功能叫防洪,挺BOSS的。

防止 DDOS 的另一种方法是来自第三方服务,例如 block dos http://www.blockdos.net/

有点贵,但它对你有用。

但是 PHP 本身无法配置为处理 DDOS 攻击。在转到 PHP 脚本之前,您需要在所有要审查的请求前放置某种设备或防火墙。

关于PHP、.htaccess、DDoS 和快速请求保护,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14087117/

有关PHP、.htaccess、DDoS 和快速请求保护的更多相关文章

  1. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

  2. jquery - 我的 jquery AJAX POST 请求无需发送 Authenticity Token (Rails) - 2

    rails中是否有任何规定允许站点的所有AJAXPOST请求在没有authenticity_token的情况下通过?我有一个调用Controller方法的JqueryPOSTajax调用,但我没有在其中放置任何真实性代码,但调用成功。我的ApplicationController确实有'request_forgery_protection'并且我已经改变了config.action_controller.consider_all_requests_local在我的environments/development.rb中为false我还搜索了我的代码以确保我没有重载ajaxSend来发送

  3. ruby - HTTP 请求中的用户代理,Ruby - 2

    我是Ruby的新手。我试过查看在线文档,但没有找到任何有效的方法。我想在以下HTTP请求botget_response()和get()中包含一个用户代理。有人可以指出我正确的方向吗?#PreliminarycheckthatProggitisupcheck=Net::HTTP.get_response(URI.parse(proggit_url))ifcheck.code!="200"puts"ErrorcontactingProggit"returnend#Attempttogetthejsonresponse=Net::HTTP.get(URI.parse(proggit_url)

  4. ruby-on-rails - 获取并发布相同匹配项的请求 - 2

    在我的路线文件中我有:match'graphs/(:id(/:action))'=>'graphs#(:action)'如果是GET请求(工作)或POST请求(不工作),我想匹配它我知道我可以使用以下方法在资源中声明POST请求:post'/'=>:show,:on=>:member但是我怎样才能为比赛做到这一点呢?谢谢。 最佳答案 如果你同时想要POST和GETmatch'graphs/(:id(/:action))'=>'graphs#(:action)',:via=>[:get,:post]编辑默认值可以设置如下match'g

  5. ruby - 如何以表格格式快速打印 Ruby 哈希值? - 2

    有没有办法快速将表格格式的ruby​​哈希打印到文件中?如:keyAkeyBkeyC...1232343451253474456...其中散列的值是不同大小的数组。还是使用双循环是唯一的方法?谢谢 最佳答案 试试我写的这个gem(在表中打印散列、ruby对象、ActiveRecord对象):http://github.com/arches/table_print 关于ruby-如何以表格格式快速打印Ruby哈希值?,我们在StackOverflow上找到一个类似的问题:

  6. ruby-on-rails - 如何在 ActionController::TestCase 请求中设置内容类型 - 2

    我试图像这样在我的测试用例中执行获取:request.env['CONTENT_TYPE']='application/json'get:index,:application_name=>"Heka"虽然,它失败了:ActionView::MissingTemplate:Missingtemplatealarm_events/indexwith{:handlers=>[:builder,:haml,:erb,:rjs,:rhtml,:rxml],:locale=>[:en,:en],:formats=>[:html]尽管在我的Controller中我有:respond_to:html,

  7. 电脑启动后显示器黑屏怎么办?排查下面4个问题,快速解决 - 2

    电脑启动出现显示器黑屏是一个相当常见的问题。如果您遇到了这个问题,不要惊慌,因为它有很多可能的原因,可以采取一些简单的措施来解决它。在本文中,小编将介绍下面4种常见的电脑启动后显示器黑屏的原因,排查这些原因,快速解决! 演示机型:联想Ideapad700-15ISK-ISE系统版本:Windows10一、显示器问题如果出现电脑启动后显示器黑屏的情况。那么首先您需要检查一下显示器是否正常工作。您可以通过更换另一个显示器或将当前显示器连接到另一台计算机来检查显示器是否存在问题。如果问题仍然存在,那么您可以排除显示器故障的可能性。 二、显卡问题如果您的电脑配备了独立显卡,那么显卡故障也可能是导致电脑

  8. ruby-on-rails - 这个 C 和 PHP 程序员如何学习 Ruby 和 Rails? - 2

    按照目前的情况,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visitthehelpcenter指导。关闭9年前。我来自C、php和bash背景,很容易学习,因为它们都有相同的C结构,我可以将其与我已经知道的联系起来。然后2年前我学了Python并且学得很好,Python对我来说比Ruby更容易学。然后从去年开始,我一直在尝试学习Ruby,然后是Rails,我承认,直到现在我还是学不会,讽刺的是那些打着简单易学的烙印,但是对于我这样一个老练的程序员来说,我只是无法将它

  9. ruby - 如何测试 (rspec) 花费太长时间的 http 请求? - 2

    如果使用rspec请求花费的时间太长,我该如何测试行为?我正在考虑使用线程来模拟这个:describe"Test"doit"shouldtimeoutiftherequesttakestoolong"dolambda{thread1=Thread.new{#net::httprequesttogoogle.com}thread2=Thread.new{sleep(xxseconds)}thread1.jointhread2.join}.shouldraise_errorendend我想确保在第一次发出请求后,另一个线程“启动”,在这种情况下只是休眠xx秒。然后我应该期望请求超时,因为执

  10. ruby - Sinatra 路由中定义的全局变量是否在请求之间共享? - 2

    假设我有:get'/'do$random=Random.rand()response.body=$randomend如果我每秒有数千个请求到达/,$random是否会被共享并“泄漏”到上下文之外,或者它会像getblock的“本地”变量一样?我想如果它是在get'/'do的上下文之外定义的,它确实会被共享,但我想知道在ruby​​中是否有我不知道的$机制。 最佳答案 ThispartoftheSinatraREADMEaboutscopeisalwayshelpfultoread但是,如果您只需要为请求保留变量,那么我认为我建议使用

随机推荐