利用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地址

本文是很早之前写在博客上的,分享出来希望对大家有用,觉得不错,记得关注,点赞,收藏哦。


分享到:


相關文章: