eiwd

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

wpas.py (12642B)


      1 #!/usr/bin/python3
      2 import os
      3 import socket
      4 import shutil
      5 from gi.repository import GLib
      6 from config import ctx
      7 from unittest import SkipTest
      8 
      9 import binascii
     10 
     11 from utils import Process
     12 
     13 ctrl_count = 0
     14 
     15 class Wpas:
     16     io_watch = None
     17     sockets = {}
     18     wpa_supplicant = None
     19     cleanup_paths = []
     20 
     21     def _start_wpas(self, config_name=None, p2p=False):
     22         if not shutil.which('wpa_supplicant'):
     23             print('wpa_supplicant not found, skipping test')
     24             raise SkipTest
     25 
     26         main_interface = None
     27         for interface in ctx.wpas_interfaces:
     28             if config_name is None or interface.config == config_name:
     29                 if main_interface is not None:
     30                     raise Exception('More than one wpa_supplicant interface matches given config')
     31                 main_interface = interface
     32 
     33         if main_interface is None:
     34             raise Exception('No matching wpa_supplicant interface')
     35 
     36         ifname = main_interface.name
     37         if p2p:
     38             ifname = 'p2p-dev-' + ifname
     39 
     40         self.interface = main_interface
     41         self.ifname = ifname
     42         self.config_path = '/tmp/' + self.interface.config
     43         self.config = self._get_config()
     44         self.socket_path = self.config['ctrl_interface']
     45 
     46         cmd = ['wpa_supplicant', '-i', self.interface.name, '-c', self.config_path]
     47         if Process.is_verbose('wpa_supplicant-dbg'):
     48             cmd += ['-d']
     49 
     50         self.wpa_supplicant = ctx.start_process(cmd)
     51 
     52         self.sockets = {}
     53         self.io_watch = GLib.io_add_watch(self._get_socket(), GLib.IO_IN, self._handle_data_in)
     54 
     55         self.p2p_peers = {}
     56         self.p2p_go_neg_requests = {}
     57         self.p2p_clients = {}
     58         self.p2p_group = None
     59 
     60         self._rx_data = []
     61         self._ctrl_request('ATTACH')
     62         self.wait_for_event('OK')
     63 
     64     def __init__(self, *args, **kwargs):
     65         self._start_wpas(*args, **kwargs)
     66 
     67     def _get_config(self):
     68         f = open(self.config_path)
     69         lines = f.readlines()
     70         f.close()
     71         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])
     72 
     73     def _check_event(self, event):
     74         if not event and len(self._rx_data) >= 1:
     75             return self._rx_data[0]
     76 
     77         for e in self._rx_data:
     78             if event in e:
     79                 return e
     80 
     81         return False
     82 
     83     def wait_for_event(self, event, timeout=10):
     84         self._rx_data = []
     85         return ctx.non_block_wait(self._check_event, timeout, event)
     86 
     87     def wait_for_result(self, timeout=10):
     88         self._rx_data = []
     89         return self.wait_for_event(None, timeout=timeout)
     90 
     91     def _event_parse(self, line):
     92         # Unescape event parameter values in '', other escaping rules not implemented
     93         key = None
     94         value = ''
     95         count = 0
     96         quoted = False
     97         event = {}
     98 
     99         def handle_eow():
    100             nonlocal key, value, count, event
    101             if count == 0:
    102                 key = 'event'
    103             elif key is None:
    104                 if not value:
    105                     return
    106                 key = 'arg' + str(count)
    107             event[key] = value
    108             key = None
    109             value = ''
    110             count += 1
    111 
    112         for ch in line:
    113             if ch == '\'':
    114                 quoted = not quoted
    115             elif quoted:
    116                 value += ch
    117             elif ch == '=' and key is None:
    118                 key = value
    119                 value = ''
    120             elif ch in ' \n':
    121                 handle_eow()
    122             else:
    123                 value += ch
    124         handle_eow()
    125         return event
    126 
    127     def _handle_data_in(self, sock, *args):
    128         newdata = sock.recv(4096)
    129         if len(newdata) == 0:
    130             raise Exception('Wpa_s control socket error')
    131 
    132         decoded = newdata.decode('utf-8')
    133         if len(decoded) >= 3 and decoded[0] == '<' and decoded[2] == '>':
    134             decoded = decoded[3:]
    135         while len(decoded) and decoded[-1] == '\n':
    136             decoded = decoded[:-1]
    137 
    138         self._rx_data.append(decoded)
    139 
    140         event = self._event_parse(decoded)
    141         if event['event'] == 'P2P-DEVICE-FOUND':
    142             event.pop('event')
    143             event.pop('arg1')
    144             self.p2p_peers[event['p2p_dev_addr']] = event
    145         elif event['event'] == 'P2P-DEVICE-LOST':
    146             del self.p2p_peers[event['p2p_dev_addr']]
    147         elif event['event'] == 'P2P-GO-NEG-REQUEST':
    148             event.pop('event')
    149             event['p2p_dev_addr'] = event.pop('arg1')
    150             self.p2p_go_neg_requests[event['p2p_dev_addr']] = event
    151         elif event['event'] == 'P2P-GO-NEG-SUCCESS':
    152             event.pop('event')
    153             addr = event.pop('peer_dev')
    154             event['success'] = True
    155             event['p2p_dev_addr'] = addr
    156 
    157             if addr in self.p2p_go_neg_requests:
    158                 self.p2p_go_neg_requests[addr].update(event)
    159             else:
    160                 self.p2p_go_neg_requests[addr] = event
    161         elif event['event'] == 'AP-STA-CONNECTED':
    162             event.pop('event')
    163             addr = event.pop('arg1')
    164             self.p2p_clients[addr] = event
    165         elif event['event'] == 'AP-STA-DISCONNECTED':
    166             addr = event.pop('arg1')
    167             del self.p2p_clients[addr]
    168         elif event['event'] == 'P2P-GROUP-STARTED':
    169             event.pop('event')
    170             event['ifname'] = event.pop('arg1')
    171             event['role'] = event.pop('arg2')
    172             self.p2p_group = event
    173         elif event['event'] == 'P2P-GROUP-REMOVED':
    174             self.p2p_group = None
    175 
    176         return True
    177 
    178     def _ctrl_request(self, command, ifname=None):
    179         if type(command) is str:
    180             command = str.encode(command)
    181 
    182         self._get_socket(ifname).send(bytes(command))
    183 
    184     def _get_socket(self, ifname=None):
    185         global ctrl_count
    186 
    187         if ifname is None:
    188             ifname = self.ifname
    189 
    190         if ifname in self.sockets:
    191             return self.sockets[ifname]
    192 
    193         local_path = '/tmp/wpas_' + str(os.getpid()) + '_' + str(ctrl_count)
    194         ctrl_count = ctrl_count + 1
    195         remote_path = self.socket_path + '/' + ifname
    196 
    197         self.wpa_supplicant.wait_for_socket(remote_path, 2)
    198         sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
    199         sock.bind(local_path)
    200         self.cleanup_paths.append(local_path)
    201         sock.connect(remote_path)
    202         self.cleanup_paths.append(remote_path)
    203 
    204         self.sockets[ifname] = sock
    205         return sock
    206 
    207     # Normal find phase with listen and active scan states
    208     def p2p_find(self):
    209         self._rx_data = []
    210         self._ctrl_request('P2P_SET disc_int 2 3 300')
    211         self.wait_for_event('OK')
    212         self._rx_data = []
    213         self._ctrl_request('P2P_FIND type=social')
    214         self.wait_for_event('OK')
    215 
    216     # Like p2p_find but uses only listen states
    217     def p2p_listen(self):
    218         self._rx_data = []
    219         self._ctrl_request('P2P_LISTEN')
    220         self.wait_for_event('OK')
    221 
    222     # Stop a p2p_find or p2p_listen
    223     def p2p_stop_find_listen(self):
    224         self._rx_data = []
    225         self._ctrl_request('P2P_STOP_FIND')
    226         self.wait_for_event('OK')
    227 
    228     def p2p_connect(self, peer, pin=None, go_intent=None):
    229         self._rx_data = []
    230         self._ctrl_request('P2P_CONNECT ' + peer['p2p_dev_addr'] + ' ' + ('pbc' if pin is None else pin) +
    231                         ('' if go_intent is None else ' go_intent=' + str(go_intent)))
    232         self.wait_for_event('OK')
    233 
    234     def p2p_accept_go_neg_request(self, request, pin=None, go_intent=None):
    235         self._rx_data = []
    236         self._ctrl_request('P2P_CONNECT ' + request['p2p_dev_addr'] + ' ' + ('pbc' if pin is None else pin) +
    237                         ('' if go_intent is None else ' go_intent=' + str(go_intent)))
    238         self.wait_for_event('OK')
    239 
    240     # Pre-accept the next GO Negotiation Request from this peer to avoid the extra Response + Request frames
    241     def p2p_authorize(self, peer, pin=None, go_intent=None):
    242         self._rx_data = []
    243         self._ctrl_request('P2P_CONNECT ' + peer['p2p_dev_addr'] + ' ' + ('pbc' if pin is None else pin) +
    244                         ('' if go_intent is None else ' go_intent=' + str(go_intent)) + ' auth')
    245         self.wait_for_event('OK')
    246 
    247     def p2p_set(self, key, value, **kwargs):
    248         self._ctrl_request('P2P_SET ' + key + ' ' + value, **kwargs)
    249 
    250     def set(self, key, value, **kwargs):
    251         self._ctrl_request('SET ' + key + ' ' + value, **kwargs)
    252 
    253     def dpp_enrollee_start(self, uri=None, oper_and_channel=None):
    254         if not oper_and_channel:
    255             oper_and_channel = '81/1'
    256 
    257         self._rx_data = []
    258         self._ctrl_request('DPP_BOOTSTRAP_GEN type=qrcode chan=%s' % oper_and_channel)
    259         self._dpp_qr_id = self.wait_for_result()
    260         self._ctrl_request('DPP_BOOTSTRAP_GET_URI %s' % self._dpp_qr_id)
    261         self._dpp_uri = self.wait_for_result()
    262 
    263         print("DPP Enrollee QR: %s" % self._dpp_uri)
    264 
    265         if uri:
    266             self._rx_data = []
    267             self._ctrl_request('DPP_QR_CODE ' + uri)
    268             self._dpp_qr_id = self.wait_for_result()
    269             self._rx_data = []
    270             self._ctrl_request('DPP_AUTH_INIT peer=%s role=enrollee' % self._dpp_qr_id)
    271         else:
    272             self._ctrl_request('DPP_CHIRP own=%s iter=100' % self._dpp_qr_id)
    273 
    274         return self._dpp_uri
    275 
    276     def dpp_configurator_create(self, uri=None):
    277         self._rx_data = []
    278         self._ctrl_request('DPP_CONFIGURATOR_ADD')
    279         self._dpp_conf_id = self.wait_for_result()
    280         while not self._dpp_conf_id.isnumeric():
    281             self._dpp_conf_id = self.wait_for_result()
    282 
    283         if not uri:
    284             print("DPP Configurator ID: %s" % self._dpp_conf_id)
    285             return
    286 
    287         self._rx_data = []
    288         self._ctrl_request('DPP_QR_CODE ' + uri)
    289         self._dpp_qr_id = self.wait_for_result()
    290         while not self._dpp_conf_id.isnumeric():
    291             self._dpp_qr_id = self.wait_for_result()
    292 
    293         print("DPP Configurator ID: %s. DPP QR ID: %s" % (self._dpp_conf_id, self._dpp_qr_id))
    294 
    295     def dpp_configurator_start(self, ssid, passphrase, freq=None):
    296         ssid = binascii.hexlify(ssid.encode()).decode()
    297         passphrase = binascii.hexlify(passphrase.encode()).decode()
    298 
    299         cmd = 'DPP_AUTH_INIT peer=%s conf=sta-psk ssid=%s pass=%s ' % (self._dpp_qr_id, ssid, passphrase)
    300 
    301         if freq:
    302             cmd += 'neg_freq=%u ' % freq
    303 
    304         self._rx_data = []
    305         self._ctrl_request(cmd)
    306         self.wait_for_event('DPP-AUTH-SUCCESS', timeout=30)
    307         self.wait_for_event('DPP-CONF-SENT')
    308 
    309     def dpp_bootstrap_gen(self, type='qrcode', curve=None):
    310         cmd = f'DPP_BOOTSTRAP_GEN type={type}'
    311 
    312         if curve:
    313             cmd += f' curve={curve}'
    314 
    315         self._rx_data = []
    316         self._ctrl_request(cmd)
    317         self._dpp_id = self.wait_for_result()
    318         while not self._dpp_id.isnumeric():
    319             self._dpp_id = self.wait_for_result()
    320 
    321     def dpp_pkex_add(self, code, identifier=None, version=None, initiator=False, role=None):
    322         cmd = f'DPP_PKEX_ADD own={self._dpp_id}'
    323 
    324         if identifier:
    325             cmd += f' identifier={identifier}'
    326 
    327         if initiator:
    328             cmd += f' init=1'
    329 
    330         if version:
    331             cmd += f' ver={version}'
    332 
    333         if role:
    334             cmd += f' role={role}'
    335 
    336         cmd += f' code={code}'
    337 
    338         self._rx_data = []
    339         self._ctrl_request(cmd)
    340 
    341     def dpp_pkex_remove(self):
    342         self._rx_data = []
    343         self._ctrl_request("DPP_PKEX_REMOVE *")
    344 
    345     def dpp_listen(self, freq):
    346         self._rx_data = []
    347         self._ctrl_request(f'DPP_LISTEN {freq}')
    348 
    349     def dpp_stop_listen(self):
    350         self._rx_data = []
    351         self._ctrl_request("DPP_STOP_LISTEN")
    352 
    353     def dpp_configurator_remove(self):
    354         self._ctrl_request('DPP_CONFIGURATOR_REMOVE *')
    355         self.wait_for_result()
    356         self._ctrl_request('DPP_BOOTSTRAP_REMOVE *')
    357         self.wait_for_result()
    358 
    359     def disconnect(self):
    360         self._ctrl_request('DISCONNECT')
    361 
    362     # Probably needed: remove references to self so that the GC can call __del__ automatically
    363     def clean_up(self):
    364         if self.io_watch is not None:
    365             GLib.source_remove(self.io_watch)
    366             self.io_watch = None
    367         for ifname in self.sockets:
    368             self.sockets[ifname].close()
    369         self.sockets = {}
    370         if self.wpa_supplicant is not None:
    371             ctx.stop_process(self.wpa_supplicant)
    372             self.wpa_supplicant = None
    373         for path in self.cleanup_paths:
    374             if os.path.exists(path):
    375                 os.remove(path)
    376         self.cleanup_paths = []
    377 
    378     def __del__(self):
    379         self.clean_up()