def get_iface(self):
     for iface in pyw.winterfaces():
         LOG.debug("iface: {}".format(iface))
     for iface in pyw.winterfaces():
         #if "wlan0" in iface:
         if "p2p" in iface:
             return iface
     raise RuntimeError('No p2p interfaces are up')
Esempio n. 2
0
    def __init__(self):
        """
        Setup the class with all the given arguments.

        :param self: A NetworkManager object
        :param jamming_argument: The jamming argument given by user
        :param ap_argument: The AP argument given by user
        :type self: NetworkManager
        :type jamming_argument: str
        :type ap_argument: str
        :return: None
        :rtype: None
        .. seealso:: NetworkAdapter
        """

        # Setup the fields
        self._interfaces = {}
        self.ap_iface = ""
        self.jam_iface = ""

        # Create, add and check compatibility for each interface
        for interface in pyw.winterfaces():
            try:
                self._interfaces[interface] = NetworkAdapter(interface)
            except pyric.error as e:
                pass
Esempio n. 3
0
    def __init__(self):
        """
        Setup the class with all the given arguments.

        :param self: A NetworkManager object
        :param jamming_argument: The jamming argument given by user
        :param ap_argument: The AP argument given by user
        :type self: NetworkManager
        :type jamming_argument: str
        :type ap_argument: str
        :return: None
        :rtype: None
        .. seealso:: NetworkAdapter
        """

        # Setup the fields
        self._interfaces = {}
        self.ap_iface = ""
        self.jam_iface = ""

        # Create, add and check compatibility for each interface
        for interface in pyw.winterfaces():
            try:
                self._interfaces[interface] = NetworkAdapter(interface)
            except pyric.error as e:
                pass
    def start_sniffer(self, plugins=[]):
        """
        This method starts the AirScanner sniffing service.
        """
        # Sniffing options
        if not self.air_scanner.sniffer_running:
            self.add_plugins(plugins, self.air_scanner, AirScannerPlugin)
            card = NetworkCard(
                self.configs["airscanner"]["sniffing_interface"])
            try:
                fixed_sniffing_channel = int(
                    self.configs["airscanner"]["fixed_sniffing_channel"])
                if fixed_sniffing_channel not in card.get_available_channels():
                    raise
            except:
                print "Chosen operating channel is not supported by the Wi-Fi card.\n"
                return

            sniffing_interface = self.configs["airscanner"][
                "sniffing_interface"]
            if sniffing_interface not in winterfaces():
                print "[-] sniffing_interface '{}' does not exist".format(
                    sniffing_interface)
                return

            if not self.network_manager.set_mac_and_unmanage(
                    sniffing_interface, card.get_mac(), retry=True):
                print "[-] Unable to set mac and unmanage, resetting interface and retrying."
                print "[-] Sniffer will probably crash."

            self.air_scanner.start_sniffer(sniffing_interface)

        else:
            print "[-] Sniffer already running"
Esempio n. 5
0
def change_interface():
    menu_contents = []
    interfaces = pyw.winterfaces()
    for interface in interfaces:
        menu_contents.append(
            [interface, lambda x=interface: change_current_interface(x)])
    Menu(menu_contents, i, o, "Interface change menu").activate()
Esempio n. 6
0
def get_next_name() -> str:
    name = "wlan"
    for i in range(10):
        if name + str(i) not in pyw.winterfaces():
            return name + str(i)
    else:
        raise ValueError("Couldnt find a suitable interface name")
Esempio n. 7
0
    def __init__(self, jamming_argument, ap_argument):
        """
        Setup the class with all the given arguments.

        :param self: A NetworkManager object
        :param jamming_argument: The jamming argument given by user
        :param ap_argument: The AP argument given by user
        :type self: NetworkManager
        :type jamming_argument: str
        :type ap_argument: str
        :return: None
        :rtype: None
        .. seealso:: NetworkAdapter
        """

        # Setup the fields
        self._jam_argument = jamming_argument
        self._ap_argument = ap_argument
        self._interfaces = list()

        # Get all the wireless interfaces
        wireless_interfaces = pyric.winterfaces()

        # Create, add and check compatibility for each interface
        for interface in wireless_interfaces:
            interface_object = NetworkAdapter(interface)
            self._interfaces.append(interface_object)
            self._check_compatibility(interface_object)
 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
Esempio n. 9
0
def waitfor_network_adapters(wifi_ap_blacklist=None):
    """
    Wait for at least one network adapter to be detected by the OS. Adapters that will be used for the Wifi AP will be
    ignored

    :param wifi_ap_blacklist: List of wifi adapters that will be ignored and not set to monitor mode
    """
    keep_waiting = True
    print("Waiting for wifi adapters to be detected ", end="", flush=True)
    while keep_waiting:
        winterfaces = pyw.winterfaces()

        # Remove AP and internal interfaces for GND as well as blacklisted interfaces
        for wifi_if in wifi_ap_blacklist:
            try:
                winterfaces.remove(wifi_if)
            except ValueError:
                pass

        if len(winterfaces) > 0:
            keep_waiting = False
            print("\n")
        else:
            print(".", end="", flush=True)
            time.sleep(1)
    time.sleep(2)
    def start_sniffer(self, plugins = []):
        """
        This method starts the AirScanner sniffing service.
        """
        # Sniffing options
        if not self.air_scanner.sniffer_running:
            self.add_plugins(plugins, self.air_scanner, AirScannerPlugin)
            card = NetworkCard(self.configs["airscanner"]["sniffing_interface"])
            try:
                fixed_sniffing_channel = int(self.configs["airscanner"]["fixed_sniffing_channel"])
                if fixed_sniffing_channel not in card.get_available_channels():
                    raise
            except:
                print "Chosen operating channel is not supported by the Wi-Fi card.\n"
                return

            sniffing_interface = self.configs["airscanner"]["sniffing_interface"]
            if  sniffing_interface not in winterfaces():
                print "[-] sniffing_interface '{}' does not exist".format(sniffing_interface)
                return

            if not self.network_manager.set_mac_and_unmanage(sniffing_interface, card.get_mac(), retry = True):
                print "[-] Unable to set mac and unmanage, resetting interface and retrying."
                print "[-] Sniffer will probably crash."

            self.air_scanner.start_sniffer(sniffing_interface)

        else:
            print "[-] Sniffer already running"
Esempio n. 11
0
    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
Esempio n. 12
0
    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 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 start_sniffer(self, plugins = []):
		# Sniffing options
		if not self.air_scanner.sniffer_running:
			self.add_plugins(plugins, self.air_scanner, AirScannerPlugin)

			sniff_probes = self.configs["airscanner"]["probes"].lower() == "true"
			sniff_beacons = self.configs["airscanner"]["beacons"].lower() == "true"
			hop_channels = self.configs["airscanner"]["hop_channels"].lower() == "true"
			try:
				fixed_sniffing_channel = int(self.configs["airscanner"]["fixed_sniffing_channel"])
				if fixed_sniffing_channel > 13:
					raise
			except:
				print "Channel must be an integer and below 14\n"
				return

			sniffing_interface = self.configs["airscanner"]["sniffing_interface"]
			if  sniffing_interface not in winterfaces():
				print "[-] sniffing_interface '{}' does not exist".format(sniffing_interface)
				return

			mac = self.configs["airhost"]["aplauncher"]["bssid"]

			if not self.network_manager.set_mac_and_unmanage(sniffing_interface, mac, retry = True):
				print "[-] Unable to set mac and unmanage, resetting interface and retrying."
				print "[-] Sniffer will probably crash."

			self.air_scanner.set_probe_sniffing(sniff_probes)
			self.air_scanner.set_beacon_sniffing(sniff_beacons)
			self.air_scanner.start_sniffer(sniffing_interface, hop_channels, fixed_sniffing_channel)
				
		else:
			print "[-] Sniffer already running"
    def __init__(self, networkmanager_config_path='/etc/NetworkManager/NetworkManager.conf', unmanaged_interfaces = []):
        self.interfaces = pyw.interfaces()
        self.netcards = { interface: NetworkCard(interface) for interface in pyw.winterfaces() }
        self.nm_config_file = networkmanager_config_path
        self.file_handler = None

        self.unmanaged_interfaces_setup(unmanaged_interfaces)
	def start_deauthentication_attack(self, plugins = []):
		if not self.air_deauthenticator.deauth_running:
			jamming_interface = self.configs["airdeauthor"]["jamming_interface"]
			if jamming_interface not in winterfaces():
				print "[-] jamming_interface '{}' does not exist".format(jamming_interface)
				return

			burst_count = 5
			targeted_only = False
			for arg in self.configs["airdeauthor"].keys():
				try:
					val = self.configs["airdeauthor"][arg]
					if arg == "burst_count":    burst_count = int(val)
					else:                       targeted_only = True if str(val).lower() == "true" else False
				except ValueError:
					print "[-] Burst count must be in integer form, not changing value."
				except KeyError:
					pass
		
			self.add_plugins(plugins, self.air_deauthenticator, AirDeauthorPlugin)
			self.air_deauthenticator.set_burst_count(int(burst_count))
			self.air_deauthenticator.set_targeted(targeted_only)
			self.air_deauthenticator.start_deauthentication_attack(jamming_interface)
		else:
			print "[-] Deauthentication attack still running"
Esempio n. 17
0
    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())
Esempio n. 18
0
 def __init__(self):
     self.iface = pyw.winterfaces()[0]
     self.ap = AccessPoint(self.iface)
     self.server = None
     self.ws = WebsocketClient()
     self.init_events()
     self.conn_monitor = None
     self.conn_monitor_stop = threading.Event()
Esempio n. 19
0
def callback():
    # picking a wireless interface to go with
    # needed on i.e. RPi3 to avoid the p2p-dev-wlan0 stuff
    # thanks Raspbian developers, you broke a lot of decent WiFi setup tutorials
    # even if by accident =(
    # also needed to support proper multi-interface work for the app
    global last_interface, current_interface, wifi_connect_status_cb
    winterfaces = pyw.winterfaces()
    if not winterfaces:
        Printer("No wireless cards found, exiting", i, o, 3, skippable=True)
        return
    if last_interface:
        # last_interface is only set when an interface was explicitly changed
        if last_interface in winterfaces:
            # last interface still present
            current_interface = last_interface
        else:
            # last interface no longer present, clearing it to avoid confusion
            # and picking an interface that actually exists
            last_interface = None
            current_interface = winterfaces[0]
    else:
        current_interface = winterfaces[0]  # Simple, I know
        # Might add some ZP-specific logic here later, so that
        # i.e. the ESP-12 based WiFi is guaranteed to be the first
    # clearing the connect status callback that might be left over
    # after the WiFi connect wizard
    wifi_connect_status_cb = None

    def get_contents():
        # A function for main menu to be able to dynamically update
        return [["Status", status_monitor],
                ["Current: {}".format(current_interface), change_interface],
                ["Scan", scan], ["Networks", show_scan_results],
                ["Saved networks", saved_networks]]

    # Testing if we actually can connect
    try:
        wpa_cli.set_active_interface(current_interface)
    except OSError as e:
        if e.errno == 2:
            Printer("wpa_cli not found, exiting", i, o, 3, skippable=True)
            return
        else:
            raise e
    except wpa_cli.WPAException:
        Printer(
            "Do you have wireless cards? Is wpa_supplicant running? Exiting",
            i,
            o,
            3,
            skippable=True)
        return
    else:
        start_monitor()
        Menu([], i, o, "wpa_cli main menu",
             contents_hook=get_contents).activate()
        stop_monitor()
Esempio n. 20
0
def my_wifi_module(request):
    # Create module
    module = wishful_module_wifi.WifiModule()
    wInterfaces = pyw.winterfaces()
    wInterface = wInterfaces[0]
    module.interface = wInterface
    module.wlan_interface = wInterface
    module.phy = get_device_phyid(wInterface)
    return module
Esempio n. 21
0
 def __init__(self):
     self.iface = pyw.winterfaces()[0]
     self.ap = AccessPoint(self.iface)
     self.server = None
     self.client = WebsocketClient()
     self.enclosure = EnclosureAPI(self.client)
     self.config = ConfigurationManager.get().get(self.NAME)
     self.init_events()
     self.first_setup()
Esempio n. 22
0
 def _linux_get_signals(self):
     p = PointSignals()
     for iface in pyw.winterfaces():
         for cell in Cell.all(iface):
             s = Signal(ssid=cell.ssid,
                        bssid=cell.address,
                        rssi=cell.signal)
             p.add_signal(s)
     return p
Esempio n. 23
0
def CheckInterfaces(check=1):
    if check == 1:
        if len(pyw.winterfaces()) < 2:
            return False
        else:
            return True
    elif check == 0:
        return pyw.interfaces()
    else:
        print("Error accessing interfaces.")
Esempio n. 24
0
 def __init__(self):
     self.iface = pyw.winterfaces()[0]
     self.ap = AccessPoint(self.iface)
     self.server = None
     self.ws = WebsocketClient()
     self.enclosure = EnclosureAPI(self.ws)
     self.init_events()
     self.conn_monitor = None
     self.conn_monitor_stop = threading.Event()
     self.starting = False
Esempio n. 25
0
 def __init__(self):
     self.iface = pyw.winterfaces()[0]
     self.ap = AccessPoint(self.iface)
     self.server = None
     self.ws = WebsocketClient()
     ConfigurationManager.init(self.ws)
     self.enclosure = EnclosureAPI(self.ws)
     self.init_events()
     self.conn_monitor = None
     self.conn_monitor_stop = threading.Event()
 def __init__(
         self,
         networkmanager_config_path='/etc/NetworkManager/NetworkManager.conf'
 ):
     self.interfaces = pyw.interfaces()
     self.netcards = {
         interface: NetworkCard(interface)
         for interface in pyw.winterfaces()
     }
     self.nm_config_file = networkmanager_config_path
     self.file_handler = None
Esempio n. 27
0
    def start_injection_attack(self, plugins = []):
        """Launches the AirInjector module with the specified plugins."""
        if not self.air_injector.is_running():
            injection_interface = self.configs["airinjector"]["injection_interface"]
            if injection_interface not in winterfaces():
                print "[-] Injection_interface '{}' does not exist".format(injection_interface)
                return

            self.add_plugins(plugins, self.air_injector, AirInjectorPlugin)
            self.air_injector.start_injection_attack(injection_interface)
        else:
            print "[-] Injection attack still running"
    def start_injection_attack(self, plugins = []):
        """Launches the AirInjector module with the specified plugins."""
        if not self.air_injector.is_running():
            injection_interface = self.configs["airinjector"]["injection_interface"]
            if injection_interface not in winterfaces():
                print "[-] Injection_interface '{}' does not exist".format(injection_interface)
                return

            self.add_plugins(plugins, self.air_injector, AirInjectorPlugin)
            self.air_injector.start_injection_attack(injection_interface)
        else:
            print "[-] Injection attack still running"
Esempio n. 29
0
def main():
    interface_name_list = []
    config_file = "/opt/geofrenzy/etc/gfiwscan.yaml"
    parser = argparse.ArgumentParser()
    #    parser.add_argument("wireless_interface")
    args = parser.parse_args()
    with open(config_file, 'r') as f:
        doc = yaml.load(f)
    ignorelist = doc['ignore']
    pprint.pprint(pyw.winterfaces())
    for winterface in pyw.winterfaces():
        print winterface
        dev_dict = pyw.devinfo(winterface)
        if dev_dict["mac"] in ignorelist:
            print "ignoring " + winterface + " with mac " + dev_dict["mac"]
        else:
            interface_name_list.append(winterface)
    for interface_name in interface_name_list:
        p = Process(target=interface_handler, args=(interface_name, ))
        p.start()
        cardprocesslist.append(p)
    pprint.pprint(cardprocesslist)
    def get_netcard(self, interface):
        netcard = None
        try:
            try:
                netcard = self.netcards[interface]
            except KeyError:
                # Check if it was plugged in at runtime
                self.netcards = { interface: NetworkCard(interface) for interface in pyw.winterfaces() }
                netcard = self.netcards[interface]
        except KeyError:
            print "[-] Interface: '{}' does not exist".format(interface)
            return None

        return netcard
