Move Ifconfig and Iwconfig logic to separate classes.

This commit is contained in:
derv82
2018-04-18 06:15:14 -04:00
parent bd13bf69cf
commit 3542381b3e
7 changed files with 147 additions and 75 deletions

View File

@@ -100,11 +100,11 @@ class Configuration(object):
Configuration.load_from_arguments() Configuration.load_from_arguments()
if load_interface: if load_interface:
Configuration.get_interface() Configuration.get_monitor_mode_interface()
@staticmethod @staticmethod
def get_interface(): def get_monitor_mode_interface():
if Configuration.interface is None: if Configuration.interface is None:
# Interface wasn't defined, select it! # Interface wasn't defined, select it!
from .tools.airmon import Airmon from .tools.airmon import Airmon
@@ -112,6 +112,9 @@ class Configuration(object):
if Configuration.random_mac: if Configuration.random_mac:
Macchanger.random() Macchanger.random()
@staticmethod
def get_wireless_interface():
pass
@staticmethod @staticmethod
def load_from_arguments(): def load_from_arguments():

View File

@@ -1,6 +1,7 @@
#!/usr/bin/python2.7 #!/usr/bin/python2.7
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from ..tools.ifconfig import Ifconfig
from ..util.color import Color from ..util.color import Color
import re import re
@@ -10,13 +11,6 @@ class Interface(object):
Represents an 'interface' known by airmon-ng Represents an 'interface' known by airmon-ng
''' '''
# Max length of fields.
# Used for printing a table of interfaces.
PHY_LEN = 6
NAME_LEN = 12
DRIVER_LEN = 20
CHIPSET_LEN = 30
def __init__(self, fields): def __init__(self, fields):
''' '''
Initializes & stores info about an interface. Initializes & stores info about an interface.
@@ -24,7 +18,7 @@ class Interface(object):
Args: Args:
Fields - list of fields Fields - list of fields
0: PHY 0: PHY
1: NAME 1: INTERFACE
2: DRIVER 2: DRIVER
3: CHIPSET 3: CHIPSET
''' '''
@@ -38,42 +32,35 @@ class Interface(object):
if len(fields) != 4: if len(fields) != 4:
raise Exception("Expected 4, got %d in %s" % (len(fields), fields)) raise Exception("Expected 4, got %d in %s" % (len(fields), fields))
self.phy = fields[0].strip() self.phy = fields[0].strip()
self.name = fields[1].strip() self.interface = fields[1].strip()
self.driver = fields[2].strip() self.driver = fields[2].strip()
self.chipset = fields[3].strip() self.chipset = fields[3].strip()
# Max length of fields.
# Used for printing a table of interfaces.
PHY_LEN = 6
INTERFACE_LEN = 12
DRIVER_LEN = 20
CHIPSET_LEN = 30
def __str__(self): def __str__(self):
''' Colored string representation of interface ''' ''' Colored string representation of interface '''
s = Color.s("{W}%s" % self.phy) s = Color.s('{W}%s' % self.phy.ljust(self.PHY_LEN))
s += ' ' * max(Interface.PHY_LEN - len(self.phy), 0) s += Color.s('{G}%s' % self.interface.ljust(self.INTERFACE_LEN))
s += Color.s('{C}%s' % self.driver.ljust(self.DRIVER_LEN))
s += Color.s("{G}%s" % self.name) s += Color.s('{W}%s' % self.chipset.ljust(self.CHIPSET_LEN))
s += ' ' * max(Interface.NAME_LEN - len(self.name), 0)
s += Color.s("{C}%s" % self.driver)
s += ' ' * max(Interface.DRIVER_LEN - len(self.driver), 0)
s += Color.s("{W}%s" % self.chipset)
s += ' ' * max(Interface.CHIPSET_LEN - len(self.chipset), 0)
return s return s
@staticmethod @staticmethod
def menu_header(): def menu_header():
''' Colored header row for interfaces ''' ''' Colored header row for interfaces '''
s = ' ' s = ' '
s += 'PHY' s += 'PHY'.ljust(Interface.PHY_LEN)
s += ' ' * (Interface.PHY_LEN - len("PHY")) s += 'Interface'.ljust(Interface.INTERFACE_LEN)
s += 'Driver'.ljust(Interface.DRIVER_LEN)
s += 'Interface' s += 'Chipset'.ljust(Interface.CHIPSET_LEN)
s += ' ' * (Interface.NAME_LEN - len("Interface")) s += '\n'
s += 'Driver' s += '-' * (Interface.PHY_LEN + Interface.INTERFACE_LEN + Interface.DRIVER_LEN + Interface.CHIPSET_LEN + 3)
s += ' ' * (Interface.DRIVER_LEN - len("Driver"))
s += 'Chipset'
s += ' ' * (Interface.CHIPSET_LEN - len("Chipset"))
s += '\n---'
s += '-' * (Interface.PHY_LEN + Interface.NAME_LEN + Interface.DRIVER_LEN + Interface.CHIPSET_LEN)
return s return s
@staticmethod @staticmethod
@@ -87,14 +74,7 @@ class Interface(object):
if iface is None: if iface is None:
raise Exception('Interface must be defined (-i)') raise Exception('Interface must be defined (-i)')
output = Process(['ifconfig', iface]).stdout() Ifconfig.get_mac(iface)
mac_regex = ('[a-zA-Z0-9]{2}-' * 6)[:-1]
match = re.search(' (%s)' % mac_regex, output)
if not match:
match = re.search('unspec (%s)' % mac_regex, output)
if not match:
raise Exception('Could not find the mac address for %s' % iface)
return match.groups()[0].replace('-', ':')
if __name__ == '__main__': if __name__ == '__main__':
mac = Interface.get_mac() mac = Interface.get_mac()

View File

@@ -2,6 +2,8 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from ..model.interface import Interface from ..model.interface import Interface
from ..tools.ifconfig import Ifconfig
from ..tools.iwconfig import Iwconfig
from ..util.process import Process from ..util.process import Process
from ..util.color import Color from ..util.color import Color
from ..util.input import raw_input from ..util.input import raw_input
@@ -63,7 +65,10 @@ class Airmon(object):
@staticmethod @staticmethod
def start_baddriver(iface): #fix for bad drivers like the rtl8812AU def start_baddriver(iface): #fix for bad drivers like the rtl8812AU
os.system("ifconfig %s down; iwconfig %s mode monitor; ifconfig %s up" % (iface, iface, iface)) Ifconfig.down(iface)
Iwconfig.mode(iface, 'monitor')
Ifconfig.up(iface)
with open("/sys/class/net/" + iface + "/type", "r") as f: with open("/sys/class/net/" + iface + "/type", "r") as f:
if (int(f.read()) == Airmon.ARPHRD_IEEE80211_RADIOTAP): if (int(f.read()) == Airmon.ARPHRD_IEEE80211_RADIOTAP):
return iface return iface
@@ -72,7 +77,10 @@ class Airmon(object):
@staticmethod @staticmethod
def stop_baddriver(iface): def stop_baddriver(iface):
os.system("ifconfig %s down; iwconfig %s mode managed; ifconfig %s up" % (iface, iface, iface)) Ifconfig.down(iface)
Iwconfig.mode(iface, 'managed')
Ifconfig.up(iface)
with open("/sys/class/net/" + iface + "/type", "r") as f: with open("/sys/class/net/" + iface + "/type", "r") as f:
if (int(f.read()) == Airmon.ARPHRD_ETHER): if (int(f.read()) == Airmon.ARPHRD_ETHER):
return iface return iface
@@ -94,7 +102,7 @@ class Airmon(object):
''' '''
# Get interface name from input # Get interface name from input
if type(iface) == Interface: if type(iface) == Interface:
iface = iface.name iface = iface.interface
Airmon.base_interface = iface Airmon.base_interface = iface
# Call airmon-ng # Call airmon-ng
@@ -181,17 +189,7 @@ class Airmon(object):
Returns: Returns:
List of interface names that are in monitor mode List of interface names that are in monitor mode
''' '''
interfaces = [] return Iwconfig.get_interfaces(mode='Monitor')
(out, err) = Process.call("iwconfig")
for line in out.split("\n"):
if len(line) == 0: continue
if line[0] != ' ':
iface = line.split(' ')[0]
if '\t' in iface:
iface = iface.split('\t')[0]
if 'Mode:Monitor' in line and iface not in interfaces:
interfaces.append(iface)
return interfaces
@staticmethod @staticmethod
@@ -242,11 +240,11 @@ class Airmon(object):
iface = a.get(choice) iface = a.get(choice)
if a.get(choice).name in mon_ifaces: if a.get(choice).interface in mon_ifaces:
Color.pl('{+} {G}%s{W} is already in monitor mode' % iface.name) Color.pl('{+} {G}%s{W} is already in monitor mode' % iface.interface)
else: else:
iface.name = Airmon.start(iface) iface.interface = Airmon.start(iface)
return iface.name return iface.interface
@staticmethod @staticmethod
@@ -297,7 +295,7 @@ class Airmon(object):
@staticmethod @staticmethod
def put_interface_up(iface): def put_interface_up(iface):
Color.p("{!} {O}putting interface {R}%s up{O}..." % (iface)) Color.p("{!} {O}putting interface {R}%s up{O}..." % (iface))
(out,err) = Process.call('ifconfig %s up' % (iface)) Ifconfig.up(iface)
Color.pl(" {R}done{W}") Color.pl(" {R}done{W}")
@staticmethod @staticmethod

