FreeSWITCH fail2ban.lua

--[[
部署:
	在vars.xml里面增加配置项目:
		
	或者在 lua.conf.xml 里面增加下面这个配置项目:
			
	目前仅仅记录到/tmp/fail2ban.log,以后可以记录到数据库,再启用shell ban脚本
--]]

function log_to_file(s)
	local f = io.open("/tmp/fail2ban.log", "a")
	local prefix = os.date("%Y-%m-%d %H:%M:%S ", os.time())
	f:write(prefix .. s .. "\n")
	f:close()
end

freeswitch.consoleLog("NOTICE", "enter fail2ban.lua\n")
local con = freeswitch.EventConsumer()
con:bind("SHUTDOWN")
con:bind("CUSTOM")

function recv_custom(e)
	-- freeswitch.consoleLog("NOTICE", "*** custom event: " .. e:serialize())
	local subclass = e:getHeader("Event-Subclass") or ""
	if string.find(subclass, "sofia::") ~= 1 then return end

	local ip = e:getHeader("network_ip") or e:getHeader("network-ip") -- fs源代码有不一致的地方,有的是network_ip, 有的是 network-ip
	if not ip then return end
	local ua = e:getHeader("user-agent") or ""
	local to_user = e:getHeader("to-user") or ""
	local from_user = e:getHeader("from-user") or ""
	local auth_result = e:getHeader("auth-result") or ""
	local registration_type = e:getHeader("registration-type") or ""

	local s = string.format("*** %s, ip = %s, ua = %s, to = %s, from = %s, result = %s, type = %s\n", subclass, ip, ua, to_user, from_user, auth_result, registration_type)
	freeswitch.consoleLog("NOTICE", s)

	if subclass == "sofia::wrong_call_state" or subclass == "sofia::register_failure" then
		log_to_file("ip = " .. ip .. ", from = " .. from_user .. ", to = " .. to_user .. ", ua = " .. ua)
	end
end

while true do
	local e = con:pop(1)
	if e then
		local event_name = e:getHeader("Event-Name") or ""
		if event_name == "SHUTDOWN" then break
		elseif event_name == "CUSTOM" then
			recv_custom(e)
		end
	end
end

freeswitch.consoleLog("NOTICE",  "exit fail2ban.lua\n")

你可能感兴趣的:(FreeSWITCH,lua)