Skip to content

Instantly share code, notes, and snippets.

@mitsh
Created November 3, 2018 19:25
Show Gist options
  • Save mitsh/796e14764e80c27b316d3046eac6e7e3 to your computer and use it in GitHub Desktop.
Save mitsh/796e14764e80c27b316d3046eac6e7e3 to your computer and use it in GitHub Desktop.
iptables for syn/dos attacks
#!/usr/bin/env bash
# @authors Rodrigo Gomes link: https://serverfault.com/questions/766901/how-temporarily-block-an-ip-address-making-too-many-hits-on-the-server-with-ipta
iptables -N BLOCK_IP
iptables -N SYN_CHECK
iptables -N DOS_CHECK
iptables -N SYN_ATTACK
iptables -N DOS_ATTACK
# first checks if the IP is already blocked
iptables -A INPUT -j BLOCK_IP
# drop if is blocked
iptables -A BLOCK_IP -m recent --name BlockedIP --rcheck --seconds 60 -j DROP
iptables -A BLOCK_IP -m recent --name BlockedIP --remove -j RETURN
# check: if there is more than 20 simultaneous connections with SYN status
iptables -A INPUT -p tcp --syn -m connlimit --connlimit-above 20 -j SYN_CHECK
iptables -A INPUT -m state --state NEW -j DOS_CHECK
# checks if the attack is frequently
iptables -A SYN_CHECK -m recent --update --seconds 10 --hitcount 20 --name RATE -j SYN_ATTACK
iptables -A DOS_CHECK -m recent --update --seconds 3 --hitcount 20 --name RATE -j DOS_ATTACK
# if the attack is frequent blocks for 1 minute and generates log
iptables -A SYN_ATTACK -j LOG --log-prefix "BLOCK SYN ATTACK: " --log-level 6
iptables -A SYN_ATTACK -m recent --set --name BlockedIP -j DROP
iptables -A DOS_ATTACK -j LOG --log-prefix "BLOCK DOS ATTACK: " --log-level 6
iptables -A DOS_ATTACK -m recent --set --name BlockedIP -j DROP
# if the attack is not frequent, accept
iptables -A SYN_CHECK -m recent --set --name RATE -j ACCEPT
iptables -A DOS_CHECK -m recent --set --name RATE -j ACCEPT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment