ngx_lua_waf_oneinstack/lib.lua

97 lines
2.4 KiB
Lua
Raw Normal View History

2018-12-04 09:42:10 +00:00
-- waf core lib
require "config"
2018-06-24 12:16:03 +00:00
2018-12-04 09:42:10 +00:00
-- Get the client IP
2018-06-24 12:16:03 +00:00
function get_client_ip()
2018-12-04 09:42:10 +00:00
local CLIENT_IP = ngx.req.get_headers()["X_real_ip"]
2018-06-24 12:16:03 +00:00
if CLIENT_IP == nil then
CLIENT_IP = ngx.req.get_headers()["X_Forwarded_For"]
end
if CLIENT_IP == nil then
CLIENT_IP = ngx.var.remote_addr
end
if CLIENT_IP == nil then
CLIENT_IP = "unknown"
end
return CLIENT_IP
end
2018-12-04 09:42:10 +00:00
-- Get the client user agent
2018-06-24 12:16:03 +00:00
function get_user_agent()
2018-12-04 09:42:10 +00:00
local USER_AGENT = ngx.var.http_user_agent
2018-06-24 12:16:03 +00:00
if USER_AGENT == nil then
USER_AGENT = "unknown"
end
return USER_AGENT
end
2018-12-04 09:42:10 +00:00
-- Get WAF rule
2018-06-24 12:16:03 +00:00
function get_rule(rulefilename)
2018-12-04 09:42:10 +00:00
local io = require "io"
2018-06-24 12:16:03 +00:00
local RULE_PATH = config_rule_dir
local RULE_FILE = io.open(RULE_PATH..'/'..rulefilename,"r")
if RULE_FILE == nil then
return
end
2018-12-04 09:42:10 +00:00
local RULE_TABLE = {}
2018-06-24 12:16:03 +00:00
for line in RULE_FILE:lines() do
table.insert(RULE_TABLE,line)
end
RULE_FILE:close()
return(RULE_TABLE)
end
2018-12-04 09:42:10 +00:00
-- WAF log record for json,(use logstash codec => json)
2018-06-24 12:16:03 +00:00
function log_record(method,url,data,ruletag)
local cjson = require("cjson")
2018-12-04 09:42:10 +00:00
local io = require "io"
2018-06-24 12:16:03 +00:00
local LOG_PATH = config_log_dir
local CLIENT_IP = get_client_ip()
local USER_AGENT = get_user_agent()
2018-06-27 03:21:37 +00:00
local SERVER_NAME = ngx.var.host
2018-06-24 12:16:03 +00:00
local LOCAL_TIME = ngx.localtime()
local log_json_obj = {
client_ip = CLIENT_IP,
local_time = LOCAL_TIME,
server_name = SERVER_NAME,
req_url = url,
attack_method = method,
req_data = data,
rule_tag = ruletag,
user_agent = USER_AGENT,
}
local LOG_LINE = cjson.encode(log_json_obj)
local LOG_NAME = LOG_PATH..'/'..ngx.today().."_sec.log"
local file = io.open(LOG_NAME,"a")
if file == nil then
return
end
file:write(LOG_LINE.."\n")
file:flush()
file:close()
end
2018-12-04 09:42:10 +00:00
-- test log
2018-06-27 03:21:37 +00:00
function write(logfile, msg)
local fd,err = io.open(logfile,"a+")
if fd == nil then
ngx.log(ngx.ERR,"writefile msg : "..msg,err)
return
end
fd:write(msg)
fd:flush()
fd:close()
end
2018-12-04 09:42:10 +00:00
-- WAF return
2018-06-24 12:16:03 +00:00
function waf_output()
if config_waf_output == "redirect" then
ngx.redirect(config_waf_redirect_url, 301)
else
ngx.header.content_type = "text/html"
ngx.status = ngx.HTTP_FORBIDDEN
ngx.say(config_output_html)
ngx.exit(ngx.status)
end
end