コード例 #1
0
ファイル: interfaces.py プロジェクト: Droid-MAX/wifiphisher
    def __init__(self, name):
        """
        Setup the class with all the given arguments.

        :param self: A NetworkAdapter object
        :param name: Name of the interface
        :type self: NetworkAdapter
        :type name: str
        :return: None
        :rtype: None
        .. note: the availability of monitor mode and AP mode is set to False
            by default
        """

        # Setup the fields
        self._name = name
        self._support_ap_mode = False
        self._support_monitor_mode = False
        self.being_used = False

        # Set monitor and AP mode if card supports it
        card = pyw.getcard(name)
        modes = pyw.devmodes(card)

        if "monitor" in modes:
            self._support_monitor_mode = True
        if "AP" in modes:
            self._support_ap_mode = True
コード例 #2
0
ファイル: networking.py プロジェクト: wifiace/wifiace
    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
コード例 #3
0
ファイル: interfaces.py プロジェクト: yeraldinm/wifiphisher
    def __init__(self, name):
        """
        Setup the class with all the given arguments.

        :param self: A NetworkAdapter object
        :param name: Name of the interface
        :type self: NetworkAdapter
        :type name: str
        :return: None
        :rtype: None
        .. note: the availability of monitor mode and AP mode is set to False
            by default
        """

        # Setup the fields
        self._name = name
        self._support_ap_mode = False
        self._support_monitor_mode = False
        self.being_used = False

        # Set monitor and AP mode if card supports it
        card = pyw.getcard(name)
        modes = pyw.devmodes(card)

        if "monitor" in modes:
            self._support_monitor_mode = True
        if "AP" in modes:
            self._support_ap_mode = True
コード例 #4
0
    def __init__(self, interface):

        self.interface = interface
        self.card = pyw.getcard(interface)
        self.modes = pyw.devmodes(self.card)
        self.original_mac = pyw.macget(self.card)

        # Important capabilities
        self._ap_mode_support = "AP" in self.modes
        self._monitor_mode_support = "monitor" in self.modes
コード例 #5
0
    def __init__(self, interface):

        self.interface = interface
        self.card = pyw.getcard(interface)
        self.modes = pyw.devmodes(self.card)
        self.original_mac = pyw.macget(self.card)

        # Important capabilities
        self._ap_mode_support = "AP" in self.modes
        self._monitor_mode_support = "monitor" in self.modes
        self._number_of_supported_aps = None
        self._is_managed = False
コード例 #6
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())
コード例 #7
0
    def monitor_interfaces(self):
        """Get a list of interfaces that support monitor mode"""

        # Get a list of all the interfaces.
        ret = []
        for iface in pyw.interfaces():
            # Check if this card support monitor mode
            try:
                card = pyw.getcard(iface)
                if 'monitor' in pyw.devmodes(card) and 'mon0' != card.dev:
                    # Add the card to the list
                    ret.append(iface)
            except pyric.error as e:
                pass

        # Return the collected list
        return ret
コード例 #8
0
    def set_scan_adapter(self, value):
        """ wireless adapter being used to scan / inject """
        if value:
            value = value.encode('ascii')
        else:
            value = None

        if value and pyw.isinterface(value):
            card = pyw.getcard(value)
            if 'monitor' not in pyw.devmodes(card):
                raise Exception(
                    "Error, adapter: {} cannot perform monitor mode".format(
                        value))
        elif value:
            LOG.error("Invalid Card detected: {}, saving None to config")
            value = None
        config = cfg.get_config()
        config[cfg.FIELD_ADAPTER_SCAN] = value
        cfg.write_config(config)
コード例 #9
0
ファイル: interfaces.py プロジェクト: yehias/wifiphisher
def interface_property_detector(network_adapter):
    """
    Add appropriate properties of the interface such as supported modes
    and wireless type(wireless)

    :param network_adapter: A NetworkAdapter object
    :type interface_name: NetworkAdapter
    :return: None
    :rtype: None
    """

    supported_modes = pyw.devmodes(network_adapter.card)

    # check for monitor, AP and wireless mode support
    if "monitor" in supported_modes:
        network_adapter.has_monitor_mode = True
    if "AP" in supported_modes:
        network_adapter.has_ap_mode = True
    if pyw.iswireless(network_adapter.name):
        network_adapter.is_wireless = True
コード例 #10
0
def interface_property_detector(network_adapter):
    """
    Add appropriate properties of the interface such as supported modes
    and wireless type(wireless)

    :param network_adapter: A NetworkAdapter object
    :type interface_name: NetworkAdapter
    :return: None
    :rtype: None
    """

    supported_modes = pyw.devmodes(network_adapter.card)

    # check for monitor, AP and wireless mode support
    if "monitor" in supported_modes:
        network_adapter.has_monitor_mode = True
    if "AP" in supported_modes:
        network_adapter.has_ap_mode = True

    interface_name = network_adapter.name
    network_adapter.is_managed_by_nm = is_managed_by_network_manager(interface_name)
