
+------+-------------------------------------------+----------+--------------+
|  +-->|     Denegacion de Servicio Distribuido    |<---------|    Yo_Soy    |
+->|<--> r17_04 <-+-----------+-----+--------->+--------------+----------->|-+
   +--------------------------------------------------------------------------



DDOS

1.- Introduccion.
2.- Funcionamiento del ataque.
3.- Herramientas de ataque.
    3.1 - Stacheldraht.
    3.2.- Trinoo.
    3.3.- Tribe Flood Network.
    3.4.- TFN2K.
4.- Tipos de Denegacion de Servicio
5.- Soluciones
    5.1.- Network Ingress\Egress Filtering.
6.- Conclusion
7.- Referencias


 1.- Introduccion
 ----------------

        Antes que nada, debo decir que la informacion aqui expuesta no debe
ser utilizada para joder y chingar, mas bien esta informacion se provee con
el fin de aclarar y exponer como es que trabajan estos ataques,  mas no con
el fin de utilizarlos como terrorismo electronico.

Distributed Denial of  Service  (Denegacion de Servicio Distribuido) o DDOS
( DDOS sera usado de aqui en adelante en este documento) es  como su nombre
lo dice,  un  ataque  de  DoS  distribuido ,  esto es  varias  computadoras
conectadas a un red que  envian  un flood  de paquetes para hacer  caer una
maquina, este ataque es lanzado desde una sola maquina ,  misma que cordina
los ataques de  las demas maquinas (tenemos en cuenta que una maquina mueve
a las demas y de ahi se lanza el ataque completo) Para una mayor compresion
de esto, ver el diagrama de abajo:

                    .---.
                ....| 2 |..........
              .'    `---' .---.    '....                      
             . ...........| 2 |..........'..
        .---.       .---. `---'             '......   .--------------.       
        | 1 |.......| 2 | .........................`. | HOST VICTIMA |
        `---'       `---' .---.              ......'  `--------------'
            '.............| 2 |.............'
              .     .---. `---'     ......'         
               '....| 2 |..........'                
                    `---'

Pues el unico proposito de este ataque  es hacer caer una o varias maquinas
que  normalmente no se  ven afectadas por  un ataque sencillo  de una  sola
maquina , por poner un ejemplo , un sistema con una ancho de banda de T3 no
se ve muy (mas bien casi nada) afectada por un ataque DoS desde un modem de
28.800 bps ( en caso de que se  trate de un ataque DoS de flood de paquetes
y no un buffer  overflow en  algun demonio que  vaya consumiendo  memoria y
haga que el server se caiga).


 2.- Funcionamiento del ataque
 -----------------------------

        Antes de lanzar el  ataque ,  el atacante debera haber penetrado en
varios hosts, instalar el software ( en este caso un software cliente ) que
le permitira  hacer el ataque DDOS de forma  que desde el  otra maquina que
hara de servidor,  envie una serie de comandos a las maquinas cliente, para
iniciar el ataque.

La mejor defensa  es asegurar tu  maquina, tener  seguridad y estar siempre
revisando  si  eres  vulnerable a  algun  ataque  que pueda  comprometer tu
maquina y por lo tanto ser suceptible a que te instalen un programa de DDOS
cliente.


 3.- Herramientas de ataque
 --------------------------

        Voy a explicar mas o menos las herramientas en forma teorica , sin
explicar  como se usan  ( lo cual no  es el proposito de este  documento ),
ademas si quieres obtenerlas, buscalas en Internet =P.

Actualmente las  herramientas  para hacer  DDOS no envian un  simple flood,
sino que ademas spoofean la direccion de donde provienen los paquetes.

Las Herramientas de ataque mas utilizadas son : Trinoo, TFN, Stacheldraht y
TFN2K.


 3.1.- TRINOO
 ------------

        Una red  de  trinoo es  creada por  el  programa  servidor, llamado
maestro (master.c) y por los  demonios del trinoo (ns.c) y  utilizan  estos
puertos por default ( estos puertos pueden  ser cambiados facilmente en las
fuentes ):

          1524 tcp    
          27665 tcp     <-- Atacante al maestro
          27444 udp     <-- Maestro a los demonios
          31335 udp     <-- Demonio al maestro
  
Las redes que  forman la red de trinoo estan  protegidas por una contrase~a
( ambos, cliente y servidor ) para protegerse del propio administrador o de
otros atacantes. Las contrase~as por default son:

         "l44adsl"           daemon password
         "gOrave"            trinoo master server 
         "betaalmostdone"    trinoo master remote interface password
         "killme"            trinoo master password


Podemos utilizar  el  comando 'strings' para  obtener  el password  cifrado
(utiliza la funcion crypt() de manera que lo podemos crackear como si de un
archivo de /etc/passwd se tratase), por ejemplo en el demonio del trinoo:


 #  strings - ns
  . . .
 socket
 bind
 recvfrom
 %s %s %s
 aIf3YWfOhw.V.      <--------  password "l44adsl" cifrado usando crypt()
 PONG
 *HELLO*
 . . .

Vamos, este documento no tiene porque ser oscuro, asi que aqui va algo para
los  adminstradores, si crees  que tu  maquina esta  corriendo  el  demonio,
puedes hacer un netstat -a --inet como viene:


 # netstat -a --inet
 Active Internet connections (servers and established)
 Proto Recv-Q Send-Q Local Address           Foreign Address         State 
 . . .
 udp        0      0 *:1024                  *:*                           
 udp        0      0 *:27444                 *:*                           
 . . .

 # lsof | egrep ":27444"
 ns       1316     root    3u  inet       2502              UDP *:27444 


Vemos un "ns" (recuerda que el demonio del trinoo es ns.c), seguimos:


 # lsof -p 1316
 COMMAND  PID USER   FD   TYPE DEVICE    SIZE   NODE NAME
 ns      1316 root  cwd    DIR    3,1    1024 153694 /tmp/...
 ns      1316 root  rtd    DIR    3,1    1024      2 /
 ns      1316 root  txt    REG    3,1    6156 153711 /tmp/.../ns
 ns      1316 root  mem    REG    3,1  342206  28976 /lib/ld-2.1.1.so
 ns      1316 root  mem    REG    3,1   63878  29116 /lib/libcrypt-2.1.1.so
 ns      1316 root  mem    REG    3,1 4016683  29115 /lib/libc-2.1.1.so
 ns      1316 root    0u   CHR    4,1           2967 /dev/tty1
 ns      1316 root    1u   CHR    4,1           2967 /dev/tty1
 ns      1316 root    2u   CHR    4,1           2967 /dev/tty1
 ns      1316 root    3u  inet   2502            UDP *:27444 
 ns      1316 root    4u  inet   2503            UDP *:1024 


Por  supuesto  que esto no es  aplicable  siempre, pues  no se trata  de un
metodo seguro en caso de que se le haya cambiado el nombre del binario y se
ejecute  con un  nombre menos  sospechoso o  que  se haya  instalado  algun
rootkit que esconda los archivos y procesos.

WINTRINO

En maquinas  windows, la version  de trinoo suele llamarse service.exe ( no
confundir con el services.exe de Windows NT) y generalmente se encuentra en
\windows\system y se instala en el registo en: HKEY_LOCAL_MACHINE/SOFTWARE/
Microsoft/Windows/CurrentVersion/Run .

Cuando se ejecuta el archivo se instala en \windows\system y generalmente
mide 23,145 bytes, este programa espera en el puerto 34555 una conexion UDP.
Aparentemente bloqueando este puerto y el 35555 logramos impedir el ataque.


------------------------------- trinokiller.c --------------------------
/*
 * AFRO-PRODUCTIONS.COM
 *
 * By your buddies at afro productions!
 *
 *   This program kills trino nodes on version 1.07b2+f3 and below.
 *
 *
 */

#include <stdlib.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>

#define KILL "d1e l44adsl d1e\n"

int main(int argc, char **argv)
{
	int sock;
	struct sockaddr_in s;
	struct hostent *h;
	char *host;

	if (argc == 1)
	{
		fprintf(stdout,"Usage: %s <ip>\n",argv[0]);
		return 0;
	}

	host = argv[1];

	sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);		

	s.sin_family = AF_INET;
  	s.sin_addr.s_addr = inet_addr(host);
  	s.sin_port = htons(27444);

	if (s.sin_addr.s_addr == -1)
	{
		h = gethostbyname(host);

		if (!h)
		{
			fprintf(stdout,"%s is an invalid target.\n",host);
			return 0;
		}

		memcpy(&s.sin_addr.s_addr,h->h_addr,h->h_length);
	}

	sendto(sock,KILL,strlen(KILL),0,(struct sockaddr *)&s,sizeof(s));

	fprintf(stdout,"Packet sent to target %s.\n",host);

	return 1;
}
------------------------------- trinokiller.c -------------------------- 


 3.2.- Tribe Flood Network (TFN)
 -------------------------------

Esta herramienta publica fue creada por el programador aleman Mixter, y una
red de TFN esta basada en el cliente ( tribe.c ) y el demonio (td.c);  esta
herramienta es  similar al trinoo  en cuanto a uso; actualmente existe otra
version mas actual de este programa, llamado TF2K creada por el mismo autor.


 3.3.- Tribe Flood Network 2000 (TFN2K)
 --------------------------------------

        Esta heramienta es considerada sofisticada para ser una herramienta
publica, de acuerdo con el autor, es  publica para que exista consiencia de
seguridad informatica en el mundo.

Utiliza  TCP,  UDP  o  ICMP  para  enviar  los  paquetes  y ademas  usa los
siguientes  ataques :  SYN flooding, UDP  flooding, ICMP echo reply attack,
SMURF, MIX, Targa3, ademas de que  permite abrir un root shell en un puerto
o ejecutar comandos remotos.

    
He aqui un programa para extraer los passwords de los binarios de tfn2k, ya
sea del binario 'td' o 'tfn'.


-------------------------------- tfn2kpass.c ----------------------------
/*
 * tfn2kpass - tfn2k Password Recovery. Extract password for tfn2k from a
 * td or tfn binary.
 *
 * Written by Simple Nomad [thegnome@razor.bindview.com] 21Feb2000
 *
 * More fun stuff at http://razor.bindview.com/, licensing at end
 * of file.
 *
 * Should compile and run fine on any Intel/Sun-based system:
 *    gcc -o tfn2kpass tfn2kpass.c
 *
 * Example usage:
 *    ./tfn2kpass tfn-binary-file
 *
 * Tested against binaries compiled on Intel Linux, Intel FreeBSD, and
 * Solaris. Thanks for the help, Jordan <jritter@razor.bindview.com>
 * and Paul <pashton@razor.bindview.com> from the RAZOR team.
 *
 */

/* includes */
#include <stdio.h>
#include <stdlib.h>

/*
 * Main program....
 */
int main(int argc, char *argv[])
{
  FILE *ftd;
  int i, search = 0, search2, found = 0, rew = 32;
  unsigned char recover[32];
  unsigned char password[32];
  unsigned char offset;
  char close[]="@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@";
  char check[sizeof(close)];

  /* Say hello... */
  printf("tfn2kpass - Recover the password from tfn2k's 'td' or 'tfn'\n");
  printf("Comments/bugs: Simple Nomad <thegnome@razor.bindview.com>\n");
  printf("http://razor.bindview.com/\n\n");

  if (argc!=2)
  {
    fprintf(stderr,"USAGE: tfn2kpass <td_filename>\n\n");
    fprintf(stderr,"EXAMPLES:\n");
    fprintf(stderr,"  tfn2kpass renamed_td\n");
    exit(-1);
  }

  ftd=fopen(argv[1],"rb");
  if (ftd == NULL)
  {
    fprintf(stderr,"Unable to open file %s.\n",argv[1]);
    exit(-1);
  }

  /* first we search the file for the first marker that we
     are close to the password -- the 40 @'s should be right
     after the password */
  while(!feof(ftd))
  {
    fseek(ftd,search,SEEK_SET);
    fread(&check,40,1,ftd);
    if (!strncmp(check,close,40))
    {
      found = 1;
      break;
    }
    search++;
  }

  if (found)
  {
    found = 0; /* reset our flag for next 'find' */
    search--;
    search2 = search;
    /* Now we'll search backward looking for the first non-zero
       value, which is the offset used to mask the password.
       The amount of zeroes depends upon platform as well as the
       daemon type (td or tfn), so we move back one at a time.
       Also it allows us to examine daemons compiled on a freebsd
       box from our linux box, for example. */
    while(search2!=0)
    {
      fseek(ftd,search2,SEEK_SET);
      fread(&offset,1,1,ftd);
      /* Sol bins have the needed "offset" right before the string
         of @'s as well as at the end of the password field, so we
         need to skip that byte. Also, if we do not shorten the
         amount of bytes for a Sol bin by one, we end up with one
         extra char at the beginning of the password. Go figure. */
      if((offset) && (search2 == search))
      {
        rew--;
      }
      else if(offset)
      {
        found = 1;
        break;
      }
      search2--;
    }
    if (found) /* if we found the offset, grab and print the password */
    {
      fseek(ftd,search2-rew,SEEK_SET);
      fread(&recover,32,1,ftd);
      fclose(ftd);

      for (i=0;i<32;i++) password[i]=recover[i] - offset;
      printf("The password is - ");
      for (i=0;i<32;i++)
      {
        if (isprint(password[i]))
          printf("%c",password[i]);
      }
      printf("\n\n");
    }
  }
  if(!found) printf("The password was not found\n\n");
  exit(0);
}

/*
 * BindView License -

Copyright (c) 2000 BindView Corporation.  All rights reserved.

By using this software, YOU AGREE to the following license terms.  IF YOU
DO NOT AGREE, YOU MAY NOT USE THE SOFTWARE.

1.  BindView believes that this software is safe for use in normal
circumstances, and has performed what it believes to be reasonable but
non-exhaustive testing to verify this.  The software is intended for use
only by experienced and knowledgeable computer professionals; IT IS
PROVIDED "AS IS, WITH ALL FAULTS," including source code so that the user
can study the source code and independently determine the software's
suitability.  BindView makes no warranty of any kind, express or implied,
and DISCLAIMS ANY AND ALL WARRANTIES, CONDITIONS, OR IMPLIED TERM OF
QUALITY, INCLUDING THE IMPLIED WARRANTIES OF TITLE, NON-INFRINGEMENT,
MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.  All use of the
software is entirely at the user's own risk.

2.  IN NO EVENT WILL BINDVIEW BE LIABLE FOR DAMAGES OF ANY KIND arising
from or relating to use of the software, whether such damages are direct,
indirect, incidental, consequential, exemplary, or any other kind, and
whether arising under contract, tort (including negligence), strict
liability, or otherwise.

3.  BindView will not object to your distribution of complete, unmodified
copies of the distribution package of the software as provided by
BindView, PROVIDED that you do not charge a fee other than a reasonable
fee for distribution services.  You may charge a fee for any warranty or
support services that you offer to purchasers of copies of the software.

4.  You may modify the software and distribute copies of the modified
software, PROVIDED:

	(a) that you distribute, together with the executable code of the
            modified software:
	
 		(1) the source code of the modified software, which must
		 contain the BindView copyright notice set forth above (in
		 addition to your own copyright notice if any); and

 		(2) a copy of the complete, unmodified distribution
		package of the software as provided by BindView; and

 	(b) that you clearly indicate in the source code and in an
 	    accompanying documentation file that the software is based on
	    BindView's software and was modified by you; and

 	(c) that you grant users of the modified software the same rights
	    as are granted to you by this license.

 *
 */
-------------------------------- tfn2kpass.c ----------------------------


 4.- Tipos de Denegacion de Servicio (DOS)
 -----------------------------------------


SMURF

Este ataque envia paquetes ICMP ( ping ) spoofeados con  direcciones de una 
maquina de la  misma red o con la direccion fuente de la misma victima, por
lo  tanto,  se  contesta  el  ping  hacia  si  misma y  comienza  un  flood
( inundacion ) de paquetes y la maquina termina callendose al consumirse el
ancho de banda.

ICMP echo reply attack

Similar al  smurf, pero  sin  enviar  datos  spoofeados  y  por  lo  tanto,
tendriamos  que tener  una conexion  mayor o  igual  para lograr hacer algo
contra un sitio  con un gran ancho de banda. ( Esto se ve minimizado con el
DDOS ).

MIX

Es un ataque combinado, envia paquetes UDP, SYN e ICMP.


 5.- Soluciones
 --------------

        La mayoria de  paquetes  usados  en  la actualidad en  ataques DDOS
utilizan el  spoofing, el primer router en  recibir el paquete  puede darse
cuenta  facilmente  del enga~o, pues  el router  tiene  que  saber de donde
provienen y hacia donde  van los paquetes, de tal manera  que pueda  rutear
correctamente los paquetes.

Si el paquete que llega al router, y si la direccion fuente no coincide con
la direccion de  la red de la cual proviene, el router deberia descartar el
paquete. Esta forma de  verificar los  paquetes es llamada Ingress o Egress
Filtering ( Filtro de acceso o salida )  dependiendo  del  punto de  vista,
Egress desde  el punto de  vista de  la red del cliente o Ingress  desde el
corazon de Internet.



 5.1.- Network Ingress\Egress Filtering
 --------------------------------------

Network Ingress  Filtering  es una  de las  soluciones  propuestas  por The
Internet Society para  detener los  ataques de  denegacion de  servicio que
utilice como fuente una direccion IP spoofeada. La solucion:

El primer  router debe  verificar  si la  direccion IP fuente proviene  del
mismo lado de la red en donde esta, es decir, que se trate de una direccion
valida,  de esta manera el router  se daria cuenta de  que los paquetes que
pasan por el estan spoofeados o no. Ejemplo:
 
                                                  12.0.0.0/8
                                                    router
                                                      |
                                                      |
   9.0.0.0/8                                          |
   Atacante -->  router  --->  ISP  --->  ISP  --->  ISP  --->  ISP
                   [1]         [A]         |
                                           |
                                           |
                                         router
                                       11.0.0.0/8


En  este  caso el ISP [A] le  provee el  acceso a  Internet a  el atacante,
cualquier  paquete que  envie el  atacante es  recibido por  el router [1],
usando Network Ingress Filtering en el router [1] cualquier paquete que no
provenga del  rango 9.0.0.0/8 es  descartado por el router, por  lo que no
llega a  su destino,  y esto  impide al atacante  realizar el  ataque  sin
delatar su verdadera direccion IP. En otras palabras:


  IF    el paquete proviene del rango 9.0.0.0/8
  THEN  el router deja pasar el paquete

  IF    el paquete proviene de cualquier otro lugar
  THEN  el router descarta el paquete


Otro ejemplo mas practico seria:

Supongamos que nosotros tenemos nuestro espacio con la direccion legal de:
200.200.200.0. En un router Cisco (otros routers ver en el sitio del
fabricante) , creamos una lista de acceso desde en el modo de configuracion
global:


  Router(config)# access-list 112 permit ip 200.200.200.0 0.0.0.255 any


Despues de que los filtros fueron creados, aplicariamos la interface hacia
dentro de nuestra red interna:


  Router*config/if(#ip access/group 112 in


Si asumimos que la interface es Ethernet 0 (eth0) podriamos pegar este
script del global configuration mode:


  access-list 112 permit ip 200.200.200.0 0.0.0.255 any

  int eth0

  ip access-group 112 in

  exit

  exit

  show running


Con esto hemos logrado que nuestro filtro que acabamos de crear solo deje
pasar los paquetes que provienen del rango 200.200.200.0 y si provenieran
de otra direccion IP, los descarte.


 6.- Conclusion
 --------------

        El  mayor  problema  de  esta  ataque es  consecuencia del  la mala
seguridad que presentan muchas de las maquinas presentes en Internet, y que
muchos administradores, si bien  no se preocupan  por ella, no se esfuerzan
como deberia (claro que siempre hay excepciones ;). Ademas la dificultad de
rastrear al atacante al realizar DDOS. Pero es un riesgo que debemos correr.


 7.- Referencias
 ---------------

 [1] - Have Script, Will Destroy (Lessons in DoS) by Brian Martin.
 [2] - Cisco, Strategies to Protect Against DDOS Attacks by Cisco Systems.
       http://www.cisco.com/warp/public/707/newsflash.html
 [3] - Distributed Denial of Service Attacks by Bennett Todd <bet@oven.com>
 [4] - DDOS Attack Mitigation by Elias Levy <aleph1@SECURITYFOCUS.COM>
 [5] - RFC 2267 - Network Ingress Filtering
 [6] - Distributed Denial Of Service attacks. A proposal based on routing
       by Fernando P. Schapachnik <fernando@via-net-works.net.ar>
 [7] - Global Incident Analisys Center: Egress Filtering v0.2 by SANS
       Institute.

                                    Yo_Soy - http://www.bigfoot.com/~varf
                            <yo_soy@raza-mexicana.org> <varf@bigfoot.com>

