Server Attack Prevention

What do you want to see in Armagetron soon? Any new feature ideas? Let's ponder these ground breaking ideas...
Post Reply
User avatar
Light
Reverse Outside Corner Grinder
Posts: 1659
Joined: Thu Oct 20, 2011 2:11 pm

Server Attack Prevention

Post by Light »

This will be a thread that I'll post random crap in that I do to help handle attacks. Feel free to chime in with other ideas, but please don't spam with a ton of off topic discussions. Let's try to keep it dealing with servers.

Block DDoS Attacks -ish - This will block IP's that get over 100 connections at a time in netstat. This is a high enough limit for me that I don't have to worry about regular users hitting an issue. Note that if you use it, someone spamming a page refresh on your site before their page loads will build up connections that won't drop for I think 30 seconds. They could potentially get themselves blocked, but they shouldn't really be spamming page refreshes. That's not really a lot different than a DoS attack.

Code: Select all

#!/bin/bash
while true;
do
	for f in `netstat -utn | awk '{print $5}' | grep -v [a-z] | cut -d : -f 1 | sort | uniq -c | sort -nr | sed 's/^ *//' | awk '$1 > 100' | awk '{print $2}'`; do ./block.sh $f; echo `date`": ${f}"; done
	sleep 3
done
Here's the block.sh that goes along with it. It will block an IP on all ports and then re-save your iptables rules. It will also sort through and remove duplicates because the script running every 3 seconds will try to ban the same IP multiple times until their connections start closing and they fall below 100 connections.

Code: Select all

#!/bin/bash
iptables -A INPUT -s $1 -j DROP
iptables-save | awk '!x[$0]++' | iptables-restore
iptables-save > /etc/network/iptables.rules
SSH Brute Force - This will block people on port 22 that attempt to brute your SSH server. There are many bots that run to do it, and it's a constant thing I deal with, so here's my basic solution.

Code: Select all

#!/bin/bash
pam_tally2 -r > /dev/null

while true;
do
	sleep 60
	for f in `pam_tally2 -r | tail -n +2 | awk '$2 >= 10' | awk '{print $5}'`;
	do
		./blockssh.sh $f
		echo "Blocked: ${f}"
	done
done
And then we just need to make SSH log to pam_tally so we can check how many failed attempts per minute. Add this to the top of /etc/pam.d/sshd.

Code: Select all

auth required pam_tally2.so deny=3 onerr=fail unlock_time=300
Then restart the SSH service.

Code: Select all

service ssh restart
Side Note: All of this is on Debian, so if you're on a different distro, you may need to rewrite the bash files, but it should still provide a basic guide.

Post Reply