]>
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 pmf 0")
89 self
.request("SET external_sim 0")
90 self
.request("SET hessid 00:00:00:00:00:00")
91 self
.request("SET access_network_type 15")
92 self
.request("SET p2p_add_cli_chan 0")
93 self
.request("SET p2p_no_go_freq ")
94 self
.request("SET p2p_pref_chan ")
95 self
.request("SET p2p_no_group_iface 1")
96 self
.request("SET p2p_go_intent 7")
97 self
.group_ifname
= None
102 state
= self
.get_driver_status_field("scan_state")
103 if "SCAN_STARTED" in state
or "SCAN_REQUESTED" in state
:
104 logger
.info(self
.ifname
+ ": Waiting for scan operation to complete before continuing")
110 logger
.error(self
.ifname
+ ": Driver scan state did not clear")
111 print "Trying to clear cfg80211/mac80211 scan state"
113 cmd
= ["sudo", "ifconfig", self
.ifname
, "down"]
115 except subprocess
.CalledProcessError
, e
:
116 logger
.info("ifconfig failed: " + str(e
.returncode
))
117 logger
.info(e
.output
)
119 cmd
= ["sudo", "ifconfig", self
.ifname
, "up"]
121 except subprocess
.CalledProcessError
, e
:
122 logger
.info("ifconfig failed: " + str(e
.returncode
))
123 logger
.info(e
.output
)
125 # The ongoing scan could have discovered BSSes or P2P peers
126 logger
.info("Run FLUSH again since scan was in progress")
127 self
.request("FLUSH")
131 logger
.info("No PING response from " + self
.ifname
+ " after reset")
133 def add_network(self
):
134 id = self
.request("ADD_NETWORK")
136 raise Exception("ADD_NETWORK failed")
139 def remove_network(self
, id):
140 id = self
.request("REMOVE_NETWORK " + str(id))
142 raise Exception("REMOVE_NETWORK failed")
145 def get_network(self
, id, field
):
146 res
= self
.request("GET_NETWORK " + str(id) + " " + field
)
151 def set_network(self
, id, field
, value
):
152 res
= self
.request("SET_NETWORK " + str(id) + " " + field
+ " " + value
)
154 raise Exception("SET_NETWORK failed")
157 def set_network_quoted(self
, id, field
, value
):
158 res
= self
.request("SET_NETWORK " + str(id) + " " + field
+ ' "' + value
+ '"')
160 raise Exception("SET_NETWORK failed")
163 def list_networks(self
):
164 res
= self
.request("LIST_NETWORKS")
165 lines
= res
.splitlines()
168 if "network id" in l
:
170 [id,ssid
,bssid
,flags
] = l
.split('\t')
173 network
['ssid'] = ssid
174 network
['bssid'] = bssid
175 network
['flags'] = flags
176 networks
.append(network
)
179 def hs20_enable(self
):
180 self
.request("SET interworking 1")
181 self
.request("SET hs20 1")
184 id = self
.request("ADD_CRED")
186 raise Exception("ADD_CRED failed")
189 def remove_cred(self
, id):
190 id = self
.request("REMOVE_CRED " + str(id))
192 raise Exception("REMOVE_CRED failed")
195 def set_cred(self
, id, field
, value
):
196 res
= self
.request("SET_CRED " + str(id) + " " + field
+ " " + value
)
198 raise Exception("SET_CRED failed")
201 def set_cred_quoted(self
, id, field
, value
):
202 res
= self
.request("SET_CRED " + str(id) + " " + field
+ ' "' + value
+ '"')
204 raise Exception("SET_CRED failed")
207 def add_cred_values(self
, params
):
210 quoted
= [ "realm", "username", "password", "domain", "imsi",
211 "excluded_ssid", "milenage", "ca_cert", "client_cert",
212 "private_key", "domain_suffix_match", "provisioning_sp",
216 self
.set_cred_quoted(id, field
, params
[field
])
218 not_quoted
= [ "eap", "roaming_consortium",
219 "required_roaming_consortium", "sp_priority" ]
220 for field
in not_quoted
:
222 self
.set_cred(id, field
, params
[field
])
226 def select_network(self
, id):
227 id = self
.request("SELECT_NETWORK " + str(id))
229 raise Exception("SELECT_NETWORK failed")
232 def connect_network(self
, id, timeout
=10):
234 self
.select_network(id)
235 ev
= self
.wait_event(["CTRL-EVENT-CONNECTED"], timeout
=timeout
)
237 raise Exception("Association with the AP timed out")
240 def get_status(self
):
241 res
= self
.request("STATUS")
242 lines
= res
.splitlines()
246 [name
,value
] = l
.split('=', 1)
248 except ValueError, e
:
249 logger
.info(self
.ifname
+ ": Ignore unexpected STATUS line: " + l
)
252 def get_status_field(self
, field
):
253 vals
= self
.get_status()
258 def get_group_status(self
):
259 res
= self
.group_request("STATUS")
260 lines
= res
.splitlines()
263 [name
,value
] = l
.split('=', 1)
267 def get_group_status_field(self
, field
):
268 vals
= self
.get_group_status()
273 def get_driver_status(self
):
274 res
= self
.request("STATUS-DRIVER")
275 lines
= res
.splitlines()
278 [name
,value
] = l
.split('=', 1)
282 def get_driver_status_field(self
, field
):
283 vals
= self
.get_driver_status()
288 def p2p_dev_addr(self
):
289 return self
.get_status_field("p2p_device_address")
291 def p2p_interface_addr(self
):
292 return self
.get_group_status_field("address")
294 def p2p_listen(self
):
295 return self
.global_request("P2P_LISTEN")
297 def p2p_find(self
, social
=False, dev_id
=None, dev_type
=None):
300 cmd
= cmd
+ " type=social"
302 cmd
= cmd
+ " dev_id=" + dev_id
304 cmd
= cmd
+ " dev_type=" + dev_type
305 return self
.global_request(cmd
)
307 def p2p_stop_find(self
):
308 return self
.global_request("P2P_STOP_FIND")
310 def wps_read_pin(self
):
311 #TODO: make this random
312 self
.pin
= "12345670"
315 def peer_known(self
, peer
, full
=True):
316 res
= self
.global_request("P2P_PEER " + peer
)
317 if peer
.lower() not in res
.lower():
321 return "[PROBE_REQ_ONLY]" not in res
323 def discover_peer(self
, peer
, full
=True, timeout
=15, social
=True, force_find
=False):
324 logger
.info(self
.ifname
+ ": Trying to discover peer " + peer
)
325 if not force_find
and self
.peer_known(peer
, full
):
327 self
.p2p_find(social
)
329 while count
< timeout
:
332 if self
.peer_known(peer
, full
):
336 def get_peer(self
, peer
):
337 res
= self
.global_request("P2P_PEER " + peer
)
338 if peer
.lower() not in res
.lower():
339 raise Exception("Peer information not available")
340 lines
= res
.splitlines()
344 [name
,value
] = l
.split('=', 1)
348 def group_form_result(self
, ev
, expect_failure
=False, go_neg_res
=None):
350 if "P2P-GROUP-STARTED" in ev
:
351 raise Exception("Group formation succeeded when expecting failure")
352 exp
= r
'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
353 s
= re
.split(exp
, ev
)
357 res
['result'] = 'go-neg-failed'
358 res
['status'] = int(s
[2])
361 if "P2P-GROUP-STARTED" not in ev
:
362 raise Exception("No P2P-GROUP-STARTED event seen")
364 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.]*)'
365 s
= re
.split(exp
, ev
)
367 exp
= r
'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
368 s
= re
.split(exp
, ev
)
370 raise Exception("Could not parse P2P-GROUP-STARTED")
372 res
['result'] = 'success'
374 self
.group_ifname
= s
[2]
378 if "[PERSISTENT]" in ev
:
379 res
['persistent'] = True
381 res
['persistent'] = False
382 p
= re
.match(r
'psk=([0-9a-f]*)', s
[6])
384 res
['psk'] = p
.group(1)
385 p
= re
.match(r
'passphrase="(.*)"', s
[6])
387 res
['passphrase'] = p
.group(1)
388 res
['go_dev_addr'] = s
[7]
390 if len(s
) > 8 and len(s
[8]) > 0:
391 res
['ip_addr'] = s
[8]
393 res
['ip_mask'] = s
[9]
395 res
['go_ip_addr'] = s
[10]
398 exp
= r
'<.>(P2P-GO-NEG-SUCCESS) role=(GO|client) freq=([0-9]*)'
399 s
= re
.split(exp
, go_neg_res
)
401 raise Exception("Could not parse P2P-GO-NEG-SUCCESS")
402 res
['go_neg_role'] = s
[2]
403 res
['go_neg_freq'] = s
[3]
407 def p2p_go_neg_auth(self
, peer
, pin
, method
, go_intent
=None, persistent
=False, freq
=None):
408 if not self
.discover_peer(peer
):
409 raise Exception("Peer " + peer
+ " not found")
411 cmd
= "P2P_CONNECT " + peer
+ " " + pin
+ " " + method
+ " auth"
413 cmd
= cmd
+ ' go_intent=' + str(go_intent
)
415 cmd
= cmd
+ ' freq=' + str(freq
)
417 cmd
= cmd
+ " persistent"
418 if "OK" in self
.global_request(cmd
):
420 raise Exception("P2P_CONNECT (auth) failed")
422 def p2p_go_neg_auth_result(self
, timeout
=1, expect_failure
=False):
424 ev
= self
.wait_global_event(["P2P-GO-NEG-SUCCESS",
425 "P2P-GO-NEG-FAILURE"], timeout
);
429 raise Exception("Group formation timed out")
430 if "P2P-GO-NEG-SUCCESS" in ev
:
432 ev
= self
.wait_global_event(["P2P-GROUP-STARTED"], timeout
);
436 raise Exception("Group formation timed out")
438 return self
.group_form_result(ev
, expect_failure
, go_neg_res
)
440 def p2p_go_neg_init(self
, peer
, pin
, method
, timeout
=0, go_intent
=None, expect_failure
=False, persistent
=False, freq
=None):
441 if not self
.discover_peer(peer
):
442 raise Exception("Peer " + peer
+ " not found")
445 cmd
= "P2P_CONNECT " + peer
+ " " + pin
+ " " + method
447 cmd
= "P2P_CONNECT " + peer
+ " " + method
449 cmd
= cmd
+ ' go_intent=' + str(go_intent
)
451 cmd
= cmd
+ ' freq=' + str(freq
)
453 cmd
= cmd
+ " persistent"
454 if "OK" in self
.global_request(cmd
):
459 ev
= self
.wait_global_event(["P2P-GO-NEG-SUCCESS",
460 "P2P-GO-NEG-FAILURE"], timeout
)
464 raise Exception("Group formation timed out")
465 if "P2P-GO-NEG-SUCCESS" in ev
:
467 ev
= self
.wait_global_event(["P2P-GROUP-STARTED"], timeout
)
471 raise Exception("Group formation timed out")
473 return self
.group_form_result(ev
, expect_failure
, go_neg_res
)
474 raise Exception("P2P_CONNECT failed")
476 def wait_event(self
, events
, timeout
=10):
477 start
= os
.times()[4]
479 while self
.mon
.pending():
481 logger
.debug(self
.ifname
+ ": " + ev
)
486 remaining
= start
+ timeout
- now
489 if not self
.mon
.pending(timeout
=remaining
):
493 def wait_global_event(self
, events
, timeout
):
494 if self
.global_iface
is None:
495 self
.wait_event(events
, timeout
)
497 start
= os
.times()[4]
499 while self
.global_mon
.pending():
500 ev
= self
.global_mon
.recv()
501 logger
.debug(self
.ifname
+ "(global): " + ev
)
506 remaining
= start
+ timeout
- now
509 if not self
.global_mon
.pending(timeout
=remaining
):
513 def wait_go_ending_session(self
):
514 ev
= self
.wait_event(["P2P-GROUP-REMOVED"], timeout
=3)
516 raise Exception("Group removal event timed out")
517 if "reason=GO_ENDING_SESSION" not in ev
:
518 raise Exception("Unexpected group removal reason")
520 def dump_monitor(self
):
521 while self
.mon
.pending():
523 logger
.debug(self
.ifname
+ ": " + ev
)
524 while self
.global_mon
.pending():
525 ev
= self
.global_mon
.recv()
526 logger
.debug(self
.ifname
+ "(global): " + ev
)
528 def remove_group(self
, ifname
=None):
530 ifname
= self
.group_ifname
if self
.group_ifname
else self
.ifname
531 if "OK" not in self
.global_request("P2P_GROUP_REMOVE " + ifname
):
532 raise Exception("Group could not be removed")
533 self
.group_ifname
= None
535 def p2p_start_go(self
, persistent
=None, freq
=None):
537 cmd
= "P2P_GROUP_ADD"
538 if persistent
is None:
540 elif persistent
is True:
541 cmd
= cmd
+ " persistent"
543 cmd
= cmd
+ " persistent=" + str(persistent
)
545 cmd
= cmd
+ " freq=" + str(freq
)
546 if "OK" in self
.global_request(cmd
):
547 ev
= self
.wait_global_event(["P2P-GROUP-STARTED"], timeout
=5)
549 raise Exception("GO start up timed out")
551 return self
.group_form_result(ev
)
552 raise Exception("P2P_GROUP_ADD failed")
554 def p2p_go_authorize_client(self
, pin
):
555 cmd
= "WPS_PIN any " + pin
556 if "FAIL" in self
.group_request(cmd
):
557 raise Exception("Failed to authorize client connection on GO")
560 def p2p_go_authorize_client_pbc(self
):
562 if "FAIL" in self
.group_request(cmd
):
563 raise Exception("Failed to authorize client connection on GO")
566 def p2p_connect_group(self
, go_addr
, pin
, timeout
=0, social
=False):
568 if not self
.discover_peer(go_addr
, social
=social
):
569 raise Exception("GO " + go_addr
+ " not found")
571 cmd
= "P2P_CONNECT " + go_addr
+ " " + pin
+ " join"
572 if "OK" in self
.global_request(cmd
):
576 ev
= self
.wait_global_event(["P2P-GROUP-STARTED"], timeout
)
578 raise Exception("Joining the group timed out")
580 return self
.group_form_result(ev
)
581 raise Exception("P2P_CONNECT(join) failed")
583 def tdls_setup(self
, peer
):
584 cmd
= "TDLS_SETUP " + peer
585 if "FAIL" in self
.group_request(cmd
):
586 raise Exception("Failed to request TDLS setup")
589 def tdls_teardown(self
, peer
):
590 cmd
= "TDLS_TEARDOWN " + peer
591 if "FAIL" in self
.group_request(cmd
):
592 raise Exception("Failed to request TDLS teardown")
595 def connect(self
, ssid
=None, ssid2
=None, **kwargs
):
596 logger
.info("Connect STA " + self
.ifname
+ " to AP")
597 id = self
.add_network()
599 self
.set_network_quoted(id, "ssid", ssid
)
601 self
.set_network(id, "ssid", ssid2
)
603 quoted
= [ "psk", "identity", "anonymous_identity", "password",
604 "ca_cert", "client_cert", "private_key",
605 "private_key_passwd", "ca_cert2", "client_cert2",
606 "private_key2", "phase1", "phase2", "domain_suffix_match",
607 "altsubject_match", "subject_match", "pac_file", "dh_file" ]
609 if field
in kwargs
and kwargs
[field
]:
610 self
.set_network_quoted(id, field
, kwargs
[field
])
612 not_quoted
= [ "proto", "key_mgmt", "ieee80211w", "pairwise",
613 "group", "wep_key0", "scan_freq", "eap",
614 "eapol_flags", "fragment_size", "scan_ssid", "auth_alg" ]
615 for field
in not_quoted
:
616 if field
in kwargs
and kwargs
[field
]:
617 self
.set_network(id, field
, kwargs
[field
])
619 if "raw_psk" in kwargs
and kwargs
['raw_psk']:
620 self
.set_network(id, "psk", kwargs
['raw_psk'])
621 if "password_hex" in kwargs
and kwargs
['password_hex']:
622 self
.set_network(id, "password", kwargs
['password_hex'])
623 if "peerkey" in kwargs
and kwargs
['peerkey']:
624 self
.set_network(id, "peerkey", "1")
625 if "okc" in kwargs
and kwargs
['okc']:
626 self
.set_network(id, "proactive_key_caching", "1")
627 if "ocsp" in kwargs
and kwargs
['ocsp']:
628 self
.set_network(id, "ocsp", str(kwargs
['ocsp']))
629 if "only_add_network" in kwargs
and kwargs
['only_add_network']:
631 if "wait_connect" not in kwargs
or kwargs
['wait_connect']:
633 self
.connect_network(id, timeout
=20)
635 self
.connect_network(id)
638 self
.select_network(id)
641 def scan(self
, type=None, freq
=None, no_wait
=False):
643 cmd
= "SCAN TYPE=" + type
647 cmd
= cmd
+ " freq=" + freq
650 if not "OK" in self
.request(cmd
):
651 raise Exception("Failed to trigger scan")
654 ev
= self
.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
656 raise Exception("Scan timed out")
658 def roam(self
, bssid
):
660 self
.request("ROAM " + bssid
)
661 ev
= self
.wait_event(["CTRL-EVENT-CONNECTED"], timeout
=10)
663 raise Exception("Roaming with the AP timed out")
666 def roam_over_ds(self
, bssid
):
668 self
.request("FT_DS " + bssid
)
669 ev
= self
.wait_event(["CTRL-EVENT-CONNECTED"], timeout
=10)
671 raise Exception("Roaming with the AP timed out")
674 def wps_reg(self
, bssid
, pin
, new_ssid
=None, key_mgmt
=None, cipher
=None,
675 new_passphrase
=None, no_wait
=False):
678 self
.request("WPS_REG " + bssid
+ " " + pin
+ " " +
679 new_ssid
.encode("hex") + " " + key_mgmt
+ " " +
680 cipher
+ " " + new_passphrase
.encode("hex"))
683 ev
= self
.wait_event(["WPS-SUCCESS"], timeout
=15)
685 self
.request("WPS_REG " + bssid
+ " " + pin
)
688 ev
= self
.wait_event(["WPS-CRED-RECEIVED"], timeout
=15)
690 raise Exception("WPS cred timed out")
691 ev
= self
.wait_event(["WPS-FAIL"], timeout
=15)
693 raise Exception("WPS timed out")
694 ev
= self
.wait_event(["CTRL-EVENT-CONNECTED"], timeout
=15)
696 raise Exception("Association with the AP timed out")
699 self
.request("RELOG")
701 def wait_completed(self
, timeout
=10):
702 for i
in range(0, timeout
* 2):
703 if self
.get_status_field("wpa_state") == "COMPLETED":
706 raise Exception("Timeout while waiting for COMPLETED state")
708 def get_capability(self
, field
):
709 res
= self
.request("GET_CAPABILITY " + field
)
712 return res
.split(' ')
714 def get_bss(self
, bssid
):
715 res
= self
.request("BSS " + bssid
)
716 lines
= res
.splitlines()
719 [name
,value
] = l
.split('=', 1)
723 def get_pmksa(self
, bssid
):
724 res
= self
.request("PMKSA")
725 lines
= res
.splitlines()
730 [index
,aa
,pmkid
,expiration
,opportunistic
] = l
.split(' ')
731 vals
['index'] = index
732 vals
['pmkid'] = pmkid
733 vals
['expiration'] = expiration
734 vals
['opportunistic'] = opportunistic
738 def get_sta(self
, addr
, info
=None, next
=False):
739 cmd
= "STA-NEXT " if next
else "STA "
741 res
= self
.request("STA-FIRST")
743 res
= self
.request(cmd
+ addr
+ " " + info
)
745 res
= self
.request(cmd
+ addr
)
746 lines
= res
.splitlines()
754 [name
,value
] = l
.split('=', 1)