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")
338 def p2p_listen(self):
339 return self.global_request("P2P_LISTEN")
341 def p2p_find(self, social=False, progressive=False, dev_id=None, dev_type=None):
344 cmd = cmd + " type=social"
346 cmd = cmd + " type=progressive"
348 cmd = cmd + " dev_id=" + dev_id
350 cmd = cmd + " dev_type=" + dev_type
351 return self.global_request(cmd)
353 def p2p_stop_find(self):
354 return self.global_request("P2P_STOP_FIND")
356 def wps_read_pin(self):
357 self.pin = self.request("WPS_PIN get").rstrip("\n")
358 if "FAIL" in self.pin:
359 raise Exception("Could not generate PIN")
362 def peer_known(self, peer, full=True):
363 res = self.global_request("P2P_PEER " + peer)
364 if peer.lower() not in res.lower():
368 return "[PROBE_REQ_ONLY]" not in res
370 def discover_peer(self, peer, full=True, timeout=15, social=True, force_find=False):
371 logger.info(self.ifname + ": Trying to discover peer " + peer)
372 if not force_find and self.peer_known(peer, full):
374 self.p2p_find(social)
376 while count < timeout:
379 if self.peer_known(peer, full):
383 def get_peer(self, peer):
384 res = self.global_request("P2P_PEER " + peer)
385 if peer.lower() not in res.lower():
386 raise Exception("Peer information not available")
387 lines = res.splitlines()
391 [name,value] = l.split('=', 1)
395 def group_form_result(self, ev, expect_failure=False, go_neg_res=None):
397 if "P2P-GROUP-STARTED" in ev:
398 raise Exception("Group formation succeeded when expecting failure")
399 exp = r'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
400 s = re.split(exp, ev)
404 res['result'] = 'go-neg-failed'
405 res['status'] = int(s[2])
408 if "P2P-GROUP-STARTED" not in ev:
409 raise Exception("No P2P-GROUP-STARTED event seen")
411 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.]*)'
412 s = re.split(exp, ev)
414 exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
415 s = re.split(exp, ev)
417 raise Exception("Could not parse P2P-GROUP-STARTED")
419 res['result'] = 'success'
421 self.group_ifname = s[2]
425 if "[PERSISTENT]" in ev:
426 res['persistent'] = True
428 res['persistent'] = False
429 p = re.match(r'psk=([0-9a-f]*)', s[6])
431 res['psk'] = p.group(1)
432 p = re.match(r'passphrase="(.*)"', s[6])
434 res['passphrase'] = p.group(1)
435 res['go_dev_addr'] = s[7]
437 if len(s) > 8 and len(s[8]) > 0:
438 res['ip_addr'] = s[8]
440 res['ip_mask'] = s[9]
442 res['go_ip_addr'] = s[10]
445 exp = r'<.>(P2P-GO-NEG-SUCCESS) role=(GO|client) freq=([0-9]*)'
446 s = re.split(exp, go_neg_res)
448 raise Exception("Could not parse P2P-GO-NEG-SUCCESS")
449 res['go_neg_role'] = s[2]
450 res['go_neg_freq'] = s[3]
454 def p2p_go_neg_auth(self, peer, pin, method, go_intent=None, persistent=False, freq=None):
455 if not self.discover_peer(peer):
456 raise Exception("Peer " + peer + " not found")
458 cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
460 cmd = cmd + ' go_intent=' + str(go_intent)
462 cmd = cmd + ' freq=' + str(freq)
464 cmd = cmd + " persistent"
465 if "OK" in self.global_request(cmd):
467 raise Exception("P2P_CONNECT (auth) failed")
469 def p2p_go_neg_auth_result(self, timeout=1, expect_failure=False):
471 ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
472 "P2P-GO-NEG-FAILURE"], timeout);
476 raise Exception("Group formation timed out")
477 if "P2P-GO-NEG-SUCCESS" in ev:
479 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout);
483 raise Exception("Group formation timed out")
485 return self.group_form_result(ev, expect_failure, go_neg_res)
487 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):
488 if not self.discover_peer(peer):
489 raise Exception("Peer " + peer + " not found")
492 cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
494 cmd = "P2P_CONNECT " + peer + " " + method
496 cmd = cmd + ' go_intent=' + str(go_intent)
498 cmd = cmd + ' freq=' + str(freq)
500 cmd = cmd + " persistent"
502 cmd = cmd + " persistent=" + persistent_id
504 cmd = cmd + " provdisc"
505 if "OK" in self.global_request(cmd):
510 ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
511 "P2P-GO-NEG-FAILURE"], timeout)
515 raise Exception("Group formation timed out")
516 if "P2P-GO-NEG-SUCCESS" in ev:
518 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
522 raise Exception("Group formation timed out")
524 return self.group_form_result(ev, expect_failure, go_neg_res)
525 raise Exception("P2P_CONNECT failed")
527 def wait_event(self, events, timeout=10):
528 start = os.times()[4]
530 while self.mon.pending():
532 logger.debug(self.ifname + ": " + ev)
537 remaining = start + timeout - now
540 if not self.mon.pending(timeout=remaining):
544 def wait_global_event(self, events, timeout):
545 if self.global_iface is None:
546 self.wait_event(events, timeout)
548 start = os.times()[4]
550 while self.global_mon.pending():
551 ev = self.global_mon.recv()
552 logger.debug(self.ifname + "(global): " + ev)
557 remaining = start + timeout - now
560 if not self.global_mon.pending(timeout=remaining):
564 def wait_go_ending_session(self):
565 ev = self.wait_event(["P2P-GROUP-REMOVED"], timeout=3)
567 raise Exception("Group removal event timed out")
568 if "reason=GO_ENDING_SESSION" not in ev:
569 raise Exception("Unexpected group removal reason")
571 def dump_monitor(self):
572 while self.mon.pending():
574 logger.debug(self.ifname + ": " + ev)
575 while self.global_mon.pending():
576 ev = self.global_mon.recv()
577 logger.debug(self.ifname + "(global): " + ev)
579 def remove_group(self, ifname=None):
581 ifname = self.group_ifname if self.group_ifname else self.ifname
582 if "OK" not in self.global_request("P2P_GROUP_REMOVE " + ifname):
583 raise Exception("Group could not be removed")
584 self.group_ifname = None
586 def p2p_start_go(self, persistent=None, freq=None):
588 cmd = "P2P_GROUP_ADD"
589 if persistent is None:
591 elif persistent is True:
592 cmd = cmd + " persistent"
594 cmd = cmd + " persistent=" + str(persistent)
596 cmd = cmd + " freq=" + str(freq)
597 if "OK" in self.global_request(cmd):
598 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
600 raise Exception("GO start up timed out")
602 return self.group_form_result(ev)
603 raise Exception("P2P_GROUP_ADD failed")
605 def p2p_go_authorize_client(self, pin):
606 cmd = "WPS_PIN any " + pin
607 if "FAIL" in self.group_request(cmd):
608 raise Exception("Failed to authorize client connection on GO")
611 def p2p_go_authorize_client_pbc(self):
613 if "FAIL" in self.group_request(cmd):
614 raise Exception("Failed to authorize client connection on GO")
617 def p2p_connect_group(self, go_addr, pin, timeout=0, social=False):
619 if not self.discover_peer(go_addr, social=social):
620 if social or not self.discover_peer(go_addr, social=social):
621 raise Exception("GO " + go_addr + " not found")
623 cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
624 if "OK" in self.global_request(cmd):
628 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
630 raise Exception("Joining the group timed out")
632 return self.group_form_result(ev)
633 raise Exception("P2P_CONNECT(join) failed")
635 def tdls_setup(self, peer):
636 cmd = "TDLS_SETUP " + peer
637 if "FAIL" in self.group_request(cmd):
638 raise Exception("Failed to request TDLS setup")
641 def tdls_teardown(self, peer):
642 cmd = "TDLS_TEARDOWN " + peer
643 if "FAIL" in self.group_request(cmd):
644 raise Exception("Failed to request TDLS teardown")
647 def connect(self, ssid=None, ssid2=None, **kwargs):
648 logger.info("Connect STA " + self.ifname + " to AP")
649 id = self.add_network()
651 self.set_network_quoted(id, "ssid", ssid)
653 self.set_network(id, "ssid", ssid2)
655 quoted = [ "psk", "identity", "anonymous_identity", "password",
656 "ca_cert", "client_cert", "private_key",
657 "private_key_passwd", "ca_cert2", "client_cert2",
658 "private_key2", "phase1", "phase2", "domain_suffix_match",
659 "altsubject_match", "subject_match", "pac_file", "dh_file",
660 "bgscan", "ht_mcs", "id_str" ]
662 if field in kwargs and kwargs[field]:
663 self.set_network_quoted(id, field, kwargs[field])
665 not_quoted = [ "proto", "key_mgmt", "ieee80211w", "pairwise",
666 "group", "wep_key0", "scan_freq", "eap",
667 "eapol_flags", "fragment_size", "scan_ssid", "auth_alg",
668 "wpa_ptk_rekey", "disable_ht", "disable_vht", "bssid",
669 "disable_max_amsdu", "ampdu_factor", "ampdu_density",
670 "disable_ht40", "disable_sgi", "disable_ldpc",
671 "ht40_intolerant", "update_identifier", "mac_addr" ]
672 for field in not_quoted:
673 if field in kwargs and kwargs[field]:
674 self.set_network(id, field, kwargs[field])
676 if "raw_psk" in kwargs and kwargs['raw_psk']:
677 self.set_network(id, "psk", kwargs['raw_psk'])
678 if "password_hex" in kwargs and kwargs['password_hex']:
679 self.set_network(id, "password", kwargs['password_hex'])
680 if "peerkey" in kwargs and kwargs['peerkey']:
681 self.set_network(id, "peerkey", "1")
682 if "okc" in kwargs and kwargs['okc']:
683 self.set_network(id, "proactive_key_caching", "1")
684 if "ocsp" in kwargs and kwargs['ocsp']:
685 self.set_network(id, "ocsp", str(kwargs['ocsp']))
686 if "only_add_network" in kwargs and kwargs['only_add_network']:
688 if "wait_connect" not in kwargs or kwargs['wait_connect']:
690 self.connect_network(id, timeout=20)
692 self.connect_network(id)
695 self.select_network(id)
698 def scan(self, type=None, freq=None, no_wait=False, only_new=False):
700 cmd = "SCAN TYPE=" + type
704 cmd = cmd + " freq=" + freq
709 if not "OK" in self.request(cmd):
710 raise Exception("Failed to trigger scan")
713 ev = self.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
715 raise Exception("Scan timed out")
717 def scan_for_bss(self, bssid, freq=None, force_scan=False):
718 if not force_scan and self.get_bss(bssid) is not None:
720 for i in range(0, 10):
721 self.scan(freq=freq, type="ONLY")
722 if self.get_bss(bssid) is not None:
724 raise Exception("Could not find BSS " + bssid + " in scan")
726 def roam(self, bssid, fail_test=False):
728 if "OK" not in self.request("ROAM " + bssid):
729 raise Exception("ROAM failed")
731 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
733 raise Exception("Unexpected connection")
736 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
738 raise Exception("Roaming with the AP timed out")
741 def roam_over_ds(self, bssid, fail_test=False):
743 if "OK" not in self.request("FT_DS " + bssid):
744 raise Exception("FT_DS failed")
746 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
748 raise Exception("Unexpected connection")
751 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
753 raise Exception("Roaming with the AP timed out")
756 def wps_reg(self, bssid, pin, new_ssid=None, key_mgmt=None, cipher=None,
757 new_passphrase=None, no_wait=False):
760 self.request("WPS_REG " + bssid + " " + pin + " " +
761 new_ssid.encode("hex") + " " + key_mgmt + " " +
762 cipher + " " + new_passphrase.encode("hex"))
765 ev = self.wait_event(["WPS-SUCCESS"], timeout=15)
767 self.request("WPS_REG " + bssid + " " + pin)
770 ev = self.wait_event(["WPS-CRED-RECEIVED"], timeout=15)
772 raise Exception("WPS cred timed out")
773 ev = self.wait_event(["WPS-FAIL"], timeout=15)
775 raise Exception("WPS timed out")
776 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
778 raise Exception("Association with the AP timed out")
781 self.request("RELOG")
783 def wait_completed(self, timeout=10):
784 for i in range(0, timeout * 2):
785 if self.get_status_field("wpa_state") == "COMPLETED":
788 raise Exception("Timeout while waiting for COMPLETED state")
790 def get_capability(self, field):
791 res = self.request("GET_CAPABILITY " + field)
794 return res.split(' ')
796 def get_bss(self, bssid):
797 res = self.request("BSS " + bssid)
800 lines = res.splitlines()
803 [name,value] = l.split('=', 1)
809 def get_pmksa(self, bssid):
810 res = self.request("PMKSA")
811 lines = res.splitlines()
816 [index,aa,pmkid,expiration,opportunistic] = l.split(' ')
817 vals['index'] = index
818 vals['pmkid'] = pmkid
819 vals['expiration'] = expiration
820 vals['opportunistic'] = opportunistic
824 def get_sta(self, addr, info=None, next=False):
825 cmd = "STA-NEXT " if next else "STA "
827 res = self.request("STA-FIRST")
829 res = self.request(cmd + addr + " " + info)
831 res = self.request(cmd + addr)
832 lines = res.splitlines()
840 [name,value] = l.split('=', 1)
844 def mgmt_rx(self, timeout=5):
845 ev = self.wait_event(["MGMT-RX"], timeout=timeout)
849 items = ev.split(' ')
850 field,val = items[1].split('=')
852 raise Exception("Unexpected MGMT-RX event format: " + ev)
854 frame = binascii.unhexlify(items[4])
857 hdr = struct.unpack('<HH6B6B6BH', frame[0:24])
859 msg['subtype'] = (hdr[0] >> 4) & 0xf
861 msg['duration'] = hdr[0]
863 msg['da'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
865 msg['sa'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
867 msg['bssid'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
869 msg['seq_ctrl'] = hdr[0]
870 msg['payload'] = frame[24:]