1. 需求分析
Nginx來處理訪問控制的方法有多種,實現的效果也有多種,訪問IP段,訪問內容限制,訪問頻率限制等。
用Nginx+Lua+Redis來做訪問限制主要是考慮到高並發環境下快速訪問控制的需求。
Nginx處理請求的過程一共划分為11個階段,分別是:
post-read、server-rewrite、find-config、rewrite、post-rewrite、 preaccess、access、post-access、try-files、content、log.
在openresty中,可以找到:
set_by_lua,access_by_lua,content_by_lua,rewrite_by_lua等方法。
那么訪問控制應該是,access階段。
解決方案
按照正常的邏輯思維,我們會想到的訪問控制方案如下:
1.檢測是否被forbidden?
=》是,forbidden是否到期:是,清除記錄,返回200,正常訪問;否,返回403;
=》否,返回200,正常訪問
2.每次訪問,訪問用戶的訪問頻率+1處理
3.檢測訪問頻率是否超過限制,超過即添加forbidden記錄,返回403
這是簡單地方案,還可以添加點枝枝葉葉,訪問禁止時間通過算法導入,每次凹曲線增加。
實現方法
首先為nginx添加vhost配置文件,vhost.conf部分內容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
lua_package_path "/usr/local/openresty/lualib/?.lua;;";#告訴openresty庫地址
lua_package_cpath "/usr/local/openresty/lualib/?.so;;";
error_log /usr/local/openresty/nginx/logs/openresty.debug.log debug;
server {
listen 8080 default;
server_name www.ttlsa.com;
root /www/openresty;
location /login {
default_type 'text/html';
access_by_lua_file "/usr/local/openresty/nginx/lua/access_by_redis.lua";#通過lua來處理訪問控制
}
}
|
Access_by_redis.lua
參考了下v2ex.com的做法,redis存儲方案只做簡單地string存儲就足夠了。key分別是:
用戶登錄記錄:user:127.0.0.1:time(unix時間戳)
訪問限制:block:127.0.0.1
先連接Redis吧:
1
2
3
4
5
6
7
8
|
local red = redis:new()
function M:redis()
red:set_timeout(1000)
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
end
end
|
按照我們的邏輯方案,第二步是,檢測是否forbidden,下面我們就檢測block:127.0.0.1
,如果搜索到數據,檢測時間是否過期,未過期返回403,否則直接返回200:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
function M:check1()
local time=os.time() --system time
local res, err = red:get("block:"..ngx.var.remote_addr)
if not res then -- redis error
ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR) --redis get data error end
if type(res) == "string" then --if red not null then type(red)==string
if tonumber(res) >= tonumber(time) then --check if forbidden expired
ngx.exit(ngx.HTTP_FORBIDDEN)
--ngx.say("forbidden")
end
end
}
|
接下來會做檢測,是否訪問頻率過高,如果過高,要拉到黑名單的,
實現的方法是,檢測user:127.0.0.1:time
的值是否超標:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
function M:check2()
local time=os.time() --system time
local res, err = red:get("user:"..ngx.var.remote_addr..":"..time)
if not res then -- redis error
ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR) --redis get data error
end
if type(res) == "string" then
if tonumber(res) >= 10 then -- attack, 10 times request/s
red:del("block:"..self.ip)
red:set("block:"..self.ip, tonumber(time)+5*60 ) --set block time
ngx.exit(ngx.HTTP_FORBIDDEN)
end
end
end
|
最后呢,還要記得,把每次訪問時間做一個自增長,user:127.0.0.1:time
:
1
2
3
4
5
6
7
|
function M:add()
local time=os.time() --system time
ok, err = red:incr("user:"..ngx.var.remote_addr..":"..time)
if not ok then
ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR) --redis get data error
end
end
|
那么,測試,強刷幾次瀏覽器,發現過一會,返回了403,ok,搞定。
https://www.ttlsa.com/nginx/nginx-lua-redis-access-frequency-limit/