Skip to content

Instantly share code, notes, and snippets.

@TruncatedDinoSour
Last active September 10, 2024 16:17
Show Gist options
  • Save TruncatedDinoSour/e0c0c5076448a09c68ff50b00fbfab2b to your computer and use it in GitHub Desktop.
Save TruncatedDinoSour/e0c0c5076448a09c68ff50b00fbfab2b to your computer and use it in GitHub Desktop.
Use IPTables and IP6Tables as a firewall in Linux easily for SSH, HTTP(S), Email, Matrix, and XMPP traffic.
#!/bin/sh
set -eu
main() {
for ip in iptables ip6tables; do
echo '----------------------------------------------------------------'
echo "[$ip] Setting up iptables rules..."
echo "[$ip] Flushing all rules..."
"$ip" -F
"$ip" -X
echo "[$ip] Allowing established connections..."
"$ip" -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
echo "[$ip] Allowing loopback interface..."
"$ip" -A INPUT -i lo -j ACCEPT
"$ip" -A OUTPUT -o lo -j ACCEPT
echo "[$ip] Allowing SSH, HTTP, HTTPS, Email federation, Matrix federation, and XMPP federation on tcp..."
"$ip" -A INPUT -p tcp --dport 22 -j ACCEPT # SSH
"$ip" -A INPUT -p tcp --dport 80 -j ACCEPT # HTTP
"$ip" -A INPUT -p tcp --dport 443 -j ACCEPT # HTTPS
"$ip" -A INPUT -p tcp -m multiport --dports 25,465,587,143,993,110,995,2525,4190 -j ACCEPT # Email federation
"$ip" -A INPUT -p tcp --dport 8448 -j ACCEPT # Matrix federation
"$ip" -A INPUT -p tcp -m multiport --dports 5222,5269,5223,5270,5281 -j ACCEPT # XMPP federation
echo "[$ip] Rate limiting SSH traffic on tcp..."
"$ip" -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m recent --set
"$ip" -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m recent --update --seconds 60 --hitcount 5 -j DROP
echo "[$ip] Dropping invalid packets on tcp..."
"$ip" -A INPUT -p tcp -m state --state INVALID -j DROP
echo "[$ip] Dropping other traffic..."
"$ip" -P INPUT DROP
"$ip" -P FORWARD DROP
echo "[$ip] Rules:"
"$ip" -vL
echo '----------------------------------------------------------------'
done
echo '[ICMP] Allowing limited ICMP traffic...'
iptables -A INPUT -p icmp -m limit --limit 5/sec --limit-burst 10 -j ACCEPT
iptables -A INPUT -p icmp -j DROP
ip6tables -A INPUT -p icmpv6 -m limit --limit 5/sec --limit-burst 10 -j ACCEPT
ip6tables -A INPUT -p icmpv6 -j DROP
echo '----------------------------------------------------------------'
echo '[iptables-save] Saving rules...'
iptables-save | tee /etc/iptables/rules.v4
echo '----------------------------------------------------------------'
echo '[ip6tables-save] Saving rules...'
ip6tables-save | tee /etc/iptables/rules.v6
echo 'Meoww :3 done'
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment