]> git.ipfire.org Git - thirdparty/hostap.git/blob - tests/hwsim/wpasupplicant.py
tests: INTERWORKING_ADD_NETWORK
[thirdparty/hostap.git] / tests / hwsim / wpasupplicant.py
1 # Python class for controlling wpa_supplicant
2 # Copyright (c) 2013-2014, Jouni Malinen <j@w1.fi>
3 #
4 # This software may be distributed under the terms of the BSD license.
5 # See README for more details.
6
7 import os
8 import time
9 import logging
10 import binascii
11 import re
12 import struct
13 import subprocess
14 import wpaspy
15
16 logger = logging.getLogger()
17 wpas_ctrl = '/var/run/wpa_supplicant'
18
19 class WpaSupplicant:
20 def __init__(self, ifname=None, global_iface=None):
21 self.group_ifname = None
22 self.gctrl_mon = None
23 if ifname:
24 self.set_ifname(ifname)
25 else:
26 self.ifname = None
27
28 self.global_iface = global_iface
29 if global_iface:
30 self.global_ctrl = wpaspy.Ctrl(global_iface)
31 self.global_mon = wpaspy.Ctrl(global_iface)
32 self.global_mon.attach()
33 else:
34 self.global_mon = None
35
36 def close_ctrl(self):
37 if self.global_mon:
38 self.global_mon.detach()
39 self.global_mon = None
40 self.global_ctrl = None
41 self.remove_ifname()
42
43 def set_ifname(self, ifname):
44 self.ifname = ifname
45 self.ctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
46 self.mon = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
47 self.mon.attach()
48
49 def remove_ifname(self):
50 if self.ifname:
51 self.mon.detach()
52 self.mon = None
53 self.ctrl = None
54 self.ifname = None
55
56 def interface_add(self, ifname, config="", driver="nl80211",
57 drv_params=None, br_ifname=None):
58 try:
59 groups = subprocess.check_output(["id"])
60 group = "admin" if "(admin)" in groups else "adm"
61 except Exception, e:
62 group = "admin"
63 cmd = "INTERFACE_ADD " + ifname + "\t" + config + "\t" + driver + "\tDIR=/var/run/wpa_supplicant GROUP=" + group
64 if drv_params:
65 cmd = cmd + '\t' + drv_params
66 if br_ifname:
67 if not drv_params:
68 cmd += '\t'
69 cmd += '\t' + br_ifname
70 if "FAIL" in self.global_request(cmd):
71 raise Exception("Failed to add a dynamic wpa_supplicant interface")
72 self.set_ifname(ifname)
73
74 def interface_remove(self, ifname):
75 self.remove_ifname()
76 self.global_request("INTERFACE_REMOVE " + ifname)
77
78 def request(self, cmd, timeout=10):
79 logger.debug(self.ifname + ": CTRL: " + cmd)
80 return self.ctrl.request(cmd, timeout=timeout)
81
82 def global_request(self, cmd):
83 if self.global_iface is None:
84 self.request(cmd)
85 else:
86 ifname = self.ifname or self.global_iface
87 logger.debug(ifname + ": CTRL(global): " + cmd)
88 return self.global_ctrl.request(cmd)
89
90 def group_request(self, cmd):
91 if self.group_ifname and self.group_ifname != self.ifname:
92 logger.debug(self.group_ifname + ": CTRL: " + cmd)
93 gctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, self.group_ifname))
94 return gctrl.request(cmd)
95 return self.request(cmd)
96
97 def ping(self):
98 return "PONG" in self.request("PING")
99
100 def global_ping(self):
101 return "PONG" in self.global_request("PING")
102
103 def reset(self):
104 self.dump_monitor()
105 res = self.request("FLUSH")
106 if not "OK" in res:
107 logger.info("FLUSH to " + self.ifname + " failed: " + res)
108 self.request("SET p2p_add_cli_chan 0")
109 self.request("SET p2p_no_go_freq ")
110 self.request("SET p2p_pref_chan ")
111 self.request("SET p2p_no_group_iface 1")
112 self.request("SET p2p_go_intent 7")
113 self.request("SET ignore_old_scan_res 0")
114 if self.gctrl_mon:
115 try:
116 self.gctrl_mon.detach()
117 except:
118 pass
119 self.gctrl_mon = None
120 self.group_ifname = None
121 self.dump_monitor()
122
123 iter = 0
124 while iter < 60:
125 state = self.get_driver_status_field("scan_state")
126 if "SCAN_STARTED" in state or "SCAN_REQUESTED" in state:
127 logger.info(self.ifname + ": Waiting for scan operation to complete before continuing")
128 time.sleep(1)
129 else:
130 break
131 iter = iter + 1
132 if iter == 60:
133 logger.error(self.ifname + ": Driver scan state did not clear")
134 print "Trying to clear cfg80211/mac80211 scan state"
135 try:
136 cmd = ["ifconfig", self.ifname, "down"]
137 subprocess.call(cmd)
138 except subprocess.CalledProcessError, e:
139 logger.info("ifconfig failed: " + str(e.returncode))
140 logger.info(e.output)
141 try:
142 cmd = ["ifconfig", self.ifname, "up"]
143 subprocess.call(cmd)
144 except subprocess.CalledProcessError, e:
145 logger.info("ifconfig failed: " + str(e.returncode))
146 logger.info(e.output)
147 if iter > 0:
148 # The ongoing scan could have discovered BSSes or P2P peers
149 logger.info("Run FLUSH again since scan was in progress")
150 self.request("FLUSH")
151 self.dump_monitor()
152
153 if not self.ping():
154 logger.info("No PING response from " + self.ifname + " after reset")
155
156 def add_network(self):
157 id = self.request("ADD_NETWORK")
158 if "FAIL" in id:
159 raise Exception("ADD_NETWORK failed")
160 return int(id)
161
162 def remove_network(self, id):
163 id = self.request("REMOVE_NETWORK " + str(id))
164 if "FAIL" in id:
165 raise Exception("REMOVE_NETWORK failed")
166 return None
167
168 def get_network(self, id, field):
169 res = self.request("GET_NETWORK " + str(id) + " " + field)
170 if res == "FAIL\n":
171 return None
172 return res
173
174 def set_network(self, id, field, value):
175 res = self.request("SET_NETWORK " + str(id) + " " + field + " " + value)
176 if "FAIL" in res:
177 raise Exception("SET_NETWORK failed")
178 return None
179
180 def set_network_quoted(self, id, field, value):
181 res = self.request("SET_NETWORK " + str(id) + " " + field + ' "' + value + '"')
182 if "FAIL" in res:
183 raise Exception("SET_NETWORK failed")
184 return None
185
186 def list_networks(self):
187 res = self.request("LIST_NETWORKS")
188 lines = res.splitlines()
189 networks = []
190 for l in lines:
191 if "network id" in l:
192 continue
193 [id,ssid,bssid,flags] = l.split('\t')
194 network = {}
195 network['id'] = id
196 network['ssid'] = ssid
197 network['bssid'] = bssid
198 network['flags'] = flags
199 networks.append(network)
200 return networks
201
202 def hs20_enable(self, auto_interworking=False):
203 self.request("SET interworking 1")
204 self.request("SET hs20 1")
205 if auto_interworking:
206 self.request("SET auto_interworking 1")
207 else:
208 self.request("SET auto_interworking 0")
209
210 def interworking_add_network(self, bssid):
211 id = self.request("INTERWORKING_ADD_NETWORK " + bssid)
212 if "FAIL" in id or "OK" in id:
213 raise Exception("INTERWORKING_ADD_NETWORK failed")
214 return int(id)
215
216 def add_cred(self):
217 id = self.request("ADD_CRED")
218 if "FAIL" in id:
219 raise Exception("ADD_CRED failed")
220 return int(id)
221
222 def remove_cred(self, id):
223 id = self.request("REMOVE_CRED " + str(id))
224 if "FAIL" in id:
225 raise Exception("REMOVE_CRED failed")
226 return None
227
228 def set_cred(self, id, field, value):
229 res = self.request("SET_CRED " + str(id) + " " + field + " " + value)
230 if "FAIL" in res:
231 raise Exception("SET_CRED failed")
232 return None
233
234 def set_cred_quoted(self, id, field, value):
235 res = self.request("SET_CRED " + str(id) + " " + field + ' "' + value + '"')
236 if "FAIL" in res:
237 raise Exception("SET_CRED failed")
238 return None
239
240 def get_cred(self, id, field):
241 return self.request("GET_CRED " + str(id) + " " + field)
242
243 def add_cred_values(self, params):
244 id = self.add_cred()
245
246 quoted = [ "realm", "username", "password", "domain", "imsi",
247 "excluded_ssid", "milenage", "ca_cert", "client_cert",
248 "private_key", "domain_suffix_match", "provisioning_sp",
249 "roaming_partner", "phase1", "phase2" ]
250 for field in quoted:
251 if field in params:
252 self.set_cred_quoted(id, field, params[field])
253
254 not_quoted = [ "eap", "roaming_consortium", "priority",
255 "required_roaming_consortium", "sp_priority",
256 "max_bss_load", "update_identifier", "req_conn_capab",
257 "min_dl_bandwidth_home", "min_ul_bandwidth_home",
258 "min_dl_bandwidth_roaming", "min_ul_bandwidth_roaming" ]
259 for field in not_quoted:
260 if field in params:
261 self.set_cred(id, field, params[field])
262
263 return id;
264
265 def select_network(self, id, freq=None):
266 if freq:
267 extra = " freq=" + str(freq)
268 else:
269 extra = ""
270 id = self.request("SELECT_NETWORK " + str(id) + extra)
271 if "FAIL" in id:
272 raise Exception("SELECT_NETWORK failed")
273 return None
274
275 def mesh_group_add(self, id):
276 id = self.request("MESH_GROUP_ADD " + str(id))
277 if "FAIL" in id:
278 raise Exception("MESH_GROUP_ADD failed")
279 return None
280
281 def mesh_group_remove(self):
282 id = self.request("MESH_GROUP_REMOVE " + str(self.ifname))
283 if "FAIL" in id:
284 raise Exception("MESH_GROUP_REMOVE failed")
285 return None
286
287 def connect_network(self, id, timeout=10):
288 self.dump_monitor()
289 self.select_network(id)
290 self.wait_connected(timeout=timeout)
291 self.dump_monitor()
292
293 def get_status(self, extra=None):
294 if extra:
295 extra = "-" + extra
296 else:
297 extra = ""
298 res = self.request("STATUS" + extra)
299 lines = res.splitlines()
300 vals = dict()
301 for l in lines:
302 try:
303 [name,value] = l.split('=', 1)
304 vals[name] = value
305 except ValueError, e:
306 logger.info(self.ifname + ": Ignore unexpected STATUS line: " + l)
307 return vals
308
309 def get_status_field(self, field, extra=None):
310 vals = self.get_status(extra)
311 if field in vals:
312 return vals[field]
313 return None
314
315 def get_group_status(self, extra=None):
316 if extra:
317 extra = "-" + extra
318 else:
319 extra = ""
320 res = self.group_request("STATUS" + extra)
321 lines = res.splitlines()
322 vals = dict()
323 for l in lines:
324 try:
325 [name,value] = l.split('=', 1)
326 except ValueError:
327 logger.info(self.ifname + ": Ignore unexpected status line: " + l)
328 continue
329 vals[name] = value
330 return vals
331
332 def get_group_status_field(self, field, extra=None):
333 vals = self.get_group_status(extra)
334 if field in vals:
335 return vals[field]
336 return None
337
338 def get_driver_status(self):
339 res = self.request("STATUS-DRIVER")
340 lines = res.splitlines()
341 vals = dict()
342 for l in lines:
343 try:
344 [name,value] = l.split('=', 1)
345 except ValueError:
346 logger.info(self.ifname + ": Ignore unexpected status-driver line: " + l)
347 continue
348 vals[name] = value
349 return vals
350
351 def get_driver_status_field(self, field):
352 vals = self.get_driver_status()
353 if field in vals:
354 return vals[field]
355 return None
356
357 def get_mcc(self):
358 mcc = int(self.get_driver_status_field('capa.num_multichan_concurrent'))
359 return 1 if mcc < 2 else mcc
360
361 def get_mib(self):
362 res = self.request("MIB")
363 lines = res.splitlines()
364 vals = dict()
365 for l in lines:
366 try:
367 [name,value] = l.split('=', 1)
368 vals[name] = value
369 except ValueError, e:
370 logger.info(self.ifname + ": Ignore unexpected MIB line: " + l)
371 return vals
372
373 def p2p_dev_addr(self):
374 return self.get_status_field("p2p_device_address")
375
376 def p2p_interface_addr(self):
377 return self.get_group_status_field("address")
378
379 def own_addr(self):
380 try:
381 res = self.p2p_interface_addr()
382 except:
383 res = self.p2p_dev_addr()
384 return res
385
386 def p2p_listen(self):
387 return self.global_request("P2P_LISTEN")
388
389 def p2p_find(self, social=False, progressive=False, dev_id=None,
390 dev_type=None, delay=None):
391 cmd = "P2P_FIND"
392 if social:
393 cmd = cmd + " type=social"
394 elif progressive:
395 cmd = cmd + " type=progressive"
396 if dev_id:
397 cmd = cmd + " dev_id=" + dev_id
398 if dev_type:
399 cmd = cmd + " dev_type=" + dev_type
400 if delay:
401 cmd = cmd + " delay=" + str(delay)
402 return self.global_request(cmd)
403
404 def p2p_stop_find(self):
405 return self.global_request("P2P_STOP_FIND")
406
407 def wps_read_pin(self):
408 self.pin = self.request("WPS_PIN get").rstrip("\n")
409 if "FAIL" in self.pin:
410 raise Exception("Could not generate PIN")
411 return self.pin
412
413 def peer_known(self, peer, full=True):
414 res = self.global_request("P2P_PEER " + peer)
415 if peer.lower() not in res.lower():
416 return False
417 if not full:
418 return True
419 return "[PROBE_REQ_ONLY]" not in res
420
421 def discover_peer(self, peer, full=True, timeout=15, social=True, force_find=False):
422 logger.info(self.ifname + ": Trying to discover peer " + peer)
423 if not force_find and self.peer_known(peer, full):
424 return True
425 self.p2p_find(social)
426 count = 0
427 while count < timeout * 4:
428 time.sleep(0.25)
429 count = count + 1
430 if self.peer_known(peer, full):
431 return True
432 return False
433
434 def get_peer(self, peer):
435 res = self.global_request("P2P_PEER " + peer)
436 if peer.lower() not in res.lower():
437 raise Exception("Peer information not available")
438 lines = res.splitlines()
439 vals = dict()
440 for l in lines:
441 if '=' in l:
442 [name,value] = l.split('=', 1)
443 vals[name] = value
444 return vals
445
446 def group_form_result(self, ev, expect_failure=False, go_neg_res=None):
447 if expect_failure:
448 if "P2P-GROUP-STARTED" in ev:
449 raise Exception("Group formation succeeded when expecting failure")
450 exp = r'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
451 s = re.split(exp, ev)
452 if len(s) < 3:
453 return None
454 res = {}
455 res['result'] = 'go-neg-failed'
456 res['status'] = int(s[2])
457 return res
458
459 if "P2P-GROUP-STARTED" not in ev:
460 raise Exception("No P2P-GROUP-STARTED event seen")
461
462 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.]*)'
463 s = re.split(exp, ev)
464 if len(s) < 11:
465 exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
466 s = re.split(exp, ev)
467 if len(s) < 8:
468 raise Exception("Could not parse P2P-GROUP-STARTED")
469 res = {}
470 res['result'] = 'success'
471 res['ifname'] = s[2]
472 self.group_ifname = s[2]
473 try:
474 self.gctrl_mon = wpaspy.Ctrl(os.path.join(wpas_ctrl, self.group_ifname))
475 self.gctrl_mon.attach()
476 except:
477 logger.debug("Could not open monitor socket for group interface")
478 self.gctrl_mon = None
479 res['role'] = s[3]
480 res['ssid'] = s[4]
481 res['freq'] = s[5]
482 if "[PERSISTENT]" in ev:
483 res['persistent'] = True
484 else:
485 res['persistent'] = False
486 p = re.match(r'psk=([0-9a-f]*)', s[6])
487 if p:
488 res['psk'] = p.group(1)
489 p = re.match(r'passphrase="(.*)"', s[6])
490 if p:
491 res['passphrase'] = p.group(1)
492 res['go_dev_addr'] = s[7]
493
494 if len(s) > 8 and len(s[8]) > 0:
495 res['ip_addr'] = s[8]
496 if len(s) > 9:
497 res['ip_mask'] = s[9]
498 if len(s) > 10:
499 res['go_ip_addr'] = s[10]
500
501 if go_neg_res:
502 exp = r'<.>(P2P-GO-NEG-SUCCESS) role=(GO|client) freq=([0-9]*)'
503 s = re.split(exp, go_neg_res)
504 if len(s) < 4:
505 raise Exception("Could not parse P2P-GO-NEG-SUCCESS")
506 res['go_neg_role'] = s[2]
507 res['go_neg_freq'] = s[3]
508
509 return res
510
511 def p2p_go_neg_auth(self, peer, pin, method, go_intent=None, persistent=False, freq=None):
512 if not self.discover_peer(peer):
513 raise Exception("Peer " + peer + " not found")
514 self.dump_monitor()
515 if pin:
516 cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
517 else:
518 cmd = "P2P_CONNECT " + peer + " " + method + " auth"
519 if go_intent:
520 cmd = cmd + ' go_intent=' + str(go_intent)
521 if freq:
522 cmd = cmd + ' freq=' + str(freq)
523 if persistent:
524 cmd = cmd + " persistent"
525 if "OK" in self.global_request(cmd):
526 return None
527 raise Exception("P2P_CONNECT (auth) failed")
528
529 def p2p_go_neg_auth_result(self, timeout=1, expect_failure=False):
530 go_neg_res = None
531 ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
532 "P2P-GO-NEG-FAILURE"], timeout);
533 if ev is None:
534 if expect_failure:
535 return None
536 raise Exception("Group formation timed out")
537 if "P2P-GO-NEG-SUCCESS" in ev:
538 go_neg_res = ev
539 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout);
540 if ev is None:
541 if expect_failure:
542 return None
543 raise Exception("Group formation timed out")
544 self.dump_monitor()
545 return self.group_form_result(ev, expect_failure, go_neg_res)
546
547 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):
548 if not self.discover_peer(peer):
549 raise Exception("Peer " + peer + " not found")
550 self.dump_monitor()
551 if pin:
552 cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
553 else:
554 cmd = "P2P_CONNECT " + peer + " " + method
555 if go_intent:
556 cmd = cmd + ' go_intent=' + str(go_intent)
557 if freq:
558 cmd = cmd + ' freq=' + str(freq)
559 if persistent:
560 cmd = cmd + " persistent"
561 elif persistent_id:
562 cmd = cmd + " persistent=" + persistent_id
563 if provdisc:
564 cmd = cmd + " provdisc"
565 if "OK" in self.global_request(cmd):
566 if timeout == 0:
567 self.dump_monitor()
568 return None
569 go_neg_res = None
570 ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
571 "P2P-GO-NEG-FAILURE"], timeout)
572 if ev is None:
573 if expect_failure:
574 return None
575 raise Exception("Group formation timed out")
576 if "P2P-GO-NEG-SUCCESS" in ev:
577 if not wait_group:
578 return ev
579 go_neg_res = ev
580 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
581 if ev is None:
582 if expect_failure:
583 return None
584 raise Exception("Group formation timed out")
585 self.dump_monitor()
586 return self.group_form_result(ev, expect_failure, go_neg_res)
587 raise Exception("P2P_CONNECT failed")
588
589 def wait_event(self, events, timeout=10):
590 start = os.times()[4]
591 while True:
592 while self.mon.pending():
593 ev = self.mon.recv()
594 logger.debug(self.ifname + ": " + ev)
595 for event in events:
596 if event in ev:
597 return ev
598 now = os.times()[4]
599 remaining = start + timeout - now
600 if remaining <= 0:
601 break
602 if not self.mon.pending(timeout=remaining):
603 break
604 return None
605
606 def wait_global_event(self, events, timeout):
607 if self.global_iface is None:
608 self.wait_event(events, timeout)
609 else:
610 start = os.times()[4]
611 while True:
612 while self.global_mon.pending():
613 ev = self.global_mon.recv()
614 logger.debug(self.ifname + "(global): " + ev)
615 for event in events:
616 if event in ev:
617 return ev
618 now = os.times()[4]
619 remaining = start + timeout - now
620 if remaining <= 0:
621 break
622 if not self.global_mon.pending(timeout=remaining):
623 break
624 return None
625
626 def wait_group_event(self, events, timeout=10):
627 if self.group_ifname and self.group_ifname != self.ifname:
628 if self.gctrl_mon is None:
629 return None
630 start = os.times()[4]
631 while True:
632 while self.gctrl_mon.pending():
633 ev = self.gctrl_mon.recv()
634 logger.debug(self.group_ifname + ": " + ev)
635 for event in events:
636 if event in ev:
637 return ev
638 now = os.times()[4]
639 remaining = start + timeout - now
640 if remaining <= 0:
641 break
642 if not self.gctrl_mon.pending(timeout=remaining):
643 break
644 return None
645
646 return self.wait_event(events, timeout)
647
648 def wait_go_ending_session(self):
649 if self.gctrl_mon:
650 try:
651 self.gctrl_mon.detach()
652 except:
653 pass
654 self.gctrl_mon = None
655 ev = self.wait_global_event(["P2P-GROUP-REMOVED"], timeout=3)
656 if ev is None:
657 raise Exception("Group removal event timed out")
658 if "reason=GO_ENDING_SESSION" not in ev:
659 raise Exception("Unexpected group removal reason")
660
661 def dump_monitor(self):
662 while self.mon.pending():
663 ev = self.mon.recv()
664 logger.debug(self.ifname + ": " + ev)
665 while self.global_mon and self.global_mon.pending():
666 ev = self.global_mon.recv()
667 logger.debug(self.ifname + "(global): " + ev)
668
669 def remove_group(self, ifname=None):
670 if self.gctrl_mon:
671 try:
672 self.gctrl_mon.detach()
673 except:
674 pass
675 self.gctrl_mon = None
676 if ifname is None:
677 ifname = self.group_ifname if self.group_ifname else self.ifname
678 if "OK" not in self.global_request("P2P_GROUP_REMOVE " + ifname):
679 raise Exception("Group could not be removed")
680 self.group_ifname = None
681
682 def p2p_start_go(self, persistent=None, freq=None, no_event_clear=False):
683 self.dump_monitor()
684 cmd = "P2P_GROUP_ADD"
685 if persistent is None:
686 pass
687 elif persistent is True:
688 cmd = cmd + " persistent"
689 else:
690 cmd = cmd + " persistent=" + str(persistent)
691 if freq:
692 cmd = cmd + " freq=" + str(freq)
693 if "OK" in self.global_request(cmd):
694 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
695 if ev is None:
696 raise Exception("GO start up timed out")
697 if not no_event_clear:
698 self.dump_monitor()
699 return self.group_form_result(ev)
700 raise Exception("P2P_GROUP_ADD failed")
701
702 def p2p_go_authorize_client(self, pin):
703 cmd = "WPS_PIN any " + pin
704 if "FAIL" in self.group_request(cmd):
705 raise Exception("Failed to authorize client connection on GO")
706 return None
707
708 def p2p_go_authorize_client_pbc(self):
709 cmd = "WPS_PBC"
710 if "FAIL" in self.group_request(cmd):
711 raise Exception("Failed to authorize client connection on GO")
712 return None
713
714 def p2p_connect_group(self, go_addr, pin, timeout=0, social=False,
715 freq=None):
716 self.dump_monitor()
717 if not self.discover_peer(go_addr, social=social):
718 if social or not self.discover_peer(go_addr, social=social):
719 raise Exception("GO " + go_addr + " not found")
720 self.dump_monitor()
721 cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
722 if freq:
723 cmd += " freq=" + str(freq)
724 if "OK" in self.global_request(cmd):
725 if timeout == 0:
726 self.dump_monitor()
727 return None
728 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
729 if ev is None:
730 raise Exception("Joining the group timed out")
731 self.dump_monitor()
732 return self.group_form_result(ev)
733 raise Exception("P2P_CONNECT(join) failed")
734
735 def tdls_setup(self, peer):
736 cmd = "TDLS_SETUP " + peer
737 if "FAIL" in self.group_request(cmd):
738 raise Exception("Failed to request TDLS setup")
739 return None
740
741 def tdls_teardown(self, peer):
742 cmd = "TDLS_TEARDOWN " + peer
743 if "FAIL" in self.group_request(cmd):
744 raise Exception("Failed to request TDLS teardown")
745 return None
746
747 def tspecs(self):
748 """Return (tsid, up) tuples representing current tspecs"""
749 res = self.request("WMM_AC_STATUS")
750 tspecs = re.findall(r"TSID=(\d+) UP=(\d+)", res)
751 tspecs = [tuple(map(int, tspec)) for tspec in tspecs]
752
753 logger.debug("tspecs: " + str(tspecs))
754 return tspecs
755
756 def add_ts(self, tsid, up, direction="downlink", expect_failure=False,
757 extra=None):
758 params = {
759 "sba": 9000,
760 "nominal_msdu_size": 1500,
761 "min_phy_rate": 6000000,
762 "mean_data_rate": 1500,
763 }
764 cmd = "WMM_AC_ADDTS %s tsid=%d up=%d" % (direction, tsid, up)
765 for (key, value) in params.iteritems():
766 cmd += " %s=%d" % (key, value)
767 if extra:
768 cmd += " " + extra
769
770 if self.request(cmd).strip() != "OK":
771 raise Exception("ADDTS failed (tsid=%d up=%d)" % (tsid, up))
772
773 if expect_failure:
774 ev = self.wait_event(["TSPEC-REQ-FAILED"], timeout=2)
775 if ev is None:
776 raise Exception("ADDTS failed (time out while waiting failure)")
777 if "tsid=%d" % (tsid) not in ev:
778 raise Exception("ADDTS failed (invalid tsid in TSPEC-REQ-FAILED")
779 return
780
781 ev = self.wait_event(["TSPEC-ADDED"], timeout=1)
782 if ev is None:
783 raise Exception("ADDTS failed (time out)")
784 if "tsid=%d" % (tsid) not in ev:
785 raise Exception("ADDTS failed (invalid tsid in TSPEC-ADDED)")
786
787 if not (tsid, up) in self.tspecs():
788 raise Exception("ADDTS failed (tsid not in tspec list)")
789
790 def del_ts(self, tsid):
791 if self.request("WMM_AC_DELTS %d" % (tsid)).strip() != "OK":
792 raise Exception("DELTS failed")
793
794 ev = self.wait_event(["TSPEC-REMOVED"], timeout=1)
795 if ev is None:
796 raise Exception("DELTS failed (time out)")
797 if "tsid=%d" % (tsid) not in ev:
798 raise Exception("DELTS failed (invalid tsid in TSPEC-REMOVED)")
799
800 tspecs = [(t, u) for (t, u) in self.tspecs() if t == tsid]
801 if tspecs:
802 raise Exception("DELTS failed (still in tspec list)")
803
804 def connect(self, ssid=None, ssid2=None, **kwargs):
805 logger.info("Connect STA " + self.ifname + " to AP")
806 id = self.add_network()
807 if ssid:
808 self.set_network_quoted(id, "ssid", ssid)
809 elif ssid2:
810 self.set_network(id, "ssid", ssid2)
811
812 quoted = [ "psk", "identity", "anonymous_identity", "password",
813 "ca_cert", "client_cert", "private_key",
814 "private_key_passwd", "ca_cert2", "client_cert2",
815 "private_key2", "phase1", "phase2", "domain_suffix_match",
816 "altsubject_match", "subject_match", "pac_file", "dh_file",
817 "bgscan", "ht_mcs", "id_str", "openssl_ciphers",
818 "domain_match" ]
819 for field in quoted:
820 if field in kwargs and kwargs[field]:
821 self.set_network_quoted(id, field, kwargs[field])
822
823 not_quoted = [ "proto", "key_mgmt", "ieee80211w", "pairwise",
824 "group", "wep_key0", "wep_key1", "wep_key2", "wep_key3",
825 "wep_tx_keyidx", "scan_freq", "eap",
826 "eapol_flags", "fragment_size", "scan_ssid", "auth_alg",
827 "wpa_ptk_rekey", "disable_ht", "disable_vht", "bssid",
828 "disable_max_amsdu", "ampdu_factor", "ampdu_density",
829 "disable_ht40", "disable_sgi", "disable_ldpc",
830 "ht40_intolerant", "update_identifier", "mac_addr",
831 "erp", "bg_scan_period", "bssid_blacklist",
832 "bssid_whitelist" ]
833 for field in not_quoted:
834 if field in kwargs and kwargs[field]:
835 self.set_network(id, field, kwargs[field])
836
837 if "raw_psk" in kwargs and kwargs['raw_psk']:
838 self.set_network(id, "psk", kwargs['raw_psk'])
839 if "password_hex" in kwargs and kwargs['password_hex']:
840 self.set_network(id, "password", kwargs['password_hex'])
841 if "peerkey" in kwargs and kwargs['peerkey']:
842 self.set_network(id, "peerkey", "1")
843 if "okc" in kwargs and kwargs['okc']:
844 self.set_network(id, "proactive_key_caching", "1")
845 if "ocsp" in kwargs and kwargs['ocsp']:
846 self.set_network(id, "ocsp", str(kwargs['ocsp']))
847 if "only_add_network" in kwargs and kwargs['only_add_network']:
848 return id
849 if "wait_connect" not in kwargs or kwargs['wait_connect']:
850 if "eap" in kwargs:
851 self.connect_network(id, timeout=20)
852 else:
853 self.connect_network(id)
854 else:
855 self.dump_monitor()
856 self.select_network(id)
857 return id
858
859 def scan(self, type=None, freq=None, no_wait=False, only_new=False):
860 if type:
861 cmd = "SCAN TYPE=" + type
862 else:
863 cmd = "SCAN"
864 if freq:
865 cmd = cmd + " freq=" + str(freq)
866 if only_new:
867 cmd += " only_new=1"
868 if not no_wait:
869 self.dump_monitor()
870 if not "OK" in self.request(cmd):
871 raise Exception("Failed to trigger scan")
872 if no_wait:
873 return
874 ev = self.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
875 if ev is None:
876 raise Exception("Scan timed out")
877
878 def scan_for_bss(self, bssid, freq=None, force_scan=False, only_new=False):
879 if not force_scan and self.get_bss(bssid) is not None:
880 return
881 for i in range(0, 10):
882 self.scan(freq=freq, type="ONLY", only_new=only_new)
883 if self.get_bss(bssid) is not None:
884 return
885 raise Exception("Could not find BSS " + bssid + " in scan")
886
887 def flush_scan_cache(self, freq=2417):
888 self.request("BSS_FLUSH 0")
889 self.scan(freq=freq, only_new=True)
890
891 def roam(self, bssid, fail_test=False):
892 self.dump_monitor()
893 if "OK" not in self.request("ROAM " + bssid):
894 raise Exception("ROAM failed")
895 if fail_test:
896 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
897 if ev is not None:
898 raise Exception("Unexpected connection")
899 self.dump_monitor()
900 return
901 self.wait_connected(timeout=10, error="Roaming with the AP timed out")
902 self.dump_monitor()
903
904 def roam_over_ds(self, bssid, fail_test=False):
905 self.dump_monitor()
906 if "OK" not in self.request("FT_DS " + bssid):
907 raise Exception("FT_DS failed")
908 if fail_test:
909 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
910 if ev is not None:
911 raise Exception("Unexpected connection")
912 self.dump_monitor()
913 return
914 self.wait_connected(timeout=10, error="Roaming with the AP timed out")
915 self.dump_monitor()
916
917 def wps_reg(self, bssid, pin, new_ssid=None, key_mgmt=None, cipher=None,
918 new_passphrase=None, no_wait=False):
919 self.dump_monitor()
920 if new_ssid:
921 self.request("WPS_REG " + bssid + " " + pin + " " +
922 new_ssid.encode("hex") + " " + key_mgmt + " " +
923 cipher + " " + new_passphrase.encode("hex"))
924 if no_wait:
925 return
926 ev = self.wait_event(["WPS-SUCCESS"], timeout=15)
927 else:
928 self.request("WPS_REG " + bssid + " " + pin)
929 if no_wait:
930 return
931 ev = self.wait_event(["WPS-CRED-RECEIVED"], timeout=15)
932 if ev is None:
933 raise Exception("WPS cred timed out")
934 ev = self.wait_event(["WPS-FAIL"], timeout=15)
935 if ev is None:
936 raise Exception("WPS timed out")
937 self.wait_connected(timeout=15)
938
939 def relog(self):
940 self.global_request("RELOG")
941
942 def wait_completed(self, timeout=10):
943 for i in range(0, timeout * 2):
944 if self.get_status_field("wpa_state") == "COMPLETED":
945 return
946 time.sleep(0.5)
947 raise Exception("Timeout while waiting for COMPLETED state")
948
949 def get_capability(self, field):
950 res = self.request("GET_CAPABILITY " + field)
951 if "FAIL" in res:
952 return None
953 return res.split(' ')
954
955 def get_bss(self, bssid, ifname=None):
956 if not ifname or ifname == self.ifname:
957 res = self.request("BSS " + bssid)
958 elif ifname == self.group_ifname:
959 res = self.group_request("BSS " + bssid)
960 else:
961 return None
962
963 if "FAIL" in res:
964 return None
965 lines = res.splitlines()
966 vals = dict()
967 for l in lines:
968 [name,value] = l.split('=', 1)
969 vals[name] = value
970 if len(vals) == 0:
971 return None
972 return vals
973
974 def get_pmksa(self, bssid):
975 res = self.request("PMKSA")
976 lines = res.splitlines()
977 for l in lines:
978 if bssid not in l:
979 continue
980 vals = dict()
981 [index,aa,pmkid,expiration,opportunistic] = l.split(' ')
982 vals['index'] = index
983 vals['pmkid'] = pmkid
984 vals['expiration'] = expiration
985 vals['opportunistic'] = opportunistic
986 return vals
987 return None
988
989 def get_sta(self, addr, info=None, next=False):
990 cmd = "STA-NEXT " if next else "STA "
991 if addr is None:
992 res = self.request("STA-FIRST")
993 elif info:
994 res = self.request(cmd + addr + " " + info)
995 else:
996 res = self.request(cmd + addr)
997 lines = res.splitlines()
998 vals = dict()
999 first = True
1000 for l in lines:
1001 if first:
1002 vals['addr'] = l
1003 first = False
1004 else:
1005 [name,value] = l.split('=', 1)
1006 vals[name] = value
1007 return vals
1008
1009 def mgmt_rx(self, timeout=5):
1010 ev = self.wait_event(["MGMT-RX"], timeout=timeout)
1011 if ev is None:
1012 return None
1013 msg = {}
1014 items = ev.split(' ')
1015 field,val = items[1].split('=')
1016 if field != "freq":
1017 raise Exception("Unexpected MGMT-RX event format: " + ev)
1018 msg['freq'] = val
1019 frame = binascii.unhexlify(items[4])
1020 msg['frame'] = frame
1021
1022 hdr = struct.unpack('<HH6B6B6BH', frame[0:24])
1023 msg['fc'] = hdr[0]
1024 msg['subtype'] = (hdr[0] >> 4) & 0xf
1025 hdr = hdr[1:]
1026 msg['duration'] = hdr[0]
1027 hdr = hdr[1:]
1028 msg['da'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
1029 hdr = hdr[6:]
1030 msg['sa'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
1031 hdr = hdr[6:]
1032 msg['bssid'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
1033 hdr = hdr[6:]
1034 msg['seq_ctrl'] = hdr[0]
1035 msg['payload'] = frame[24:]
1036
1037 return msg
1038
1039 def wait_connected(self, timeout=10, error="Connection timed out"):
1040 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=timeout)
1041 if ev is None:
1042 raise Exception(error)
1043 return ev
1044
1045 def wait_disconnected(self, timeout=10, error="Disconnection timed out"):
1046 ev = self.wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=timeout)
1047 if ev is None:
1048 raise Exception(error)
1049 return ev
1050
1051 def get_group_ifname(self):
1052 return self.group_ifname if self.group_ifname else self.ifname