コード例 #11
0
    def __init__(self, interface):

        self.interface = interface
        self.card = None
        self.modes = None
        self.original_mac = None
        self._ap_mode_support = None
        self._monitor_mode_support = None

        try:
            self.card = pyw.getcard(interface)
            self.modes = pyw.devmodes(self.card)
            self.original_mac = pyw.macget(self.card)

            # Important capabilities
            self._ap_mode_support = "AP" in self.modes
            self._monitor_mode_support = "monitor" in self.modes
        except: pass

        self._number_of_supported_aps = None
        self._is_managed = False
コード例 #12
0
ファイル: networking.py プロジェクト: wifiace/wifiace
    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
コード例 #13
0
def show_networking():
    # auto load mymons.
    Global.monCtrl.autoLoadMymons()

    kroute = Wired.getRoute()

    wirelessInfo = []
    for w in Wireless.listInterfaces():
        info = Wireless.getInfo(w)
        c = pyw.getcard(w)

        if "monitor" in pyw.devmodes(c):
            info["inUsed"] = Global.monCtrl.isMymon(c)

        info["priority"] = Global.monCtrl.usedAs(c)
        wirelessInfo.append(info)

    wiredInfo = []
    for w in Wired.listInterfaces():
        wiredInfo.append(Wired.getInfo(w))

    return render_template("networking.html", kroute=kroute, wiredInfo=wiredInfo, wirelessInfo=wirelessInfo)
コード例 #14
0
    def _check_compatibility(self, interface):
        """
        Check and set the compatibility of the network adapter in regards to
        monitor mode and AP mode.

        :param self: A NetworkManager object
        :param interface: A network adapter to be checked
        :type self: NetworkManager
        :type interface: NetworkAdapter
        :return: None
        :rtype: None
        :raises IwCmdError: If an error is produced after executing iw command
        .. seealso:: _iw_cmd, _word_in_sentence, NetworkAdapter
        """

        # Set monitor and AP mode if card supports it
        card = pyric.getcard(interface.get_name())
        modes = pyric.devmodes(card)

        if "monitor" in modes:
            interface.set_monitor_support(True)
        if "AP" in modes:
            interface.set_ap_support(True)
コード例 #15
0
ファイル: captiv.py プロジェクト: wraith-wireless/captiv8
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
コード例 #16
0
def is_add_vif_required(args):
    """
    Return the card if only that card support both monitor and ap
    :param args: Arguemnt from pywifiphisher
    :type args: parse.args
    :return: tuple of card and is_frequency_hop_allowed
    :rtype: tuple
    """

    def get_perfect_card(phy_map_vifs, vif_score_tups):
        """
        Get the perfect card that both supports ap and monitor when we
        have only one phy interface can do that
        :param phy_map_vifs: phy number maps to the virtual interfaces
        :param vif_score_tups: list of tuple containing card and score
        :type phy_map_vifs: dict
        :type vif_score_tups: list
        :return tuple of card and single_perfect_phy_case
        :rtype: tuple
        """
        # case 1 : one phy maps to one virtual interface
        if len(phy_map_vifs) == 1 and len(phy_map_vifs.values()[0]) == 1:
            # only take the first tuple
            vif_score_tuple = vif_score_tups[0]
            card = vif_score_tuple[0]
            score = vif_score_tuple[1]
            # if this card support both monitor and AP mode
            if score == 2:
                return card, True
        # case 2 : one phy maps to multiple virtual interfaces
        # we don't need to create one more virtual interface in this case
        elif len(phy_map_vifs) == 1 and len(phy_map_vifs.values()[0]) > 1:
            return None, True
        # case 3 : we have multiple phy interfaces but only
        # one card support both monitor and AP and the other
        # ones just support the managed mode only
        elif len(phy_map_vifs) > 1:
            if vif_score_tups[0][1] == 2 and vif_score_tups[1][1] == 0:
                return vif_score_tups[0][0], True
        return None, False

    # map the phy interface to virtual interfaces
    # i.e. phy0 to wlan0
    phy_to_vifs = defaultdict(list)
    # store the phy number for the internet access
    invalid_phy_number = list()
    # record the invalid_phy_number when it is wireless card
    if args.internetinterface and pyw.iswireless(args.internetinterface):
        card = pyw.getcard(args.internetinterface)
        invalid_phy_number.append(card.phy)

    if args.wpspbc_assoc_interface:
        card = pyw.getcard(args.wpspbc_assoc_interface)
        invalid_phy_number.append(card.phy)

    # map the phy# to the virtual interface tuples
    for vif in [vif for vif in pyw.interfaces() if pyw.iswireless(vif)]:
        # excluding the card that used for internet accessing
        # setup basic card information
        score = 0
        card = pyw.getcard(vif)
        phy_number = card.phy
        if phy_number in invalid_phy_number:
            continue

        supported_modes = pyw.devmodes(card)

        if "monitor" in supported_modes:
            score += 1
        if "AP" in supported_modes:
            score += 1

        phy_to_vifs[phy_number].append((card, score))

    # each phy number map to a sublist containing (card, score)
    vif_score_tuples = [sublist[0] for sublist in phy_to_vifs.values()]
    # sort with score
    vif_score_tuples = sorted(vif_score_tuples, key=lambda tup: -tup[1])

    use_one_phy = False
    if args.interface:
        card = pyw.getcard(args.interface)
        phy_number = card.phy
        if phy_to_vifs[card.phy][0][1] == 2:
            perfect_card = card
            use_one_phy = True
    else:
        perfect_card, use_one_phy = get_perfect_card(
            phy_to_vifs, vif_score_tuples)

    return perfect_card, use_one_phy
