2021-05-19 09:11:18 +00:00
local M = { }
local logger = require " logger "
2021-05-13 14:21:51 +00:00
function M . is_banned ( )
return ngx.shared . behavior_ban : get ( ngx.var . remote_addr ) == true
end
2021-05-18 15:29:00 +00:00
function M . count ( status_codes , threshold , count_time , ban_time )
2021-05-13 14:21:51 +00:00
for k , v in ipairs ( status_codes ) do
if v == tostring ( ngx.status ) then
local count = ngx.shared . behavior_count : get ( ngx.var . remote_addr )
if count == nil then
count = 0
end
count = count + 1
local ok , err = ngx.shared . behavior_count : set ( ngx.var . remote_addr , count , count_time )
if not ok then
2021-05-19 09:11:18 +00:00
logger.log ( ngx.ERR , " BEHAVIOR " , " not enough memory allocated to behavior_ip_count " )
2021-10-06 13:41:55 +00:00
return false
2021-05-13 14:21:51 +00:00
end
if count >= threshold then
2021-05-19 09:11:18 +00:00
logger.log ( ngx.WARN , " BEHAVIOR " , " threshold reached for " .. ngx.var . remote_addr .. " ( " .. count .. " / " .. threshold .. " ) : IP is banned for " .. ban_time .. " seconds " )
2021-05-13 14:21:51 +00:00
local ok , err = ngx.shared . behavior_ban : safe_set ( ngx.var . remote_addr , true , ban_time )
if not ok then
2021-05-19 09:11:18 +00:00
logger.log ( ngx.ERR , " BEHAVIOR " , " not enough memory allocated to behavior_ip_ban " )
2021-10-06 13:41:55 +00:00
return false
2021-05-13 14:21:51 +00:00
end
2021-10-06 13:41:55 +00:00
return true
2021-05-13 14:21:51 +00:00
end
2021-10-06 13:41:55 +00:00
return false
2021-05-13 14:21:51 +00:00
end
end
end
return M