]>
git.ipfire.org Git - thirdparty/hostap.git/blob - tests/hwsim/wpasupplicant.py
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.
14 logger
= logging
.getLogger()
15 wpas_ctrl
= '/var/run/wpa_supplicant'
18 def __init__(self
, ifname
=None, global_iface
=None):
19 self
.group_ifname
= None
21 self
.set_ifname(ifname
)
25 self
.global_iface
= global_iface
27 self
.global_ctrl
= wpaspy
.Ctrl(global_iface
)
28 self
.global_mon
= wpaspy
.Ctrl(global_iface
)
29 self
.global_mon
.attach()
31 def set_ifname(self
, ifname
):
33 self
.ctrl
= wpaspy
.Ctrl(os
.path
.join(wpas_ctrl
, ifname
))
34 self
.mon
= wpaspy
.Ctrl(os
.path
.join(wpas_ctrl
, ifname
))
37 def remove_ifname(self
):
44 def interface_add(self
, ifname
, driver
="nl80211", drv_params
=None):
46 groups
= subprocess
.check_output(["id"])
47 group
= "admin" if "(admin)" in groups
else "adm"
50 cmd
= "INTERFACE_ADD " + ifname
+ "\t\t" + driver
+ "\tDIR=/var/run/wpa_supplicant GROUP=" + group
52 cmd
= cmd
+ '\t' + drv_params
53 if "FAIL" in self
.global_request(cmd
):
54 raise Exception("Failed to add a dynamic wpa_supplicant interface")
55 self
.set_ifname(ifname
)
57 def interface_remove(self
, ifname
):
59 self
.global_request("INTERFACE_REMOVE " + ifname
)
61 def request(self
, cmd
):
62 logger
.debug(self
.ifname
+ ": CTRL: " + cmd
)
63 return self
.ctrl
.request(cmd
)
65 def global_request(self
, cmd
):
66 if self
.global_iface
is None:
69 ifname
= self
.ifname
or self
.global_iface
70 logger
.debug(ifname
+ ": CTRL: " + cmd
)
71 return self
.global_ctrl
.request(cmd
)
73 def group_request(self
, cmd
):
74 if self
.group_ifname
and self
.group_ifname
!= self
.ifname
:
75 logger
.debug(self
.group_ifname
+ ": CTRL: " + cmd
)
76 gctrl
= wpaspy
.Ctrl(os
.path
.join(wpas_ctrl
, self
.group_ifname
))
77 return gctrl
.request(cmd
)
78 return self
.request(cmd
)
81 return "PONG" in self
.request("PING")
84 res
= self
.request("FLUSH")
86 logger
.info("FLUSH to " + self
.ifname
+ " failed: " + res
)
87 self
.request("WPS_ER_STOP")
88 self
.request("SET external_sim 0")
89 self
.request("SET hessid 00:00:00:00:00:00")
90 self
.request("SET access_network_type 15")
91 self
.request("SET p2p_add_cli_chan 0")
92 self
.request("SET p2p_no_go_freq ")
93 self
.request("SET p2p_pref_chan ")
94 self
.request("SET p2p_no_group_iface 1")
95 self
.request("SET p2p_go_intent 7")
96 self
.group_ifname
= None
101 state
= self
.get_driver_status_field("scan_state")
102 if "SCAN_STARTED" in state
or "SCAN_REQUESTED" in state
:
103 logger
.info(self
.ifname
+ ": Waiting for scan operation to complete before continuing")
109 logger
.error(self
.ifname
+ ": Driver scan state did not clear")
110 print "Trying to clear cfg80211/mac80211 scan state"
112 cmd
= ["sudo", "ifconfig", self
.ifname
, "down"]
114 except subprocess
.CalledProcessError
, e
:
115 logger
.info("ifconfig failed: " + str(e
.returncode
))
116 logger
.info(e
.output
)
118 cmd
= ["sudo", "ifconfig", self
.ifname
, "up"]
120 except subprocess
.CalledProcessError
, e
:
121 logger
.info("ifconfig failed: " + str(e
.returncode
))
122 logger
.info(e
.output
)
124 # The ongoing scan could have discovered BSSes or P2P peers
125 logger
.info("Run FLUSH again since scan was in progress")
126 self
.request("FLUSH")
130 logger
.info("No PING response from " + self
.ifname
+ " after reset")
132 def add_network(self
):
133 id = self
.request("ADD_NETWORK")
135 raise Exception("ADD_NETWORK failed")
138 def remove_network(self
, id):
139 id = self
.request("REMOVE_NETWORK " + str(id))
141 raise Exception("REMOVE_NETWORK failed")
144 def get_network(self
, id, field
):
145 res
= self
.request("GET_NETWORK " + str(id) + " " + field
)
150 def set_network(self
, id, field
, value
):
151 res
= self
.request("SET_NETWORK " + str(id) + " " + field
+ " " + value
)
153 raise Exception("SET_NETWORK failed")
156 def set_network_quoted(self
, id, field
, value
):
157 res
= self
.request("SET_NETWORK " + str(id) + " " + field
+ ' "' + value
+ '"')
159 raise Exception("SET_NETWORK failed")
162 def list_networks(self
):
163 res
= self
.request("LIST_NETWORKS")
164 lines
= res
.splitlines()
167 if "network id" in l
:
169 [id,ssid
,bssid
,flags
] = l
.split('\t')
172 network
['ssid'] = ssid
173 network
['bssid'] = bssid
174 network
['flags'] = flags
175 networks
.append(network
)
178 def hs20_enable(self
):
179 self
.request("SET interworking 1")
180 self
.request("SET hs20 1")
183 id = self
.request("ADD_CRED")
185 raise Exception("ADD_CRED failed")
188 def remove_cred(self
, id):
189 id = self
.request("REMOVE_CRED " + str(id))
191 raise Exception("REMOVE_CRED failed")
194 def set_cred(self
, id, field
, value
):
195 res
= self
.request("SET_CRED " + str(id) + " " + field
+ " " + value
)
197 raise Exception("SET_CRED failed")
200 def set_cred_quoted(self
, id, field
, value
):
201 res
= self
.request("SET_CRED " + str(id) + " " + field
+ ' "' + value
+ '"')
203 raise Exception("SET_CRED failed")
206 def add_cred_values(self
, params
):
209 quoted
= [ "realm", "username", "password", "domain", "imsi",
210 "excluded_ssid", "milenage", "ca_cert", "client_cert",
214 self
.set_cred_quoted(id, field
, params
[field
])
216 not_quoted
= [ "eap", "roaming_consortium",
217 "required_roaming_consortium" ]
218 for field
in not_quoted
:
220 self
.set_cred(id, field
, params
[field
])
224 def select_network(self
, id):
225 id = self
.request("SELECT_NETWORK " + str(id))
227 raise Exception("SELECT_NETWORK failed")
230 def connect_network(self
, id, timeout
=10):
232 self
.select_network(id)
233 ev
= self
.wait_event(["CTRL-EVENT-CONNECTED"], timeout
=timeout
)
235 raise Exception("Association with the AP timed out")
238 def get_status(self
):
239 res
= self
.request("STATUS")
240 lines
= res
.splitlines()
244 [name
,value
] = l
.split('=', 1)
246 except ValueError, e
:
247 logger
.info(self
.ifname
+ ": Ignore unexpected STATUS line: " + l
)
250 def get_status_field(self
, field
):
251 vals
= self
.get_status()
256 def get_group_status(self
):
257 res
= self
.group_request("STATUS")
258 lines
= res
.splitlines()
261 [name
,value
] = l
.split('=', 1)
265 def get_group_status_field(self
, field
):
266 vals
= self
.get_group_status()
271 def get_driver_status(self
):
272 res
= self
.request("STATUS-DRIVER")
273 lines
= res
.splitlines()
276 [name
,value
] = l
.split('=', 1)
280 def get_driver_status_field(self
, field
):
281 vals
= self
.get_driver_status()
286 def p2p_dev_addr(self
):
287 return self
.get_status_field("p2p_device_address")
289 def p2p_interface_addr(self
):
290 return self
.get_group_status_field("address")
292 def p2p_listen(self
):
293 return self
.global_request("P2P_LISTEN")
295 def p2p_find(self
, social
=False, dev_id
=None, dev_type
=None):
298 cmd
= cmd
+ " type=social"
300 cmd
= cmd
+ " dev_id=" + dev_id
302 cmd
= cmd
+ " dev_type=" + dev_type
303 return self
.global_request(cmd
)
305 def p2p_stop_find(self
):
306 return self
.global_request("P2P_STOP_FIND")
308 def wps_read_pin(self
):
309 #TODO: make this random
310 self
.pin
= "12345670"
313 def peer_known(self
, peer
, full
=True):
314 res
= self
.global_request("P2P_PEER " + peer
)
315 if peer
.lower() not in res
.lower():
319 return "[PROBE_REQ_ONLY]" not in res
321 def discover_peer(self
, peer
, full
=True, timeout
=15, social
=True, force_find
=False):
322 logger
.info(self
.ifname
+ ": Trying to discover peer " + peer
)
323 if not force_find
and self
.peer_known(peer
, full
):
325 self
.p2p_find(social
)
327 while count
< timeout
:
330 if self
.peer_known(peer
, full
):
334 def get_peer(self
, peer
):
335 res
= self
.global_request("P2P_PEER " + peer
)
336 if peer
.lower() not in res
.lower():
337 raise Exception("Peer information not available")
338 lines
= res
.splitlines()
342 [name
,value
] = l
.split('=', 1)
346 def group_form_result(self
, ev
, expect_failure
=False, go_neg_res
=None):
348 if "P2P-GROUP-STARTED" in ev
:
349 raise Exception("Group formation succeeded when expecting failure")
350 exp
= r
'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
351 s
= re
.split(exp
, ev
)
355 res
['result'] = 'go-neg-failed'
356 res
['status'] = int(s
[2])
359 if "P2P-GROUP-STARTED" not in ev
:
360 raise Exception("No P2P-GROUP-STARTED event seen")
362 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.]*)'
363 s
= re
.split(exp
, ev
)
365 exp
= r
'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
366 s
= re
.split(exp
, ev
)
368 raise Exception("Could not parse P2P-GROUP-STARTED")
370 res
['result'] = 'success'
372 self
.group_ifname
= s
[2]
376 if "[PERSISTENT]" in ev
:
377 res
['persistent'] = True
379 res
['persistent'] = False
380 p
= re
.match(r
'psk=([0-9a-f]*)', s
[6])
382 res
['psk'] = p
.group(1)
383 p
= re
.match(r
'passphrase="(.*)"', s
[6])
385 res
['passphrase'] = p
.group(1)
386 res
['go_dev_addr'] = s
[7]
388 if len(s
) > 8 and len(s
[8]) > 0:
389 res
['ip_addr'] = s
[8]
391 res
['ip_mask'] = s
[9]
393 res
['go_ip_addr'] = s
[10]
396 exp
= r
'<.>(P2P-GO-NEG-SUCCESS) role=(GO|client) freq=([0-9]*)'
397 s
= re
.split(exp
, go_neg_res
)
399 raise Exception("Could not parse P2P-GO-NEG-SUCCESS")
400 res
['go_neg_role'] = s
[2]
401 res
['go_neg_freq'] = s
[3]
405 def p2p_go_neg_auth(self
, peer
, pin
, method
, go_intent
=None, persistent
=False, freq
=None):
406 if not self
.discover_peer(peer
):
407 raise Exception("Peer " + peer
+ " not found")
409 cmd
= "P2P_CONNECT " + peer
+ " " + pin
+ " " + method
+ " auth"
411 cmd
= cmd
+ ' go_intent=' + str(go_intent
)
413 cmd
= cmd
+ ' freq=' + str(freq
)
415 cmd
= cmd
+ " persistent"
416 if "OK" in self
.global_request(cmd
):
418 raise Exception("P2P_CONNECT (auth) failed")
420 def p2p_go_neg_auth_result(self
, timeout
=1, expect_failure
=False):
422 ev
= self
.wait_global_event(["P2P-GO-NEG-SUCCESS",
423 "P2P-GO-NEG-FAILURE"], timeout
);
427 raise Exception("Group formation timed out")
428 if "P2P-GO-NEG-SUCCESS" in ev
:
430 ev
= self
.wait_global_event(["P2P-GROUP-STARTED"], timeout
);
434 raise Exception("Group formation timed out")
436 return self
.group_form_result(ev
, expect_failure
, go_neg_res
)
438 def p2p_go_neg_init(self
, peer
, pin
, method
, timeout
=0, go_intent
=None, expect_failure
=False, persistent
=False, freq
=None):
439 if not self
.discover_peer(peer
):
440 raise Exception("Peer " + peer
+ " not found")
443 cmd
= "P2P_CONNECT " + peer
+ " " + pin
+ " " + method
445 cmd
= "P2P_CONNECT " + peer
+ " " + method
447 cmd
= cmd
+ ' go_intent=' + str(go_intent
)
449 cmd
= cmd
+ ' freq=' + str(freq
)
451 cmd
= cmd
+ " persistent"
452 if "OK" in self
.global_request(cmd
):
457 ev
= self
.wait_global_event(["P2P-GO-NEG-SUCCESS",
458 "P2P-GO-NEG-FAILURE"], timeout
)
462 raise Exception("Group formation timed out")
463 if "P2P-GO-NEG-SUCCESS" in ev
:
465 ev
= self
.wait_global_event(["P2P-GROUP-STARTED"], timeout
)
469 raise Exception("Group formation timed out")
471 return self
.group_form_result(ev
, expect_failure
, go_neg_res
)
472 raise Exception("P2P_CONNECT failed")
474 def wait_event(self
, events
, timeout
=10):
475 start
= os
.times()[4]
477 while self
.mon
.pending():
479 logger
.debug(self
.ifname
+ ": " + ev
)
484 remaining
= start
+ timeout
- now
487 if not self
.mon
.pending(timeout
=remaining
):
491 def wait_global_event(self
, events
, timeout
):
492 if self
.global_iface
is None:
493 self
.wait_event(events
, timeout
)
495 start
= os
.times()[4]
497 while self
.global_mon
.pending():
498 ev
= self
.global_mon
.recv()
499 logger
.debug(self
.ifname
+ "(global): " + ev
)
504 remaining
= start
+ timeout
- now
507 if not self
.global_mon
.pending(timeout
=remaining
):
511 def wait_go_ending_session(self
):
512 ev
= self
.wait_event(["P2P-GROUP-REMOVED"], timeout
=3)
514 raise Exception("Group removal event timed out")
515 if "reason=GO_ENDING_SESSION" not in ev
:
516 raise Exception("Unexpected group removal reason")
518 def dump_monitor(self
):
519 while self
.mon
.pending():
521 logger
.debug(self
.ifname
+ ": " + ev
)
522 while self
.global_mon
.pending():
523 ev
= self
.global_mon
.recv()
524 logger
.debug(self
.ifname
+ "(global): " + ev
)
526 def remove_group(self
, ifname
=None):
528 ifname
= self
.group_ifname
if self
.group_ifname
else self
.ifname
529 if "OK" not in self
.global_request("P2P_GROUP_REMOVE " + ifname
):
530 raise Exception("Group could not be removed")
531 self
.group_ifname
= None
533 def p2p_start_go(self
, persistent
=None, freq
=None):
535 cmd
= "P2P_GROUP_ADD"
536 if persistent
is None:
538 elif persistent
is True:
539 cmd
= cmd
+ " persistent"
541 cmd
= cmd
+ " persistent=" + str(persistent
)
543 cmd
= cmd
+ " freq=" + str(freq
)
544 if "OK" in self
.global_request(cmd
):
545 ev
= self
.wait_global_event(["P2P-GROUP-STARTED"], timeout
=5)
547 raise Exception("GO start up timed out")
549 return self
.group_form_result(ev
)
550 raise Exception("P2P_GROUP_ADD failed")
552 def p2p_go_authorize_client(self
, pin
):
553 cmd
= "WPS_PIN any " + pin
554 if "FAIL" in self
.group_request(cmd
):
555 raise Exception("Failed to authorize client connection on GO")
558 def p2p_go_authorize_client_pbc(self
):
560 if "FAIL" in self
.group_request(cmd
):
561 raise Exception("Failed to authorize client connection on GO")
564 def p2p_connect_group(self
, go_addr
, pin
, timeout
=0, social
=False):
566 if not self
.discover_peer(go_addr
, social
=social
):
567 raise Exception("GO " + go_addr
+ " not found")
569 cmd
= "P2P_CONNECT " + go_addr
+ " " + pin
+ " join"
570 if "OK" in self
.global_request(cmd
):
574 ev
= self
.wait_global_event(["P2P-GROUP-STARTED"], timeout
)
576 raise Exception("Joining the group timed out")
578 return self
.group_form_result(ev
)
579 raise Exception("P2P_CONNECT(join) failed")
581 def tdls_setup(self
, peer
):
582 cmd
= "TDLS_SETUP " + peer
583 if "FAIL" in self
.group_request(cmd
):
584 raise Exception("Failed to request TDLS setup")
587 def tdls_teardown(self
, peer
):
588 cmd
= "TDLS_TEARDOWN " + peer
589 if "FAIL" in self
.group_request(cmd
):
590 raise Exception("Failed to request TDLS teardown")
593 def connect(self
, ssid
=None, ssid2
=None, **kwargs
):
594 logger
.info("Connect STA " + self
.ifname
+ " to AP")
595 id = self
.add_network()
597 self
.set_network_quoted(id, "ssid", ssid
)
599 self
.set_network(id, "ssid", ssid2
)
601 quoted
= [ "psk", "identity", "anonymous_identity", "password",
602 "ca_cert", "client_cert", "private_key",
603 "private_key_passwd", "ca_cert2", "client_cert2",
604 "private_key2", "phase1", "phase2", "domain_suffix_match",
605 "altsubject_match", "subject_match", "pac_file", "dh_file" ]
607 if field
in kwargs
and kwargs
[field
]:
608 self
.set_network_quoted(id, field
, kwargs
[field
])
610 not_quoted
= [ "proto", "key_mgmt", "ieee80211w", "pairwise",
611 "group", "wep_key0", "scan_freq", "eap",
612 "eapol_flags", "fragment_size", "scan_ssid", "auth_alg" ]
613 for field
in not_quoted
:
614 if field
in kwargs
and kwargs
[field
]:
615 self
.set_network(id, field
, kwargs
[field
])
617 if "raw_psk" in kwargs
and kwargs
['raw_psk']:
618 self
.set_network(id, "psk", kwargs
['raw_psk'])
619 if "password_hex" in kwargs
and kwargs
['password_hex']:
620 self
.set_network(id, "password", kwargs
['password_hex'])
621 if "peerkey" in kwargs
and kwargs
['peerkey']:
622 self
.set_network(id, "peerkey", "1")
623 if "okc" in kwargs
and kwargs
['okc']:
624 self
.set_network(id, "proactive_key_caching", "1")
625 if "ocsp" in kwargs
and kwargs
['ocsp']:
626 self
.set_network(id, "ocsp", str(kwargs
['ocsp']))
627 if "only_add_network" in kwargs
and kwargs
['only_add_network']:
629 if "wait_connect" not in kwargs
or kwargs
['wait_connect']:
631 self
.connect_network(id, timeout
=20)
633 self
.connect_network(id)
636 self
.select_network(id)
639 def scan(self
, type=None, freq
=None, no_wait
=False):
641 cmd
= "SCAN TYPE=" + type
645 cmd
= cmd
+ " freq=" + freq
648 if not "OK" in self
.request(cmd
):
649 raise Exception("Failed to trigger scan")
652 ev
= self
.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
654 raise Exception("Scan timed out")
656 def roam(self
, bssid
):
658 self
.request("ROAM " + bssid
)
659 ev
= self
.wait_event(["CTRL-EVENT-CONNECTED"], timeout
=10)
661 raise Exception("Roaming with the AP timed out")
664 def roam_over_ds(self
, bssid
):
666 self
.request("FT_DS " + bssid
)
667 ev
= self
.wait_event(["CTRL-EVENT-CONNECTED"], timeout
=10)
669 raise Exception("Roaming with the AP timed out")
672 def wps_reg(self
, bssid
, pin
, new_ssid
=None, key_mgmt
=None, cipher
=None,
673 new_passphrase
=None, no_wait
=False):
676 self
.request("WPS_REG " + bssid
+ " " + pin
+ " " +
677 new_ssid
.encode("hex") + " " + key_mgmt
+ " " +
678 cipher
+ " " + new_passphrase
.encode("hex"))
681 ev
= self
.wait_event(["WPS-SUCCESS"], timeout
=15)
683 self
.request("WPS_REG " + bssid
+ " " + pin
)
686 ev
= self
.wait_event(["WPS-CRED-RECEIVED"], timeout
=15)
688 raise Exception("WPS cred timed out")
689 ev
= self
.wait_event(["WPS-FAIL"], timeout
=15)
691 raise Exception("WPS timed out")
692 ev
= self
.wait_event(["CTRL-EVENT-CONNECTED"], timeout
=15)
694 raise Exception("Association with the AP timed out")
697 self
.request("RELOG")
699 def wait_completed(self
, timeout
=10):
700 for i
in range(0, timeout
* 2):
701 if self
.get_status_field("wpa_state") == "COMPLETED":
704 raise Exception("Timeout while waiting for COMPLETED state")
706 def get_capability(self
, field
):
707 res
= self
.request("GET_CAPABILITY " + field
)
710 return res
.split(' ')
712 def get_bss(self
, bssid
):
713 res
= self
.request("BSS " + bssid
)
714 lines
= res
.splitlines()
717 [name
,value
] = l
.split('=', 1)
721 def get_pmksa(self
, bssid
):
722 res
= self
.request("PMKSA")
723 lines
= res
.splitlines()
728 [index
,aa
,pmkid
,expiration
,opportunistic
] = l
.split(' ')
729 vals
['index'] = index
730 vals
['pmkid'] = pmkid
731 vals
['expiration'] = expiration
732 vals
['opportunistic'] = opportunistic
736 def get_sta(self
, addr
, info
=None, next
=False):
737 cmd
= "STA-NEXT " if next
else "STA "
739 res
= self
.request("STA-FIRST")
741 res
= self
.request(cmd
+ addr
+ " " + info
)
743 res
= self
.request(cmd
+ addr
)
744 lines
= res
.splitlines()
752 [name
,value
] = l
.split('=', 1)