eiwd

no dbus iwd with iwctl functionality
git clone https://git.daat.foo/repos/eiwd.git
Log | Files | Refs | Submodules | README | LICENSE

hwsim.py (16014B)


      1 #!/usr/bin/python3
      2 import dbus
      3 import sys
      4 
      5 from collections.abc import Mapping
      6 from weakref import WeakValueDictionary
      7 from abc import ABCMeta, abstractmethod
      8 from enum import Enum
      9 from scapy.all import *
     10 try:
     11     from scapy.contrib.wpa_eapol import WPA_key
     12 except:
     13     from scapy.layers.eap import EAPOL_KEY
     14 
     15 import iwd
     16 from config import ctx
     17 
     18 HWSIM_SERVICE =                 'net.connman.hwsim'
     19 HWSIM_RULE_MANAGER_INTERFACE =  'net.connman.hwsim.RuleManager'
     20 HWSIM_RULE_INTERFACE =          'net.connman.hwsim.Rule'
     21 HWSIM_RADIO_MANAGER_INTERFACE = 'net.connman.hwsim.RadioManager'
     22 HWSIM_RADIO_INTERFACE =         'net.connman.hwsim.Radio'
     23 HWSIM_INTERFACE_INTERFACE =     'net.connman.hwsim.Interface'
     24 
     25 HWSIM_AGENT_MANAGER_PATH =      '/'
     26 
     27 class HwsimDBusAbstract(iwd.AsyncOpAbstract):
     28     __metaclass__ = ABCMeta
     29 
     30     def __init__(self, object_path, properties = None, namespace=ctx):
     31         self._bus = namespace.get_bus()
     32         self._object_path = object_path
     33         proxy = self._bus.get_object(HWSIM_SERVICE, self._object_path)
     34         self._iface = dbus.Interface(proxy, self._iface_name)
     35         self._prop_proxy = dbus.Interface(proxy, iwd.DBUS_PROPERTIES)
     36 
     37         if properties is None:
     38             self._properties = self._prop_proxy.GetAll(self._iface_name)
     39         else:
     40             self._properties = properties
     41 
     42         self._prop_proxy.connect_to_signal("PropertiesChanged",
     43                 self._property_changed_handler, path_keyword="path")
     44 
     45     def _property_changed_handler(self, interface, changed, invalidated, path):
     46         if interface == self._iface_name and path == self._object_path:
     47             for name, value in changed.items():
     48                 self._properties[name] = value
     49 
     50     @abstractmethod
     51     def __str__(self):
     52         pass
     53 
     54     @property
     55     def path(self):
     56         return self._object_path
     57 
     58 class Rule(HwsimDBusAbstract):
     59     _iface_name = HWSIM_RULE_INTERFACE
     60 
     61     @property
     62     def source(self):
     63         return self._properties['Source']
     64 
     65     @source.setter
     66     def source(self, value):
     67         self._prop_proxy.Set(self._iface_name, 'Source', value, reply_handler=self._success,
     68                                 error_handler=self._failure)
     69         self._wait_for_async_op()
     70 
     71     @property
     72     def destination(self):
     73         return self._properties['Destination']
     74 
     75     @destination.setter
     76     def destination(self, value):
     77         self._prop_proxy.Set(self._iface_name, 'Destination', value, reply_handler=self._success,
     78                                 error_handler=self._failure)
     79         self._wait_for_async_op()
     80 
     81     @property
     82     def bidirectional(self):
     83         return bool(self._properties['Bidirectional'])
     84 
     85     @bidirectional.setter
     86     def bidirectional(self, value):
     87         self._prop_proxy.Set(self._iface_name, 'Bidirectional',
     88                 dbus.Boolean(value), reply_handler=self._success, error_handler=self._failure)
     89         self._wait_for_async_op()
     90 
     91     @property
     92     def frequency(self):
     93         return int(self._properties['Frequency'])
     94 
     95     @frequency.setter
     96     def frequency(self, value):
     97         self._prop_proxy.Set(self._iface_name, 'Frequency',
     98                 dbus.UInt32(value), reply_handler=self._success, error_handler=self._failure)
     99         self._wait_for_async_op()
    100 
    101     @property
    102     def priority(self):
    103         return int(self._properties['Priority'])
    104 
    105     @priority.setter
    106     def priority(self, value):
    107         self._prop_proxy.Set(self._iface_name, 'Priority',
    108                 dbus.Int16(value), reply_handler=self._success, error_handler=self._failure)
    109         self._wait_for_async_op()
    110 
    111     @property
    112     def signal(self):
    113         return int(self._properties['SignalStrength'])
    114 
    115     @signal.setter
    116     def signal(self, value):
    117         self._prop_proxy.Set(self._iface_name, 'SignalStrength',
    118                 dbus.Int16(value), reply_handler=self._success, error_handler=self._failure)
    119         self._wait_for_async_op()
    120 
    121     @property
    122     def drop(self):
    123         return bool(self._properties['Drop'])
    124 
    125     @drop.setter
    126     def drop(self, value):
    127         self._prop_proxy.Set(self._iface_name, 'Drop', dbus.Boolean(value),
    128                                     reply_handler=self._success, error_handler=self._failure)
    129         self._wait_for_async_op()
    130 
    131     @property
    132     def delay(self):
    133         return int(self._properties['Delay'])
    134 
    135     @delay.setter
    136     def delay(self, value):
    137         self._prop_proxy.Set(self._iface_name, 'Delay', dbus.UInt32(value),
    138                             reply_handler=self._success, error_handler=self._failure)
    139         self._wait_for_async_op()
    140 
    141     @property
    142     def prefix(self):
    143         return self._properties['Prefix']
    144 
    145     @prefix.setter
    146     def prefix(self, value):
    147         self._prop_proxy.Set(self._iface_name, 'Prefix', dbus.ByteArray.fromhex(value),
    148                             reply_handler=self._success, error_handler=self._failure)
    149         self._wait_for_async_op()
    150 
    151     @property
    152     def enabled(self):
    153         return self._properties['Enabled']
    154 
    155     @enabled.setter
    156     def enabled(self, value):
    157         self._prop_proxy.Set(self._iface_name, 'Enabled', value,
    158                             reply_handler=self._success, error_handler=self._failure)
    159         self._wait_for_async_op()
    160 
    161     @property
    162     def match_times(self):
    163         return self._properties['MatchTimes']
    164 
    165     @match_times.setter
    166     def match_times(self, value):
    167         self._prop_proxy.Set(self._iface_name, 'MatchTimes', dbus.UInt16(value))
    168 
    169     @property
    170     def drop_ack(self):
    171         return self._properties(['DropAck'])
    172 
    173     @drop_ack.setter
    174     def drop_ack(self, value):
    175         self._prop_proxy.Set(self._iface_name, 'DropAck', value)
    176 
    177     @property
    178     def match(self):
    179         return self._properties['MatchBytes']
    180 
    181     @match.setter
    182     def match(self, value):
    183         self._prop_proxy.Set(self._iface_name, 'MatchBytes', dbus.ByteArray.fromhex(value))
    184 
    185     @property
    186     def match_offset(self):
    187         return self._properties(['MatchBytesOffset'])
    188 
    189     @match_offset.setter
    190     def match_offset(self, value):
    191         self._prop_proxy.Set(self._iface_name, 'MatchBytesOffset', dbus.UInt16(value))
    192 
    193     def remove(self):
    194         self._iface.Remove(reply_handler=self._success,
    195                 error_handler=self._failure)
    196 
    197         self._wait_for_async_op()
    198 
    199     def __del__(self):
    200         self.remove()
    201 
    202     def __str__(self, prefix = ''):
    203         return prefix + 'Rule: ' + self.path + '\n' + \
    204                prefix + '\tSource:\t\t' + self.source + '\n' + \
    205                prefix + '\tDestination:\t' + self.destination + '\n' + \
    206                prefix + '\tBidirectional:\t' + \
    207                str(self.bidirectional) + '\n' + \
    208                prefix + '\tPriority:\t' + str(self.priority) + '\n' +\
    209                prefix + '\tFrequency:\t' + str(self.frequency) + '\n' + \
    210                prefix + '\tApply rssi:\t' + str(self.signal) + '\n' + \
    211                prefix + '\tApply drop:\t' + str(self.drop) + '\n' + \
    212                prefix + '\tPrefix:\t' + str([hex(b) for b in self.prefix]) + '\n' + \
    213                prefix + '\tDelay:\t' + str(self.delay) + '\n' + \
    214                prefix + '\tEnabled:\t' + str(self.enabled) + '\n'
    215 
    216 class RuleSet(Mapping):
    217     def __init__(self, hwsim, objects):
    218         self._dict = {}
    219         self._rule_manager = hwsim.rule_manager
    220 
    221         hwsim.object_manager.connect_to_signal("InterfacesAdded",
    222                 self._interfaces_added_handler, HWSIM_RULE_INTERFACE)
    223         hwsim.object_manager.connect_to_signal("InterfacesRemoved",
    224                 self._interfaces_removed_handler, HWSIM_RULE_INTERFACE)
    225 
    226         for path in objects:
    227             for interface in objects[path]:
    228                 if interface == HWSIM_RULE_INTERFACE:
    229                     self._dict[path] = Rule(path, objects[path][interface])
    230 
    231     def __getitem__(self, key):
    232         return self._dict.__getitem__(key)
    233 
    234     def __iter__(self):
    235         return self._dict.__iter__()
    236 
    237     def __len__(self):
    238         return self._dict.__len__()
    239 
    240     def __delitem__(self, key):
    241         self._dict.pop(key).remove()
    242 
    243     def _interfaces_added_handler(self, path, interfaces):
    244         self._dict[path] = Rule(interfaces[HWSIM_RULE_INTERFACE])
    245 
    246     def _interfaces_removed_handler(self, path, interfaces):
    247         del _dict[path]
    248 
    249     def create(self):
    250         path = self._rule_manager.AddRule()
    251         obj = Rule(path)
    252         self._dict[path] = obj
    253         return obj
    254 
    255     def remove_all(self):
    256         for rule in self._dict.values():
    257             rule.remove()
    258 
    259 class Radio(HwsimDBusAbstract):
    260     _iface_name = HWSIM_RADIO_INTERFACE
    261 
    262     @property
    263     def name(self):
    264         return self._properties['Name']
    265 
    266     @property
    267     def addresses(self):
    268         return [str(addr) for addr in self._properties['Addresses']]
    269 
    270     def remove(self):
    271         self._iface.Destroy(reply_handler=self._success,
    272                 error_handler=self._failure)
    273 
    274         self._wait_for_async_op()
    275 
    276     def __str__(self, prefix = ''):
    277         return prefix + 'Radio: ' + self.path + '\n' + \
    278                prefix + '\tName:\t\t' + self.name + '\n' + \
    279                prefix + '\tAddresses:\t' + repr(self.destination) + '\n'
    280 
    281 class RadioList(Mapping):
    282     def __init__(self, hwsim, objects):
    283         self._dict = {}
    284         self._radio_manager = hwsim.radio_manager
    285 
    286         hwsim.object_manager.connect_to_signal("InterfacesAdded",
    287                 self._interfaces_added_handler, HWSIM_RADIO_INTERFACE)
    288         hwsim.object_manager.connect_to_signal("InterfacesRemoved",
    289                 self._interfaces_removed_handler, HWSIM_RADIO_INTERFACE)
    290 
    291         for path in objects:
    292             for interface in objects[path]:
    293                 if interface == HWSIM_RADIO_INTERFACE:
    294                     self._dict[path] = Radio(path, objects[path][interface])
    295 
    296     def __getitem__(self, key):
    297         return self._dict.__getitem__(key)
    298 
    299     def __iter__(self):
    300         return self._dict.__iter__()
    301 
    302     def __len__(self):
    303         return self._dict.__len__()
    304 
    305     def __delitem__(self, key):
    306         self._dict.pop(key).remove()
    307 
    308     def values(self):
    309         return self._dict.values()
    310 
    311     def _interfaces_added_handler(self, path, interfaces):
    312         self._dict[path] = Radio(interfaces[HWSIM_RADIO_INTERFACE])
    313 
    314     def _interfaces_removed_handler(self, path, interfaces):
    315         del _dict[path]
    316 
    317     def create(self, name, p2p_device=False, iftype_disable=None,
    318                 cipher_disable=None, wait=True):
    319         args = dbus.Dictionary({
    320             'Name': name,
    321             'P2P': p2p_device,
    322             'NoVirtualInterface': True,
    323         }, signature='sv')
    324 
    325         if iftype_disable:
    326             args['InterfaceTypeDisable'] = iftype_disable
    327 
    328         if cipher_disable:
    329             args['CipherTypeDisable'] = cipher_disable
    330 
    331         if not wait:
    332             self._radio_manager.CreateRadio(args, reply_handler=self._success,
    333                                                 error_handler=self._failure)
    334             return None
    335 
    336         path = self._radio_manager.CreateRadio(args)
    337         obj = Radio(path)
    338         self._dict[path] = obj
    339         return obj
    340 
    341     def _success(self, bla):
    342         pass
    343 
    344     def _failure(self, ex):
    345         pass
    346 
    347 class Hwsim(iwd.AsyncOpAbstract):
    348     _instances = WeakValueDictionary()
    349 
    350     def __new__(cls, namespace=ctx):
    351         key = id(namespace)
    352 
    353         if key not in cls._instances.keys():
    354             obj = object.__new__(cls)
    355             obj._initialized = False
    356 
    357             cls._instances[key] = obj
    358 
    359         return cls._instances[key]
    360 
    361     def __init__(self, namespace=ctx):
    362         if self._initialized:
    363             return
    364 
    365         self._initialized = True
    366 
    367         self._bus = namespace.get_bus()
    368 
    369         self._rule_manager_if = dbus.Interface(
    370                 self._bus.get_object(HWSIM_SERVICE, '/'),
    371                 HWSIM_RULE_MANAGER_INTERFACE)
    372         self._radio_manager_if = dbus.Interface(
    373                 self._bus.get_object(HWSIM_SERVICE, '/'),
    374                 HWSIM_RADIO_MANAGER_INTERFACE)
    375         self._object_manager_if = dbus.Interface(
    376                 self._bus.get_object(HWSIM_SERVICE, '/'),
    377                 iwd.DBUS_OBJECT_MANAGER)
    378 
    379         objects = self.object_manager.GetManagedObjects()
    380 
    381         self._rules = RuleSet(self, objects)
    382         self._radios = RadioList(self, objects)
    383 
    384     @property
    385     def rules(self):
    386         return self._rules
    387 
    388     @property
    389     def rule_manager(self):
    390         return self._rule_manager_if
    391 
    392     @property
    393     def radios(self):
    394         return self._radios
    395 
    396     @property
    397     def radio_manager(self):
    398         return self._radio_manager_if
    399 
    400     @property
    401     def object_manager(self):
    402         return self._object_manager_if
    403 
    404     def spoof_disassociate(self, radio, freq, station):
    405         '''
    406             Send a spoofed disassociate frame to a station
    407         '''
    408         frame = Dot11()/Dot11Disas(reason=7)
    409         frame[Dot11].addr1 = station
    410         frame[Dot11].addr2 = radio.addresses[0]
    411         frame[Dot11].addr3 = radio.addresses[0]
    412 
    413         self.spoof_frame(radio, freq, station, raw(frame))
    414 
    415     def spoof_deauthenticate(self, radio, freq, station):
    416         '''
    417             Send a spoofed deauthenticate frame to a station
    418         '''
    419         frame = Dot11()/Dot11Deauth(reason=6)
    420         frame[Dot11].addr1 = station
    421         frame[Dot11].addr2 = radio.addresses[0]
    422         frame[Dot11].addr3 = radio.addresses[0]
    423 
    424         self.spoof_frame(radio, freq, station, raw(frame))
    425 
    426     def spoof_eap_fail(self, radio, freq, station):
    427         '''
    428             Send a spoofed EAP-Failure frame to a station
    429         '''
    430         frame = Dot11(type="Data", subtype=0)
    431         frame[Dot11].addr1 = station
    432         frame[Dot11].addr2 = radio.addresses[0]
    433         frame[Dot11].addr3 = radio.addresses[0]
    434         frame /= LLC()/SNAP()/EAPOL( version="802.1X-2001" )
    435         frame /= EAP( code="Failure" )
    436 
    437         self.spoof_frame(radio, freq, station, raw(frame))
    438 
    439     def spoof_invalid_ptk_1_of_4(self, radio, freq, station):
    440         '''
    441             Send a spoofed PTK 1/4 frame to a station
    442         '''
    443         frame = Dot11(type="Data", subtype=0)
    444         frame[Dot11].addr1 = station
    445         frame[Dot11].addr2 = radio.addresses[0]
    446         frame[Dot11].addr3 = radio.addresses[0]
    447 
    448         # NOTE: Expected key_info is 0x008a, with the install flag
    449         # this becomes 0x00ca.
    450         try:
    451             eapol = WPA_key( descriptor_type = 2,
    452                             key_info = 0x00ca, # Includes an invalid install flag!
    453                             replay_counter = struct.pack(">Q", 100))
    454         except:
    455             eapol = EAPOL_KEY( key_descriptor_type = 2,
    456                             install = 1,
    457                             key_ack = 1,
    458                             key_replay_counter = 1)
    459         frame /= LLC()/SNAP()/EAPOL(version="802.1X-2004", type="EAPOL-Key")
    460         frame /= eapol
    461 
    462         self.spoof_frame(radio, freq, station, raw(frame))
    463 
    464     def spoof_frame(self, radio, freq, station, frame):
    465         '''
    466             Send a spoofed arbitrary frame to a station
    467         '''
    468         radio_path = None
    469         objects = self.object_manager.GetManagedObjects()
    470 
    471         for path in objects:
    472             obj = objects[path]
    473             for interface in obj:
    474                 if interface == HWSIM_INTERFACE_INTERFACE:
    475                     if obj[interface]['Address'] == radio.addresses[0] or \
    476                                     obj[interface]['Address'] == radio.addresses[1]:
    477                         radio_path = path
    478                         break
    479 
    480         if not radio_path:
    481             raise Exception("Could not find radio %s" % radio.path)
    482 
    483         iface = dbus.Interface(self._bus.get_object(HWSIM_SERVICE, radio_path),
    484                 HWSIM_INTERFACE_INTERFACE)
    485 
    486         iface.SendFrame(dbus.ByteArray.fromhex(station.replace(':', '')),
    487                         freq, -30, frame)
    488 
    489     def get_radio(self, name):
    490         for path in self.radios:
    491             radio = self.radios[path]
    492             if radio.name == name:
    493                 return radio
    494 
    495         return None