ZmEu

anti_ddos.rb - it works and daemonises perfectly!! and works in loop, so only start ONCE!

Mar 3rd, 2011
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. #!/usr/bin/env ruby
  2. # Attack 0.1 - A threaded (D)DoS-Deflate alternative written in Ruby (2008) works great!!! (xd)
  3. require 'logger'
  4.  
  5. class Attack
  6. # The number of concurent connections per IP.
  7. CONNECTION_LIMIT = 5
  8. # The frequency (in seconds) that Attack checks the current connections.
  9. FREQUENCY = 30
  10. # The firewall. Available options: csf, apf or any other firewall that takes a -d IP argument.
  11. FIREWALL = "csf"
  12. # Connection checks and bans are logged here.
  13. LOG_FILE = "deflate_attack.log"
  14. # IP Whitelist.
  15. WHITELIST = %w{ 127.0.0.1 }
  16. def initialize
  17. @connections = `netstat -ntu | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n`
  18. @log = Logger.new(LOG_FILE)
  19. daemonize
  20. loop do
  21. run
  22. sleep(FREQUENCY)
  23. end
  24. end
  25. def check(connections)
  26. connections.each { |connection|
  27. conn, ip = connection.split
  28. if conn.to_i > CONNECTION_LIMIT and not WHITELIST.include? ip
  29. `#{FIREWALL} -d #{ip}`
  30. @log.info "Blocked #{ip} with #{conn} connections."
  31. end
  32. }
  33. end
  34. def run
  35. Thread.new {
  36. check @connections
  37. @log.info "Checked connections at #{Time.now}"
  38. }.join
  39. end
  40. protected
  41. def daemonize
  42. exit if fork
  43. Process.setsid
  44. exit if fork
  45. Dir.chdir "/"
  46. File.umask 0000
  47. STDIN.reopen "/dev/null"
  48. STDOUT.reopen "/dev/null", "a"
  49. STDERR.reopen STDOUT
  50. trap("TERM") { exit }
  51. end
  52. end
  53. Attack.new
Advertisement
Add Comment
Please, Sign In to add comment