コード例 #17
0
ファイル: pyw.unittest.py プロジェクト: wifiphisher/WiPy
 def test_devcmds(self):
     self.assertIsInstance(pyw.devmodes(self.card), list)
コード例 #18
0
ファイル: pyw.unittest.py プロジェクト: wifiphisher/WiPy
 def test_devmodes(self):
     self.assertListEqual(pri["modes"], pyw.devmodes(self.card))
コード例 #19
0
ファイル: pyw.unittest.py プロジェクト: wraith-wireless/PyRIC
 def test_devmodes(self):
     self.assertListEqual(pri['modes'],pyw.devmodes(self.card))
コード例 #20
0
ファイル: pyw.unittest.py プロジェクト: pgawlowicz/PyRIC
 def test_devcmds(self):
     self.assertIsInstance(pyw.devmodes(self.card),list)
コード例 #21
0
def is_add_vif_required(args):
    """
    Return the card if only that card support both monitor and ap
    :param args: Arguemnt from pywifiphisher
    :type args: parse.args
    :return: tuple of card and is_frequency_hop_allowed
    :rtype: tuple
    """

    def get_perfect_card(phy_map_vifs, vif_score_tups):
        """
        Get the perfect card that both supports ap and monitor when we
        have only one phy interface can do that
        :param phy_map_vifs: phy number maps to the virtual interfaces
        :param vif_score_tups: list of tuple containing card and score
        :type phy_map_vifs: dict
        :type vif_score_tups: list
        :return tuple of card and single_perfect_phy_case
        :rtype: tuple
        """
        # case 1 : one phy maps to one virtual interface
        if len(phy_map_vifs) == 1 and len(phy_map_vifs.values()[0]) == 1:
            # only take the first tuple
            vif_score_tuple = vif_score_tups[0]
            card = vif_score_tuple[0]
            score = vif_score_tuple[1]
            # if this card support both monitor and AP mode
            if score == 2:
                return card, True
        # case 2 : one phy maps to multiple virtual interfaces
        # we don't need to create one more virtual interface in this case
        elif len(phy_map_vifs) == 1 and len(phy_map_vifs.values()[0]) > 1:
            return None, True
        # case 3 : we have multiple phy interfaces but only
        # one card support both monitor and AP and the other
        # ones just support the managed mode only
        elif len(phy_map_vifs) > 1:
            if vif_score_tups[0][1] == 2 and vif_score_tups[1][1] == 0:
                return vif_score_tups[0][0], True
        return None, False

    # map the phy interface to virtual interfaces
    # i.e. phy0 to wlan0
    phy_to_vifs = defaultdict(list)
    # store the phy number for the internet access
    invalid_phy_number = None
    # record the invalid_phy_number when it is wireless card
    if args.internetinterface and pyw.iswireless(args.internetinterface):
        card = pyw.getcard(args.internetinterface)
        invalid_phy_number = card.phy

    # map the phy# to the virtual interface tuples
    for vif in [vif for vif in pyw.interfaces() if pyw.iswireless(vif)]:
        # excluding the card that used for internet accessing
        # setup basic card information
        score = 0
        card = pyw.getcard(vif)
        phy_number = card.phy
        if phy_number == invalid_phy_number:
            continue

        supported_modes = pyw.devmodes(card)

        if "monitor" in supported_modes:
            score += 1
        if "AP" in supported_modes:
            score += 1

        phy_to_vifs[phy_number].append((card, score))

    # each phy number map to a sublist containing (card, score)
    vif_score_tuples = [sublist[0] for sublist in phy_to_vifs.values()]
    # sort with score
    vif_score_tuples = sorted(vif_score_tuples, key=lambda tup: -tup[1])

    perfect_card, is_single_perfect_phy = get_perfect_card(phy_to_vifs,
                                                           vif_score_tuples)

    return perfect_card, is_single_perfect_phy
コード例 #22
0
ファイル: pyw.unittest.py プロジェクト: pgawlowicz/PyRIC
 def test_devmodes(self):
     self.assertIn('managed',pyw.devmodes(self.card))
コード例 #23
0
    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