Thursday, October 20, 2016

Denial of Service on detection of Intrusion event

The following iptables rules should be adequate to lower the change an intruder to continuously try to login to our server.

#!/bin/bash

### BLOCKING INTRUDERS TO OUR SSH SERVICE ####

VERBOSE=1

execandprint() {
 cmd="${1}"
 [[ $VERBOSE -eq 1 ]] && echo "$cmd"
 ${cmd}
}

# create properREJECT chain that does different rejects for tcp/udp
rjchain="properREJECT"
echo "Creating chain $rjchain in filter table..."
iptables -N $rjchain
iptables -A $rjchain -m limit --limit 2/min -j LOG --log-prefix "REJECTED: " --log-level 4
iptables -A $rjchain -p tcp -j REJECT --reject-with tcp-reset
iptables -A $rjchain -j REJECT --reject-with icmp-port-unreachable

#
blchain="blacklistdrop"
echo "Creating chain $blchain in filter table..."
iptables -N $blchain
iptables -A $blchain -m limit --limit 2/second -j LOG --log-prefix "adding to BLACKLIST: " --log-level 6
iptables -A $blchain -m recent --name BLACKLIST --set -j DROP

# block this baukdeh in Shenzhen, China
iptables -A INPUT -s 221.229.172.71 -j $rjchain

#
# if the src address of packet is currently in the list BLACKLIST within the last 120 seconds, drop it
# see /proc/net/xt_recent/BLACKLIST
execandprint "iptables -A INPUT -m recent --name BLACKLIST --update --seconds 120 -j DROP"
#
# all *established* ssh connections simply continue
# see /proc/net/nf_conntrack and /proc/net/xt_recent/sshconn
execandprint "iptables -A INPUT  -p tcp --dport 22 -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT"
#
# *new* ssh connections are all put into a list 'sshconn', and if there are 3 such packets in 30 seconds
# we send the package to chain 'blacklistdrop' which puts the IP in the blacklist
execandprint "iptables -A INPUT  -p tcp --dport 22 -m conntrack --ctstate NEW -m recent --name sshconn --rcheck --seconds 30 --hitcount 3 -j $blchain"

#
# if we have seen less then 3 such packets in the last 30 seconds we accept
execandprint "iptables -A INPUT  -p tcp --dport 22 -m conntrack --ctstate NEW -m recent --name sshconn --set -j ACCEPT"

#
# if the destination address is in the blacklist, we REJECT *any* packet
execandprint "iptables -A OUTPUT -m recent --name BLACKLIST --rdest --rcheck --seconds 30 -j $rjchain"

#
# outgoing we accept all ssh traffic, with connection tracking
execandprint "iptables -A OUTPUT -p tcp --sport 22 -m conntrack --ctstate ESTABLISHED,NEW,RELATED -j ACCEPT"