1 # Python class for controlling wpa_supplicant
2 # Copyright (c) 2013-2014, Jouni Malinen <j@w1.fi>
4 # This software may be distributed under the terms of the BSD license.
5 # See README for more details.
16 logger = logging.getLogger()
17 wpas_ctrl = '/var/run/wpa_supplicant'
20 def __init__(self, ifname=None, global_iface=None):
21 self.group_ifname = None
24 self.set_ifname(ifname)
28 self.global_iface = global_iface
30 self.global_ctrl = wpaspy.Ctrl(global_iface)
31 self.global_mon = wpaspy.Ctrl(global_iface)
32 self.global_mon.attach()
34 def set_ifname(self, ifname):
36 self.ctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
37 self.mon = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
40 def remove_ifname(self):
47 def interface_add(self, ifname, config="", driver="nl80211", drv_params=None):
49 groups = subprocess.check_output(["id"])
50 group = "admin" if "(admin)" in groups else "adm"
53 cmd = "INTERFACE_ADD " + ifname + "\t" + config + "\t" + driver + "\tDIR=/var/run/wpa_supplicant GROUP=" + group
55 cmd = cmd + '\t' + drv_params
56 if "FAIL" in self.global_request(cmd):
57 raise Exception("Failed to add a dynamic wpa_supplicant interface")
58 self.set_ifname(ifname)
60 def interface_remove(self, ifname):
62 self.global_request("INTERFACE_REMOVE " + ifname)
64 def request(self, cmd):
65 logger.debug(self.ifname + ": CTRL: " + cmd)
66 return self.ctrl.request(cmd)
68 def global_request(self, cmd):
69 if self.global_iface is None:
72 ifname = self.ifname or self.global_iface
73 logger.debug(ifname + ": CTRL(global): " + cmd)
74 return self.global_ctrl.request(cmd)
76 def group_request(self, cmd):
77 if self.group_ifname and self.group_ifname != self.ifname:
78 logger.debug(self.group_ifname + ": CTRL: " + cmd)
79 gctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, self.group_ifname))
80 return gctrl.request(cmd)
81 return self.request(cmd)
84 return "PONG" in self.request("PING")
86 def global_ping(self):
87 return "PONG" in self.global_request("PING")
91 res = self.request("FLUSH")
93 logger.info("FLUSH to " + self.ifname + " failed: " + res)
94 self.request("WPS_ER_STOP")
95 self.request("SET pmf 0")
96 self.request("SET p2p_add_cli_chan 0")
97 self.request("SET p2p_no_go_freq ")
98 self.request("SET p2p_pref_chan ")
99 self.request("SET p2p_no_group_iface 1")
100 self.request("SET p2p_go_intent 7")
101 self.request("SET ignore_old_scan_res 0")
104 self.gctrl_mon.detach()
107 self.gctrl_mon = None
108 self.group_ifname = None
113 state = self.get_driver_status_field("scan_state")
114 if "SCAN_STARTED" in state or "SCAN_REQUESTED" in state:
115 logger.info(self.ifname + ": Waiting for scan operation to complete before continuing")
121 logger.error(self.ifname + ": Driver scan state did not clear")
122 print "Trying to clear cfg80211/mac80211 scan state"
124 cmd = ["sudo", "ifconfig", self.ifname, "down"]
126 except subprocess.CalledProcessError, e:
127 logger.info("ifconfig failed: " + str(e.returncode))
128 logger.info(e.output)
130 cmd = ["sudo", "ifconfig", self.ifname, "up"]
132 except subprocess.CalledProcessError, e:
133 logger.info("ifconfig failed: " + str(e.returncode))
134 logger.info(e.output)
136 # The ongoing scan could have discovered BSSes or P2P peers
137 logger.info("Run FLUSH again since scan was in progress")
138 self.request("FLUSH")
142 logger.info("No PING response from " + self.ifname + " after reset")
144 def add_network(self):
145 id = self.request("ADD_NETWORK")
147 raise Exception("ADD_NETWORK failed")
150 def remove_network(self, id):
151 id = self.request("REMOVE_NETWORK " + str(id))
153 raise Exception("REMOVE_NETWORK failed")
156 def get_network(self, id, field):
157 res = self.request("GET_NETWORK " + str(id) + " " + field)
162 def set_network(self, id, field, value):
163 res = self.request("SET_NETWORK " + str(id) + " " + field + " " + value)
165 raise Exception("SET_NETWORK failed")
168 def set_network_quoted(self, id, field, value):
169 res = self.request("SET_NETWORK " + str(id) + " " + field + ' "' + value + '"')
171 raise Exception("SET_NETWORK failed")
174 def list_networks(self):
175 res = self.request("LIST_NETWORKS")
176 lines = res.splitlines()
179 if "network id" in l:
181 [id,ssid,bssid,flags] = l.split('\t')
184 network['ssid'] = ssid
185 network['bssid'] = bssid
186 network['flags'] = flags
187 networks.append(network)
190 def hs20_enable(self, auto_interworking=False):
191 self.request("SET interworking 1")
192 self.request("SET hs20 1")
193 if auto_interworking:
194 self.request("SET auto_interworking 1")
196 self.request("SET auto_interworking 0")
199 id = self.request("ADD_CRED")
201 raise Exception("ADD_CRED failed")
204 def remove_cred(self, id):
205 id = self.request("REMOVE_CRED " + str(id))
207 raise Exception("REMOVE_CRED failed")
210 def set_cred(self, id, field, value):
211 res = self.request("SET_CRED " + str(id) + " " + field + " " + value)
213 raise Exception("SET_CRED failed")
216 def set_cred_quoted(self, id, field, value):
217 res = self.request("SET_CRED " + str(id) + " " + field + ' "' + value + '"')
219 raise Exception("SET_CRED failed")
222 def get_cred(self, id, field):
223 return self.request("GET_CRED " + str(id) + " " + field)
225 def add_cred_values(self, params):
228 quoted = [ "realm", "username", "password", "domain", "imsi",
229 "excluded_ssid", "milenage", "ca_cert", "client_cert",
230 "private_key", "domain_suffix_match", "provisioning_sp",
231 "roaming_partner", "phase1", "phase2" ]
234 self.set_cred_quoted(id, field, params[field])
236 not_quoted = [ "eap", "roaming_consortium", "priority",
237 "required_roaming_consortium", "sp_priority",
238 "max_bss_load", "update_identifier", "req_conn_capab",
239 "min_dl_bandwidth_home", "min_ul_bandwidth_home",
240 "min_dl_bandwidth_roaming", "min_ul_bandwidth_roaming" ]
241 for field in not_quoted:
243 self.set_cred(id, field, params[field])
247 def select_network(self, id, freq=None):
249 extra = " freq=" + freq
252 id = self.request("SELECT_NETWORK " + str(id) + extra)
254 raise Exception("SELECT_NETWORK failed")
257 def mesh_group_add(self, id):
258 id = self.request("MESH_GROUP_ADD " + str(id))
260 raise Exception("MESH_GROUP_ADD failed")
263 def mesh_group_remove(self):
264 id = self.request("MESH_GROUP_REMOVE " + str(self.ifname))
266 raise Exception("MESH_GROUP_REMOVE failed")
269 def connect_network(self, id, timeout=10):
271 self.select_network(id)
272 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=timeout)
274 raise Exception("Association with the AP timed out")
277 def get_status(self, extra=None):
282 res = self.request("STATUS" + extra)
283 lines = res.splitlines()
287 [name,value] = l.split('=', 1)
289 except ValueError, e:
290 logger.info(self.ifname + ": Ignore unexpected STATUS line: " + l)
293 def get_status_field(self, field, extra=None):
294 vals = self.get_status(extra)
299 def get_group_status(self, extra=None):
304 res = self.group_request("STATUS" + extra)
305 lines = res.splitlines()
309 [name,value] = l.split('=', 1)
311 logger.info(self.ifname + ": Ignore unexpected status line: " + l)
316 def get_group_status_field(self, field, extra=None):
317 vals = self.get_group_status(extra)
322 def get_driver_status(self):
323 res = self.request("STATUS-DRIVER")
324 lines = res.splitlines()
328 [name,value] = l.split('=', 1)
330 logger.info(self.ifname + ": Ignore unexpected status-driver line: " + l)
335 def get_driver_status_field(self, field):
336 vals = self.get_driver_status()
342 mcc = int(self.get_driver_status_field('capa.num_multichan_concurrent'))
343 return 1 if mcc < 2 else mcc
346 res = self.request("MIB")
347 lines = res.splitlines()
351 [name,value] = l.split('=', 1)
353 except ValueError, e:
354 logger.info(self.ifname + ": Ignore unexpected MIB line: " + l)
357 def p2p_dev_addr(self):
358 return self.get_status_field("p2p_device_address")
360 def p2p_interface_addr(self):
361 return self.get_group_status_field("address")
365 res = self.p2p_interface_addr()
367 res = self.p2p_dev_addr()
370 def p2p_listen(self):
371 return self.global_request("P2P_LISTEN")
373 def p2p_find(self, social=False, progressive=False, dev_id=None, dev_type=None):
376 cmd = cmd + " type=social"
378 cmd = cmd + " type=progressive"
380 cmd = cmd + " dev_id=" + dev_id
382 cmd = cmd + " dev_type=" + dev_type
383 return self.global_request(cmd)
385 def p2p_stop_find(self):
386 return self.global_request("P2P_STOP_FIND")
388 def wps_read_pin(self):
389 self.pin = self.request("WPS_PIN get").rstrip("\n")
390 if "FAIL" in self.pin:
391 raise Exception("Could not generate PIN")
394 def peer_known(self, peer, full=True):
395 res = self.global_request("P2P_PEER " + peer)
396 if peer.lower() not in res.lower():
400 return "[PROBE_REQ_ONLY]" not in res
402 def discover_peer(self, peer, full=True, timeout=15, social=True, force_find=False):
403 logger.info(self.ifname + ": Trying to discover peer " + peer)
404 if not force_find and self.peer_known(peer, full):
406 self.p2p_find(social)
408 while count < timeout * 4:
411 if self.peer_known(peer, full):
415 def get_peer(self, peer):
416 res = self.global_request("P2P_PEER " + peer)
417 if peer.lower() not in res.lower():
418 raise Exception("Peer information not available")
419 lines = res.splitlines()
423 [name,value] = l.split('=', 1)
427 def group_form_result(self, ev, expect_failure=False, go_neg_res=None):
429 if "P2P-GROUP-STARTED" in ev:
430 raise Exception("Group formation succeeded when expecting failure")
431 exp = r'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
432 s = re.split(exp, ev)
436 res['result'] = 'go-neg-failed'
437 res['status'] = int(s[2])
440 if "P2P-GROUP-STARTED" not in ev:
441 raise Exception("No P2P-GROUP-STARTED event seen")
443 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.]*)'
444 s = re.split(exp, ev)
446 exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
447 s = re.split(exp, ev)
449 raise Exception("Could not parse P2P-GROUP-STARTED")
451 res['result'] = 'success'
453 self.group_ifname = s[2]
455 self.gctrl_mon = wpaspy.Ctrl(os.path.join(wpas_ctrl, self.group_ifname))
456 self.gctrl_mon.attach()
458 logger.debug("Could not open monitor socket for group interface")
459 self.gctrl_mon = None
463 if "[PERSISTENT]" in ev:
464 res['persistent'] = True
466 res['persistent'] = False
467 p = re.match(r'psk=([0-9a-f]*)', s[6])
469 res['psk'] = p.group(1)
470 p = re.match(r'passphrase="(.*)"', s[6])
472 res['passphrase'] = p.group(1)
473 res['go_dev_addr'] = s[7]
475 if len(s) > 8 and len(s[8]) > 0:
476 res['ip_addr'] = s[8]
478 res['ip_mask'] = s[9]
480 res['go_ip_addr'] = s[10]
483 exp = r'<.>(P2P-GO-NEG-SUCCESS) role=(GO|client) freq=([0-9]*)'
484 s = re.split(exp, go_neg_res)
486 raise Exception("Could not parse P2P-GO-NEG-SUCCESS")
487 res['go_neg_role'] = s[2]
488 res['go_neg_freq'] = s[3]
492 def p2p_go_neg_auth(self, peer, pin, method, go_intent=None, persistent=False, freq=None):
493 if not self.discover_peer(peer):
494 raise Exception("Peer " + peer + " not found")
496 cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
498 cmd = cmd + ' go_intent=' + str(go_intent)
500 cmd = cmd + ' freq=' + str(freq)
502 cmd = cmd + " persistent"
503 if "OK" in self.global_request(cmd):
505 raise Exception("P2P_CONNECT (auth) failed")
507 def p2p_go_neg_auth_result(self, timeout=1, expect_failure=False):
509 ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
510 "P2P-GO-NEG-FAILURE"], timeout);
514 raise Exception("Group formation timed out")
515 if "P2P-GO-NEG-SUCCESS" in ev:
517 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout);
521 raise Exception("Group formation timed out")
523 return self.group_form_result(ev, expect_failure, go_neg_res)
525 def p2p_go_neg_init(self, peer, pin, method, timeout=0, go_intent=None, expect_failure=False, persistent=False, persistent_id=None, freq=None, provdisc=False, wait_group=True):
526 if not self.discover_peer(peer):
527 raise Exception("Peer " + peer + " not found")
530 cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
532 cmd = "P2P_CONNECT " + peer + " " + method
534 cmd = cmd + ' go_intent=' + str(go_intent)
536 cmd = cmd + ' freq=' + str(freq)
538 cmd = cmd + " persistent"
540 cmd = cmd + " persistent=" + persistent_id
542 cmd = cmd + " provdisc"
543 if "OK" in self.global_request(cmd):
548 ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
549 "P2P-GO-NEG-FAILURE"], timeout)
553 raise Exception("Group formation timed out")
554 if "P2P-GO-NEG-SUCCESS" in ev:
558 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
562 raise Exception("Group formation timed out")
564 return self.group_form_result(ev, expect_failure, go_neg_res)
565 raise Exception("P2P_CONNECT failed")
567 def wait_event(self, events, timeout=10):
568 start = os.times()[4]
570 while self.mon.pending():
572 logger.debug(self.ifname + ": " + ev)
577 remaining = start + timeout - now
580 if not self.mon.pending(timeout=remaining):
584 def wait_global_event(self, events, timeout):
585 if self.global_iface is None:
586 self.wait_event(events, timeout)
588 start = os.times()[4]
590 while self.global_mon.pending():
591 ev = self.global_mon.recv()
592 logger.debug(self.ifname + "(global): " + ev)
597 remaining = start + timeout - now
600 if not self.global_mon.pending(timeout=remaining):
604 def wait_group_event(self, events, timeout=10):
605 if self.group_ifname and self.group_ifname != self.ifname:
606 if self.gctrl_mon is None:
608 start = os.times()[4]
610 while self.gctrl_mon.pending():
611 ev = self.gctrl_mon.recv()
612 logger.debug(self.group_ifname + ": " + ev)
617 remaining = start + timeout - now
620 if not self.gctrl_mon.pending(timeout=remaining):
624 return self.wait_event(events, timeout)
626 def wait_go_ending_session(self):
629 self.gctrl_mon.detach()
632 self.gctrl_mon = None
633 ev = self.wait_event(["P2P-GROUP-REMOVED"], timeout=3)
635 raise Exception("Group removal event timed out")
636 if "reason=GO_ENDING_SESSION" not in ev:
637 raise Exception("Unexpected group removal reason")
639 def dump_monitor(self):
640 while self.mon.pending():
642 logger.debug(self.ifname + ": " + ev)
643 while self.global_mon.pending():
644 ev = self.global_mon.recv()
645 logger.debug(self.ifname + "(global): " + ev)
647 def remove_group(self, ifname=None):
650 self.gctrl_mon.detach()
653 self.gctrl_mon = None
655 ifname = self.group_ifname if self.group_ifname else self.ifname
656 if "OK" not in self.global_request("P2P_GROUP_REMOVE " + ifname):
657 raise Exception("Group could not be removed")
658 self.group_ifname = None
660 def p2p_start_go(self, persistent=None, freq=None):
662 cmd = "P2P_GROUP_ADD"
663 if persistent is None:
665 elif persistent is True:
666 cmd = cmd + " persistent"
668 cmd = cmd + " persistent=" + str(persistent)
670 cmd = cmd + " freq=" + str(freq)
671 if "OK" in self.global_request(cmd):
672 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
674 raise Exception("GO start up timed out")
676 return self.group_form_result(ev)
677 raise Exception("P2P_GROUP_ADD failed")
679 def p2p_go_authorize_client(self, pin):
680 cmd = "WPS_PIN any " + pin
681 if "FAIL" in self.group_request(cmd):
682 raise Exception("Failed to authorize client connection on GO")
685 def p2p_go_authorize_client_pbc(self):
687 if "FAIL" in self.group_request(cmd):
688 raise Exception("Failed to authorize client connection on GO")
691 def p2p_connect_group(self, go_addr, pin, timeout=0, social=False,
694 if not self.discover_peer(go_addr, social=social):
695 if social or not self.discover_peer(go_addr, social=social):
696 raise Exception("GO " + go_addr + " not found")
698 cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
700 cmd += " freq=" + str(freq)
701 if "OK" in self.global_request(cmd):
705 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
707 raise Exception("Joining the group timed out")
709 return self.group_form_result(ev)
710 raise Exception("P2P_CONNECT(join) failed")
712 def tdls_setup(self, peer):
713 cmd = "TDLS_SETUP " + peer
714 if "FAIL" in self.group_request(cmd):
715 raise Exception("Failed to request TDLS setup")
718 def tdls_teardown(self, peer):
719 cmd = "TDLS_TEARDOWN " + peer
720 if "FAIL" in self.group_request(cmd):
721 raise Exception("Failed to request TDLS teardown")
724 def add_ts(self, tsid, up):
727 "nominal_msdu_size": 1500,
728 "min_phy_rate": 6000000,
729 "mean_data_rate": 1500,
731 cmd = "WMM_AC_ADDTS downlink tsid=%d up=%d" % (tsid, up)
732 for (key, value) in params.iteritems():
733 cmd += " %s=%d" % (key, value)
735 if self.request(cmd).strip() != "OK":
736 raise Exception("ADDTS failed (tsid=%d up=%d)" % (tsid, up))
738 ev = self.wait_event(["TSPEC-ADDED"], timeout=1)
740 raise Exception("ADDTS failed (time out)")
741 if "tsid=%d" % (tsid) not in ev:
742 raise Exception("ADDTS failed (invalid tsid in TSPEC-ADDED)")
744 def del_ts(self, tsid):
745 if self.request("WMM_AC_DELTS %d" % (tsid)).strip() != "OK":
746 raise Exception("DELTS failed")
748 ev = self.wait_event(["TSPEC-REMOVED"], timeout=1)
750 raise Exception("DELTS failed (time out)")
751 if "tsid=%d" % (tsid) not in ev:
752 raise Exception("DELTS failed (invalid tsid in TSPEC-REMOVED)")
754 def connect(self, ssid=None, ssid2=None, **kwargs):
755 logger.info("Connect STA " + self.ifname + " to AP")
756 id = self.add_network()
758 self.set_network_quoted(id, "ssid", ssid)
760 self.set_network(id, "ssid", ssid2)
762 quoted = [ "psk", "identity", "anonymous_identity", "password",
763 "ca_cert", "client_cert", "private_key",
764 "private_key_passwd", "ca_cert2", "client_cert2",
765 "private_key2", "phase1", "phase2", "domain_suffix_match",
766 "altsubject_match", "subject_match", "pac_file", "dh_file",
767 "bgscan", "ht_mcs", "id_str", "openssl_ciphers" ]
769 if field in kwargs and kwargs[field]:
770 self.set_network_quoted(id, field, kwargs[field])
772 not_quoted = [ "proto", "key_mgmt", "ieee80211w", "pairwise",
773 "group", "wep_key0", "wep_key1", "wep_key2", "wep_key3",
774 "wep_tx_keyidx", "scan_freq", "eap",
775 "eapol_flags", "fragment_size", "scan_ssid", "auth_alg",
776 "wpa_ptk_rekey", "disable_ht", "disable_vht", "bssid",
777 "disable_max_amsdu", "ampdu_factor", "ampdu_density",
778 "disable_ht40", "disable_sgi", "disable_ldpc",
779 "ht40_intolerant", "update_identifier", "mac_addr",
781 for field in not_quoted:
782 if field in kwargs and kwargs[field]:
783 self.set_network(id, field, kwargs[field])
785 if "raw_psk" in kwargs and kwargs['raw_psk']:
786 self.set_network(id, "psk", kwargs['raw_psk'])
787 if "password_hex" in kwargs and kwargs['password_hex']:
788 self.set_network(id, "password", kwargs['password_hex'])
789 if "peerkey" in kwargs and kwargs['peerkey']:
790 self.set_network(id, "peerkey", "1")
791 if "okc" in kwargs and kwargs['okc']:
792 self.set_network(id, "proactive_key_caching", "1")
793 if "ocsp" in kwargs and kwargs['ocsp']:
794 self.set_network(id, "ocsp", str(kwargs['ocsp']))
795 if "only_add_network" in kwargs and kwargs['only_add_network']:
797 if "wait_connect" not in kwargs or kwargs['wait_connect']:
799 self.connect_network(id, timeout=20)
801 self.connect_network(id)
804 self.select_network(id)
807 def scan(self, type=None, freq=None, no_wait=False, only_new=False):
809 cmd = "SCAN TYPE=" + type
813 cmd = cmd + " freq=" + str(freq)
818 if not "OK" in self.request(cmd):
819 raise Exception("Failed to trigger scan")
822 ev = self.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
824 raise Exception("Scan timed out")
826 def scan_for_bss(self, bssid, freq=None, force_scan=False):
827 if not force_scan and self.get_bss(bssid) is not None:
829 for i in range(0, 10):
830 self.scan(freq=freq, type="ONLY")
831 if self.get_bss(bssid) is not None:
833 raise Exception("Could not find BSS " + bssid + " in scan")
835 def flush_scan_cache(self):
836 self.request("BSS_FLUSH 0")
837 self.scan(freq=2412, only_new=True)
839 def roam(self, bssid, fail_test=False):
841 if "OK" not in self.request("ROAM " + bssid):
842 raise Exception("ROAM failed")
844 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
846 raise Exception("Unexpected connection")
849 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
851 raise Exception("Roaming with the AP timed out")
854 def roam_over_ds(self, bssid, fail_test=False):
856 if "OK" not in self.request("FT_DS " + bssid):
857 raise Exception("FT_DS failed")
859 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
861 raise Exception("Unexpected connection")
864 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
866 raise Exception("Roaming with the AP timed out")
869 def wps_reg(self, bssid, pin, new_ssid=None, key_mgmt=None, cipher=None,
870 new_passphrase=None, no_wait=False):
873 self.request("WPS_REG " + bssid + " " + pin + " " +
874 new_ssid.encode("hex") + " " + key_mgmt + " " +
875 cipher + " " + new_passphrase.encode("hex"))
878 ev = self.wait_event(["WPS-SUCCESS"], timeout=15)
880 self.request("WPS_REG " + bssid + " " + pin)
883 ev = self.wait_event(["WPS-CRED-RECEIVED"], timeout=15)
885 raise Exception("WPS cred timed out")
886 ev = self.wait_event(["WPS-FAIL"], timeout=15)
888 raise Exception("WPS timed out")
889 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
891 raise Exception("Association with the AP timed out")
894 self.global_request("RELOG")
896 def wait_completed(self, timeout=10):
897 for i in range(0, timeout * 2):
898 if self.get_status_field("wpa_state") == "COMPLETED":
901 raise Exception("Timeout while waiting for COMPLETED state")
903 def get_capability(self, field):
904 res = self.request("GET_CAPABILITY " + field)
907 return res.split(' ')
909 def get_bss(self, bssid):
910 res = self.request("BSS " + bssid)
913 lines = res.splitlines()
916 [name,value] = l.split('=', 1)
922 def get_pmksa(self, bssid):
923 res = self.request("PMKSA")
924 lines = res.splitlines()
929 [index,aa,pmkid,expiration,opportunistic] = l.split(' ')
930 vals['index'] = index
931 vals['pmkid'] = pmkid
932 vals['expiration'] = expiration
933 vals['opportunistic'] = opportunistic
937 def get_sta(self, addr, info=None, next=False):
938 cmd = "STA-NEXT " if next else "STA "
940 res = self.request("STA-FIRST")
942 res = self.request(cmd + addr + " " + info)
944 res = self.request(cmd + addr)
945 lines = res.splitlines()
953 [name,value] = l.split('=', 1)
957 def mgmt_rx(self, timeout=5):
958 ev = self.wait_event(["MGMT-RX"], timeout=timeout)
962 items = ev.split(' ')
963 field,val = items[1].split('=')
965 raise Exception("Unexpected MGMT-RX event format: " + ev)
967 frame = binascii.unhexlify(items[4])
970 hdr = struct.unpack('<HH6B6B6BH', frame[0:24])
972 msg['subtype'] = (hdr[0] >> 4) & 0xf
974 msg['duration'] = hdr[0]
976 msg['da'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
978 msg['sa'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
980 msg['bssid'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
982 msg['seq_ctrl'] = hdr[0]
983 msg['payload'] = frame[24:]