利用openresty+lua+redis 實現封殺頻繁惡意訪問IP地址

Nginx來限制訪問控制的方法有多種,nginx主要有2個模塊控制,但是那些不支持自定義,非常死,在大多數場景下並不實用。今天分享一個:利用openresty+lua+redis 實現封殺頻繁惡意訪問IP地址,當然這個方式也是有弊端的,那就是不斷試用代理 IP之類的,但是作用還是有的,起碼提高了惡意的成本。

nginx的版本有淘寶nginx,還有春哥的 openresty,但是openresty打包了 nginx 的時候,集成了很多的有用的擴展,特別是 lua,一個小巧的編程語言。本文就是:openresty最新穩定版本+lua Lua +redis最新穩定版本 。

具體環境我就不安裝了,大家可以使用寶塔面板啥的安裝openresty,如果你的原生態的nginx就需要手動安裝,網上教程都是有的,也比較簡單。

本文是防止別人破解用戶登錄界面的,只是以一個思路,供給大家進行探討學習哈,實際生產環境,需要多重考慮各方面的因素。

先在 http 中加載lua 包和 lua 的 c 包

lua_package_path "/usr/local/openresty/lualib/?.lua;;";

lua_package_cpath "/usr/local/openresty/lualib/?.so;;";

<code>server {
listen 80;
server_name _;
access_log /data/wwwlogs/access_nginx.log combined;
root /data/wwwroot/default;
index index.html index.htm index.php;

#例如我防止別人破解我的登錄帳號,還有譬如你匹配你的驗證碼文件進行限制

location /login {
default_type 'text/html';
access_by_lua_file "/usr/local/openresty/nginx/lua/access_by_redis.lua";
content_by_lua_block {
ngx.say("ok: ")
}

}

location ~ [^/]\\.php(/|$) {
#fastcgi_pass remote_php_ip:9000;
fastcgi_pass unix:/dev/shm/php-cgi.sock;
fastcgi_index index.php;
include fastcgi.conf;
}
。。。。。#省略
}/<code>

access_by_redis.lua 具體代碼如下(已包含詳細註釋):

<code>ip_bind_time = 30  --封禁IP多長時間
ip_time_out = 6 --指定統計ip訪問頻率時間範圍
connect_count = 10 --指定ip訪問頻率計數最大值
--上面的意思就是6秒內訪問超過10次,自動封 IP 30秒。

--連接redis
local redis = require "resty.redis"
local cache = redis.new()
local ok , err = cache.connect(cache,"127.0.0.1","6379")
cache:set_timeout(60000)

--如果連接失敗,跳轉到腳本結尾
if not ok then
goto Lastend
end

--查詢ip是否在封禁段內,若在則返回403錯誤代碼
--因封禁時間會大於ip記錄時間,故此處不對ip時間key和計數key做處理
is_bind , err = cache:get("bind_"..ngx.var.remote_addr)

if is_bind == '1' then
ngx.exit(ngx.HTTP_FORBIDDEN)
-- 或者 ngx.exit(403)
-- 當然,你也可以返回500錯誤啥的,搞一個500頁面,提示,親您訪問太頻繁啥的。

goto Lastend
end

start_time , err = cache:get("time_"..ngx.var.remote_addr)
ip_count , err = cache:get("count_"..ngx.var.remote_addr)

--如果ip記錄時間大於指定時間間隔或者記錄時間或者不存在ip時間key則重置時間key和計數key
--如果ip時間key小於時間間隔,則ip計數+1,且如果ip計數大於ip頻率計數,則設置ip的封禁key為1
--同時設置封禁key的過期時間為封禁ip的時間

if start_time == ngx.null or os.time() - start_time > ip_time_out then
res , err = cache:set("time_"..ngx.var.remote_addr , os.time())
res , err = cache:set("count_"..ngx.var.remote_addr , 1)
else
ip_count = ip_count + 1
res , err = cache:incr("count_"..ngx.var.remote_addr)
if ip_count >= connect_count then
res , err = cache:set("bind_"..ngx.var.remote_addr,1)
res , err = cache:expire("bind_"..ngx.var.remote_addr,ip_bind_time) --fix keys
end
end
--結尾標記
::Lastend::
local ok, err = cache:close()/<code>

最後的效果就是:http://xxxx/login 6秒內訪問超過10次,自動封 IP 30秒 。。。這個具體,你也調嘛


利用openresty+lua+redis 實現封殺頻繁惡意訪問IP地址

本文是很早之前寫在博客上的,分享出來希望對大家有用,覺得不錯,記得關注,點贊,收藏哦。


分享到:


相關文章: