Tienda Wifi

Tienda Wifi
CiudadWireless es la tienda Wifi recomendada por elhacker.NET

Entradas Mensuales

Síguenos en:

Canal Oficial Telegram de elhacker.NET Grupo Facebook elhacker.NET Twitter elhacker.NET Canal Youtube elhacker.NET Comunidad Steam: Grupo elhacker.NET Mastodon

Entradas populares

PostHeaderIcon Floodmon: alerta, detecta y mitiga ataques SYN Flood


Ya hemos visto en entradas anteriores cómo mitigar un ataque DDoS con DDoS Deflate un sencillo script bash para servidores linux, y ahora veremos el script floodmon, un daemon escrito en perl que monitoriza ataques SYN flood (inundaciones) y es capaz de mitigar el ataque modificando en tiempo real la pila TCP/IP (optimizando), hacer un null-route (banear) a rangos de ip's de los atacantes, capturar los paquetes y además alertar por e-mail y/o sms.


floodmon es capaz de modificar en tiempo real la pila tcp/ip analizando cada 15 segundos en busca de un ataque de inundación llamado SYN flood. No utiliza iptables para bloquear ip's, directamente añade un null-route con iproute para descartar los paquetes de la ip atacante y la restaura a los 10 minutos (valores configurables)

Ver el número de conexiones en estado SYN_RECV

netstat -an | grep :80 | grep -i syn | wc -l
Por defecto cuando floodmon detecta 350 conexiones o más en estado SYN_RECV pasa al nivel 1 de alerta.

por defecto en caso de un ataque de nivel 2 ( más de 500 conexiones SYN_RECV) se chequea el '/proc/net' y  '/proc/sys/net'  cada 1,5 segundos, en el nivel 3 cada 1 segundo y en el nivel 4 cada 0,5 segundos.

Con iptables una de las maneras más sencillas pero efectivas de mitigar un ataque es con el módulo recent:

/sbin/iptables -I INPUT -p tcp -m state --state NEW --dport 80 -m recent --update --seconds 15 --hitcount 10 -j DROP

 Limitar ataques SYN_Flood usando iptables con limit y limit-burst


--limit rate[/second|/minute|/hour|/day] Maximum average matching rate: specified as a number, with an optional `/second’, `/minute’, `/hour’, or `/day’ suffix; the default is 3/hour.

--limit-burst

Maximum initial number of packets to match: this number gets recharged by one every time the limit specified above is not reached, up to this number; the default is 5.
iptables -N DDoS
iptables -A DDoS -m limit –limit 1/s –limit-burst 10 -j RETURN
iptables -A DDoS -j LOG –log-prefix “[Recibiendo ataque DDOS]“
iptables -A DDoS -j DROP

iptables -N syn-flood
iptables -A INPUT -p tcp --dport 80 --syn -j syn-flood
iptables -A syn-flood -m limit --limit 50/s --limit-burst 100 -j RETURN
iptables -A syn-flood -j LOG --log-prefix "SYN flood: " --log-level 4
iptables -A syn-flood -j DROP
Con --limit se especifica una media, no un caudal. Por ejemplo: decir 3/minuto puede significar que en el primer minuto se reciben 3 paquetes y en el segundo también 3 o puede significar que en el primer minuto se reciben 5 y en el segundo 1... la media sigue siendo 3/minuto.

--limit-bust especifica un máximo, si no se especifica un --limit-burst por defecto vale 5 y significa que se aceptaran los primeros 5 paquetes y luego se esperara hasta alcanzar la media para seguir aceptando. Parece complicado pero no lo es.

Ejemplo: especificaste un --limit 3/segundo y un --limit-burst 6, entonces se aceptarán los primeros 6 paquetes, no importa que tan seguido vengan, luego se dejara de aceptar hasta alcanzar la media, es decir se esperará a que se cumplan 2 segundos y luego se volverá a permitir un máximo de 6.

-A INPUT -p tcp -m tcp --dport 80 -m limit --limit 75/second --limit-burst 120 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -m limit --limit 75/second --limit-burst 200 -j LOG
-A INPUT -p tcp -m tcp --dport 80 -j DROP

Tal y cómo hemos visto en anteriores ocasiones, una de las mejores maneras de mitigar (que no parar) un ataque es modificando, optimizando los parámetros de la pila tcp/ip, número de conexiones.



Los valores del /proc/sys/net/ipv4 controlan la pila ipv4, número de conexiones en espera, número de conexiones máximas, reduciendo valores de tiemout,


  • tcp_max_syn_backlog (/proc/sys/net/ipv4/tcp_max_syn_backlog)
  • tcp_syncookies (/proc/sys/net/ipv4/tcp_syncookies)
  • somaxconn (/proc/sys/net/core/somaxconn)  incluye sockfd y backlog
  • tcp_synack_retries
  • ip_conntrack_max ( ip_conntrack: table full, dropping packet.) y nf_conntrack_max 
  • ip_conntrack_tcp_timeout_syn_recv (net.ipv4.netfilter.ip_conntrack_tcp_timeout_syn_recv)
Tuning y hardering sysctl.conf
http://wiki.elhacker.net/sistemas-operativos/gnulinux/tuning-sysctl-conf

Protección contra ataques DoS de inundación SYN El ataque de denegación de servicio (DoS) por inundación SYN ("SYN Flood") consigue consumir todos los recursos de la máquina, haciendo que sea necesario reiniciarla para volver a funcionar con normalidad.

Cada vez que se realiza una conexión TCP/IP existe una negociación de tres pasos:




  1. El cliente envía un paquete (paquete 1) al servidor con el bit SYN activado y permanece a la escucha.
  2. El servidor responde al cliente con un paquete de confirmación (paquete 2) y permanece a la escucha.
  3. El cliente envía un tercer paquete (paquete 3) que consolida la conexión.



La información recibida en el paquete 1 se conserva dentro de una cola para que pueda ser comparada con los datos recibidos en el paquete 3 y dar por establecida la conexión. Esta cola es de un tamaño limitado y
tiene un tiempo de latencia muy elevado.

El ataque de inundación SYN consiste en llenar esa cola, mediante el envío de un gran número de paquetes 1 y nunca respondiendo con un paquete 3. En el momento en que se llena la cola, el sistema es incapaz
de atender cualquier otra petición de conexión que reciba.

En Windows también es posible cambiar los valores por defecto de la pila TCP/IP (Hardening the TCP/IP stack)

Activación de la protección anti Syn Flood:

C:\>reg add HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters /v SynAttackProtect /t REG_DWORD /d 1

Aumentamos el 'backlog queue'

C:\>reg add HKLM\System\CurrentControlSet\Services\AFD\Parameters /v EnableDynamicBacklog /t REG_DWORD /d 1
C:\>reg add HKLM\System\CurrentControlSet\Services\AFD\Parameters /v MinimumDynamicBacklog /t REG_DWORD /d 20
C:\>reg add HKLM\System\CurrentControlSet\Services\AFD\Parameters /v MaximumDynamicBacklog /t REG_DWORD /d 20000
C:\>reg add HKLM\System\CurrentControlSet\Services\AFD\Parameters /v DynamicBacklogGrowthDelta /t REG_DWORD /d 10
 
Decrementamos el tiempo de espera en conexiones 'Half Open'

C:\>reg add HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters /v TcpMaxConnectResponseRetransmissions /t REG_DWORD /d 2
Ejemplo ataque syn-flood al puerto 80 con servidor web Apache (conexiones reading)



Instalación de floodmon

La documentación completa de floodmon se puede encontrar en la web del proyecto en SourceForge

Hay que copiar el fichero binario floodmon al directorio /usr/sbin/, el fichero de configuración floodmon.conf al directorio /etc/

