Script de bloqueo para usuarios ilegales del servicio SSH
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hace un tiempo, mantuvimos un hilo acerca de como securizar el servicio ssh. http://lists.suse.com/archive/suse-linux-s/2005-Jan/0113.html Me acuerdo que surgió la duda de cómo hacer que los usuarios ilegales fueran incluídos automáticamente en una lista negra; bien, pues hoy leyendo el grupo de news de security, he dado con esto:
#!/bin/csh
#Made by Jack-Benny, founder of cyberinfo.se, bluedogsecurity.cyberinfo.se #and linuxsecurity.cyberinfo.se #This is a script I wrote to automaticly block the SSH probes. #The code is pretty quick written and not fancy in anyway, but for #me it works like a dream! #If you find any bugs or have any improvments or suggestions #please drop me an e-mail: jake@cyberinfo.se
#A short explanation of how it works: #The script first uses grep to find the word Invalid in the #/var/log/messages file. #Then it takes field number 10 (Field separator is a whitespace) #wich is the IP number. #It then compares this to the "history" file and prints any new #IP's in the file new_ip. #Then the file new_ip is processed with sed ("old" IP's have #tab in front of them, "new" ones don't) #It is then written to file block_this and a black list (used #for backup purpose) #Finaly the new IP's are inserted to an IPTABLES command wich #blocks the IP access to port 22 #By the way: Sorry for the long lines, don't split them up, #it won't work if you do!!! #MUST BE RUN AS ROOT, it could also be a good idea to run it #in a separate directory as it genarates a lot of files...
touch hist_ip
START:
sleep 10 grep Invalid /var/log/messages > ips cat ips | awk '{ FS = " " } { print $10 | "uniq" }' | sort | uniq > ext_ip comm -1 hist_ip ext_ip > new_ip cat ips | awk '{ FS = " " } { print $10 | "uniq" }' | sort | uniq > hist_ip cat new_ip | sed -e '/^\t/d' > block_this cat block_this >> black_list.txt cat block_this | awk '{ system("iptables -A INPUT -i eth0 -p tcp --dport 22 -j DROP -s " $0 )}'
goto START
---End of code---
No lo he probado (ya tengo mi propio sistema de lista negra) y, además, no soy un experto en scripting y no entiendo todo el código, pero por lo que śe, tiene buena pinta. A ver si a alguien le es de utilidad. - -- ¡Share your knowledge! Linux user id 332494 # http://counter.li.org/ PGP id 0xC5ABA76A # http://pgp.mit.edu/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQFB9/oNVW601sWrp2oRAkhfAKCdmxlMetUC13gsmfiD13eJWrCCZQCfWpJp vc0TJmHtAAFF26RZh6wEfdA= =Tv6Y -----END PGP SIGNATURE-----
Mas sencillo: #!/bin/bash ############################################################## for i in $(grep Invalid /var/log/messages|awk '{print $10}'|sort -u |sed -e "s/::ffff://g"); do iptables -A INPUT -p tcp --dport 22 -s $i -j DROP done ############################################################## Lo guardas en /bin, le das un chmod +x <archivo> y lo añades al cron (crontab -u root -e): 10 * * * * /bin/<archivo> salu2 El Miércoles, 26 de Enero de 2005 21:14, Aquiles escribió:
Hace un tiempo, mantuvimos un hilo acerca de como securizar el servicio ssh. http://lists.suse.com/archive/suse-linux-s/2005-Jan/0113.html
Me acuerdo que surgió la duda de cómo hacer que los usuarios ilegales fueran incluídos automáticamente en una lista negra; bien, pues hoy leyendo el grupo de news de security, he dado con esto:
#!/bin/csh
#Made by Jack-Benny, founder of cyberinfo.se, bluedogsecurity.cyberinfo.se #and linuxsecurity.cyberinfo.se #This is a script I wrote to automaticly block the SSH probes. #The code is pretty quick written and not fancy in anyway, but for #me it works like a dream! #If you find any bugs or have any improvments or suggestions #please drop me an e-mail: jake@cyberinfo.se
#A short explanation of how it works: #The script first uses grep to find the word Invalid in the #/var/log/messages file. #Then it takes field number 10 (Field separator is a whitespace) #wich is the IP number. #It then compares this to the "history" file and prints any new #IP's in the file new_ip. #Then the file new_ip is processed with sed ("old" IP's have #tab in front of them, "new" ones don't) #It is then written to file block_this and a black list (used #for backup purpose) #Finaly the new IP's are inserted to an IPTABLES command wich #blocks the IP access to port 22 #By the way: Sorry for the long lines, don't split them up, #it won't work if you do!!! #MUST BE RUN AS ROOT, it could also be a good idea to run it #in a separate directory as it genarates a lot of files...
touch hist_ip
START:
sleep 10 grep Invalid /var/log/messages > ips cat ips | awk '{ FS = " " } { print $10 | "uniq" }' | sort | uniq > ext_ip comm -1 hist_ip ext_ip > new_ip cat ips | awk '{ FS = " " } { print $10 | "uniq" }' | sort | uniq > hist_ip cat new_ip | sed -e '/^\t/d' > block_this cat block_this >> black_list.txt cat block_this | awk '{ system("iptables -A INPUT -i eth0 -p tcp --dport 22 -j DROP -s " $0 )}'
goto START
---End of code---
No lo he probado (ya tengo mi propio sistema de lista negra) y, además, no soy un experto en scripting y no entiendo todo el código, pero por lo que śe, tiene buena pinta. A ver si a alguien le es de utilidad.
-- ¡Share your knowledge!
Linux user id 332494 # http://counter.li.org/ PGP id 0xC5ABA76A # http://pgp.mit.edu/
El 2005-01-27 a las 09:32 +0100, chakal escribió:
##############################################################
for i in $(grep Invalid /var/log/messages|awk '{print $10}'|sort -u |sed -e "s/::ffff://g"); do iptables -A INPUT -p tcp --dport 22 -s $i -j DROP done
##############################################################
Lo guardas en /bin, le das un chmod +x <archivo> y lo añades al cron (crontab -u root -e):
10 * * * * /bin/<archivo>
Pero buscar simplemente por la cadena "Invalid" me parece un poco arriesgado. Se podría ampliar, ¿no? -- Saludos Carlos Robinson
Claro al ponerlo y enviar me faltaba depurarlo xD y si mejor cercionarse que la cadena que contiene Invalid es referida al servidor sshd por lo tanto podriamos poner: ############################################################## for i in $(cat /var/log/messages |grep sshd |grep Invalid|awk '{print $10}'| sort -u |sed -e "s/::ffff://g"); do iptables -A INPUT -p tcp --dport 22 -s $i -j DROP done ##############################################################
El 2005-01-28 a las 04:26 +0100, chakal escribió:
Claro al ponerlo y enviar me faltaba depurarlo xD y si mejor cercionarse que la cadena que contiene Invalid es referida al servidor sshd por lo tanto podriamos poner:
##############################################################
for i in $(cat /var/log/messages |grep sshd |grep Invalid|awk '{print $10}'| sort -u |sed -e "s/::ffff://g"); do iptables -A INPUT -p tcp --dport 22 -s $i -j DROP done
##############################################################
En la lista "suse-security" acaba de salir el tema, y han dicho esto: |> Date: Thu, 03 Feb 2005 15:10:36 -0600 |> From: Michael Weber |> Subject: Re: [suse-security] SSH attacks. |> |> Swatch is your friend! |> |> It watches log files in real time (within a second or two, anyway) and |> reacts just like you want. |> |> Have it watch the security log file for failed attempts from a single |> IP and run an IPTABLES command when a count is reached within a certain |> time period. No lo he mirado, ni siquiera dicen de donde bajarlo; pero los que tengais maquinas con el ssh abierto os puede interesar mirarlo. La idea básica es la misma, mirar el syslog, pero dinámicamente (tailf, por ejemplo). -- Saludos Carlos Robinson
Carlos E. R. wrote:
El 2005-01-28 a las 04:26 +0100, chakal escribió:
Claro al ponerlo y enviar me faltaba depurarlo xD y si mejor cercionarse que la cadena que contiene Invalid es referida al servidor sshd por lo tanto podriamos poner:
##############################################################
for i in $(cat /var/log/messages |grep sshd |grep Invalid|awk '{print $10}'| sort -u |sed -e "s/::ffff://g"); do iptables -A INPUT -p tcp --dport 22 -s $i -j DROP done
##############################################################
En la lista "suse-security" acaba de salir el tema, y han dicho esto:
|> Date: Thu, 03 Feb 2005 15:10:36 -0600 |> From: Michael Weber |> Subject: Re: [suse-security] SSH attacks. |> |> Swatch is your friend! |> |> It watches log files in real time (within a second or two, anyway) and |> reacts just like you want. |> |> Have it watch the security log file for failed attempts from a single |> IP and run an IPTABLES command when a count is reached within a certain |> time period.
No lo he mirado, ni siquiera dicen de donde bajarlo; pero los que tengais maquinas con el ssh abierto os puede interesar mirarlo. La idea básica es la misma, mirar el syslog, pero dinámicamente (tailf, por ejemplo).
En sourceforge aparece http://sourceforge.net/projects/swatch/ voy a instalarlo ahora mismo a ver que tal
El Viernes, 4 de Febrero de 2005 12:01, Emiliano Sutil escribió:
No lo he mirado, ni siquiera dicen de donde bajarlo; pero los que tengais maquinas con el ssh abierto os puede interesar mirarlo. La idea básica es la misma, mirar el syslog, pero dinámicamente (tailf, por ejemplo).
En sourceforge aparece
http://sourceforge.net/projects/swatch/
voy a instalarlo ahora mismo a ver que tal
* Swatch es un analizador de logs al igual y creo que inferior a logsurfer, vamos que no soluciona el asunto. * Con iptables, parche 3.16 iptables -A FORWARD -m recent --name mamonssh --rcheck --seconds 60 -j DROP iptables -A FORWARD -p tcp -i eth0 --dport 22 -m recent --name mamonssh \ --set -j DROP * En /etc/ssh/sshd_config tambien valdra. LoginGraceTime 5 MaxAuthTries 2 # <-- dependiente de version MaxStartups 1:5:20 * Colocar a escuchar el servidor en otro puerto.
El 2005-02-04 a las 14:27 +0100, jose maria escribió:
* Swatch es un analizador de logs al igual y creo que inferior a logsurfer, vamos que no soluciona el asunto.
* Con iptables, parche 3.16
iptables -A FORWARD -m recent --name mamonssh --rcheck --seconds 60 -j DROP iptables -A FORWARD -p tcp -i eth0 --dport 22 -m recent --name mamonssh \ --set -j DROP
Acaban de poner un método muy interesante - no está fino, pero es una idea - y es del mismo estilo que el tuyo: |Date: Fri, 4 Feb 2005 09:56:05 -0500 |From: Bruce Smith |Subject: Re: [suse-security] SSH attacks. | |... | |I'll check into swatch when I get time, but for now I'll share the |iptables rules I ended up with with this list as my thanks to |everyone. This will block any IP for 60 seconds that tries to connect |5 or more time in a one minute time frame (along with logging it). |It's easy to test, just login multiple times and ALL the connections |will freeze for awhile when you hit the login limit: | | iptables -A INPUT -p tcp --syn --dport 22 -i eth0 -m recent --name sshattack --set | iptables -A INPUT -m recent --name sshattack --rcheck --seconds 60 --hitcount 5 -j LOG --log-prefix 'SSH attack: ' | iptables -A INPUT -m recent --name sshattack --rcheck --seconds 60 --hitcount 5 -j DROP Parece que usa el modulo del kernel "recent", y la idea es bloquear y registrar cualquier IP que ha intentado conectarse 5 o más veces en el último minuto. La pega es que también cuenta las conexiones válidas, así que un scp tendría problemas. Más no puedo decir, casi no se nada de iptables. -- Saludos Carlos Robinson
participants (5)
-
Aquiles
-
Carlos E. R.
-
chakal
-
Emiliano Sutil
-
jose maria