Esempio n. 31
0
 def post_start(self):
     # Wait for hostapd to setup all the access points
     sleep(1)
     card = NetworkCard(self.ap_interface)
     if card is not None:
         gateway = card.get_ip()
         for i in range(self.number_of_configured_nets - 1):
             interface_name = "{}_{}".format(self.ap_interface, i)
             if interface_name in pyw.winterfaces():
                 gateway = ".".join(gateway.split(".")[0:2] + [str(int(gateway.split(".")[2]) + 1)] + [gateway.split(".")[3]])
                 NetUtils().interface_config(interface_name, card.get_ip())
                 NetUtils().set_interface_mtu(interface_name, 1800)
                 NetUtils().accept_forwarding(interface_name)
     self.dnsmasqhandler.start_dnsmasq()
Esempio n. 32
0
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)
Esempio n. 33
0
def interface_command(interface, verbose):
    faces = pyw.winterfaces() if interface == "all" else [interface]
    for face in faces:
        if face not in pyw.winterfaces():
            sys.exit(f"{face} is not an interface")

    print(f"{Fore.GREEN}Interfaces:{Fore.YELLOW}")
    for interface in faces:
        face = pyw.getcard(interface)
        up = Fore.YELLOW if pyw.isup(face) else Fore.RED

        print(f"  {up}{interface:<10} {Style.RESET_ALL}")
        if verbose >= 1:
            iinfo = pyw.ifinfo(face)
            for i in iinfo:
                print(
                    f"\t{i.title():<15} {Fore.CYAN}{iinfo[i]}{Style.RESET_ALL}"
                )
        if verbose >= 2:
            dinfo = pyw.devinfo(face)
            for d in dinfo:
                print(
                    f"\t{d.title():<15} {Fore.CYAN}{dinfo[d]}{Style.RESET_ALL}"
                )

        if verbose >= 3:
            pinfo = pyw.phyinfo(face)
            for p in pinfo:
                if type(pinfo[p]) == list:
                    print(
                        f"\t{p.title():<15} {Fore.CYAN}{', '.join(pinfo[p])}{Style.RESET_ALL}"
                    )
                elif p == "bands":
                    print(
                        f"\t{p.title():<15} {Fore.CYAN}{', '.join(pinfo[p].keys())}{Style.RESET_ALL}"
                    )
Esempio n. 34
0
 def get_wifi_interfaces(self):
     try:
         self.wifi_interfaces = pyw.winterfaces()
         print(self.wifi_interfaces)
         if self.wifi_interfaces.__len__()>=2:
             self.attack_interface = self.wifi_interfaces[1]
             self.scan_interface = self.wifi_interfaces[0]
         elif self.wifi_interfaces.__len__()==1:
             self.attack_interface = self.wifi_interfaces[0]
             self.scan_interface = self.wifi_interfaces[0]
         else :
             exit("No wifi interfaces available")
         #print(self.scan_interface,self.attack_interface)
     except pyric.error as e:
         print("Error {}".format(e))
     return self
Esempio n. 35
0
    def getLocation(self):
        """
        Get location from Wlan and WifiAccessPoints for Mozilla Location Services
        """
        postdata = {}
        ifaces = []
        flbmode = {"lacf": "false", "ipf": "true"}
        postdata['fallbacks'] = flbmode
        postdata['wifiAccessPoints'] = ifaces
        wintf = pyw.winterfaces()
        selectintf = wintf[0]
        setwintf = 'iwlist {0} scan'.format(selectintf)
        wlist = subprocess.Popen([setwintf],
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE,
                                 bufsize=1,
                                 universal_newlines=True,
                                 shell=True)

        for line in wlist.stdout:
            if "Address" in line:
                iface = {}
                key = line.split('Address: ')[1].strip()
                iface['macAddress'] = key
                ifaces.append(iface)
            if "dBm" in line:
                signal = line.split('level=')[1].strip().replace(' dBm', '')
                iface['signalStrength'] = int(signal)
            if "ESSID" in line:
                essid = line.split(':')[1].strip().replace('"', '')
            if "Frequency" in line:
                frequencyStr = line.split(':')[1].split(' GHz')[0]
                frequency = int(float(frequencyStr) * 1000)
                #channel = int(line.split('(Channel ')[1].replace(')',''))
                #iface['channel'] = channel
                iface['frequency'] = frequency

        postdata['wifiAccessPoints'].sort(key=lambda x: x['signalStrength'],
                                          reverse=True)

        del postdata['wifiAccessPoints'][5:]

        url = 'https://location.services.mozilla.com/v1/geolocate?key=test'
        r = requests.post(url, data=json.dumps(postdata))
        getlocresult = json.loads(r.text)

        return getlocresult
    def get_netcard(self, interface):
        netcard = None
        try:
            try:
                netcard = self.netcards[interface]
            except KeyError:
                # Check if it was plugged in at runtime
                self.netcards = {
                    interface: NetworkCard(interface)
                    for interface in pyw.winterfaces()
                }
                netcard = self.netcards[interface]
        except KeyError:
            print "[-] Interface: '{}' does not exist".format(interface)
            return None

        return netcard
Esempio n. 37
0
    def _update_connected_clients(self, interface):
        fail_count = 0
        while self.ap_running:
            # Gets virtual interfaces too because their name is same as ap_interface with _<index> appended
            ap_interfaces = [iface for iface in pyw.winterfaces() if interface in iface]
            for ap_interface in ap_interfaces:
                if not self._parse_connected_clients(ap_interface):
                    fail_count += 1

                if fail_count > 5:
                    print "[-] hostapd was unable to start the access point,"
                    print "check configuration file or try restarting. Stopping now."
                    self.stop_access_point(wait = False)
                    print "stop airhost manually to stop other services"
                    break

            sleep(3)
Esempio n. 38
0
 def post_start(self):
     # Wait for hostapd to setup all the access points
     sleep(1)
     card = NetworkCard(self.ap_interface)
     if card is not None:
         gateway = card.get_ip()
         for i in range(self.number_of_configured_nets - 1):
             interface_name = "{}_{}".format(self.ap_interface, i)
             if interface_name in pyw.winterfaces():
                 gateway = ".".join(
                     gateway.split(".")[0:2] +
                     [str(int(gateway.split(".")[2]) + 1)] +
                     [gateway.split(".")[3]])
                 NetUtils().interface_config(interface_name, card.get_ip())
                 NetUtils().set_interface_mtu(interface_name, 1800)
                 NetUtils().accept_forwarding(interface_name)
     self.dnsmasqhandler.start_dnsmasq()
Esempio n. 39
0
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
Esempio n. 40
0
 def get_iface(self):
     for iface in pyw.winterfaces():
         if "p2p" in iface:
             return iface
