def up(self): try: card = pyw.getcard(self.iface) except: wpa(self.wiface, 'p2p_group_add', 'persistent=0') self.iface = self.get_iface() self.password = wpa(self.iface, 'p2p_get_passphrase') card = pyw.getcard(self.iface) pyw.inetset(card, self.ip) copyfile('/etc/dnsmasq.conf', '/tmp/dnsmasq-bk.conf') self.save() sysctrl('restart', 'dnsmasq.service')
def parse_channel(self, channel): five_ghz = [ 36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112, 116, 132, 136, 140, 149, 153, 157, 161, 165 ] if channel == None: self.channel = None return elif 0 < int(channel) < 12: print(c.OKGREEN + " [+] " + c.WHITE + "Channel in range: 2GHz") self.frequency = "2GHz" if self.frequency in pyw.phyinfo(pyw.getcard( self.interface))['bands'].keys(): print(c.OKGREEN + " [+] " + c.WHITE + "Valid Channel selected.") self.channel = channel return else: print(c.FAIL + " [-] " + c.WHITE + " Invalid Channel selected.") exit(0) elif int(channel) in five_ghz: print(" [+] Channel in range: 5GHz") self.frequency = "5GHz" if self.frequency in pyw.phyinfo(pyw.getcard( self.interface))['bands'].keys(): print(c.OKGREEN + " [+] " + c.WHITE + "Valid Channel selected.") self.channel = channel return else: print(c.FAIL + " [-] " + c.WHITE + " Invalid Channel selected.") exit(0) else: print(c.FAIL + " [-] " + c.WHITE + " Channel is invalid in either frequency") exit(0) return
def _wifi_scanner(self): # reset the known access points self.access_points = [] # walk through all known wireless interfaces to get complete coverage for interface in self.wireless_interfaces: # create a card instance to work with card = pyw.getcard(interface) # check if the card is still valid if pyw.validcard(card): # skip the card if it is hard blocked if pyw.isblocked(card)[1]: continue else: # try to unblock a softblock, put the card up and disable the powersave mode try: pyw.unblock(card) pyw.up(card) pyw.pwrsaveset(card, False) except: # ignore failures pass # start scanning wifi_scanner = get_scanner(interface) # extend the access point list self.access_points.extend(wifi_scanner.get_access_points()) # the first scan has been completed self.first_scan_complete = True
def _get_my_ifaces(self): myWInterfaces = [] for ifName in pyw.winterfaces(): card = pyw.getcard(ifName) if card.phy == self.phyIndex: myWInterfaces.append(ifName) return myWInterfaces
def deauth(packets, channel, ap_bssid, client_bssid, iface): """ Sends deauth packets to the AP Arguments: packets -- no of deauth packets to send. channel -- channel on which to send the packets. ap_bssid -- bssid of the AP . client_bssid -- bssid of the client. iface -- interface to be used. """ # change channel. mon = pyw.getcard(str(iface)) pyw.chset(mon, channel, None) # disconnect client from the ap. if client_bssid: # disconnects the given client from the ap. aireplay_deauth = sb.call([ "aireplay-ng", "--deauth", str(packets), "-a", ap_bssid, "-c", client_bssid, iface ], stdout=DN, stderr=DN) else: # disconnects all clients from the ap. aireplay_deauth = sb.call([ "aireplay-ng", "--deauth", str(packets), "-a", ap_bssid, iface ], stdout=DN, stderr=DN)
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 rename_interface(orig_interface_name): """ Changes the name of the interface to its mac address :param orig_interface_name: The interface that you want to rename """ if pyw.isinterface(orig_interface_name): wifi_card = pyw.getcard(orig_interface_name) pyw.down(wifi_card) new_name = pyw.macget(wifi_card).replace(':', '') print(f"\trenaming {orig_interface_name} to {new_name}") subprocess.run(['ip link set ' + orig_interface_name + ' name ' + new_name], shell=True) wifi_card = pyw.getcard(new_name) pyw.up(wifi_card) else: print("Error: Interface " + str(orig_interface_name) + " does not exist. Cannot rename")
def _parse_connected_clients(self, interface): try: if not pyw.modeget(pyw.getcard(interface)) == 'AP': print "[-] '{}' is not on AP mode".format(interface) return False except Exception: return False client_dump = check_output("iw dev {} station dump".format(interface).split()).split('Station') client_dump = [ map(str.strip, client.split("\n")) for client in client_dump if interface in client ] temp_clients = [] # At this point a client is a list of arguments to be parsed for client in client_dump: client_mac = client[0].split()[0].strip() client_name, client_ip = self._get_ip_from_mac(interface, client_mac) inactivity_time = client[1].split(":")[1].strip() rx_packets = client[3].split(":")[1].strip() tx_packets = client[5].split(":")[1].strip() signal = client[8].split(":")[1].strip() tx_bitrate = client[10].split(":")[1].strip() rx_bitrate = client[11].split(":")[1].strip() id = len(temp_clients) client = Client(id, client_name, client_mac, client_ip, inactivity_time, rx_packets, tx_packets, rx_bitrate, tx_bitrate, signal) if client not in self.connected_clients: print "[+] New connected client with -> ip: {ip}, mac: {mac} ({vendor})".format(ip=client_ip, mac=client_mac, vendor=client.vendor) temp_clients.append(client) self.connected_clients = temp_clients return True
def hopper(self): interface = pyw.getcard(self.mface) timeout = 1.0 if self.mfreq == 2: __FREQS__ = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] elif self.mfreq == 5: __FREQS__ = [ 36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112, 116, 132, 136, 140, 149, 153, 157, 161, 165 ] while True: if not self.mfilter_channel: channel = choice(__FREQS__) pyw.chset(interface, channel, None) self.mchannel = channel else: channel = self.mfilter_channel pyw.chset(interface, channel, None) self.mchannel = self.mfilter_channel break while timeout < 3: timeout += .05 sleep(timeout) return
def getInfo(card_name): """ Returns the dict containing info regarding the wireless card. Dict : {name, channel, ipv4, mac, status} Arguments : card_name -- name of the wireless card """ c = pyw.getcard(card_name) channel = Wireless.getChannel(card_name) status = "" if pyw.isup(c): status = "up" else: status = "down" # one of this function disables during root so autload whichever available. ipv4 = None if "inetget" in dir(pyw): ipv4 = pyw.inetget(c)[0] elif "ifaddrget" in dir(pyw): ipv4 = pyw.ifaddrget(c)[0] mac = pyw.macget(c) return { "name": str(card_name), "channel": str(channel), "ipv4": str(ipv4), "mac": str(mac), "status": str(status) }
def mode_command(interface, mode): card = pyw.getcard(interface) newcard = None if mode == "monitor": if pyw.modeget(card) == "monitor": sys.exit( f"{Fore.YELLOW}Card is already in monitor mode{Style.RESET_ALL}" ) newcard = pyw.devset(card, get_next_name() + "mon") pyw.modeset(newcard, "monitor") pyw.up(newcard) else: if pyw.modeget(card) == "managed": sys.exit( f"{Fore.YELLOW}Card is already in managed mode{Style.RESET_ALL}" ) newcard = pyw.devset(card, card.dev[:-3]) pyw.modeset(newcard, "managed") pyw.up(newcard) print( f"{Fore.GREEN}New interface created: {Style.RESET_ALL}{newcard.dev} - {pyw.modeget(newcard)}" ) return newcard
def listInterfaces(mode="managed", prefix_str="", postfix_str=""): """ Returns the list of wireless interface. Arguments : mode -- list only those interfaces which have the given mode(default:manage) prefix_str -- list only those interfaces which starts with the following prefix. postfix_str -- list only those interfaces which ends with the following prefix. """ # check if its a wireless interface wifaces = pyw.winterfaces() # list to store the result result = [] # iterate through all interfaces for wi in wifaces: # create there card object w_card = pyw.getcard(wi) # check modes and prefix if specifed if (mode in pyw.devmodes(w_card)) and (w_card.dev.startswith( prefix_str)) and w_card.dev.endswith(postfix_str): result.append(wi) # return a list of strings containing the names of the interfaces. return result
def updatesourceinfo(win,iws,c): """ writes current state to info window :param win: the info window :param iws: the info window output dict should at minimum the keys 'dev','Driver','Mode','MAC','Manuf','Connected', :param c: the current config should be in the form config = {'SSID':None, 'dev':None, 'connect':None} """ # set defaults then check the conf dict for a device dev = c['dev'] if c['dev'] else '-'*_DEVLEN_ driver = mode = manuf = '-'*_FIXLEN_ hwaddr = '-'*_MACLEN_ conn = '-' color = CPS[WHITE] if c['dev']: try: card = pyw.getcard(dev) ifinfo = pyw.ifinfo(card) driver = ifinfo['driver'][:_FIXLEN_] # trim excess hwaddr = ifinfo['hwaddr'].upper() manuf = ifinfo['manufacturer'][:_FIXLEN_] # trim excess mode = pyw.modeget(card) conn = 'Y' if pyw.isconnected(card) else 'N' color = CPS[GREEN] except pyric.error as _e: raise error("ERRNO {0}. {1}".format(_e.errno,_e.strerror)) win.addstr(iws['dev'][0],iws['dev'][1],dev,color) win.addstr(iws['Driver'][0],iws['Driver'][1],driver,color) win.addstr(iws['Mode'][0],iws['Mode'][1],mode,color) win.addstr(iws['MAC'][0],iws['MAC'][1],hwaddr,color) win.addstr(iws['Manuf'][0],iws['Manuf'][1],manuf,color) win.addstr(iws['Connected'][0],iws['Connected'][1],conn,color)
def __init__( self, interface : str, frequencies : list = [2], channels : list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] + FIVEHERTZ ): if not root(): raise OSError(f"User must be root to use this functionality") if interface not in [x for x in pyw.winterfaces() if pyw.modeget(x) == "monitor"]: raise ValueError(f"Invalid interface: {interface}") self.logger = logging.getLogger(__name__) logging.basicConfig(level=logging.ERROR, format='%(name)-12s:%(levelname)-8s | %(funcName)-12s:%(lineno)-4d | %(message)s') self.interface = pyw.getcard(interface) self.channels = [] if 2 in frequencies: [self.channels.append(x) for x in channels if x in range(12)] if 5 in frequencies: [self.channels.append(x) for x in channels if x in FIVEHERTZ]
def setup_card(interface_name, frequency, data_rate=2): print("Settings up " + interface_name) wifi_card = pyw.getcard(interface_name) driver_name = iwhw.ifdriver(interface_name) if driver_name in EXPERIMENTAL_DRIVERS: print("Warning: Using WiFi adapter with experimental support!") print("Setting " + wifi_card.dev + " " + driver_name + " " + str(frequency) + " MHz" + " bitrate: " + get_bit_rate(data_rate) + " Mbps") if not pyw.isup(wifi_card): print("\tup...") pyw.up(wifi_card) if is_atheros_card(driver_name): # for all other cards the transmission rate is set via the radiotap header set_bitrate(interface_name, data_rate) if pyw.isup(wifi_card): print("\tdown...") pyw.down(wifi_card) print("\tmonitor...") pyw.modeset(wifi_card, 'monitor') if is_realtek_card(driver_name): # Other cards power settings are set via e.g. 'txpower_atheros 58' or 'txpower_ralink 0' (defaults) pyw.txset(wifi_card, 'fixed', 3000) if not pyw.isup(wifi_card): print("\tup...") pyw.up(wifi_card) print("\tfrequency...") pyw.freqset(wifi_card, frequency) print("\tMTU...") if is_realtek_card(driver_name): subprocess.run(['ip link set dev ' + interface_name + ' mtu 1500'], shell=True) else: subprocess.run(['ip link set dev ' + interface_name + ' mtu 2304'], shell=True) pyw.regset('DE') # to allow channel 12 and 13 for hotspot rename_interface(interface_name)
def __init__(self, name): """ Setup the class with all the given arguments. :param self: A NetworkAdapter object :param name: Name of the interface :type self: NetworkAdapter :type name: str :return: None :rtype: None .. note: the availability of monitor mode and AP mode is set to False by default """ # Setup the fields self._name = name self._support_ap_mode = False self._support_monitor_mode = False self.being_used = False # Set monitor and AP mode if card supports it card = pyw.getcard(name) modes = pyw.devmodes(card) if "monitor" in modes: self._support_monitor_mode = True if "AP" in modes: self._support_ap_mode = True
def __init__(self, file_prefix='capture'): self.orig_dir = os.getcwd() self.dest_dir = state.PCAP_DIR self.cracked = state.CRACKED_FILE self.hs_dir = os.path.join(*[self.dest_dir, 'hs']) if not os.path.isdir(self.dest_dir): LOG.warn("path {} not detected, creating!".format(self.dest_dir)) os.mkdir(self.dest_dir) self.file_prefix = os.path.join(*[self.dest_dir, file_prefix]) self.state = STATE self.adapter = self.state.scan_adapter.encode('ascii') self.mon_adapter = None self.card = pyw.getcard(self.adapter) self.phy = self.card.phy self.bssid = self.state.bssid wordlist = self.state.wordlist if not os.path.exists(wordlist): raise IOError("Could not find file: {}".format(wordlist)) self.wordlist = os.path.abspath(wordlist) self.channel = STATE.channel self.args = { 'bssid': self.bssid, 'adapter': self.adapter, 'channel': self.channel if self.channel else '', 'airdump': binaries.airodump_ng, 'airmon': binaries.airmon_ng, 'aircrack': binaries.aircrack_ng, 'wifite': binaries.wifite, 'wordlist': self.wordlist, }
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 set_interface_mode(self, interface, mode): """ Set the desired mode to the network interface. :param self: A NetworkManager object :param interface: A NetworkAdapter object :param mode: The mode the interface should be set to :type self: NetworkManager :type interface: NetworkAdapter :type mode: str :return: None :rtype: None :raises IfconfigCmdError: if an error is produced after executing ifconfig command .. note:: available modes are ad-hoc, managed, master, monitor, repeater, secondary .. seealso:: _ifconfig_cmd """ # Get the card card = pyw.getcard(interface.get_name()) # Turn off, set the mode and turn on the interface pyw.down(card) pyw.modeset(card, mode) pyw.up(card)
def is_wifi_present(): wlan = pyw.winterfaces() if len(wlan) >= 1: interface = wlan[0] if pyw.isinterface(interface): card = pyw.getcard(interface) info = pyw.ifinfo(card) if pyw.isup(card) is not True: print("Turn On wifi Actual estate:", pyw.isup(card)) wifi_info = {'wifi': interface, 'card': pyw.isup(card), 'mac': pyw.macget(card), 'driver': info.get('driver'), 'chip': info.get('chipset'), 'man': info.get('manufacturer'), 'con': to_json(get_all_info())} print(texto.safe_substitute(wifi_info)) else: wifi_info = {'wifi': interface, 'card': pyw.isup(card), 'mac': pyw.macget(card), 'driver': info.get('driver'), 'chip': info.get('chipset'), 'man': info.get('manufacturer'), 'con': to_json(get_all_info())} print(texto.safe_substitute(wifi_info)) else: print('wifi no encobtrado')
def setup_ap(self): if 'mon0' in pyw.winterfaces(): mon0 = pyw.getcard('mon0') if pyw.modeget(mon0) == 'monitor': try: pyw.up(mon0) pyw.chset(mon0, 1, None) success = True except Exception as e: success = False else: try: pyw.down(mon0) pyw.modeset(mon0, 'monitor') pyw.up(mon0) pyw.chset(mon0, 1, None) success = True except Exception as e: success = False else: card_name = '' for interface in pyw.winterfaces(): if interface.startswith('wlx7'): card_name = interface break c0 = pyw.getcard(card_name) if 'monitor' in pyw.devmodes(c0): try: pyw.down(c0) pyw.modeset(c0, 'monitor') pyw.up(c0) mon0 = pyw.devset(c0, 'mon0') pyw.up(mon0) pyw.chset(mon0, 1, None) success = True except Exception as e: success = False else: success = False if success: print('Successfully Setup Monitoring Device') self.request.sendall('0'.encode()) else: print('Error Setting up Monitoring Device') self.request.sendall('1'.encode())
def hopper(self): interface = pyw.getcard(self.interface) while True: channel = random.choice(TWOHERTZ) # print("channel", channel) set_channel(interface, channel) self.channel = channel time.sleep(4.5)
def __init__(self, iface_name): super().__init__() self._HANDLER = self._make_handler() self._abort = False self._observers = [] self._monitor = None self._iface_name = iface_name self._iface = pyw.getcard(iface_name) self._timeout = 0
def packetHandler(pkt) : try: global cfg #Collect data if pkt.haslayer(Dot11) and ( pkt.type == 0 and pkt.subtype == 8) : #Check if beacon & get data channel = hex2int(dot11EltInfoFromId(pkt, 3)) ssid = pkt.info if not channel in cfg.chan_ap: cfg.chan_ap[channel] = [ssid] else: if ssid not in cfg.chan_ap[channel]: cfg.chan_ap[channel].append(ssid) if ssid == cfg.ssid: cfg.track_channel = channel #Time to switch channel ? if (time_ms() - cfg.elapsed_time_channel) > cfg.channel_timer: if cfg.if_channel == 13: cfg.if_channel = 1 else: cfg.if_channel += 1 try: if cfg.verbose: sys.stderr.write("Change to channel " + str(cfg.if_channel) + " for " + cfg.card.dev) pyw.chset(pyw.getcard(cfg.card.dev), cfg.if_channel, None) except: if cfg.verbose: sys.stderr.write("Change to channel "+str(cfg.if_channel)+" failed for " + cfg.card.dev) cfg.elapsed_time_channel = time_ms() #Time to consumme data ? Aggregate data every cfg.ouput_timer ms if (time_ms() - cfg.elapsed_time_ouput) > cfg.output_timer: if cfg.ssid: output = [time.strftime("%H:%M:%S"), cfg.track_channel] else: output = [time.strftime("%H:%M:%S")] for i in range(1,14): if cfg.chan_ap.has_key(i): output.append(str(len(cfg.chan_ap[i]))) else: output.append(0) print ",".join(str(x) for x in output) cfg.chan_ap.clear() cfg.elapsed_time_ouput = time_ms() except: raise
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 __init__(self, iface_name): Thread.__init__(self) Observable.__init__(self) self._HANDLER = self._make_handler() self._abort = False self._monitor = None self._iface_name = iface_name self._iface = pyw.getcard(iface_name) self._timeout = 0
def switch_channel_loop(self, capture): mon0 = pyw.getcard('mon0') channel_range = [1, 3, 5, 7, 9, 11, 13] i = 0 while capture[0]: s = 'Listening on channel {}'.format(channel_range[i]) print('\033[1A{}\033[K'.format(s)) pyw.chset(mon0, channel_range[i], None) time.sleep(0.25) i = (i + 1) % len(channel_range)
def __init__(self, interface): self.interface = interface self.card = pyw.getcard(interface) self.modes = pyw.devmodes(self.card) self.original_mac = pyw.macget(self.card) # Important capabilities self._ap_mode_support = "AP" in self.modes self._monitor_mode_support = "monitor" in self.modes
def setup_capture_card(wireless_interface): procedure_logger.info("Loading card handle from interface name..") card = pyw.getcard(wireless_interface) if pyw.modeget(card) == 'monitor': procedure_logger.info("Wireless card already in monitor mode.") else: procedure_logger.info("Setting wireless card to monitor mode.") pyw.down(card) pyw.modeset(card, 'monitor') pyw.up(card) return card
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_wifi_chard(self, iface): ''' Get WiFi chard ''' if not self._check_if_my_iface(iface): self.log.error('check_if_my_iface failed') raise exceptions.FunctionExecutionFailed( func_name=inspect.currentframe().f_code.co_name, err_msg='No such interface: ' + iface) return pyw.getcard(iface) # get a card for interface
def __init__(self, interface): self.interface = interface self.card = None self.modes = None self.original_mac = None self._ap_mode_support = None self._monitor_mode_support = None try: self.card = pyw.getcard(interface) self.modes = pyw.devmodes(self.card) self.original_mac = pyw.macget(self.card) # Important capabilities self._ap_mode_support = "AP" in self.modes self._monitor_mode_support = "monitor" in self.modes except: pass self._number_of_supported_aps = None self._is_managed = False
def __init__(self, batch_size, sending_interval, wireless_interface, data_store): """ Initialize an aDTN instance and its respective key manager and message store, as well as a sending message pool from which the next sending batch gets generated. Define aDTNInnerPacket to be the payload of aDTNPacket. Define aDTNPacket to be the payload of Ethernet frames of type 0xcafe. Set up a scheduler to handle message sending. Define a thread to handle received messages. The wireless interface should be previously set to ad-hoc mode and its ESSID should be the same in other devices running aDTN. :param batch_size: number of packets to transmit at each sending operation :param sending_interval: number of seconds between two sending operations :param wireless_interface: wireless interface to send and receive packets """ self._batch_size = batch_size self._sending_freq = sending_interval self._wireless_interface = wireless_interface self._km = KeyManager() self.data_store = DataStore(data_store) self._sending_pool = [] self._scheduler = sched.scheduler(time, sleep) self._sending = None self._sniffing = None self._thread_send = None self._thread_receive = None self._sent_pkt_counter = None self._received_pkt_counter = None self._decrypted_pkt_counter = None self._start_time = None self._mac_address = macget(getcard(wireless_interface)) self._sending_socket = L2Socket(iface=self._wireless_interface) bind_layers(aDTNPacket, aDTNInnerPacket) bind_layers(Ether, aDTNPacket, type=ETHERTYPE) log_debug("MAC address in use: {}".format(self._mac_address)) self._stats_file_name = '{}_{}.stats'.format(batch_size, sending_interval)
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 getinfo(self): try: self.data['macaddress'] = netifaces.ifaddresses(self._if)[netifaces.AF_LINK][0]['addr'] except: self.data['macaddress'] = None try: self.data['ipaddress'] = netifaces.ifaddresses(self._if)[netifaces.AF_INET][0]['addr'] except: self.data['ipaddress'] = None try: self.data['vendorstr'] = self.udevnet.data[self._if+"_id_vendor_from_database"] except: self.data['vendorstr'] = None try: self.data['vendoroui'] = self.udevnet.data[self._if+"_id_oui_from_database"] except: self.data['vendoroui'] = None try: self.data['vendor'] = self.udevnet.data[self._if+"_id_vendor"] except: self.data['vendor'] = None # Hack for onboard raspberry devices if type(self.data['vendoroui']) is str: if re.search("^Raspberry", self.data['vendoroui']): self.data['vendor'] = "RaspberryPi" try: self.data['driver'] = self.udevnet.data[self._if+"_id_net_driver"] except: try: self.data['driver'] = self.udevnet.data[self._if+"_id_usb_driver"] except: self.data['driver'] = None try: self.data['model'] = self.udevnet.data[self._if+"_id_model_id"] except: self.data['model'] = None try: self.data['modelstr'] = self.udevnet.data[self._if+"_id_model_from_database"] except: self.data['modelstr'] = None try: self.data['netname'] = self.udevnet.data[self._if+"_id_net_name_from_database"] except: try: self.data['netname'] = self.udevnet.data[self._if+"_id_net_name_onboard"] except: try: self.data['netname'] = self.udevnet.data[self._if+"_id_net_name_slot"] except: try: self.data['netname'] = self.udevnet.data[self._if+"_id_net_name_path"] except: try: self.data['netname'] = self.udevnet.data[self._if+"_id_net_name_mac"] except: self.data['netname'] = None try: self.data['type'] = self.udevnet.data[self._if+"_devtype"] if self.data['type'] == "wlan": self.data['type'] = "Wireless" except: try: if re.search("^en", self.data['netname']): self.data['type'] = "Ethernet" elif re.search("^wl", self.data['netname']): self.data['type'] = "Wireless" else: self.data['type'] = None except: self.data['type'] = None # Stop here if we don't have a wireless card if self.data['type'] != "Wireless": return # Retrieve wireless info try: _ifobj = pyw.getcard(self._if) _ifinfo = pyw.ifinfo(_ifobj) _devinfo = pyw.devinfo(_ifobj) _physinfo = pyw.phyinfo(_ifobj) _linkinfo = pyw.link(_ifobj) except: pass try: self.data['isup'] = pyw.isup(_ifobj) except: self.data['isup'] = None try: self.data['blocked'] = pyw.isblocked(_ifobj) except: self.data['blocked'] = None try: self.data['mode'] = _devinfo['mode'] except: self.data['mode'] = None try: self.data['modes'] = _physinfo['modes'] except: self.data['modes'] = None try: self.data['bands'] = _physinfo['bands'] except: self.data['bands'] = None try: self.data['standards'] = pyw.devstds(_ifobj) except: self.data['standards'] = None try: self.data['freqs'] = pyw.devfreqs(_ifobj) except: self.data['freqs'] = None try: self.data['txpower'] = pyw.txget(_ifobj) except: self.data['txpower'] = None try: self.data['chans'] = pyw.devchs(_ifobj) except: self.data['chans'] = None try: self.data['reg'] = pyw.regget(_ifobj) except: self.data['reg'] = None try: self.data['chipset'] = _ifinfo['chipset'] except: self.data['chipset'] = None try: self.data['state'] = _linkinfo['stat'] except: self.data['state'] = None try: self.data['ssid'] = _linkinfo['ssid'] except: self.data['ssid'] = None try: self.data['chw'] = _devinfo['CHW'] except: self.data['chw'] = None try: self.data['frequency'] = _devinfo['RF'] except: self.data['frequency'] = None try: self.data['rss'] = _linkinfo['rss'] except: self.data['rss'] = None try: self.data['wtx'] = _linkinfo['tx'] except: self.data['wtx'] = None try: self.data['wrx'] = _linkinfo['rx'] except: self.data['wrx'] = None
def test_validcard(self): for wnic in wnics: self.assertTrue(pyw.validcard(pyw.getcard(wnic)))
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
def set_channel(self, channel): card = pyw.getcard(self._name) pyw.chset(card, channel, None)
def configure(win,conf): """ shows options to configure captiv8 for running :param win: the main window :param conf: current state of configuration dict """ # create our on/off for radio buttons BON = curses.ACS_DIAMOND BOFF = '_' # create an inputs dict to hold the begin locations of inputs ins = {} # input -> (start_y,start_x,endx) # create a copy of conf to manipulate newconf = {} for c in conf: newconf[c] = conf[c] # create new window (new window will cover the main window) # get sizes for coord translation nr,nc = win.getmaxyx() # size of the main window ny,nx = 15,50 # size of new window zy,zx = (nr-ny)/2,(nc-nx)/2 # 0,0 (top left corner) of new window confwin = curses.newwin(ny,nx,zy,zx) # draw a blue border and write title confwin.attron(CPS[BLUE]) confwin.border(0) confwin.attron(CPS[BLUE]) confwin.addstr(1,1,"Configure Options",CPS[BLUE]) # ssid option, add if present add a clear button to the right confwin.addstr(2,1,"SSID: " + '_'*_SSIDLEN_,CPS[WHITE]) ins['SSID'] = (2+zy,len("SSID: ")+zx+1,len("SSID: ")+zx+_SSIDLEN_) if newconf['SSID']: for i,s in enumerate(newconf['SSID']): confwin.addch(ins['SSID'][0]-zy,ins['SSID'][1]-zx+i,s,CPS[GREEN]) # allow for up to 6 devices to choose in rows of 2 x 3 confwin.addstr(3,1,"Select dev:",CPS[WHITE]) # the sub title i = 4 # current row j = 0 # current dev devs = pyw.winterfaces()[:8] if not newconf['dev'] in devs: newconf['dev'] = None for dev in devs: stds = "" monitor = True nl80211 = True try: card = pyw.getcard(dev) stds = pyw.devstds(card) monitor = 'monitor' in pyw.devmodes(card) except pyric.error: # assume just related to current dev nl80211 = False devopt = "{0}. (_) {1}".format(j+1,dev) if stds: devopt += " IEEE 802.11{0}".format(''.join(stds)) if monitor and nl80211: confwin.addstr(i,2,devopt,CPS[WHITE]) ins[j] = (i+zy,len("n. (")+zx+2,len("n. (")+zx+3) if newconf['dev'] == dev: confwin.addch(ins[j][0]-zy,ins[j][1]-zx,BON,CPS[GREEN]) else: # make it gray errmsg = "" if not monitor: errmsg = "No monitor mode" elif not nl80211: errmsg = "No nl80211" confwin.addstr(i,2,devopt,CPS[GRAY]) confwin.addstr(i,3,'X',CPS[GRAY]) confwin.addstr(i,len(devopt)+3,errmsg,CPS[GRAY]) i += 1 j += 1 # connect option, select current if present confwin.addstr(i,1,"Connect: (_) auto (_) manual",CPS[WHITE]) ins['auto'] = (i+zy,len("Connect: (")+zx+1,len("Connect: (")+zx+2) ins['manual'] = (i+zy, len("Connect: (_) auto (")+zx+1, len("Connect: (_) auto (")+zx+2) if newconf['connect']: confwin.addch(ins[newconf['connect']][0]-zy, ins[newconf['connect']][1]-zx, BON,CPS[GREEN]) # we want two buttons Set and Cancel. Make these buttons centered. Underline # the first character btn1 = "Set" btn2 = "Cancel" btnlen = len(btn1) + len(btn2) + 1 # add a space btncen = (nx-btnlen) / 2 # center point for both # btn 1 -> underline first character y,x = ny-2,btncen-(len(btn1)-1) confwin.addstr(y,x,btn1[0],CPS[BUTTON]|curses.A_UNDERLINE) confwin.addstr(y,x+1,btn1[1:],CPS[BUTTON]) ins['set'] = (y+zy,x+zx,x+zx+len(btn1)-1) # btn 2 -> underline first character y,x = ny-2,btncen+2 confwin.addstr(y,x,btn2[0],CPS[BUTTON]|curses.A_UNDERLINE) confwin.addstr(y,x+1,btn2[1:],CPS[BUTTON]) ins['cancel'] = (y+zy,x+zx,x+zx+len(btn2)-1) confwin.refresh() # capture the focus and run our execution loop confwin.keypad(1) # enable IOT read mouse events store = False while True: _ev = confwin.getch() if _ev == curses.KEY_MOUSE: # handle mouse, determine if we should check/uncheck etc try: _,mx,my,_,b = curses.getmouse() except curses.error: continue if b == curses.BUTTON1_CLICKED: # determine if we're inside a option area if my == ins['set'][0]: if ins['set'][1] <= mx <= ins['set'][2]: store = True break elif ins['cancel'][1] <= mx <= ins['cancel'][2]: break elif my == ins['SSID'][0]: if ins['SSID'][1] <= mx <= ins['SSID'][2]: # move the cursor to the first entry char & turn on curs = ins['SSID'][0],ins['SSID'][1] confwin.move(curs[0]-zy,curs[1]-zx) curses.curs_set(1) # loop until we get <ENTER> while True: # get the next char _ev = confwin.getch() if _ev == ascii.NL or _ev == curses.KEY_ENTER: break elif _ev == ascii.BS or _ev == curses.KEY_BACKSPACE: if curs[1] == ins['SSID'][1]: continue # delete (write over with '-') prev char, then move back curs = curs[0],curs[1]-1 confwin.addch(curs[0]-zy, curs[1]-zx, BOFF, CPS[WHITE]) confwin.move(curs[0]-zy,curs[1]-zx) else: if curs[1] > ins['SSID'][2]: curses.flash() continue # add the character, (cursor moves on its own) # update our pointer for the next entry try: confwin.addstr(curs[0]-zy, curs[1]-zx, chr(_ev), CPS[GREEN]) curs = curs[0],curs[1]+1 except ValueError: # put this back on and see if the outer # loop can do something with it curses.ungetch(_ev) break curses.curs_set(0) # turn off the cursor elif my == ins['auto'][0]: if ins['auto'][1] <= mx <= ins['auto'][2]: if newconf['connect'] == 'manual': # turn off manual confwin.addch(ins['manual'][0]-zy, ins['manual'][1]-zx, BOFF,CPS[WHITE]) newconf['connect'] = 'auto' confwin.addch(my-zy,mx-zx,BON,CPS[GREEN]) confwin.refresh() elif ins['manual'][1] <= mx <= ins['manual'][2]: if newconf['connect'] == 'auto': # turn off auto confwin.addch(ins['auto'][0]-zy, ins['auto'][1]-zx, BOFF,CPS[WHITE]) newconf['connect'] = 'manual' confwin.addch(my-zy,mx-zx,BON,CPS[GREEN]) confwin.refresh() else: # check for each listed device for d in range(j): if my == ins[d][0] and ins[d][1] <= mx <= ins[d][2]: # check the selected dev confwin.addch(my-zy,mx-zx,BON,CPS[GREEN]) # determine if a previously selected needs to be unchecked if newconf['dev'] is None: pass elif newconf['dev'] != devs[d]: i = devs.index(newconf['dev']) confwin.addch(ins[i][0]-zy, ins[i][1]-zx, BOFF, CPS[WHITE]) newconf['dev'] = devs[d] confwin.refresh() break # exit the for loop else: try: _ch = chr(_ev).upper() except ValueError: continue if _ch == 'S': store = True break elif _ch == 'C': break elif _ch == 'L': pass # only 'radio buttons' are kept, check if a SSID was entered and add if so if store: ssid = confwin.instr(ins['SSID'][0]-zy,ins['SSID'][1]-zx,_SSIDLEN_) ssid = ssid.strip('_').strip() # remove training lines, & spaces if ssid: newconf['SSID'] = ssid # delete this window and return del confwin # remove the window return newconf if store else None
def up_ifaces(self, ifaces): for i in ifaces: card = pyw.getcard(i.get_name()) pyw.up(card)
def setUp(self): self.card = pyw.getcard(pri['dev']) def tearDown(self): pass
def test_getcard(self): for wnic in wnics: self.assertIsNotNone(pyw.getcard(wnic))
def _get_ssid_from_mac(self, mac_address): for iface in pyw.winterfaces(): if pyw.macget(pyw.getcard(iface)) == mac_address: return NetUtils().get_ssid_from_interface(iface)