Renombrar el fichero floodmon.initd a floodmon y copiarlo en el directorio /etc/init.d/ o /etc/rc.d/init.d

Floodmon crea un archivo de registro '/ var/log /floodmon.log' y hace una copia de seguridad de todo el sistema de configuración del usuario (pila TCP/IP) en '/var/cache/floodmon /' antes de realizar cualquier modificación.

En CentOS los valores por defecto son:



#!/bin/sh
echo 5 > /proc/sys/net/ipv4/tcp_synack_retries
echo 0 > /proc/sys/net/ipv4/tcp_syncookies
echo 1024 > /proc/sys/net/ipv4/tcp_max_syn_backlog
echo 1024 > /proc/sys/net/core/somaxconn
echo 1 > /proc/sys/net/ipv4/conf/eth0/rp_filter
echo 1 > /proc/sys/net/ipv4/conf/default/rp_filter
echo 0 > /proc/sys/net/ipv4/conf/lo/rp_filter
echo 1 > /proc/sys/net/ipv4/conf/all/rp_filter
echo "180000" > /proc/sys/net/ipv4/tcp_max_tw_buckets
echo "10" > /proc/sys/net/ipv4/tcp_fin_timeout
echo "32768 61000" > /proc/sys/net/ipv4/ip_local_port_range
echo "0" > /proc/sys/net/ipv4/tcp_rfc1337
echo "0" > /proc/sys/net/ipv4/tcp_tw_reuse
echo "0" > /proc/sys/net/ipv4/tcp_tw_recycle
echo 60 > /proc/sys/net/ipv4/netfilter/ip_conntrack_tcp_timeout_syn_recv
echo 120 > /proc/sys/net/ipv4/netfilter/ip_conntrack_tcp_timeout_syn_sent
echo 65536 > /proc/sys/net/ipv4/netfilter/ip_conntrack_max
echo 8192 > /sys/module/ip_conntrack/parameters/hashsize

Requisitos

Obviamente perl y algunos módulos:

Time::HiRes : (sólo usado en el modo --debug)

- Debian : # apt-get install libtime-hires-perl
- RH/CentOS : # yum install perl-Time-HiRes

MIME::QuotedPrint : para enviar los e-mails

Net::Pcap : sólo usado para guardar el log del ataque en formato pcap 

- Debian : # apt-get install libnet-pcap-perl
- RH/CentOS : # yum install perl-Net-Pcap

iproute : floodmon usa iproute para "banear" las ip's atacantes, no usa iptables

- Debian : # apt-get install iproute
- RH/CentOS : # yum install iproute

sendmail :para enviar los e-mails y wget : para enviar los SMS

Para arrancar floodmon simplemente debemos ejecutar:

floodmon --daemon
O arrancar el servicio:

service floodmon start

Configurando floodmon


Fichero de configuración floodmon.conf en /etc

######################################################################
# floodmon.conf
#
# Floodmon configuration file
# This file must be copied to your '/etc/' directory
#
# If you make changes to this file while floodmon is running,
# run `floodmon --reload` so that the daemon will reload it.
######################################################################

######################################################################
# Network interface. It is only used to capture SYN packets
# and setting up rp_filter (reverse-path filtering).
# Example :  'eth0', 'venet0'...
INTERFACE = 'eth0'
######################################################################
# Connection tracking table : if you are not using it, set
# this value to '1' (see documentation for more info).
# Default value : 0
NO_CONNTRACK = '0'

