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 breakmonitor(): self.iface = pyw.devadd(m0, 'wlan0', 'managed') # restore wlan0 in managed mode pyw.devdel(self.moniface) # delete the monitor interface pyw.setmac(self.iface, self.macaddress) # restore the original mac address pyw.up(self.iface) # and bring the card up
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 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_up(self, ifaceName): card = self.get_wifi_chard(ifaceName) # get a card for interface # TODO: replace by pyric rfkill cmd = "rfkill unblock wifi" self.run_command(cmd) pyw.up(card) return pyw.isup(card)
def __enter__(self): if not pyw.isup(self.wlan_if): pyw.up(self.wlan_if) return True # Good to go if it's already active, but not otherwise return self.initial_state == self.STATE_ACTIVE
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 _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 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 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 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 up_interface(self, interface_name): # type: (str) -> None """Equivalent to ifconfig interface_name up. ..note: Let the pyrobophisher decide when to up the interface since some cards cannot up two virtual interface with managed mode in the same time. """ card = self._name_to_object[interface_name].card pyw.up(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 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 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 up_interface(self, interface_name): """ Equivalent to ifconfig interface_name up :param self: A NetworkManager object :param interface_name: Name of an interface :type self: NetworkManager :type interface_name: str :return: None :rtype: None ..note: Let the pywifiphisher decide when to up the interface since some cards cannot up two virtual interface with managed mode in the same time. """ card = self._name_to_object[interface_name].card pyw.up(card)
def turn_monitor_on(self): self.card = pyw.getcard(self.interface) if self.name: self.newcard = pyw.devset(self.card, self.name) pyw.modeset(self.newcard, "monitor") pyw.up(self.newcard) else: self.newcard = pyw.devset(self.card, self.card.dev+"mon") pyw.modeset(self.newcard, "monitor") pyw.up(self.newcard) print(c.OKGREEN+" [+] "+c.WHITE+"New Card Name: "+c.HEADER+self.newcard.dev) if self.channel != None: self.set_channel() return
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 turn_monitor_on(self): self.card = pyw.getcard(self.interface) try: if self.name: self.newcard = pyw.devset(self.card, self.name) pyw.modeset(self.newcard, "monitor") pyw.up(self.newcard) else: self.newcard = pyw.devset(self.card, self.card.dev + "mon") pyw.modeset(self.newcard, "monitor") pyw.up(self.newcard) print(c.OKGREEN + " [+] " + c.WHITE + "New Card Name: " + c.HEADER + self.newcard.dev) if self.channel != None: self.set_channel() except: print(c.FAIL + " [-] " + c.WHITE + " Error: " + str(exc_info())) return
def createVirtualInterface(old_iface, new_iface, mode="monitor", channel=1): """ Creates a virtual interface with the specified options and returns its pywric.Card object. (when creating new interface the old one is deleted.) Arguments : old_iface -- old interface name. new_iface -- new interface name. mode -- open the new interface in the given mode (default:monitor). channel -- start the new interface on the given channel. """ # return None if invailed wireless interface if pyw.iswireless(old_iface) == False: return None wi = pyw.getcard(old_iface) # check if the specifed mode is supported by the card if mode in pyw.devmodes(wi): # create new interfaces with the specifed prefix-string default="mon" viface = pyw.devadd(wi, new_iface, mode) # delete all other interfaces with same phy id for card, _ in pyw.ifaces(wi): # delete all interfaces if not card.dev == viface.dev: # that are not our pyw.devdel(card) # set default channel pyw.chset(viface, channel, None) # up the vitual interface pyw.up(viface) # return the newly created interface as pyw.Card() onject return viface
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 run(self): print("Starting scanner...") self._abort = False hopper = None try: # set up monitor self._monitor = pyw.devadd(self._iface, Scanner._MON_NAME, 'monitor') for card, dev in pyw.ifaces(self._monitor): if card.dev != self._monitor.dev: pyw.devdel(card) pyw.up(self._monitor) self._iface = None # set up channel hopping hopper = ChannelHopper(self._monitor) hopper.start() sniff(iface=Scanner._MON_NAME, store=0, prn=self._HANDLER, lfilter=Scanner._LFILTER, timeout=self._timeout, stop_filter=self._stop_filter) self.notify_observers((EV_SCAN_OK, )) except pyric.error as e: self.notify_observers((EV_SCAN_FAILED, e)) finally: if hopper: # stop channel hopping hopper.stop() if self._monitor: # destroy monitor interface self._iface = pyw.devadd(self._monitor, self._iface_name, 'managed') pyw.devdel(self._monitor) pyw.up(self._iface) self._monitor = None
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 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 up_ifaces(self, ifaces): for i in ifaces: card = pyw.getcard(i.get_name()) pyw.up(card)
def test_up(self): self.assertEqual(None,pyw.up(self.card)) self.assertTrue(pyw.isup(self.card))
def ifconfig(self, ip, netmask=None, broadcast=None): if self._valid_card(): pyw.up(self.card) pyw.ifaddrset(self.card, ip, netmask, broadcast)
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 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 tearDown(self): pyw.up(self.card)