Last active
March 22, 2018 07:05
-
-
Save glenuidev/80c4a7518c016e774b626f083d3495eb to your computer and use it in GitHub Desktop.
DDoS IP Filter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# api limit = 2 | |
# refresh interval = 1 second | |
# is_allowed(source_ip) | |
class RateLimit | |
Api_limit = 2 | |
Refresh_interval = 1 | |
Active_users = {} | |
def is_allowed (ip) | |
puts "===========running==============" | |
current_time = Time.now.strftime('%s').to_i | |
if Active_users.key?(ip) | |
if (Active_users[ip][0] > current_time) | |
if Active_users[ip][1] >= Api_limit | |
puts "ALERT: ip has exceeded the threshold of #{Api_limit} in #{Refresh_interval} seconds" | |
puts false | |
return | |
# do log stuff | |
else | |
puts "WARNING: ip requests being tracked" | |
Active_users[ip][1] += 1 | |
puts "ip has visited #{Active_users[ip][1]} times in #{Refresh_interval} seconds" | |
puts true | |
return | |
end | |
else | |
puts "it's been longer than 1 second - resetting time to now" | |
Active_users.delete(ip) | |
track_ip(ip,current_time) | |
end | |
else # start tracking the user for the first time | |
track_ip(ip,current_time) | |
end | |
end | |
def track_ip (ip,current_time) | |
interval_time = current_time + Refresh_interval | |
puts "tracking NEW ip time #{interval_time}" | |
Active_users[ip] = [] | |
Active_users[ip][0] = interval_time | |
Active_users[ip][1] = 1 | |
puts true | |
return | |
end | |
end | |
rl = RateLimit.new | |
rl.is_allowed('1.2.3.4') # - true | |
rl.is_allowed('1.2.3.4') # - true | |
rl.is_allowed('1.2.3.4') # - false | |
sleep(1) | |
rl.is_allowed('1.2.3.4') # - true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment