Nginx 通过 Lua + Redis 实现动态封禁 IP

来自Linux78|wiki

一、背景 为了封禁某些爬虫或者恶意用户对服务器的请求,我们需要建立一个动态的 IP 黑名单。对于黑名单之内的 IP ,拒绝提供服务。

二、架构 实现 IP 黑名单的功能有很多途径:

1、在操作系统层面,配置 iptables,拒绝指定 IP 的网络请求;

2、在 Web Server 层面,通过 Nginx 自身的 deny 选项 或者 lua 插件 配置 IP 黑名单;

3、在应用层面,在请求服务之前检查一遍客户端 IP 是否在黑名单。

为了方便管理和共享,我们通过 Nginx+Lua+Redis 的架构实现 IP 黑名单的功能,架构图如下:

client---> nginx(lua)---application
            |
            |
            redis

三、实现 1、安装 Nginx+Lua模块,推荐使用 OpenResty,这是一个集成了各种 Lua 模块的 Nginx 服务器:

2、安装并启动 Redis 服务器;

3、配置 Nginx 示例:

http {

   lua_shared_dict ip_blacklist 1m;
   server {
   listen 80;
   server_name localhost;
   location = /ip_blacklist {
       access_by_lua-file lua/ip_blacklist.lua;
       default_type text/html;
       content_by_lua '
           ngx.say("hello lua")
           ';
   }
   }

} Nginx 配置

其中

lua_shared_dict ip_blacklist 1m;

由 Nginx 进程分配一块 1M 大小的共享内存空间,用来缓存 IP 黑名单,参见:

https://github.com/openresty/lua-nginx-module#lua_shared_dict

access_by_lua_file lua/ip_blacklist.lua;

指定 lua 脚本位置

4、配置 lua 脚本,定期从 Redis 获取最新的 IP 黑名单,文件内容参见:

https://gist.github.com/Ceelog/39862d297d9c85e743b3b5111b7d44cb

ip_blacklist.lua

-- a quick LUA access script for nginx to check IP addresses against an
-- `ip_blacklist` set in Redis, and if a match is found send a HTTP 403.
--
-- allows for a common blacklist to be shared between a bunch of nginx
-- web servers using a remote redis instance. lookups are cached for a
-- configurable period of time.
--
-- block an ip:
--   redis-cli SADD ip_blacklist 10.1.1.1
-- remove an ip:
--   redis-cli SREM ip_blacklist 10.1.1.1
--
-- also requires lua-resty-redis from:
--   https://github.com/agentzh/lua-resty-redis
--
-- your nginx http context should contain something similar to the
-- below: (assumes resty/redis.lua exists in /etc/nginx/lua/)
--
--   lua_package_path "/etc/nginx/lua/?.lua;;";
--   lua_shared_dict ip_blacklist 1m; 
--
-- you can then use the below (adjust path where necessary) to check
-- against the blacklist in a http, server, location, if context:
--
-- access_by_lua_file /etc/nginx/lua/ip_blacklist.lua;
--
-- from https://gist.github.com/chrisboulton/6043871
-- modify by Ceelog
local redis_host    = "your.redis.server.here"
local redis_port    = 6379
-- connection timeout for redis in ms. don't set this too high!
local redis_connection_timeout = 100
-- check a set with this key for blacklist entries
local redis_key     = "ip_blacklist"
-- cache lookups for this many seconds
local cache_ttl     = 60
-- end configuration
local ip                = ngx.var.remote_addr
local ip_blacklist         = ngx.shared.ip_blacklist
local last_update_time     = ip_blacklist:get("last_update_time");
-- only update ip_blacklist from Redis once every cache_ttl seconds:
if last_update_time == nil or last_update_time < ( ngx.now() - cache_ttl ) then
 local redis = require "resty.redis";
 local red = redis:new();
 red:set_timeout(redis_connect_timeout);
 local ok, err = red:connect(redis_host, redis_port);
 if not ok then
   ngx.log(ngx.DEBUG, "Redis connection error while retrieving ip_blacklist: " .. err);
 else
   local new_ip_blacklist, err = red:smembers(redis_key);
   if err then
     ngx.log(ngx.DEBUG, "Redis read error while retrieving ip_blacklist: " .. err);
   else
     -- replace the locally stored ip_blacklist with the updated values:
     ip_blacklist:flush_all();
     for index, banned_ip in ipairs(new_ip_blacklist) do
       ip_blacklist:set(banned_ip, true);
     end
     -- update time
     ip_blacklist:set("last_update_time", ngx.now());
   end
 end
end
if ip_blacklist:get(ip) then
 ngx.log(ngx.DEBUG, "Banned IP detected and refused access: " .. ip);
 return ngx.exit(ngx.HTTP_FORBIDDEN);
end

5、在 Redis 服务器上新建 Set 类型的数据 ip_blacklist,并加入最新的 IP 黑名单。

完成以上步骤后,重新加载 nginx,配置便开始生效了

这时访问服务器,如果你的 IP 地址在黑名单内的话,将出现拒绝访问:

四、总结 以上,便是 Nginx+Lua+Redis 实现的 IP 黑名单功能,具有如下优点:

1、配置简单、轻量,几乎对服务器性能不产生影响;

2、多台服务器可以通过Redis实例共享黑名单;

3、动态配置,可以手工或者通过某种自动化的方式设置 Redis 中的黑名单。