######################################################################
# Send alert by email to the admin
# Accepted values : 0, 2, 3 and 4
# 0 == no alert
# 2 == send an email when alert level 2 is reached
# 3 == send an email when alert level 3 is reached
# 4 == send an email when alert level 4 is reached
# Default value : '2'
EMAIL_ALERT = '2'
# Email alert frequency (in minutes).
# During an attack, you will not receive more than one email
# every [EMAIL_ALERT_FREQ] minutes.
# Default value : '30'
EMAIL_ALERT_FREQ = '30'
# Admin address email where alerts and reports should be sent to :
ADMIN_EMAIL = 'webmaster@elhacker.net'
# Floodmon can attach to its email alert a capture of the last
# SYN packets received. The file uses 'pcap' format and can
# be open/read with a network analyzer like Wireshark
# (http://www.wireshark.org).
# Valuess : 0      == don't send anything (deactivated)
#           1 Ã  99 == number of packets to capture
# Default value : '25'
DUMP_SYNPACKETS = '99'
######################################################################
# Send a SMS alert to the admin.
# You must be using a service (VOIP etc) that allows you to send
# SMS from a simple URL (HTTP or HTTPS).
# The whole URL + its parameters should be included.
# Don't use any reserved/accentued chars and replace all spaces
# between words with the '+' sign.
# Example with voipbuster.com service :
# SMS_ALERT = 'https://myaccount.voipbuster.com/clx/sendsms.php?username=USERNAME&password=PASSWD&from=SENDER&to=PHONENUMBER&text=SYN+flood+alert+on+mydomain.com'
#
# You can test if everything is working well with the command :
# `floodmon --sms-test`
#
SMS_ALERT = ''
# SMS alert frequency (in hours).
# During an attack, you will not receive more than one SMS
# every [SMS_ALERT_FREQ] hours.
# Default value : '24'
SMS_ALERT_FREQ = '24'

######################################################################
# Null-routed IPs flush frequency (minutes).
# By default, IPs are unblocked after 10 minutes.
FLUSH_FREQ = '10'
# Network mask used to nullroute IPs :
# Accepted values : 8, 16 or 24
#  8 == 0.xxx.xxx.xxx
# 16 == 0.0.xxx.xxx
# 24 == 0.0.0.xxx
# Default value : '16'
NETMASK = '24'

######################################################################
# Log file verboseness (/var/log/floodmon.log).
# Values :  1 == log daemon start/stop and errors only.
#           2 == same as above + alert levels, number of SYN received
#                and nullrouted IPs etc.
# Default value : '2'
# Warning : during a large scale attack, you are advised to set
# this variable to '1' to avoid flooding the logfile.
LOG_LEVEL = '2'

######################################################################
#
#                        /!\ IMPORTANT /!\
#
# DO NOT ACTIVATE/MODIFY ANY OF THE FOLLOWING VALUES WITHOUT HAVING
# READ THE FULL DOCUMENTATION :
#        => http://floodmon.sourceforge.net/   <=
#
######################################################################
# To activate a variable, uncomment the corresponding line by
# removing the '#' sign.
# All value should be integers only, except 'LOOP_DELAY' which can
# accept '.' for milliseconds.
# The 4 values represent all 4 alert levels and should always be
# space-separated.
# eg. : VARIABLE = 'level_1 level_2 level_3 level_4'
######################################################################
MAX_SYN            = '150 300 400 500'
#SYN_COOKIES        = '0 1 1 1'
#MAX_SYN_QUEUE      = '10000 20000 100000 200000'
#SOMAXCONN          = '10000 20000 40000 65000'
#MAX_SYNACK_RETRY   = '3 2 1 0'
#LOOP_DELAY         = '15 1.5 1 0.5'
NULLROUTE_SUBNET   = '50 100 200 300'
#CONNTRACK_TIMEOUT  = '60 21 9 3'
#CONNTRACK_MAX      = '65536 65536 131072 131072'
#CONNTRACK_HASHSIZE = '16384 65536 65536 131072'
#BEST_EFFORT        = '0 1 1 1'
######################################################################
Los últimos valores (a partir de MAX_SYN) están configurados por defecto para ofrecer una buena protección, pero pueden ser cambiados en cualquier momento:

 floodmon --reload
floodmon v0.9.5 : (c) Jerome Bruandet - http://floodmon.sourceforge.net/
        [OK] : reloading user configuration