53
wifite/tools/ifconfig.py Normal file
View File

@@ -0,0 +1,53 @@
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
import re
class Ifconfig(object):
@classmethod
def up(cls, interface, args=[]):
'''Put interface up'''
from ..util.process import Process
command = ['ifconfig', interface, 'up']
if type(args) is list:
command.extend(args)
elif type(args) is 'str':
command.append(args)
pid = Process(command)
pid.wait()
return pid.poll() == 0
@classmethod
def down(cls, interface):
'''Put interface down'''
from ..util.process import Process
command = ['ifconfig', interface, 'down']
if type(args) is list:
command.extend(args)
elif type(args) is 'str':
command.append(args)
pid = Process(command)
pid.wait()
return pid.poll() == 0
@classmethod
def get_mac(cls, interface):
from ..util.process import Process
output = Process(['ifconfig', interface]).stdout()
mac_regex = ('[a-zA-Z0-9]{2}-' * 6)[:-1]
match = re.search(' (%s)' % mac_regex, output)
if not match:
raise Exception('Could not find the mac address for %s' % interface)
return match.groups()[0].replace('-', ':')

38
wifite/tools/iwconfig.py Normal file
View File

@@ -0,0 +1,38 @@
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
class Iwconfig(object):
@classmethod
def exists(cls):
pass
@classmethod
def mode(cls, iface, mode_name):
from ..util.process import Process
pid = Process(['iwconfig', iface, 'mode', mode_name])
pid.wait()
return pid.poll()
@classmethod
def get_interfaces(cls, mode=None):
from ..util.process import Process
interfaces = set()
(out, err) = Process.call('iwconfig')
for line in out.split('\n'):
if len(line) == 0: continue
if not line.startswith(' '):
iface = line.split(' ')[0]
if '\t' in iface:
iface = iface.split('\t')[0]
if mode is None:
interfaces.add(iface)
if mode is not None and 'Mode:{}'.format(mode) in line:
interfaces.add(iface)
return list(interfaces)

View File

