eiwd

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

hostapd.py (11724B)


      1 #!/usr/bin/python3
      2 import os, os.path
      3 import re
      4 import socket
      5 import select
      6 import time
      7 from gi.repository import GLib
      8 from weakref import WeakValueDictionary
      9 from config import ctx
     10 
     11 chan_freq_map = [
     12     None,
     13     2412,
     14     2417,
     15     2422,
     16     2427,
     17     2432,
     18     2437,
     19     2442,
     20     2447,
     21     2452,
     22     2457,
     23     2462,
     24     2467,
     25     2472,
     26     2484
     27 ]
     28 
     29 ctrl_count = 0
     30 mainloop = GLib.MainLoop()
     31 
     32 class HostapdCLI(object):
     33     _instances = WeakValueDictionary()
     34 
     35     def __new__(cls, config=None, *args, **kwargs):
     36         hapd = ctx.get_hapd_instance(config)
     37 
     38         if not config:
     39             config = hapd.config
     40 
     41         if not config in cls._instances.keys():
     42             obj = object.__new__(cls, *args, **kwargs)
     43             obj._initialized = False
     44 
     45             cls._instances[config] = obj
     46 
     47         return cls._instances[config]
     48 
     49     def __init__(self, config=None, *args, **kwargs):
     50         global ctrl_count
     51 
     52         if self._initialized:
     53             return
     54 
     55         self._initialized = True
     56         self.ctrl_sock = None
     57 
     58         if not ctx.hostapd:
     59             raise Exception("No hostapd instances are configured")
     60 
     61         if not config and sum([len(hapd.instances) for hapd in ctx.hostapd]) > 1:
     62             raise Exception('config must be provided if more than one hostapd instance exists')
     63 
     64         hapd = ctx.get_hapd_instance(config)
     65 
     66         self.interface = hapd.intf
     67         self._config_path = "/tmp/" + hapd.config
     68         self._default_config = self._get_config(self._config_path)
     69 
     70         # The vendor_elements is somewhat of a special case because you can't
     71         # set it to 'nothing' within the hostapd config. In most cases tests do
     72         # not use this and we don't want to require they unset this value
     73         # during initialization. Default this to '' so set_value won't throw
     74         # an exception.
     75         if self._default_config.get('vendor_elements', None) == None:
     76             self._default_config['vendor_elements'] = ''
     77 
     78         self._current_config = self._default_config.copy()
     79 
     80         if not self.interface:
     81             raise Exception('config %s not found' % config)
     82 
     83         self.ifname = self.interface.name
     84         self.socket_path = os.path.dirname(self.interface.ctrl_interface)
     85 
     86         self.cmdline = ['hostapd_cli', '-p', self.socket_path, '-i', self.ifname]
     87 
     88         self.local_ctrl = '/tmp/hostapd_' + str(os.getpid()) + '_' + \
     89                             str(ctrl_count)
     90         self.ctrl_sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
     91         self.ctrl_sock.bind(self.local_ctrl)
     92 
     93         self.ctrl_sock.connect(self.socket_path + '/' + self.ifname)
     94 
     95         self.events = []
     96         self.io_watch = GLib.io_add_watch(self.ctrl_sock, GLib.IO_IN, self._handle_data_in)
     97 
     98         if 'OK' not in self._ctrl_request('ATTACH'):
     99             raise Exception('ATTACH failed')
    100 
    101         ctrl_count = ctrl_count + 1
    102 
    103     def _get_config(self, path):
    104         f = open(path)
    105         lines = f.readlines()
    106         f.close()
    107         return dict([[v.strip() for v in kv] for kv in [l.split('#', 1)[0].split('=', 1) for l in lines] if len(kv) == 2])
    108 
    109     def _handle_data_in(self, sock, *args):
    110         newdata = sock.recv(4096)
    111 
    112         decoded = newdata.decode('utf-8')
    113         if len(decoded) >= 3 and decoded[0] == '<' and decoded[2] == '>':
    114             decoded = decoded[3:]
    115         while len(decoded) and decoded[-1] == '\n':
    116             decoded = decoded[:-1]
    117 
    118         self.events.insert(0, decoded)
    119 
    120         return True
    121 
    122     def _poll_event(self, event, disallow):
    123         # Look through the list (most recent is first) until the even is found.
    124         # Once found consume this event and any older ones as to not
    125         # accidentally trigger a false positive later on.
    126         for idx, e in enumerate(self.events):
    127             for d in disallow:
    128                 if d in e:
    129                     raise Exception('Event %s found while waiting for %s' % (d, event))
    130             if event in e:
    131                 self.events = self.events[:idx]
    132                 return e
    133 
    134         return False
    135 
    136     def wait_for_event(self, event, timeout=10, disallow=[]):
    137         if event == 'AP-ENABLED':
    138             if self.enabled:
    139                 return 'AP-ENABLED'
    140 
    141         return ctx.non_block_wait(self._poll_event, timeout, event, disallow,
    142                                     exception=TimeoutError("waiting for event"))
    143 
    144     def _data_available(self):
    145         [r, w, e] = select.select([self.ctrl_sock], [], [])
    146         if r:
    147             return True
    148         return False
    149 
    150     def _ctrl_request(self, command, timeout=10):
    151         if type(command) is str:
    152             command = str.encode(command)
    153 
    154         self.ctrl_sock.send(bytes(command))
    155 
    156         ctx.non_block_wait(self._data_available, timeout,
    157                             exception=TimeoutError("waiting for control response"))
    158 
    159         return self.ctrl_sock.recv(4096).decode('utf-8')
    160 
    161     def __del__(self):
    162         if self.ctrl_sock:
    163             self.ctrl_sock.close()
    164 
    165         try:
    166             os.remove(self.local_ctrl)
    167         except:
    168             pass
    169 
    170     def set_value(self, key, value):
    171         # Don't allow new settings, defaults should always be in hostapd config
    172         if self._default_config.get(key, None) == None:
    173             raise Exception("Untracked setting '%s'! Please set default in hostapd config" % key)
    174 
    175         self._current_config[key] = value
    176 
    177         cmd = self.cmdline + ['set', key, value]
    178         ctx.start_process(cmd).wait()
    179 
    180     def wps_push_button(self):
    181         ctx.start_process(self.cmdline + ['wps_pbc']).wait()
    182 
    183     def wps_pin(self, pin):
    184         cmd = self.cmdline + ['wps_pin', 'any', pin]
    185         ctx.start_process(cmd).wait()
    186 
    187     def deauthenticate(self, client_address, reason=None, test=None):
    188         cmd = self.cmdline + ['deauthenticate', client_address]
    189 
    190         if reason:
    191             cmd.append(f"reason={reason} test={test}")
    192 
    193         ctx.start_process(cmd).wait()
    194 
    195     def eapol_reauth(self, client_address):
    196         self.events = []
    197         cmd = 'EAPOL_REAUTH ' + client_address
    198         self.ctrl_sock.sendall(cmd.encode('utf-8'))
    199         self.wait_for_event('CTRL-EVENT-EAP-STARTED', disallow=['AP-STA-DISCONNECTED'])
    200         self.wait_for_event('CTRL-EVENT-EAP-SUCCESS', disallow=['AP-STA-DISCONNECTED'])
    201 
    202     def reload(self):
    203         # Seemingly all three commands needed for the instance to notice
    204         # interface's address change
    205         ctx.start_process(self.cmdline + ['reload']).wait()
    206         ctx.start_process(self.cmdline + ['disable']).wait()
    207         ctx.start_process(self.cmdline + ['enable']).wait()
    208 
    209     def default(self):
    210         for k, v in self._default_config.items():
    211             # Only bother setting the value if it differs
    212             if self._current_config[k] != v:
    213                 self.set_value(k, v)
    214                 self._current_config[k] = v
    215 
    216         self.reload()
    217 
    218     def disable(self):
    219         ctx.start_process(self.cmdline + ['disable']).wait()
    220 
    221     def list_sta(self):
    222         proc = ctx.start_process(self.cmdline + ['list_sta'])
    223         proc.wait()
    224 
    225         if not proc.out:
    226             return []
    227 
    228         return [line for line in proc.out.split('\n') if line]
    229 
    230     def set_neighbor(self, addr, ssid, nr):
    231         cmd = self.cmdline + ['set_neighbor', addr, 'ssid="%s"' % ssid, 'nr=%s' % nr]
    232         ctx.start_process(cmd).wait()
    233 
    234     def remove_neighbor(self, addr):
    235         cmd = self.cmdline + ['remove_neighbor', addr]
    236         ctx.start_process(cmd).wait()
    237 
    238     def send_bss_transition(self, device, nr_list, disassoc_imminent=True):
    239         # Send a BSS transition to a station (device). nr_list should be an
    240         # array of tuples containing the BSS address and neighbor report.
    241         # Parsing the neighbor report is a bit ugly but it makes it more
    242         # consistent with the set_neighbor() API, i.e. the same neighbor report
    243         # string could be used in both API's.
    244         pref = 1
    245         cmd = self.cmdline + ['bss_tm_req', device]
    246 
    247         if disassoc_imminent:
    248             cmd.append('disassoc_imminent=1')
    249 
    250         for i in nr_list:
    251             addr = i[0]
    252             nr = i[1]
    253 
    254             bss_info=str(int(nr[0:8], 16))
    255             op_class=str(int(nr[8:10], 16))
    256             chan_num=nr[10:12]
    257             phy_num=nr[14:16]
    258 
    259             cmd += ['pref=%s' % str(pref), 'neighbor=%s,%s,%s,%s,%s' % \
    260                         (addr, bss_info, op_class, chan_num, phy_num)]
    261             pref += 1
    262 
    263         proc = ctx.start_process(cmd)
    264         proc.wait()
    265 
    266         if 'OK' not in proc.out:
    267             raise Exception('BSS_TM_REQ failed, is hostapd built with CONFIG_WNM_AP=y?')
    268 
    269     def req_beacon(self, addr, request):
    270         '''
    271             Send a RRM Beacon request
    272         '''
    273         cmd = self.cmdline + ['req_beacon', addr, request]
    274         ctx.start_process(cmd).wait()
    275 
    276     def rekey(self, address=None):
    277         if address:
    278             cmd = 'REKEY_PTK %s' % address
    279             self.ctrl_sock.sendall(cmd.encode('utf-8'))
    280             self.events = []
    281             self.wait_for_event('EAPOL-4WAY-HS-COMPLETED', disallow=['AP-STA-DISCONNECTED'])
    282             return
    283 
    284         cmd = 'REKEY_GTK'
    285         self.ctrl_sock.sendall(cmd.encode('utf-8'))
    286 
    287     def resend_m3(self, address):
    288         cmd = 'RESEND_M3 %s' % address
    289         self.ctrl_sock.sendall(cmd.encode('utf-8'))
    290 
    291     def chan_switch(self, channel, wait=True):
    292         if channel > len(chan_freq_map):
    293             raise Exception("Only 2.4GHz channels supported for chan_switch")
    294 
    295         cmd = self.cmdline + ['chan_switch', '50', str(chan_freq_map[channel])]
    296         ctx.start_process(cmd).wait()
    297 
    298         if wait:
    299             self.wait_for_event('AP-CSA-FINISHED')
    300 
    301     def _get_status(self):
    302         ret = {}
    303 
    304         cmd = self.cmdline + ['status']
    305         proc = ctx.start_process(cmd)
    306         proc.wait()
    307         status = proc.out.strip().split('\n')
    308 
    309         for kv in status:
    310             k, v = kv.split('=')
    311             ret[k] = v
    312 
    313         return ret
    314 
    315     def sta_status(self, address):
    316         ret = {}
    317 
    318         cmd = self.cmdline + ['sta', address]
    319         proc = ctx.start_process(cmd)
    320         proc.wait()
    321         status = proc.out.strip().split('\n')
    322 
    323         # Pop address
    324         status.pop(0)
    325         for kv in status:
    326             k, v = kv.split('=', 1)
    327             ret[k] = v
    328 
    329         return ret
    330 
    331     @property
    332     def bssid(self):
    333         return self._get_status()['bssid[0]']
    334 
    335     @property
    336     def frequency(self):
    337         return int(self._get_status()['freq'])
    338 
    339     @property
    340     def enabled(self):
    341         return self._get_status()['state'] == 'ENABLED'
    342 
    343     def set_address(self, mac):
    344         os.system('ip link set dev %s down' % self.ifname)
    345         os.system('ip link set dev %s addr %s up' % (self.ifname, mac))
    346 
    347         self.reload()
    348         self.wait_for_event("AP-ENABLED")
    349 
    350     def _add_neighbors(self, *args, op_class=81):
    351         for hapd in args:
    352             status = hapd._get_status()
    353 
    354             ssid = status['ssid[0]']
    355             bssid = status['bssid[0]']
    356             channel = int(status['channel'])
    357 
    358             if (channel > 14 and op_class == 81):
    359                 raise Exception("default add_neighbors assumes opclass 0x51!")
    360 
    361             channel = '{:02x}'.format(channel)
    362             oper_class = '{:02x}'.format(op_class)
    363 
    364             self.set_neighbor(bssid, ssid, '%s8f000000%s%s060603000000' %
    365                                 (bssid.replace(':', ''), oper_class, channel))
    366 
    367     @classmethod
    368     def group_neighbors(cls, *args):
    369         for hapd in args:
    370             others = [h for h in args if h != hapd]
    371 
    372             hapd._add_neighbors(*others)
    373 
    374     def pmksa_flush(self):
    375         cmd = self.cmdline + ['pmksa_flush']
    376         ctx.start_process(cmd).wait()