Countering SSH bruteforce attacks
Jump to navigation
Jump to search
Create Parsing command[edit]
sudo touch /usr/bin/brute sudo chmod +x /usr/bin/brute sudo nano /usr/bin/brute
#!/bin/bash
sudo cat /var/log/auth.log | grep -i 'invalid user' | grep -v ']$' | awk '{print $8 " --> " $10}'
Python script to scan ports from attackers[edit]
import os
import optparse
from socket import *
PATH="/opt/counter_attack_ssh"
def main():
parser = optparse.OptionParser('usage %prog -H <target host> -p <target port>')
parser.add_option('-H', dest='tgtHost', type='string', help='specify target host')
(options, args) = parser.parse_args()
tgtHost = options.tgtHost
tgtPorts = [20, 21, 22, 23, 25, 53, 67, 68, 69, 80, 110, 123, 137, 138, 139, 143, 161, 162, 179, 389, 443, 445, 636, 989, 990]
with open(os.path.join(PATH, 'already_scanned.txt'), 'ra') as already_scanned:
already_scanned_list = already_scanned.readlines()
already_scanned_list = [x.strip() for x in already_scanned_list]
if (tgtHost == None):
print parser.usage
exit(0)
if tgtHost in already_scanned_list:
print "IP already scanned"
else:
already_scanned = open(os.path.join(PATH, 'already_scanned.txt'), 'a')
already_scanned.write(str(tgtHost) + "\n" )
already_scanned.close()
portScan(tgtHost, tgtPorts)
def connScan(tgtHost, tgtPort):
try:
connSkt = socket(AF_INET, SOCK_STREAM)
connSkt.connect((tgtHost, tgtPort))
print '[+] %d/tcp open' % tgtPort
f = open(os.path.join(PATH, 'open_ports.txt'), 'a')
f.write("HOST: " + str(tgtHost) + " PORT ---> " + str(tgtPort) + "\n")
f.close()
connSkt.close()
except:
print '[-] %d/tcp closed'%tgtPort
def portScan(tgtHost, tgtPorts):
try:
tgtIP = gethostbyname(tgtHost)
except:
print "[-] Cannot resolve '%s': Unkown host"%tgtHost
try:
tgtIP = tgtHost
tgtName = gethostbyaddr(tgtIP)
print '\n[+] Scan results for: ' + tgtName[0]
except:
print '\n[+] Scan results for: ' + tgtIP
setdefaulttimeout(1)
for tgtPort in tgtPorts:
print 'Scanning port ' + str(tgtPort)
connScan(tgtHost, int(tgtPort))
if __name__ == '__main__':
main()
counter_attack.sh[edit]
#!/bin/bash
WD=/opt/counter_attack_ssh
newest_log=${WD}/newest_log.txt
old_log=${WD}/old_log.txt
portscan_script=${WD}/portscan.py
function save_old_log{
cat ${newest_log} >> ${old_log}
}
save_old_log
/usr/bin/brute > ${newest_log}
input="${newest_log}"
while IFS= read -r var
do
ipaddress=$( echo "$var" | awk -F " -->" '{print $2}' )
#echo "$ipaddress"
python ${portscan_script} -H "$ipaddress"
done < "$input"
Crontab[edit]
0 20 * * * /opt/counter_attack_ssh/counter_attack_ssh.sh