@@ -2,6 +2,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from ..model.interface import Interface from ..model.interface import Interface
from ..tools.ifconfig import Ifconfig
from ..util.color import Color from ..util.color import Color
class Macchanger(object): class Macchanger(object):
@@ -15,22 +16,22 @@ class Macchanger(object):
from ..config import Configuration from ..config import Configuration
iface = Configuration.interface iface = Configuration.interface
if type(iface) == Interface: if type(iface) == Interface:
iface = iface.name iface = iface.interface
cls.original_mac = Interface.get_mac(iface) cls.original_mac = Ifconfig.get_mac(iface)
cls.is_init = True
@classmethod @classmethod
def down_macch_up(cls, macch_option): def down_macch_up(cls, macch_option):
cls.init() cls.init()
from ..util.process import Process from ..util.process import Process
from ..config import Configuration from ..config import Configuration
iface = Configuration.interface iface = Configuration.interface
cmd = ["ifconfig", iface, "down"]
Color.clear_entire_line() Color.clear_entire_line()
Color.p("\r{+} {C}macchanger{W}: Taking interface {C}%s{W} down..." % iface) Color.p("\r{+} {C}macchanger{W}: Taking interface {C}%s{W} down..." % iface)
ifdown = Process(cmd)
ifdown.wait() if Ifconfig.down(iface) != 0:
if ifdown.poll() != 0:
Color.pl("{!} {C}macchanger{W}: Error running %s" % " ".join(cmd)) Color.pl("{!} {C}macchanger{W}: Error running %s" % " ".join(cmd))
Color.pl("{!} Output: %s, %s" % (ifdown.stdout(), ifdown.stderr())) Color.pl("{!} Output: %s, %s" % (ifdown.stdout(), ifdown.stderr()))
return False return False
@@ -45,12 +46,11 @@ class Macchanger(object):
Color.pl("{!} Output: %s, %s" % (macch.stdout(), macch.stderr())) Color.pl("{!} Output: %s, %s" % (macch.stdout(), macch.stderr()))
return False return False
cmd = ["ifconfig", iface, "up"]
Color.clear_entire_line() Color.clear_entire_line()
Color.p("\r{+} {C}macchanger{W}: Bringing interface {C}%s{W} up..." % iface) Color.p("\r{+} {C}macchanger{W}: Bringing interface {C}%s{W} up..." % iface)
ifup = Process(cmd)
ifup.wait() ifup.wait()
if ifup.poll() != 0: if Ifconfig.up(iface) != 0:
Color.pl("{!} {C}macchanger{W}: Error running %s" % " ".join(cmd)) Color.pl("{!} {C}macchanger{W}: Error running %s" % " ".join(cmd))
Color.pl("{!} Output: %s, %s" % (ifup.stdout(), ifup.stderr())) Color.pl("{!} Output: %s, %s" % (ifup.stdout(), ifup.stderr()))
return False return False
@@ -62,7 +62,7 @@ class Macchanger(object):
if not cls.down_macch_up("-p"): return if not cls.down_macch_up("-p"): return
Color.pl("\r{+} {C}macchanger{W}: Resetting MAC address...") Color.pl("\r{+} {C}macchanger{W}: Resetting MAC address...")
from ..config import Configuration from ..config import Configuration
new_mac = Interface.get_mac(Configuration.interface) new_mac = Ifconfig.get_mac(Configuration.interface)
Color.clear_entire_line() Color.clear_entire_line()
Color.pl("\r{+} {C}macchanger{W}: Reset MAC address back to {C}%s{W}" % new_mac) Color.pl("\r{+} {C}macchanger{W}: Reset MAC address back to {C}%s{W}" % new_mac)
@@ -72,7 +72,7 @@ class Macchanger(object):
if not cls.down_macch_up("-r"): return if not cls.down_macch_up("-r"): return
cls.is_changed = True cls.is_changed = True
from ..config import Configuration from ..config import Configuration
new_mac = Interface.get_mac(Configuration.interface) new_mac = Ifconfig.get_mac(Configuration.interface)
Color.clear_entire_line() Color.clear_entire_line()
Color.pl("\r{+} {C}macchanger{W}: Changed MAC address to {C}%s{W}" % new_mac) Color.pl("\r{+} {C}macchanger{W}: Changed MAC address to {C}%s{W}" % new_mac)

View File

@@ -4,7 +4,7 @@
try: try:
from .config import Configuration from .config import Configuration
except (ValueError, ImportError) as e: except (ValueError, ImportError) as e:
raise Exception('You may need to run wifite from the root directory (which includes README.md)') raise Exception('You may need to run wifite from the root directory (which includes README.md)', e)
from .util.scanner import Scanner from .util.scanner import Scanner
from .util.process import Process from .util.process import Process
@@ -43,7 +43,7 @@ class Wifite(object):
elif Configuration.crack_handshake: elif Configuration.crack_handshake:
CrackHandshake() CrackHandshake()
else: else:
Configuration.get_interface() Configuration.get_monitor_mode_interface()
self.run() self.run()
def dependency_check(self): def dependency_check(self):