溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

nginx中如何實(shí)現(xiàn)ip黑名單動(dòng)態(tài)封禁

發(fā)布時(shí)間:2021-08-21 11:05:13 來源:億速云 閱讀:281 作者:小新 欄目:服務(wù)器

這篇文章給大家分享的是有關(guān)nginx中如何實(shí)現(xiàn)ip黑名單動(dòng)態(tài)封禁的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。

網(wǎng)站被惡意請求,拉黑IP是重要的手段,如果每次拉黑都要到nginx上配置,未免太low了;我們需要更方便的控制nginx IP黑名單。

1.方案

黑名單持久化到mysql (常見的方案是redis,但不利于控制,如:不同的IP設(shè)置不同的有效期、IP的CRUD、統(tǒng)計(jì)等等);

通過lua-nginx-module,在nginx中開辟一塊內(nèi)存(lua_shared_dict),lua將黑名單定期從mysql全量刷新至lua_shared_dict;

所有請求,都要到與lua_shared_dict中的IP check一下。

2.安裝

2.1 安裝luajit

cd LuaJIT-2.0.5
make
make install PREFIX=/usr/local/luajit

2.2.安裝nginx時(shí),將lua模塊編譯進(jìn)去

export LUAJIT_LIB=/usr/local/luajit/lib
export LUAJIT_INC=/usr/local/luajit/include/luajit-2.1
 
./configure --prefix=/nginx \
--with-ld-opt="-Wl,-rpath,/usr/local/luajit/lib" \
--add-module=/opt/ngx_devel_kit-0.3.1rc1 \
--add-module=/opt/lua-nginx-module-0.10.14rc3
 
make -j2
make install
ln -s /nginx/sbin/nginx /usr/sbin/nginx

3.配置

3.1 nginx配置

http {
  server_tokens off;
  lua_package_path "/usr/local/lib/lua/?.lua;;";
  lua_shared_dict ip_blacklist 4m;
}
 
server {
  set $real_ip $remote_addr;
  if ( $http_x_forwarded_for ~ "^(\d+\.\d+\.\d+\.\d+)" ) {
    set $real_ip $1;
  }
 
  # 管理信息,訪問該URL可以查看nginx中的IP黑名單信息
  location /get-ipblacklist-info {
    access_by_lua_file conf/lua/get_ipblacklist_info.lua;
  }
 
  # 同步URL,通過定時(shí)任務(wù)調(diào)用該URL,實(shí)現(xiàn)IP黑名單從mysql到nginx的定時(shí)刷新
  location /sync-ipblacklist {
   access_by_lua_file conf/lua/sync_ipblacklist.lua;
  }
 
  # 生產(chǎn)域名配置,所有需要IP黑名單控制的location,都要包含以下語句
  location / {
   access_by_lua_file conf/lua/check_realip.lua;
  }
 
}

nginx服務(wù)器配置以下crrontab

* * * * * /usr/bin/curl -o /dev/null -s http://127.0.0.1/sync-ipblacklist > /dev/null 2>&1

3.2 lua腳本

sync_ipblacklist.lua

local mysql_host = "ip of mysql server"
local mysql_port = 3306
local database = "dbname"
local username = "user"
local password = "password"
 
-- update ip_blacklist from mysql once every cache_ttl seconds
local cache_ttl  = 1
local mysql_connection_timeout = 1000
 
local client_ip  = ngx.var.real_ip
local ip_blacklist  = ngx.shared.ip_blacklist
local last_update_time = ip_blacklist:get("last_update_time");
 