Esempio n. 41
0
 def test_enumwinterfaces(self):
     for wnic in wnics: self.assertTrue(wnic in pyw.winterfaces())
    def start_access_point(self, plugins = []):
        """This method starts the access point with hostapd while also avoiding conflicts with NetworkManager."""
        # Start by getting all the info from the configuration file
        try:
            ap_interface = self.configs["airhost"]["ap_interface"]
            internet_interface = self.configs["airhost"]["internet_interface"]
            gateway = self.configs["airhost"]["dnsmasqhandler"]["gateway"]
            dhcp_range = self.configs["airhost"]["dnsmasqhandler"]["dhcp_range"]
            ssid = self.configs["airhost"]["aplauncher"]["ssid"]
            bssid = self.configs["airhost"]["aplauncher"]["bssid"]
            channel = self.configs["airhost"]["aplauncher"]["channel"]
            hw_mode = self.configs["airhost"]["aplauncher"]["hw_mode"]
            dns_servers = self.configs["airhost"]["dnsmasqhandler"]["dns_server"]
        except KeyError as e:
            print "[-] Unable to start Access Point, too few configurations"
            return False

        if  ap_interface not in winterfaces():
            print "[-] ap_interface '{}' does not exist".format(ap_interface)
            return False

        if internet_interface not in interfaces():
            print "[-] internet_interface '{}' does not exist".format(internet_interface)
            return False

        necessary_interfaces = [internet_interface, ap_interface]

        # Check if another service is using our interfaces.
        if self.air_injector.is_running() and \
           self.air_injector.injection_interface in necessary_interfaces:
            print "[-] AirInjector is using a needed interface."
            return False

        if self.air_scanner.is_running() and \
           self.air_scanner.running_interface in necessary_interfaces:
            print "[-] AirScanner using a needed interface."
            return False

        # Add plugins
        self.add_plugins(plugins, self.air_host, AirHostPlugin)

        # NetworkManager setup
        is_catch_all_honeypot   = self.configs["airhost"]["aplauncher"]["catch_all_honeypot"].lower() == "true"
        is_multiple_ssid        = type(ssid) is list
        nVirtInterfaces         = 3             if is_catch_all_honeypot else \
                                  len(ssid) - 1 if is_multiple_ssid else \
                                  0

        if self.network_manager.set_mac_and_unmanage(   ap_interface, bssid,
                                                        retry = True,
                                                        virtInterfaces = nVirtInterfaces):

            # Initial configuration
            self.network_manager.configure_interface(ap_interface, gateway)
            self.network_manager.iptables_redirect(ap_interface, internet_interface)

            # dnsmasq and hostapd setup
            try:
                captive_portal_mode = self.configs["airhost"]["dnsmasqhandler"]["captive_portal_mode"].lower() == "true"
            except KeyError:
                captive_portal_mode = False

            self.air_host.dnsmasqhandler.set_captive_portal_mode(captive_portal_mode)
            self.air_host.dnsmasqhandler.write_dnsmasq_configurations(  ap_interface, gateway, dhcp_range, dns_servers,
                                                                        nVirtInterfaces)
            try:
                self.air_host.aplauncher.write_hostapd_configurations(
                    interface=ap_interface, ssid=ssid, bssid=bssid, channel=channel, hw_mode=hw_mode,
                    encryption=self.configs["airhost"]["aplauncher"]["encryption"],
                    auth=self.configs["airhost"]["aplauncher"]["auth"],
                    cipher=self.configs["airhost"]["aplauncher"]["cipher"],
                    password=self.configs["airhost"]["aplauncher"]["password"],
                    catch_all_honeypot=is_catch_all_honeypot)
            except KeyError:
                self.air_host.aplauncher.write_hostapd_configurations(
                    interface=ap_interface, ssid=ssid, bssid=bssid, channel=channel, hw_mode=hw_mode)
            except Exception as e:
                print e
                return

            # Start services
            print_creds = self.configs["airhost"]["aplauncher"]["print_creds"].lower() == "true"
            success = self.air_host.start_access_point( ap_interface,
                                                        print_creds)

            if success:
                # Configure Virtual Interfaces once hostapd has set them up
                sleep(.5)  # Wait for for hostapd to setup interfaces
                extra_interfaces = False
                for i in range(nVirtInterfaces):
                    interface_name = "{}_{}".format(ap_interface, i)
                    if interface_name in winterfaces():
                        gateway = ".".join(gateway.split(".")[0:2] + [str(int(gateway.split(".")[2]) + 1)] + [gateway.split(".")[3]])
                        self.network_manager.configure_interface(interface_name, gateway)
                        self.network_manager.iptables_redirect(interface_name, internet_interface)
                        extra_interfaces = True

                # Needed for dnsmasq to work correctly with virtual interfaces once they are configured
                if extra_interfaces:
                    self.air_host.dnsmasqhandler.start_dnsmasq()

            return True

        print dedent("""
                    [-] Errors occurred while trying to start access point,
                    try restarting network services and unplug your network adapter""")
        return False
Esempio n. 43
0
 def test_iswinterface(self):
     for wnic in pyw.winterfaces(): self.assertTrue(pyw.iswireless(wnic))
Esempio n. 44
0
 def test_inwinterfaces(self):
     for wnic in pyw.winterfaces(): self.assertIn(wnic,pyw.winterfaces())
Esempio n. 45
0
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")
Esempio n. 46
0
def execute(dev,itype):
    # ensure dev is a wireless interfaces
    wifaces = pyw.winterfaces()
    if dev not in wifaces:
        print("Device {0} is not wireless, use one of {1}".format(dev,wifaces))

    # get info dicts
    dinfo = pyw.devinfo(dev)
    card = dinfo['card']
    pinfo = pyw.phyinfo(card)
    iinfo = pyw.ifinfo(card)

    if itype == 'all' or itype == 'if':
        msg = "Interface {0}\n".format(card.idx)
        msg += "\tDriver: {0} Chipset: {1}\n".format(iinfo['driver'],iinfo['chipset'])
        msg += "\tHW Addr: {0} Manufacturer: {1}\n".format(iinfo['hwaddr'],
                                                           iinfo['manufacturer'])
        msg += "\tInet: {0} Bcast: {1} Mask: {2}\n".format(iinfo['inet'],
                                                           iinfo['bcast'],
                                                           iinfo['mask'])
        print(msg)

    if itype == 'all' or itype == 'dev':
        msg = "Device {0}\n".format(card.dev)
        msg += "\tifindex: {0}\n".format(card.idx)
        msg += "\twdev: {0}\n".format(dinfo['wdev'])
        msg += "\taddr: {0}\n".format(dinfo['mac'])
        msg += "\tmode: {0}\n".format(dinfo['mode'])
        msg += "\twiphy: {0}\n".format(card.phy)
        if dinfo['mode'] != 'managed': msg += "\tDevice not associated\n"
        else:
            msg += "\tchannel: {0} ({1} MHz), width: {2}, CF: {3} MHz\n".format(rf2ch(dinfo['RF']),
                                                                                dinfo['RF'],
                                                                                dinfo['CHW'],
                                                                                dinfo['CF'])
        print(msg)

    if itype == 'all' or itype == 'phy':
        msg = "Wiphy phy{0}\n".format(card.phy)
        msg += "\tGeneration: {0}m Coverage Class: {1}\n".format(pinfo['generation'],
                                                                 pinfo['cov_class'])
        msg += "\tMax # scan SSIDs: {0}\n".format(pinfo['scan_ssids'])
        msg += "\tRetry Short: {0}, Long: {1}\n".format(pinfo['retry_short'],
                                                        pinfo['retry_long'])
        msg += "\tThreshold Frag: {0}, RTS: {1}\n".format(pinfo['frag_thresh'],
                                                          pinfo['rts_thresh'])
        msg += "\tSupported Modes:\n"
        for mode in pinfo['modes']: msg += "\t  * {0}\n".format(mode)
        msg += "\tSupported Commands:\n"
        for cmd in pinfo['commands']: msg += "\t  * {0}\n".format(cmd)
        msg += "\tSupported Ciphers:\n"
        for cipher in pinfo['ciphers']: msg += "\t  * {0}\n".format(cipher)
        for band in pinfo['bands']:
            msg += "\tBand {0}: (HT: {1} VHT: {2})\n".format(band,
                                                             pinfo['bands'][band]['HT'],
                                                             pinfo['bands'][band]['VHT'])
            msg += "\t   Rates:\n"
            for rate in pinfo['bands'][band]['rates']:
                msg += "\t    * {0} Mbps\n".format(rate)
            msg += "\t   Frequencies:\n"
            for i,rf in enumerate(pinfo['bands'][band]['rfs']):
                dbm = pinfo['bands'][band]['rf-data'][i]['max-tx']
                msg += "\t    * {0} MHz ({1} dBm)".format(rf,dbm)
                if not pinfo['bands'][band]['rf-data'][i]['enabled']:
                    msg += " (disabled)\n"
                else:
                    msg += "\n"
        print(msg)
Esempio n. 47
0
def skip_if_no_wifi_devices():
    wInterfaces = pyw.winterfaces()  # get all system wireless interfaces
    if len(wInterfaces) == 0:
        return True
    else:
        return False
Esempio n. 48
0
argp.add_argument('-d','--dev',help="Wireless Monitor Device")
argp.add_argument('-s','--ssid',help="SSID", default="")
argp.add_argument('-v','--verbose',help="Verbose mode")
argp.add_argument('-c','--cs_timer',help="Channel switch timer in ms", default=250)
argp.add_argument('-o','--output_timer',help="Output timer for aggregated data", default=5000)
args = argp.parse_args()

if not args.dev:
    argp.print_help()
    exit()


########################## WiFi initalization and sanity checks ########################################################


wifaces = pyw.winterfaces()
if args.dev not in wifaces:
    print "Device {0} is not wireless, use one of {1}".format(args.dev, wifaces)
    exit()


dev = pyw.devinfo(args.dev)

if args.verbose:
    print args
    print dev


if dev['mode'] != "monitor":
    print "Interface {0} is not in monitor mode".format(args.dev)
    exit()
 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)