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 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 _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 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 get_connected_clients(self): try: mode = pyw.modeget(self.card) except: mode = None if mode == 'AP': os.system("iw dev {} station dump".format(self.interface)) else: print "[-] '{}' is not on AP mode".format(self.interface)
def get_connected_clients(self): try: mode = pyw.modeget(self.card) except: mode = None if mode == 'AP': os.system("iw dev {} station dump".format(self.interface)) else: print "[-] '{}' is not on AP mode".format(self.interface)
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 set_mac(self, mac): try: pyw.down(self.card) # If card was in monitor mode then macset wouldn't work right if pyw.modeget(self.card) == "monitor": pyw.modeset(self.card, "managed") pyw.macset(self.card, mac) pyw.up(self.card) return True except Exception as e: print e, "\n[-] Unable to set mac on {}".format(self.interface) return False
def set_mac(self, mac): try: pyw.down(self.card) # If card was in monitor mode then macset wouldn't work right if pyw.modeget(self.card) == "monitor": pyw.modeset(self.card, "managed") pyw.macset(self.card, mac) pyw.up(self.card) return True except Exception as e: print e, "\n[-] Unable to set mac on {}".format(self.interface) return False
def set_monitor_mode(interface: Union[str, pyw.Card]) -> pyw.Card: interface = _get_card(interface) if pyw.modeget(interface) != "monitor": if pyw.isup(interface): pyw.down(interface) pyw.modeset(interface, "monitor") if not pyw.isup(interface): pyw.up(interface) return interface
def get_interface(): """ Find a possibly working wifi interface that can be used by a DroneBridge module :return: Name of an interface set to monitor mode """ interface_names = pyw.winterfaces() for interface_name in interface_names: if interface_name != PI3_WIFI_NIC and interface_name != HOTSPOT_NIC: card = pyw.getcard(interface_name) if pyw.modeget(card) == 'monitor': return interface_name print("ERROR: Could not find a wifi adapter in monitor mode") exit(-1)
def SetMonitorMode(iface, action): wcard = pyw.getcard(iface) # bring card down to ensure safe change pyw.down(wcard) if action == "monitor": # check to make sure the card isn't already in monitor mode if pyw.modeget(wcard) == 'monitor': print(("Card %s is already in monitor Mode" % str(iface))) else: print(("Putting card %s into monitor mode" % str(iface))) pyw.modeset(wcard, action) elif action == "managed": # check to make sure the card isn't already in managed mode if pyw.modeget(wcard) == 'managed': print(("Card %s is already in managed Mode" % str(iface))) else: print(("Putting card %s into managed mode" % str(iface))) pyw.modeset(wcard, action) else: print("Unrecongnized command") # Bring card back up, should now be changed. pyw.up(wcard)
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 ] ssid = NetUtils().get_ssid_from_interface(interface) 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 = NetUtils().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, ssid, inactivity_time, rx_packets, tx_packets, rx_bitrate, tx_bitrate, signal) try: if client not in self.connected_clients[interface]: connected_client_str = "New connected client on '{ssid}'-> ip: {ip}, mac: {mac} ({vendor})"\ .format(ssid=ssid, ip=client_ip, mac=client_mac, vendor=client.vendor) SessionManager().log_event( SuccessfulEvent(connected_client_str)) print "[+]", connected_client_str except: pass temp_clients.append(client) self.connected_clients[interface] = temp_clients return True
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 set_monitor_mode(interface): """ Set interface in mode monitor an set channel 1 """ interface = pyw.getcard(interface) if pyw.modeget(interface) != "monitor": if pyw.isup(interface): pyw.down(interface) pyw.modeset(interface, "monitor") if not pyw.isup(interface): pyw.up(interface) if pyw.chget(interface) != 1: pyw.chset(interface, 1)
def get_interfaces() -> list: """ Find a possibly working wifi interfaces that can be used by a DroneBridge modules :return: List of names of interfaces set to monitor mode """ interfaces = [] interface_names = pyw.winterfaces() for interface_name in interface_names: if interface_name != PI3_WIFI_NIC and interface_name != HOTSPOT_NIC: card = pyw.getcard(interface_name) if pyw.modeget(card) == 'monitor': interfaces.append(interface_name) if len(interfaces) == 0: print("ERROR: Could not find a wifi adapter in monitor mode") exit(-1) else: return interfaces
def __init__(self, interface : str, hopper = None, target : str = None): 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.handler_map = {0:{}, 1:{}, 2:{}} self.filter = f"ether host {target}" if target else None self.hopper = hopper self.logger.info(f"App created on interface: {self.interface.dev}")
def get_all_monitor_interfaces(formatted=False): """ Find all possibly working wifi interfaces that can be used by a DroneBridge modules :param formatted: Formatted to be used as input for DroneBridge modules :return: List of names of interfaces set to monitor mode """ w_interfaces = [] interface_names = pyw.winterfaces() for interface_name in interface_names: if interface_name != PI3_WIFI_NIC and interface_name != HOTSPOT_NIC: card = pyw.getcard(interface_name) if pyw.modeget(card) == 'monitor': w_interfaces.append(interface_name) if formatted: formated_str = "" for w_int in w_interfaces: formated_str = formated_str + " -n " + w_int return formated_str[1:] else: formated_str = "" for w_int in w_interfaces: formated_str = formated_str + " " + w_int return formated_str[1:]
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 get_mode(self): try: return pyw.modeget(self.card) except Exception: return None
def get_mode(self): try: return pyw.modeget(self.card) except Exception: return None
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 test_modeget(self): self.assertEqual('managed',pyw.modeget(self.card))
def get_mode(interface): return pyw.modeget(interface)
def get_mon_devices(): return [x for x in pyw.winterfaces() if pyw.modeget(x) == "monitor"]