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 set_interface_mac(self, interface_name, mac_address): """ Set the specified MAC address for the interface :param self: A NetworkManager object :param interface_name: Name of an interface :param mac_address: A MAC address :type self: NetworkManager :type interface_name: str :type mac_address: str :return: None :rtype: None .. note: This method will set the interface to managed mode """ card = self._name_to_object[interface_name].card self.set_interface_mode(interface_name, "managed") # card must be turned off(down) before setting mac address try: pyw.down(card) pyw.macset(card, mac_address) pyw.up(card) # make sure to catch an invalid mac address except pyric.error as error: if error[0] == 22: raise InvalidMacAddressError(mac_address) else: raise
def add_virtual_interface(self, card): """ Add the virtual interface to the host system :param self: A NetworkManager object :param card: A pyw.Card object :type self: NetworkManager :type card: pyw.Card :return name of the interface :rtype str :..note: when add the interface it is possible raising the pyric.error causing by adding the duplicated wlan interface name. """ done_flag = True number = 0 while done_flag: try: number += 1 name = 'wlan' + str(number) pyw.down(card) monitor_card = pyw.devadd(card, name, 'monitor') done_flag = False # catch if wlan1 is already exist except pyric.error: pass self._vifs_add.add(monitor_card) return name
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 set_mode(self, mode): try: pyw.down(self.card) pyw.modeset(self.card, mode) pyw.up(self.card) except Exception as e: print e, "\n[-] Unable to set mode on {}".format(self.interface) return False
def test_chsetget(self): pyw.down(self.card) pyw.modeset(self.card,'monitor') pyw.up(self.card) self.assertEqual(None,pyw.chset(self.card,1)) self.assertIsInstance(pyw.chget(self.card),int) pyw.down(self.card) pyw.modeset(self.card,'managed') pyw.up(self.card)
def set_mac(self, mac): try: pyw.down(self.card) 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 test_chsetget(self): pyw.down(self.card) pyw.modeset(self.card, "monitor") pyw.up(self.card) self.assertEqual(None, pyw.chset(self.card, 1)) self.assertIsInstance(pyw.chget(self.card), int) pyw.down(self.card) pyw.modeset(self.card, "managed") pyw.up(self.card)
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_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 down_interface(self, interface_name): """ Equivalent to ifconfig interface_name down :param self: A NetworkManager object :param interface_name: Name of an interface :type self: NetworkManager :type interface_name: str :return: None :rtype: None """ card = self._name_to_object[interface_name].card pyw.down(card)
def restore_mac(): if "iface" not in request.args: return jsonify(message="'iface' not provided") iface = str(request.args.get("iface")) mac = Wireless.getRealMac(iface).strip() try: w0 = pyw.getcard(iface) pyw.down(w0) sb.check_call(["macchanger", "-p", w0.dev]) pyw.up(w0) except Exception, e: print str(e) return jsonify(message="Failed to change mac addr : "), 400
def recover_mac_address_to_original(self): """ Recover the mac addresses to original one on exit :param self: A NetworkManager object :type self: NetworkManager :return: None :rtype: None """ for k, i in self._interfaces.iteritems(): if i._prev_mac != i._current_mac: card = pyw.getcard(i.get_name()) pyw.down(card) pyw.macset(card, i._prev_mac) pyw.up(card)
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 randomize_interface_mac(self, mac=None): """ Randomize the MACs for the network adapters :param self: A NetworkAdapter object :param mac: A MAC address :type self: NetworkAdapter :type mac: string :return: None :rtype: None """ mac_addr = self._generate_random_address() if mac is None else mac card = pyw.getcard(self.get_name()) pyw.down(card) pyw.macset(card, mac_addr) self._current_mac = mac_addr
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 change_mac(): if "iface" not in request.args: return jsonify(message="'iface' not provided") if "mac" not in request.args: return jsonify(message="'mac' not provided") iface = str(request.args.get("iface")) mac = str(request.args.get("mac")) try: w0 = pyw.getcard(iface) pyw.down(w0) sb.check_call(["macchanger", "-m", mac, w0.dev]) pyw.up(w0) except Exception, e: print str(e) return jsonify(message="Failed to change mac addr : "), 400
def set_interface_mode(self, interface_name, mode): """ Set the specified mode for the interface :param self: A NetworkManager object :param interface_name: Name of an interface :param mode: Mode of an interface :type self: NetworkManager :type interface_name: str :type mode: str :return: None :rtype: None .. note: Available modes are unspecified, ibss, managed, AP AP VLAN, wds, monitor, mesh, p2p """ card = self._name_to_object[interface_name].card # set interface mode between brining it down and up pyw.down(card) pyw.modeset(card, mode) pyw.up(card)
def setup_hotspot(interface): if interface == 'internal': interface = PI3_WIFI_NIC if pyw.isinterface(HOTSPOT_NIC): interface = HOTSPOT_NIC # check if we already setup a hot spot if pyw.isinterface(interface): card = pyw.getcard(interface) pyw.down(card) subprocess.run(["ip link set " + card.dev + " name " + HOTSPOT_NIC], shell=True) time.sleep(1) card = pyw.getcard(HOTSPOT_NIC) pyw.up(card) pyw.inetset(card, '192.168.2.1') subprocess.run(["udhcpd -I 192.168.2.1 " + os.path.join(DRONEBRIDGE_BIN_PATH, "udhcpd-wifi.conf")], shell=True, stdout=DEVNULL) subprocess.run( ["dos2unix -n " + os.path.join(DRONEBRIDGE_SETTINGS_PATH, "apconfig.txt") + " /tmp/apconfig.txt"], shell=True, stdout=DEVNULL) subprocess.Popen(["hostapd", "/tmp/apconfig.txt"], shell=False) print("Setup wifi hotspot: " + card.dev + " AP-IP: 192.168.2.1") else: print("Error: Could not find AP-adapter: " + str(interface) + ", unable to enable access point")
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 run_capture(wireless_interface, log_file, tmp_dir, database_loc, verbose=False, sample_seconds=10, rounds=0, ignore_non_root=False, db_timeout_seconds=60, heartbeat_func=lambda: None, run_with_monitor=True): setup_logging(log_file, verbose) if run_with_monitor: return run_monitored(run_capture, always_restart=False)(wireless_interface, log_file, tmp_dir, database_loc, verbose, sample_seconds, rounds, ignore_non_root, db_timeout_seconds, run_with_monitor=False) try: heartbeat_func() effective_user_id = os.geteuid() if effective_user_id != 0 and ignore_non_root: procedure_logger.warning( "Not running as root, attempting to proceed...") elif effective_user_id != 0: raise OSError( "This script requires root-level permissions to run. " "Please either run as superuser or use the --ignore-non-root flag." ) run_forever = rounds == 0 db_conn = create_connection(database_loc, db_timeout_seconds) write_schema(db_conn) with transaction_wrapper(db_conn) as t: kv_store_set(t, "capture/script_start_time", time.time()) kv_store_set(t, 'capture/script_pid', os.getpid()) kv_store_set(t, "capture/interface", wireless_interface) kv_store_set(t, "capture/sample_seconds", sample_seconds) card = setup_capture_card(wireless_interface) if not os.path.exists(tmp_dir): procedure_logger.warning( "Tmp dir {0} does not exist. Creating...".format(tmp_dir)) os.makedirs(tmp_dir) procedure_logger.info("Beginning channel scan.") heartbeat_func() current_round = 0 while run_forever or rounds > 0: heartbeat_func() procedure_logger.info( "Executing capture round {0}".format(current_round)) with transaction_wrapper(db_conn) as t: kv_store_set(t, "capture/current_script_round", current_round) for channel in range(1, 12): heartbeat_func() procedure_logger.info( "Changing to channel {0}".format(channel)) pyw.down(card) pyw.up(card) pyw.chset(card, channel, None) procedure_logger.info("Opening the pcap driver...") capture_file = os.path.join( tmp_dir, "channel{0}-{1}.pcap".format(channel, time.time())) try: procedure_logger.info("Beginning live capture...") start_time, end_time, duration = run_live_capture( wireless_interface, capture_file, sample_seconds) procedure_logger.info("Starting offline analysis...") data = run_offline_analysis(capture_file, start_time, end_time, duration, channel) procedure_logger.info( "Writing analysis data to database...") write_offline_analysis_to_database(db_conn, data) procedure_logger.info("Data written...") finally: procedure_logger.info("Cleaning up capture file..") if os.path.exists(capture_file): os.unlink(capture_file) if not run_forever: rounds -= 1 current_round += 1 except BaseException: procedure_logger.exception( "Unhandled exception during capture! Aborting,...") raise else: procedure_logger.info("No more data. Ending...")
def __exit__(self, *args): # Leave things the way you found them, like your parents said if self.initial_state == self.STATE_INACTIVE: pyw.down(self.wlan_if)
def setUp(self): CardTestCase.setUp(self) pyw.down(self.card)
def set_interface_down(self, ifaceName): card = self.get_wifi_chard(ifaceName) # get a card for interface pyw.down(card) return True
def card_down(card): return pyw.down(card)
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 test_modeset(self): pyw.down(self.card) self.assertEquals(None, pyw.modeset(self.card, "monitor")) self.assertEquals(None, pyw.modeset(self.card, "managed")) pyw.up(self.card)
def test_modeset(self): pyw.down(self.card) self.assertEqual(None,pyw.modeset(self.card,'monitor')) self.assertEqual(None,pyw.modeset(self.card,'managed')) pyw.up(self.card)
def configure_interface(self, interface, name='mon0', channel=1, txpower=60, bitrate=11): """Configure the given card in monitor mode""" # Determine the type of card for this interface try: driver = pywhw.ifcard(interface)[0] print(driver) if driver == 'rtl88xxau': type = Card.rtl88xx else: type = Card.ath9k except Exception as e: print(e) return None # Get the card for this interface try: card = pyw.getcard(interface) except pyric.error as e: logging.error("Error connecting to the interface: " + interface) return None # Ensure this card supports monitor mode if 'monitor' not in pyw.devmodes(card): logging.error(interface + " does not support monitor mode") return None # Configure the bitrate for this card # This is not supported by pyric, so we have to do it manually. if bitrate != 0 and type == Card.ath9k: try: pyw.down(card) pyw.modeset(card, 'managed') pyw.up(card) logging.debug("Setting the bitrate on interface " + interface + " to " + str(bitrate)) if os.system("iw dev " + card.dev + " set bitrates legacy-2.4 " + str(bitrate)) != 0: #if os.system("iwconfig " + card.dev + " rate 54M fixed") != 0: logging.error("Error setting the bitrate for: " + interface) return None pyw.down(card) except pyric.error as e: logging.error("Error setting the bitrate for: " + interface) logging.error(e) return None # Try to configure the transmit power level (some cards don't support this) try: pyw.txset(card, txpower, 'fixed') except pyric.error as e: pass # Bring the interface up try: pyw.up(card) except pyric.error as e: logging.error("Error bringing up the interface: " + card.dev) logging.error(e) return False # Configure the channel try: logging.debug("Changing to channel: " + str(channel)) pyw.chset(card, channel, None) except pyric.error as e: logging.error("Error setting the wifi channel on: " + card.dev) logging.error(e) return False return card
def test_down(self): self.assertEqual(None,pyw.down(self.card)) self.assertFalse(pyw.isup(self.card))
def test_down(self): self.assertEqual(None, pyw.down(self.card)) self.assertFalse(pyw.isup(self.card))
# parse arguments parser = argparse.ArgumentParser(prog="python3 -m sniffer", description='Wifinet Sniffer') parser.add_argument('-i', '--iface', required=True, help="Interface of Wifi Card") parser.add_argument('-m', '--mongodb', default=MONGO_DB, help="Default: {}".format(MONGO_DB)) args = parser.parse_args() # set card into monitor mode pyw_card = pyw.getcard(args.iface) pyw.down(pyw_card) pyw.modeset(pyw_card, 'monitor') pyw.up(pyw_card) journal.write("Interface {} set to promiscuous mode".format(args.iface)) # start scanning sniffer = Process(name='sniffer', target=scan, args=(args.iface, channel_weights, args.mongodb)) sniffer.start() journal.write("Start channel hopping on interface {}".format(args.iface)) while (sniffer.is_alive): weights = list(channel_weights) channels = list(range(1, CHANNEL_COUNT + 1)) ch = choices(channels, weights)[0]