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部分內容如下:
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吧:
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:
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的值是否超標:
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:
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,搞定。
例子2
一、概述
需求:所有訪問/myapi/**的請求必須是POST請求,而且根據請求參數過濾不符合規則的非法請求(黑名單), 這些請求一律不轉寄到後端伺服器(Tomcat)
實現思路:通過在Nginx上進行訪問限制,通過Lua來靈活實現業務需求,而Redis用於儲存黑名單列表。
二、具體實現
1.lua代碼
本例中限制規則包括(post請求,ip地址黑名單,請求參數中imsi,tel值和黑名單)
-- access_by_lua_file '/usr/local/lua_test/my_access_limit.lua';
ngx.req.read_body()
local redis = require "resty.redis"
local red = redis.new()
red.connect(red, '127.0.0.1', '6379')
local myIP = ngx.req.get_headers()["X-Real-IP"]
if myIP == nil then
myIP = ngx.req.get_headers()["x_forwarded_for"]
end
if myIP == nil then
myIP = ngx.var.remote_addr
end
if ngx.re.match(ngx.var.uri,"^(/myapi/).*$") then
local method = ngx.var.request_method
if method == 'POST' then
local args = ngx.req.get_post_args()
local hasIP = red:sismember('black.ip',myIP)
local hasIMSI = red:sismember('black.imsi',args.imsi)
local hasTEL = red:sismember('black.tel',args.tel)
if hasIP==1 or hasIMSI==1 or hasTEL==1 then
--ngx.say("This is 'Black List' request")
ngx.exit(ngx.HTTP_FORBIDDEN)
end
else
--ngx.say("This is 'GET' request")
ngx.exit(ngx.HTTP_FORBIDDEN)
end
end
2.nginx.conf
location / {
root html;
index index.html index.htm;
access_by_lua_file /usr/local/lua_test/my_access_limit.lua;
proxy_pass http://127.0.0.1:8080;
client_max_body_size 1m;
}
3.添加黑名單規則資料
#redis-cli sadd black.ip '153.34.118.50'
#redis-cli sadd black.imsi '460123456789'
#redis-cli sadd black.tel '15888888888'
可以通過redis-cli smembers black.imsi 查看列表明細
4.驗證結果
#curl -d "imsi=460123456789&tel=15800000000" "http://www.mysite.com/myapi/abc"