blob: bd53a1ec0991b085029d018b981231a4a1b0254d [file] [log] [blame]
b.liue9582032025-04-17 19:18:16 +08001# Python class for controlling wpa_supplicant
2# Copyright (c) 2013-2019, Jouni Malinen <j@w1.fi>
3#
4# This software may be distributed under the terms of the BSD license.
5# See README for more details.
6
7import os
8import time
9import logging
10import binascii
11import re
12import struct
13import wpaspy
14import remotehost
15import subprocess
16
17logger = logging.getLogger()
18wpas_ctrl = '/var/run/wpa_supplicant'
19
20class WpaSupplicant:
21 def __init__(self, ifname=None, global_iface=None, hostname=None,
22 port=9877, global_port=9878, monitor=True):
23 self.monitor = monitor
24 self.hostname = hostname
25 self.group_ifname = None
26 self.global_mon = None
27 self.global_ctrl = None
28 self.gctrl_mon = None
29 self.ctrl = None
30 self.mon = None
31 self.ifname = None
32 self.host = remotehost.Host(hostname, ifname)
33 self._group_dbg = None
34 if ifname:
35 self.set_ifname(ifname, hostname, port)
36 res = self.get_driver_status()
37 if 'capa.flags' in res and int(res['capa.flags'], 0) & 0x20000000:
38 self.p2p_dev_ifname = 'p2p-dev-' + self.ifname
39 else:
40 self.p2p_dev_ifname = ifname
41
42 self.global_iface = global_iface
43 if global_iface:
44 if hostname != None:
45 self.global_ctrl = wpaspy.Ctrl(hostname, global_port)
46 if self.monitor:
47 self.global_mon = wpaspy.Ctrl(hostname, global_port)
48 self.global_dbg = hostname + "/" + str(global_port) + "/"
49 else:
50 self.global_ctrl = wpaspy.Ctrl(global_iface)
51 if self.monitor:
52 self.global_mon = wpaspy.Ctrl(global_iface)
53 self.global_dbg = ""
54 if self.monitor:
55 self.global_mon.attach()
56
57 def __del__(self):
58 self.close_monitor()
59 self.close_control()
60
61 def close_control_ctrl(self):
62 if self.ctrl:
63 del self.ctrl
64 self.ctrl = None
65
66 def close_control_global(self):
67 if self.global_ctrl:
68 del self.global_ctrl
69 self.global_ctrl = None
70
71 def close_control(self):
72 self.close_control_ctrl()
73 self.close_control_global()
74
75 def close_monitor_mon(self):
76 if not self.mon:
77 return
78 try:
79 while self.mon.pending():
80 ev = self.mon.recv()
81 logger.debug(self.dbg + ": " + ev)
82 except:
83 pass
84 try:
85 self.mon.detach()
86 except ConnectionRefusedError:
87 pass
88 except Exception as e:
89 if str(e) == "DETACH failed":
90 pass
91 else:
92 raise
93 del self.mon
94 self.mon = None
95
96 def close_monitor_global(self):
97 if not self.global_mon:
98 return
99 try:
100 while self.global_mon.pending():
101 ev = self.global_mon.recv()
102 logger.debug(self.global_dbg + ": " + ev)
103 except:
104 pass
105 try:
106 self.global_mon.detach()
107 except ConnectionRefusedError:
108 pass
109 except Exception as e:
110 if str(e) == "DETACH failed":
111 pass
112 else:
113 raise
114 del self.global_mon
115 self.global_mon = None
116
117 def close_monitor_group(self):
118 if not self.gctrl_mon:
119 return
120 try:
121 while self.gctrl_mon.pending():
122 ev = self.gctrl_mon.recv()
123 logger.debug(self.dbg + ": " + ev)
124 except:
125 pass
126 try:
127 self.gctrl_mon.detach()
128 except:
129 pass
130 del self.gctrl_mon
131 self.gctrl_mon = None
132
133 def close_monitor(self):
134 self.close_monitor_mon()
135 self.close_monitor_global()
136 self.close_monitor_group()
137
138 def cmd_execute(self, cmd_array, shell=False):
139 if self.hostname is None:
140 if shell:
141 cmd = ' '.join(cmd_array)
142 else:
143 cmd = cmd_array
144 proc = subprocess.Popen(cmd, stderr=subprocess.STDOUT,
145 stdout=subprocess.PIPE, shell=shell)
146 out = proc.communicate()[0]
147 ret = proc.returncode
148 return ret, out.decode()
149 else:
150 return self.host.execute(cmd_array)
151
152 def terminate(self):
153 if self.global_mon:
154 self.close_monitor_global()
155 self.global_ctrl.terminate()
156 self.global_ctrl = None
157
158 def close_ctrl(self):
159 self.close_monitor_global()
160 self.close_control_global()
161 self.remove_ifname()
162
163 def set_ifname(self, ifname, hostname=None, port=9877):
164 self.remove_ifname()
165 self.ifname = ifname
166 if hostname != None:
167 self.ctrl = wpaspy.Ctrl(hostname, port)
168 if self.monitor:
169 self.mon = wpaspy.Ctrl(hostname, port)
170 self.host = remotehost.Host(hostname, ifname)
171 self.dbg = hostname + "/" + ifname
172 else:
173 self.ctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
174 if self.monitor:
175 self.mon = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
176 self.dbg = ifname
177 if self.monitor:
178 self.mon.attach()
179
180 def remove_ifname(self):
181 self.close_monitor_mon()
182 self.close_control_ctrl()
183 self.ifname = None
184
185 def get_ctrl_iface_port(self, ifname):
186 if self.hostname is None:
187 return None
188
189 res = self.global_request("INTERFACES ctrl")
190 lines = res.splitlines()
191 found = False
192 for line in lines:
193 words = line.split()
194 if words[0] == ifname:
195 found = True
196 break
197 if not found:
198 raise Exception("Could not find UDP port for " + ifname)
199 res = line.find("ctrl_iface=udp:")
200 if res == -1:
201 raise Exception("Wrong ctrl_interface format")
202 words = line.split(":")
203 return int(words[1])
204
205 def interface_add(self, ifname, config="", driver="nl80211",
206 drv_params=None, br_ifname=None, create=False,
207 set_ifname=True, all_params=False, if_type=None):
208 status, groups = self.host.execute(["id"])
209 if status != 0:
210 group = "admin"
211 group = "admin" if "(admin)" in groups else "adm"
212 cmd = "INTERFACE_ADD " + ifname + "\t" + config + "\t" + driver + "\tDIR=/var/run/wpa_supplicant GROUP=" + group
213 if drv_params:
214 cmd = cmd + '\t' + drv_params
215 if br_ifname:
216 if not drv_params:
217 cmd += '\t'
218 cmd += '\t' + br_ifname
219 if create:
220 if not br_ifname:
221 cmd += '\t'
222 if not drv_params:
223 cmd += '\t'
224 cmd += '\tcreate'
225 if if_type:
226 cmd += '\t' + if_type
227 if all_params and not create:
228 if not br_ifname:
229 cmd += '\t'
230 if not drv_params:
231 cmd += '\t'
232 cmd += '\t'
233 if "FAIL" in self.global_request(cmd):
234 raise Exception("Failed to add a dynamic wpa_supplicant interface")
235 if not create and set_ifname:
236 port = self.get_ctrl_iface_port(ifname)
237 self.set_ifname(ifname, self.hostname, port)
238 res = self.get_driver_status()
239 if 'capa.flags' in res and int(res['capa.flags'], 0) & 0x20000000:
240 self.p2p_dev_ifname = 'p2p-dev-' + self.ifname
241 else:
242 self.p2p_dev_ifname = ifname
243
244 def interface_remove(self, ifname):
245 self.remove_ifname()
246 self.global_request("INTERFACE_REMOVE " + ifname)
247
248 def request(self, cmd, timeout=10):
249 logger.debug(self.dbg + ": CTRL: " + cmd)
250 return self.ctrl.request(cmd, timeout=timeout)
251
252 def global_request(self, cmd):
253 if self.global_iface is None:
254 return self.request(cmd)
255 else:
256 ifname = self.ifname or self.global_iface
257 logger.debug(self.global_dbg + ifname + ": CTRL(global): " + cmd)
258 return self.global_ctrl.request(cmd)
259
260 @property
261 def group_dbg(self):
262 if self._group_dbg is not None:
263 return self._group_dbg
264 if self.group_ifname is None:
265 raise Exception("Cannot have group_dbg without group_ifname")
266 if self.hostname is None:
267 self._group_dbg = self.group_ifname
268 else:
269 self._group_dbg = self.hostname + "/" + self.group_ifname
270 return self._group_dbg
271
272 def group_request(self, cmd):
273 if self.group_ifname and self.group_ifname != self.ifname:
274 if self.hostname is None:
275 gctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, self.group_ifname))
276 else:
277 port = self.get_ctrl_iface_port(self.group_ifname)
278 gctrl = wpaspy.Ctrl(self.hostname, port)
279 logger.debug(self.group_dbg + ": CTRL(group): " + cmd)
280 return gctrl.request(cmd)
281 return self.request(cmd)
282
283 def ping(self):
284 return "PONG" in self.request("PING")
285
286 def global_ping(self):
287 return "PONG" in self.global_request("PING")
288
289 def reset(self):
290 self.dump_monitor()
291 res = self.request("FLUSH")
292 if "OK" not in res:
293 logger.info("FLUSH to " + self.ifname + " failed: " + res)
294 self.global_request("REMOVE_NETWORK all")
295 self.global_request("SET p2p_no_group_iface 1")
296 self.global_request("P2P_FLUSH")
297 self.close_monitor_group()
298 self.group_ifname = None
299 self.dump_monitor()
300
301 iter = 0
302 while iter < 60:
303 state1 = self.get_driver_status_field("scan_state")
304 p2pdev = "p2p-dev-" + self.ifname
305 state2 = self.get_driver_status_field("scan_state", ifname=p2pdev)
306 states = str(state1) + " " + str(state2)
307 if "SCAN_STARTED" in states or "SCAN_REQUESTED" in states:
308 logger.info(self.ifname + ": Waiting for scan operation to complete before continuing")
309 time.sleep(1)
310 else:
311 break
312 iter = iter + 1
313 if iter == 60:
314 logger.error(self.ifname + ": Driver scan state did not clear")
315 print("Trying to clear cfg80211/mac80211 scan state")
316 status, buf = self.host.execute(["ifconfig", self.ifname, "down"])
317 if status != 0:
318 logger.info("ifconfig failed: " + buf)
319 logger.info(status)
320 status, buf = self.host.execute(["ifconfig", self.ifname, "up"])
321 if status != 0:
322 logger.info("ifconfig failed: " + buf)
323 logger.info(status)
324 if iter > 0:
325 # The ongoing scan could have discovered BSSes or P2P peers
326 logger.info("Run FLUSH again since scan was in progress")
327 self.request("FLUSH")
328 self.dump_monitor()
329
330 if not self.ping():
331 logger.info("No PING response from " + self.ifname + " after reset")
332
333 def set(self, field, value, allow_fail=False):
334 if "OK" not in self.request("SET " + field + " " + value):
335 if allow_fail:
336 return
337 raise Exception("Failed to set wpa_supplicant parameter " + field)
338
339 def add_network(self):
340 id = self.request("ADD_NETWORK")
341 if "FAIL" in id:
342 raise Exception("ADD_NETWORK failed")
343 return int(id)
344
345 def remove_network(self, id):
346 id = self.request("REMOVE_NETWORK " + str(id))
347 if "FAIL" in id:
348 raise Exception("REMOVE_NETWORK failed")
349 return None
350
351 def get_network(self, id, field):
352 res = self.request("GET_NETWORK " + str(id) + " " + field)
353 if res == "FAIL\n":
354 return None
355 return res
356
357 def set_network(self, id, field, value):
358 res = self.request("SET_NETWORK " + str(id) + " " + field + " " + value)
359 if "FAIL" in res:
360 raise Exception("SET_NETWORK failed")
361 return None
362
363 def set_network_quoted(self, id, field, value):
364 res = self.request("SET_NETWORK " + str(id) + " " + field + ' "' + value + '"')
365 if "FAIL" in res:
366 raise Exception("SET_NETWORK failed")
367 return None
368
369 def p2pdev_request(self, cmd):
370 return self.global_request("IFNAME=" + self.p2p_dev_ifname + " " + cmd)
371
372 def p2pdev_add_network(self):
373 id = self.p2pdev_request("ADD_NETWORK")
374 if "FAIL" in id:
375 raise Exception("p2pdev ADD_NETWORK failed")
376 return int(id)
377
378 def p2pdev_set_network(self, id, field, value):
379 res = self.p2pdev_request("SET_NETWORK " + str(id) + " " + field + " " + value)
380 if "FAIL" in res:
381 raise Exception("p2pdev SET_NETWORK failed")
382 return None
383
384 def p2pdev_set_network_quoted(self, id, field, value):
385 res = self.p2pdev_request("SET_NETWORK " + str(id) + " " + field + ' "' + value + '"')
386 if "FAIL" in res:
387 raise Exception("p2pdev SET_NETWORK failed")
388 return None
389
390 def list_networks(self, p2p=False):
391 if p2p:
392 res = self.global_request("LIST_NETWORKS")
393 else:
394 res = self.request("LIST_NETWORKS")
395 lines = res.splitlines()
396 networks = []
397 for l in lines:
398 if "network id" in l:
399 continue
400 [id, ssid, bssid, flags] = l.split('\t')
401 network = {}
402 network['id'] = id
403 network['ssid'] = ssid
404 network['bssid'] = bssid
405 network['flags'] = flags
406 networks.append(network)
407 return networks
408
409 def hs20_enable(self, auto_interworking=False):
410 self.request("SET interworking 1")
411 self.request("SET hs20 1")
412 if auto_interworking:
413 self.request("SET auto_interworking 1")
414 else:
415 self.request("SET auto_interworking 0")
416
417 def interworking_add_network(self, bssid):
418 id = self.request("INTERWORKING_ADD_NETWORK " + bssid)
419 if "FAIL" in id or "OK" in id:
420 raise Exception("INTERWORKING_ADD_NETWORK failed")
421 return int(id)
422
423 def add_cred(self):
424 id = self.request("ADD_CRED")
425 if "FAIL" in id:
426 raise Exception("ADD_CRED failed")
427 return int(id)
428
429 def remove_cred(self, id):
430 id = self.request("REMOVE_CRED " + str(id))
431 if "FAIL" in id:
432 raise Exception("REMOVE_CRED failed")
433 return None
434
435 def set_cred(self, id, field, value):
436 res = self.request("SET_CRED " + str(id) + " " + field + " " + value)
437 if "FAIL" in res:
438 raise Exception("SET_CRED failed")
439 return None
440
441 def set_cred_quoted(self, id, field, value):
442 res = self.request("SET_CRED " + str(id) + " " + field + ' "' + value + '"')
443 if "FAIL" in res:
444 raise Exception("SET_CRED failed")
445 return None
446
447 def get_cred(self, id, field):
448 return self.request("GET_CRED " + str(id) + " " + field)
449
450 def add_cred_values(self, params):
451 id = self.add_cred()
452
453 quoted = ["realm", "username", "password", "domain", "imsi",
454 "excluded_ssid", "milenage", "ca_cert", "client_cert",
455 "private_key", "domain_suffix_match", "provisioning_sp",
456 "roaming_partner", "phase1", "phase2", "private_key_passwd",
457 "roaming_consortiums", "imsi_privacy_cert",
458 "imsi_privacy_attr"]
459 for field in quoted:
460 if field in params:
461 self.set_cred_quoted(id, field, params[field])
462
463 not_quoted = ["eap", "roaming_consortium", "priority",
464 "required_roaming_consortium", "sp_priority",
465 "max_bss_load", "update_identifier", "req_conn_capab",
466 "min_dl_bandwidth_home", "min_ul_bandwidth_home",
467 "min_dl_bandwidth_roaming", "min_ul_bandwidth_roaming"]
468 for field in not_quoted:
469 if field in params:
470 self.set_cred(id, field, params[field])
471
472 as_list = ["home_ois", "required_home_ois"]
473 for field in as_list:
474 if field in params:
475 self.set_cred_quoted(id, field, ','.join(params[field]))
476
477 return id
478
479 def select_network(self, id, freq=None):
480 if freq:
481 extra = " freq=" + str(freq)
482 else:
483 extra = ""
484 id = self.request("SELECT_NETWORK " + str(id) + extra)
485 if "FAIL" in id:
486 raise Exception("SELECT_NETWORK failed")
487 return None
488
489 def mesh_group_add(self, id):
490 id = self.request("MESH_GROUP_ADD " + str(id))
491 if "FAIL" in id:
492 raise Exception("MESH_GROUP_ADD failed")
493 return None
494
495 def mesh_group_remove(self):
496 id = self.request("MESH_GROUP_REMOVE " + str(self.ifname))
497 if "FAIL" in id:
498 raise Exception("MESH_GROUP_REMOVE failed")
499 return None
500
501 def connect_network(self, id, timeout=None):
502 if timeout is None:
503 timeout = 10 if self.hostname is None else 60
504 self.dump_monitor()
505 self.select_network(id)
506 self.wait_connected(timeout=timeout)
507 self.dump_monitor()
508
509 def get_status(self, extra=None):
510 if extra:
511 extra = "-" + extra
512 else:
513 extra = ""
514 res = self.request("STATUS" + extra)
515 lines = res.splitlines()
516 vals = dict()
517 for l in lines:
518 try:
519 [name, value] = l.split('=', 1)
520 vals[name] = value
521 except ValueError as e:
522 logger.info(self.ifname + ": Ignore unexpected STATUS line: " + l)
523 return vals
524
525 def get_status_field(self, field, extra=None):
526 vals = self.get_status(extra)
527 if field in vals:
528 return vals[field]
529 return None
530
531 def get_group_status(self, extra=None):
532 if extra:
533 extra = "-" + extra
534 else:
535 extra = ""
536 res = self.group_request("STATUS" + extra)
537 lines = res.splitlines()
538 vals = dict()
539 for l in lines:
540 try:
541 [name, value] = l.split('=', 1)
542 except ValueError:
543 logger.info(self.ifname + ": Ignore unexpected status line: " + l)
544 continue
545 vals[name] = value
546 return vals
547
548 def get_group_status_field(self, field, extra=None):
549 vals = self.get_group_status(extra)
550 if field in vals:
551 return vals[field]
552 return None
553
554 def get_driver_status(self, ifname=None):
555 if ifname is None:
556 res = self.request("STATUS-DRIVER")
557 else:
558 res = self.global_request("IFNAME=%s STATUS-DRIVER" % ifname)
559 if res.startswith("FAIL"):
560 return dict()
561 lines = res.splitlines()
562 vals = dict()
563 for l in lines:
564 try:
565 [name, value] = l.split('=', 1)
566 except ValueError:
567 logger.info(self.ifname + ": Ignore unexpected status-driver line: " + l)
568 continue
569 vals[name] = value
570 return vals
571
572 def get_driver_status_field(self, field, ifname=None):
573 vals = self.get_driver_status(ifname)
574 if field in vals:
575 return vals[field]
576 return None
577
578 def get_mcc(self):
579 mcc = int(self.get_driver_status_field('capa.num_multichan_concurrent'))
580 return 1 if mcc < 2 else mcc
581
582 def get_mib(self):
583 res = self.request("MIB")
584 lines = res.splitlines()
585 vals = dict()
586 for l in lines:
587 try:
588 [name, value] = l.split('=', 1)
589 vals[name] = value
590 except ValueError as e:
591 logger.info(self.ifname + ": Ignore unexpected MIB line: " + l)
592 return vals
593
594 def p2p_dev_addr(self):
595 return self.get_status_field("p2p_device_address")
596
597 def p2p_interface_addr(self):
598 return self.get_group_status_field("address")
599
600 def own_addr(self):
601 try:
602 res = self.p2p_interface_addr()
603 except:
604 res = self.p2p_dev_addr()
605 return res
606
607 def get_addr(self, group=False):
608 dev_addr = self.own_addr()
609 if not group:
610 addr = self.get_status_field('address')
611 if addr:
612 dev_addr = addr
613
614 return dev_addr
615
616 def p2p_listen(self):
617 return self.global_request("P2P_LISTEN")
618
619 def p2p_ext_listen(self, period, interval):
620 return self.global_request("P2P_EXT_LISTEN %d %d" % (period, interval))
621
622 def p2p_cancel_ext_listen(self):
623 return self.global_request("P2P_EXT_LISTEN")
624
625 def p2p_find(self, social=False, progressive=False, dev_id=None,
626 dev_type=None, delay=None, freq=None):
627 cmd = "P2P_FIND"
628 if social:
629 cmd = cmd + " type=social"
630 elif progressive:
631 cmd = cmd + " type=progressive"
632 if dev_id:
633 cmd = cmd + " dev_id=" + dev_id
634 if dev_type:
635 cmd = cmd + " dev_type=" + dev_type
636 if delay:
637 cmd = cmd + " delay=" + str(delay)
638 if freq:
639 cmd = cmd + " freq=" + str(freq)
640 return self.global_request(cmd)
641
642 def p2p_stop_find(self):
643 return self.global_request("P2P_STOP_FIND")
644
645 def wps_read_pin(self):
646 self.pin = self.request("WPS_PIN get").rstrip("\n")
647 if "FAIL" in self.pin:
648 raise Exception("Could not generate PIN")
649 return self.pin
650
651 def peer_known(self, peer, full=True):
652 res = self.global_request("P2P_PEER " + peer)
653 if peer.lower() not in res.lower():
654 return False
655 if not full:
656 return True
657 return "[PROBE_REQ_ONLY]" not in res
658
659 def discover_peer(self, peer, full=True, timeout=15, social=True,
660 force_find=False, freq=None):
661 logger.info(self.ifname + ": Trying to discover peer " + peer)
662 if not force_find and self.peer_known(peer, full):
663 return True
664 self.p2p_find(social, freq=freq)
665 count = 0
666 while count < timeout * 4:
667 time.sleep(0.25)
668 count = count + 1
669 if self.peer_known(peer, full):
670 return True
671 return False
672
673 def get_peer(self, peer):
674 res = self.global_request("P2P_PEER " + peer)
675 if peer.lower() not in res.lower():
676 raise Exception("Peer information not available")
677 lines = res.splitlines()
678 vals = dict()
679 for l in lines:
680 if '=' in l:
681 [name, value] = l.split('=', 1)
682 vals[name] = value
683 return vals
684
685 def group_form_result(self, ev, expect_failure=False, go_neg_res=None):
686 if expect_failure:
687 if "P2P-GROUP-STARTED" in ev:
688 raise Exception("Group formation succeeded when expecting failure")
689 exp = r'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
690 s = re.split(exp, ev)
691 if len(s) < 3:
692 return None
693 res = {}
694 res['result'] = 'go-neg-failed'
695 res['status'] = int(s[2])
696 return res
697
698 if "P2P-GROUP-STARTED" not in ev:
699 raise Exception("No P2P-GROUP-STARTED event seen")
700
701 exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*) ip_addr=([0-9.]*) ip_mask=([0-9.]*) go_ip_addr=([0-9.]*)'
702 s = re.split(exp, ev)
703 if len(s) < 11:
704 exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
705 s = re.split(exp, ev)
706 if len(s) < 8:
707 raise Exception("Could not parse P2P-GROUP-STARTED")
708 res = {}
709 res['result'] = 'success'
710 res['ifname'] = s[2]
711 self.group_ifname = s[2]
712 try:
713 if self.hostname is None:
714 self.gctrl_mon = wpaspy.Ctrl(os.path.join(wpas_ctrl,
715 self.group_ifname))
716 else:
717 port = self.get_ctrl_iface_port(self.group_ifname)
718 self.gctrl_mon = wpaspy.Ctrl(self.hostname, port)
719 if self.monitor:
720 self.gctrl_mon.attach()
721 except:
722 logger.debug("Could not open monitor socket for group interface")
723 self.gctrl_mon = None
724 res['role'] = s[3]
725 res['ssid'] = s[4]
726 res['freq'] = s[5]
727 if "[PERSISTENT]" in ev:
728 res['persistent'] = True
729 else:
730 res['persistent'] = False
731 p = re.match(r'psk=([0-9a-f]*)', s[6])
732 if p:
733 res['psk'] = p.group(1)
734 p = re.match(r'passphrase="(.*)"', s[6])
735 if p:
736 res['passphrase'] = p.group(1)
737 res['go_dev_addr'] = s[7]
738
739 if len(s) > 8 and len(s[8]) > 0 and "[PERSISTENT]" not in s[8]:
740 res['ip_addr'] = s[8]
741 if len(s) > 9:
742 res['ip_mask'] = s[9]
743 if len(s) > 10:
744 res['go_ip_addr'] = s[10]
745
746 if go_neg_res:
747 exp = r'<.>(P2P-GO-NEG-SUCCESS) role=(GO|client) freq=([0-9]*)'
748 s = re.split(exp, go_neg_res)
749 if len(s) < 4:
750 raise Exception("Could not parse P2P-GO-NEG-SUCCESS")
751 res['go_neg_role'] = s[2]
752 res['go_neg_freq'] = s[3]
753
754 return res
755
756 def p2p_go_neg_auth(self, peer, pin, method, go_intent=None,
757 persistent=False, freq=None, freq2=None,
758 max_oper_chwidth=None, ht40=False, vht=False):
759 if not self.discover_peer(peer):
760 raise Exception("Peer " + peer + " not found")
761 self.dump_monitor()
762 if pin:
763 cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
764 else:
765 cmd = "P2P_CONNECT " + peer + " " + method + " auth"
766 if go_intent:
767 cmd = cmd + ' go_intent=' + str(go_intent)
768 if freq:
769 cmd = cmd + ' freq=' + str(freq)
770 if freq2:
771 cmd = cmd + ' freq2=' + str(freq2)
772 if max_oper_chwidth:
773 cmd = cmd + ' max_oper_chwidth=' + str(max_oper_chwidth)
774 if ht40:
775 cmd = cmd + ' ht40'
776 if vht:
777 cmd = cmd + ' vht'
778 if persistent:
779 cmd = cmd + " persistent"
780 if "OK" in self.global_request(cmd):
781 return None
782 raise Exception("P2P_CONNECT (auth) failed")
783
784 def p2p_go_neg_auth_result(self, timeout=None, expect_failure=False):
785 if timeout is None:
786 timeout = 1 if expect_failure else 5
787 go_neg_res = None
788 ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
789 "P2P-GO-NEG-FAILURE"], timeout)
790 if ev is None:
791 if expect_failure:
792 return None
793 raise Exception("Group formation timed out")
794 if "P2P-GO-NEG-SUCCESS" in ev:
795 go_neg_res = ev
796 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
797 if ev is None:
798 if expect_failure:
799 return None
800 raise Exception("Group formation timed out")
801 self.dump_monitor()
802 return self.group_form_result(ev, expect_failure, go_neg_res)
803
804 def p2p_go_neg_init(self, peer, pin, method, timeout=0, go_intent=None,
805 expect_failure=False, persistent=False,
806 persistent_id=None, freq=None, provdisc=False,
807 wait_group=True, freq2=None, max_oper_chwidth=None,
808 ht40=False, vht=False):
809 if not self.discover_peer(peer):
810 raise Exception("Peer " + peer + " not found")
811 self.dump_monitor()
812 if pin:
813 cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
814 else:
815 cmd = "P2P_CONNECT " + peer + " " + method
816 if go_intent is not None:
817 cmd = cmd + ' go_intent=' + str(go_intent)
818 if freq:
819 cmd = cmd + ' freq=' + str(freq)
820 if freq2:
821 cmd = cmd + ' freq2=' + str(freq2)
822 if max_oper_chwidth:
823 cmd = cmd + ' max_oper_chwidth=' + str(max_oper_chwidth)
824 if ht40:
825 cmd = cmd + ' ht40'
826 if vht:
827 cmd = cmd + ' vht'
828 if persistent:
829 cmd = cmd + " persistent"
830 elif persistent_id:
831 cmd = cmd + " persistent=" + persistent_id
832 if provdisc:
833 cmd = cmd + " provdisc"
834 if "OK" in self.global_request(cmd):
835 if timeout == 0:
836 return None
837 go_neg_res = None
838 ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
839 "P2P-GO-NEG-FAILURE"], timeout)
840 if ev is None:
841 if expect_failure:
842 return None
843 raise Exception("Group formation timed out")
844 if "P2P-GO-NEG-SUCCESS" in ev:
845 if not wait_group:
846 return ev
847 go_neg_res = ev
848 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
849 if ev is None:
850 if expect_failure:
851 return None
852 raise Exception("Group formation timed out")
853 self.dump_monitor()
854 return self.group_form_result(ev, expect_failure, go_neg_res)
855 raise Exception("P2P_CONNECT failed")
856
857 def _wait_event(self, mon, pfx, events, timeout):
858 if not isinstance(events, list):
859 raise Exception("WpaSupplicant._wait_event() called with incorrect events argument type")
860 start = os.times()[4]
861 while True:
862 while mon.pending():
863 ev = mon.recv()
864 logger.debug(self.dbg + pfx + ev)
865 for event in events:
866 if event in ev:
867 return ev
868 now = os.times()[4]
869 remaining = start + timeout - now
870 if remaining <= 0:
871 break
872 if not mon.pending(timeout=remaining):
873 break
874 return None
875
876 def wait_event(self, events, timeout=10):
877 return self._wait_event(self.mon, ": ", events, timeout)
878
879 def wait_global_event(self, events, timeout):
880 if self.global_iface is None:
881 return self.wait_event(events, timeout)
882 return self._wait_event(self.global_mon, "(global): ",
883 events, timeout)
884
885 def wait_group_event(self, events, timeout=10):
886 if not isinstance(events, list):
887 raise Exception("WpaSupplicant.wait_group_event() called with incorrect events argument type")
888 if self.group_ifname and self.group_ifname != self.ifname:
889 if self.gctrl_mon is None:
890 return None
891 start = os.times()[4]
892 while True:
893 while self.gctrl_mon.pending():
894 ev = self.gctrl_mon.recv()
895 logger.debug(self.group_dbg + "(group): " + ev)
896 for event in events:
897 if event in ev:
898 return ev
899 now = os.times()[4]
900 remaining = start + timeout - now
901 if remaining <= 0:
902 break
903 if not self.gctrl_mon.pending(timeout=remaining):
904 break
905 return None
906
907 return self.wait_event(events, timeout)
908
909 def wait_go_ending_session(self):
910 self.close_monitor_group()
911 timeout = 3 if self.hostname is None else 10
912 ev = self.wait_global_event(["P2P-GROUP-REMOVED"], timeout=timeout)
913 if ev is None:
914 raise Exception("Group removal event timed out")
915 if "reason=GO_ENDING_SESSION" not in ev:
916 raise Exception("Unexpected group removal reason")
917
918 def dump_monitor(self, mon=True, global_mon=True):
919 count_iface = 0
920 count_global = 0
921 while mon and self.monitor and self.mon.pending():
922 ev = self.mon.recv()
923 logger.debug(self.dbg + ": " + ev)
924 count_iface += 1
925 while global_mon and self.monitor and self.global_mon and self.global_mon.pending():
926 ev = self.global_mon.recv()
927 logger.debug(self.global_dbg + self.ifname + "(global): " + ev)
928 count_global += 1
929 return (count_iface, count_global)
930
931 def remove_group(self, ifname=None):
932 self.close_monitor_group()
933 if ifname is None:
934 ifname = self.group_ifname if self.group_ifname else self.ifname
935 if "OK" not in self.global_request("P2P_GROUP_REMOVE " + ifname):
936 raise Exception("Group could not be removed")
937 self.group_ifname = None
938
939 def p2p_start_go(self, persistent=None, freq=None, no_event_clear=False):
940 self.dump_monitor()
941 cmd = "P2P_GROUP_ADD"
942 if persistent is None:
943 pass
944 elif persistent is True:
945 cmd = cmd + " persistent"
946 else:
947 cmd = cmd + " persistent=" + str(persistent)
948 if freq:
949 cmd = cmd + " freq=" + str(freq)
950 if "OK" in self.global_request(cmd):
951 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
952 if ev is None:
953 raise Exception("GO start up timed out")
954 if not no_event_clear:
955 self.dump_monitor()
956 return self.group_form_result(ev)
957 raise Exception("P2P_GROUP_ADD failed")
958
959 def p2p_go_authorize_client(self, pin):
960 cmd = "WPS_PIN any " + pin
961 if "FAIL" in self.group_request(cmd):
962 raise Exception("Failed to authorize client connection on GO")
963 return None
964
965 def p2p_go_authorize_client_pbc(self):
966 cmd = "WPS_PBC"
967 if "FAIL" in self.group_request(cmd):
968 raise Exception("Failed to authorize client connection on GO")
969 return None
970
971 def p2p_connect_group(self, go_addr, pin, timeout=0, social=False,
972 freq=None):
973 self.dump_monitor()
974 if not self.discover_peer(go_addr, social=social, freq=freq):
975 if social or not self.discover_peer(go_addr, social=social):
976 raise Exception("GO " + go_addr + " not found")
977 self.p2p_stop_find()
978 self.dump_monitor()
979 cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
980 if freq:
981 cmd += " freq=" + str(freq)
982 if "OK" in self.global_request(cmd):
983 if timeout == 0:
984 self.dump_monitor()
985 return None
986 ev = self.wait_global_event(["P2P-GROUP-STARTED",
987 "P2P-GROUP-FORMATION-FAILURE"],
988 timeout)
989 if ev is None:
990 raise Exception("Joining the group timed out")
991 if "P2P-GROUP-STARTED" not in ev:
992 raise Exception("Failed to join the group")
993 self.dump_monitor()
994 return self.group_form_result(ev)
995 raise Exception("P2P_CONNECT(join) failed")
996
997 def tdls_setup(self, peer):
998 cmd = "TDLS_SETUP " + peer
999 if "FAIL" in self.group_request(cmd):
1000 raise Exception("Failed to request TDLS setup")
1001 return None
1002
1003 def tdls_teardown(self, peer):
1004 cmd = "TDLS_TEARDOWN " + peer
1005 if "FAIL" in self.group_request(cmd):
1006 raise Exception("Failed to request TDLS teardown")
1007 return None
1008
1009 def tdls_link_status(self, peer):
1010 cmd = "TDLS_LINK_STATUS " + peer
1011 ret = self.group_request(cmd)
1012 if "FAIL" in ret:
1013 raise Exception("Failed to request TDLS link status")
1014 return ret
1015
1016 def tspecs(self):
1017 """Return (tsid, up) tuples representing current tspecs"""
1018 res = self.request("WMM_AC_STATUS")
1019 tspecs = re.findall(r"TSID=(\d+) UP=(\d+)", res)
1020 tspecs = [tuple(map(int, tspec)) for tspec in tspecs]
1021
1022 logger.debug("tspecs: " + str(tspecs))
1023 return tspecs
1024
1025 def add_ts(self, tsid, up, direction="downlink", expect_failure=False,
1026 extra=None):
1027 params = {
1028 "sba": 9000,
1029 "nominal_msdu_size": 1500,
1030 "min_phy_rate": 6000000,
1031 "mean_data_rate": 1500,
1032 }
1033 cmd = "WMM_AC_ADDTS %s tsid=%d up=%d" % (direction, tsid, up)
1034 for (key, value) in params.items():
1035 cmd += " %s=%d" % (key, value)
1036 if extra:
1037 cmd += " " + extra
1038
1039 if self.request(cmd).strip() != "OK":
1040 raise Exception("ADDTS failed (tsid=%d up=%d)" % (tsid, up))
1041
1042 if expect_failure:
1043 ev = self.wait_event(["TSPEC-REQ-FAILED"], timeout=2)
1044 if ev is None:
1045 raise Exception("ADDTS failed (time out while waiting failure)")
1046 if "tsid=%d" % (tsid) not in ev:
1047 raise Exception("ADDTS failed (invalid tsid in TSPEC-REQ-FAILED")
1048 return
1049
1050 ev = self.wait_event(["TSPEC-ADDED"], timeout=1)
1051 if ev is None:
1052 raise Exception("ADDTS failed (time out)")
1053 if "tsid=%d" % (tsid) not in ev:
1054 raise Exception("ADDTS failed (invalid tsid in TSPEC-ADDED)")
1055
1056 if (tsid, up) not in self.tspecs():
1057 raise Exception("ADDTS failed (tsid not in tspec list)")
1058
1059 def del_ts(self, tsid):
1060 if self.request("WMM_AC_DELTS %d" % (tsid)).strip() != "OK":
1061 raise Exception("DELTS failed")
1062
1063 ev = self.wait_event(["TSPEC-REMOVED"], timeout=1)
1064 if ev is None:
1065 raise Exception("DELTS failed (time out)")
1066 if "tsid=%d" % (tsid) not in ev:
1067 raise Exception("DELTS failed (invalid tsid in TSPEC-REMOVED)")
1068
1069 tspecs = [(t, u) for (t, u) in self.tspecs() if t == tsid]
1070 if tspecs:
1071 raise Exception("DELTS failed (still in tspec list)")
1072
1073 def connect(self, ssid=None, ssid2=None, **kwargs):
1074 logger.info("Connect STA " + self.ifname + " to AP")
1075 id = self.add_network()
1076 if ssid:
1077 self.set_network_quoted(id, "ssid", ssid)
1078 elif ssid2:
1079 self.set_network(id, "ssid", ssid2)
1080
1081 quoted = ["psk", "identity", "anonymous_identity", "password",
1082 "machine_identity", "machine_password",
1083 "ca_cert", "client_cert", "private_key",
1084 "private_key_passwd", "ca_cert2", "client_cert2",
1085 "private_key2", "phase1", "phase2", "domain_suffix_match",
1086 "altsubject_match", "subject_match", "pac_file",
1087 "bgscan", "ht_mcs", "id_str", "openssl_ciphers",
1088 "domain_match", "dpp_connector", "sae_password",
1089 "sae_password_id", "check_cert_subject",
1090 "machine_ca_cert", "machine_client_cert",
1091 "machine_private_key", "machine_phase2",
1092 "imsi_identity", "imsi_privacy_cert", "imsi_privacy_attr"]
1093 for field in quoted:
1094 if field in kwargs and kwargs[field]:
1095 self.set_network_quoted(id, field, kwargs[field])
1096
1097 not_quoted = ["proto", "key_mgmt", "ieee80211w", "pairwise",
1098 "group", "wep_key0", "wep_key1", "wep_key2", "wep_key3",
1099 "wep_tx_keyidx", "scan_freq", "freq_list", "eap",
1100 "eapol_flags", "fragment_size", "scan_ssid", "auth_alg",
1101 "wpa_ptk_rekey", "disable_ht", "disable_vht", "bssid",
1102 "disable_he",
1103 "disable_max_amsdu", "ampdu_factor", "ampdu_density",
1104 "disable_ht40", "disable_sgi", "disable_ldpc",
1105 "ht40_intolerant", "update_identifier", "mac_addr",
1106 "erp", "bg_scan_period", "bssid_ignore",
1107 "bssid_accept", "mem_only_psk", "eap_workaround",
1108 "engine", "fils_dh_group", "bssid_hint",
1109 "dpp_csign", "dpp_csign_expiry",
1110 "dpp_netaccesskey", "dpp_netaccesskey_expiry", "dpp_pfs",
1111 "dpp_connector_privacy",
1112 "group_mgmt", "owe_group", "owe_only",
1113 "owe_ptk_workaround",
1114 "transition_disable", "sae_pk",
1115 "roaming_consortium_selection", "ocv",
1116 "multi_ap_backhaul_sta", "rx_stbc", "tx_stbc",
1117 "ft_eap_pmksa_caching", "beacon_prot",
1118 "mac_value",
1119 "wpa_deny_ptk0_rekey",
1120 "enable_4addr_mode"]
1121 for field in not_quoted:
1122 if field in kwargs and kwargs[field]:
1123 self.set_network(id, field, kwargs[field])
1124
1125 known_args = {"raw_psk", "password_hex", "peerkey", "okc", "ocsp",
1126 "only_add_network", "wait_connect", "raw_identity"}
1127 unknown = set(kwargs.keys())
1128 unknown -= set(quoted)
1129 unknown -= set(not_quoted)
1130 unknown -= known_args
1131 if unknown:
1132 raise Exception("Unknown WpaSupplicant::connect() arguments: " + str(unknown))
1133
1134 if "raw_identity" in kwargs and kwargs['raw_identity']:
1135 self.set_network(id, "identity", kwargs['raw_identity'])
1136 if "raw_psk" in kwargs and kwargs['raw_psk']:
1137 self.set_network(id, "psk", kwargs['raw_psk'])
1138 if "password_hex" in kwargs and kwargs['password_hex']:
1139 self.set_network(id, "password", kwargs['password_hex'])
1140 if "peerkey" in kwargs and kwargs['peerkey']:
1141 self.set_network(id, "peerkey", "1")
1142 if "okc" in kwargs and kwargs['okc']:
1143 self.set_network(id, "proactive_key_caching", "1")
1144 if "ocsp" in kwargs and kwargs['ocsp']:
1145 self.set_network(id, "ocsp", str(kwargs['ocsp']))
1146 if "only_add_network" in kwargs and kwargs['only_add_network']:
1147 return id
1148 if "wait_connect" not in kwargs or kwargs['wait_connect']:
1149 if "eap" in kwargs:
1150 self.connect_network(id, timeout=20)
1151 else:
1152 self.connect_network(id, timeout=15)
1153 else:
1154 self.dump_monitor()
1155 self.select_network(id)
1156 return id
1157
1158 def scan(self, type=None, freq=None, no_wait=False, only_new=False,
1159 passive=False, timeout=15):
1160 if not no_wait:
1161 self.dump_monitor()
1162 if type:
1163 cmd = "SCAN TYPE=" + type
1164 else:
1165 cmd = "SCAN"
1166 if freq:
1167 cmd = cmd + " freq=" + str(freq)
1168 if only_new:
1169 cmd += " only_new=1"
1170 if passive:
1171 cmd += " passive=1"
1172 if not no_wait:
1173 self.dump_monitor()
1174 res = self.request(cmd)
1175 if "OK" not in res:
1176 raise Exception("Failed to trigger scan: " + str(res))
1177 if no_wait:
1178 return
1179 ev = self.wait_event(["CTRL-EVENT-SCAN-RESULTS",
1180 "CTRL-EVENT-SCAN-FAILED"], timeout)
1181 if ev is None:
1182 raise Exception("Scan timed out")
1183 if "CTRL-EVENT-SCAN-FAILED" in ev:
1184 raise Exception("Scan failed: " + ev)
1185
1186 def scan_for_bss(self, bssid, freq=None, force_scan=False, only_new=False,
1187 passive=False):
1188 if not force_scan and self.get_bss(bssid) is not None:
1189 return
1190 for i in range(0, 10):
1191 self.scan(freq=freq, type="ONLY", only_new=only_new,
1192 passive=passive)
1193 if self.get_bss(bssid) is not None:
1194 return
1195 raise Exception("Could not find BSS " + bssid + " in scan")
1196
1197 def flush_scan_cache(self, freq=2417):
1198 self.request("BSS_FLUSH 0")
1199 self.scan(freq=freq, only_new=True)
1200 res = self.request("SCAN_RESULTS")
1201 if len(res.splitlines()) > 1:
1202 logger.debug("Scan results remaining after first attempt to flush the results:\n" + res)
1203 self.request("BSS_FLUSH 0")
1204 self.scan(freq=2422, only_new=True)
1205 res = self.request("SCAN_RESULTS")
1206 if len(res.splitlines()) > 1:
1207 logger.info("flush_scan_cache: Could not clear all BSS entries. These remain:\n" + res)
1208
1209 def disconnect_and_stop_scan(self):
1210 self.request("DISCONNECT")
1211 res = self.request("ABORT_SCAN")
1212 for i in range(2 if "OK" in res else 1):
1213 self.wait_event(["CTRL-EVENT-DISCONNECTED",
1214 "CTRL-EVENT-SCAN-RESULTS"], timeout=0.5)
1215 self.dump_monitor()
1216
1217 def roam(self, bssid, fail_test=False, assoc_reject_ok=False,
1218 check_bssid=True):
1219 self.dump_monitor()
1220 if "OK" not in self.request("ROAM " + bssid):
1221 raise Exception("ROAM failed")
1222 if fail_test:
1223 if assoc_reject_ok:
1224 ev = self.wait_event(["CTRL-EVENT-CONNECTED",
1225 "CTRL-EVENT-DISCONNECTED",
1226 "CTRL-EVENT-ASSOC-REJECT"], timeout=1)
1227 else:
1228 ev = self.wait_event(["CTRL-EVENT-CONNECTED",
1229 "CTRL-EVENT-DISCONNECTED"], timeout=1)
1230 if ev and "CTRL-EVENT-DISCONNECTED" in ev:
1231 self.dump_monitor()
1232 return
1233 if ev is not None and "CTRL-EVENT-ASSOC-REJECT" not in ev:
1234 raise Exception("Unexpected connection")
1235 self.dump_monitor()
1236 return
1237 if assoc_reject_ok:
1238 ev = self.wait_event(["CTRL-EVENT-CONNECTED",
1239 "CTRL-EVENT-DISCONNECTED"], timeout=10)
1240 else:
1241 ev = self.wait_event(["CTRL-EVENT-CONNECTED",
1242 "CTRL-EVENT-DISCONNECTED",
1243 "CTRL-EVENT-ASSOC-REJECT"], timeout=10)
1244 if ev is None:
1245 raise Exception("Roaming with the AP timed out")
1246 if "CTRL-EVENT-ASSOC-REJECT" in ev:
1247 raise Exception("Roaming association rejected")
1248 if "CTRL-EVENT-DISCONNECTED" in ev:
1249 raise Exception("Unexpected disconnection when waiting for roam to complete")
1250 self.dump_monitor()
1251 if check_bssid and self.get_status_field('bssid') != bssid:
1252 raise Exception("Did not roam to correct BSSID")
1253
1254 def roam_over_ds(self, bssid, fail_test=False, force=False):
1255 self.dump_monitor()
1256 cmd = "FT_DS " + bssid
1257 if force:
1258 cmd += " force"
1259 if "OK" not in self.request(cmd):
1260 raise Exception("FT_DS failed")
1261 if fail_test:
1262 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
1263 if ev is not None:
1264 raise Exception("Unexpected connection")
1265 self.dump_monitor()
1266 return
1267 ev = self.wait_event(["CTRL-EVENT-CONNECTED",
1268 "CTRL-EVENT-ASSOC-REJECT"], timeout=10)
1269 if ev is None:
1270 raise Exception("Roaming with the AP timed out")
1271 if "CTRL-EVENT-ASSOC-REJECT" in ev:
1272 raise Exception("Roaming association rejected")
1273 self.dump_monitor()
1274
1275 def wps_reg(self, bssid, pin, new_ssid=None, key_mgmt=None, cipher=None,
1276 new_passphrase=None, no_wait=False):
1277 self.dump_monitor()
1278 if new_ssid:
1279 self.request("WPS_REG " + bssid + " " + pin + " " +
1280 binascii.hexlify(new_ssid.encode()).decode() + " " +
1281 key_mgmt + " " + cipher + " " +
1282 binascii.hexlify(new_passphrase.encode()).decode())
1283 if no_wait:
1284 return
1285 ev = self.wait_event(["WPS-SUCCESS"], timeout=15)
1286 else:
1287 self.request("WPS_REG " + bssid + " " + pin)
1288 if no_wait:
1289 return
1290 ev = self.wait_event(["WPS-CRED-RECEIVED"], timeout=15)
1291 if ev is None:
1292 raise Exception("WPS cred timed out")
1293 ev = self.wait_event(["WPS-FAIL"], timeout=15)
1294 if ev is None:
1295 raise Exception("WPS timed out")
1296 self.wait_connected(timeout=15)
1297
1298 def relog(self):
1299 self.global_request("RELOG")
1300
1301 def wait_completed(self, timeout=10):
1302 for i in range(0, timeout * 2):
1303 if self.get_status_field("wpa_state") == "COMPLETED":
1304 return
1305 time.sleep(0.5)
1306 raise Exception("Timeout while waiting for COMPLETED state")
1307
1308 def get_capability(self, field):
1309 res = self.request("GET_CAPABILITY " + field)
1310 if "FAIL" in res:
1311 return None
1312 return res.split(' ')
1313
1314 def get_bss(self, bssid, ifname=None):
1315 if not ifname or ifname == self.ifname:
1316 res = self.request("BSS " + bssid)
1317 elif ifname == self.group_ifname:
1318 res = self.group_request("BSS " + bssid)
1319 else:
1320 return None
1321
1322 if "FAIL" in res:
1323 return None
1324 lines = res.splitlines()
1325 vals = dict()
1326 for l in lines:
1327 [name, value] = l.split('=', 1)
1328 vals[name] = value
1329 if len(vals) == 0:
1330 return None
1331 return vals
1332
1333 def get_pmksa(self, bssid):
1334 res = self.request("PMKSA")
1335 lines = res.splitlines()
1336 for l in lines:
1337 if bssid not in l:
1338 continue
1339 vals = dict()
1340 try:
1341 [index, aa, pmkid, expiration, opportunistic] = l.split(' ')
1342 cache_id = None
1343 except ValueError:
1344 [index, aa, pmkid, expiration, opportunistic, cache_id] = l.split(' ')
1345 vals['index'] = index
1346 vals['pmkid'] = pmkid
1347 vals['expiration'] = expiration
1348 vals['opportunistic'] = opportunistic
1349 if cache_id != None:
1350 vals['cache_id'] = cache_id
1351 return vals
1352 return None
1353
1354 def get_pmk(self, network_id):
1355 bssid = self.get_status_field('bssid')
1356 res = self.request("PMKSA_GET %d" % network_id)
1357 for val in res.splitlines():
1358 if val.startswith(bssid):
1359 return val.split(' ')[2]
1360 return None
1361
1362 def get_sta(self, addr, info=None, next=False):
1363 cmd = "STA-NEXT " if next else "STA "
1364 if addr is None:
1365 res = self.request("STA-FIRST")
1366 elif info:
1367 res = self.request(cmd + addr + " " + info)
1368 else:
1369 res = self.request(cmd + addr)
1370 lines = res.splitlines()
1371 vals = dict()
1372 first = True
1373 for l in lines:
1374 if first:
1375 vals['addr'] = l
1376 first = False
1377 else:
1378 [name, value] = l.split('=', 1)
1379 vals[name] = value
1380 return vals
1381
1382 def mgmt_rx(self, timeout=5):
1383 ev = self.wait_event(["MGMT-RX"], timeout=timeout)
1384 if ev is None:
1385 return None
1386 msg = {}
1387 items = ev.split(' ')
1388 field, val = items[1].split('=')
1389 if field != "freq":
1390 raise Exception("Unexpected MGMT-RX event format: " + ev)
1391 msg['freq'] = val
1392
1393 field, val = items[2].split('=')
1394 if field != "datarate":
1395 raise Exception("Unexpected MGMT-RX event format: " + ev)
1396 msg['datarate'] = val
1397
1398 field, val = items[3].split('=')
1399 if field != "ssi_signal":
1400 raise Exception("Unexpected MGMT-RX event format: " + ev)
1401 msg['ssi_signal'] = val
1402
1403 frame = binascii.unhexlify(items[4])
1404 msg['frame'] = frame
1405
1406 hdr = struct.unpack('<HH6B6B6BH', frame[0:24])
1407 msg['fc'] = hdr[0]
1408 msg['subtype'] = (hdr[0] >> 4) & 0xf
1409 hdr = hdr[1:]
1410 msg['duration'] = hdr[0]
1411 hdr = hdr[1:]
1412 msg['da'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
1413 hdr = hdr[6:]
1414 msg['sa'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
1415 hdr = hdr[6:]
1416 msg['bssid'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
1417 hdr = hdr[6:]
1418 msg['seq_ctrl'] = hdr[0]
1419 msg['payload'] = frame[24:]
1420
1421 return msg
1422
1423 def wait_connected(self, timeout=10, error="Connection timed out"):
1424 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=timeout)
1425 if ev is None:
1426 raise Exception(error)
1427 return ev
1428
1429 def wait_disconnected(self, timeout=None, error="Disconnection timed out"):
1430 if timeout is None:
1431 timeout = 10 if self.hostname is None else 30
1432 ev = self.wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=timeout)
1433 if ev is None:
1434 raise Exception(error)
1435 return ev
1436
1437 def get_group_ifname(self):
1438 return self.group_ifname if self.group_ifname else self.ifname
1439
1440 def get_config(self):
1441 res = self.request("DUMP")
1442 if res.startswith("FAIL"):
1443 raise Exception("DUMP failed")
1444 lines = res.splitlines()
1445 vals = dict()
1446 for l in lines:
1447 [name, value] = l.split('=', 1)
1448 vals[name] = value
1449 return vals
1450
1451 def asp_provision(self, peer, adv_id, adv_mac, session_id, session_mac,
1452 method="1000", info="", status=None, cpt=None, role=None):
1453 if status is None:
1454 cmd = "P2P_ASP_PROVISION"
1455 params = "info='%s' method=%s" % (info, method)
1456 else:
1457 cmd = "P2P_ASP_PROVISION_RESP"
1458 params = "status=%d" % status
1459
1460 if role is not None:
1461 params += " role=" + role
1462 if cpt is not None:
1463 params += " cpt=" + cpt
1464
1465 if "OK" not in self.global_request("%s %s adv_id=%s adv_mac=%s session=%d session_mac=%s %s" %
1466 (cmd, peer, adv_id, adv_mac, session_id, session_mac, params)):
1467 raise Exception("%s request failed" % cmd)
1468
1469 def note(self, txt):
1470 self.request("NOTE " + txt)
1471
1472 def save_config(self):
1473 if "OK" not in self.request("SAVE_CONFIG"):
1474 raise Exception("Failed to save configuration file")
1475
1476 def wait_regdom(self, country_ie=False):
1477 for i in range(5):
1478 ev = self.wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=1)
1479 if ev is None:
1480 break
1481 if country_ie:
1482 if "init=COUNTRY_IE" in ev:
1483 break
1484 else:
1485 break
1486
1487 def dpp_qr_code(self, uri):
1488 res = self.request("DPP_QR_CODE " + uri)
1489 if "FAIL" in res:
1490 raise Exception("Failed to parse QR Code URI")
1491 return int(res)
1492
1493 def dpp_nfc_uri(self, uri):
1494 res = self.request("DPP_NFC_URI " + uri)
1495 if "FAIL" in res:
1496 raise Exception("Failed to parse NFC URI")
1497 return int(res)
1498
1499 def dpp_bootstrap_gen(self, type="qrcode", chan=None, mac=None, info=None,
1500 curve=None, key=None, supported_curves=None,
1501 host=None):
1502 cmd = "DPP_BOOTSTRAP_GEN type=" + type
1503 if chan:
1504 cmd += " chan=" + chan
1505 if mac:
1506 if mac is True:
1507 mac = self.own_addr()
1508 cmd += " mac=" + mac.replace(':', '')
1509 if info:
1510 cmd += " info=" + info
1511 if curve:
1512 cmd += " curve=" + curve
1513 if key:
1514 cmd += " key=" + key
1515 if supported_curves:
1516 cmd += " supported_curves=" + supported_curves
1517 if host:
1518 cmd += " host=" + host
1519 res = self.request(cmd)
1520 if "FAIL" in res:
1521 raise Exception("Failed to generate bootstrapping info")
1522 return int(res)
1523
1524 def dpp_bootstrap_set(self, id, conf=None, configurator=None, ssid=None,
1525 extra=None):
1526 cmd = "DPP_BOOTSTRAP_SET %d" % id
1527 if ssid:
1528 cmd += " ssid=" + binascii.hexlify(ssid.encode()).decode()
1529 if extra:
1530 cmd += " " + extra
1531 if conf:
1532 cmd += " conf=" + conf
1533 if configurator is not None:
1534 cmd += " configurator=%d" % configurator
1535 if "OK" not in self.request(cmd):
1536 raise Exception("Failed to set bootstrapping parameters")
1537
1538 def dpp_listen(self, freq, netrole=None, qr=None, role=None):
1539 cmd = "DPP_LISTEN " + str(freq)
1540 if netrole:
1541 cmd += " netrole=" + netrole
1542 if qr:
1543 cmd += " qr=" + qr
1544 if role:
1545 cmd += " role=" + role
1546 if "OK" not in self.request(cmd):
1547 raise Exception("Failed to start listen operation")
1548
1549 def dpp_auth_init(self, peer=None, uri=None, conf=None, configurator=None,
1550 extra=None, own=None, role=None, neg_freq=None,
1551 ssid=None, passphrase=None, expect_fail=False,
1552 tcp_addr=None, tcp_port=None, conn_status=False,
1553 ssid_charset=None, nfc_uri=None, netrole=None,
1554 csrattrs=None):
1555 cmd = "DPP_AUTH_INIT"
1556 if peer is None:
1557 if nfc_uri:
1558 peer = self.dpp_nfc_uri(nfc_uri)
1559 else:
1560 peer = self.dpp_qr_code(uri)
1561 cmd += " peer=%d" % peer
1562 if own is not None:
1563 cmd += " own=%d" % own
1564 if role:
1565 cmd += " role=" + role
1566 if extra:
1567 cmd += " " + extra
1568 if conf:
1569 cmd += " conf=" + conf
1570 if configurator is not None:
1571 cmd += " configurator=%d" % configurator
1572 if neg_freq:
1573 cmd += " neg_freq=%d" % neg_freq
1574 if ssid:
1575 cmd += " ssid=" + binascii.hexlify(ssid.encode()).decode()
1576 if ssid_charset:
1577 cmd += " ssid_charset=%d" % ssid_charset
1578 if passphrase:
1579 cmd += " pass=" + binascii.hexlify(passphrase.encode()).decode()
1580 if tcp_addr:
1581 cmd += " tcp_addr=" + tcp_addr
1582 if tcp_port:
1583 cmd += " tcp_port=" + tcp_port
1584 if conn_status:
1585 cmd += " conn_status=1"
1586 if netrole:
1587 cmd += " netrole=" + netrole
1588 if csrattrs:
1589 cmd += " csrattrs=" + csrattrs
1590 res = self.request(cmd)
1591 if expect_fail:
1592 if "FAIL" not in res:
1593 raise Exception("DPP authentication started unexpectedly")
1594 return
1595 if "OK" not in res:
1596 raise Exception("Failed to initiate DPP Authentication")
1597 return int(peer)
1598
1599 def dpp_pkex_init(self, identifier, code, role=None, key=None, curve=None,
1600 extra=None, use_id=None, allow_fail=False, ver=None,
1601 tcp_addr=None, tcp_port=None):
1602 if use_id is None:
1603 id1 = self.dpp_bootstrap_gen(type="pkex", key=key, curve=curve)
1604 else:
1605 id1 = use_id
1606 cmd = "own=%d " % id1
1607 if identifier:
1608 cmd += "identifier=%s " % identifier
1609 cmd += "init=1 "
1610 if ver is not None:
1611 cmd += "ver=" + str(ver) + " "
1612 if role:
1613 cmd += "role=%s " % role
1614 if tcp_addr:
1615 cmd += "tcp_addr=" + tcp_addr + " "
1616 if tcp_port:
1617 cmd += "tcp_port=" + tcp_port + " "
1618 if extra:
1619 cmd += extra + " "
1620 cmd += "code=%s" % code
1621 res = self.request("DPP_PKEX_ADD " + cmd)
1622 if allow_fail:
1623 return id1
1624 if "FAIL" in res:
1625 raise Exception("Failed to set PKEX data (initiator)")
1626 return id1
1627
1628 def dpp_pkex_resp(self, freq, identifier, code, key=None, curve=None,
1629 listen_role=None, use_id=None):
1630 if use_id is None:
1631 id0 = self.dpp_bootstrap_gen(type="pkex", key=key, curve=curve)
1632 else:
1633 id0 = use_id
1634 cmd = "own=%d " % id0
1635 if identifier:
1636 cmd += "identifier=%s " % identifier
1637 cmd += "code=%s" % code
1638 res = self.request("DPP_PKEX_ADD " + cmd)
1639 if "FAIL" in res:
1640 raise Exception("Failed to set PKEX data (responder)")
1641 self.dpp_listen(freq, role=listen_role)
1642 return id0
1643
1644 def dpp_configurator_add(self, curve=None, key=None,
1645 net_access_key_curve=None):
1646 cmd = "DPP_CONFIGURATOR_ADD"
1647 if curve:
1648 cmd += " curve=" + curve
1649 if net_access_key_curve:
1650 cmd += " net_access_key_curve=" + net_access_key_curve
1651 if key:
1652 cmd += " key=" + key
1653 res = self.request(cmd)
1654 if "FAIL" in res:
1655 raise Exception("Failed to add configurator")
1656 return int(res)
1657
1658 def dpp_configurator_set(self, conf_id, net_access_key_curve=None):
1659 cmd = "DPP_CONFIGURATOR_SET %d" % conf_id
1660 if net_access_key_curve:
1661 cmd += " net_access_key_curve=" + net_access_key_curve
1662 res = self.request(cmd)
1663 if "FAIL" in res:
1664 raise Exception("Failed to set configurator")
1665
1666 def dpp_configurator_remove(self, conf_id):
1667 res = self.request("DPP_CONFIGURATOR_REMOVE %d" % conf_id)
1668 if "OK" not in res:
1669 raise Exception("DPP_CONFIGURATOR_REMOVE failed")
1670
1671 def get_ptksa(self, bssid, cipher):
1672 res = self.request("PTKSA_CACHE_LIST")
1673 lines = res.splitlines()
1674 for l in lines:
1675 if bssid not in l or cipher not in l:
1676 continue
1677
1678 vals = dict()
1679 [index, addr, cipher, expiration, tk, kdk] = l.split(' ', 5)
1680 vals['index'] = index
1681 vals['addr'] = addr
1682 vals['cipher'] = cipher
1683 vals['expiration'] = expiration
1684 vals['tk'] = tk
1685 vals['kdk'] = kdk
1686 return vals
1687 return None