if last_update_time == nil or last_update_time < ( ngx.now() - cache_ttl ) then
 
 local mysql = require "resty.mysql";
 local red = mysql:new();
 
 red:set_timeout(mysql_connect_timeout);
 
 local ok, err, errcode, sqlstate = red:connect{
     host = mysql_host,
     port = mysql_port,
     database = database,
     user = username,
     password = password,
     charset = "utf8",
     max_packet_size = 1024 * 1024,
    }
 if not ok then
 ngx.log(ngx.ERR, "mysql connection error while retrieving ip_blacklist: " .. err);
 else
 new_ip_blacklist, err, errcode, sqlstate = red:query("select ip_addr from ip_blacklist where status = 0 order by create_time desc limit 10000", 100)
 if not new_ip_blacklist then
  ngx.log(ngx.ERR, "bad result. errcode: " .. errcode .. " sqlstate: " .. sqlstate .. " err: " .. err);
  return
 end
 
 ip_blacklist:flush_all();
 for k1, v1 in pairs(new_ip_blacklist) do
  for k2, v2 in pairs(v1) do
  ip_blacklist:set(v2,true);
  end
 end
 
 ip_blacklist:set("last_update_time", ngx.now());
 end
end
 
ngx.say("sync successful");

get_ipblacklist_info.lua

-- 調(diào)用URL查看黑名單信息
-- 1萬IP消耗不到1.5M ngx.shared內(nèi)存
-- 獲取所有KEY會(huì)堵塞別的正常請求對ngx.shared內(nèi)存的訪問,因此只能取少數(shù)key展示
require "resty.core.shdict"
ngx.say("total space: " .. ngx.shared.ip_blacklist:capacity() .. "<br/>");
ngx.say("free space: " .. ngx.shared.ip_blacklist:free_space() .. "<br/>");
ngx.say("last update time: " .. os.date("%Y%m%d_%H:%M:%S",ngx.shared.ip_blacklist:get("last_update_time")) .. "<br/>");
ngx.say("first 100 keys: <br/>");
ngx.say("--------------------------<br/>");
ip_blacklist = ngx.shared.ip_blacklist:get_keys(100);
for key, value in pairs(ip_blacklist) do
 ngx.say(key .. ": " .. value .. "<br/>");
end

check_realip.lua

if ngx.shared.ip_blacklist:get(ngx.var.real_ip) then
 return ngx.exit(ngx.HTTP_FORBIDDEN);
end

3.3 數(shù)據(jù)庫設(shè)計(jì)

CREATE TABLE `ip_blacklist` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `ip_addr` varchar(15) COLLATE utf8mb4_bin DEFAULT NULL,
 `status` int(11) DEFAULT '0' COMMENT '0: valid 有效, 1: invalid 失效',
 `effective_hour` decimal(11,2) DEFAULT '24' COMMENT '有效期,單位:小時(shí)',
 `ip_source` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '黑名單來源',
 `create_time` datetime DEFAULT CURRENT_TIMESTAMP,
 `modify_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
 `remark` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '備注',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
 
 
CREATE PROCEDURE proc_ip_blacklist_status_update()
-- 將過期的IP狀態(tài)改為失效
begin 
 update ip_blacklist
 set status=1
 where date_add(create_time,INTERVAL effective_hour hour) < now();
 commit;
end;
 
 
CREATE EVENT job_ip_blacklist_status_update
ON SCHEDULE EVERY 1 MINUTE
ON COMPLETION PRESERVE
ENABLE
DO
call proc_ip_blacklist_status_update();

4 CRUD

黑名單產(chǎn)生有手工的方式,也有自動(dòng)的方式,或者兩者兼有。

自動(dòng)的方式有通過python分析elk日志,將惡意IP自動(dòng)寫入mysql,這是個(gè)大話題,這里不涉及。

手工的方式可以人肉查看elk請求日志,發(fā)現(xiàn)惡意IP,手工填入mysql,這里推薦一個(gè)開源的CRUD工具,用戶體驗(yàn)很nice(比直接navicat好多了),當(dāng)然也可以自己寫……

項(xiàng)目地址:https://github.com/jonseg/crud-admin-generator

項(xiàng)目的強(qiáng)大之處在于,所有表都幫你生成菜單,然后這些表的CRUD就直接用了。

具體操作見官方說明,就不贅述了。

nginx中如何實(shí)現(xiàn)ip黑名單動(dòng)態(tài)封禁

感謝各位的閱讀!關(guān)于“nginx中如何實(shí)現(xiàn)ip黑名單動(dòng)態(tài)封禁”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI