3 # Python class for controlling wpa_supplicant
4 # Copyright (c) 2013, Jouni Malinen <j@w1.fi>
6 # This software may be distributed under the terms of the BSD license.
7 # See README for more details.
16 logger = logging.getLogger()
17 wpas_ctrl = '/var/run/wpa_supplicant'
20 def __init__(self, ifname, global_iface=None):
22 self.group_ifname = None
23 self.ctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
24 self.mon = wpaspy.Ctrl(os.path.join(wpas_ctrl, 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 request(self, cmd):
34 logger.debug(self.ifname + ": CTRL: " + cmd)
35 return self.ctrl.request(cmd)
37 def global_request(self, cmd):
38 if self.global_iface is None:
41 logger.debug(self.ifname + ": CTRL: " + cmd)
42 return self.global_ctrl.request(cmd)
44 def group_request(self, cmd):
45 if self.group_ifname and self.group_ifname != self.ifname:
46 logger.debug(self.group_ifname + ": CTRL: " + cmd)
47 gctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, self.group_ifname))
48 return gctrl.request(cmd)
49 return self.request(cmd)
52 return "PONG" in self.request("PING")
55 res = self.request("FLUSH")
57 logger.info("FLUSH to " + self.ifname + " failed: " + res)
58 self.request("SET ignore_old_scan_res 0")
59 self.request("SET external_sim 0")
60 self.request("SET hessid 00:00:00:00:00:00")
61 self.request("SET access_network_type 15")
62 self.request("SET p2p_add_cli_chan 0")
63 self.request("SET p2p_no_go_freq ")
64 self.request("SET p2p_pref_chan ")
65 self.request("SET disallow_aps ")
66 self.request("SET p2p_no_group_iface 1")
67 self.request("P2P_SET per_sta_psk 0")
68 self.request("P2P_SET disabled 0")
69 self.request("P2P_SERVICE_FLUSH")
70 self.group_ifname = None
75 state = self.get_driver_status_field("scan_state")
76 if "SCAN_STARTED" in state or "SCAN_REQUESTED" in state:
77 logger.info(self.ifname + ": Waiting for scan operation to complete before continuing")
83 logger.error(self.ifname + ": Driver scan state did not clear")
84 print "Trying to clear cfg80211/mac80211 scan state"
86 cmd = ["sudo", "ifconfig", self.ifname, "down"]
88 except subprocess.CalledProcessError, e:
89 logger.info("ifconfig failed: " + str(e.returncode))
92 cmd = ["sudo", "ifconfig", self.ifname, "up"]
94 except subprocess.CalledProcessError, e:
95 logger.info("ifconfig failed: " + str(e.returncode))
99 logger.info("No PING response from " + self.ifname + " after reset")
101 def add_network(self):
102 id = self.request("ADD_NETWORK")
104 raise Exception("ADD_NETWORK failed")
107 def remove_network(self, id):
108 id = self.request("REMOVE_NETWORK " + str(id))
110 raise Exception("REMOVE_NETWORK failed")
113 def set_network(self, id, field, value):
114 res = self.request("SET_NETWORK " + str(id) + " " + field + " " + value)
116 raise Exception("SET_NETWORK failed")
119 def set_network_quoted(self, id, field, value):
120 res = self.request("SET_NETWORK " + str(id) + " " + field + ' "' + value + '"')
122 raise Exception("SET_NETWORK failed")
125 def list_networks(self):
126 res = self.request("LIST_NETWORKS")
127 lines = res.splitlines()
130 if "network id" in l:
132 [id,ssid,bssid,flags] = l.split('\t')
135 network['ssid'] = ssid
136 network['bssid'] = bssid
137 network['flags'] = flags
138 networks.append(network)
141 def hs20_enable(self):
142 self.request("SET interworking 1")
143 self.request("SET hs20 1")
146 id = self.request("ADD_CRED")
148 raise Exception("ADD_CRED failed")
151 def remove_cred(self, id):
152 id = self.request("REMOVE_CRED " + str(id))
154 raise Exception("REMOVE_CRED failed")
157 def set_cred(self, id, field, value):
158 res = self.request("SET_CRED " + str(id) + " " + field + " " + value)
160 raise Exception("SET_CRED failed")
163 def set_cred_quoted(self, id, field, value):
164 res = self.request("SET_CRED " + str(id) + " " + field + ' "' + value + '"')
166 raise Exception("SET_CRED failed")
169 def add_cred_values(self, params):
172 quoted = [ "realm", "username", "password", "domain", "imsi",
173 "excluded_ssid", "milenage", "ca_cert", "client_cert",
177 self.set_cred_quoted(id, field, params[field])
179 not_quoted = [ "eap", "roaming_consortium",
180 "required_roaming_consortium" ]
181 for field in not_quoted:
183 self.set_cred(id, field, params[field])
187 def select_network(self, id):
188 id = self.request("SELECT_NETWORK " + str(id))
190 raise Exception("SELECT_NETWORK failed")
193 def connect_network(self, id):
195 self.select_network(id)
196 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
198 raise Exception("Association with the AP timed out")
201 def get_status(self):
202 res = self.request("STATUS")
203 lines = res.splitlines()
206 [name,value] = l.split('=', 1)
210 def get_status_field(self, field):
211 vals = self.get_status()
216 def get_group_status(self):
217 res = self.group_request("STATUS")
218 lines = res.splitlines()
221 [name,value] = l.split('=', 1)
225 def get_group_status_field(self, field):
226 vals = self.get_group_status()
231 def get_driver_status(self):
232 res = self.request("STATUS-DRIVER")
233 lines = res.splitlines()
236 [name,value] = l.split('=', 1)
240 def get_driver_status_field(self, field):
241 vals = self.get_driver_status()
246 def p2p_dev_addr(self):
247 return self.get_status_field("p2p_device_address")
249 def p2p_interface_addr(self):
250 return self.get_group_status_field("address")
252 def p2p_listen(self):
253 return self.global_request("P2P_LISTEN")
255 def p2p_find(self, social=False):
257 return self.global_request("P2P_FIND type=social")
258 return self.global_request("P2P_FIND")
260 def p2p_stop_find(self):
261 return self.global_request("P2P_STOP_FIND")
263 def wps_read_pin(self):
264 #TODO: make this random
265 self.pin = "12345670"
268 def peer_known(self, peer, full=True):
269 res = self.global_request("P2P_PEER " + peer)
270 if peer.lower() not in res.lower():
274 return "[PROBE_REQ_ONLY]" not in res
276 def discover_peer(self, peer, full=True, timeout=15, social=True):
277 logger.info(self.ifname + ": Trying to discover peer " + peer)
278 if self.peer_known(peer, full):
280 self.p2p_find(social)
282 while count < timeout:
285 if self.peer_known(peer, full):
289 def get_peer(self, peer):
290 res = self.global_request("P2P_PEER " + peer)
291 if peer.lower() not in res.lower():
292 raise Exception("Peer information not available")
293 lines = res.splitlines()
297 [name,value] = l.split('=', 1)
301 def group_form_result(self, ev, expect_failure=False, go_neg_res=None):
303 if "P2P-GROUP-STARTED" in ev:
304 raise Exception("Group formation succeeded when expecting failure")
305 exp = r'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
306 s = re.split(exp, ev)
310 res['result'] = 'go-neg-failed'
311 res['status'] = int(s[2])
314 if "P2P-GROUP-STARTED" not in ev:
315 raise Exception("No P2P-GROUP-STARTED event seen")
317 exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
318 s = re.split(exp, ev)
320 raise Exception("Could not parse P2P-GROUP-STARTED")
322 res['result'] = 'success'
324 self.group_ifname = s[2]
328 if "[PERSISTENT]" in ev:
329 res['persistent'] = True
331 res['persistent'] = False
332 p = re.match(r'psk=([0-9a-f]*)', s[6])
334 res['psk'] = p.group(1)
335 p = re.match(r'passphrase="(.*)"', s[6])
337 res['passphrase'] = p.group(1)
338 res['go_dev_addr'] = s[7]
341 exp = r'<.>(P2P-GO-NEG-SUCCESS) role=(GO|client) freq=([0-9]*)'
342 s = re.split(exp, go_neg_res)
344 raise Exception("Could not parse P2P-GO-NEG-SUCCESS")
345 res['go_neg_role'] = s[2]
346 res['go_neg_freq'] = s[3]
350 def p2p_go_neg_auth(self, peer, pin, method, go_intent=None, persistent=False, freq=None):
351 if not self.discover_peer(peer):
352 raise Exception("Peer " + peer + " not found")
354 cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
356 cmd = cmd + ' go_intent=' + str(go_intent)
358 cmd = cmd + ' freq=' + str(freq)
360 cmd = cmd + " persistent"
361 if "OK" in self.global_request(cmd):
363 raise Exception("P2P_CONNECT (auth) failed")
365 def p2p_go_neg_auth_result(self, timeout=1, expect_failure=False):
367 ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
368 "P2P-GO-NEG-FAILURE"], timeout);
372 raise Exception("Group formation timed out")
373 if "P2P-GO-NEG-SUCCESS" in ev:
375 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout);
379 raise Exception("Group formation timed out")
381 return self.group_form_result(ev, expect_failure, go_neg_res)
383 def p2p_go_neg_init(self, peer, pin, method, timeout=0, go_intent=None, expect_failure=False, persistent=False, freq=None):
384 if not self.discover_peer(peer):
385 raise Exception("Peer " + peer + " not found")
388 cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
390 cmd = "P2P_CONNECT " + peer + " " + method
392 cmd = cmd + ' go_intent=' + str(go_intent)
394 cmd = cmd + ' freq=' + str(freq)
396 cmd = cmd + " persistent"
397 if "OK" in self.global_request(cmd):
402 ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
403 "P2P-GO-NEG-FAILURE"], timeout)
407 raise Exception("Group formation timed out")
408 if "P2P-GO-NEG-SUCCESS" in ev:
410 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
414 raise Exception("Group formation timed out")
416 return self.group_form_result(ev, expect_failure, go_neg_res)
417 raise Exception("P2P_CONNECT failed")
419 def wait_event(self, events, timeout=10):
421 while count < timeout * 10:
424 while self.mon.pending():
426 logger.debug(self.ifname + ": " + ev)
432 def wait_global_event(self, events, timeout):
433 if self.global_iface is None:
434 self.wait_event(events, timeout)
437 while count < timeout * 10:
440 while self.global_mon.pending():
441 ev = self.global_mon.recv()
442 logger.debug(self.ifname + "(global): " + ev)
448 def wait_go_ending_session(self):
449 ev = self.wait_event(["P2P-GROUP-REMOVED"], timeout=3)
451 raise Exception("Group removal event timed out")
452 if "reason=GO_ENDING_SESSION" not in ev:
453 raise Exception("Unexpected group removal reason")
455 def dump_monitor(self):
456 while self.mon.pending():
458 logger.debug(self.ifname + ": " + ev)
459 while self.global_mon.pending():
460 ev = self.global_mon.recv()
461 logger.debug(self.ifname + "(global): " + ev)
463 def remove_group(self, ifname=None):
465 ifname = self.group_ifname if self.group_ifname else self.ifname
466 if "OK" not in self.global_request("P2P_GROUP_REMOVE " + ifname):
467 raise Exception("Group could not be removed")
468 self.group_ifname = None
470 def p2p_start_go(self, persistent=None, freq=None):
472 cmd = "P2P_GROUP_ADD"
473 if persistent is None:
475 elif persistent is True:
476 cmd = cmd + " persistent"
478 cmd = cmd + " persistent=" + str(persistent)
480 cmd = cmd + " freq=" + str(freq)
481 if "OK" in self.global_request(cmd):
482 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
484 raise Exception("GO start up timed out")
486 return self.group_form_result(ev)
487 raise Exception("P2P_GROUP_ADD failed")
489 def p2p_go_authorize_client(self, pin):
490 cmd = "WPS_PIN any " + pin
491 if "FAIL" in self.group_request(cmd):
492 raise Exception("Failed to authorize client connection on GO")
495 def p2p_go_authorize_client_pbc(self):
497 if "FAIL" in self.group_request(cmd):
498 raise Exception("Failed to authorize client connection on GO")
501 def p2p_connect_group(self, go_addr, pin, timeout=0, social=False):
503 if not self.discover_peer(go_addr, social=social):
504 raise Exception("GO " + go_addr + " not found")
506 cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
507 if "OK" in self.global_request(cmd):
511 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
513 raise Exception("Joining the group timed out")
515 return self.group_form_result(ev)
516 raise Exception("P2P_CONNECT(join) failed")
518 def tdls_setup(self, peer):
519 cmd = "TDLS_SETUP " + peer
520 if "FAIL" in self.group_request(cmd):
521 raise Exception("Failed to request TDLS setup")
524 def tdls_teardown(self, peer):
525 cmd = "TDLS_TEARDOWN " + peer
526 if "FAIL" in self.group_request(cmd):
527 raise Exception("Failed to request TDLS teardown")
530 def connect(self, ssid, psk=None, proto=None, key_mgmt=None, wep_key0=None,
531 ieee80211w=None, pairwise=None, group=None, scan_freq=None,
532 eap=None, identity=None, anonymous_identity=None,
533 password=None, phase1=None, phase2=None, ca_cert=None,
534 domain_suffix_match=None, password_hex=None,
535 client_cert=None, private_key=None, peerkey=False, okc=False,
536 wait_connect=True, only_add_network=False):
537 logger.info("Connect STA " + self.ifname + " to AP")
538 id = self.add_network()
539 self.set_network_quoted(id, "ssid", ssid)
541 self.set_network_quoted(id, "psk", psk)
543 self.set_network(id, "proto", proto)
545 self.set_network(id, "key_mgmt", key_mgmt)
547 self.set_network(id, "ieee80211w", ieee80211w)
549 self.set_network(id, "pairwise", pairwise)
551 self.set_network(id, "group", group)
553 self.set_network(id, "wep_key0", wep_key0)
555 self.set_network(id, "scan_freq", scan_freq)
557 self.set_network(id, "eap", eap)
559 self.set_network_quoted(id, "identity", identity)
560 if anonymous_identity:
561 self.set_network_quoted(id, "anonymous_identity",
564 self.set_network_quoted(id, "password", password)
566 self.set_network(id, "password", password_hex)
568 self.set_network_quoted(id, "ca_cert", ca_cert)
570 self.set_network_quoted(id, "client_cert", client_cert)
572 self.set_network_quoted(id, "private_key", private_key)
574 self.set_network_quoted(id, "phase1", phase1)
576 self.set_network_quoted(id, "phase2", phase2)
577 if domain_suffix_match:
578 self.set_network_quoted(id, "domain_suffix_match",
581 self.set_network(id, "peerkey", "1")
583 self.set_network(id, "proactive_key_caching", "1")
587 self.connect_network(id)
590 self.select_network(id)
593 def scan(self, type=None, freq=None):
595 cmd = "SCAN TYPE=" + type
599 cmd = cmd + " freq=" + freq
601 if not "OK" in self.request(cmd):
602 raise Exception("Failed to trigger scan")
603 ev = self.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
605 raise Exception("Scan timed out")
607 def roam(self, bssid):
609 self.request("ROAM " + bssid)
610 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
612 raise Exception("Roaming with the AP timed out")
615 def roam_over_ds(self, bssid):
617 self.request("FT_DS " + bssid)
618 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
620 raise Exception("Roaming with the AP timed out")
623 def wps_reg(self, bssid, pin, new_ssid=None, key_mgmt=None, cipher=None,
624 new_passphrase=None, no_wait=False):
627 self.request("WPS_REG " + bssid + " " + pin + " " +
628 new_ssid.encode("hex") + " " + key_mgmt + " " +
629 cipher + " " + new_passphrase.encode("hex"))
632 ev = self.wait_event(["WPS-SUCCESS"], timeout=15)
634 self.request("WPS_REG " + bssid + " " + pin)
637 ev = self.wait_event(["WPS-CRED-RECEIVED"], timeout=15)
639 raise Exception("WPS cred timed out")
640 ev = self.wait_event(["WPS-FAIL"], timeout=15)
642 raise Exception("WPS timed out")
643 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
645 raise Exception("Association with the AP timed out")
648 self.request("RELOG")
650 def wait_completed(self, timeout=10):
651 for i in range(0, timeout * 2):
652 if self.get_status_field("wpa_state") == "COMPLETED":
655 raise Exception("Timeout while waiting for COMPLETED state")
657 def get_capability(self, field):
658 res = self.request("GET_CAPABILITY " + field)
661 return res.split(' ')
663 def get_bss(self, bssid):
664 res = self.request("BSS " + bssid)
665 lines = res.splitlines()
668 [name,value] = l.split('=', 1)
672 def get_pmksa(self, bssid):
673 res = self.request("PMKSA")
674 lines = res.splitlines()
679 [index,aa,pmkid,expiration,opportunistic] = l.split(' ')
680 vals['index'] = index
681 vals['pmkid'] = pmkid
682 vals['expiration'] = expiration
683 vals['opportunistic'] = opportunistic