Hay 4 valores según el nivel de alerta


  • Nivel de Alerta 1 = 350 conexiones SYN_RECV
  • Nivel de Alerta 2 = 500 conexiones SYN_RECV
  • Nivel de Alerta 3 = 1.000 conexiones SYN_RECV
  • Nivel de Alerta 4 = 2.000 conexiones SYN_RECV



Estadísticas con floodmon --stats
[ ------------------- TCP ------------------- ]
- current SYN_RECV sockets  . . : 0
- sockets SYN_RECV reset  . . . : 86736
- syncookies sent . . . . . . . : 727267
- syncookies received . . . . . : 0
- invalid syncookies received . : 5
- failed connection attempts  . : 151,980
- received segments . . . . . . : 2,583,815,242
- sent segments . . . . . . . . : 3,644,082,835
- in/out seg. ratio . . . . . . : 0.709
[ ------------------ Route ------------------ ]
- null-routed IPs/blocks  . . . : 0
[ ------------------- IP -------------------- ]
- dropped packets (OutNoRoutes) : 119,918
[ ------------------ ICMP --------------------]
- received  . . . . . . . . . . : 1,080,128
- sent  . . . . . . . . . . . . : 17,494,885
- in/out ratio  . . . . . . . . : 0.062
[ ------------------- UDP ------------------- ]
- received packets  . . . . . . : 4,289,029,403
- sent packets  . . . . . . . . : 3,192,131,079
- in/out ratio  . . . . . . . . : 1.344
[ ------------------ eth0 ------------------- ]
- total bytes received  . . . . : 2,166,570,455
- total bytes sent  . . . . . . : 1,202,731,119
- total packets received  . . . : 18,716,243
- total packets sent  . . . . . : 31,273,511
- in/out packets ratio  . . . . : 0.598
[ ------------------------------------------- ]

Alertas de floodmon: detectando el ataque

El kernel avisa que manda las syn-cookies:
May 26 19:08:53 ns2 kernel: possible SYN flooding on port 30033. Sending cookies.
May 26 19:09:53 ns2 kernel: possible SYN flooding on port 30033. Sending cookies.
May 26 19:10:53 ns2 kernel: possible SYN flooding on port 30033. Sending cookies.
May 26 19:11:53 ns2 kernel: possible SYN flooding on port 30033. Sending cookies.
May 26 19:12:53 ns2 kernel: possible SYN flooding on port 30033. Sending cookies.
May 26 19:13:53 ns2 kernel: possible SYN flooding on port 30033. Sending cookies.
May 26 19:14:53 ns2 kernel: possible SYN flooding on port 30033. Sending cookies.
 
Fichero de log: /var/log/floodmon.log
May 22 20:05:24 [notice] floodmon v0.9.5 : running daemon (PID : 5612)
May 26 19:08:53 [ ] current number of SYN_RECV : 1033
May 26 19:08:53 [++++++] increasing alert level : 2/4
May 26 19:08:55 [ ] current number of SYN_RECV : 1033
May 26 19:08:55 [++++++] increasing alert level : 3/4
May 26 19:08:56 [ ] current number of SYN_RECV : 1035
May 26 19:08:56 [++++++] increasing alert level : 4/4
May 26 19:10:15 [ ] current number of SYN_RECV : 975
May 26 19:10:15 [------] decreasing alert level : 3/4
May 26 19:10:16 [ ] current number of SYN_RECV : 1025
May 26 19:10:16 [++++++] increasing alert level : 4/4
May 26 19:12:14 [ ] current number of SYN_RECV : 999
May 26 19:12:14 [------] decreasing alert level : 3/4
May 26 19:12:15 [ ] current number of SYN_RECV : 1024
May 26 19:12:15 [++++++] increasing alert level : 4/4
May 26 19:13:37 [ ] current number of SYN_RECV : 977
May 26 19:13:37 [------] decreasing alert level : 3/4
May 26 19:13:38 [ ] current number of SYN_RECV : 1025
May 26 19:13:38 [++++++] increasing alert level : 4/4
May 26 19:15:28 [ ] current number of SYN_RECV : 982
May 26 19:15:28 [------] decreasing alert level : 3/4
May 26 19:15:29 [ ] current number of SYN_RECV : 1025
May 26 19:15:29 [++++++] increasing alert level : 4/4
May 26 19:15:37 [ ] current number of SYN_RECV : 2
May 26 19:15:37 [------] decreasing alert level : 3/4
May 26 19:15:49 [ ] current number of SYN_RECV : 0
May 26 19:15:49 [------] decreasing alert level : 2/4
May 26 19:16:07 [ ] current number of SYN_RECV : 0
May 26 19:16:07 [------] decreasing alert level : 1/4




