Prima di tutto, non reinventare la ruota. Questo è esattamente ciò che denyhostsserve per:
DenyHosts is a python program that automatically blocks ssh attacks by
adding entries to /etc/hosts.deny. DenyHosts will also inform Linux
administrators about offending hosts, attacked users and suspicious
logins.
Per quanto ne so, denyhostsè solo per le sshconnessioni, ma c'è anche
fail2banche si occupa praticamente di tutto:
Fail2Ban consists of a client, server and configuration files to limit
brute force authentication attempts.
The server program fail2ban-server is responsible for monitoring log
files and issuing ban/unban commands. It gets configured through a
simple protocol by fail2ban-client, which can also read configuration
files and issue corresponding configuration commands to the server.
Entrambi sono disponibili nei repository:
sudo apt-get install denyhosts fail2ban
Puoi anche scrivere questo script, se vuoi. Qualcosa di simile a:
#!/usr/bin/env sh
netstat -an |
awk -vmax=100 '/tcp/{split($5,a,":"); if(a[1] > 0 && a[1]!="0.0.0.0"){c[a[1]]++}}
END{for(ip in c){if(c[ip]>max){print ip}}}' |
while read ip; do iptables -I INPUT 1 -s "$ip" -j DROP; done
Il awkestrarrà i progetti integrati e le considero e stampare solo quelli che appaiono più di maxvolte (qui, -vmax=100, cambia di conseguenza). Gli IP vengono quindi inviati a un ciclo while che esegue la iptablesregola pertinente .
Per eseguire questo 24/7, farei un cronjob che esegue il comando sopra ogni minuto o giù di lì. Aggiungi questa linea a/etc/crontab
* * * * * root /path/to/script.sh