django项目遭遇cc攻击,不要惊慌,这里推荐两招简单实用的技巧。
项目Nginx作为http接入层,分发到django应用,启动10个uwsgi worker。
今日突然发现,网页打开卡顿,打开server一看,cpu100%。
打开uwsgi的log,发现某一个IP进行了大量的请求,占用了worker。
这里总结下两种解决方法:
1.设置nginx黑名单
vi blockip.conf创建文件,输入:
deny x.x.x.x;
编辑nginx.conf, 在http{}内添加:
include blockip.conf;
验证配置:
[root@server nginx]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
重启nginx:
nginx -s reload
2.django内添加middleware
RequestBlockingMiddleware.py
import time
from django.core.exceptions import PermissionDenied
from django.utils.deprecation import MiddlewareMixin
MAX_REQUEST_PER_SECOND=2 #每秒访问次数
class RequestBlockingMiddleware(MiddlewareMixin):
def process_request(self,request):
now=time.time()
request_queue = request.session.get('request_queue',[])
if len(request_queue) < MAX_REQUEST_PER_SECOND:
request_queue.append(now)
request.session['request_queue']=request_queue
else:
time0=request_queue[0]
if (now-time0)<1:
raise PermissionDenied('Forbidden user agent')
request_queue.append(time.time())
request.session['request_queue']=request_queue[1:]
setting.py中注册:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'common.middleware.RequestBlockingMiddleware', #在sessions之后,auth之前
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
不足100行代码,log里再也没有对方的IP出现,相信对方正在某个小黑屋的电脑前气得跺脚吧