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 set_interface_channel(self, interface_name, channel): """ Set the channel for the interface :param self: A NetworkManager object :param interface_name: Name of an interface :param channel: A channel number :type self: NetworkManager :type interface_name: str :type channel: int :return: None :rtype: None """ card = self._name_to_object[interface_name].card pyw.chset(card, channel)
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 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 channel_hop(self): interface = pyw.getcard(self.mInterface) channelCounter = 0 while 1: if len(self.mChannels) == 1: with threadLock: self.mChannel = self.mChannels[0] try: pyw.chset(interface, int(self.mChannel), None) except: sys.stderr.write("Channel Hopping Failed") else: with threadLock: self.mChannel = str(self.mChannels[channelCounter]) channelCounter += 1 if channelCounter == len(self.mChannels): channelCounter = 0 with threadLock: self.firstPass = False try: pyw.chset(interface, int(self.mChannel), None) except Exception, e: print str(e) sys.stderr.write("Channel Hopping Failed!") self.output() if len(self.mChannels) == 1: time.sleep(.1) else: if self.firstPass == 1: time.sleep(3.5) continue self.deauth()
def set_channel(self, channel, ifaceName, chw=None, **kwargs): """ Set the Rf channel :param channel: the new channel, i.e. channel number according to IEEE 802.11 spec :param ifaceName: name of the interface :param chw: bandwidth of the channel :param kwargs: optional args, i.e. path to control socket, :return: True in case it was successful """ self.log.info('Setting channel for {}:{} to {}'.format( ifaceName, self.device, channel)) try: w0 = self.get_wifi_chard(ifaceName) # get a card for interface # check mode dinfo = pyw.devinfo(w0) if dinfo['mode'] == 'AP': if not "control_socket_path" in kwargs: self.log.warn( 'Please pass the path to hostapd control socket') return False # pass new chanel to hostapd # hostapd requires frequency not channel freq = ch2rf(channel) control_socket_path = kwargs["control_socket_path"] beacon_periods = 5 cmd = ('sudo hostapd_cli -p {} chan_switch {} {}'.format( control_socket_path, beacon_periods, freq)) self.run_command(cmd) else: # chw: channel width oneof {None|'HT20'|'HT40-'|'HT40+'} # chw = None pyw.chset(w0, channel, chw) self.channel = channel except Exception as e: fname = inspect.currentframe().f_code.co_name self.log.fatal("An error occurred in %s: %s" % (fname, e)) raise exceptions.FunctionExecutionFailed(func_name=fname, err_msg=str(e)) return True
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 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 channel_hopping(self, channel): if hasattr(self, '_interface_mon'): pyw.chset(self._interface_mon, channel, None) return True else: return False
def set_channel(self, channel): try: pyw.chset(self.card, channel) except: return None
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")
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] pyw.chset(pyw_card, ch, None) sleep(0.5)
def set_channel(self, channel): card = pyw.getcard(self._name) pyw.chset(card, channel, None)
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 hopper(self): global gAlive # Create pyric card object. interface = pyw.getcard(self.mInterface) # Set channel hopping timeout. timeout = 1.0 # Get channels if frequency is 2.4 ghz if self.mFrequency == 2: freqs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] # Get channels if frequency is 5.8 ghz elif self.mFrequency == 5: freqs = [ 36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112, 116, 132, 136, 140, 149, 153, 157, 161, 165 ] # Repeat until program exits. while gAlive: try: # If target not found yet. if not self.mFilterChannel: # Choose channel at random. channel = choice(freqs) # Set channel pyw.chset(interface, channel, None) # Set channel variable self.mChannel = channel # If target found. else: # Set Channel pyw.chset(interface, self.mFilterChannel, None) # Set channel variable self.mChannel = self.mFilterChannel # Set cap messages self.mCapMessage = "[:Hopper Thread Exited:]" # Break out of loop and return. break # Increase timeout every iteration. if timeout < 3: # Increment timeout. timeout += .05 # Sleep program for timeout. sleep(timeout) except AttributeError: printf( "Thread-1 Error: Most likely interpreter shutdown. Disregard." ) # Exit hopper. return
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 set_channel(self, channel): pyw.chset(self.card, channel)
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 set_channel(self, channel): try: pyw.chset(self.card, channel) except Exception as e: raise e return None
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")