def parse_interface(self, interface): if interface in pyw.interfaces() and pyw.modeget(interface) == "monitor": self.interface = interface else: print(c.F + " [-] Non Monitor card selected.") exit(0) return
def __init__(self): """ Setup the class with all the given arguments. :param self: A NetworkManager object :param jamming_argument: The jamming argument given by user :param ap_argument: The AP argument given by user :type self: NetworkManager :type jamming_argument: str :type ap_argument: str :return: None :rtype: None .. seealso:: NetworkAdapter """ # Setup the fields self._interfaces = {} self.ap_iface = "" self.jam_iface = "" # Create, add and check compatibility for each interface for interface in pyw.interfaces(): try: self._interfaces[interface] = NetworkAdapter(interface) except pyric.error as e: pass
def start(self, args): """ Start the network manager :param self: A NetworkManager object :type self: NetworkManager :param args: An argparse.Namespace object :type args: argparse.Namespace :return: None :rtype: None """ # populate our dictionary with all the available interfaces on the system for interface in pyw.interfaces(): try: card = pyw.getcard(interface) mac_address = pyw.macget(card) adapter = NetworkAdapter(interface, card, mac_address) self._name_to_object[interface] = adapter interface_property_detector(adapter) # ignore devices that are not supported(93) and no such device(19) except pyric.error as error: if error.args[0] in (93, 19): pass elif interface == args.internetinterface: return False else: raise error
def __init__(self, networkmanager_config_path='/etc/NetworkManager/NetworkManager.conf', unmanaged_interfaces = []): self.interfaces = pyw.interfaces() self.netcards = { interface: NetworkCard(interface) for interface in pyw.winterfaces() } self.nm_config_file = networkmanager_config_path self.file_handler = None self.unmanaged_interfaces_setup(unmanaged_interfaces)
def parse_name(self, name): if str(name) not in pyw.interfaces() or self.interface == name: self.name = name else: print(c.FAIL+" [-] "+c.WHITE+" Address already in use.") exit(0) return
def create_menu(self, master): interfaces = pyw.interfaces(); self.inter_options = []; self.freq_options = []; self.channel_options = []; for interface in interfaces: try: if pyw.modeget(interface) == "monitor": self.inter_options.append(interface); except: pass; self.INTERFACE = StringVar(); self.FREQUENCY = StringVar(); self.CHANNEL = StringVar(); try: self.INTERFACE.set(self.inter_options[0]); interface = pyw.getcard(self.inter_options[0]); pinfo = pyw.phyinfo(interface)['bands']; self.freq_options = pinfo.keys(); self.FREQUENCY.set(self.freq_options[0]); if self.FREQUENCY.get() == "2GHz": self.channel_options = ["all", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; else: self.channel_options = ["all", 36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112, 116, 132, 136, 140, 149, 153, 157, 161, 165]; self.CHANNEL.set(self.channel_options[0]); except: print("No Valid Monitor Interfaces.") sys.exit(0); self.header_frame = Frame(master, height=50, bg=Color.BACKGROUND); self.header_frame.pack(fill=X); self.interface_label = Label(self.header_frame, text="Face: ", bg=Color.BACKGROUND, fg="black", font="14"); self.interface_label.pack(padx=(15,0), pady=(10,0), anchor=NW, side=LEFT); self.interface_options = apply(OptionMenu, (self.header_frame, self.INTERFACE) + tuple(self.inter_options)); self.interface_options.pack(padx=(5, 0), pady=(7, 0), anchor=NW, side=LEFT); self.frequency_label = Label(self.header_frame, text="Freq: ", bg=Color.BACKGROUND, fg="black", font="14"); self.frequency_label.pack(padx=(5,0), pady=(10,0), anchor=NW, side=LEFT); self.frequency_options = apply(OptionMenu, (self.header_frame, self.FREQUENCY) + tuple(self.freq_options)); self.frequency_options.pack(padx=(5, 0), pady=(7, 0), anchor=NW, side=LEFT); self.channel_label = Label(self.header_frame, text="Ch: ", bg=Color.BACKGROUND, fg="black", font="14"); self.channel_label.pack(padx=(5,0), pady=(10,0), anchor=NW, side=LEFT); self.ch_options = apply(OptionMenu, (self.header_frame, self.CHANNEL) + tuple(self.channel_options)); self.ch_options.pack(padx=(5, 0), pady=(7, 0), anchor=NW); self.INTERFACE.trace('w', self.update_freq_options); self.FREQUENCY.trace('w', self.update_channel_options); return;
def CheckInterfaces(check=1): if check == 1: if len(pyw.winterfaces()) < 2: return False else: return True elif check == 0: return pyw.interfaces() else: print("Error accessing interfaces.")
def findap(): for interface in pyw.interfaces(): try: w0 = pyw.getcard(interface) except: pass else: pinfo = pyw.devinfo(w0) if pinfo["mode"] == "AP": return w0.dev
def parse_interface(self, interface): """ Parse Interface Argument *REQUIRED* """ if interface in pyw.interfaces() and pyw.modeget( interface) == "monitor": self.__FACE__ = interface else: sys.exit() return
def __init__( self, networkmanager_config_path='/etc/NetworkManager/NetworkManager.conf' ): self.interfaces = pyw.interfaces() self.netcards = { interface: NetworkCard(interface) for interface in pyw.winterfaces() } self.nm_config_file = networkmanager_config_path self.file_handler = None
def DebuggingInterface(iface): interfaces = pyw.interfaces() print(interfaces) print(("Is %s an interface? %s" % (iface, pyw.isinterface(iface)))) print(("Is %s a wireless device? %s" % (iface, pyw.iswireless(iface)))) w0 = pyw.getcard(iface) print(("Is %s active? %s" % (iface, pyw.isup(w0)))) print(("Is %s blocked? %s" % (iface, pyw.isblocked(w0)))) iinfo = pyw.ifinfo(w0) print(iinfo) pinfo = pyw.phyinfo(w0) print((pinfo['bands']))
def parse_interface(self, interface): if interface in pyw.interfaces(): print(c.OKGREEN + " [+] " + c.WHITE + "Valid Card Selected.") if pyw.modeget(pyw.getcard(interface)) == "monitor": self.monitor = True else: self.monitor = False self.interface = interface return print(c.FAIL + " [+] Invalid Card Selected.") exit(0) return
def monitor_interfaces(self): """Get a list of interfaces that support monitor mode""" # Get a list of all the interfaces. ret = [] for iface in pyw.interfaces(): # Check if this card support monitor mode try: card = pyw.getcard(iface) if 'monitor' in pyw.devmodes(card) and 'mon0' != card.dev: # Add the card to the list ret.append(iface) except pyric.error as e: pass # Return the collected list return ret
def __enter__(self): LOG.info("starting monitor mode on {}".format(self.adapter)) cmd = '{airmon} start {adapter}'.format(**self.args) exec_cmd(cmd) time.sleep(2) for iface in pyw.interfaces(): try: c = pyw.getcard(iface) except Exception: LOG.exception("error getting interface: {}".format(iface)) continue if c.phy == self.phy: LOG.info("Found monitor adapter: {}".format(c.dev)) self.mon_adapter = c.dev self.args['mon_adapter'] = self.mon_adapter break if not self.mon_adapter: raise Exception("Error, could not determin monitoring adapter") return self
def parse_interface(self, interface): if interface in pyw.interfaces(): print(c.OKGREEN+" [+] "+c.WHITE+"Valid Card Selected.") info = pyw.ifinfo(pyw.getcard(interface)) print(" '-> Driver: "+info["driver"]) print(" '-> Hardware Address: "+info["hwaddr"]) print(" '-> manufacturer: "+info["manufacturer"]) if pyw.modeget(pyw.getcard(interface)) == "monitor": self.monitor = True else: self.monitor = False self.interface = interface return print(c.FAIL+" [+] Invalid Card Selected.") exit(0) return
def get_interfaces(self): # request list of interfaces from pyric all_interfaces = pyw.interfaces() #walk all interfaces for interface in all_interfaces: # check if the interface is loopback or virtual if get_mac_address( interface) != "00:00:00:00:00" and interface != "lo": # check if it's wireless or not if pyw.iswireless(interface): self.wireless_interfaces.append(interface) else: self.wired_interfaces.append(interface) # append a placeholder interaface for the empty lists if len(self.wireless_interfaces) == 0: self.wireless_interfaces.append("None") if len(self.wired_interfaces) == 0: self.wired_interfaces.append("None")
def start(self): """ Start the network manager :param self: A NetworkManager object :type self: NetworkManager :return: None :rtype: None """ # populate our dictionary with all the available interfaces on the system for interface in pyw.interfaces(): try: card = pyw.getcard(interface) mac_address = pyw.macget(card) adapter = NetworkAdapter(interface, card, mac_address) self._name_to_object[interface] = adapter interface_property_detector(adapter) # ignore devices that are not supported(93) and no such device(19) except pyric.error as error: if error[0] == 93 or error[0] == 19: pass else: raise error
def is_add_vif_required(args): """ Return the card if only that card support both monitor and ap :param args: Arguemnt from pywifiphisher :type args: parse.args :return: tuple of card and is_frequency_hop_allowed :rtype: tuple """ def get_perfect_card(phy_map_vifs, vif_score_tups): """ Get the perfect card that both supports ap and monitor when we have only one phy interface can do that :param phy_map_vifs: phy number maps to the virtual interfaces :param vif_score_tups: list of tuple containing card and score :type phy_map_vifs: dict :type vif_score_tups: list :return tuple of card and single_perfect_phy_case :rtype: tuple """ # case 1 : one phy maps to one virtual interface if len(phy_map_vifs) == 1 and len(phy_map_vifs.values()[0]) == 1: # only take the first tuple vif_score_tuple = vif_score_tups[0] card = vif_score_tuple[0] score = vif_score_tuple[1] # if this card support both monitor and AP mode if score == 2: return card, True # case 2 : one phy maps to multiple virtual interfaces # we don't need to create one more virtual interface in this case elif len(phy_map_vifs) == 1 and len(phy_map_vifs.values()[0]) > 1: return None, True # case 3 : we have multiple phy interfaces but only # one card support both monitor and AP and the other # ones just support the managed mode only elif len(phy_map_vifs) > 1: if vif_score_tups[0][1] == 2 and vif_score_tups[1][1] == 0: return vif_score_tups[0][0], True return None, False # map the phy interface to virtual interfaces # i.e. phy0 to wlan0 phy_to_vifs = defaultdict(list) # store the phy number for the internet access invalid_phy_number = list() # record the invalid_phy_number when it is wireless card if args.internetinterface and pyw.iswireless(args.internetinterface): card = pyw.getcard(args.internetinterface) invalid_phy_number.append(card.phy) if args.wpspbc_assoc_interface: card = pyw.getcard(args.wpspbc_assoc_interface) invalid_phy_number.append(card.phy) # map the phy# to the virtual interface tuples for vif in [vif for vif in pyw.interfaces() if pyw.iswireless(vif)]: # excluding the card that used for internet accessing # setup basic card information score = 0 card = pyw.getcard(vif) phy_number = card.phy if phy_number in invalid_phy_number: continue supported_modes = pyw.devmodes(card) if "monitor" in supported_modes: score += 1 if "AP" in supported_modes: score += 1 phy_to_vifs[phy_number].append((card, score)) # each phy number map to a sublist containing (card, score) vif_score_tuples = [sublist[0] for sublist in phy_to_vifs.values()] # sort with score vif_score_tuples = sorted(vif_score_tuples, key=lambda tup: -tup[1]) use_one_phy = False if args.interface: card = pyw.getcard(args.interface) phy_number = card.phy if phy_to_vifs[card.phy][0][1] == 2: perfect_card = card use_one_phy = True else: perfect_card, use_one_phy = get_perfect_card( phy_to_vifs, vif_score_tuples) return perfect_card, use_one_phy
import os, re import pyric.pyw as pyw ROOT = os.geteuid() == 0 MWINTERFACES = [x for x in pyw.winterfaces() if pyw.modeget(x) == "monitor"] INTERFACES = [x for x in pyw.interfaces()] BAD_MAC = [ "ff:ff:ff:ff:ff:ff", "00:00:00:00:00:00", # Multicast "01:80:c2:00:00:00", # Multicast "01:00:5e", # Multicast "01:80:c2", # Multicast "33:33", # Multicast ] MACFILTER = "[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$" WPS_QUERY = { b"\x00\x10\x18": "Broadcom", # Broadcom */ b"\x00\x03\x7f": "AtherosC", # Atheros Communications */ b"\x00\x0c\x43": "RalinkTe", # Ralink Technology, Corp. */ b"\x00\x17\xa5": "RalinkTe", # Ralink Technology Corp */ b"\x00\xe0\x4c": "RealtekS", # Realtek Semiconductor Corp. */ b"\x00\x0a\x00": "Mediatek", # Mediatek Corp. */ b"\x00\x0c\xe7": "Mediatek", # Mediatek MediaTek Inc. */ b"\x00\x1c\x51": "CelenoCo", # Celeno Communications */ b"\x00\x50\x43": "MarvellS", # Marvell Semiconductor, Inc. */ b"\x00\x26\x86": "Quantenn", # Quantenna */
def execute(dev): print('Setting up...') # ensure dev is a wireless interfaces ifaces = pyw.interfaces() wifaces = pyw.winterfaces() if dev not in ifaces: print("Device {0} is not valid, use one of {1}".format(dev, ifaces)) return elif dev not in wifaces: print("Device {0} is not wireless, use one of {1}".format( dev, wifaces)) # get a Card & info for dev print("Regulatory Domain currently: ", pyw.regget()) dinfo = pyw.devinfo(dev) card = dinfo['card'] pinfo = pyw.phyinfo(card) driver = hw.ifdriver(card.dev) chipset = hw.ifchipset(driver) # bring the card down and change the mac pyw.down(card) pyw.macset(card, '00:03:93:57:54:46') # print details msg = "Using {0} currently in mode: {1}\n".format(card, dinfo['mode']) msg += "\tDriver: {0} Chipset: {1}\n".format(driver, chipset) if dinfo['mode'] == 'managed': msg += "\tcurrently on channel {0} width {1}\n".format( rf2ch(dinfo['RF']), dinfo['CHW']) msg += "\tSupports modes {0}\n".format(pinfo['modes']) msg += "\tSupports commands {0}".format(pinfo['commands']) msg += "\thw addr {0}".format(pyw.macget(card)) print(msg) # prepare a virtual interface named pent0 in monitor mode # delete all ifaces on the phy to avoid interference # bring the card up when down print('Preparing pent0 for monitor mode') pdev = 'pent0' pcard = pyw.devadd(card, pdev, 'monitor') for iface in pyw.ifaces(card): if iface[0].dev != pcard.dev: print("deleting {0} in mode {1}".format(iface[0], iface[1])) pyw.devdel(iface[0]) pyw.up(pcard) print("Using", pcard) print("Setting channel to 6 NOHT") pyw.chset(pcard, 6, None) msg = "Virtual interface {0} in monitor mode on ch 6".format(pcard) print(msg + ", using hwaddr: {0}".format(pyw.macget(pcard))) # DO stuff here try: print('Now ready to do stuff') print( 'For example, run wireshark to verify card is seeing all packets') print('Hit Ctrl-C to quit and restore') while True: time.sleep(1) except KeyboardInterrupt: pass # restore original print('Restoring', card, 'mode =', dinfo['mode'], 'mac =', dinfo['mac']) card = pyw.devadd(pcard, card.dev, dinfo['mode']) print('Deleting', pcard) pyw.devdel(pcard) pyw.macset(card, dinfo['mac']) pyw.up(card) print("card ", card, " restored")
def read_network_interfaces(self): import pyric.pyw as pyw network_info = '' try: network_info = pyw.interfaces() except: pass self.available_share = [_('none'),'auto'] unavailable_net = ['wlan9','lo'] if self.bridge.GetValue(): unavailable_net.append('eth0') for i in network_info: if not 'can' in i and not 'canable' in i and not i in unavailable_net: self.available_share.append(i) self.share.Clear() for i in self.available_share: self.share.Append(i) type='' phy='' AP=-1 GHz=-1 self.available_ap_device = [] self.available_ap_device.append([_('none'),'',-1,-1,'none']) for i in pyw.winterfaces(): if 'wlan' in i: try: wlan = 'wlan9' #AP allways on wlan9 w0 = pyw.getcard(i) mac = subprocess.check_output(('cat /sys/class/net/'+i+'/address').split()).decode()[:-1] AP = -1 if 'AP' in pyw.phyinfo(w0)['modes']:AP = 0 GHz = -1 if 'a' in pyw.devstds(w0): GHz = 1 if b'usb' in subprocess.check_output(('ls -l /sys/class/net/'+i).split()): type = 'usb' if AP > -1: self.available_ap_device.append([mac+' '+type, mac, type, GHz, wlan]) else: type = 'on board' do_exist = False for j in self.available_ap_device: if j[1] == mac: do_exist = True if not do_exist: self.available_ap_device.append([mac+' '+type, mac, type, GHz, wlan]) except: pass if not ('Raspberry Pi 2' in self.rpimodel) and len(self.available_ap_device) == 2: for i in self.available_ap_device: if 'on board' == i[2]: type = 'AP and Station' wlan = 'uap' self.available_ap_device.append([i[1]+' '+type, i[1], type, i[3], wlan]) self.available_ap_device2 = [] for i in self.available_ap_device: self.available_ap_device2.append(i[0]) self.ap_device.Clear() for i in self.available_ap_device2: self.ap_device.Append(i)
def test_ininterfaces(self): for nic in nics: self.assertIn(nic, pyw.interfaces())
def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--version', action='version', version="{0}{1}".format(c.G, "Version: 1.0.0")) parser.add_argument("-i", "--interface", action="store", dest="interface", help="select an interface", required=True) parser.add_argument("-f", "--frequency", action="store", default=2, dest="freq", type=int, help="select a frequency (2/5)", choices=[2, 5]) parser.add_argument("-c", "--channel", action="store", default=None, dest="channel", type=int, help="select a channel") parser.add_argument("-k", "--kill", action="store_true", dest="kill", help="sudo kill interfering processes.") parser.add_argument("-u", "--unassociated", action="store_true", dest="unassociated", help="Whether to show unassociated clients.") parser.add_argument("-a", "--accesspoint", action="store", default=None, dest="access_mac", help="Command for a specific mac addr.") results = parser.parse_args() interface = results.interface channel = results.channel frequency = results.freq kill = results.kill mfilter = results.access_mac unassociated = results.unassociated if interface not in pyw.interfaces( ) or pyw.modeget(interface) != "monitor": print(c.F + " [-] Non Monitor card selected.") exit(0) if channel == None: if frequency == 2: hop = True elif frequency == 5: hop = True else: print(c.F + " [-] Channel Setting incorrect.") exit(0) elif channel != None: if frequency == 2 and channel in xrange(1, 12): hop = False elif frequency == "5" and channel in [ 36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112, 116, 132, 136, 140, 149, 153, 157, 161, 165 ]: hop = False else: print(c.F + " [-] Channel Setting incorrect." + c.E) exit(0) if kill != False: commandlist = [ "service avahi-daemon stop", "service network-manager stop", "pkill wpa_supplicant", "pkill dhclient" ] for item in commandlist: try: system("sudo %s" % (item)) except: pass return [interface, channel, hop, frequency, kill, mfilter, unassociated]
def create_options(self): self.options_frame = Frame(self.master, bg=c.TITLE_BACKGROUND, width=900, height=50); self.options_frame.pack(fill=BOTH); self.flag_frame = Frame(self.master, bg=c.TITLE_BACKGROUND, width=900, height=50); self.flag_frame.pack(fill=BOTH); interfaces = pyw.interfaces(); self.inter_options = []; self.freq_options = []; self.channel_options = []; for interface in interfaces: try: if pyw.modeget(interface) == "monitor": self.inter_options.append(interface); except: pass self.INTERFACE = StringVar(); self.FREQUENCY = StringVar(); self.CHANNEL = StringVar(); try: self.INTERFACE.set(self.inter_options[0]); interface = pyw.getcard(self.inter_options[0]); pinfo = pyw.phyinfo(interface)['bands']; self.freq_options = pinfo.keys(); self.FREQUENCY.set(self.freq_options[0]); if self.FREQUENCY.get() == "2GHz": self.channel_options = ["all", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; else: self.channel_options = ["all", 36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112, 116, 132, 136, 140, 149, 153, 157, 161, 165]; self.CHANNEL.set(self.channel_options[0]); except: print("No Valid Monitor Interfaces."); sys.exit(0); self.interface_label = Label(self.options_frame, text="Face: ", bg=c.TITLE_BACKGROUND, fg="white", font="14"); self.interface_label.pack(padx=(25,0), pady=(15,0), anchor=NW, side=LEFT); self.interface_options = apply(OptionMenu, (self.options_frame, self.INTERFACE) + tuple(self.inter_options)); self.interface_options.pack(padx=(0, 5), pady=(11, 0), anchor=NW, side=LEFT); self.frequency_label = Label(self.options_frame, text="Freq: ", bg=c.TITLE_BACKGROUND, fg="white", font="14"); self.frequency_label.pack(padx=(7, 0), pady=(15,0), anchor=NW, side=LEFT); self.frequency_options = apply(OptionMenu, (self.options_frame, self.FREQUENCY) + tuple(self.freq_options)); self.frequency_options.pack(padx=(0, 5), pady=(11, 0), anchor=NW, side=LEFT); self.channel_label = Label(self.options_frame, text="Ch: ", bg=c.TITLE_BACKGROUND, fg="white", font="14"); self.channel_label.pack(padx=(7, 0), pady=(15,0), anchor=NW, side=LEFT); self.ch_options = apply(OptionMenu, (self.options_frame, self.CHANNEL) + tuple(self.channel_options)); self.ch_options.pack(padx=(0, 5), pady=(11, 0), anchor=NW); self.INTERFACE.trace('w', self.update_freq_options); self.FREQUENCY.trace('w', self.update_channel_options); ########## FLAGS ################ self.KILL = StringVar(); self.UNASSOCIATED = StringVar(); self.MACFILTER = StringVar(); self.kill = Checkbutton( self.flag_frame, text="Kill blocking tasks", fg="white", selectcolor=c.TITLE_BACKGROUND, activeforeground="white", activebackground=c.TITLE_BACKGROUND, variable=self.KILL, highlightthickness = 0, bd = 0, relief=FLAT, font="10", bg=c.TITLE_BACKGROUND ); self.kill.pack(padx=(25, 0), pady=(10, 0), anchor=W, side=LEFT); self.filter_label = Label(self.flag_frame, text="AP Filter: ", bg=c.TITLE_BACKGROUND, fg="white", font="14"); self.filter_label.pack(padx=(12, 0), pady=(10, 0), anchor=W, side=LEFT); self.filter_entry = Entry(self.flag_frame, exportselection=0, state=DISABLED, takefocus=True, textvariable=self.MACFILTER); self.filter_entry.pack(padx=(5, 0), pady=(11, 0), anchor=W); self.filter_entry.config(state=NORMAL); return;
def test_isinterface(self): for nic in pyw.interfaces(): self.assertTrue(pyw.isinterface(nic))
def test_ininterfaces(self): for nic in nics: self.assertIn(nic,pyw.interfaces())
def test_interfaces_two_interfaces(): """Test the interfaces function when two interfaces are available.""" assert interfaces() == ["enp12s0", "lo"]
def start_access_point(self, plugins = []): ''' This method is responsible for starting the access point with hostapd while also avoiding conflicts with NetworkManager. It replaces the original NetworkManager.conf file and adding some lines that tell it to ignore managing the interface that we are going to use as AP then it restarts the service ''' # Start by getting all the info from the configuration file try: ap_interface = self.configs["airhost"]["ap_interface"] internet_interface = self.configs["airhost"]["internet_interface"] gateway = self.configs["airhost"]["dnsmasqhandler"]["gateway"] dhcp_range = self.configs["airhost"]["dnsmasqhandler"]["dhcp_range"] ssid = self.configs["airhost"]["aplauncher"]["ssid"] bssid = self.configs["airhost"]["aplauncher"]["bssid"] channel = self.configs["airhost"]["aplauncher"]["channel"] hw_mode = self.configs["airhost"]["aplauncher"]["hw_mode"] dns_servers = self.configs["airhost"]["dnsmasqhandler"]["dns_server"] except KeyError as e: print "[-] Unable to start Access Point, too few configurations" return False if ap_interface not in winterfaces(): print "[-] ap_interface '{}' does not exist".format(ap_interface) return False if internet_interface not in interfaces(): print "[-] internet_interface '{}' does not exist".format(internet_interface) return False # Add plugins self.add_plugins(plugins, self.air_host, AirHostPlugin) # NetworkManager setup is_catch_all_honeypot = self.configs["airhost"]["aplauncher"]["catch_all_honeypot"].lower() == "true" is_multiple_ssid = type(ssid) is list nVirtInterfaces = 3 if is_catch_all_honeypot else \ len(ssid) if is_multiple_ssid else \ 0 if self.network_manager.set_mac_and_unmanage( ap_interface, bssid, retry = True, virtInterfaces = nVirtInterfaces): # Initial configuration self.network_manager.configure_interface(ap_interface, gateway) self.network_manager.iptables_redirect(ap_interface, internet_interface) # dnsmasq and hostapd setup try: captive_portal_mode = self.configs["airhost"]["dnsmasqhandler"]["captive_portal_mode"].lower() == "true" except KeyError: captive_portal_mode = False self.air_host.dnsmasqhandler.set_captive_portal_mode(captive_portal_mode) self.air_host.dnsmasqhandler.write_dnsmasq_configurations( ap_interface, gateway, dhcp_range, dns_servers, nVirtInterfaces) try: self.air_host.aplauncher.write_hostapd_configurations( interface=ap_interface, ssid=ssid, bssid=bssid, channel=channel, hw_mode=hw_mode, encryption=self.configs["airhost"]["aplauncher"]["encryption"], auth=self.configs["airhost"]["aplauncher"]["auth"], cipher=self.configs["airhost"]["aplauncher"]["cipher"], password=self.configs["airhost"]["aplauncher"]["password"], catch_all_honeypot=is_catch_all_honeypot) except KeyError: self.air_host.aplauncher.write_hostapd_configurations( interface=ap_interface, ssid=ssid, bssid=bssid, channel=channel, hw_mode=hw_mode) except Exception as e: print e return # Start services print_creds = self.configs["airhost"]["aplauncher"]["print_creds"].lower() == "true" self.air_host.start_access_point( ap_interface, print_creds) # Configure Virtual Interfaces once hostapd has set them up sleep(.5) # Wait for for hostapd to setup interfaces extra_interfaces = False for i in range(nVirtInterfaces-1): interface_name = "{}_{}".format(ap_interface, i) if interface_name in winterfaces(): gateway = ".".join(gateway.split(".")[0:2] + [str(int(gateway.split(".")[2]) + 1)] + [gateway.split(".")[3]]) self.network_manager.configure_interface(interface_name, gateway) self.network_manager.iptables_redirect(interface_name, internet_interface) extra_interfaces = True # Needed for dnsmasq to work correctly with virtual interfaces once they are configured if extra_interfaces: self.air_host.dnsmasqhandler.start_dnsmasq() return True print dedent(""" [-] Errors occurred while trying to start access point, try restarting network services and unplug your network adapter""") return False
def main(): # list of all channels in 5ghz spectrum fspectrum = [ 36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112, 116, 132, 136, 140, 149, 153, 157, 161, 165 ] # Get all arguments from terminal results = parseArgs() # Check if interface exists. if results['interface'] not in pyw.interfaces(): printf("Interface is not valid.") exit(1) # Check if interface in monitor mode. if pyw.modeget(results['interface']) != "monitor": printf("Non monitor interface selected.") exit(1) # Check if channel specified if results['channel']: # Check if channel is valid. if results['freq'] == 2 and results['channel'] not in range(1, 12): printf("Channel selected is invalid") exit(1) # Check if channel is valid. elif results['freq'] == 5 and results['channel'] not in fspectrum: printf("Channel selected is invalid") exit(1) # Check if mac is of valid length. if results['mac'] and len(results['mac']) != 17: printf("Invalid mac option selected.") exit(1) # Check if task kill flag is set. if results['kill']: killBlockingTasks() # Check if target mac is of valid length. if results['target'] and len(results['target']) != 17: printf("Invalid Target Selected.") exit(1) # Set ctrl+c interceptor. signal.signal(signal.SIGINT, signal_handler) # Check values at start up: OS and UID. startupChecks() # Create directory for captured handshakes. createPcapDirectory() # Create Sniffer object sniffer = Sniffer(results) # If channel isnt set then create channel hopping thread. if not results['channel']: # Create hopper thread. hop_thread = Thread(target=sniffer.hopper) # Set thread object as a daemon. hop_thread.daemon = True # Start thread. hop_thread.start() # If channel is set. else: # set channel and continue. pyw.chset(pyw.getcard(results['interface']), results['channel'], None) printer_thread = Thread(target=sniffer.printer) printer_thread.daemon = True printer_thread.start() try: sniffer.run() except AttributeError: printf("AttributeError: Disregard This Error.")
def test_interfaces_no_interface(): """Test interfaces function when no interfaces are available.""" assert interfaces() == []
def test_enuminterfaces(self): for nic in nics: self.assertTrue(nic in pyw.interfaces())
self.data['wtx'] = _linkinfo['tx'] except: self.data['wtx'] = None try: self.data['wrx'] = _linkinfo['rx'] except: self.data['wrx'] = None def runall(self): pass #If we're being called as a command, instantiate and report if __name__ == '__main__': try: ifs = pyw.interfaces() except pyric.error as e: print "Error running netinfo, pyric not available" sys.exit(1) print "netinfo_present=yes" with open("/etc/hostname", "r") as etc_hostname: data = etc_hostname.readlines() if data: print "netinfo_etchostname=" + str(data[0].rstrip()) print "netinfo_interfaces=" + ",".join(ifs) for _if in ifs: _netinfo = Netinfo(_if) _netinfo.getinfo() for key, val in sorted(_netinfo.data.items()):
def is_add_vif_required(args): """ Return the card if only that card support both monitor and ap :param args: Arguemnt from pywifiphisher :type args: parse.args :return: tuple of card and is_frequency_hop_allowed :rtype: tuple """ def get_perfect_card(phy_map_vifs, vif_score_tups): """ Get the perfect card that both supports ap and monitor when we have only one phy interface can do that :param phy_map_vifs: phy number maps to the virtual interfaces :param vif_score_tups: list of tuple containing card and score :type phy_map_vifs: dict :type vif_score_tups: list :return tuple of card and single_perfect_phy_case :rtype: tuple """ # case 1 : one phy maps to one virtual interface if len(phy_map_vifs) == 1 and len(phy_map_vifs.values()[0]) == 1: # only take the first tuple vif_score_tuple = vif_score_tups[0] card = vif_score_tuple[0] score = vif_score_tuple[1] # if this card support both monitor and AP mode if score == 2: return card, True # case 2 : one phy maps to multiple virtual interfaces # we don't need to create one more virtual interface in this case elif len(phy_map_vifs) == 1 and len(phy_map_vifs.values()[0]) > 1: return None, True # case 3 : we have multiple phy interfaces but only # one card support both monitor and AP and the other # ones just support the managed mode only elif len(phy_map_vifs) > 1: if vif_score_tups[0][1] == 2 and vif_score_tups[1][1] == 0: return vif_score_tups[0][0], True return None, False # map the phy interface to virtual interfaces # i.e. phy0 to wlan0 phy_to_vifs = defaultdict(list) # store the phy number for the internet access invalid_phy_number = None # record the invalid_phy_number when it is wireless card if args.internetinterface and pyw.iswireless(args.internetinterface): card = pyw.getcard(args.internetinterface) invalid_phy_number = card.phy # map the phy# to the virtual interface tuples for vif in [vif for vif in pyw.interfaces() if pyw.iswireless(vif)]: # excluding the card that used for internet accessing # setup basic card information score = 0 card = pyw.getcard(vif) phy_number = card.phy if phy_number == invalid_phy_number: continue supported_modes = pyw.devmodes(card) if "monitor" in supported_modes: score += 1 if "AP" in supported_modes: score += 1 phy_to_vifs[phy_number].append((card, score)) # each phy number map to a sublist containing (card, score) vif_score_tuples = [sublist[0] for sublist in phy_to_vifs.values()] # sort with score vif_score_tuples = sorted(vif_score_tuples, key=lambda tup: -tup[1]) perfect_card, is_single_perfect_phy = get_perfect_card(phy_to_vifs, vif_score_tuples) return perfect_card, is_single_perfect_phy
def execute(dev): print('Setting up...') # ensure dev is a wireless interfaces ifaces = pyw.interfaces() wifaces = pyw.winterfaces() if dev not in ifaces: print("Device {0} is not valid, use one of {1}".format(dev,ifaces)) return elif dev not in wifaces: print("Device {0} is not wireless, use one of {1}".format(dev,wifaces)) # get a Card & info for dev print("Regulatory Domain currently: ", pyw.regget()) dinfo = pyw.devinfo(dev) card = dinfo['card'] pinfo = pyw.phyinfo(card) driver = hw.ifdriver(card.dev) chipset = hw.ifchipset(driver) # bring the card down and change the mac pyw.down(card) pyw.macset(card,'00:03:93:57:54:46') # print details msg = "Using {0} currently in mode: {1}\n".format(card,dinfo['mode']) msg += "\tDriver: {0} Chipset: {1}\n".format(driver,chipset) if dinfo['mode'] == 'managed': msg += "\tcurrently on channel {0} width {1}\n".format(rf2ch(dinfo['RF']), dinfo['CHW']) msg += "\tSupports modes {0}\n".format(pinfo['modes']) msg += "\tSupports commands {0}".format(pinfo['commands']) msg += "\thw addr {0}".format(pyw.macget(card)) print(msg) # prepare a virtual interface named pent0 in monitor mode # delete all ifaces on the phy to avoid interference # bring the card up when down print('Preparing pent0 for monitor mode') pdev = 'pent0' pcard = pyw.devadd(card, pdev, 'monitor') for iface in pyw.ifaces(card): if iface[0].dev != pcard.dev: print("deleting {0} in mode {1}".format(iface[0],iface[1])) pyw.devdel(iface[0]) pyw.up(pcard) print("Using", pcard) print("Setting channel to 6 NOHT") pyw.chset(pcard,6,None) msg = "Virtual interface {0} in monitor mode on ch 6".format(pcard) print(msg + ", using hwaddr: {0}".format(pyw.macget(pcard))) # DO stuff here try: print('Now ready to do stuff') print('For example, run wireshark to verify card is seeing all packets') print('Hit Ctrl-C to quit and restore') while True: time.sleep(1) except KeyboardInterrupt: pass # restore original print('Restoring', card, 'mode =', dinfo['mode'], 'mac =', dinfo['mac']) card = pyw.devadd(pcard,card.dev,dinfo['mode']) print('Deleting', pcard) pyw.devdel(pcard) pyw.macset(card,dinfo['mac']) pyw.up(card) print("card ", card, " restored")
def start_access_point(self, plugins = []): """This method starts the access point with hostapd while also avoiding conflicts with NetworkManager.""" # Start by getting all the info from the configuration file try: ap_interface = self.configs["airhost"]["ap_interface"] internet_interface = self.configs["airhost"]["internet_interface"] gateway = self.configs["airhost"]["dnsmasqhandler"]["gateway"] dhcp_range = self.configs["airhost"]["dnsmasqhandler"]["dhcp_range"] ssid = self.configs["airhost"]["aplauncher"]["ssid"] bssid = self.configs["airhost"]["aplauncher"]["bssid"] channel = self.configs["airhost"]["aplauncher"]["channel"] hw_mode = self.configs["airhost"]["aplauncher"]["hw_mode"] dns_servers = self.configs["airhost"]["dnsmasqhandler"]["dns_server"] except KeyError as e: print "[-] Unable to start Access Point, too few configurations" return False if ap_interface not in winterfaces(): print "[-] ap_interface '{}' does not exist".format(ap_interface) return False if internet_interface not in interfaces(): print "[-] internet_interface '{}' does not exist".format(internet_interface) return False necessary_interfaces = [internet_interface, ap_interface] # Check if another service is using our interfaces. if self.air_injector.is_running() and \ self.air_injector.injection_interface in necessary_interfaces: print "[-] AirInjector is using a needed interface." return False if self.air_scanner.is_running() and \ self.air_scanner.running_interface in necessary_interfaces: print "[-] AirScanner using a needed interface." return False # Add plugins self.add_plugins(plugins, self.air_host, AirHostPlugin) # NetworkManager setup is_catch_all_honeypot = self.configs["airhost"]["aplauncher"]["catch_all_honeypot"].lower() == "true" is_multiple_ssid = type(ssid) is list nVirtInterfaces = 3 if is_catch_all_honeypot else \ len(ssid) - 1 if is_multiple_ssid else \ 0 if self.network_manager.set_mac_and_unmanage( ap_interface, bssid, retry = True, virtInterfaces = nVirtInterfaces): # Initial configuration self.network_manager.configure_interface(ap_interface, gateway) self.network_manager.iptables_redirect(ap_interface, internet_interface) # dnsmasq and hostapd setup try: captive_portal_mode = self.configs["airhost"]["dnsmasqhandler"]["captive_portal_mode"].lower() == "true" except KeyError: captive_portal_mode = False self.air_host.dnsmasqhandler.set_captive_portal_mode(captive_portal_mode) self.air_host.dnsmasqhandler.write_dnsmasq_configurations( ap_interface, gateway, dhcp_range, dns_servers, nVirtInterfaces) try: self.air_host.aplauncher.write_hostapd_configurations( interface=ap_interface, ssid=ssid, bssid=bssid, channel=channel, hw_mode=hw_mode, encryption=self.configs["airhost"]["aplauncher"]["encryption"], auth=self.configs["airhost"]["aplauncher"]["auth"], cipher=self.configs["airhost"]["aplauncher"]["cipher"], password=self.configs["airhost"]["aplauncher"]["password"], catch_all_honeypot=is_catch_all_honeypot) except KeyError: self.air_host.aplauncher.write_hostapd_configurations( interface=ap_interface, ssid=ssid, bssid=bssid, channel=channel, hw_mode=hw_mode) except Exception as e: print e return # Start services print_creds = self.configs["airhost"]["aplauncher"]["print_creds"].lower() == "true" success = self.air_host.start_access_point( ap_interface, print_creds) if success: # Configure Virtual Interfaces once hostapd has set them up sleep(.5) # Wait for for hostapd to setup interfaces extra_interfaces = False for i in range(nVirtInterfaces): interface_name = "{}_{}".format(ap_interface, i) if interface_name in winterfaces(): gateway = ".".join(gateway.split(".")[0:2] + [str(int(gateway.split(".")[2]) + 1)] + [gateway.split(".")[3]]) self.network_manager.configure_interface(interface_name, gateway) self.network_manager.iptables_redirect(interface_name, internet_interface) extra_interfaces = True # Needed for dnsmasq to work correctly with virtual interfaces once they are configured if extra_interfaces: self.air_host.dnsmasqhandler.start_dnsmasq() return True print dedent(""" [-] Errors occurred while trying to start access point, try restarting network services and unplug your network adapter""") return False
try: self.data['wtx'] = _linkinfo['tx'] except: self.data['wtx'] = None try: self.data['wrx'] = _linkinfo['rx'] except: self.data['wrx'] = None def runall(self): pass #If we're being called as a command, instantiate and report if __name__ == '__main__': try: ifs = pyw.interfaces() except pyric.error as e: print("Error running netinfo, pyric not available") sys.exit(1) print("netinfo_present=yes") with open ("/etc/hostname", "r") as etc_hostname: data=etc_hostname.readlines() if data: print("netinfo_etchostname="+str(data[0].rstrip())) print("netinfo_interfaces="+",".join(ifs)) for _if in ifs: _netinfo = Netinfo(_if) _netinfo.getinfo() for key,val in sorted(_netinfo.data.items()):
def is_internet_there(): internet = pyw.interfaces() internet = internet[0] return pyw.isinterface(internet)