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
23 self.set_ifname(ifname)
27 self.global_iface = global_iface
29 self.global_ctrl = wpaspy.Ctrl(global_iface)
30 self.global_mon = wpaspy.Ctrl(global_iface)
31 self.global_mon.attach()
33 def set_ifname(self, ifname):
35 self.ctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
36 self.mon = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
39 def remove_ifname(self):
46 def interface_add(self, ifname, config="", driver="nl80211", drv_params=None):
48 groups = subprocess.check_output(["id"])
49 group = "admin" if "(admin)" in groups else "adm"
52 cmd = "INTERFACE_ADD " + ifname + "\t" + config + "\t" + driver + "\tDIR=/var/run/wpa_supplicant GROUP=" + group
54 cmd = cmd + '\t' + drv_params
55 if "FAIL" in self.global_request(cmd):
56 raise Exception("Failed to add a dynamic wpa_supplicant interface")
57 self.set_ifname(ifname)
59 def interface_remove(self, ifname):
61 self.global_request("INTERFACE_REMOVE " + ifname)
63 def request(self, cmd):
64 logger.debug(self.ifname + ": CTRL: " + cmd)
65 return self.ctrl.request(cmd)
67 def global_request(self, cmd):
68 if self.global_iface is None:
71 ifname = self.ifname or self.global_iface
72 logger.debug(ifname + ": CTRL(global): " + cmd)
73 return self.global_ctrl.request(cmd)
75 def group_request(self, cmd):
76 if self.group_ifname and self.group_ifname != self.ifname:
77 logger.debug(self.group_ifname + ": CTRL: " + cmd)
78 gctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, self.group_ifname))
79 return gctrl.request(cmd)
80 return self.request(cmd)
83 return "PONG" in self.request("PING")
85 def global_ping(self):
86 return "PONG" in self.global_request("PING")
90 res = self.request("FLUSH")
92 logger.info("FLUSH to " + self.ifname + " failed: " + res)
93 self.request("WPS_ER_STOP")
94 self.request("SET pmf 0")
95 self.request("SET external_sim 0")
96 self.request("SET hessid 00:00:00:00:00:00")
97 self.request("SET access_network_type 15")
98 self.request("SET p2p_add_cli_chan 0")
99 self.request("SET p2p_no_go_freq ")
100 self.request("SET p2p_pref_chan ")
101 self.request("SET p2p_no_group_iface 1")
102 self.request("SET p2p_go_intent 7")
103 self.group_ifname = None
108 state = self.get_driver_status_field("scan_state")
109 if "SCAN_STARTED" in state or "SCAN_REQUESTED" in state:
110 logger.info(self.ifname + ": Waiting for scan operation to complete before continuing")
116 logger.error(self.ifname + ": Driver scan state did not clear")
117 print "Trying to clear cfg80211/mac80211 scan state"
119 cmd = ["sudo", "ifconfig", self.ifname, "down"]
121 except subprocess.CalledProcessError, e:
122 logger.info("ifconfig failed: " + str(e.returncode))
123 logger.info(e.output)
125 cmd = ["sudo", "ifconfig", self.ifname, "up"]
127 except subprocess.CalledProcessError, e:
128 logger.info("ifconfig failed: " + str(e.returncode))
129 logger.info(e.output)
131 # The ongoing scan could have discovered BSSes or P2P peers
132 logger.info("Run FLUSH again since scan was in progress")
133 self.request("FLUSH")
137 logger.info("No PING response from " + self.ifname + " after reset")
139 def add_network(self):
140 id = self.request("ADD_NETWORK")
142 raise Exception("ADD_NETWORK failed")
145 def remove_network(self, id):
146 id = self.request("REMOVE_NETWORK " + str(id))
148 raise Exception("REMOVE_NETWORK failed")
151 def get_network(self, id, field):
152 res = self.request("GET_NETWORK " + str(id) + " " + field)
157 def set_network(self, id, field, value):
158 res = self.request("SET_NETWORK " + str(id) + " " + field + " " + value)
160 raise Exception("SET_NETWORK failed")
163 def set_network_quoted(self, id, field, value):
164 res = self.request("SET_NETWORK " + str(id) + " " + field + ' "' + value + '"')
166 raise Exception("SET_NETWORK failed")
169 def list_networks(self):
170 res = self.request("LIST_NETWORKS")
171 lines = res.splitlines()
174 if "network id" in l:
176 [id,ssid,bssid,flags] = l.split('\t')
179 network['ssid'] = ssid
180 network['bssid'] = bssid
181 network['flags'] = flags
182 networks.append(network)
185 def hs20_enable(self, auto_interworking=False):
186 self.request("SET interworking 1")
187 self.request("SET hs20 1")
188 if auto_interworking:
189 self.request("SET auto_interworking 1")
191 self.request("SET auto_interworking 0")
194 id = self.request("ADD_CRED")
196 raise Exception("ADD_CRED failed")
199 def remove_cred(self, id):
200 id = self.request("REMOVE_CRED " + str(id))
202 raise Exception("REMOVE_CRED failed")
205 def set_cred(self, id, field, value):
206 res = self.request("SET_CRED " + str(id) + " " + field + " " + value)
208 raise Exception("SET_CRED failed")
211 def set_cred_quoted(self, id, field, value):
212 res = self.request("SET_CRED " + str(id) + " " + field + ' "' + value + '"')
214 raise Exception("SET_CRED failed")
217 def get_cred(self, id, field):
218 return self.request("GET_CRED " + str(id) + " " + field)
220 def add_cred_values(self, params):
223 quoted = [ "realm", "username", "password", "domain", "imsi",
224 "excluded_ssid", "milenage", "ca_cert", "client_cert",
225 "private_key", "domain_suffix_match", "provisioning_sp",
226 "roaming_partner", "phase1", "phase2" ]
229 self.set_cred_quoted(id, field, params[field])
231 not_quoted = [ "eap", "roaming_consortium", "priority",
232 "required_roaming_consortium", "sp_priority",
233 "max_bss_load", "update_identifier", "req_conn_capab",
234 "min_dl_bandwidth_home", "min_ul_bandwidth_home",
235 "min_dl_bandwidth_roaming", "min_ul_bandwidth_roaming" ]
236 for field in not_quoted:
238 self.set_cred(id, field, params[field])
242 def select_network(self, id, freq=None):
244 extra = " freq=" + freq
247 id = self.request("SELECT_NETWORK " + str(id) + extra)
249 raise Exception("SELECT_NETWORK failed")
252 def connect_network(self, id, timeout=10):
254 self.select_network(id)
255 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=timeout)
257 raise Exception("Association with the AP timed out")
260 def get_status(self, extra=None):
265 res = self.request("STATUS" + extra)
266 lines = res.splitlines()
270 [name,value] = l.split('=', 1)
272 except ValueError, e:
273 logger.info(self.ifname + ": Ignore unexpected STATUS line: " + l)
276 def get_status_field(self, field, extra=None):
277 vals = self.get_status(extra)
282 def get_group_status(self, extra=None):
287 res = self.group_request("STATUS" + extra)
288 lines = res.splitlines()
291 [name,value] = l.split('=', 1)
295 def get_group_status_field(self, field, extra=None):
296 vals = self.get_group_status(extra)
301 def get_driver_status(self):
302 res = self.request("STATUS-DRIVER")
303 lines = res.splitlines()
306 [name,value] = l.split('=', 1)
310 def get_driver_status_field(self, field):
311 vals = self.get_driver_status()
317 mcc = int(self.get_driver_status_field('capa.num_multichan_concurrent'))
318 return 1 if mcc < 2 else mcc
321 res = self.request("MIB")
322 lines = res.splitlines()
326 [name,value] = l.split('=', 1)
328 except ValueError, e:
329 logger.info(self.ifname + ": Ignore unexpected MIB line: " + l)
332 def p2p_dev_addr(self):
333 return self.get_status_field("p2p_device_address")
335 def p2p_interface_addr(self):
336 return self.get_group_status_field("address")
340 res = self.p2p_interface_addr()
342 res = self.p2p_dev_addr()
345 def p2p_listen(self):
346 return self.global_request("P2P_LISTEN")
348 def p2p_find(self, social=False, progressive=False, dev_id=None, dev_type=None):
351 cmd = cmd + " type=social"
353 cmd = cmd + " type=progressive"
355 cmd = cmd + " dev_id=" + dev_id
357 cmd = cmd + " dev_type=" + dev_type
358 return self.global_request(cmd)
360 def p2p_stop_find(self):
361 return self.global_request("P2P_STOP_FIND")
363 def wps_read_pin(self):
364 self.pin = self.request("WPS_PIN get").rstrip("\n")
365 if "FAIL" in self.pin:
366 raise Exception("Could not generate PIN")
369 def peer_known(self, peer, full=True):
370 res = self.global_request("P2P_PEER " + peer)
371 if peer.lower() not in res.lower():
375 return "[PROBE_REQ_ONLY]" not in res
377 def discover_peer(self, peer, full=True, timeout=15, social=True, force_find=False):
378 logger.info(self.ifname + ": Trying to discover peer " + peer)
379 if not force_find and self.peer_known(peer, full):
381 self.p2p_find(social)
383 while count < timeout:
386 if self.peer_known(peer, full):
390 def get_peer(self, peer):
391 res = self.global_request("P2P_PEER " + peer)
392 if peer.lower() not in res.lower():
393 raise Exception("Peer information not available")
394 lines = res.splitlines()
398 [name,value] = l.split('=', 1)
402 def group_form_result(self, ev, expect_failure=False, go_neg_res=None):
404 if "P2P-GROUP-STARTED" in ev:
405 raise Exception("Group formation succeeded when expecting failure")
406 exp = r'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
407 s = re.split(exp, ev)
411 res['result'] = 'go-neg-failed'
412 res['status'] = int(s[2])
415 if "P2P-GROUP-STARTED" not in ev:
416 raise Exception("No P2P-GROUP-STARTED event seen")
418 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.]*)'
419 s = re.split(exp, ev)
421 exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
422 s = re.split(exp, ev)
424 raise Exception("Could not parse P2P-GROUP-STARTED")
426 res['result'] = 'success'
428 self.group_ifname = s[2]
432 if "[PERSISTENT]" in ev:
433 res['persistent'] = True
435 res['persistent'] = False
436 p = re.match(r'psk=([0-9a-f]*)', s[6])
438 res['psk'] = p.group(1)
439 p = re.match(r'passphrase="(.*)"', s[6])
441 res['passphrase'] = p.group(1)
442 res['go_dev_addr'] = s[7]
444 if len(s) > 8 and len(s[8]) > 0:
445 res['ip_addr'] = s[8]
447 res['ip_mask'] = s[9]
449 res['go_ip_addr'] = s[10]
452 exp = r'<.>(P2P-GO-NEG-SUCCESS) role=(GO|client) freq=([0-9]*)'
453 s = re.split(exp, go_neg_res)
455 raise Exception("Could not parse P2P-GO-NEG-SUCCESS")
456 res['go_neg_role'] = s[2]
457 res['go_neg_freq'] = s[3]
461 def p2p_go_neg_auth(self, peer, pin, method, go_intent=None, persistent=False, freq=None):
462 if not self.discover_peer(peer):
463 raise Exception("Peer " + peer + " not found")
465 cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
467 cmd = cmd + ' go_intent=' + str(go_intent)
469 cmd = cmd + ' freq=' + str(freq)
471 cmd = cmd + " persistent"
472 if "OK" in self.global_request(cmd):
474 raise Exception("P2P_CONNECT (auth) failed")
476 def p2p_go_neg_auth_result(self, timeout=1, expect_failure=False):
478 ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
479 "P2P-GO-NEG-FAILURE"], timeout);
483 raise Exception("Group formation timed out")
484 if "P2P-GO-NEG-SUCCESS" in ev:
486 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout);
490 raise Exception("Group formation timed out")
492 return self.group_form_result(ev, expect_failure, go_neg_res)
494 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):
495 if not self.discover_peer(peer):
496 raise Exception("Peer " + peer + " not found")
499 cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
501 cmd = "P2P_CONNECT " + peer + " " + method
503 cmd = cmd + ' go_intent=' + str(go_intent)
505 cmd = cmd + ' freq=' + str(freq)
507 cmd = cmd + " persistent"
509 cmd = cmd + " persistent=" + persistent_id
511 cmd = cmd + " provdisc"
512 if "OK" in self.global_request(cmd):
517 ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
518 "P2P-GO-NEG-FAILURE"], timeout)
522 raise Exception("Group formation timed out")
523 if "P2P-GO-NEG-SUCCESS" in ev:
527 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
531 raise Exception("Group formation timed out")
533 return self.group_form_result(ev, expect_failure, go_neg_res)
534 raise Exception("P2P_CONNECT failed")
536 def wait_event(self, events, timeout=10):
537 start = os.times()[4]
539 while self.mon.pending():
541 logger.debug(self.ifname + ": " + ev)
546 remaining = start + timeout - now
549 if not self.mon.pending(timeout=remaining):
553 def wait_global_event(self, events, timeout):
554 if self.global_iface is None:
555 self.wait_event(events, timeout)
557 start = os.times()[4]
559 while self.global_mon.pending():
560 ev = self.global_mon.recv()
561 logger.debug(self.ifname + "(global): " + ev)
566 remaining = start + timeout - now
569 if not self.global_mon.pending(timeout=remaining):
573 def wait_go_ending_session(self):
574 ev = self.wait_event(["P2P-GROUP-REMOVED"], timeout=3)
576 raise Exception("Group removal event timed out")
577 if "reason=GO_ENDING_SESSION" not in ev:
578 raise Exception("Unexpected group removal reason")
580 def dump_monitor(self):
581 while self.mon.pending():
583 logger.debug(self.ifname + ": " + ev)
584 while self.global_mon.pending():
585 ev = self.global_mon.recv()
586 logger.debug(self.ifname + "(global): " + ev)
588 def remove_group(self, ifname=None):
590 ifname = self.group_ifname if self.group_ifname else self.ifname
591 if "OK" not in self.global_request("P2P_GROUP_REMOVE " + ifname):
592 raise Exception("Group could not be removed")
593 self.group_ifname = None
595 def p2p_start_go(self, persistent=None, freq=None):
597 cmd = "P2P_GROUP_ADD"
598 if persistent is None:
600 elif persistent is True:
601 cmd = cmd + " persistent"
603 cmd = cmd + " persistent=" + str(persistent)
605 cmd = cmd + " freq=" + str(freq)
606 if "OK" in self.global_request(cmd):
607 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
609 raise Exception("GO start up timed out")
611 return self.group_form_result(ev)
612 raise Exception("P2P_GROUP_ADD failed")
614 def p2p_go_authorize_client(self, pin):
615 cmd = "WPS_PIN any " + pin
616 if "FAIL" in self.group_request(cmd):
617 raise Exception("Failed to authorize client connection on GO")
620 def p2p_go_authorize_client_pbc(self):
622 if "FAIL" in self.group_request(cmd):
623 raise Exception("Failed to authorize client connection on GO")
626 def p2p_connect_group(self, go_addr, pin, timeout=0, social=False):
628 if not self.discover_peer(go_addr, social=social):
629 if social or not self.discover_peer(go_addr, social=social):
630 raise Exception("GO " + go_addr + " not found")
632 cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
633 if "OK" in self.global_request(cmd):
637 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
639 raise Exception("Joining the group timed out")
641 return self.group_form_result(ev)
642 raise Exception("P2P_CONNECT(join) failed")
644 def tdls_setup(self, peer):
645 cmd = "TDLS_SETUP " + peer
646 if "FAIL" in self.group_request(cmd):
647 raise Exception("Failed to request TDLS setup")
650 def tdls_teardown(self, peer):
651 cmd = "TDLS_TEARDOWN " + peer
652 if "FAIL" in self.group_request(cmd):
653 raise Exception("Failed to request TDLS teardown")
656 def connect(self, ssid=None, ssid2=None, **kwargs):
657 logger.info("Connect STA " + self.ifname + " to AP")
658 id = self.add_network()
660 self.set_network_quoted(id, "ssid", ssid)
662 self.set_network(id, "ssid", ssid2)
664 quoted = [ "psk", "identity", "anonymous_identity", "password",
665 "ca_cert", "client_cert", "private_key",
666 "private_key_passwd", "ca_cert2", "client_cert2",
667 "private_key2", "phase1", "phase2", "domain_suffix_match",
668 "altsubject_match", "subject_match", "pac_file", "dh_file",
669 "bgscan", "ht_mcs", "id_str", "openssl_ciphers" ]
671 if field in kwargs and kwargs[field]:
672 self.set_network_quoted(id, field, kwargs[field])
674 not_quoted = [ "proto", "key_mgmt", "ieee80211w", "pairwise",
675 "group", "wep_key0", "scan_freq", "eap",
676 "eapol_flags", "fragment_size", "scan_ssid", "auth_alg",
677 "wpa_ptk_rekey", "disable_ht", "disable_vht", "bssid",
678 "disable_max_amsdu", "ampdu_factor", "ampdu_density",
679 "disable_ht40", "disable_sgi", "disable_ldpc",
680 "ht40_intolerant", "update_identifier", "mac_addr" ]
681 for field in not_quoted:
682 if field in kwargs and kwargs[field]:
683 self.set_network(id, field, kwargs[field])
685 if "raw_psk" in kwargs and kwargs['raw_psk']:
686 self.set_network(id, "psk", kwargs['raw_psk'])
687 if "password_hex" in kwargs and kwargs['password_hex']:
688 self.set_network(id, "password", kwargs['password_hex'])
689 if "peerkey" in kwargs and kwargs['peerkey']:
690 self.set_network(id, "peerkey", "1")
691 if "okc" in kwargs and kwargs['okc']:
692 self.set_network(id, "proactive_key_caching", "1")
693 if "ocsp" in kwargs and kwargs['ocsp']:
694 self.set_network(id, "ocsp", str(kwargs['ocsp']))
695 if "only_add_network" in kwargs and kwargs['only_add_network']:
697 if "wait_connect" not in kwargs or kwargs['wait_connect']:
699 self.connect_network(id, timeout=20)
701 self.connect_network(id)
704 self.select_network(id)
707 def scan(self, type=None, freq=None, no_wait=False, only_new=False):
709 cmd = "SCAN TYPE=" + type
713 cmd = cmd + " freq=" + freq
718 if not "OK" in self.request(cmd):
719 raise Exception("Failed to trigger scan")
722 ev = self.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
724 raise Exception("Scan timed out")
726 def scan_for_bss(self, bssid, freq=None, force_scan=False):
727 if not force_scan and self.get_bss(bssid) is not None:
729 for i in range(0, 10):
730 self.scan(freq=freq, type="ONLY")
731 if self.get_bss(bssid) is not None:
733 raise Exception("Could not find BSS " + bssid + " in scan")
735 def roam(self, bssid, fail_test=False):
737 if "OK" not in self.request("ROAM " + bssid):
738 raise Exception("ROAM failed")
740 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
742 raise Exception("Unexpected connection")
745 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
747 raise Exception("Roaming with the AP timed out")
750 def roam_over_ds(self, bssid, fail_test=False):
752 if "OK" not in self.request("FT_DS " + bssid):
753 raise Exception("FT_DS failed")
755 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
757 raise Exception("Unexpected connection")
760 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
762 raise Exception("Roaming with the AP timed out")
765 def wps_reg(self, bssid, pin, new_ssid=None, key_mgmt=None, cipher=None,
766 new_passphrase=None, no_wait=False):
769 self.request("WPS_REG " + bssid + " " + pin + " " +
770 new_ssid.encode("hex") + " " + key_mgmt + " " +
771 cipher + " " + new_passphrase.encode("hex"))
774 ev = self.wait_event(["WPS-SUCCESS"], timeout=15)
776 self.request("WPS_REG " + bssid + " " + pin)
779 ev = self.wait_event(["WPS-CRED-RECEIVED"], timeout=15)
781 raise Exception("WPS cred timed out")
782 ev = self.wait_event(["WPS-FAIL"], timeout=15)
784 raise Exception("WPS timed out")
785 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
787 raise Exception("Association with the AP timed out")
790 self.request("RELOG")
792 def wait_completed(self, timeout=10):
793 for i in range(0, timeout * 2):
794 if self.get_status_field("wpa_state") == "COMPLETED":
797 raise Exception("Timeout while waiting for COMPLETED state")
799 def get_capability(self, field):
800 res = self.request("GET_CAPABILITY " + field)
803 return res.split(' ')
805 def get_bss(self, bssid):
806 res = self.request("BSS " + bssid)
809 lines = res.splitlines()
812 [name,value] = l.split('=', 1)
818 def get_pmksa(self, bssid):
819 res = self.request("PMKSA")
820 lines = res.splitlines()
825 [index,aa,pmkid,expiration,opportunistic] = l.split(' ')
826 vals['index'] = index
827 vals['pmkid'] = pmkid
828 vals['expiration'] = expiration
829 vals['opportunistic'] = opportunistic
833 def get_sta(self, addr, info=None, next=False):
834 cmd = "STA-NEXT " if next else "STA "
836 res = self.request("STA-FIRST")
838 res = self.request(cmd + addr + " " + info)
840 res = self.request(cmd + addr)
841 lines = res.splitlines()
849 [name,value] = l.split('=', 1)
853 def mgmt_rx(self, timeout=5):
854 ev = self.wait_event(["MGMT-RX"], timeout=timeout)
858 items = ev.split(' ')
859 field,val = items[1].split('=')
861 raise Exception("Unexpected MGMT-RX event format: " + ev)
863 frame = binascii.unhexlify(items[4])
866 hdr = struct.unpack('<HH6B6B6BH', frame[0:24])
868 msg['subtype'] = (hdr[0] >> 4) & 0xf
870 msg['duration'] = hdr[0]
872 msg['da'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
874 msg['sa'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
876 msg['bssid'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
878 msg['seq_ctrl'] = hdr[0]
879 msg['payload'] = frame[24:]