mod_c2s_auth_throttle/mod_c2s_auth_throttle.lua
changeset 612 15763c1d085c
parent 611 d87a9e1e6d30
child 613 b5a8e8492570
equal deleted inserted replaced
611:d87a9e1e6d30 612:15763c1d085c
     1 -- Clients Connection Throttler.
       
     2 -- Usage:
       
     3 -- Add the module into modules loaded into the virtual host section
       
     4 --
       
     5 -- cthrottler_logins_count = 3 -> number of logins attempt allowed
       
     6 -- cthrottler_time = 120 -> in x seconds
       
     7 
       
     8 local time = os.time
       
     9 local in_count = {}
       
    10 local logins_count = module:get_option_number("cthrottler_logins_count", 3)
       
    11 local throttle_time = module:get_option_number("cthrottler_time", 60)
       
    12 
       
    13 local function handle_sessions(event)
       
    14 	local session = event.origin
       
    15 
       
    16 	if not in_count[session.ip] and session.type == "c2s_unauthed" then
       
    17 		in_count[session.ip] = { t = time(), c = 1 }
       
    18 	elseif in_count[session.ip] and session.type == "c2s_unauthed" then
       
    19 		in_count[session.ip].c = in_count[session.ip].c + 1
       
    20 		
       
    21 		if in_count[session.ip].c > logins_count and time() - in_count[session.ip].t < throttle_time then
       
    22 			module:log("error", "Exceeded login count for %s, closing connection", session.ip)
       
    23 			session:close{ condition = "policy-violation", text = "You exceeded the number of connections/logins allowed in "..throttle_time.." seconds, good bye." }
       
    24 			return true
       
    25 		elseif time() - in_count[session.ip].t > throttle_time then
       
    26 			in_count[session.ip] = nil ; return
       
    27 		end
       
    28 	end	
       
    29 end
       
    30 
       
    31 module:hook("stanza/urn:ietf:params:xml:ns:xmpp-sasl:auth", handle_sessions, 100)
       
    32 module:hook("stanza/iq/jabber:iq:auth:query", handle_sessions, 100) -- Legacy?