Baneando (Null-route) rango /24 - Tipo 0.0.0.x
Configuración NULLROUTE_SUBNET   = '50 100 200 300'
 
May 27 01:46:22 [XXXXXX] 1 blocks /24 null-routed (more than 50 SYN_RECV)
May 27 01:56:08 [------] flushing null-routed blocks : x 1 /24
May 27 02:53:45 [XXXXXX] 1 blocks /24 null-routed (more than 50 SYN_RECV)
May 27 03:03:31 [------] flushing null-routed blocks : x 1 /24
May 27 06:47:59 [XXXXXX] 1 blocks /24 null-routed (more than 50 SYN_RECV)
May 27 06:57:45 [------] flushing null-routed blocks : x 1 /24
May 27 07:10:01 [XXXXXX] 1 blocks /24 null-routed (more than 50 SYN_RECV)
May 27 07:19:48 [------] flushing null-routed blocks : x 1 /24
May 27 08:07:08 [XXXXXX] 1 blocks /24 null-routed (more than 50 SYN_RECV)
May 27 08:15:54 [XXXXXX] 1 blocks /24 null-routed (more than 50 SYN_RECV)
May 27 08:16:54 [------] flushing null-routed blocks : x 2 /24
May 27 08:22:10 [XXXXXX] 1 blocks /24 null-routed (more than 10 SYN_RECV)
May 27 08:31:56 [------] flushing null-routed blocks : x 1 /24
May 27 12:51:28 [XXXXXX] 1 blocks /24 null-routed (more than 50 SYN_RECV)
May 27 13:01:14 [------] flushing null-routed blocks : x 1 /24
May 27 15:29:19 [XXXXXX] 1 blocks /24 null-routed (more than 10 SYN_RECV)
May 27 15:39:05 [------] flushing null-routed blocks : x 1 /24
May 27 18:37:02 [XXXXXX] 1 blocks /24 null-routed (more than 50 SYN_RECV)
May 27 18:46:48 [------] flushing null-routed blocks : x 1 /24 
 
 
Alerta recibida por e-mail:

On 26-05-2014 at 19:08:53
*** Possible SYN flood attack ***
- number of SYN_RECV : 1033
- number of IP blocks : 1019
- IP blocks nullrouted : 0
- number of individual IPs : 1029
- current alert level : 2/4
Please connect to your server and check the logfile :
/var/log/floodmon.log
Attachment : pcap dump of the last 25 SYN packets received

Gráfico del ataque monitorizado con Monitorix

40 millones de paquetes recibidos:



pico de 360Mb/s recibido:




1 comentarios :

Juan Cruz dijo...

Gracias por la información. Muy útil y descriptivo

Publicar un comentario

Los comentarios pueden ser revisados en cualquier momento por los moderadores.

Serán publicados aquellos que cumplan las siguientes condiciones:
- Comentario acorde al contenido del post.
- Prohibido mensajes de tipo SPAM.
- Evite incluir links innecesarios en su comentario.
- Contenidos ofensivos, amenazas e insultos no serán permitidos.

Debe saber que los comentarios de los lectores no reflejan necesariamente la opinión del STAFF.