lib.lua
2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
--waf core lib
require 'config'
--Get the client IP
function get_client_ip()
local SET_IP_FROM = config_set_ip_addr
if SET_IP_FROM == "X_Forwarded_For" then
CLIENT_IP = ngx.req.get_headers()["X_Forwarded_For"]
end
if SET_IP_FROM == "X_real_ip" then
CLIENT_IP = ngx.req.get_headers()["X_real_ip"]
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
--Get the client user agent
function get_user_agent()
USER_AGENT = ngx.var.http_user_agent
if USER_AGENT == nil then
USER_AGENT = "unknown"
end
return USER_AGENT
end
--Get WAF rule
function get_rule(rulefilename)
local io = require 'io'
local RULE_PATH = config_rule_dir
local RULE_FILE = io.open(RULE_PATH..'/'..rulefilename,"r")
if RULE_FILE == nil then
return
end
RULE_TABLE = {}
for line in RULE_FILE:lines() do
if line ~= nil and line ~= "" then
table.insert(RULE_TABLE,line)
end
end
RULE_FILE:close()
return(RULE_TABLE)
end
--WAF log record for json,(use logstash codec => json)
function log_record(method,url,data,ruletag)
local io = require 'io'
local LOG_PATH = config_log_dir
local CLIENT_IP = get_client_ip()
local USER_AGENT = get_user_agent()
local SERVER_NAME = ngx.var.server_name
local LOCAL_TIME = ngx.localtime()
local log_json_obj = CLIENT_IP .. " " .. LOCAL_TIME .. " " .. method .. " " .. url .. " -> " ..ruletag .. "\n" .. SERVER_NAME .. " " .. data .. " ".. USER_AGENT
local LOG_LINE = log_json_obj
local LOG_NAME = LOG_PATH..'/'..os.date("%Y-%m-%d", os.time()).."_waf.log"
--local LOG_NAME = LOG_PATH..'/'.."waf.log"
local file = io.open(LOG_NAME,"a")
if file == nil then
return
end
file:write(LOG_LINE.."\n")
file:flush()
file:close()
end
--WAF return
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