導讀OpenResty 經過匯聚各類設計精良的 Nginx 模塊(主要由 OpenResty 團隊自主開發),從而將 Nginx 有效地變成一個強大的通用 Web 應用平臺。這樣,Web 開發人員和系統工程師能夠使用 Lua 腳本語言調動 Nginx 支持的各類 C 以及 Lua 模塊,快速構造出足以勝任 10K 乃至 1000K 以上單機併發鏈接的高性能 Web 應用系統html
本文介紹使用openresty來實現防cc攻擊的功能。openresty官網http://openresty.org/cn/index.html。下面是防cc攻擊的流程圖。
根據流程圖,咱們知道防cc攻擊主要包括兩部分,一是限制請求速度,二是給用戶發送js跳轉代碼進行驗證請求是否合法。
nginx
RHEL/Centos:git
yum install readline-devel pcre-devel openssl-devel
ubuntu:ubuntu
apt-get install libreadline-dev libncurses5-dev libpcre3-dev libssl-dev perl
cd /tmp/ git clone http://luajit.org/git/luajit-2.0.git cd luajit-2.0/ make && make install ln -sf luajit-2.0.0-beta10 /usr/local/bin/luajit ln -sf /usr/local/lib/libluajit-5.1.so.2 /usr/lib/
cd /tmp wget http://agentzh.org/misc/nginx/ngx_openresty-1.2.4.13.tar.gz tar xzf ngx_openresty-1.2.4.13.tar.gz cd ngx_openresty-1.2.4.13/ ./configure --prefix=/usr/local/openresty --with-luajit make && make install
nginx.conf:centos
http{ [......] lua_shared_dict limit 10m; lua_shared_dict jsjump 10m; server { #lua_code_cache off; listen 80; server_name www.centos.bz; location / { default_type text/html; content_by_lua_file "/usr/local/openresty/nginx/conf/lua"; } location @cc { internal; root html; index index.html index.htm; } } }
/usr/local/openresty/nginx/conf/lua文件:併發
local ip = ngx.var.binary_remote_addr local limit = ngx.shared.limit local req,_=limit:get(ip) if req then if req > 20 then ngx.exit(503) else limit:incr(ip,1) end else limit:set(ip,1,10) end local jsjump = ngx.shared.jsjump local uri = ngx.var.request_uri local jspara,flags=jsjump:get(ip) local args = ngx.req.get_uri_args() if jspara then if flags then ngx.exec("@cc") else local p_jskey='' if args["jskey"] and type(args["jskey"])=='table' then p_jskey=args["jskey"][table.getn(args["jskey"])] else p_jskey=args["jskey"] end if p_jskey and p_jskey==tostring(jspara) then jsjump:set(ip,jspara,3600,1) ngx.exec("@cc") else local url='' if ngx.var.args then url=ngx.var.scheme.."://"..ngx.var.host..uri.."&jskey="..jspara else url=ngx.var.scheme.."://"..ngx.var.host..uri.."?jskey="..jspara end local jscode="window.location.href='"..url.."';" ngx.say(jscode) end end else math.randomseed( os.time() ); local random=math.random(100000,999999) jsjump:set(ip,random,60) local url='' if ngx.var.args then url=ngx.var.scheme.."://"..ngx.var.host..uri.."&jskey="..random else url=ngx.var.scheme.."://"..ngx.var.host..uri.."?jskey="..random end local jscode="window.location.href='"..url.."';" ngx.say(jscode) end
lua代碼部分解釋:
一、1-12行是限速功能實現,第5和第10行表示10秒鐘內容最多隻能請求20次。
二、14-48行是驗證部分,24行中的3600表示驗證經過後,白名單時間爲3600秒,即1小時。dom
update: 2013.5.26
一、修復JS無限跳轉bug
二、增長隨機種子jsp