Skip to content

Instantly share code, notes, and snippets.

@megahall
Last active December 21, 2024 09:14
Show Gist options
  • Save megahall/c302e6e4fc8576a3be0b672ee0c9d98c to your computer and use it in GitHub Desktop.
Save megahall/c302e6e4fc8576a3be0b672ee0c9d98c to your computer and use it in GitHub Desktop.
how to detect brute force SSH connections in a short time window, and apply the ban for a long time window
#!/bin/bash
count="3"
window="60"
length="300"
ip_mask="255.255.255.0"
ip6_mask="ffff:ffff:ffff:ffff::"
iptables -A INPUT -p tcp --dport 22 \
-m state --state NEW \
-m recent --mask "${ip_mask}" --set --name SSH_DETECT
iptables -A INPUT -p tcp --dport 22 \
-m state --state NEW \
-m recent --mask "${ip_mask}" --rcheck --seconds "${window}" --hitcount "${count}" --name SSH_DETECT \
-m recent --mask "${ip_mask}" --set --name SSH_BAN \
-j DROP
iptables -A INPUT -p tcp --dport 22 \
-m state --state NEW \
-m recent --mask "${ip_mask}" --rcheck --seconds "${length}" --name SSH_BAN \
-j DROP
ip6tables -A INPUT -p tcp --dport 22 \
-m state --state NEW \
-m recent --mask "${ip6_mask}" --set --name SSH_DETECT
ip6tables -A INPUT -p tcp --dport 22 \
-m state --state NEW \
-m recent --mask "${ip6_mask}" --rcheck --seconds "${window}" --hitcount "${count}" --name SSH_DETECT \
-m recent --mask "${ip6_mask}" --set --name SSH_BAN \
-j DROP
ip6tables -A INPUT -p tcp --dport 22 \
-m state --state NEW \
-m recent --mask "${ip6_mask}" --rcheck --seconds "${length}" --name SSH_BAN \
-j DROP
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment