Okay, if it’s only a small bandwidth attacks, it might work with an NGINX Reverse Proxy. On the server running NGINX, save the following script as ddos.rb and run it with “ruby ddos.rb”:
#!/usr/bin/env ruby
# Attack v1 (xd-mod) - A Threaded (D)aemonisied (D)DoS-Deflate alternative written in Ruby for IPtables
require 'logger'
class Attack
CONNECTION_LIMIT = 25
FREQUENCY = 20
FIREWALL = "/usr/bin/iptables"
LOG_FILE = "ddos.log"
WHITELIST = %w{ 127.0.0.1 }
def initialize
@connections = `netstat -ntu | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n`
@log = Logger.new(LOG_FILE)
daemonize
loop do
run
sleep(FREQUENCY)
end
end
def check(connections)
connections.each { |connection|
conn, ip = connection.split
if conn.to_i > CONNECTION_LIMIT and not WHITELIST.include? ip
`#{FIREWALL} -I INPUT -s #{ip} -j DROP`
@log.info "[IPT] Dropped -> #{ip} with -> #{conn} connections .."
end
}
end
def run
Thread.new {
check @connections
@log.info "[IPT] Checked connections at -> #{Time.now} .."
}.join
end
protected
def daemonize
exit if fork
Process.setsid
exit if fork
Dir.chdir "/"
File.umask 0000
STDIN.reopen "/dev/null"
STDOUT.reopen "/dev/null", "a"
STDERR.reopen STDOUT
trap("TERM") {
exit
}
end
end
Attack.new
This will block IPs with more than 25 concurrent connections using IPTables. Also change the NGINX workers in your NGINX config from 1 to the number of CPUs your Reverse Proxy server has, like 4 for a quad core and restart NGINX.
Add the following kernel settings to your /etc/sysctl.conf and execute “sysctl -p”:
net.ipv4.tcp_syncookies = 1
net.core.somaxconn = 1024
net.ipv4.tcp_syn_retries = 1
net.ipv4.tcp_synack_retries = 1
net.ipv4.tcp_keepalive_intvl = 5
net.ipv4.tcp_keepalive_probes = 1
net.ipv4.tcp_keepalive_time = 30
net.ipv4.tcp_fin_timeout = 20
net.ipv4.tcp_timestamps = 0
If that solution doesn’t work, you will need to forget about your reverse proxy and switch your web server’s web server to LiteSpeed, install fail2ban with a custom regex, use this script ruby too and also the kernel settings.
Tags: ddos, nginx, ruby, Server, sysctl
Copyright © Security, Server Tweaking, IT Management Blog By SolidShellSecurity [How to using Nginx anti ddos proxy script and server protection], All Right Reserved. 2013.
The post How to using Nginx anti ddos proxy script and server protection appeared first on Security, Server Tweaking, IT Management Blog By SolidShellSecurity.